ETrade Java API issue - previewEquityOrder and previewOptionOrder throw an ETWSException - java

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.

Related

Why is withRegion() of AmazonSNSClientBuilder not visible?

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.

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;
}
}

Call REST Api from VB.Net WPF application

I have this sample code written in Java that explains how to call a method of a REST Api:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apac he.commons.io.FileUtils;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
public class Test {
public static void main(String[] args) {
String alias = "ABCD";
String pin = "012345";
String originFileName = "C:\file.pdf";
String destinationFilename = "C:\file2.pdf";
String urlService = "https://serviceUrl";
Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
FormDataMultiPart form = new FormDataMultiPart();
form.field("pin", pin);
form.bodyPart(new FileDataBodyPart("content", new File(originFileName)));
Response response = client.target(urlService).path("/auto/action/name/" + alias).request(MediaType.MULTIPART_FORM_DATA).post(Entity.entity(form, form.getMediaType()));
if (response.getStatus() == 200) {
InputStream file = response.readEntity(InputStream.class);
File targetFile = new File(destinationFilename);
try {
FileUtils.copyInputStreamToFile(file, targetFile);
System.out.print("Success");
} catch (IOException e) {
e.printStackTrace();
System.out.print("Error");
}
} else {
System.out.print("Error:" + response.readEntity(String.class));
}
}
}
In my application I've converted it to something like this:
Dim userAlias As String = "ABCD"
Dim pin As HttpContent = New StringContent("012345")
Dim content As HttpContent = New StreamContent(File.OpenRead(originFileName))
Using client = New HttpClient()
client.BaseAddress = New Uri(urlService)
Using formData = New MultipartFormDataContent()
formData.Add(pinCode, "pin", "pin")
formData.Add(content, "test", "test")
Dim response = client.PostAsync("/auto/sign/pades/" + userAlias, formData).Result
If response.StatusCode = 200 Then
Return response.Content.ReadAsStreamAsync().Result
Else
MessageBox.Show(response.ReasonPhrase)
Return Nothing
End If
End Using
End Using
As a result I get a 500 Internal Server Error.
I checked the service url and it's correct, so I guess I'm doing something wrong in the MultipartFormDataContent creation.
I found out that the error was caused by a typo in the name of the parameter I was uploading.
The way I created the MultipartFormDataContent was actually correct.
Thanks to #Chillzy for the suggestion that made me rewrite my code finding the typo.

Softlayer JAVA API sample to order "Hourly/Pre-set Configuration Bare Metal Servers"

I'm working to get a way to order Bare Metal Server with GPU on Softlayer (hourly) with Java language. There are some fragment messages about this, but I cannot find a whole sample for Java. With current information, I should can get the target at last, but time will be wasted. :(
Where can I get such a Java sample?
see this example:
package restapp.examples;
import java.util.ArrayList;
import java.util.List;
import com.softlayer.api.*;
import com.softlayer.api.service.Hardware;
import com.softlayer.api.service.hardware.Server;
import com.softlayer.api.service.Location;
import com.softlayer.api.service.network.Component;
import com.softlayer.api.service.product.Order;
import com.softlayer.api.service.product.item.Price;
import com.softlayer.api.service.product.pkg.Preset;
import com.google.gson.Gson;
public class OrderPreSetBMS2
{
public static void main( String[] args )
{
String user = "set me";
String apiKey = "set me";
Location datacenter = new Location();
datacenter.setName("ams01");
Preset preset = new Preset();
preset.setKeyName("S1270_8GB_2X1TBSATA_NORAID");
Component networkComponent = new Component();
networkComponent.setMaxSpeed(100L);
Hardware hardware = new Hardware();
hardware.setDatacenter(datacenter);
hardware.setHostname("simplebmi");
hardware.setDomain("test.com");
hardware.setHourlyBillingFlag(true);
hardware.setFixedConfigurationPreset(preset);
List<Component> networkComponents = hardware.getNetworkComponents();
networkComponents.add(networkComponent);
hardware.setOperatingSystemReferenceCode("UBUNTU_14_64");
ApiClient client = new RestApiClient().withCredentials(user, apiKey).withLoggingEnabled();
Hardware.Service hardwareService = Hardware.service(client);
Order.Service orderService = Order.service(client);
try
{
com.softlayer.api.service.container.product.Order productOrder = hardwareService.generateOrderTemplate(hardware);
Gson gson = new Gson();
System.out.println(gson.toJson(productOrder));
com.softlayer.api.service.container.product.Order order = orderService.verifyOrder(productOrder);
Gson gson2 = new Gson();
System.out.println(gson2.toJson(order));
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}
basically that is the idea you need to change the values of the parameters to see the valid configurations you need to call the method http://sldn.softlayer.com/reference/services/SoftLayer_Hardware_Server/getCreateObjectOptions
Also check the documentation of the createObject method http://sldn.softlayer.com/reference/services/softlayer_hardware_server/createobject

Amazon Product Advertising API through Java/SOAP

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());
}

Categories

Resources