I am new to java, for several weeks I have been trying to report the status of a person via microsoft graph, I have no error but the returned value is unreadable. I must be missing something to show the status.
It's a Gradle Project in Eclipse
here is my code:
```public class App {
public static void main(String[] args) {
// <LoadSettingsSnippet>
// Load OAuth settings
final Properties oAuthProperties = new Properties();
try {
oAuthProperties.load(App.class.getResourceAsStream("oAuth.properties"));
} catch (IOException e) {
System.out.println("Unable to read OAuth configuration. Make sure you have a properly formatted oAuth.properties file. See README for details.");
return;
}
final String appId = oAuthProperties.getProperty("app.id");
final List<String> appScopes = Arrays
.asList(oAuthProperties.getProperty("app.scopes").split(","));
// </LoadSettingsSnippet>
// Initialize Graph with auth settings
Graph.initializeGraphAuth(appId, appScopes);
final String accessToken = Graph.getUserAccessToken();
// getpresence
Presence teamCollectionPage = Graph.getPresence();
System.out.println("Valeur Presence : " + teamCollectionPage);
Scanner input = new Scanner(System.in);
``
public class Graph {
private static GraphServiceClient<Request> graphClient = null;
private static TokenCredentialAuthProvider authProvider = null;
public static void initializeGraphAuth(String applicationId, List<String> scopes) {
// Create the auth provider
final DeviceCodeCredential credential = new DeviceCodeCredentialBuilder()
.clientId(applicationId)
.challengeConsumer(challenge -> System.out.println(challenge.getMessage()))
.build();
authProvider = new TokenCredentialAuthProvider(scopes, credential);
// Create default logger to only log errors
DefaultLogger logger = new DefaultLogger();
logger.setLoggingLevel(LoggerLevel.ERROR);
// Build a Graph client
graphClient = GraphServiceClient.builder()
.authenticationProvider(authProvider)
.logger(logger)
.buildClient();
}
public static String getUserAccessToken()
{
try {
URL meUrl = new URL("https://graph.microsoft.com/v1.0/me");
return authProvider.getAuthorizationTokenAsync(meUrl).get();
} catch(Exception ex) {
return null;
}
}
public static Presence getPresence() {
if (graphClient == null) throw new NullPointerException(
"Graph client has not been initialized. Call initializeGraphAuth before calling this method");
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
Presence presence = graphClient.users("XXXXXXXXXXXXXXXX").presence()
.buildRequest()
.get();
return presence ;
}
}
the message return is "Valeur Presence : com.microsoft.graph.models.Presence#4d411036"
thank you in advance for your help
What you’re seeing is the default value of Object.toString if the method isn’t overridden in the child class (and it isn’t for the Presence model class).
You can access the value explicitly, e.g.:
System.out.println("Valeur Presence : " + teamCollectionPage.availability);
Related
I am using DocuSign java client first time. I am create custom template for my pdf file. I am using DocuSign APIs. But facing following error:
javax.servlet.ServletException: java.lang.NoClassDefFoundError:
com/migcomponents/migbase64/Base64
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
I have created REST API and in that API i am trying to use createTemplate code but facing above issue.
I have imported all required jars in my project using maven. All jars are also present in my classpath. It seems at compile time all jar are found but at runtime not able to find the jars.
#Path("/template")
public class CreateTemplate {
private static final String UserName = "xyz.abc#gmail.com";
private static final String UserId = "fcc5726c-cd73-4844-b580-40bbbe6ca126";
private static final String IntegratorKey = "ae30ea4e-3959-4d1c-b867-fcb57d2dc4df";
private static final String IntegratorKeyImplicit = "68c1711f-8b19-47b1-888f-b49b4211d831";
//private static final String ClientSecret = "b4dccdbe-232f-46cc-96c5-b2f0f7448f8f";
private static final String RedirectURI = "https://www.docusign.com/api";
private static final String BaseUrl = "https://demo.docusign.net/restapi";
//private static final String OAuthBaseUrl = "account-d.docusign.com";
private static final String privateKeyFullPath = System.getProperty("user.dir") + "/src/test/keys/docusign_private_key.txt";
private static final String SignTest1File = "C:\\Users\\xyz\\Documents\\testDocuments\\SignTest1.pdf";
//private static final String TemplateId = "cf2a46c2-8d6e-4258-9d62-752547b1a419";
private String[] envelopeIds = new String[0];
TemplateSummary templateSummary;
#GET
#Path("/createTemplate")
#Produces("text/plain")
public TemplateSummary createTemplate() {
System.out.println("\nCreateTemplateTest:\n" + "===========================================");
byte[] fileBytes = null;
File f;
try {
// String currentDir = new java.io.File(".").getCononicalPath();
String currentDir = System.getProperty("user.dir");
java.nio.file.Path path = Paths.get(SignTest1File);
fileBytes = Files.readAllBytes(path);
f = new File(path.toString());
//Assert.assertTrue(f.length() > 0);
System.out.println("f.length()-->"+f.length());
} catch (IOException ioExcp) {
//Assert.assertEquals(null, ioExcp);
ioExcp.printStackTrace();
}
// create an envelope to be signed
EnvelopeTemplate templateDef = new EnvelopeTemplate();
templateDef.setEmailSubject("Please Sign my Java SDK Envelope");
templateDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.encodeToString(fileBytes, false);
//String base64Doc = Base64.encodeToString(str.getBytes("UTF-8"), false))
doc.setDocumentBase64(base64Doc);
doc.setName("TestFile.pdf");
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
templateDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setRoleName("Signer1");
signer.setRecipientId("1");
// Create a SignHere tab somewhere on the document for the signer to
// sign
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("100");
signHere.setScaleValue("0.5");
List<SignHere> signHereTabs = new ArrayList<SignHere>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
templateDef.setRecipients(new Recipients());
templateDef.getRecipients().setSigners(new ArrayList<Signer>());
templateDef.getRecipients().getSigners().add(signer);
EnvelopeTemplateDefinition envTemplateDef = new EnvelopeTemplateDefinition();
envTemplateDef.setName("myTemplate");
templateDef.setEnvelopeTemplateDefinition(envTemplateDef);
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
byte[] privateKeyBytes = null;
try {
privateKeyBytes = Files.readAllBytes(Paths.get(privateKeyFullPath));
} catch (IOException ioExcp) {
//Assert.assertEquals(null, ioExcp);
ioExcp.printStackTrace();
}
if (privateKeyBytes == null) return null;
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
//Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
/*Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
*/
System.out.println("userInfo.getAccounts().size()-->"+userInfo.getAccounts().size());
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
TemplatesApi templatesApi = new TemplatesApi();
templateSummary = templatesApi.createTemplate(accountId, templateDef);
//Assert.assertNotNull(templateSummary);
//Assert.assertNotNull(templateSummary.getTemplateId());
System.out.println("templateSummary-->"+templateSummary);
System.out.println("templateSummary.getTemplateId()-->"+templateSummary.getTemplateId());
//System.out.println("TemplateSummary: " + templateSummary);
} catch (ApiException ex) {
System.out.println("Exception: 123");
ex.printStackTrace();
} catch (Exception e) {
//System.out.println("Exception: " + e.getLocalizedMessage());
System.out.println("Exception: 234");
e.printStackTrace();
}
return templateSummary;
}
}
I feel like I am facing missing runtime jar files.
I run a custom WebSocketServlet for Jetty, which sends short text push notifications (for an async mobile and desktop word game) to many platforms (Facebook, Vk.com, Mail.ru, Ok.ru also Firebase and Amazon messaging) using a Jetty HttpClient instance:
public class MyServlet extends WebSocketServlet {
private final SslContextFactory mSslFactory = new SslContextFactory();
private final HttpClient mHttpClient = new HttpClient(mSslFactory);
#Override
public void init() throws ServletException {
super.init();
try {
mHttpClient.start();
} catch (Exception ex) {
throw new ServletException(ex);
}
mFcm = new Fcm(mHttpClient); // Firebase
mAdm = new Adm(mHttpClient); // Amazon
mApns = new Apns(mHttpClient); // Apple
mFacebook = new Facebook(mHttpClient);
mMailru = new Mailru(mHttpClient);
mOk = new Ok(mHttpClient);
mVk = new Vk(mHttpClient);
}
This has worked very good for the past year, but since I have recently upgraded my WAR-file to use Jetty 9.4.14.v20181114 the trouble has begun -
public class Facebook {
private final static String APP_ID = "XXXXX";
private final static String APP_SECRET = "XXXXX";
private final static String MESSAGE_URL = "https://graph.facebook.com/%s/notifications?" +
// the app access token is: "app id | app secret"
"access_token=%s%%7C%s" +
"&template=%s";
private final HttpClient mHttpClient;
public Facebook(HttpClient httpClient) {
mHttpClient = httpClient;
}
private final BufferingResponseListener mMessageListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
LOG.warn("facebook failure: {}", result.getFailure());
return;
}
try {
// THE jsonStr SUDDENLY CONTAINS PREVIOUS CONTENT!
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
LOG.info("facebook success: {}", jsonStr);
} catch (Exception ex) {
LOG.warn("facebook exception: ", ex);
}
}
};
public void postMessage(int uid, String sid, String body) {
String url = String.format(MESSAGE_URL, sid, APP_ID, APP_SECRET, UrlEncoded.encodeString(body));
mHttpClient.POST(url).send(mMessageListener);
}
}
Suddenly the getContentAsString method called for successful HttpClient invocations started to deliver the strings, which were fetched previously - prepended to the the actual result string.
What could it be please, is it some changed BufferingResponseListener behaviour or maybe some non-obvious Java quirk?
BufferingResponseListener was never intended to be reusable across requests.
Just allocate a new BufferingResponseListener for every request/response.
For some reason is returning null when tries to get results, somebody has seen this?
When debuging, he goes to the exception on main method, right when he reads this line :
printResults(getResults(analytics, profile));
He does reach the profile ID, although its not working on the method results, my google analytics account is working just fine
I get this in console:
First Profile Id: 166128559
java.lang.NullPointerException at HelloAnalytics.printResults(HelloAnalytics.java:99)
at HelloAnalytics.main(HelloAnalytics.java:33)
Code :
public class HelloAnalytics {
private static final String APPLICATION_NAME = "Hello Analytics";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String KEY_FILE_LOCATION = "C:/Users/Shell/workspace/relatorio-analytics/src/main/java/client_secrets.p12";
private static final String SERVICE_ACCOUNT_EMAIL = "shell-121#projeto-analytics-188712.iam.gserviceaccount.com";
public static void main(String[] args) {
try {
Analytics analytics = initializeAnalytics();
String profile = getFirstProfileId(analytics);
System.out.println("First Profile Id: " + profile);
printResults(getResults(analytics, profile));
} catch (Exception e) {
e.printStackTrace();
}
}
private static Analytics initializeAnalytics() throws Exception {
// Initializes an authorized analytics service object.
// Construct a GoogleCredential object with the service account email
// and p12 file downloaded from the developer console.
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY).setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
.setServiceAccountScopes(AnalyticsScopes.all()).build();
// Construct the Analytics service object.
return new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
.build();
}
private static String getFirstProfileId(Analytics analytics) throws IOException {
// Get the first view (profile) ID for the authorized user.
String profileId = null;
// Query for the list of all accounts associated with the service account.
Accounts accounts = analytics.management().accounts().list().execute();
if (accounts.getItems().isEmpty()) {
System.err.println("No accounts found");
} else {
String firstAccountId = accounts.getItems().get(0).getId();
// Query for the list of properties associated with the first account.
Webproperties properties = analytics.management().webproperties().list(firstAccountId).execute();
if (properties.getItems().isEmpty()) {
System.err.println("No Webproperties found");
} else {
String firstWebpropertyId = properties.getItems().get(0).getId();
// Query for the list views (profiles) associated with the property.
Profiles profiles = analytics.management().profiles().list(firstAccountId, firstWebpropertyId)
.execute();
if (profiles.getItems().isEmpty()) {
System.err.println("No views (profiles) found");
} else {
// Return the first (view) profile associated with the property.
profileId = profiles.getItems().get(0).getId();
}
}
}
return profileId;
}
private static GaData getResults(Analytics analytics, String profileId) throws IOException {
// Query the Core Reporting API for the number of sessions
// in the past seven days.
return analytics.data().ga().get("ga:" + profileId, "7daysAgo", "today", "ga:sessions").execute();
}
private static void printResults(GaData results) {
// Parse the response from the Core Reporting API for
// the profile name and number of sessions.
if (results != null && !results.getRows().isEmpty()) {
System.out.println("View (Profile) Name: " + results.getProfileInfo().getProfileName());
System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
} else {
System.out.println("No results found");
}
}
I want to create ec2 instances when ever the new user arrive. I created a servlet class to do this. When User arrive i check DB that is user new or not if new then create the instance and send back his/her IP. When i send http request to this servlet one by one for users i get the IP correctly. But when i send HTTP Call in parallel (for user1 send request in tab1, for user2 send request in tab2 simultaneously before getting response from user1 HTTP call). When i do this i got error. Sometimes user1 said
"The instance ID 'i-0b79495934c3b5459' does not exist (Service:
AmazonEC2; Status Code: 400; Error Code: InvalidInstanceID.NotFound;
Request ID: e18a9eaa-cb1b-4130-a3ee-bf1b19fa184c) "
And user2 send IP in response. Kindly help me What is the issue and how to resolve this.
This is the Servlet Class which i created.
public class GateKeeperController extends HttpServlet {
private static final long serialVersionUID = 1L;
BasicAWSCredentials awsCreds = new BasicAWSCredentials(credentials);
AmazonEC2Client ec2Client = new AmazonEC2Client(awsCreds);
RunInstancesRequest runInstancesRequest;
RunInstancesResult runInstancesResult;
Reservation reservation;
Instance intstance;
DescribeInstancesRequest describeInstanceRequest;
DescribeInstancesResult describeInstanceResult;
GatekeeperModal gateKeepermodal;
String sourceAMI = null;
String destinationAMI = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession s = request.getSession();
String userID = (String) request.getParameter("userID");
Double lattitude = Double.parseDouble((String) request.getParameter("lat"));
Double lonitude = Double.parseDouble((String) request.getParameter("long"));
if (userID != null) {
Pair coordinates = new Pair(lattitude, lonitude);
RegionSelection targetRegion = new RegionSelection();
String regionResult = targetRegion.getRegion(coordinates);
String instanceIP = null;
gateKeepermodal = new GatekeeperModal();
try {
if (gateKeepermodal.checkUserIsNew(userID)) {
instanceIP = startInstance(userID, regionResult);
if (instanceIP != null) {
response.getWriter().write(instanceIP);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
}
}
private String startInstance(String userID, String region) {
String ami_id = new AMI().getAMI_ID(region);
ec2Client.setEndpoint(region);
runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.withImageId(ami_id).withInstanceType("t2.micro").withMinCount(1).withMaxCount(1)
.withKeyName("GateKeeper_User").withSecurityGroups("GateKeeper User");
runInstancesResult = ec2Client.runInstances(runInstancesRequest);
reservation = runInstancesResult.getReservation();
intstance = reservation.getInstances().get(0);
String s1 = intstance.getState().getName();
String s2 = InstanceStateName.Running.name();
while (!s1.toLowerCase().equals(s2.toLowerCase())) {
describeInstanceRequest = new DescribeInstancesRequest();
describeInstanceRequest.withInstanceIds(intstance.getInstanceId());
ec2Client.setEndpoint(region);
describeInstanceResult = ec2Client.describeInstances(describeInstanceRequest);
reservation = describeInstanceResult.getReservations().get(0);
intstance = reservation.getInstances().get(0);
s1 = intstance.getState().getName();
s2 = InstanceStateName.Running.name();
}
GateKeeperUser user = new GateKeeperUser(userID, intstance.getInstanceId(), intstance.getPublicIpAddress(),
region);
Boolean result;
try {
result = gateKeepermodal.createUser(user);
if (result) {
return intstance.getPublicIpAddress();
} else {
return null;
}
} catch (SQLException e) {
}
return null;
}
}
According to the documentation:
"If you successfully run the RunInstances command, and then
immediately run another command using the instance ID that was
provided in the response of RunInstances, it may return an
InvalidInstanceID.NotFound error. This does not mean the instance does
not exist. Some specific commands that may be affected are:
DescribeInstances: To confirm the actual state of the instance, run
this command using an exponential backoff algorithm.
TerminateInstances: To confirm the state of the instance, first run
the DescribeInstances command using an exponential backoff algorithm."
I have this error:
WARNING: Authentication error: Unable to respond to any of these challenges: {}
Exception : No authentication header information
I am using GWT with eclipse.
I really don't know what's wrong in my code.
Any help would be appreciated.
Thanks in advance.
Client side EntryPoint class:
private static final String GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
private static final String GOOGLE_CLIENT_ID = "xxxxxxx.apps.googleusercontent.com";
private static final String CONTACTS_SCOPE = "https://www.google.com/m8/feeds";
private static final Auth AUTH = Auth.get();
public void onModuleLoad() {
final AuthRequest req = new AuthRequest(GOOGLE_AUTH_URL, GOOGLE_CLIENT_ID).withScopes(CONTACTS_SCOPE);
AUTH.login(req, new Callback<String, Throwable>() {
public void onSuccess(String token) {
ABASession.setToken(token);
}
public void onFailure(Throwable caught) {
Window.alert("Error:\n" + caught.getMessage());
}
});
}
I store the token in a class that I will use later.
Server side: ContactServiceImpl (RPC GAE procedure)
//The token stored previously is then passed through RPC
public List printAllContacts(String token) {
try {
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey("My consumer key");
oauthParameters.setOAuthConsumerSecret("My consumer secret");
PrivateKey privKey = getPrivateKey("certificate/akyosPrivateKey.key");
OAuthRsaSha1Signer signer = new OAuthRsaSha1Signer(privKey);
ContactsService service = new ContactsService("XXX");
service.setProtocolVersion(ContactsService.Versions.V3);
oauthParameters.setOAuthToken(token);
service.setOAuthCredentials(oauthParameters, signer);
// Request the feed
URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/default/full?xoauth_requestor_id=xxx.yyy#gmail.com");
ContactFeed resultFeed = service.getFeed(feedUrl, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) {
for (Email email : entry.getEmailAddresses()) {
contactNames.add(email.getAddress());
}
}
return contactNames;
} catch (Exception e) {
System.err.println("Exception : " + e.getMessage());
}
return null;
}
set the scope
oauthParameters.setScope("http://www.google.com/m8/feeds/contacts/default/full");