AWS Connect API - StartTaskContact operation: InvalidRequestException: - task

I have tried the new AWS Connect API and have cut down the parameters to the minimum required but I still get the Invalid Exception and now at a loss. So any help welcome, I am sure it is obvious.
I am running the latest version of boto3 1.16.30
import boto3
client = boto3.client('connect')
aws_instance = "arn:aws:connect:eu-west-2:xxxxxxx:instance/341e64ab-de99-4f3f-b8c4-f068d2a4284c"
def CreateTask():
# Obtain data from AWS Connect
try:
response = client.start_task_contact(
InstanceId = 'arn:aws:connect:eu-west-2:xxxxx:instance/341e64ab-de99-4f3f-b8c4-f068d2a4284c',
ContactFlowId = 'c7f9557a-f8a3-4858-8187-fb3871787725',
Name = 'Account Refer',
Description = "Task referal",
Attributes={
'Account': 'AB100'
},
References={
'string': {
'Value': 'www.bbc.co.uk',
'Type': 'URL'
}
}
)
print(response)
except client.exceptions.InvalidRequestException as Ex:
print("Invalid Exception::", Ex)
except client.exceptions.InvalidRequestException as Ex:
print("Invalid Request Exception", Ex)
except client.exceptions.InvalidParameterException as Ex:
print("Invalid Exception", Ex)
except client.exceptions.ResourceNotFoundException as Ex:
print("Resource Not Found Exception", Ex)
except client.exceptions.ThrottlingException as Ex:
print("Throttling Exception", Ex)
except client.exceptions.ServiceQuotaExceededException as Ex:
print("Service Quota Exceeded Exception", Ex)
except client.exceptions.InternalServiceException as Ex:
print("Internak Service Exception", Ex)
if name == 'main':
CreateTask()

The issue was using the ARN for the instance instead of the instance id, so beware there are some inconsistency with use of ARN/ID

Related

WebClientReactiveJwtBearerTokenResponseClient failing to parse successful response

I am assuming that its because of the specified body extractor, just wondering what part of the response is incorrect or if there is a different token response class.
var client = new WebClientReactiveJwtBearerTokenResponseClient();
client.setBodyExtractor(BodyExtractors.toMono(OAuth2AccessTokenResponse.class));
...
LOG.info("Response: {}", client
.getTokenResponse(request)
.onErrorMap(e -> {
LOG.error("Error is {}", e.getMessage());
return e;}
)
.block());
It fails with
Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.security.oauth2.core.OAuth2AccessToken.getScopes()" because the return value of "org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse.getAccessToken()" is null
at org.springframework.security.oauth2.client.endpoint.AbstractWebClientReactiveOAuth2AccessTokenResponseClient.populateTokenResponse(AbstractWebClientReactiveOAuth2AccessTokenResponseClient.java:240) ~[spring-security-oauth2-client-5.7.6.jar:5.7.6]
at org.springframework.security.oauth2.client.endpoint.AbstractWebClientReactiveOAuth2AccessTokenResponseClient.lambda$readTokenResponse$3(AbstractWebClientReactiveOAuth2AccessTokenResponseClient.java:228) ~[spring-security-oauth2-client-5.7.6.jar:5.7.6]
but, the access token is in the response which looks like
{
"access_token":"00D8K0000004cbe!AQgAQGO6yn3qEnI_QJJTsQHT5SyYt75M_o0QW9YdKDoj4L_r3wQir3P4zkCFal.I0oeNciySYsw52VazmZV_5LVy",
"scope":"api full",
"instance_url":"https://example.org",
"id":"00D8K0000004cbeUAA/0055f000008GSREAA4",
"token_type":"Bearer"
}

Connecting to Neo4j Aura with .NET Core 2.2 web api

I am trying to connect a to Neo4j Aura instance from a .NET core 2.2 web api. I understand I need the Neo4j .Net Driver v4.0.0-alpha01, but I do not seem to be able to connect. There aren't very many examples out there as this driver is new and so is Aura.
I keep getting:
Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again.
I configure the driver as such
public void ConfigureServices(IServiceCollection services)
{
string uri = "neo4j://1234567.databases.neo4j.io:7687";//not actual subdomain
string username = "neo4j";
string password = "seeeeeeecret";//not actual password
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password)));
}
and in my test controller i run this
private async Task<string> Neo4JTestAsync()
{
string db = "MyDb";
string message = "TESTMESSAGE";
IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(db));
try
{
var greeting = session.WriteTransactionAsync(async tx =>
{
var result = tx.RunAsync("CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
new { message });
var res = await result;
return "return something eventually";
});
return await greeting;
}
catch (Exception e)
{
return e.Message; // throws "Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again"
}
finally
{
await session.CloseAsync();
}
}
I can't get the exact error message you do - but I'm pretty sure this is due to encryption - one of the big differences between the 1.x and 4.x drivers is the default position on Encryption - which is now off by default.
So you'll want to change your initialisation to:
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password), config => config.WithEncryptionLevel(EncryptionLevel.Encrypted)));
That should get you going. Also - make sure you stick with the neo4j:// protocol, as that'll route you properly.
Have you tried bolt:// in the connection string?
string uri = "bolt://1234567.databases.neo4j.io:7687";//not actual subdomain

Invoking getQueueUrl() on FIFO Queue with SSE Enabled Results in 403 / All requests to this queue must use HTTPS and SigV4

I am using a SQS FIFO queue with SSE enabled. When I use a SQS client to call getQueueUrl(), an exception is thrown with the message All requests to this queue must use HTTPS and SigV4.
Using the latest version of the aws-java-sdk:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.160</version>
</dependency>
The following code reproduces the issue:
public class SimpleSqsClient {
private static ClientConfiguration clientConfiguration() {
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("proxy.foo.com");
clientConfiguration.setProxyPort(8099);
clientConfiguration.setProxyUsername("username");
clientConfiguration.setProxyPassword("password");
clientConfiguration.setProtocol(Protocol.HTTP);
clientConfiguration.setPreemptiveBasicProxyAuth(false);
return clientConfiguration;
}
public static void main(String[] args) throws Exception {
/*
* The ProfileCredentialsProvider will return your [default] credential
* profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
+ "Please make sure that your credentials file is at the correct "
+ "location (~/.aws/credentials), and is in valid format.", e);
}
AmazonSQS sqs = AmazonSQSClientBuilder.standard().withClientConfiguration(clientConfiguration())
.withCredentials(new ProfileCredentialsProvider("SOME_PROFILE"))
.withRegion(Regions.US_EAST_1).build();
System.out.println("===========================================");
System.out.println("Simple SQS Test");
System.out.println("===========================================\n");
try {
System.out.println(sqs.getQueueUrl("some-sse-enabled-queue.fifo"));
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it "
+ "to Amazon SQS, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with SQS, such as not "
+ "being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
}
Output:
Caught an AmazonServiceException, which means your request made it to Amazon SQS, but was rejected with an error response for some reason.
Error Message: All requests to this queue must use HTTPS and SigV4. (Service: AmazonSQS; Status Code: 403; Error Code: InvalidSecurity; Request ID: ...)
HTTP Status Code: 403
AWS Error Code: InvalidSecurity
Error Type: Client
Request ID: ...
Changing
clientConfiguration.setProtocol(Protocol.HTTP);
to
clientConfiguration.setProtocol(Protocol.HTTPS);
Resolved the issue

.Net Quartz Scheduler 2.3 does not work on the remote server

I am working on a windows service that works on my development machine, but when I deploy to a test server I find that the Quartz Scheduler I have set up does not work.
There are no exceptions thrown or any clues as to why this is.
Here is my code;
protected override void OnStart(string[] args)
{
try
{
this.SetDailySchedule();
}
catch (SchedulerException ex)
{
this.eventLog.WriteEntry("WMS FM Loader: Schedule Error - " + ex.Message);
throw ex;
}
catch (Exception ex)
{
this.eventLog.WriteEntry("WMS FM Loader: Unexpected Error - " + ex.Message);
throw ex;
}
}
private void SetDailySchedule()
{
this.eventLog.WriteEntry("On Start".Log());
var schedule = this.GetSchedule();
try
{
this.schedFact = new StdSchedulerFactory();
this.sched = this.schedFact.GetScheduler();
}
catch (Exception ex)
{
this.eventLog.WriteEntry(ex.Message.Log());
throw;
}
this.eventLog.WriteEntry(string.Format("Got a scheduler: {0}", schedule).Log());
try
{
ScheduleTheLoad(schedule);
}
catch (Exception ex)
{
this.eventLog.WriteEntry(ex.Message.Log());
throw;
}
this.eventLog.WriteEntry("WMS FM Loader: Scheduler ready");
}
private void ScheduleTheLoad(string schedule)
{
var job = JobBuilder.Create<LoadWorksOrders>().WithIdentity("LoadWorksOrdersJob").Build();
// Trigger the job to run now, and then every day
var trigger =
TriggerBuilder.Create()
.ForJob(job)
.WithIdentity("LoadWorksOrdersTrigger")
.StartNow()
.WithCronSchedule(schedule)
.Build();
this.sched.ScheduleJob(job, trigger);
this.sched.Start();
}
I manually start the service and the event log shows that the scheduler is ready, but LoadWorksOrdersJob doe snot get run.
How should I fix this?
Are you running the two methods in the windows service OnStart? Are you using a service account? Any exceptions in the event viewer/ have you started /stopped the service from services.msc?
I also had this problem. It took me a day to work it out.
For me it was that my assembly had dots/periods in its name. e.g.
Project.UpdateService
When I changed it to...
ProjectUpdateService
... it worked fine. It always worked on the development machine. It just would not work on the remote machine.
UPDATE: It may have been the length of the service that has caused this issue. By removing the dots I shortened the service name. It looks like the maximum length is 25 characters.

Cant connect to survey monkey API

I am trying to connect to the survey monekey API with this code, which is not working. It says "Invalid API key" even though I got the API from the API console.
public void fetch() {
String url = "https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=" + apiKey;
System.out.println("request being sent");
System.out.println(url);
JSONObject obj = new JSONObject();
try {
// byte[] postDataBytes = obj.toJSONString().getBytes("UTF-8");
URL ourl = new URL(url.toString());
HttpURLConnection conn = (HttpURLConnection) ourl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "bearer " + accessToken);
conn.setRequestProperty("Content-Type", "application/json");
conn.getRequestProperty(obj.toString().getBytes("UTF-8").toString());
int k = conn.getResponseCode();
System.out.println("The response code received is " + k);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
output = br.readLine();
System.out.println(output);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here's the error:
request being sent
https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=---API-KEY----
The response code received is 200
Output from Server ....
{"status":3,"errmsg":"Expected object or value"}
I just got this url from the API console.
Ensure you are using the API key associated with your developer account registered at http://developer.surveymonkey.com, not the sample API key the console uses to let you try requests. The sample api key is not meant to be used with apps, only on the API console.
That particular error is generated when an empty string is sent for the POST data. The API expects an empty object at minimum ("{}"). If the issue pointed out by Miles above was just a typo (using 'getRequestProperty' instead of 'setRequestProperty',) check if toString on an empty JSONObject is returning "" or "{}".

Resources