i have java sample code that insert 2 basic documents
#Container
private final ElasticsearchContainer elasticContainer = DataApiElasticSearchContainer.getInstance();
HttpEntity<String> entity_post = new HttpEntity<>("{\"man_name\": \"Hello world!\"}", headers);
HttpEntity<String> entity_post2 = new HttpEntity<>("{\"man_name\": \"Hello world666!\"}", headers);
HttpEntity<String> entity_get = new HttpEntity<>("{\n" +
" \"aggs\": {\n" +
" \"genres\": {\n" +
" \"terms\": { \"field\": \"man_name\" } \n" +
" }\n" +
" }\n" +
"}" +
"}", headers);
ResponseEntity<String> response_post =
restTemplate.exchange("http://" + elasticContainer.getHttpHostAddress() + "/bookindex/man_name",
HttpMethod.POST, entity_post,String.class);
assertThat(response_post.getStatusCode()).isEqualTo(HttpStatus.CREATED);
ResponseEntity<String> response_post2 =
restTemplate.exchange("http://" + elasticContainer.getHttpHostAddress() + "/bookindex/man_name",
HttpMethod.POST, entity_post2,String.class);
assertThat(response_post2.getStatusCode()).isEqualTo(HttpStatus.CREATED);
ResponseEntity<String> response =
restTemplate.exchange("http://" + elasticContainer.getHttpHostAddress() + "/bookindex/_search",
HttpMethod.GET, entity_get, String.class);
System.out.println(response.getBody());
But i have this output from my get body
{"took":36,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":0,"relation":"eq"},"max_score":null,"hits":[]}}
i want list of man_name values like this : ["Hello world!", "Hello world666!"]
If I get you question right, There is nothing wrong with your code and every time you execute the code you will receive the log that your two documents ingested successfully in one shard but if you want to get the list of your ingested documents as you may know you need to add query Api such below at the end of your http request . In this manner you will receive the list of your documents.
curl -XGET "http://localhost:9200/yourindexname/_search" -H 'Content-Type: application/json' -d'{ "query": {"match_all": {}}}'
Related
How would be the class that matches the following json :
'''{
"id1" : {
"apiToCall" : ["200", "400", "500"],
"apiToCall2" : ["100"],
"apiToCall5" : ["600", "300"]
},
"id2" : {
"apiToCall10" : ["300"],
"apiToCall8" : ["600", "700", "500"]
},
"id3" : {
"apiToCall80" : ["200", "400", "500"]
}
}'''
I want to send this object in POST method using spring rest, but my issue is that i have dynamic attributes.
So i don't know how to create the class that manages this case.
HttpEntity<String> entity = new HttpEntity(reqJsonStr, headers);
KeyPoint : "HttpEntity<String>" means type of request(reqJsonStr) is string.
RestTemplate restTemplate = new RestTemplate();
String reqURL = \"https://www.request_url.com/restapi/\";
String reqJsonStr = \"{"
+ " "\"id1\" : {"
+ " \"apiToCall\" : [\"200\", \"400\", \"500\"],"
+ " \"apiToCall2\" : [\"100\"],"
+ " \"apiToCall5\" : [\"600\", \"300\"]"
+ " },"
+ " \"id2\" : {"
+ " \"apiToCall10\" : [\"300\"],"
+ " \"apiToCall8\" : [\"600\", \"700\", \"500\"]"
+ " },"
+ " \"id3\" : {"
+ " \"apiToCall80\" : [\"200\", \"400\", \"500\"]"
+ " }"
+ "}";
headers headers = new headers();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr, headers);
String responseStr = restTemplate.exchange(reqURL, reqJsonStr, HttpMethod.POST, String.class);
I am not sure if it will work or not but it can be
Map<String, Map<String, List<String>>
I am trying to fetch list of WAF from my AWS account. But always I am getting empty values.
AWSWAF client = AWSWAFClientBuilder.standard().withRegion(Regions.US_EAST_1)
.withCredentials(new StaticCredentialsProvider(awsCredentials)).build();
ListWebACLsRequest request = new ListWebACLsRequest();
ListWebACLsResult response = client.listWebACLs(request);
System.out.println("Response " + response);
List<WebACLSummary> webACLSummary = response.getWebACLs();
System.out.println(" webACLSummary "+webACLSummary);
webACLSummary.forEach(webACL -> {
System.out.println("Web ACL " + webACL.getName() + " ACLID " + webACL.getWebACLId());
});
Response:
Response {WebACLs: []}
webACLSummary []
But in my AWS Region, I have "AWS WAF", AM I missing anything in my code.
I'm building a web with spring that will allow the user to see the repositories, their issues and add new issues if they want. The problem appears when the user wants to create a new issue. I get "Error 400 Bad Request" and I can not underestand why.
I've tried to send the request through URL parameters but it didn't work either. I've also tried to automatically create the body with an ObjectMapper but I got the same result. So I'm building the body by myself but... same result again.
At the line with the comment "XXX" is where the software fails and in the web shows me the mentioned error.
#PostMapping("newIssue/{user}/{repo}/{fullName}")
public String registerUser(#PathVariable String user, #PathVariable String repo, #PathVariable String fullName, #Valid NewIssue newissue, Errors errors, Model model, OAuth2AuthenticationToken authentication) throws JsonProcessingException {
//To debug
System.out.println("### Registering issue");
//Check errors
List<String> errorsStrings = new ArrayList<>();
errors.getAllErrors().forEach(e->errorsStrings.add(e.getDefaultMessage()));
model.addAttribute("errors", errorsStrings);
model.addAttribute("newissue", newissue);
if(errors.hasErrors()) {
//To debug
System.out.println("### HAS ERRORS");
for (String err: errorsStrings )
System.out.println(" " + err);
//If has errors show again the page
return "newIssue";
}
//To debug
System.out.println("### Does not have ERRORS");
//Create the client variable
OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient( authentication.getAuthorizedClientRegistrationId(), authentication.getName() );
//Construct the necessary headers
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "token " + client.getAccessToken().getTokenValue());
headers.add(HttpHeaders.ACCEPT, "application/vnd.github.v3+json");
//Construct the html petition's body
ObjectMapper mapper = new ObjectMapper();
//String body = mapper.writeValueAsString(newissue);
String body =
"{\n" +
" \"title\": \"" + newissue.getTitle() + "\",\n" +
" \"body\": \"" + newissue.getBody() + "\",\n" +
" \"assignees\": [],\n" +
" \"milestone\": none,\n" +
" \"labels\": []\n" +
"}"
;
//Merge the header and the body
HttpEntity<String> request = new HttpEntity<String>(body, headers);
//To debug
System.out.println("### Going to send post: ");
System.out.println(body);
//Send the issue to the api
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("https://api.github.com/repos/" + user + "/" + repo + "/issues", HttpMethod.POST, request, String.class); //XXX
//To debug
System.out.println("### Post sent");
//To debug
System.out.println("### RESPONSE: " + response);
//Go to the repos' issues webpage
return "redirect:issues/"+user+"/"+repo+"/"+fullName;
}
I expected this method to create the new issue in the repository and then redirect to the repository's list of issues.
I've checked the body and it seems to be correct to me:
{
"title": "TestTitle",
"body": "TestBody",
"assignees": [],
"milestone": none,
"labels": []
}
I did it all consulting the GitHub api documentation: https://developer.github.com/v3/issues/#create-an-issue
According to the documentation you provided under 'Create an issue', the value for "milestone" should be an Integer. Therefore, looking at your request, none is not an integer. I'm not sure what int you would supply in the request but I don't believe 'none' would work.
String body =
"{\n" +
" \"title\": \"" + newissue.getTitle() + "\",\n" +
" \"body\": \"" + newissue.getBody() + "\",\n" +
" \"assignees\": [],\n" +
" \"milestone\": 0,\n" +
" \"labels\": []\n" +
"}"
;
This would create the following body:
{
"title": "TestTitle",
"body": "TestBody",
"assignees": [],
"milestone": 0,
"labels": []
}
In addition, looking at the 'List issues for a repository' section, it appears they mention to only use "none" as a String.
As Brandon and NeplatnyUdaj said the issue was probably related with the "milestone line" because it was mandatory to be an integer. I put "none" because I did not want to add any milestone and it is the keyword used if you want to remove the milestones after the creation of the issue.
Thanks to the people that answered me I figured out that you could remove the "milestone line" due there is no way to telling the API that "there are no milestones" in the creation of the issue (despite you can remove all the milestones after the creation according to the documentation).
Than you all!
Hey guys!
I'm currently trying to create an app that uses the Twitter API to get timelines of users. I'm currently stuck at a specific point! My user has already logged in and I've already received the access token and the token secret. I'm now trying to send a get request to the Twitter server.
My problem is that I'm always getting a 400 bad request error code WITHOUT any kind of message.
I'm using Volley to send the requests - Heres the code
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Response Time: " + error.getNetworkTimeMs() + " ms");
Log.e(TAG, "Code: " + error.networkResponse.statusCode);
Log.e(TAG, "Data: " + new String(error.networkResponse.data));
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
Long tsLong = System.currentTimeMillis() / 1000;
//I receive all the difference parts
String consumerKey = context.getString(R.string.twitter_consumer_key);
String nonce = GenerationHelper.generateNonce();
String signature_method = "HMAC-SHA1";
String timestamp = tsLong.toString();
String token = sTwitterToken;
String version = "1.0";
// I use this list to pass the parameters to the function
// generating the signature
List<String> param= new ArrayList<>();
param.add("screen_name=" + username);
param.add("count=" + count);
param.add("oauth_token" + sTwitterToken);
param.add("oauth_consumer_key=" + consumerKey);
param.add("oauth_nonce=" + nonce);
param.add("oauth_signature_method=" + signature_method);
param.add("oauth_timestamp=" + timestamp);
param.add("oauth_version=" + version);
String signature = GenerationHelper.generateSignature(context, param, "POST", "https://api.twitter.com/1.1/statuses/user_timeline.json");
// I create the header String
StringBuilder paramBuilder = new StringBuilder();
paramBuilder.append("oauth_consumer_key=\"" + consumerKey + "\", ");
paramBuilder.append("oauth_nonce=\"" + nonce + "\", ");
paramBuilder.append("oauth_signature=\"" + signature + "\", ");
paramBuilder.append("oauth_signature_method=\"" + "HMAC-SHA1" + "\", ");
paramBuilder.append("oauth_timestamp=\"" + timestamp + "\", ");
paramBuilder.append("oauth_token=\"" + sTwitterToken + "\", ");
paramBuilder.append("oauth_version=\"" + "1.0" + "\"");
String credentialString = paramBuilder.toString();
Log.d(TAG, credentialString);
params.put("Authorization", "OAuth " + credentialString);
return params;
}
};
My current response is
Code: 400
Data:
If I remove the line adding the authorization data I get the response
Code: 400
Data: {"errors":[{"code":215,"message":"Bad Authentication data."}]}
I'm pretty sure that I don't get rate limited because I'm just sending about 10 requests per 15 minutes.
Does anybody have any idea why I'm having this problem?
Please help me to send a JSON object in POST HTTP request through HttpClient, in Android.
The problem I am facing is that the JSON object having the URL is replaced by forward slash ,i.e
originally it should have the following value in JSON object
{"product":
{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg,
"short_description":"this is a test","title":"Raiders from the North"}
}
i tried many options to keep it in the above format. But it always comes as {"featured_src":
We assume this is your input
private final static String JSON_DATA = "{"
+ " \"product\": ["
+ " {"
+ " \"featured_src\": \"https:\\/\\/example.com\\/wp-content"
+ "\\/uploads\\/2015\\/06\\/sidney-compressed.jpg\","
+ " \"short_description\": \"this is a test\","
+ " \"title\" : \"Raiders from the North\""
+ " }"
+ " ]"
+ "}";
You could use replace to do the trick.
YOUR_STRING.replace("\\", "");
Finally your method would look like this, by passing your string as parameter
private static String jsonUrlCorrector(String json_data) {
json_data = json_data.replace("\\", "");
return json_data;
}
Here is the input:
{"product":[{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg","short_description": "this is a test","title":"Raiders from the North"}]}
Here is the output
{"product":[{"featured_src":"https://example.com/wp-content/uploads/2015/06/sidney-compressed.jpg","short_description":"this is a test","title":"Raiders from the North"}]}