I am working to modernize old legacy code, and while doing that ran into some deprecated constructs that I can't figure out how to handle. They all look somewhat like this:
HttpPost oauthVerificationRequest = new HttpPost(authURL);
oauthVerificationRequest.getParams().setParameter(OAUTH_TOKEN_KEY, oauthToken);
HttpResponse oauthVerificationRequestResponse = client.getHttpClient().execute(oauthVerificationRequest);
There, my IDE complains that both getParams() as well as setParameter is deprecated.
The thing is, written as it is like this, I understand exactly what is happening. The deprecated line sets the value of the parameter with the key OAUTH_TOKEN_KEY of the request to the value of oauthToken, and probably creates it if it doesn't exist.
However, even knowing that this is what is supposed to happen in this line, I have been unable to find a way to write this line in a modern way. I've tried to figure it out, but the new way of constructing a AbstractHttpMessage simply confuses me.
Since I learn best by examples, could someone please provide me with a "translation" of the above code to the new logic?
Okay, once again it seems that writing down my thoughts as a question helped get my mind down on the right track to find the solution. So to answer my own question, the correct way to write above statement in the new logic would be:
URIBuilder oauthVerificationRequestBuilder = new URIBuilder(authUrl);
oauthVerificationRequestBuilder.setParameter(OAUTH_TOKEN_KEY, oauthToken);
HttpPost oauthVerificationRequest = new HttpPost(oauthVerificationRequestBuilder.build());
HttpResponse oauthVerificationRequestResponse = client.getHttpClient().execute(oauthVerificationRequest);
So basically, you first create a builder, then set the parameters inside the builder, and then create the request using builder.build() as its parameter.
Bonus Question:
Is there also a way to get the addHeader() modification into the builder? Because right now, the entire construct looks like this for me, and it feels kinda inconsistent to use the builder for the parameters, and then slapping the header on top of the request the "old fashioned" way:
URIBuilder oauthVerificationRequestBuilder = new URIBuilder(authUrl);
oauthVerificationRequestBuilder.setParameter(OAUTH_TOKEN_KEY, oauthToken);
oauthVerificationRequestBuilder.setParameter(OAUTH_VERIFIER_KEY, oauthVerifier);
oauthVerificationRequestBuilder.setParameter(AUTHORIZE_KEY, VALUE_STRING_TRUE);
HttpPost oauthVerificationRequest = new HttpPost(oauthVerificationRequestBuilder.build());
oauthVerificationRequest.addHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED_UTF_8);
Googling "java httppost" gives a link to the documentation. Looking for getParams() in the docs, shows that it is inherited from AbstractHttpMessage and another google search found the docs for that class. That docs explains what to do instead of using the deprecated method:
Deprecated. (4.3) use constructor parameters of configuration API provided by HttpClient
I hope this helps some future reader. Good libraries will document what the suggested replacement is for deprecated methods. It's always a good idea to consult the documentation for these suggestions.
It's very simple by http-request built on apache http API.
HttpRequest httpRequest = HttpRequestBuilder.create(
ClientBuilder.create().build();
)
.build();
Response response = httpRequest.target(authURL)
.addParameter(OAUTH_TOKEN_KEY, oauthToken)
.addParameter(ANOTHER_PARAM, "VALUE")
.addHeader(ANY_HEADER, "VALUE")
.post();
Dependency
<dependency>
<groupId>com.jsunsoft.http</groupId>
<artifactId>http-request</artifactId>
<version>2.2.2</version>
</dependency>
Related
In the below code am I calling sanitizer correctly? I'm having trouble satisfying veracode - it says its still vulnerable to XXS and I'm trying the above code next but I'm not sure I'm calling it right.
PolicyFactory policy = new HtmlPolicyBuilder()
.requireRelNofollowOnLinks()
.build();
String SafeOutputLine = policy.sanitize(unsafeoutputLine+"\n");
What would be the most restrictive way to call sanitizer? I'd rather try something super restrictive first to see if the issue is remediated first.
I appreciate any help
I tried this code hoping it would be more restrictive but my security tool says there's still a xxs attack possible
PolicyFactory policy = new HtmlPolicyBuilder()
.allowElements("")
.allowUrlProtocols("")
.allowAttributes("").onElements("")
.requireRelNofollowOnLinks()
.toFactory();
I am aware of the fact that I am able to use a HTTP request to use the distance matrix API (i.e. https://maps.googleapis.com/maps/api/distancematrix/json?origins=42.11622,78.10112&destinations=40.82231,72.224166&key=YOUR_API_KEY)
But I would like to simply use the Java API instead. From my understanding the first step is to create a GeoApiContext and this seems to be where I am failing. I have tried the following code:
private static GeoApiContext context = new GeoApiContext.Builder().apiKey("MyKey").queryRateLimit(500).build();
However I am just met with the following compile error:
java.land.NoClassDefFoundError: com/google/common/util/concurrent/RateLimiter
Any help on the matter would be appreciated. The plan is to use this to create a DistanceMatrix API request if that helps.
check out this link you may find it useful... there are code examples
https://www.programcreek.com/java-api-examples/index.php?api=com.google.maps.model.DistanceMatrix
Is there a way to call solrs analysis api in java using solr-core and get the analyzed tokens.
Analysis api takes fieldName or fieldType and values and give the analyzed tokens.
Is there a way to get those tokens from java?
I found the following link: FieldAnalysisRequestHandler, But I could not get any examples to use it.
In the Admin UI (for which the FieldAnalysisRequestHandler is meant) you can call it by selecting a core and then go to the "Analysis" entry.
See https://cwiki.apache.org/confluence/x/UYDxAQ or https://cwiki.apache.org/confluence/x/FoDxAQ for that.
From a client (which I guess you mean, as you tagged this question with solrj) you need to call the correct URL.
Typically the FieldAnalysisRequestHandler is bound to /analysis/field, see your solrconfig.xml.
From Solrj it should work like this:
SolrQuery query = new SolrQuery();
solrQuery.setRequestHandler("/analysis/field");
solrQuery.set("analysis.fieldtype", "mytype");
solrQuery.set("analysis.fieldvalue", "myval");
QueryResponse solrResponse = solrServer.query(solrQuery);
But it doesn't seem like there's a great support for this in Solrj, probably because it's meant to be called from the Solr Admin UI as mentioned.
This is a very basic beginner question, but I checked the main API site (https://developers.google.com/youtube/v3/) pretty thoroughly and messed around for quite a frustrating while with the sample code, used Google to find other working examples and I came up with nothing so I decided to ask here.
My aim is to write a simple Java program that connects to a YouTube account and retrieves the names and contents of the user's playlists, then possibly saves them to a text file or w/e.
I didn't find much on the site to explain exactly what steps are involved in properly connecting to a YouTube account through Java, so I tried running some sample code. If I take this for example:
https://developers.google.com/youtube/v3/code_samples/java#retrieve_my_uploads
And paste it into Eclipse, it tells me the following:
The type "FileCredentialStore" is deprecated.
At the following method:
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JSON_FACTORY, MyUploads.class.getResourceAsStream("/client_secrets.json"));
It tells me:
"The method load(JsonFactory, Reader) in the type GoogleClientSecrets is not applicable for the arguments (JsonFactory, InputStream)"
A bit of Googling led me somewhere that suggested the method used in the example which uses an InputStream was deprecated and later removed in 1.16 I believe.
Later the following error occurs:
channelRequest.setMine("true");
Where the String "true", should be the boolean value true. Again I'm assuming a previous version of that method was deprecated.
I've tried messing around with it, trying to piece things together from Google but it hasn't worked at all. The code seems to be outdated and not to work with the latest version of the API, and most code I can find online seems old too. I don't know enough about what I'm doing and I can't find any documentation that actually outlines what steps are required, why, and how they work.
For instance, I can't figure out what client_secrets.json is for and how it's supposed to be set up, beyond it being a part of authentication. If the API site explained it fully, I couldn't find where.
Does anyone know of a site with some working up-to-date sample code that performs some simple connection and data retrieval? Or a proper step-by-step guide that explains how to connect?
I would've thought something like the YouTube API would be straightforward and well-documented but I just can't get my head around it, unless I've missed something important but I'm out of ideas.
Google API says:
load method with InputStream is Deprecated. (scheduled to be removed in 1.16) Use load(JsonFactory, Reader) instead. Source
Thus convert InputStream to Reader and problem solved
private static GoogleClientSecrets loadClientSecrets(String clientSecretsLocation) {
try {
Reader reader = new InputStreamReader(BigQueryJavaGettingStarted.class.getResourceAsStream(clientSecretsLocation));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(new JacksonFactory(),
reader);
} catch (Exception e) {
System.out.println("Could not load client_secrets.json");
e.printStackTrace();
}
return clientSecrets;
}
I've found this guide on internet to publish on Wordpress using XML-RPC inside my Java Project, for example I want a message on my Blog, every time it's specified date.
http://wordpress.rintcius.nl/post/look-how-this-wordpress-post-got-created-from-java
Now, I've followed the guide and I'm trying to let it run but I don't understand yet how exactly parameters for my post works.
For example using the method blogger.NewPost I call:
public Integer post(String contents) throws XmlRpcException {
Object[] params = new Object[] {
blogInfo.getApiKey(),
blogInfo.getBlogId(),
blogInfo.getUserName(),
blogInfo.getPassword(),
contents,
postType.booleanValue()
};
return (Integer) client.execute(POST_METHOD_NAME, params);
}
and my "contents" value is:
[title]Look how this wordpress post got created from java![/title]"
+ "[category]6[/category]"
+ FileUtils.getContentsOfResource("rintcius/blog/post.txt");
(I'm using "[" instead of "<" and "]" instead of ">" that are processed by stackoverflow)
Now, how could I use all parameters in this XML way?
Parameters here: http://codex.wordpress.org/XML-RPC_MetaWeblog_API#metaWeblog.newPost
And, it's the content only a "string" without any tag?
Thanks a lot to all!
Still don't know why it gives me back errors but i think it's only a bit outdated.
Found this other libraries that works perfectly
http://code.google.com/p/wordpress-java/
I advice all to use this since the other one is outdated
Thanks all