How to get list of AWS WAF details - java

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.

Related

java get all values for a field in elasticsearch

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": {}}}'

Randomly changing the JSON Values for every "Post" Request Body using Java

This could be a duplicate question, but I couldn't find my solution anywhere. Hence, posting it.
I am trying to simply POST a request for a Student account Creation Scenario. I do have a JSON file which comprises all the "Keys:Values", required for Student account creation.
This is how the file student_Profile.json looks like:
{
"FirstName":"APi1-Stud-FN",
"MiddleInitial":"Q",
"LastName":"APi1-Stud-LN",
"UserAlternateEmail":"",
"SecretQuestionId":12,
"SecretQuestionAnswer":"Scot",
"UserName":"APi1-stud#xyz.com",
"VerifyUserName":"APi1-stud#xyz.com",
"Password":"A123456",
"VerifyPassword":"A123456",
"YKey":"123xyz",
"YId":6,
"Status":false,
"KeyCode":"",
"SsoUserName":"APi1-stud#xyz.com",
"SsoPassword":"",
"BirthYear":2001
}
So everything on Posting the request from "Rest Assured" point of view looks fine, it's just that I want to update a few values from the above JSON body using JAVA so that I can create a new Student profile every time I run my function and don't have to manually change the Body.
For Every POST Student Account Creation scenario, I need to update the value for
the following keys so that a new test student user account can be created:
First Name
Last Name and
Username // "VerifyUserName" and "SSO UserName" will remain same as user name
I modified the answer to get random values and pass them to json body. random value generation was taken from the accepted answer of this question.
public void testMethod() {
List<String> randomValueList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
randomValueList.add(salt.toString());
}
String jsonBody = "{\n" +
" \"FirstName\":\"" + randomValueList.remove(0) + "\",\n" +
" \"MiddleInitial\":\"Q\",\n" +
" \"LastName\":\"" + randomValueList.remove(0) + "\",\n" +
" \"UserAlternateEmail\":\"\",\n" +
" \"SecretQuestionId\":12,\n" +
" \"SecretQuestionAnswer\":\"Scot\",\n" +
" \"UserName\":\"" + randomValueList.remove(0) + " \",\n" +
" \"VerifyUserName\":\"APi1-stud#xyz.com\",\n" +
" \"Password\":\"A123456\",\n" +
" \"VerifyPassword\":\"A123456\",\n" +
" \"YKey\":\"123xyz\",\n" +
" \"YId\":6,\n" +
" \"Status\":false,\n" +
" \"KeyCode\":\"\",\n" +
" \"SsoUserName\":\"APi1-stud#xyz.com\",\n" +
" \"SsoPassword\":\"\",\n" +
" \"BirthYear\":2001\n" +
"}";
Response response = RestAssured
.given()
.body(jsonBody)
.when()
.post("api_url")
.then()
.extract()
.response();
// Do what you need to do with the response body
}
We can used pojo based approach to do certain things very easily . No matter how complex is the payload , serialization and dieselization is the best answer . I have created a framework template for api automation that can we used by putting required POJO's in path :
https://github.com/tanuj-vishnoi/pojo_api_automation
To create pojo, I also have ready to eat food for you :
https://github.com/tanuj-vishnoi/pojo_generator_using_jsonschema2pojo
for the above problem you can refer to the JsonPath lib https://github.com/json-path/JsonPath and use this code:
String mypayload = "{\n" +
" \"FirstName\":\"APi1-Stud-FN\",\n" +
" \"MiddleInitial\":\"Q\",\n" +
" \"LastName\":\"APi1-Stud-LN\"}";
Map map = JsonPath.parse(mypayload).read("$",Map.class);
System.out.println(list);
once the payload converted into map you can change only required values as per the requirement
To generate random strings you can refer to lib org.apache.commons.lang3.RandomStringUtils;
public static String generateUniqueString(int lenghtOfString){
return
RandomStringUtils.randomAlphabetic(lenghtOfString).toLowerCase();
}
I recommend to store payload in a separate file and load it at runtime.

I get error "400 Bad request" when trying to post a new issue into a GitHub repository

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!

iOS Push Notifications not working

I am using Ionic 3 with Ionic Native Push Notifications on the client and Java com.notnoop.apns on the server.
I can get the Push Notifications to work successfully on an Android devise. However, on an iOS devise, the client does not display the notification.
client (ts)
let topics: string[] = [this.personModelLoggedIn.uid];
const options: PushOptions = {
android: {
senderID: "XXXXXXXXXXXXXX",
sound: "true",
vibrate: "true",
topics: topics
},
ios: {
alert: "true",
badge: false,
sound: "true"
},
windows: {}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((data: any) => {
alert('Received Notification!!! message = ' + data.message);
});
server (java)
Android
private String sendAndroidPushNotification(String device_token, String topics, String title, String message)
throws Exception {
String pushMessage = null;
if (device_token != null && !device_token.equals("null")) {
pushMessage = "{\"data\":{\"title\":\"" + title + "\",\"message\":\"" + message + "\"},\"to\":\""
+ device_token + "\"}";
} else {
pushMessage = "{\"data\":{\"title\":\"" + title + "\",\"message\":\"" + message + "\"},\"to\": \"/topics/"
+ topics + "\"}";
}
// Create connection to send FCM Message request.
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send FCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(pushMessage.getBytes());
return "Android Push Notification: " + conn.getResponseCode() + " " + conn.getResponseMessage() + " - " + pushMessage;
}
iOS
private String sendIOSPushNotification(String device_token, String topics, String title, String message)
throws Exception {
ApnsService service = APNS.newService().withCert(PATH_TO_P12_CERT, CERT_PASSWORD).withSandboxDestination()
.build();
String payload = APNS.newPayload()
// .customFields(map)
.alertBody(title + " " + message).sound("default").build();
//service.push(Utilities.encodeHex(topics.getBytes()), payload);
service.push(device_token), payload);
return "iOS Push Notification: " + title + " " + message;
}
When the above two java methods get called with the appropriate devise tokens, the Android devise receives a notification, but the iOS devise does not.
Question
If anyone can advise what's wrong with my iOS code (either client or server), I would appreciate your advise.
UPDATE
If I try test my APNS on http://pushtry.com/, with my apps apns-prod-cert.p12, I get the following:
Push Notification sent Successfully
And the client does display the notification. So this makes me think there is something wrong with my server code.
Solution
private String sendIOSPushNotification(String device_token, String topics, String title, String message)
throws Exception {
ApnsServiceBuilder serviceBuilder = APNS.newService();
serviceBuilder.withCert(PATH_TO_P12_CERT, CERT_PASSWORD)
.withProductionDestination();
ApnsService service = serviceBuilder.build();
String payload = APNS.newPayload()
.alertBody(message)
.alertTitle(title)
.sound("default")
.customField("custom", "custom value").build();
service.push(device_token, payload);
return "iOS Push Notification: " + title + " " + message;
}

400 bad request without error message - Twitter API

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?

Categories