I'm using Amazon SQS. My goal is to read ApproximateReceiveCount attribute from ReceiveMessage API action using the Java SDK (v2.10.4, Java 11).
I tried the following code, but message.attributes() doesn't contain the required key:
String getApproximateReceiveCount() {
var receiveMessageRequest = ReceiveMessageRequest.builder()
.queueUrl("https://sqs.eu-west-1.amazonaws.com/012345678910/my-example-queue")
.build();
var sqsClient = SqsClient.builder().endpointOverride(URI.create("http://localhost:4576")).build();
var response = sqsClient.receiveMessage(receiveMessageRequest);
var message = response.messages().get(0);
return message.attributes().get(MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT);
}
How to go about receiving an entry for MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT key, in this map?
As per the documentation page to ReceiveMessage which you linked, there is a parameter called AttributeName.N described as
A list of attributes that need to be returned along with each message. These attributes include:
[...]
ApproximateReceiveCount – Returns the number of times a message has been received from the queue but not deleted.
Therefore you need to ask for the attribute in the request, for it to be available in the response. To do that use ReceiveMessageRequestBuilder.attributeNamesWithStrings() method like so:
String getApproximateReceiveCount() {
var receiveMessageRequest = ReceiveMessageRequest.builder()
.queueUrl("https://sqs.eu-west-1.amazonaws.com/012345678910/my-example-queue")
.attributeNamesWithStrings(MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT.toString())
.build();
var sqsClient = SqsClient.builder().endpointOverride(URI.create("http://localhost:4576")).build();
var response = sqsClient.receiveMessage(receiveMessageRequest);
var message = response.messages().get(0);
return message.attributes().get(MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT);
}
Note that there are two similarly named methods, which you can't use:
.attributeNames() - the parameter enum doesn't list the required key,
.messageAttributeNames() - corresponds to attributes sent along with the message body.
Related
i need to implement webhook controller to handle complete payment event so how can i handle or subscribe.
`public IActionResult Webhook()
{
// The APIContext object can contain an optional override for the trusted certificate.
var apiContext = PayPalConfiguration.GetAPIContext();
// Get the received request's headers
var requestheaders = HttpContext.Request.Headers;
// Get the received request's body
var requestBody = string.Empty;
using (var reader = new System.IO.StreamReader(HttpContext.Request.Body))
{
requestBody = reader.ReadToEnd();
}
dynamic jsonBody = JObject.Parse(requestBody);
string webhookId = jsonBody.id;
var ev = WebhookEvent.Get(apiContext, webhookId);
// We have all the information the SDK needs, so perform the validation.
// Note: at least on Sandbox environment this returns false.
// var isValid = WebhookEvent.ValidateReceivedEvent(apiContext, ToNameValueCollection(requestheaders), requestBody, webhookId);
switch (ev.event_type)
{
case "PAYMENT.CAPTURE.COMPLETED":
// Handle payment completed
break;
case "PAYMENT.CAPTURE.DENIED":
// Handle payment denied
break;
// Handle other webhooks
default:
break;
}
return new HttpStatusCodeResult(200);
}
this is javascript example i got but same as i want to handler implementation in java.and which parameters are needed when controller getting hit.
For PayPal Subscriptions, the list of Webhook event names is here: https://developer.paypal.com/docs/api-basics/notifications/webhooks/event-names/#subscriptions , and in particular the one you would want is PAYMENT.SALE.COMPLETED (not ".CAPTURE.")
You may find the information here helpful: https://stackoverflow.com/a/65139331/2069605
I have a node js server implementation and I would like to send some values to an Android (Java) client. The method of the node js server is as follows:
app.get('/GetValues*', function (request, response) {
// Request needs to be a GET
if (request.method == 'GET') {
var username = request.query.account;
var time_now = Date.now();
var db = database('./database.db');
var row_account = db.prepare('SELECT SCORE score, STARTED_STUDY_SERVER_MILLIS timestamp, DAYS_TOTAL days_total FROM ACCOUNTS WHERE NAME = ?').get(username);
var score = row_account.score;
var days_total = row_account.days_total;
var days_count = time_now - row_account.timestamp;
var minutes_count = time_now - row_account.timestamp;
var statement = db.prepare("UPDATE ACCOUNTS SET DAYS_COUNT = ?, MINUTES_COUNT = ? WHERE ID = ?");
statement.run(days_count,minutes_count,getAccountID(db, request.query.account));
var row_usage = db.prepare('SELECT DURATION_ENABLED duration_enabled, DURATION_DISABLED duration_disabled FROM USAGE WHERE NAME = ?').get(username);
var duration_enabled = row_usage.duration_enabled;
var duration_disabled = row_usage.duration_disabled;
}
});
I would like to send the values score (integer), days_total (integer), days_count (integer), minutes_count (long), duration_enabled (long), duration_disabled (long) to the client.
How can I send it to the client? I think response.send() only accepts strings. How can I parse the values in Java when received?
Since you need to send all those values at once, it's common to respond with a JSON in such a case. In express, you can send a JSON response using response.send() or response.json() like this:
app.get('/GetValues*', function (request, response) {
// ... your db operations here, then
response.json({
score: score,
days_total: days_total,
days_count: days_count,
minutes_count: minutes_count,
duration_enabled: duration_enabled,
duration_disabled: duration_disabled
});
});
This will send a response with Content-Type: application/json and a JSON string in the body looking like this:
{"score":12,"days_total":12,"days_count":12,"minutes_count":12,"duration_enabled":12,"duration_disabled":12}
Then you just parse it in your Java code.
By the way, this line
if (request.method == 'GET') {
is unnecessary. Registering a handler via app.get(), express will only handle GET requests anyway.
I'm listening for connection changes through events pluging ("amq.rabbitmq.event", "connection.#").
It works properly so I'm adding at java side two additional parameters as clientproperties, to get the identity of the user that connects or disconnect.
However at c# side I can only access these properties as a list of byte[], and not sure on how to convert it to a Dictionary or so..
If I print all entries
if (args.BasicProperties.Headers.TryGetValue("client_properties", out object value))
{
var items = value as List<object>;
foreach(var item in items)
{
Console.WriteLine($"{item.GetType().ToString()}");
var bytes = item as byte[];
result.Add(Encoding.UTF8.GetString(bytes));
}
}
I can see this:
{<<"platform">>,longstr,<<"Java">>}
{<<"capabilities">>,table,[{<<"connection.blocked">>,bool,true},{<<"basic.nack">>,bool,true},{<<"exchange_exchange_bindings">>,bool,true},{<<"authentication_failure_close">>,bool,true},{<<"publisher_confirms">>,bool,true},{<<"consumer_cancel_notify">>,bool,true}]}
{<<"groupId">>,longstr,<<"1e6e935f0d4d9ec446d67dadc85cbafd10d1a095">>}
{<<"information">>,longstr,<<"Licensed under the MPL. See http://www.rabbitmq.com/">>}
{<<"version">>,longstr,<<"4.8.1">>}
{<<"copyright">>,longstr,<<"Copyright (c) 2007-2018 Pivotal Software, Inc.">>}
{<<"product">>,longstr,<<"RabbitMQ">>}
What kind of object format is and how can I parse this?:
{<<id>>,type,<<value>>}
Apparently ( as for an answer I got on Rabbit client google group for this questions ), client_properties is something that's not created to being read by the receiving party..
However is a really good way to have something like LWT ( Last Will and Testament ), then I am using it at the minute doing the parse by myself.
if (args.BasicProperties.Headers.TryGetValue("client_properties", out object value))
{
var items = value as List<object>;
foreach (var item in items)
{
var bytes = item as byte[];
//{<<id>>, type, <<value>>}
String itemStr = Encoding.UTF8.GetString(bytes);
var parts = itemStr.Split(",");
var key = CleanErlangString(parts[0]);
var value = CleanErlangString(parts[2]);
// Do things with key/value
}
}
ClearErlangFunction
private static string CleanErlangString(string toClean)
{
return toClean
.Replace("{", "").Replace("}", "")
.Replace("\"", "")
.Replace("<<", "").Replace(">>", "");
}
What I am doing to use it as LWT, is setting a custom property on client side and then obtaining it while reading events at "amq.rabbitmq.event", "connection.#". With that I know who have disconnected and even process something as LWT with my core server.
I hope this helps someone :)
I tried to get product from API with some parameters. I used WooCommerce API Java Wrapper. REST API with OAuth 1.0. Simple getAll method return list of one page (10 products). To get all i must set how much products must be in one page and use offset. To get third page must send this parameters: "per_page=10&offset=20". I test with query in get&post programm - all work. In Java, when i added parameters - i got error (401)- "Invalid signature - the provided signature did not match".
I changed WooCommerceAPI class:
private static final String API_URL_FORMAT = "%s/wp-json/wc/v2/%s";
private static final String API_URL_ONE_ENTITY_FORMAT = "%s/wp-json/wc/v2/%s/%d";
private HttpClient client;
private OAuthConfig config;
public List getAll(String endpointBase) {
String url = String.format(API_URL_FORMAT, config.getUrl(), endpointBase) + "?per_page=10&offset=20";
String signature = OAuthSignature.getAsQueryString(config, url, HttpMethod.GET);
String securedUrl = String.format("%s&%s", url, signature);
System.out.println("url="+url);
System.out.println("securedUrl="+securedUrl);
return client.getAll(securedUrl);
}
But I have got the same error.
I've just released a new version of wc-api-java library (version 1.2) and now you can use the method getAll with params argument where you can put additional request parameters. For example:
// Get all with request parameters
Map<String, String> params = new HashMap<>();
params.put("per_page","100");
params.put("offset","0");
List products = wooCommerce.getAll(EndpointBaseType.PRODUCTS.getValue(), params);
System.out.println(products.size());
As you noticed, you changed URL_SECURED_FORMAT from "%s?%s" to "%s&%s", as soon as you added query params. But problem is that signature is generated based on all query params, not only oauth_*, and your params offset and per_page are ignored while generating signature (as soon as lib author did not expect additional params).
Think that you need to modify this lib to support signature based on all params.
I'm using the SoapUI API as part of an existing java project.
The application should save the request and response XML in an specific report file.
I wonder if it's possible to get those requests and responses via the API.
The method invoking the TestCaseRunner looks like this
protected void checkTestCase(TestCase testCase) {
TestCaseRunner tr = testCase.run(null, false);
for (TestStepResult tcr : tr.getResults()) {
String status = tcr.getStatus();
String time = tcr.getTimeTaken() + "ms";
/* How to get XML messages?
* String request =
* String response =
*/
}
}
Depending on exactly what kind of test steps you have they might be an instance of a MessageExchange. Casting the TestStepResult to a MessageExchange and calling getRequestContent / getResponseContent might do the trick.
String request = ((MessageExchange)tcr).getRequestContent();
String response = ((MessageExchange)tcr).getResponseContent();
I have used the following way to get the response from the API CAll performed:
runner = testRunner.runTestStepByName("Your Test Case name");
// Here we take the response in ms of the API call
timeTaken = runner.response.timeTaken;
// here we get the HTTP response code.
responseCode = runner.getResponseHeaders()."#status#";
// here we get the response content
String response = runner.getResponseContent();
// here we get the API call endpoint -> in case you need to print it out.
String endPoint = runner.getEndpoint();