/*
© 2011-2013 eBay Inc., All Rights Reserved
Licensed under CDDL 1.0 - http://opensource.org/licenses/cddl1.php
*/
import com.ebay.sdk.*;
import com.ebay.sdk.util.*;
import com.ebay.soap.eBLBaseComponents.*;
import java.io.*;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.bind.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.w3c.dom.Node;
import org.slf4j.*;
public class UploadHostPicturesExternal {
private static String JAXB_PACKAGE_NAME = "com.ebay.soap.eBLBaseComponents";
private static String USERTOKEN = "YOUR TOKEN";
private static String SERVERURL = "https://api.sandbox.ebay.com/ws/api.dll";
private static final String EBAY_NAMESPACE = "urn:ebay:apis:eBLBaseComponents";
private static final Logger log = LoggerFactory.getLogger(UploadHostPicturesExternal.class);
private static ApiContext apiContext = new ApiContext();
private static ApiLogging apiLogging = new ApiLogging();
private static String pictureURL[] = {"YOUR IMAGE URL"};
public UploadHostPicturesExternal() {
ApiCredential cred = new ApiCredential();
apiContext.setApiCredential(cred);
//set api call credential
apiContext.getApiCredential().seteBayToken(USERTOKEN);
//enable api logging
apiContext.setApiLogging(apiLogging);
//register EPS server URL in ApiContext object
apiContext.setEpsServerUrl(SERVERURL);
}
public static void main(String[] args) {
UploadHostPicturesExternal sample = new UploadHostPicturesExternal();
try {
// create and initial an UploadSiteHostedPicturesRequestType object
UploadSiteHostedPicturesRequestType requestObj = new UploadSiteHostedPicturesRequestType();
requestObj.setWarningLevel(WarningLevelCodeType.HIGH);
//set the ExternalPictureURL with the image URL string array
requestObj.setExternalPictureURL(pictureURL);
UploadSiteHostedPicturesResponseType responseObj = sample.upLoadSiteHostedPicture(requestObj);
if (responseObj != null && responseObj instanceof UploadSiteHostedPicturesResponseType) {
UploadSiteHostedPicturesResponseType response = (UploadSiteHostedPicturesResponseType) responseObj;
System.out.println(response.getAck());
System.out.println(response.getBuild());
System.out.println(response.getSiteHostedPictureDetails().getFullURL());
}
} catch (Exception e) {
e.printStackTrace();
}
}
/*
*
*/
public UploadSiteHostedPicturesResponseType upLoadSiteHostedPicture(UploadSiteHostedPicturesRequestType request) {
UploadSiteHostedPicturesResponseType response = null;
try {
Document doc = marshalObject2Xml(request);
//Add eBay API token to the document
addAuthToken(doc);
if (apiLogging != null && apiLogging.isLogSOAPMessages()) {
String formattedReqXmlString = XmlUtil.getXmlStringFromDom(doc);
logMessage("UploadSiteHostedPicturesRequest", formattedReqXmlString);
}
//Convert XML Document to XML String
String requestXmlString = xmlToString(doc);
InputStreamReader inputStream = openConnectionFireRequest(requestXmlString);
// response stream is unmarshalled into a Java content tree
Object returnedObj = unmashalInputStream(inputStream);
if (apiLogging != null && apiLogging.isLogSOAPMessages()) {
Document respDom = XmlUtil.createDom(requestXmlString);
String formattedRespXmlString = XmlUtil.getXmlStringFromDom(respDom);
logMessage("UploadSiteHostedPicturesResponse", formattedRespXmlString);
}
if (returnedObj != null && returnedObj instanceof UploadSiteHostedPicturesResponseType) {
response = (UploadSiteHostedPicturesResponseType) returnedObj;
}
} catch (Exception e) {
//handle your exception here
}
return response;
}
/*
* marshal UploadSiteHostedPicturesRequestType object to Document object
*
*/
private Document marshalObject2Xml(UploadSiteHostedPicturesRequestType requestobj) throws Exception {
JAXBContext jc = JAXBContext.newInstance(JAXB_PACKAGE_NAME);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
ObjectFactory of = new ObjectFactory();
JAXBElement<UploadSiteHostedPicturesRequestType> requestElement = of.createUploadSiteHostedPicturesRequest(requestobj);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
m.marshal(requestElement, doc);
return doc;
}
/*
* open SSL https connection and send the request xml data
*
*/
public InputStreamReader openConnectionFireRequest(String XmlFileName) throws Exception {
URL url = new URL(SERVERURL);
// open SSL https connection
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml");
// required headers
conn.setRequestProperty("X-EBAY-API-COMPATIBILITY-LEVEL", "717");
conn.setRequestProperty("X-EBAY-API-CALL-NAME", "UploadSiteHostedPictures");
conn.setRequestProperty("X-EBAY-API-SITEID", "0");
PrintWriter output = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
System.out.println(conn.getURL());
System.out.println(XmlFileName);
output.println(XmlFileName);
output.close();
conn.connect();
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
return isr;
}
/*
*
*/
public Object unmashalInputStream(InputStreamReader isr) {
Object returnedObj = null;
try {
int c = 0;
String uploadSiteHostedPictureResponse = "uploadSiteHostedPictureResponse.xml";
OutputStream f = new FileOutputStream(uploadSiteHostedPictureResponse);
while ((c = isr.read()) > -1) {
f.write(c);
}
f.close();
String responseXML = convertFileContent2String(uploadSiteHostedPictureResponse);
System.out.println(responseXML);
InputStream input = new ByteArrayInputStream(responseXML.getBytes());
JAXBContext context = JAXBContext.newInstance(JAXB_PACKAGE_NAME);
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement<Object> poe = (JAXBElement) unmarshaller.unmarshal(input);//(new
returnedObj = poe.getValue();
isr.close();
} catch (Exception e) {
e.printStackTrace();
}
return returnedObj;
}
private static String convertFileContent2String(String fileName) {
String fileContentInString = "";
try {
File soapFile = new File(fileName);
byte fileContent[] = new byte[(int) soapFile.length()];
FileInputStream soapFileIS = new FileInputStream(soapFile);
soapFileIS.read(fileContent, 0, fileContent.length);
fileContentInString = new String(fileContent);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return fileContentInString;
}
/**
* Add eBay API authentication token to the XML Document
* @param doc, XML Document
* @throws SdkException
*/
private void addAuthToken(Document doc) throws SdkException {
Node node = XmlUtil.getChildByName(doc, "UploadSiteHostedPicturesRequest");
Node requesterCredentials = XmlUtil.appendChildNode(doc, EBAY_NAMESPACE, node, "RequesterCredentials");
String tokenString = this.apiContext.getApiCredential().geteBayToken();
if (tokenString == null || tokenString.length() == 0) {
throw new SdkException("No Token Found!!!");
} else {
XmlUtil.appendChildNode(doc, requesterCredentials, "eBayAuthToken", tokenString);
}
}
/**
* Convert an XML Document to an XML String
* @param doc, XML Document
* @return string representation of the XML document
* @throws TransformerException
*/
private String xmlToString(Document doc) throws TransformerException {
Source source = new DOMSource(doc);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
return stringWriter.getBuffer().toString();
}
private void logMessage(String msgName, String msgStr) {
String reqTime = eBayUtil.toAPITimeString(java.util.Calendar.getInstance().getTime());
log.info(java.text.MessageFormat.format("[{0}][{1}][{2}]\n",
new Object[]{msgName,
reqTime,
apiContext.getEpsServerUrl()
}));
log.info(msgStr);
}
|