Jersey Client - Post request giving error "Content-Type header must be application/vnd.api+json" - jersey

I am trying to test post request using jersey client, although i am setting header as below i am getting error in response that Content-Type header must be application/vnd.api+json. Please refer below code:
String input = "{\r\n" +
" \"data\": {\r\n" +
" \"attributes\": {\r\n" +
" \"email\": \"emailqwszxwe#example.com\",\r\n" +
" \"password\": \"password\",\r\n" +
" \"avatar_url\": \"http://example.com/example.png\",\r\n" +
" \"first-name\": \"John\",\r\n" +
" \"last-name\": \"Doe\",\r\n" +
" \"details\": \"example\",\r\n" +
" \"contact\": \"example\",\r\n" +
" \"facebook-url\": \"http://facebook.com/facebook\",\r\n" +
" \"twitter-url\": \"http://twitter.com/twitter\",\r\n" +
" \"instagram-url\": \"http://instagram.com/instagram\",\r\n" +
" \"google-plus-url\": \"http://plus.google.com/plus.google\",\r\n" +
" \"original-image-url\": \"https://cdn.pixabay.com/photo/2013/11/23/16/25/birds-216412_1280.jpg\"\r\n" +
" },\r\n" +
" \"type\": \"user\"\r\n" +
" }\r\n" +
"}";
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://qe.events.infostretch.com/api");
String content = "application/vnd.api+json";
Response response = target.path("/v1/users").request().header("Content-Type", content).post(Entity.json(input));
Output :
{"errors": [{"source": "", "detail": "Content-Type header must be application/vnd.api+json", "title": "InvalidRequestHeader", "status": 415}], "jsonapi": {"version": "1.0"}}```
I am not able to understand why it is not showing correct response???
i am using below dependency:
<dependency> <groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.30.1</version> </dependency>

Related

JSoup, Extract specific text or image-link from website

This is in my HTML and I need to extract either the link of the image or the fileId to create a link.
{
"created": "2018-11-06T06:46:21.181Z",
"inRiverId": "58515",
"mediaInformation": {
"bildid": 67708,
"description": "ABC",
"excelImportField": "ABC",
"fileId": "41964",
"filename": "ABC",
"imageAccess": true,
"imageItemType": "ABC",
"imageStatus": "ABC",
"imageType": "ABC",
"itcl": "ABC",
"photographer": "ABC",
"projectName": "ABC",
"projectType": "Webb",
"type": "Bild",
"url": "https://static.john.com/images/products/41964.jpg"
},
The fileId is dynamic, therefor is the link also dynamic depending on which article I'm visiting on my website. The link will always start with "https://static.john.com/images/products/" and then it adds the fileId and ".jpeg" automatically.
The code above is of course just a piece of the code on the website, so there is more images on it, so it needs to extract it specifically.
The dream would be if Jsoup could get this output:
"https://static.john.com/images/products/" + "fileId" + ".jpeg"
I'm a beginner in Android Studio, and crazy-new to JSoup.
Bad news. Jsoup can't do this. Jsoup parses only HTML but this is a JSON fragment which will be used by Javascript after the page is loaded in the browser.
However my idea is to get this URL using regular expressions so try using this code:
String json = "{\n" +
" \"created\": \"2018-11-06T06:46:21.181Z\",\n" +
" \"inRiverId\": \"58515\",\n" +
" \"mediaInformation\": {\n" +
" \"bildid\": 67708,\n" +
" \"description\": \"ABC\",\n" +
" \"excelImportField\": \"ABC\",\n" +
" \"fileId\": \"41964\",\n" +
" \"filename\": \"ABC\",\n" +
" \"imageAccess\": true,\n" +
" \"imageItemType\": \"ABC\",\n" +
" \"imageStatus\": \"ABC\",\n" +
" \"imageType\": \"ABC\",\n" +
" \"itcl\": \"ABC\",\n" +
" \"photographer\": \"ABC\",\n" +
" \"projectName\": \"ABC\",\n" +
" \"projectType\": \"Webb\",\n" +
" \"type\": \"Bild\",\n" +
" \"url\": \"https://static.john.com/images/products/41964.jpg\"\n" +
" },";
Pattern p = Pattern.compile("\"url\": \"(https://static.john.com/images/products/\\d+.jp[e]*g)\"");
Matcher m = p.matcher(json);
if (m.find()) {
String imageUrl = m.group(1);
System.out.println(imageUrl);
}
and the output is: https://static.john.com/images/products/41964.jpg
In your case instead of json variable you should use document.html().
MainActivity.java
public class MainActivity extends AppCompatActivity {
public class JsoupGetImage {
public void main( String[] args ) throws IOException {
// Get the article number from TextView to complete link
String articlenumber = ((TextView) recyclerView.findViewHolderForAdapterPosition(0).itemView.findViewById(R.id.holderArticle)).getText().toString();
// My URL + article number
String url = "https://www.john.com/api/v1.0/articles/" + articlenumber;
// JSoup
Document doc = Jsoup.connect(url).get();
// Pattern - Find pattern using partial link
Pattern p = Pattern.compile("\"url\": \"(https://static.john.com/images/products/\\d+.jp[e]*g)\"");
// Matcher - Find match in my URL from Pattern
Matcher m = p.matcher(url);
if (m.find()) {
String imageUrl = m.group(1);
System.out.println(imageUrl);
}
}
}
}
Does this look good or am I missing something. How do I get my ImageView to show the image of the created link?
Kind regards,
John

Spring Data MongoDb - Criteria equivalent to a given query that uses $expr

I have a collection with documents like this:
{
"_id" : ObjectId("5a8ec4620cd3c2a4062548ec"),
"start" : 20,
"end" : 80
}
and I want to show the documents that overlap a given percentage (50%) with an interval (startInterval = 10, endInterval = 90).
I calculate the overlaping section with the following formula:
min(end , endInterval) - max(start, startInterval ) / (endInterval - startInterval)
In this example:
min(80,90) - max(20,10) / (90-10) = (80-20)/80 = 0.75 --> 75%
Then this document will be shown, as 75% is greater than 50%
I expressed this formula in mongo shell as:
db.getCollection('variants').find(
{
$expr: {
$gt: [
{
$divide: [
{
$subtract: [
{ $min: [ "$end", endInterval ] }
,
{ $max: [ "$start", startInterval ] }
]
}
,
{ $subtract: [ endInterval, startInterval ] }
]
}
,
overlap
]
}
}
)
where
overlap = 0.5, startInterval = 10 and endInterval= 90
It works fine in mongo shell.
I'm asking for an equivalent way to calculate this using Spring Data Criteria, since the $expr functionality I used in mongo shell is still to be implemented in Spring Data Mongo.
Currently I'm using Spring Boot 2.0.0, Spring Data MongoDb 2.0.5 and mongodb 3.6.
Thanks a lot for your time.
There is an open issue to add support for $expr : https://github.com/spring-projects/spring-data-mongodb/issues/2750
In the meantime, you can use an BasicQuery:
BasicQuery query = new BasicQuery("{ $expr: {'$gt': ['$results.cache.lastHit', '$results.cache.expiration']}}");
return ofNullable(mongoTemplate.findAndModify(query, updateDefinition, XXXX.class));
You can even concatenate your existing Criteria with BasicQuery, keeping it exclusive to the $expr:
Criteria criteria = Criteria.where("results.cache.cacheUpdateRetriesLeft").gt(4);
BasicQuery query = new BasicQuery("{ $expr: {'$gt': ['$results.cache.lastHit', '$results.cache.expiration']}}");
query.addCriteria(criteria);
return ofNullable(mongoTemplate.findAndModify(query, updateDefinition, XXXX.class));
Just in case it is helpful for somebody, I finally solved my problem using $redact.
String redact = "{\n" +
" \"$redact\": {\n" +
" \"$cond\": [\n" +
" {\n" +
" \"$gte\": [\n" +
" {\n" +
" \"$divide\": [\n" +
" {\n" +
" \"$subtract\": [\n" +
" {\n" +
" \"$min\": [\n" +
" \"$end\",\n" +
" " + endInterval + "\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"$max\": [\n" +
" \"$start\",\n" +
" " + startInterval + "\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"$subtract\": [\n" +
" " + endInterval + "\n" +
" " + startInterval + "\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" " + overlap + "\n" +
" ]\n" +
" },\n" +
" \"$$KEEP\",\n" +
" \"$$PRUNE\"\n" +
" ]\n" +
" }\n" +
" }";
RedactAggregationOperation redactOperation = new RedactAggregationOperation(
Document.parse(redact)
);
where RedactAggregationOperation is
public class RedactAggregationOperation implements AggregationOperation {
private Document operation;
public RedactAggregationOperation (Document operation) {
this.operation = operation;
}
#Override
public Document toDocument(AggregationOperationContext context) {
return context.getMappedObject(operation);
}
}
As you mentioned, Spring Data Mongo currently does not support $expr, so I have to use custom BSON document, and reflection of MongoTemplate.
public List<Variant> listTest() throws Exception {
double overlap = 0.5;
int startInterval = 10;
int endInterval= 90;
String jsonQuery = "{$expr:{$gt:[{$divide:[{$subtract:[{$min:[\"$end\","+endInterval+"]},{$max:[\"$start\","+startInterval+"]}]},{$subtract:["+endInterval+","+startInterval+"]}]},"+overlap+"]}}";
Document query = Document.parse(jsonQuery);
Method doFind = MongoTemplate.class.getDeclaredMethod("doFind", String.class, Document.class,Document.class,Class.class);
doFind.setAccessible(true);
return (List<Variant>) doFind.invoke(mongoTemplate, "variants", query, new Document(), Variant.class);
}
#NoArgsConstructor #Getter #Setter #ToString
public static class Variant{
int start;
int end;
}
As you may see, field mapping works OK.
Used Spring Data Mongo artifact is org.springframework:data.spring-data-mongodb:2.1.5.RELEASE
Support for $expr operator in spring-data-mongodb library is still non-existent. However there is a work around solution using MongoTemplate to solve this problem -
Aggregation.match() provides an overloaded method that accepts AggregationExpression as a parameter. This method can be used to create the query for $match aggregation pipeline with $expr operator as below -
Example usage of AggregationExpression for $match operator -
Aggregation aggregationQuery = Aggregation.newAggregation(Aggregation.match(AggregationExpression.from(MongoExpression.create("'$expr': { '$gte': [ '$foo', '$bar'] }"))));
mongoTemplate.aggregate(aggregationQuery, Entity.class);
Above code is the equivalent of query -
db.collection.aggregate([{"$match": {"$expr": {"$gte: ["$foo", "$bar"]}}}]);

How to implement Spring Rest Client for elastic search?

We are developing an elastic search application in spring boot. We cannot use the Java API or Java Rest Client API's provided by the elastic search. Instead, we need to do operations in elastic using spring rest template, but elastic doesn't seem to be accepting index requests from the rest client.We got "Not Acceptable" response back. I really appreciate if anyone gives us some hints or information.
elastic version: 5.6
Try this. It works for me for Indexing Document through HTTP API using HttpURLConnection.
URL obj = new URL("http://localhost:9200/index/type");
String json = "{\n" +
" \"user\" : \"kimchy\",\n" +
" \"post_date\" : \"2009-11-15T14:12:12\",\n" +
" \"message\" : \"trying out Elasticsearch\"\n" +
"}";
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
osw.write(json);
osw.flush();
osw.close();
System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
if (con != null)
con.disconnect();
Doing a simple search using HttpURLConnection.
URL obj = new URL("http://localhost:9200/index/type/_search");
String json = "{\n" +
" \"query\": {\n" +
" \"match_all\": {}\n" +
" }\n" +
"}";
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
osw.write(json);
osw.flush();
osw.close();
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
System.out.println("Response : " + br.readLine());
System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
if (con != null)
con.disconnect();

Cannot make a static reference to the non-static method getUnit_id() from the type Officer

I am trying to insert the values from this code below:
public int create(Officer officer) {
String sql = "insert into officer values(" + officer.getOfficer_id() + ", " + officer.getCollege_id() + ", " + Officer.getUnit_id() + ", " + officer.getRole_id() + ")";
return template.update(sql);
}
This should be a compilation error. getUnit_id is not a static method , so you need to call it using an instance of Officer.
public int create(Officer officer) {
String sql = "insert into officer values(" + officer.getOfficer_id() + ", " + officer.getCollege_id() + ", " + officer.getUnit_id() + ", " + officer.getRole_id() + ")";
return template.update(sql);
}

Java EE 6 and JAXRPCSecurity

I'am trying convert my Java EE 5 (GlassFish v2, Metro 2.1.1) application to Java EE 6 (GlassFish 3.1.2, Metro 2.2.1-1). I have problem with webservice client, which security is based on JAXRPCSecuirty. JAXRPCSecurity configuration:
private final static String SECURITY_CONFIG =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?> "+
"<xwss:JAXRPCSecurity xmlns:xwss=\"http://java.sun.com/xml/ns/xwss/config\"> " +
" <xwss:Service> " +
" <xwss:SecurityConfiguration dumpMessages=\"true\"> " +
" <xwss:Sign includeTimestamp=\"false\"> " +
" <xwss:X509Token certificateAlias=\"certificate_alias\" /> " +
" <xwss:CanonicalizationMethod disableInclusivePrefix=\"true\" /> " +
" <xwss:SignatureTarget type=\"xpath\" value=\"//SOAP-ENV:Body\"> " +
" <xwss:Transform algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\" " +
" disableInclusivePrefix=\"true\" /> " +
" </xwss:SignatureTarget> " +
" </xwss:Sign> " +
" </xwss:SecurityConfiguration> " +
" </xwss:Service> " +
" <xwss:SecurityEnvironmentHandler> " +
" SecurityCallbackHandler " +
" </xwss:SecurityEnvironmentHandler> " +
"</xwss:JAXRPCSecurity>";
And how I set this configuration to webservice client:
public void configureSecurity() throws SITAWebServiceException {
String JAXRPCSecurityXML = completeJAXRPCSecurityXML(alias, keyStore, callbackHandler, dumpMessage);
byte[] JAXRPCSecurityXMLBytes = convertJAXRPSecurityXMLToBytes(JAXRPCSecurityXML);
XWSSecurityConfiguration sc = createXWSSecurityConfiguration(JAXRPCSecurityXMLBytes);
((BindingProvider) port).getRequestContext().put(XWSSecurityConfiguration.MESSAGE_SECURITY_CONFIGURATION, sc);
}
private XWSSecurityConfiguration createXWSSecurityConfiguration(final byte[] JAXRPCSecurityXML) throws SITAWebServiceException {
InputStream is = new ByteArrayInputStream(JAXRPCSecurityXML);
try {
return new SecurityConfiguration(is);
} catch (XWSSecurityException e) {
throw new SITAWebServiceException("XWSSecurityConfiguration problem.", e);
} finally {
closeInputStream(is);
}
}
With GlassFish v2 and Metro 2.1.1, everything works fine. But GlassFish 3 uses OSGi based Metro (webservices-api-osgi and webservice-osgi) and classes from package com.sun.xml.xwss are no longer visible (isn't exproted) so I constantly get this Exception:
java.lang.NoClassDefFoundError: com/sun/xml/xwss/XWSSecurityConfiguration
Is there some solution how export package com.sun.xml.xwss or way how to change JAXRPCSecurity to something other/better?
Thanks.

Resources