Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE in AWS SNS - java

I am trying to send sms via Amazon Web service . I have downloaded the sd
package com.sms;
import java.util.HashMap;
import java.util.Map;
import com.sms.AwsClientFactoryDemo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.services.sns.model.MessageAttributeValue;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
public class SmsNotificationService {
private static final Logger LOG = LoggerFactory.getLogger(SmsNotificationService.class);
public PublishResult send(String phoneNumber, String message) {
Map<String, MessageAttributeValue> smsAttributes = new HashMap<String, MessageAttributeValue>();
smsAttributes.put("AWS.SNS.SMS.SenderID", new MessageAttributeValue()
.withStringValue("Lightside") //The sender ID shown on the device (except in US)
.withDataType("String"));
smsAttributes.put("AWS.SNS.SMS.MaxPrice", new MessageAttributeValue()
.withStringValue("0.01") //Sets the max price to 0.01 USD.
.withDataType("Number"));
smsAttributes.put("AWS.SNS.SMS.SMSType", new MessageAttributeValue()
.withStringValue("Promotional") //Sets the type to promotional.
.withDataType("String"));
PublishResult result = AwsClientFactoryDemo.getSnsClient().publish(new PublishRequest()
.withMessage(message)
.withPhoneNumber(phoneNumber)
.withMessageAttributes(smsAttributes));
LOG.info("Sent SMS message ID: " + result.getMessageId());
return result;
}
}
I am getting following error in the above code while trying to send sms via aws sns.
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:144)
at com.amazonaws.http.apache.client.impl.ApacheConnectionManagerFactory.getPreferredSocketFactory(ApacheConnectionManagerFactory.java:87)
at com.amazonaws.http.apache.client.impl.ApacheConnectionManagerFactory.create(ApacheConnectionManagerFactory.java:65)
at com.amazonaws.http.apache.client.impl.ApacheConnectionManagerFactory.create(ApacheConnectionManagerFactory.java:58)
at com.amazonaws.http.apache.client.impl.ApacheHttpClientFactory.create(ApacheHttpClientFactory.java:51)
at com.amazonaws.http.apache.client.impl.ApacheHttpClientFactory.create(ApacheHttpClientFactory.java:39)
at com.amazonaws.http.AmazonHttpClient.<init>(AmazonHttpClient.java:300)
at com.amazonaws.AmazonWebServiceClient.<init>(AmazonWebServiceClient.java:164)
at com.amazonaws.AmazonWebServiceClient.<init>(AmazonWebServiceClient.java:153)
at com.amazonaws.services.sns.AmazonSNSClient.<init>(AmazonSNSClient.java:207)
at com.amazonaws.services.sns.AmazonSNSClient.<init>(AmazonSNSClient.java:187)
at com.amazonaws.services.sns.AmazonSNSClient.<init>(AmazonSNSClient.java:97)
at com.sms.sms.main(sms.java:13)

This is likely caused by different versions of the HTTP client dependency on the classpath. (Reference1, Reference2) Make sure you only have one version on the classpath.

Related

Having Issue with error refreshing access token

Hi I am trying to connect to Big Query and I am using a google service account with a JSON key. I am getting the below error. This is in my java batch program.
Insert operation not performed
com.google.cloud.bigquery.BigQueryException: Unexpected error refreshing access token
This fixed my issue. more here https://cloud.google.com/bigquery/docs/authorization
import com.google.auth.Credentials;
import com.google.auth.oauth2.ServiceAccountJwtAccessCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import java.io.FileInputStream;
import java.net.URI;
public class Example {
public static void main(String... args) throws Exception {
String projectId = "myproject";
// Load JSON file that contains service account keys and create ServiceAccountJwtAccessCredentials object.
String credentialsPath = "/path/to/key.json";
URI audience = URI.create("https://bigquery.googleapis.com/");
Credentials credentials = null;
try (FileInputStream is = new FileInputStream(credentialsPath)) {
credentials = ServiceAccountJwtAccessCredentials.fromStream(is, audience);
}
// Instantiate BigQuery client with the credentials object.
BigQuery bigquery =
BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();
// Use the client to list BigQuery datasets.
System.out.println("Datasets:");
bigquery
.listDatasets(projectId)
.iterateAll()
.forEach(dataset -> System.out.printf("%s%n", dataset.getDatasetId().getDataset()));
}
}

Why is withRegion() of AmazonSNSClientBuilder not visible?

I am writing code to create an Amazon Web Services SNS client in Eclipse, when I get an error saying
The method withRegion(Region) from the type
AwsClientBuilder is not visible
Here is my code
package com.amazonaws.samples;
import java.util.Date;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.AnonymousAWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.CreateTopicResult;
import com.amazonaws.services.sns.model.PublishRequest;
// Example SNS Sender
public class Main {
// AWS credentials -- replace with your credentials
static String ACCESS_KEY = "<Your AWS Access Key>";
static String SECRET_KEY = "<Your AWS Secret Key>";
// Sender loop
public static void main(String... args) throws Exception {
// Create a client
AWSCredentials awsCred = new AnonymousAWSCredentials();
AWSStaticCredentialsProvider cred = new AWSStaticCredentialsProvider(awsCred);
Region region = Region.getRegion(Regions.US_EAST_1);
AmazonSNS service = AmazonSNSClientBuilder.standard().withRegion(region).withCredentials(cred).build(); // Error message: The method withRegion(Region) from the type AwsClientBuilder<AmazonSNSClientBuilder,AmazonSNS> is not visible
// Create a topic
CreateTopicRequest createReq = new CreateTopicRequest()
.withName("MyTopic3");
CreateTopicResult createRes = service.createTopic(createReq);
for (;;) {
// Publish to a topic
PublishRequest publishReq = new PublishRequest()
.withTopicArn(createRes.getTopicArn())
.withMessage("Example notification sent at " + new Date());
service.publish(publishReq);
Thread.sleep(1000);
}
}
}
In the screenshot it shows where the error occurs with the red underline in dotted line:
What should I check to correct this?
You are passing the wrong parameter, withRegion takes either a String or a Regions (note, not Region, singular).
Try passing Regions.EU_WEST_1.
Both AmazonSNSClientBuilder.standard().withRegion(Regions.EU_WEST_1).build();
and AmazonSNSClientBuilder.standard().withRegion("eu-west-1").build();
are working fine for me.

AWS Java SDK STS in Lambda timeout

I want to get temporary credentials via AWS Security Token Service in Lambda, but it is timeout at AWSSecurityTokenServiceClientBuilder.standard().build() all the time.
Does anyone help me?
Source Code:
package example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;
import com.amazonaws.services.securitytoken.model.AssumeRoleRequest;
import com.amazonaws.services.securitytoken.model.AssumeRoleResult;
public class SecurityTokenService implements RequestHandler<Request, Credential> {
public Credential handleRequest(Request request, Context context) {
AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
.withPolicy("arn:aws:iam::12345678900:policy/SomePolicy")
.withDurationSeconds(900);
AWSSecurityTokenService securityTokenService = AWSSecurityTokenServiceClientBuilder.standard().build();
AssumeRoleResult assumeRoleResult = securityTokenService.assumeRole(assumeRoleRequest);
return new Credential(assumeRoleResult.getCredentials());
}
}
Error Message:
{
"errorMessage": "2018-02-22T09:12:55.102Z 8f49ee0a-17b0-11e8-892f-753d21bb516c Task timed out after 3.00 seconds"
}
I had the same problem with default memory settings of 128 MB. After increasing memory to 512 MB it works now.

Error Remote Rest API Client jBPM 6.3

I've created remote REST API client but I've got an error whereas it ran properly on jBPM console but REST having problem like this
[main] ERROR org.kie.services.client.api.command.AbstractRemoteCommandObject - Response with status 200 returned.
Exception in thread "main" org.kie.remote.client.api.exception.RemoteApiException: WorkflowRuntimeException thrown with message '[Transport.Performance:207 - :5] -- Exception when trying to evaluate constraint in split ':
org.kie.remote.services.rest.exception.KieRemoteRestOperationException: [Transport.Performance:207 - :5] -- Exception when trying to evaluate constraint in split
this is my code
package org.transportclient;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jbpm.workflow.instance.WorkflowRuntimeException;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.task.TaskService;
import org.kie.api.task.model.TaskSummary;
import org.kie.remote.client.api.RemoteRuntimeEngineFactory;
import org.kie.services.client.api.command.RemoteRuntimeException;
import org.kie.services.client.api.command.exception.RemoteApiException;
public class TransportRest {
public static void main(String[] args) throws MalformedURLException {
RuntimeEngine engine = RemoteRuntimeEngineFactory.newRestBuilder()
.addUrl(new URL("http://localhost:8080/jbpm-console"))
.addUserName("krisv").addPassword("krisv")
.addDeploymentId("RnD:transport:1.5.1")
.build();
KieSession ksession = engine.getKieSession();
//TaskService taskService = engine.getTaskService();
// start a new process instance
Map<String, Object> params = new HashMap<String, Object>();
params.put("entry_date", "04-22-2016 00:00:00");
params.put("ne_id", "NY");
params.put("ping_time","900");
System.out.println(params);
ProcessInstance processInstance = ksession.startProcess("Transport.Performance", params);
System.out.println(processInstance.getParentProcessInstanceId());
System.out.println("Start Performance process " + processInstance.getId());
}
}
Anyone can help ?
Thank you
I have never seen that error, but I had problems with jBPM REST API a few weeks ago when I upgraded jBPM version from 6.2 to 6.3. I solved it adding "rest-all" role to all users who need to use REST API (like "krisv" in your case"). Could you try this?
Regards.

Troubleshoot UnknownResourceException when following AWS tutorial

I'm attempting to follow this AWS tutorial. But I'm having trouble at "You can run GreeterWorker successfully at this point." as I'm getting an UnknownResourceException.
Exception in thread "main" com.amazonaws.services.simpleworkflow.model.UnknownResourceException: Unknown domain: helloWorldWalkthrough (Service: AmazonSimpleWorkflow; Status Code: 400; Error Code: UnknownResourceFault; Request ID: xxxxx)
Steps taken
Resolved permission exception by attaching the SimpleWorkflowFullAccess IAM Policy to my AWS user.
Verified that the helloWorldWalkthrough is registered on the SWF dashboard
registered new helloWorldWalkthrough2 domain, same error occured
The tutorial didn't cover the step about attaching the SimpleWorkflowFullAccess policy to the AWS user, so I'm wondering if there is a similar undocumented step to allow my user to find this domain.
My code is copy/pasted from the GreeterWorker class in the tutorial.
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflowClient;
import com.amazonaws.services.simpleworkflow.flow.ActivityWorker;
import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker;
public class GreeterWorker {
public static void main(String[] args) throws Exception {
ClientConfiguration config = new ClientConfiguration().withSocketTimeout(70*1000);
String swfAccessId = System.getenv("AWS_ACCESS_KEY_ID");
String swfSecretKey = System.getenv("AWS_SECRET_KEY");
AWSCredentials awsCredentials = new BasicAWSCredentials(swfAccessId, swfSecretKey);
AmazonSimpleWorkflow service = new AmazonSimpleWorkflowClient(awsCredentials, config);
service.setEndpoint("https://swf.us-east-1.amazonaws.com");
String domain = "helloWorldWalkthrough";
String taskListToPoll = "HelloWorldList";
ActivityWorker aw = new ActivityWorker(service, domain, taskListToPoll);
aw.addActivitiesImplementation(new GreeterActivitiesImpl());
aw.start();
WorkflowWorker wfw = new WorkflowWorker(service, domain, taskListToPoll);
wfw.addWorkflowImplementationType(GreeterWorkflowImpl.class);
wfw.start();
}
}
You need to create the domain using the console or through an api call. Domain is not created automatically.
I was also facing the same issue and then I found that the region is hard coded in the main method inside GreeterWorker class as shown below:
service.setEndpoint("https://swf.us-east-1.amazonaws.com");
However my SWF account was in west-2 region.
I was also faving same problem. region is hard coded in tutorial.
I changed code as flllows
service.setEndpoint("https://swf.us-west-2.amazonaws.com");

Categories

Resources