I am trying to make a java app which makes connection with facebook.I am using facebok4j to achieve this,I made an app in fb devolopers and got the key annd id for it.But when i am passing it to get an access token its returning an exception error.Please help me
java code
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.Post;
import facebook4j.ResponseList;
import facebook4j.auth.AccessToken;
import facebook4j.auth.OAuthAuthorization;
import facebook4j.auth.OAuthSupport;
import facebook4j.conf.Configuration;
import facebook4j.conf.ConfigurationBuilder;
public class Fbsample {
public static Configuration createConfiguration()
{
ConfigurationBuilder confBuilder = new ConfigurationBuilder();
confBuilder.setDebugEnabled(true);
confBuilder.setOAuthAppId("*****");
confBuilder.setOAuthAppSecret("*****");
confBuilder.setUseSSL(true);
confBuilder.setJSONStoreEnabled(true);
Configuration configuration = confBuilder.build();
return configuration;
}
public static void main(String[] argv) throws FacebookException {
Configuration configuration = createConfiguration();
FacebookFactory facebookFactory = new FacebookFactory(configuration );
Facebook facebookClient = facebookFactory.getInstance();
AccessToken accessToken = null;
try{
OAuthSupport oAuthSupport = new OAuthAuthorization(configuration );
accessToken = oAuthSupport.getOAuthAppAccessToken();
}catch (FacebookException e) {
System.err.println("Error while creating access token " + e.getLocalizedMessage());
}
facebookClient.setOAuthAccessToken(accessToken);
//results in an error says {An active access token must be used to query information about the current user}
}
}
For now i specified my token and id as *.When running its returning 'Error while creating access token graph.facebook.com'.Thanks in advance.
Related
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.
I've a mobile application that using Google sign and trying to verify the token in backend (java spring).
I've set a few code for that, following many article.
FirebaseServiceCredential.java
This is for firebase connection, because i'm verifying using Admin SDK
package com.nostratech.nostrafood.config;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.FirebaseDatabase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import java.io.FileInputStream;
import java.io.IOException;
#Slf4j
#Configuration
public class FirebaseServiceCredential {
public void firebaseConnect() throws IOException {
try {
FileInputStream serviceAccount = new FileInputStream("resources/charity-firebase-adminsdk-ymwjh-61467z75ba.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://charity.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
FirebaseDatabase.getInstance(FirebaseApp.getInstance()).setPersistenceEnabled(true);
} catch (Exception e) {
log.debug("Trying to login to firebase failed. Reason: " + e.getMessage());
}
}
}
GoogleSignInService.java
This is code for verifyIdToken
package com.nostratech.nostrafood.service.base;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import org.springframework.stereotype.Service;
#Service
public class GoogleSignInService {
public void verifyToken(String idToken) throws FirebaseAuthException {
FirebaseToken decodedToken =
FirebaseAuth.getInstance().verifyIdToken(idToken);
String uid = decodedToken.getUid();
}
}
What should I do next for verify the token? I've read many article but still stuck dont know what to do.
If verifyIdToken() returns without throwing an exception, then the token is verified. No other action is needed to verify an ID token. The return value (FirebaseToken) gives you access to the UID and the JWT claims associated with the authenticated user.
I am working with the ETrade Java API. I was able to use most of the functions but I am having trouble with the previewEquityOrder and the previewOptionOrder functions. Here are the error messages/ exceptions I get when I call these functions:
URL : https://etwssandbox.etrade.com/order/sandbox/rest/previewequityorder
? Java exception occurred:
com.etrade.etws.sdk.common.ETWSException
at com.etrade.etws.sdk.common.ETWSUtil.constructException(ETWSUtil.java:9)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:90)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:32)
at com.etrade.etws.sdk.client.OrderClient.previewEquityOrder(OrderClient.java:145)
For the previewOptionOrder:
URL : https://etwssandbox.etrade.com/order/sandbox/rest/previewoptionorder
? Java exception occurred:
com.etrade.etws.sdk.common.ETWSException
at com.etrade.etws.sdk.common.ETWSUtil.constructException(ETWSUtil.java:9)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:90)
at com.etrade.etws.sdk.core.ConnectionUtils.invoke(ConnectionUtils.java:32)
at com.etrade.etws.sdk.client.OrderClient.previewOptionOrder(OrderClient.java:167)
The following Java code can reproduce the problem. You can compile this code on a Mac using the following command. On windows machine, replace the " : " with " ; " as the separator.
javac -classpath "./commons-codec-1.3.jar:./commons-httpclient-3.1.jar:./commons-httpclient-contrib-ssl-3.1.jar:./commons-lang-2.4-javadoc.jar:./commons-lang-2.4-sources.jar:./commons-lang-2.4.jar:./commons-logging-api.jar:./commons-logging.jar:./etws-accounts-sdk-1.0.jar:./etws-common-connections-1.0.jar:./etws-market-sdk-1.0.jar:./etws-oauth-sdk-1.0.jar:./etws-order-sdk-1.0.jar:./log4j-1.2.15.jar:./xstream-1.3.1.jar:" test.java
You can run the compiled class from command line using the following command:
java -classpath "./commons-codec-1.3.jar:./commons-httpclient-3.1.jar:./commons-httpclient-contrib-ssl-3.1.jar:./commons-lang-2.4-javadoc.jar:./commons-lang-2.4-sources.jar:./commons-lang-2.4.jar:./commons-logging-api.jar:./commons-logging.jar:./etws-accounts-sdk-1.0.jar:./etws-common-connections-1.0.jar:./etws-market-sdk-1.0.jar:./etws-oauth-sdk-1.0.jar:./etws-order-sdk-1.0.jar:./log4j-1.2.15.jar:./xstream-1.3.1.jar:" test <consumer_key> <consumer_secret>
You will need to pass in the ETrade consumer key and consumer secret as command line arguments to run this.
Notice that the authentication part works which is verified by getting the accounts list.
import com.etrade.etws.account.Account;
import com.etrade.etws.account.AccountListResponse;
import com.etrade.etws.oauth.sdk.client.IOAuthClient;
import com.etrade.etws.oauth.sdk.client.OAuthClientImpl;
import com.etrade.etws.oauth.sdk.common.Token;
import com.etrade.etws.sdk.client.ClientRequest;
import com.etrade.etws.sdk.client.Environment;
import com.etrade.etws.sdk.common.ETWSException;
import com.etrade.etws.sdk.client.AccountsClient;
import com.etrade.*;
import com.etrade.etws.order.PreviewEquityOrder;
import com.etrade.etws.order.PreviewEquityOrderResponse;
import com.etrade.etws.order.EquityOrderRequest;
import com.etrade.etws.order.EquityOrderTerm;
import com.etrade.etws.order.EquityOrderAction;
import com.etrade.etws.order.MarketSession;
import com.etrade.etws.order.EquityPriceType;
import com.etrade.etws.order.EquityOrderRoutingDestination;
import com.etrade.etws.sdk.client.OrderClient;
import java.math.BigInteger;
import java.awt.Desktop;
import java.net.URI;
import java.*;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class test
{
public static void main(String[] args) throws IOException, ETWSException
{
//Variables
if(args.length<2){
System.out.println("Class test needs two input argument as follows:");
System.out.println("test <consumer_key> <consumer_secret>");
return;
}
String oauth_consumer_key = args[0]; // Your consumer key
String oauth_consumer_secret = args[1]; // Your consumer secret
String oauth_request_token = null; // Request token
String oauth_request_token_secret = null; // Request token secret
String oauth_verify_code = null;
String oauth_access_token = null;
String oauth_access_token_secret = null;
ClientRequest request = new ClientRequest();
System.out.println("HERE");
IOAuthClient client = OAuthClientImpl.getInstance(); // Instantiate IOAUthClient
// Instantiate ClientRequest
request.setEnv(Environment.SANDBOX); // Use sandbox environment
request.setConsumerKey(oauth_consumer_key); //Set consumer key
request.setConsumerSecret(oauth_consumer_secret);
Token token = client.getRequestToken(request); // Get request-token object
oauth_request_token = token.getToken(); // Get token string
oauth_request_token_secret = token.getSecret(); // Get token secret
request.setToken(oauth_request_token);
request.setTokenSecret(oauth_request_token_secret);
String authorizeURL = null;
authorizeURL = client.getAuthorizeUrl(request);
System.out.println(authorizeURL);
System.out.println("Copy the URL into your browser. Get the verification code and type here");
oauth_verify_code = get_verification_code();
//oauth_verify_code = Verification(client,request);
request.setVerifierCode(oauth_verify_code);
token = client.getAccessToken(request);
oauth_access_token = token.getToken();
oauth_access_token_secret = token.getSecret();
request.setToken(oauth_access_token);
request.setTokenSecret(oauth_access_token_secret);
// Get Account List
AccountsClient account_client = new AccountsClient(request);
AccountListResponse response = account_client.getAccountList();
List<Account> alist = response.getResponse();
Iterator<Account> al = alist.iterator();
while (al.hasNext()) {
Account a = al.next();
System.out.println("===================");
System.out.println("Account: " + a.getAccountId());
System.out.println("===================");
}
// Preview Equity Order
OrderClient order_client = new OrderClient(request);
PreviewEquityOrder orderRequest = new PreviewEquityOrder();
EquityOrderRequest eor = new EquityOrderRequest();
eor.setAccountId("83405188"); // sample values
eor.setSymbol("AAPL");
eor.setAllOrNone("FALSE");
eor.setClientOrderId("asdf1234");
eor.setOrderTerm(EquityOrderTerm.GOOD_FOR_DAY);
eor.setOrderAction(EquityOrderAction.BUY);
eor.setMarketSession(MarketSession.REGULAR);
eor.setPriceType(EquityPriceType.MARKET);
eor.setQuantity(new BigInteger("100"));
eor.setRoutingDestination(EquityOrderRoutingDestination.AUTO.value());
eor.setReserveOrder("TRUE");
orderRequest.setEquityOrderRequest(eor);
PreviewEquityOrderResponse order_response = order_client.previewEquityOrder(orderRequest);
}
public static String get_verification_code() {
try{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
String input;
input=br.readLine();
return input;
}catch(IOException io){
io.printStackTrace();
return "";
}
}
}
I posted this on the ETrade community forum but that forum is not very active. I also sent a request to ETrade and haven't gotten a reply yet. If I get a solution from them, I will come back and post it here. In the mean time any help is greatly appreciated.
After debugging my above code, I figured out that the problem is that I was setting the ReserveOrder to TRUE but I wasn't providing the required ReserveOrderQuantity. I got the above code from the Java code snippet in the ETrade Developer Platform Guide. This is clearly a bug in their documentation.
I am trying to query vendors using the QBOVendorService but having no luck.
I am creating the service as follows:
QBOVendorService vService = QBServiceFactory.getService(context, QBOVendorService.class);
where the context is a valid PlatformSessionContext. I know the platform session context is good since I can get information about the user with it. When I try
vService.addVendor(context, vendor);
I end up with a NPE like my vService is null. Shouldn't I get an error initializing the QBOVendorService if it fails? Is there a good place to find more examples for using this since the intuit developer forums have been shut down?
I'm sharing a sample code snippet. Replace your OAuth tokens and relamId. It should work fine.
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import com.intuit.ds.qb.QBIdType;
import com.intuit.ds.qb.QBVendor;
import com.intuit.ds.qb.QBVendorQuery;
import com.intuit.ds.qb.QBVendorService;
import com.intuit.ds.qb.QBInvalidContextException;
import com.intuit.ds.qb.QBObjectFactory;
import com.intuit.ds.qb.QBServiceFactory;
import com.intuit.ds.qb.impl.QBRecordCountImpl;
import com.intuit.ds.qb.qbd.QBDRecordCountService;
import com.intuit.ds.qb.qbd.QBDServiceFactory;
import com.intuit.platform.client.PlatformSessionContext;
import com.intuit.platform.client.PlatformServiceType;
import com.intuit.platform.client.security.OAuthCredentials;
import com.intuit.ds.qb.QBSyncStatusRequest;
import com.intuit.ds.qb.QBSyncStatusRequestService;
import com.intuit.ds.qb.QBSyncStatusResponse;
import com.intuit.sb.cdm.NgIdSet;
import com.intuit.sb.cdm.ObjectName;
import org.slf4j.Logger;
// QBD API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0500_quickbooks_windows/0600_object_reference/vendor
// QBO API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/vendor
// JavaDocs - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/
public class CodegenStubVendorall {
final PlatformSessionContext context;
public CodegenStubVendorall(PlatformSessionContext context) {
this.context = context;
}
public void testAdd() {
final List<QBVendor> entityList = new ArrayList<QBVendor>();
try {
QBVendorService service = QBServiceFactory.getService(context, QBVendorService.class);
//Your Code
//Use Vendor POJO for creating Vendor
}
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
PlatformSessionContext context = getPlatformContext();
CodegenStubVendorall testObj = new CodegenStubVendorall(context);
testObj.testAdd();
}
public static PlatformSessionContext getPlatformContext() {
String accesstoken = "rplce_your_application_token";
String accessstokensecret = "rplce_your_application_token";
String appToken = "rplce_your_application_token";
String oauth_consumer_key = "rplce_your_application_token";
String oauth_consumer_secret = "rplce_your_application_token";
String realmID = "123456";
String dataSource = "QBO";
PlatformServiceType serviceType;
if (dataSource.equalsIgnoreCase("QBO")) {
serviceType = PlatformServiceType.QBO;
} else {
serviceType = PlatformServiceType.QBD;
}
final OAuthCredentials oauthcredentials = new OAuthCredentials(
oauth_consumer_key, oauth_consumer_secret, accesstoken,
accessstokensecret);
final PlatformSessionContext context = new PlatformSessionContext(
oauthcredentials, appToken, serviceType, realmID);
return context;
}
}
You can try to use ApiExplorer tool to verify your OAuth tokens and to check the create Vendor API endpoint.
Link - https://developer.intuit.com/apiexplorer?apiname=V2QBO
Please let me know how it goes.
Thanks
I am currently working on a Java Web application that runs on Apache Tomcat 7. Due to the fact that I want to log some information into a database, I use the following configuration file information for initiating my Logger:
log4j.rootLogger = DEBUG, DB
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DB.URL=jdbc:mysql://localhost:3306/cap_recommender_log
log4j.appender.DB.driver=com.mysql.jdbc.Driver
log4j.appender.DB.user=log_user
log4j.appender.DB.password=some_password
log4j.appender.DB.sql=INSERT INTO notify_service_log(date, logger, level, message) VALUES('%d{YYYY-MM-dd}','%C','%p','%m')
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
Also, the notify_service_log table is as follows:
CREATE TABLE `notify_service_log` (
`date` date NOT NULL,
`logger` varchar(256) NOT NULL,
`level` varchar(10) NOT NULL,
`message` text NOT NULL,
KEY `index_level` (`level`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Finally, the web service code is as follows:
package com.imis.cap.service.notify;
import com.imis.cap.module.etl.EtlModuleClient;
import gr.aia.cap.eventbroker.v1.ArrayOfServiceMessage;
import gr.aia.cap.eventbroker.v1.BooleanResponse;
import gr.aia.cap.eventbroker.v1.ServiceMessage;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.jws.WebService;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
#WebService(serviceName = "NotifyService", portName = "HttpBinding_NotifyService", endpointInterface = "gr.aia.cap.eventbroker.v1.NotifyService", targetNamespace = "http://www.aia.gr/cap/eventbroker/v1/", wsdlLocation = "WEB-INF/wsdl/NotifyService/NotifyService.wsdl")
public class NotifyService {
private String username;
private String password;
private String log_properties_file;
private DataSource registration_db;
private static org.apache.log4j.Logger notifyServiceLogger =
Logger.getLogger(NotifyService.class);
public NotifyService() {
Context context;
try {
context = (Context) new InitialContext().lookup("java:comp/env");
this.username = (String) context.lookup("CAP_RECOMMENDER_UNAME");
this.password = (String) context.lookup("CAP_RECOMMENDER_PASS");
this.registration_db = (DataSource) context.lookup("jdbc/cap_registration_db");
this.log_properties_file = (String) context.lookup("NOTIFY_SERVICE_LOG_PROPERTIES_FILE");
}catch(NamingException e) {
System.err.println(e.getMessage());
notifyServiceLogger.error("NotifyService: NamingException occured during construction. Message: " +
e.getMessage());
}
PropertyConfigurator.configure(this.log_properties_file);
notifyServiceLogger.info("NotifyService: Object constructor completed successfully.");
}
public gr.aia.cap.eventbroker.v1.BooleanResponse notify(gr.aia.cap.eventbroker.v1.NotifyRequest request) throws ParseException {
ArrayOfServiceMessage arrayOfServiceMsg = new ArrayOfServiceMessage();
ServiceMessage msg = new ServiceMessage();
BooleanResponse response = new BooleanResponse();
EventTypeReader eventType = new EventTypeReader(request);
String regCode = request.getRegistrationCode();
String dbRegCode = "";
**notifyServiceLogger.info("NotifyService.notify(): Called with reg-code: " + request.getRegistrationCode() + ".");**
/**Some more code**/
return new BooleanResponse(); //Sample response
}
}
The client Code that performs the call of the notify procedure is as follows:
package notifyclient;
import gr.aia.cap.eventbroker.v1.ArrayOfAttribute;
import gr.aia.cap.eventbroker.v1.BooleanResponse;
import gr.aia.cap.eventbroker.v1.EventType;
import gr.aia.cap.eventbroker.v1.NotifyRequest;
public class NotifyClient {
public static void main(String[] args) {
NotifyRequest request = new NotifyRequest();
request.setRegistrationCode("blasdadasd");
request.setAttributes(new ArrayOfAttribute());
request.setEventType(EventType.USER);
BooleanResponse response = notify(request);
System.out.println("Output: " + response.getErrors().getServiceMessage().toString());
}
public static gr.aia.cap.eventbroker.v1.BooleanResponse notify(gr.aia.cap.eventbroker.v1.NotifyRequest request) {
gr.aia.cap.eventbroker.v1.NotifyService_Service service = new gr.aia.cap.eventbroker.v1.NotifyService_Service();
gr.aia.cap.eventbroker.v1.NotifyService port = service.getHttpBindingNotifyService();
return port.notify(request);
}
}
I have to inform you at this point that the required classes that are needed to perform the Web Service call are automatically generated by Netbeans 7.2.
The problem lies on the fact that the Constructor's message is logged into the database, but the information message in the notify function is never logged. Why is this happening? Any ideas?
As comments state, adding PropertyConfigurator.configure(this.log_properties_file); on the line above the logger call in the notify() method resolved the problem.