I am using Java.
I have an aws user (sts client) on which I do an "assume role" before trying to call cognito "list users".
The assume role seem to be working fine. However, the "list users" is throwing an error ("The security token included in the request is invalid") and I don't know why. Here is the full error trace:
software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException: The security token included in the request is invalid. (Service: CognitoIdentityProvider, Status Code: 400, Request ID: XXX-XXX-XXX)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleErrorResponse(CombinedResponseHandler.java:125)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handleResponse(CombinedResponseHandler.java:82)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handle(CombinedResponseHandler.java:60)
at software.amazon.awssdk.core.internal.http.CombinedResponseHandler.handle(CombinedResponseHandler.java:41)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:40)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:30)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:73)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:78)
at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:40)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptMetricCollectionStage.execute(ApiCallAttemptMetricCollectionStage.java:50)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptMetricCollectionStage.execute(ApiCallAttemptMetricCollectionStage.java:36)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage.execute(RetryableStage.java:81)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage.execute(RetryableStage.java:36)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.StreamManagingStage.execute(StreamManagingStage.java:56)
at software.amazon.awssdk.core.internal.http.StreamManagingStage.execute(StreamManagingStage.java:36)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.executeWithTimer(ApiCallTimeoutTrackingStage.java:80)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.execute(ApiCallTimeoutTrackingStage.java:60)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.execute(ApiCallTimeoutTrackingStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallMetricCollectionStage.execute(ApiCallMetricCollectionStage.java:48)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallMetricCollectionStage.execute(ApiCallMetricCollectionStage.java:31)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ExecutionFailureExceptionReportingStage.execute(ExecutionFailureExceptionReportingStage.java:37)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ExecutionFailureExceptionReportingStage.execute(ExecutionFailureExceptionReportingStage.java:26)
at software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient$RequestExecutionBuilderImpl.execute(AmazonSyncHttpClient.java:193)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.invoke(BaseSyncClientHandler.java:103)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.doExecute(BaseSyncClientHandler.java:167)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.lambda$execute$1(BaseSyncClientHandler.java:82)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.measureApiCallSuccess(BaseSyncClientHandler.java:175)
at software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler.execute(BaseSyncClientHandler.java:76)
at software.amazon.awssdk.core.client.handler.SdkSyncClientHandler.execute(SdkSyncClientHandler.java:45)
at software.amazon.awssdk.awscore.client.handler.AwsSyncClientHandler.execute(AwsSyncClientHandler.java:56)
at software.amazon.awssdk.services.cognitoidentityprovider.DefaultCognitoIdentityProviderClient.listUsers(DefaultCognitoIdentityProviderClient.java:6504)
at EC.RunAWSCall.listUsersFilter(RunAWSCall.java:107)
at EC.RunAWSCall.changingUserMDP(RunAWSCall.java:62)
Here is my code in Java:
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.model.*;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.StsException;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
public class myClass{
public static void myMainFunction(String role, String envRole, String userPoolId, String clientEmail){
String roleArn = "arn:aws:iam::"+envRole+":role/"+role;
String roleSessionName = "AssumeRoleSession1";
Region region = Region.EU_WEST_1;
StsClient stsClient = StsClient.builder()
.region(region)
.credentialsProvider(ProfileCredentialsProvider.create())
.build();
Credentials myCreds = assumeGivenRole(stsClient, roleArn, roleSessionName);
AwsBasicCredentials awsCreds = AwsBasicCredentials.create(myCreds.accessKeyId(), myCreds.secretAccessKey());
CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
.region(region)
.credentialsProvider(StaticCredentialsProvider.create(awsCreds))
.build();
String username = listUsersFilter(cognitoClient, userPoolId, clientEmail);
}
public static Credentials assumeGivenRole(StsClient stsClient, String roleArn, String roleSessionName) {
AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
.roleArn(roleArn)
.roleSessionName(roleSessionName)
.build();
AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
Credentials myCreds = roleResponse.credentials();
return myCreds;
}
// Shows how to list users by using a filter.
public static String listUsersFilter(CognitoIdentityProviderClient cognitoClient, String userPoolId, String email) {
String filter = "email = \""+email+"\"";
ListUsersRequest usersRequest = ListUsersRequest.builder()
.userPoolId(userPoolId)
.filter(filter)
.build();
ListUsersResponse response = cognitoClient.listUsers(usersRequest);
response.users().forEach(user -> {
System.out.println("User with filter applied " + user.username() + " Status " + user.userStatus() + " Created " + user.userCreateDate() );
});
return response.users().get(0).username();
}
I don't know why my code isn't working. Especially since I have the exact same code in Python where it's working just fine (though in Python, I explicitly give the sessionToken to cognito, but it doesn't seem to be possible in Java?).
Any idea on what I'm doing wrong?
For comparison, here is the same code in Python which is working:
sts = boto3.client('sts')
assumed_role_object=sts.assume_role(
RoleArn="arn:aws:iam::"+env_role+":role/"+role,
RoleSessionName="AssumeRoleSession1"
)
credentials=assumed_role_object['Credentials']
cognito=boto3.client(
'cognito-idp',
region_name="eu-west-1",
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken'],
)
getUser = cognito.list_users(
UserPoolId=userPoolId,
AttributesToGet=[],
Limit=10,
Filter='email="'+email+'"'
)
It turns out, explicitly giving the sessionToken is also possible in Java. All I need to do is use AwsSessionCredentials instead of AwsBasicCredentials. (Many thanks to the person who answered my question on the aws forum.)
Related
i'm trying to integrate the google login function on my website and i'm following the relative google doc for the server side token validation: https://developers.google.com/identity/gsi/web/guides/verify-google-id-token?hl=en .
i've created a simple test app with the GoogleIdTokenVerifier declaration but i'm getting the error:
java.lang.NoClassDefFoundError: com/google/api/client/json/JsonFactory
what am I doing wrong?
Thanks.
this is the test app with the GoogleIdTokenVerifier declaration:
package test;
import java.util.Collections;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
public class Main {
public static void main(String[] args) {
try {
HttpTransport transport = new NetHttpTransport();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, new GsonFactory())
// Specify the CLIENT_ID of the app that accesses the backend:
.setAudience(Collections.singletonList("xxx.apps.googleusercontent.com"))
// Or, if multiple clients access the backend:
//.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
.build();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and this is the pom.xml i used for the dependencies:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
<dependencies>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>2.1.3</version>
</dependency>
</dependencies>
</project>
There is a sample for this on the Verify the Google ID token on your server side documentation page
You apear to be using an old sample i dont think they use GsonFactory anymore with the java library it was removed.
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
...
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
// Specify the CLIENT_ID of the app that accesses the backend:
.setAudience(Collections.singletonList(CLIENT_ID))
// Or, if multiple clients access the backend:
//.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
.build();
// (Receive idTokenString by HTTPS POST)
GoogleIdToken idToken = verifier.verify(idTokenString);
if (idToken != null) {
Payload payload = idToken.getPayload();
// Print user identifier
String userId = payload.getSubject();
System.out.println("User ID: " + userId);
// Get profile information from payload
String email = payload.getEmail();
boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
String locale = (String) payload.get("locale");
String familyName = (String) payload.get("family_name");
String givenName = (String) payload.get("given_name");
// Use or store profile information
// ...
} else {
System.out.println("Invalid ID token.");
}
I want to read and send email using Microsoft Graph API. I have tried using DeviceCodeCredentials and it is working fine but I want to read emails without any user interaction in the backend. By Using, DeviceCodeCredentials it asks me to login using my email id and enter the code provided.
below I the code I have written with ClientSecretCredentials which give me below error.
Exception in thread "main" java.lang.RuntimeException: Unable to get access token
at com.eclerx.email.AccessProvider.accessToken(AccessProvider.java:30)
at com.eclerx.email.AuthenticationBuilder2.main(AuthenticationBuilder2.java:55)
Caused by: java.util.concurrent.ExecutionException:
com.microsoft.aad.msal4j.MsalServiceException: AADSTS1002012: The provided value for scope
User.read openid profile offline_access Mail.Read is not valid. Client credential flows must
have a scope value with /.default suffixed to the resource identifier (application ID URI).
Trace ID: ac0c217d-72c7-4ba0-9472-16c711ceea00
Correlation ID: 4d9f5a16-e2e6-4c26-a30e-40e3aa89d53b
Timestamp: 2022-08-10 13:15:35Z
at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1908)
at com.eclerx.email.AccessProvider.accessToken(AccessProvider.java:27)
... 1 more
Caused by: com.microsoft.aad.msal4j.MsalServiceException: AADSTS1002012: The provided value
for scope User.read openid profile offline_access Mail.Read is not valid. Client credential
flows must have a scope value with /.default suffixed to the resource identifier (application
ID URI).
Trace ID: ac0c217d-72c7-4ba0-9472-16c711ceea00
Correlation ID: 4d9f5a16-e2e6-4c26-a30e-40e3aa89d53b
Timestamp: 2022-08-10 13:15:35Z
at
com.microsoft.aad.msal4j.MsalServiceExcepti
onFactory.fromHttpResponse(MsalServiceExceptionFactory.java:45)
at
Code is as below
import java.util.Arrays;
import java.util.List;
import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.azure.identity.DeviceCodeCredential;
import com.azure.identity.DeviceCodeCredentialBuilder;
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
import com.microsoft.graph.models.Message;
import com.microsoft.graph.models.User;
import com.microsoft.graph.requests.GraphServiceClient;
import com.microsoft.graph.requests.MessageCollectionPage;
import okhttp3.Request;
public class AuthenticationBuilder2 {
private static final String CLIENT_ID = "*************";
private static final String CLIENT_SECRET_ID = "**************";
private static final String CLIENT_SECRET = "****************";
private static final String AUTH_TENANT = "*************";
private static final List<String> graphApiScopes = Arrays.asList("Mail.Read","User.read");
public AuthenticationBuilder2() {
}
public static AccessProvider initializeGraphForUserAuth() {
ClientSecretCredential clientSecretCredential =
new ClientSecretCredentialBuilder()
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.tenantId(AUTH_TENANT)
.build();
/*final DeviceCodeCredential deviceCodeCred = new DeviceCodeCredentialBuilder()
.clientId(CLIENT_ID)
.tenantId(AUTH_TENANT)
.challengeConsumer(challange -> System.out.println(challange.getMessage()))
.build();*/
TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(graphApiScopes, clientSecretCredential);
//TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(graphApiScopes, deviceCodeCred);
GraphServiceClient<Request> graphServiceClient = GraphServiceClient.builder()
.authenticationProvider(tokenCredentialAuthProvider)
.buildClient();
return new AccessProvider(graphServiceClient, tokenCredentialAuthProvider);
}
public static void main(String[] args) {
AccessProvider accessProvider = AuthenticationBuilder.initializeGraphForUserAuth();
// get token
System.out.println("token : " + accessProvider.accessToken());
System.out.println(accessProvider.getServiceClient().users());
User user = accessProvider.getServiceClient().me().buildRequest().get();
System.out.println("My UserName :: "+user.displayName);
final MessageCollectionPage messagePage = accessProvider.getServiceClient().me().messages()
.buildRequest().top(3).select("subject").get();
List<Message> messageList = messagePage.getCurrentPage();
for(Message msg : messageList) {
System.out.println("Subject -> "+msg.subject);
}
}
}
You are using the client credential flow here, which means that you cannot dynamically request scopes. You must configure your required permission scopes on your app registration in apps.dev.microsoft.com, then you set the value of scope in your code to https://graph.microsoft.com/.default.
please use string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
ref doc - https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-acquire-token?tabs=dotnet#azure-ad-v10-resources
https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider
Hope this will help , please let us know if have any question
Thanks
I am using SendGrid as the output of one of my azure function. And I am sending the same email to multiple users with the help of personalization. The code is as follows
#FunctionName("ehprocessor")
public void eventHubProcessor(
#EventHubTrigger(name = "msg", eventHubName = "", connection = "eventhubConnString", cardinality = Cardinality.ONE) String eventHubMessage,
#SendGridOutput(name = "message", dataType = "String", apiKey = "sendGridAPIKey", to = "jithin#mailinator.com", from = "jithin#vinnovatelabz.com", subject = "Event From The Machine", text = "Sent from Azure Functions") OutputBinding<String> message,
final ExecutionContext context) {
final String toAddress = "jithin#mailinator.com";
final String toAddressMail = "jishnu#mailinator.com";
StringBuilder builder = new StringBuilder().append("{")
.append("\"personalizations\": [{ \"to\": [{ \"email\": \"%s\"},{ \"email\": \"%s\"}]}],")
.append("\"content\": [{\"type\": \"text/plain\", \"value\": \"%s\"}]").append("}");
final String body = String.format(builder.toString(), toAddress, toAddressMail, value);
message.setValue(body);
}
As you can see I am using the Json body to personalize the things. but now I want to use the helper library for sendgrid provided by java. How can I use it. Can somebody give me a code snippet of that?
You can use Twilio SendGrid library to send Email in java by following the below steps:
If you are using Maven then add this dependency in pom.xml:
<dependency>
<groupId>com.sendgrid</groupId>
<artifactId>sendgrid-java</artifactId>
<version>4.4.1</version>
</dependency>
Create a new class called SendGridEmailer in your project with the following content:
import com.sendgrid.*;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.*;
import java.io.IOException;
public class SendGridEmailer {
public static void main(String[] args) throws IOException {
Email from = new Email("test#example.com");
Email to = new Email("test#example.com");
String subject = "Sending with Twilio SendGrid ";
Content content = new Content("text/html", "and Sending with Twilio SendGrid <strong>Java</strong>");
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getHeaders());
System.out.println(response.getBody());
}
}
Here, API key is read from an environment variable.
I'm setting up a chat bot in JHIPSTER & Dialogflow. but I keep getting errors when I execute my code.
I have created a class called DetectIntent with the code for DetectIntent provided by DialogFlow v2, and a REST api that receives messages from users and then I call the DetectIntent class to understand what the user wants to say.
NOTE: I am behind a proxy of the company I work at.
import com.google.api.client.util.Maps;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.cloud.dialogflow.v2.TextInput.Builder;
import java.util.List;
import java.util.Map;
/**
* DialogFlow API Detect Intent sample with text inputs.
*/
public class DetectIntent {
public static Map<String, QueryResult> detectIntentTexts(
String projectId,
List<String> texts,
String sessionId,
String languageCode) throws Exception {
Map<String, QueryResult> queryResults = Maps.newHashMap();
// Instantiates a client
try (SessionsClient sessionsClient = SessionsClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
SessionName session = SessionName.of(projectId, sessionId);
System.out.println("Session Path: " + session.toString());
// Detect intents for each text input
for (String text : texts) {
// Set the text (hello) and language code (en-US) for the query
TextInput.Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
// Build the query with the TextInput
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
// Performs the detect intent request
DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
// Display the query result
QueryResult queryResult = response.getQueryResult();
System.out.println("====================");
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
System.out.format("Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
queryResults.put(text, queryResult);
}
}
return queryResults;
}
}
#RestController
#RequestMapping("/api")
public class ConversationExchange {
public ConversationExchange()
{
}
// Receive Messages Web Hook
#PostMapping(path="/whatsapp/hook")
public void TwilioWebHook(#RequestParam Map<String, String> map) throws Exception {
System.out.println("************************************************");
System.out.println("************************************************");
System.out.println("- DATA : " + map );
System.out.println("- SMS ID : " + map.get("SmsSid").toString());
System.out.println("- SENDER : " + map.get("From").toString());
System.out.println("- RECEIVER : " + map.get("To").toString());
System.out.println("- MESSAGE : " + map.get("Body").toString());
System.out.println("- STATUS : " + map.get("SmsStatus").toString());
System.out.println("- MESSAGE SID : " + map.get("MessageSid").toString());
System.out.println("- Account SID : " + map.get("AccountSid").toString());
System.out.println("************************************************");
System.out.println("************************************************");
List<String> list = new ArrayList<String>(Arrays.asList(map.get("Body").split(" ")));
// Detect Intent From Message
String session = UUID.randomUUID().toString();
DetectIntent detectIntent = new DetectIntent();
String response = detectIntentTexts("agent...", list, session,"fr-FR").toString();
System.out.println("----> INTENT DETECTED : " + response );
// SEND RESPONSE
}
}
I excepted to get the intent detected but what I get multiple errors in the console.
i.g.n.s.io.grpc.netty.GrpcSslContexts : Conscrypt class not found. Not using Conscrypt
i.g.n.s.i.n.u.i.NativeLibraryLoader : Unable to load the library 'io_grpc_netty_shaded_netty_tcnative_windows_x86_64', trying other loading mechanism.
i.g.n.s.i.n.u.i.NativeLibraryLoader : io_grpc_netty_shaded_netty_tcnative_windows_x86_64 cannot be loaded from java.libary.path, now trying export to -Dio.netty.native.workdir:..
Couldn't load full implementation for TagsComponent, now trying to load lite implementation.
io.opencensus.tags.Tags : Couldn't load lite implementation for TagsComponent, now using default implementation for TagsComponent.
io.opencensus.stats.Stats : Couldn't load full implementation for StatsComponent, now trying to load lite implementation.
io.opencensus.stats.Stats : Couldn't load lite implementation for StatsComponent, now using default implementation for StatsComponent.
io.opencensus.trace.Tracing : Couldn't load full implementation for TraceComponent, now trying to load lite implementation.
io.opencensus.trace.Tracing : Couldn't load lite implementation for TraceComponent, now using default implementation for TraceComponent.
io.grpc.Context : Storage override doesn't exist. Using default
Fixed it, the issue was the proxy, I had to set system variables to support the proxy.
heres the code
it basically takes a message and echos it back.
the problem is it is not replying at all :(
in google app engine, my applications page, i get error-"The requested URL /guestbook was not found on this server."
package guestbook;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.*;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
#SuppressWarnings("serial")
public class GuestbookServlet extends HttpServlet {
private static final Logger LOG =
Logger.getLogger(GuestbookServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// Parse incoming message
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
Message msg = xmpp.parseMessage(req);
JID jid = msg.getFromJid();
String body = msg.getBody();
LOG.info(jid.getId() + " --> JEliza: " + body);
// Get a response from Eliza
String response = "echo: " + body;
LOG.info(jid.getId() + " <-- JEliza: " + response);
// Send out response
msg = new MessageBuilder()
.withRecipientJids(jid)
.withBody(response)
.build();
xmpp.sendMessage(msg);
/*Message message = xmpp.parseMessage(req);
JID fromJid = message.getFromJid();
String body = message.getBody();
String respMsg = null;
if (body.equals("/list")) {
respMsg = "Hi";
} else if (body.equals("/help")) {
respMsg = "Welcome to the Guestbook Chatbot!\nThe following commands are supported: \n /list \n /help";
} else {
respMsg = "Command '" + body + "' not supported! \nEnter '/help' for list of commands.";
}
JID tojid = new JID(fromJid.getId());
Message msg = new MessageBuilder().withRecipientJids(tojid).withBody(respMsg).build();
boolean messageSent = false;
xmpp = XMPPServiceFactory.getXMPPService();
if (xmpp.getPresence(tojid).isAvailable()) {
SendResponse status = xmpp.sendMessage(msg);
messageSent = (status.getStatusMap().get(tojid) == SendResponse.Status.SUCCESS);
}*/
}
}
As per the details you have given i think the problem should be with the web.xml file
<servlet><servlet-name>GuestbookServlet</servlet-name><servlet-class>your.package.structure.GuestbookServlet</servlet-class></servlet><servlet-mapping><servlet-name>GuestbookServlet</servlet-name><url-pattern>/_ah/xmpp/message/chat/</url-pattern></servlet-mapping>
try adding this into the web.xml change your.package.structure.GuestbookServlet accordingly for example mine would be com.appengine.capp
JDK settings had to be changed from 1.7 to 1.6.
under window-> preferences -> java -> compiler