Amazon Product Advertising API through Java/SOAP - java

I have been playing with Amazon's Product Advertising API, and I cannot get a request to go through and give me data. I have been working off of this: http://docs.amazonwebservices.com/AWSECommerceService/2011-08-01/GSG/ and this: Amazon Product Advertising API signed request with Java
Here is my code. I generated the SOAP bindings using this: http://docs.amazonwebservices.com/AWSECommerceService/2011-08-01/GSG/YourDevelopmentEnvironment.html#Java
On the Classpath, I only have: commons-codec.1.5.jar
import com.ECS.client.jax.AWSECommerceService;
import com.ECS.client.jax.AWSECommerceServicePortType;
import com.ECS.client.jax.Item;
import com.ECS.client.jax.ItemLookup;
import com.ECS.client.jax.ItemLookupRequest;
import com.ECS.client.jax.ItemLookupResponse;
import com.ECS.client.jax.ItemSearchResponse;
import com.ECS.client.jax.Items;
public class Client {
public static void main(String[] args) {
String secretKey = <my-secret-key>;
String awsKey = <my-aws-key>;
System.out.println("API Test started");
AWSECommerceService service = new AWSECommerceService();
service.setHandlerResolver(new AwsHandlerResolver(
secretKey)); // important
AWSECommerceServicePortType port = service.getAWSECommerceServicePort();
// Get the operation object:
com.ECS.client.jax.ItemSearchRequest itemRequest = new com.ECS.client.jax.ItemSearchRequest();
// Fill in the request object:
itemRequest.setSearchIndex("Books");
itemRequest.setKeywords("Star Wars");
// itemRequest.setVersion("2011-08-01");
com.ECS.client.jax.ItemSearch ItemElement = new com.ECS.client.jax.ItemSearch();
ItemElement.setAWSAccessKeyId(awsKey);
ItemElement.getRequest().add(itemRequest);
// Call the Web service operation and store the response
// in the response object:
com.ECS.client.jax.ItemSearchResponse response = port
.itemSearch(ItemElement);
String r = response.toString();
System.out.println("response: " + r);
for (Items itemList : response.getItems()) {
System.out.println(itemList);
for (Item item : itemList.getItem()) {
System.out.println(item);
}
}
System.out.println("API Test stopped");
}
}
Here is what I get back.. I was hoping to see some Star Wars books available on Amazon dumped out to my console :-/:
API Test started
response: com.ECS.client.jax.ItemSearchResponse#7a6769ea
com.ECS.client.jax.Items#1b5ac06e
API Test stopped
What am I doing wrong (Note that no "item" in the second for loop is being printed out, because its empty)? How can I troubleshoot this or get relevant error information?

I don't use the SOAP API but your Bounty requirements didn't state that it had to use SOAP only that you wanted to call Amazon and get results. So, I'll post this working example using the REST API which will at least fulfill your stated requirements:
I would like some working example code that hits the amazon server and returns results
You'll need to download the following to fulfill the signature requirements:
http://associates-amazon.s3.amazonaws.com/signed-requests/samples/amazon-product-advt-api-sample-java-query.zip
Unzip it and grab the com.amazon.advertising.api.sample.SignedRequestsHelper.java file and put it directly into your project. This code is used to sign the request.
You'll also need to download Apache Commons Codec 1.3 from the following and add it to your classpath i.e. add it to your project's library. Note that this is the only version of Codec that will work with the above class (SignedRequestsHelper)
http://archive.apache.org/dist/commons/codec/binaries/commons-codec-1.3.zip
Now you can copy and paste the following making sure to replace your.pkg.here with the proper package name and replace the SECRET and the KEY properties:
package your.pkg.here;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class Main {
private static final String SECRET_KEY = "<YOUR_SECRET_KEY>";
private static final String AWS_KEY = "<YOUR_KEY>";
public static void main(String[] args) {
SignedRequestsHelper helper = SignedRequestsHelper.getInstance("ecs.amazonaws.com", AWS_KEY, SECRET_KEY);
Map<String, String> params = new HashMap<String, String>();
params.put("Service", "AWSECommerceService");
params.put("Version", "2009-03-31");
params.put("Operation", "ItemLookup");
params.put("ItemId", "1451648537");
params.put("ResponseGroup", "Large");
String url = helper.sign(params);
try {
Document response = getResponse(url);
printResponse(response);
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static Document getResponse(String url) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(url);
return doc;
}
private static void printResponse(Document doc) throws TransformerException, FileNotFoundException {
Transformer trans = TransformerFactory.newInstance().newTransformer();
Properties props = new Properties();
props.put(OutputKeys.INDENT, "yes");
trans.setOutputProperties(props);
StreamResult res = new StreamResult(new StringWriter());
DOMSource src = new DOMSource(doc);
trans.transform(src, res);
String toString = res.getWriter().toString();
System.out.println(toString);
}
}
As you can see this is much simpler to setup and use than the SOAP API. If you don't have a specific requirement for using the SOAP API then I would highly recommend that you use the REST API instead.
One of the drawbacks of using the REST API is that the results aren't unmarshaled into objects for you. This could be remedied by creating the required classes based on the wsdl.

This ended up working (I had to add my associateTag to the request):
public class Client {
public static void main(String[] args) {
String secretKey = "<MY_SECRET_KEY>";
String awsKey = "<MY AWS KEY>";
System.out.println("API Test started");
AWSECommerceService service = new AWSECommerceService();
service.setHandlerResolver(new AwsHandlerResolver(secretKey)); // important
AWSECommerceServicePortType port = service.getAWSECommerceServicePort();
// Get the operation object:
com.ECS.client.jax.ItemSearchRequest itemRequest = new com.ECS.client.jax.ItemSearchRequest();
// Fill in the request object:
itemRequest.setSearchIndex("Books");
itemRequest.setKeywords("Star Wars");
itemRequest.getResponseGroup().add("Large");
// itemRequest.getResponseGroup().add("Images");
// itemRequest.setVersion("2011-08-01");
com.ECS.client.jax.ItemSearch ItemElement = new com.ECS.client.jax.ItemSearch();
ItemElement.setAWSAccessKeyId(awsKey);
ItemElement.setAssociateTag("th0426-20");
ItemElement.getRequest().add(itemRequest);
// Call the Web service operation and store the response
// in the response object:
com.ECS.client.jax.ItemSearchResponse response = port
.itemSearch(ItemElement);
String r = response.toString();
System.out.println("response: " + r);
for (Items itemList : response.getItems()) {
System.out.println(itemList);
for (Item itemObj : itemList.getItem()) {
System.out.println(itemObj.getItemAttributes().getTitle()); // Title
System.out.println(itemObj.getDetailPageURL()); // Amazon URL
}
}
System.out.println("API Test stopped");
}
}

It looks like the response object does not override toString(), so if it contains some sort of error response, simply printing it will not tell you what the error response is. You'll need to look at the api for what fields are returned in the response object and individually print those. Either you'll get an obvious error message or you'll have to go back to their documentation to try to figure out what is wrong.

You need to call the get methods on the Item object to retrieve its details, e.g.:
for (Item item : itemList.getItem()) {
System.out.println(item.getItemAttributes().getTitle()); //Title of item
System.out.println(item.getDetailPageURL()); // Amazon URL
//etc
}
If there are any errors you can get them by calling getErrors()
if (response.getOperationRequest().getErrors() != null) {
System.out.println(response.getOperationRequest().getErrors().getError().get(0).getMessage());
}

Related

How to load all the examples in to the #ExampleObject without specifying the ref so its visible in SwaggerUI?

I am developing a simple application where I would like to read the files from a remote URL and add them to the #ExampleObject. I am able to achieve this using CustomClass SchemaFileReader implements OASFilter but the only problem is that I need to manually specify the name of the file in the ref such as #ExampleObject(name = "Example1", ref = "Example1.json").
Since I am reading the URL there can be many files and I do not know the name of all the files so I need an approach where I can add the #ExampleObject dynamically directly without specifying ref. Rather it should read all the data from the examples. Can someone please specify some logic on how to achieve this?
I have posted my complete code on GitHub: https://github.com/Aravinda93/code-with-quarkus.
As of now, I have added manually 2 files to my #ExampleObject by specifying the ref but I need a dynamic approach to add all the 3 files present in the resourses/jsonfiles without providing the ref for all the files individually.
To run the application, please follow the following steps:
Open the terminal for the project and run mvn compile quarkus:dev
Press d in the command line this should open the Swagger-UI.
Select swagger-ui from SmallRye OpenAPI
Expand api/generate and there we will see only 2 files under examples. I need an approach to get all 3 field without specifying the ref for all of them.
After trying some things, finally, this worked for me. Posting here as it can be useful to someone in the future:
Following is my RestControllerResponse:
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Map;
#Path("/api")
public class RestControllerResponse {
#Path("/generate")
#POST
#Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#RequestBody(description = "Testing Example without ref",
content = #Content())
public String generator(final Map<String, Object> input) throws Exception {
return "Hello From Generator Method";
}
}
Following is my SchemaFileReader which has the capability to read all files and respective subfolder with files and get the file contents and add to examples, pass the required URL to the getFolderData method:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.microprofile.openapi.OASFactory;
import org.eclipse.microprofile.openapi.OASFilter;
import org.eclipse.microprofile.openapi.models.Components;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.eclipse.microprofile.openapi.models.examples.Example;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class SchemaFileReader implements OASFilter {
private final ObjectMapper objectMapper = new ObjectMapper();
private final CloseableHttpClient httpClient = HttpClients.createDefault();
#Override
public void filterOpenAPI(OpenAPI openAPI) {
Components defaultComponents = OASFactory.createComponents();
if (openAPI.getComponents() == null) {
openAPI.setComponents(defaultComponents);
}
try {
//generateExamples().forEach(openAPI.getComponents()::addExample);
generateExamples().entrySet().forEach(ex -> openAPI.getPaths().getPathItem("/api/generate").getPOST().getRequestBody().getContent().getMediaType(MediaType.APPLICATION_JSON).addExample(ex.getKey(), ex.getValue()));
} catch (Exception e) {
e.printStackTrace();
}
}
Map<String, Example> generateExamples() throws Exception {
final Map<String, Example> examples = new LinkedHashMap<>();
getFolderData(examples, "PLACE YOUR URL HERE");
//getExamples(examples);
return examples;
}
//If user has provided the folder then recursively loop over it to get the files and their contents
private void getFolderData(final Map<String, Example> examples, final String inputURL) throws IOException {
//Make the request to provided folder path and get the folder/files from it.
final CloseableHttpResponse folderResponse = httpClient.execute(new HttpGet(inputURL));
final String responseBody = EntityUtils.toString(folderResponse.getEntity(), StandardCharsets.UTF_8);
//If the folder API request provides valid response and contains the list of files or folders then loop over it else its plain/text with direct contents
if (folderResponse.getStatusLine().getStatusCode() == 200 && ContentType.get(folderResponse.getEntity()).toString().equalsIgnoreCase("application/json; charset=utf-8")) {
final JSONArray jsonArray = new JSONArray(responseBody);
jsonArray.forEach(item -> {
final JSONObject obj = (JSONObject) item;
if (obj.getString("type").equalsIgnoreCase("file")) {
//Make request to each file in the GitHub folder and obtain its contents
try {
final CloseableHttpResponse fileResponse = httpClient.execute(new HttpGet(obj.getString("download_url")));
//If the response code is 200 then add the contents to Example
if (fileResponse.getStatusLine().getStatusCode() == 200) {
final String fileResponseBody = EntityUtils.toString(fileResponse.getEntity(), StandardCharsets.UTF_8);
if (obj.getString("download_url").contains(".json")) {
examples.put(obj.getString("name"), OASFactory.createExample().value(objectMapper.readValue(fileResponseBody, ObjectNode.class)));
} else if (obj.getString("download_url").contains(".xml")) {
examples.put(obj.getString("name"), OASFactory.createExample().value(fileResponseBody));
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
getFolderData(examples, obj.getString("url"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else if (folderResponse.getStatusLine().getStatusCode() == 200 && ContentType.get(folderResponse.getEntity()).toString().equalsIgnoreCase("text/plain; charset=utf-8")) {
//if direct file provided then add its content
examples.put(inputURL.substring(inputURL.lastIndexOf("/")), OASFactory.createExample().value(objectMapper.readValue(responseBody, ObjectNode.class)));
}
}
}

When using service account impersonation, when calling export on Google Docs using v3 API, viewedByMeTime timestamp is updated

I am using a service account to access google doc files of users in my enterprise google account using impersonation.
See:
https://developers.google.com/drive/api/v3/about-auth#OAuth2Authorizing
So far so good.
Then, I need to download contents of Google Docs.
When calling Google Drive API to download the contents of a Google Doc, the documentation says to run the following:
https://developers.google.com/drive/api/v3/manage-downloads
Here is a java program that should reproduce the problem:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.SecurityUtils;
import com.google.api.services.drive.Drive;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
public class FetchGoogleDocContentsWithServiceAccount {
static int readTimeout = 60000;
static int connectTimeout = 60000;
static String serviceAccountId = "";
static String serviceAccountEmail = "";
static String serviceAccountPrivateKeyFile = "";
static String serviceAccountPrivateKeyFilePassword = "";
static String fileId = "";
static JacksonFactory jacksonFactory = new JacksonFactory();
static NetHttpTransport httpTransport = new NetHttpTransport();
static List<String> googleScopeList = Arrays.asList("https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/admin.directory.group.readonly",
"https://www.googleapis.com/auth/admin.directory.user.alias.readonly",
"https://www.googleapis.com/auth/admin.directory.group", "https://www.googleapis.com/auth/admin.directory.user",
"https://www.googleapis.com/auth/drive");
public static void main(String[] args) throws Exception {
Drive drive = (new Drive.Builder(httpTransport,
jacksonFactory,
getRequestInitializer(getGoogleCredentials())))
.setApplicationName("Sample app").build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
drive.files().export(fileId, "application/vnd.google-apps.document")
.executeMediaAndDownloadTo(baos);
System.out.println(baos.toString("UTF-8"));
}
public static HttpRequestInitializer getRequestInitializer(final GoogleCredential requestInitializer) {
return httpRequest -> {
requestInitializer.initialize(httpRequest);
httpRequest.setConnectTimeout(readTimeout);
httpRequest.setReadTimeout(connectTimeout);
};
}
public static GoogleCredential getGoogleCredentials() {
GoogleCredential credential;
try {
GoogleCredential.Builder b = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jacksonFactory).setServiceAccountId(serviceAccountId)
.setServiceAccountPrivateKey(SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
new FileInputStream(new File(serviceAccountPrivateKeyFile)), serviceAccountPrivateKeyFilePassword,
"privatekey", serviceAccountPrivateKeyFilePassword))
.setServiceAccountScopes(googleScopeList);
if (serviceAccountEmail != null) {
b = b.setServiceAccountUser(serviceAccountEmail);
}
credential = b.build();
} catch (IOException | GeneralSecurityException e1) {
throw new RuntimeException("Could not build client secrets", e1);
}
return credential;
}
}
When I have performed this operation, we are seeing that the viewedByMeTime field is actually being updated as the impersonated user.
This is not good, because now people think someone might have stolen access to their account. They are going to open tickets with the security team.
Is this expected? How can I make this stop? Is there another method in the API I can call to download the google docs without updating this timestamp?
Also opened a ticket on the github for the google drive java sdk: https://github.com/googleapis/google-api-java-client-services/issues/3160
Updating the viewedByMeTime field upon calling the endpoint is indeed intended behaviour. Any action performed through the API is considered the same way as if the user did that action manually (i.e. that field would be updated too when the user visits the document through the UI).
By using domain-wise delegation (or "user impersonation"), you have no way to avoid this issue.
The only workaround would be to give the service account access to this file, and let it export the file without domain-wide delegation. The viewedByMeTime field will be updated only for the service account itself, but not for the original owner of that file (or any other user having access to it).

AWS Email Template usage using java (bulk email)

Can some one give me a direction how can I implement this aws email template tutorial by a java code? Through java code I want to set this AWS Email Template and through java only I want to set the parameter values to the template and through java only I want to send the email.
I cant find any tutorial or direction from which I can translate above requests in java code.
The "code" in your link is actually just some JSON templates for sending and formatting email, and a few calls to an AWS command line tool. If you need to make AWS send email calls from a Java process then you need to take a look at:
The SES API
The Javadoc for the Java client lib
I am able to code it successfully. Pasting the example code here.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.BulkEmailDestination;
import com.amazonaws.services.simpleemail.model.BulkEmailDestinationStatus;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.SendBulkTemplatedEmailRequest;
import com.amazonaws.services.simpleemail.model.SendBulkTemplatedEmailResult;
public class AmazonSESSample2 {
public static void main(String[] args) throws IOException {
String accessKeyId = "accessKeyId";
String secretKeyId = "secretKeyId";
String region = "us-east-1";
List<BulkEmailDestination> listBulkEmailDestination = null;
SendBulkTemplatedEmailRequest sendBulkTemplatedEmailRequest = null;
try {
AmazonSimpleEmailService client = getAmazonSESClient(accessKeyId, secretKeyId, region);
listBulkEmailDestination = new ArrayList<>();
for(String email : getRecievers()) {
String replacementData="{"
+ "\"FULL_NAME\":\"AAA BBB\","
+ "\"USERNAME\":\""+email+"\","
+ "}";
BulkEmailDestination bulkEmailDestination = new BulkEmailDestination();
bulkEmailDestination.setDestination(new Destination(Arrays.asList(email)));
bulkEmailDestination.setReplacementTemplateData(replacementData);
listBulkEmailDestination.add(bulkEmailDestination);
}
sendBulkTemplatedEmailRequest = new SendBulkTemplatedEmailRequest();
sendBulkTemplatedEmailRequest.setSource("noreply#mydomain.com");
sendBulkTemplatedEmailRequest.setTemplate("welcome-email-en_GB-v1");
sendBulkTemplatedEmailRequest.setDefaultTemplateData("{\"FULL_NAME\":\"friend\", \"USERNAME\":\"unknown\"}");
sendBulkTemplatedEmailRequest.setDestinations(listBulkEmailDestination);
SendBulkTemplatedEmailResult res = client.sendBulkTemplatedEmail(sendBulkTemplatedEmailRequest);
System.out.println("======================================");
System.out.println(res.getSdkResponseMetadata());
System.out.println("======================================");
for(BulkEmailDestinationStatus status : res.getStatus()) {
System.out.println(status.getStatus());
System.out.println(status.getError());
System.out.println(status.getMessageId());
}
} catch (Exception ex) {
System.out.println("The email was not sent. Error message: " + ex.getMessage());
ex.printStackTrace();
}
}
public static List<String> getRecievers() {
ArrayList<String> list = new ArrayList<>();
list.add("aaa+1#gmail.com");
list.add("aaa+2#gmail.com");
list.add("aaa+3#gmail.com");
list.add("aaa+4#gmail.com");
return list;
}
public static AmazonSimpleEmailService getAmazonSESClient(String accessKeyId, String secretKeyId, String region) {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKeyId, secretKeyId);
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withRegion(region)
.build();
return client;
}
}

ETrade Java API issue - previewEquityOrder and previewOptionOrder throw an ETWSException

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.

Parsing nested JSON nodes to POJOs using Google Http Java Client

For example I have a response with the following JSON:
{
response: {
id: 20,
name: Stas
}
}
And I want to parse it to the following object:
class User {
private int id;
private String name;
}
How to skip the response node?
I use Google Http Java Client and it will be good if someone will answer how to do it there.
How will this lines have changed?
request.setParser(new JacksonFactory().createJsonObjectParser());
return request.execute().parseAs(getResultType());
You can now implement this in one step:
new JsonObjectParser.Builder(jsonFactory)
.setWrapperKeys(Arrays.asList("response"))
.build()
http://javadoc.google-http-java-client.googlecode.com/hg/1.15.0-rc/index.html
I do not know the Google Http Java Client, but if you can access the Jackson ObjectMapper you could do the following:
1.) Enable root unwrapping:
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
2.) Add annotation to User.class:
#JsonRootName("response")
class User {
…
}
I hope you can use this approach.
Edit: I dug through the google-http-java-client API and have come to the conclusion that you cannot access the ObjectMapper directly. In order to use the full power of Jackson you would have to write your own implementation of JsonObjectParser to wrap a 'real' Jackson parser. Sorry about that, maybe someone else could come up with a better solution.
I didn't find a native way (for this library) to solve my task. As a result I solved this problem by extending the functionality of JsonObjectParser. It entails expanding of the JacksonFactory, but it's a final class, so I used aggregation.
I wrote the following classes:
JacksonFilteringFactory
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
public class JacksonFilteringFactory {
private final JacksonFactory factory = new JacksonFactory();
public JsonObjectParser createJsonObjectParser(String filteringNode) {
return new FilteringJsonObjectParser(factory, filteringNode);
}
}
FilteringJsonObjectParser
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.vkredmessenger.AppController;
import com.vkredmessenger.util.StringUtils;
public class FilteringJsonObjectParser extends JsonObjectParser {
private String mFilteringNode;
public FilteringJsonObjectParser(JsonFactory jsonFactory,
String filteringNode) {
super(jsonFactory);
mFilteringNode = filteringNode;
}
#Override
public Object parseAndClose(InputStream in,
Charset charset, Type dataType)
throws IOException {
String originalResponse =
StringUtils.convertStreamToString(in, charset);
String response = null;
try {
JSONTokener tokener = new JSONTokener(originalResponse);
JSONObject originalResponseObject =
(JSONObject) tokener.nextValue();
JSONObject responseObject =
originalResponseObject.getJSONObject(mFilteringNode);
response = responseObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
InputStream filteredIn =
new ByteArrayInputStream(response.getBytes(charset));
return super.parseAndClose(filteredIn, charset, dataType);
}
}
So, for example from my question, the result parsing code will be the following:
request.setParser(new JacksonFilteringFactory().createJsonObjectParser("response"));
return request.execute().parseAs(getResultType());

Categories

Resources