loadKeyMaterial method deprecated, tell me the alternative - apache-httpclient-4.x

configureBody(request, requestData.getBody())
configureHeaders(request, requestData.getHeadersAsMap())
String keyPassphrase = "password";
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream("Resources/certificates/selfsigned.jks"), keyPassphrase.toCharArray());
SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, "password").build(); //(keyStore, "password").build()
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
HttpResponse response = httpClient.execute(request, httpClientContext)
coming error:- groovy.lang.MissingMethodException: No signature of method: org.apache.http.ssl.SSLContextBuilder.loadKeyMaterial()
i am using httpclient4.5.5 jar. loadkeyMaterial method was deprecated in httpclient4.4. kindly suggest some alternative.

You should use loadKeyMaterial from org.apache.http.ssl.SSLContextBuilder instead fo from org.apache.http.conn.ssl.SSLContextBuilder which is deprecated.
So, basically change your imports:
// The one deprecated to be removed from your code
//import org.apache.http.conn.ssl.SSLContextBuilder;
// The good one
import org.apache.http.ssl.SSLContextBuilder;

Related

How Can I Add The OutputStream Using Programmatical Configuration in Log4j2?

Any idea how I can add my output stream to the build config?
ConfigurationBuilder<BuiltConfiguration> builder =
ConfigurationBuilderFactory.newConfigurationBuilder();
AppenderComponentBuilder osAppender = builder.newAppender("os", "OutputStream");
osAppender.addAttribute("target", myStream);
builder.add(osAppender);
BuiltConfiguration config = builder.build();
Configurator.initialize(config);
This is the Error message I get:
2022-01-27 15:04:41,203 main ERROR OutputStream contains an invalid element or attribute "target"
2022-01-27 15:04:41,227 main ERROR Could not create plugin of type class org.apache.logging.log4j.core.appender.OutputStreamAppender for element OutputStream: java.lang.NullPointerException java.lang.NullPointerException
at org.apache.logging.log4j.core.appender.OutputStreamAppender.getManager(OutputStreamAppender.java:159)
Thanks
The ConfigurationBuilder API does not allow you to set attributes which can not be serialized to a String. Therefore you'll need to use OutputSreamAppender's builder directly:
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
final Appender appender = OutputStreamAppender.newBuilder()//
.setTarget(myStream)
.setConfiguration(ctx.getConfiguration())
.build();
config.addLoggerAppender(ctx.getRootLogger(), appender);
See this question for another example of ConfigurationBuilder API vs direct instantiation of Log4j components.
Check also Log4j's architecture, which explains how all these components work together.

spring-ws deprecated DefaultHttpClient

I found that HttpComponentsMessageSender default constructor in spring-ws-core 3.4.0.RELEASE, which depends on httpclient 4.5.6, is instantiating a DefaultHttpClient() which is deprecated. However, when i tried to set a custom Httpclient with:
HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender(HttpClientBuilder.create().build());
httpComponentsMessageSender.setReadTimeout(1000l);
i got:
Caused by: java.lang.UnsupportedOperationException: null
at org.apache.http.impl.client.InternalHttpClient.getParams(InternalHttpClient.java:211) ~[httpclient-4.5.6.jar:4.5.6]
at org.springframework.ws.transport.http.HttpComponentsMessageSender.setReadTimeout(HttpComponentsMessageSender.java:149) ~[spring-ws-core-3.0.4.RELEASE.jar:na]
Is that correct that spring uses a deprecated class by default?
How should i set my custom HttpClient instance?
it seems that if i set my own HttpClient i cannot configure it through HttpCompoemntsMessageSender.
thanks,
Not sure if you was able to resolve this but here is the solution to the following issue:
Caused by: java.lang.UnsupportedOperationException: null
at org.apache.http.impl.client.InternalHttpClient.getParams(InternalHttpClient.java:211) ~[httpclient-4.5.6.jar:4.5.6]
at org.springframework.ws.transport.http.HttpComponentsMessageSender.setReadTimeout(HttpComponentsMessageSender.java:149) ~[spring-ws-core-3.0.4.RELEASE.jar:na]
Note the HttpComponentsMessageSender.setReadTimeout() configures the underlying HttpClient's readTimeout by configuring the HttpClient Params.
As you provided above you can use the HttpClientBuilder to do this:
HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender(HttpClientBuilder.create().build());
The solution is to set the "DefaultRequestConfig" on the HttpClientBuilder
HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.build();
As shown below you can set these configuration options at the HttpClient Level by defining a RequestConfig. Here is an example below:
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(60 * 1000)
.setConnectTimeout(60 * 1000)
.setSocketTimeout(60 * 1000)
.build();
Hope this helps.

org.apache.commons.httpclient.HttpMethod of Commons HttpClient 3.0.1 replacement in httpcomponents HttpClient 4.5.1?

We are migrating from Commons HttpClient 3.0.1 to httpcomponents HttpClient 4.5.1.
Currently we are facing an issue related to HttpMethod class which is not present in the migrating version(httpcomponents HttpClient 4.5.1). We are performing the operation of "getResponseHeader()" from the HttpMthod class.
Is there any replacement available for the HttpMethod in "httpcomponents HttpClient 4.5.1"? If not Is there any other way to get "getResponseHeader()" using "httpcomponents HttpClient 4.5.1"?
if you are looking for a common interface of all http methods, use HttpUriRequest:
String url = "http://www.example.com";
HttpUriRequest get = new HttpGet(url);
HttpUriRequest post = new HttpPost(url);
...
HttpClient client = HttpClientBuilder.create.build();
HttpResponse response = client.execute(get or post);
all response related properties (headers, return code and output stream) could be accessed by response object which is more sensible!

How to Get a Json from api/metrics of sonarqube?

I tried to use the GET method of api/metrics to retrieve a JSON to use for my program, but the documentation lack to describe all the parameter to use in the requestUrl.
for example in for my program I find, using the Google Chrome console, that the requestUrl is this one:
http://localhost:9000/api/resources?resource=my%3AjavaSample%3AMandria%2Fsrc%2Fmandria%2FIllnessException.java&metrics=new_technical_debt%2Cblocker_violations%2Cburned_budget%2Cbusiness_value%2Cclasses%2Ccomment_lines%2Ccomment_lines_density%2Ccomplexity%2Cclass_complexity%2Cfile_complexity%2Cfunction_complexity%2Cbranch_coverage%2Cnew_it_branch_coverage%2Cnew_branch_coverage%2Cconfirmed_issues%2Ccoverage%2Cnew_it_coverage%2Cnew_coverage%2Ccritical_violations%2Cdirectories%2Cduplicated_blocks%2Cduplicated_files%2Cduplicated_lines%2Cduplicated_lines_density%2Cfalse_positive_issues%2Cpackage_tangles%2Cfiles%2Cfile_complexity_distribution%2Cfunctions%2Cfunction_complexity_distribution%2Cgenerated_lines%2Cgenerated_ncloc%2Cit_branch_coverage%2Cit_coverage%2Cit_line_coverage%2Cit_uncovered_conditions%2Cit_uncovered_lines%2Cinfo_violations%2Cviolations%2Cline_coverage%2Cnew_it_line_coverage%2Cnew_line_coverage%2Clines%2Cncloc%2Clines_to_cover%2Cnew_it_lines_to_cover%2Cnew_lines_to_cover%2Cmajor_violations%2Cminor_violations%2Cnew_blocker_violations%2Cnew_critical_violations%2Cnew_info_violations%2Cnew_major_violations%2Cnew_minor_violations%2Cnew_violations%2Copen_issues%2Coverall_branch_coverage%2Cnew_overall_branch_coverage%2Coverall_coverage%2Cnew_overall_coverage%2Coverall_line_coverage%2Cnew_overall_line_coverage%2Cnew_overall_lines_to_cover%2Coverall_uncovered_conditions%2Cnew_overall_uncovered_conditions%2Coverall_uncovered_lines%2Cnew_overall_uncovered_lines%2Cpackage_cycles%2Cpackage_feedback_edges%2Cpackage_tangle_index%2Cprojects%2Cpublic_api%2Cpublic_documented_api_density%2Cpublic_undocumented_api%2Calert_status%2Creopened_issues%2Csqale_rating%2Cskipped_tests%2Cstatements%2Cteam_size%2Csqale_index%2Csqale_debt_ratio%2Cuncovered_conditions%2Cnew_it_uncovered_conditions%2Cnew_uncovered_conditions%2Cuncovered_lines%2Cnew_it_uncovered_lines%2Cnew_uncovered_lines%2Ctests%2Ctest_execution_time%2Ctest_errors%2Ctest_failures%2Ctest_success_density
is it possible to find a more detailed documentation or the way I try to solve my problem is not the correct one?
Just add &format=json to the parameters.
See http://docs.sonarqube.org/display/SONARQUBE43/Web+Service+API#WebServiceAPI-ResponseFormats
In response to your question how to call from a outside comment:
If you want to call the SonarQube Web Service API from a Java program you can use the Apache HTTP Client:
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpGet httpGet = new HttpGet("http://localhost:9000/api/resources?metrics=lines");
try(CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpGet);) {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
}
}
In this case it prints all projects on SonarQube and additionaly the metric "lines". You can add multiple metrics to the list, separated by a comma:
"http://localhost:9000/api/resources?metrics=lines,blocker_violations"

javax.xml.bind.UnmarshalException when request rest json service with jersey client

I have a rest webservice (with jersey) which returns json list, if i call it directly it returns exactly this :
[{"success":false,"uri":"foo:22","message":"Unknown host : foo"},{"success":true,"uri":"localhost:8082","message":null}]
generated by this snippet :
#GET
#Path("/opening/")
public List<OpeningResult> testOpenings(#QueryParam("uri") List<String> uris) {
LOG.debug("testOpenings request uris :[" + uris + "]");
List<OpeningResult> openingResults = infoService.testOpenings(uris);
return openingResults;
}
It's a Collection of Pojo which look like this :
#XmlRootElement(name = "OpeningResult")
public class OpeningResult {
attributes
...
getter/setter
}
this Pojo is shared through a common jar between the server and the client.
i call the web service with this snippet :
Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/scheduler/rest/opening");
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
for (String uri : uris) {
params.add("uri", uri);
}
List<OpeningResult> results = newArrayList(resource.queryParams(params).get(OpeningResult[].class));
I add some trace on the server side, i see that my rest service is called with the good parameters, buth on client side, i have this error :
Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"success"). Expected elements are <{}OpeningResult>
I don't find where it comes from ?
Modify your code to set up your client like this:
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
Client client = Client.create(clientConfig);
I had the exact same problem until this question and its answers pointed me in the right direction.
The situation is caused by the default jersey-json module used for serialization to and from JSON, which does not handle certain JSON constructs properly.
You can set the FEATURE_POJO_MAPPING flag to use the Jackson library's JacksonJsonProvider for JSON serialization instead.
Check out the Jersey Client side doc on using JSON. It looks like you're at least missing the annotation:
#Produces("application/json")
But you could also be missing the POJO Mapping feature filters for both client and server side. These all seem to be minor configuration changes.