How to use UpdateEventSourceMappingRequest in java? - java

I'm trying to use something like this:
UpdateEventSourceMappingRequest request = new UpdateEventSourceMappingRequest()
.withFunctionName("arn:aws:lambda:us-east-1:9999999999:function:"+functionName)
.withEnabled(false);
But I received a error because I have to use .withUUID(uuid):
UpdateEventSourceMappingRequest request = new UpdateEventSourceMappingRequest()
.withUUID(uuid))
.withFunctionName("arn:aws:lambda:us-east-1:9999999999:function:"+functionName)
.withEnabled(false);
I don't know how to get the value of uuid ( uuid from aws lambda ).
Can you help me with the solution to my problem ?

You need to provide the UUID identifier of the event source mapping to update it (and this field is mandatory). Update-request is not intended to create it.
When you create an event source mapping (here) - aws should return a response with a UUID identifier which you then may use in the update request.

That's the solution that I founded:
String strUUID = "";
ListEventSourceMappingsRequest requestList = new ListEventSourceMappingsRequest()
.withEventSourceArn("arn:aws:sqs:us-east-1:9999999999:test");
ListEventSourceMappingsResult result = awsLambda.listEventSourceMappings(requestList);
List<EventSourceMappingConfiguration> eventSourceMappings = result.getEventSourceMappings();
for (EventSourceMappingConfiguration eventLambda : eventSourceMappings) {
strUUID = eventLambda.getUUID();
}
System.out.println("Output UUID " + strUUID);
We have to use the ARN of the SQS that's trigger of the aws lambda.

Related

AWS SSM parameter store not fetching all key/values

Could someone let me know why the below code only fetching few entries from the parameter store ?
GetParametersByPathRequest getParametersByPathRequest = new GetParametersByPathRequest();
getParametersByPathRequest.withPath("/").setRecursive(true);
getParametersByPathRequest.setWithDecryption(true);
GetParametersByPathResult result = client.getParametersByPath(getParametersByPathRequest);
result.getParameters().forEach(parameter -> {
System.out.println(parameter.getName() + " - > " + parameter.getValue());
});
GetParametersByPath is a paged operation. After each call you must retrieve NextToken from the result object, and if it's not null and not empty you must make another call with it added to the request.
Here's an example using DescribeParameters, which has the same behavior:
DescribeParametersRequest request = new DescribeParametersRequest();
DescribeParametersResult response;
do
{
response = client.describeParameters(request);
for (ParameterMetadata param : response.getParameters())
{
// do something with metadata
}
request.setNextToken(response.getNextToken());
}
while ((response.getNextToken() != null) && ! respose.getNextToken.isEmpty());
Here is the code, based on the code above, for the new 2.0 version of AWS SSM manager. Notice I have set the maxResults to 1 to prove out the loop. You will want to remove that. AWS has mentioned that in the new code they wanted to emphasize immutability.
Using this dependency:
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ssm</artifactId>
<version>2.10.32</version>
</dependency>
I came up with this code:
private void refreshCache() {
StopWatch sw = StopWatch.createStarted();
GetParametersByPathRequest request = GetParametersByPathRequest.builder()
.path(prefix)
.withDecryption(useDecryption)
.maxResults(1)
.build();
GetParametersByPathResponse response;
do {
response = ssm.getParametersByPath(request);
for (Parameter p : response.parameters()) {
//do something with the values.
}
request = GetParametersByPathRequest.builder()
.path(prefix)
.withDecryption(useDecryption)
.nextToken(response.nextToken())
.maxResults(1)
.build();
}
while (StringUtils.isNotBlank(response.nextToken()));
LOG.trace("Refreshed parameters in {}ms", sw.getTime());
}
private void getSsmParams() {
AWSSimpleSystemsManagement client = AWSSimpleSystemsManagementClientBuilder.defaultClient();
GetParametersByPathRequest request = new GetParametersByPathRequest();
request.withRecursive(true);
request.withPath('/your/path/parameterName').setWithDecryption(true);
GetParametersByPathResult response;
do {
response = client.getParametersByPath(request);
for (Parameter p : response.parameters()) {
//do something with the values. maybe add to a list
}
request.setNextToken(response.getNextToken())
}
while (StringUtils.isNotBlank(response.getNextToken()));
}
Above piece of code worked for me .ssm only sends 10 parameters at a time, so if you want to fetch more than 10 parameters from ssm parameter store programatically you will have to use multiple calls to fetch them. here the token is important , if there are more values in the path (request.withPath('/your/path/parameterName')) you have given, it will send a token indicating that there are more values in the given path ,and you will have to make the following request with the token received from the previous request in order to get the rest of the values.

Add AWS SQS Permission to all Principals through SDK

I'm trying to create an AWS SQS queue through the Java SDK, and then add all permissions for all users. I can create the queue fine, but I'm struggling to know what value I can pass in for the Principals. This is what my code looks like:
CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName).withAttributes(attributes);
CreateQueueResult createQueueResult = amazonSqs.createQueue(createQueueRequest);
String queueUrl = createQueueResult.getQueueUrl();
amazonSqs.addPermission(queueUrl, "*", ????, Arrays.asList("*"));
The ??? is what I'm not sure on. I've tried Arrays.asList("*") but it complains about it not being valid. In the web console, there is a checkbox for Everyone, and I'm just wanting to do the same thing in the SDK. Is there some value I can pass for this?
--- UPDATE ---
I've been able to accomplish this another way through a Policy:
String queueUrl = createQueueResult.getQueueUrl();
GetQueueAttributesResult getQueueAttributesResult = amazonSqs.getQueueAttributes(queueUrl, Arrays.asList(QUEUE_ARN_ATTRIBUTE_NAME));
String queueArn = getQueueAttributesResult.getAttributes().get(QUEUE_ARN_ATTRIBUTE_NAME);
if (needToSetPolicy)
{
Policy allAccessPolicy = new Policy("SQSAllAccess", Arrays.asList(
new Statement(Effect.Allow)
.withActions(() -> "SQS:*")
.withPrincipals(Principal.All)
.withId("SQSAllAccessStatement")
.withResources(new Resource(queueArn))
));
Map<String, String> policyMap = new HashMap<>(1);
policyMap.put(POLICY_ATTRIBUTE_NAME, allAccessPolicy.toJson());
amazonSqs.setQueueAttributes(queueUrl, policyMap);
}
It seems like there should be a better/easier way to do this. Are there any better/cleaner/easier ways of doing this?
In kotlin using the constants from the SDK
val policy: Policy = Policy("AllowAllSendMessage", listOf(Statement(Effect.Allow)
.withActions(SQSActions.SendMessage)
.withPrincipals(Principal.All)
.withId("AllowAllSendMessage")
.withResources(Resource(queueArn))))
_sqs.setQueueAttributes(SetQueueAttributesRequest()
.withQueueUrl(queueUrl)
.withAttributes(mapOf(QueueAttributeName.Policy.toString() to policy.toJson())))

createUserDefinedFunction : if already exists?

I'm using azure-documentdb java SDK in order to create and use "User Defined Functions (UDFs)"
So from the official documentation I finally find the way (with a Java client) on how to create an UDF:
String regexUdfJson = "{"
+ "id:\"REGEX_MATCH\","
+ "body:\"function (input, pattern) { return input.match(pattern) !== null; }\","
+ "}";
UserDefinedFunction udfREGEX = new UserDefinedFunction(regexUdfJson);
getDC().createUserDefinedFunction(
myCollection.getSelfLink(),
udfREGEX,
new RequestOptions());
And here is a sample query :
SELECT * FROM root r WHERE udf.REGEX_MATCH(r.name, "mytest_.*")
I had to create the UDF one time only because I got an exception if I try to recreate an existing UDF:
DocumentClientException: Message: {"Errors":["The input name presented is already taken. Ensure to provide a unique name property for this resource type."]}
How should I do to know if the UDF already exists ?
I try to use "readUserDefinedFunctions" function without success. Any example / other ideas ?
Maybe for the long term, should we suggest a "createOrReplaceUserDefinedFunction(...)" on azure feedback
You can check for existing UDFs by running query using queryUserDefinedFunctions.
Example:
List<UserDefinedFunction> udfs = client.queryUserDefinedFunctions(
myCollection.getSelfLink(),
new SqlQuerySpec("SELECT * FROM root r WHERE r.id=#id",
new SqlParameterCollection(new SqlParameter("#id", myUdfId))),
null).getQueryIterable().toList();
if (udfs.size() > 0) {
// Found UDF.
}
An answer for .NET users.
`var collectionAltLink = documentCollections["myCollection"].AltLink; // Target collection's AltLink
var udfLink = $"{collectionAltLink}/udfs/{sampleUdfId}"; // sampleUdfId is your UDF Id
var result = await _client.ReadUserDefinedFunctionAsync(udfLink);
var resource = result.Resource;
if (resource != null)
{
// The UDF with udfId exists
}`
Here _client is Azure's DocumentClient and documentCollections is a dictionary of your documentDb collections.
If there's no such UDF in the mentioned collection, the _client throws a NotFound exception.

how to retrieve orders from ordertools component in atg or how to test orderlookup droplet api

iam trying to orderlookup droplet API by passing some parameters.I assume that the parameters which are mandatory is userId and organisationIds which i have passed and additionally i have also passed "state" parameter.All these params are passed thru request and then the service method of droplet is invoked.But the service method returns nothing.My goal is to check whether this droplet this retrieving the expected set of orders or not.We can use droplet invoker but i tried that way but it didnt work may be i missed something.Please help me out!!
this is my code when i tried to use OrderLookUp API
DynamoHttpServletRequest request = ServletUtil.getCurrentRequest();
mTestService.setCurrentRequest(request);
if (request == null) {
mTestService.vlogError("Request is null.");
Assert.fail("Request is null ");
}
else
{
Object droplet = mTestService
.getRequestScopedComponent("OrderLookupDroplet");
OrderLookupDroplet=(OrderLookup) droplet;
request.setParameter("state", "submitted");
request.setParameter("organisationIds", organizationIds);
request.setParameter("userId", userId);
ByteBuffer buffer = ByteBuffer.allocate(1024);
DynamoHttpServletRequest dynRequest = (DynamoHttpServletRequest) request;
TestingDynamoHttpServletRequest wrappedRequest = new TestingDynamoHttpServletRequest(
dynRequest, buffer);
TestingDynamoHttpServletResponse wrappedResponce = new TestingDynamoHttpServletResponse(
dynRequest.getResponse());
OrderLookupDroplet.service(wrappedRequest, wrappedResponce);
}
the above sample is only part of the code..
this is the code when i tried using droplet invoker
DropletInvoker invoker = new DropletInvoker(mNucleus);
invoker.getRequest().setParameter("state", "submitted");
// String [] siteIds = {"siteA", "siteB"};
// invoker.getRequest().setParameter("siteIds", Arrays.asList(siteIds));
String [] organizationIds = {"OrgA", "OrgB"};
invoker.getRequest().setParameter("organizationIds", organizationIds);
String [] orderIds = {"orderautouser001OrgA" , "orderautouser001OrgB"};
invokeDroplet(invoker, "autouser001", orderIds);
......
protected void invokeDroplet(DropletInvoker pInvoker, String pUserId, String[] pOrderIds) throws Exception
{
Map<String, Object> localParams = new HashMap();
localParams.put("userId", pUserId);
DropletResult result = pInvoker.invokeDroplet("/atg/commerce/order/OrderLookup", localParams);
RenderedOutputParameter oparam = result.getRenderedOutputParameter("output", 0);
assertNotNull("'output' oparam was not rendered", oparam);
assertEquals("Check totalCount.", pOrderIds.length, oparam.getFrameParameter("totalCount"));
List<Order> orders = (List<Order>)oparam.getFrameParameter("result");
assertEquals("Check order array length.", pOrderIds.length, orders.size());
for (int index = 0; index < pOrderIds.length; index++) {
boolean found = false;
for (Order order: orders) {
if (pOrderIds[index].equals(order.getId())) {
found = true;
break;
}
}
assertTrue("Expected orderId " + pOrderIds[index] + " not found in result array", found);
}
in first case i donno how to retrieve the orders by directly using orderlookup api....and in second case though i know how to use it ,iam still failing!! please help me out..thanks in advance
You should't use droplets in java classes they should be used only inside jsp pages. Documentation of OrderLookup with example hot to use it on jsp page is here.
If you want to get orders or any other data stored in a repository you should use repository API with RQL (Repository Query Language). Example how to get data from repository you can find here and RQL grammar here.
Thanks for giving your opinions.Good news is we can invoke droplets from any other API
OrderLookup droplet = (OrderLookup) sNucleus.resolveName("/atg/commerce/order/OrderLookup");
ServletTestUtils utils = new ServletTestUtils();
mRequest = utils.createDynamoHttpServletRequestForSession(sNucleus, null, null);
ServletUtil.setCurrentRequest(mRequest);
mResponse = new DynamoHttpServletResponse();
mRequest.setResponse(mResponse);
mResponse.setRequest(mRequest);
mResponse.setResponse(new GenericHttpServletResponse());
mRequest.setParameter("userId", "publishing");
droplet.setSearchByUserId(true);
droplet.service(mRequest, mResponse);
ArrayList<Order> orders = (ArrayList<Order>) mRequest.getObjectParameter("result");
here the "result" param is output param which this droplet sets.and the userId i have hardcoded as "publishing" which i have created.Ignore servletTestUtils class that is created by me which has not much to do with droplet theory here :)
I assume from your code example, and the fact that you mention DropletInvoker that you are writing a unit test, and that this is not functional code.
If it is functional code, you really, really, should not invoke a droplet from another Nucleus component. A droplet exists solely to be used in a JSP page. If you need the functionality of the droplet in Java code, you should refactor the droplet into a service that holds the main logic, and a droplet that simply acts as a façade to the service to allow it to be invoked from a page.
In the case of the OrderLookup look droplet, you don't need to refactor anything. The service to use should be OrderManager or OrderTools depending on what you need. Note, there is a difference between Order objects and Order repository items, and you should prefer to use order objects - so only use the Order Repository directly if you really need to.

How do I save a value into a custom field in JIRA programmatically?

I've spent days trying to find out how to save or update a value into a CustomField programmatically and finally found out how it's done. So I'll make this a question and then answer it as I would have loved to have this question and answer.
There is conflicting documentation on how to save or update a value for a Custom Field in JIRA. I was using:
customField.setCustomFieldValue(CustomField, value);
This does not save the value into the database but it does update the value as far as I can tell. It's only useful if you are using the CustomField further down in a Workflow Post Function transition for example.
I'm using Jira 4.3.2.
How do I persist the the CustomFields value into the JIRA database?
Ok, this is how I'm successfully updating and saving the CustomField value into the JIRA db.
Comments welcome...
private void saveValue(MutableIssue issue, String valueToSave, CustomField
customField) throws FieldLayoutStorageException {
issue.setCustomFieldValue(customField, valueToSave);
Map<String, ModifiedValue> modifiedFields = issue.getModifiedFields();
FieldLayoutItem fieldLayoutItem =
ComponentManager.getInstance().getFieldLayoutManager().getFieldLayout(issue).getFieldLayoutItem(
customField);
DefaultIssueChangeHolder issueChangeHolder = new DefaultIssueChangeHolder();
final ModifiedValue modifiedValue = (ModifiedValue) modifiedFields.get(customField.getId());
customField.updateValue(fieldLayoutItem, issue, modifiedValue, issueChangeHolder);
}
Here is how I do it (for a custom field I programmatically store a random UUID in):
CustomField cfHash = customFieldManager.getCustomFieldObjectByName(...);
IssueChangeHolder changeHolder = new DefaultIssueChangeHolder();
try {
Object newHashValue = java.util.UUID.randomUUID().toString();
Object oldHashValue = issue.getCustomFieldValue(cfHash);
issue.setCustomFieldValue(cfHash, newHashValue);
cfHash.updateValue(null, issue, new ModifiedValue(oldHashValue, newHashValue), changeHolder);
...
More or less the same as you but with another way to get the ModifiedValue-Object.
Here a solution that works for me in JIRA 6.4.7 to update a custom field value. Actually Im updating a single select field, therefore I have to get the Option for it:
MutableIssue issue = issueManager.getIssueByCurrentKey(issueKey);
FieldConfig relevantConfig = customField.getRelevantConfig(issue);
// if you use a text field use String. or double for numeric
Option optionForValue = optionsManager.getOptions(relevantConfig).getOptionForValue(option, null);
issue.setCustomFieldValue(customField,optionForValue);
Map<String, ModifiedValue> modifiedFields = issue.getModifiedFields();
FieldLayoutItem fieldLayoutItem =
fieldLayoutManager.getFieldLayout(issue).getFieldLayoutItem(customField);
DefaultIssueChangeHolder issueChangeHolder = new DefaultIssueChangeHolder();
final ModifiedValue modifiedValue = modifiedFields.get(customField.getId());
customField.updateValue(fieldLayoutItem, issue, modifiedValue, issueChangeHolder);
I had the same issue and had it resolved using this plugin, fyi=)

Categories

Resources