Magento XML-RPC API - Create Shipment From Java - java

Im trying to create shipments for magento orders from my third party app using the XML-RPC API. Everything works great when i make the call to "sales_order_shipment.create" with just the order increment id, but if i try making the same call with both an order increment id and a set of items and quantities, it will say "Requested order not exists." Why is that? what im doing wrong? what type should be the itemQuantity)
heres my code
package magentoapiclient;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
public class XMLRPCAPIClient {
public static void main(String[] args) {
createShipment("100000005", 5, 1.0);
}
public static XmlRpcClient prepareClient() throws MalformedURLException {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("myHost"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
client.setTypeFactory(new MyTypeFactory(client));
return client;
}
public static void createShipment(String orderIncrementId, int itemId, double quantity) {
try {
XmlRpcClient client = prepareClient();
String sessionId = login("myUser", "myKey", client);
System.out.println(sessionId);
Object[] request = {orderIncrementId, new HashMap()};
client.execute("call", new Object[]{sessionId, "sales_order_shipment.create", request});
endSession(sessionId, client);
} catch (XmlRpcException | MalformedURLException ex) {
Logger.getLogger(XMLRPCAPIClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static String login(String user, String password, XmlRpcClient client) throws XmlRpcException {
String sessionId = (String) client.execute("login", new Object[]{user, password});
return sessionId;
}
public static void endSession(String sessionToken, XmlRpcClient client) throws XmlRpcException {
client.execute("endSession", new Object[]{sessionToken});
}
}
As you see in the line
Object[] request = {orderIncrementId, new HashMap()};
i try sending a hashMap that actually should contain the order item id and quantity. Ive also tried sending an array of objects and it doesnt work for any of them. What sould be there instead then if neither a Map or an Array is available?
Thank you for your help

Order Id and Order increment id are different. You should send order increment id.
http://www.magentocommerce.com/api/soap/sales/salesOrder/sales_order.info.html

Related

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

Voice call using twilo in web application

we are trying to use voice call for our web application.
we tried using below code:
public class MakeCall {
public static final String ACCOUNT_SID = "ACbXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String AUTH_TOKEN = "545XXXXXXXXXXXXXXXXXXXXXXXX";
public static final String TWILIO_NUMBER = "+185XXXXXXXXX";
public static void main(String[] args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Account mainAccount = client.getAccount();
CallFactory callFactory = mainAccount.getCallFactory();
Map<String, String> callParams = new HashMap<String, String>();
callParams.put("From",TWILIO_NUMBER);
callParams.put("To", "+919014512394");
callParams.put("Url", "http://ahoy.twilio.com/voice/api/demo");
Call call = callFactory.create(callParams);
System.out.println(call.getSid());
}
}
From above code,we are able to hear twilio customer voice i.e,Welcome to the Twilio voice demo app. Press 1 to hear the weather forecast tomorrow. Press 2 to hear a song. Press 3 to create or join a conference bridge. Press 4 to record your voice for 5 seconds.
Actually we want to speak with other mobile number by calling from twilio number
Basically we are new to twilio API.Plz guide us
Advance thanks
Twilio developer evangelist here.
The code you've written will initiate a new call when you call that endpoint. If you want to initiate a new call and then connect to another number so the two of you can talk, you need to change that slightly do it Dials the number for you.
Here's afull working example that shows you how to pick who you want to speak with, and then dials that person.
package com.twilio;
import com.twilio.twiml.Gather;
import com.twilio.twiml.Method;
import com.twilio.twiml.Play;
import com.twilio.twiml.Say;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
public class TwilioServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Create a dict of people we know.
HashMap<String, String> callers = new HashMap<String, String>();
callers.put("+14158675309", "Curious George");
callers.put("+14158675310", "Boots");
callers.put("+14158675311", "Virgil");
String fromNumber = request.getParameter("From");
String knownCaller = callers.get(fromNumber);
String message;
if (knownCaller == null) {
// Use a generic message
message = "Hello Monkey";
} else {
// Use the caller's name
message = "Hello " + knownCaller;
}
// Create a TwiML response and add our friendly message.
VoiceResponse twiml = new VoiceResponse.Builder()
.say(new Say.Builder(message).build())
// Play an MP3 for incoming callers.
.play(new Play.Builder("http://demo.twilio.com/hellomonkey/monkey.mp3").build())
.gather(new Gather.Builder()
.action("/handle-key")
.method(Method.POST)
.numDigits(1)
.say(new Say
.Builder("To speak to a real monkey, press 1. Press any other key to start over.")
.build())
.build()
)
.build();
response.setContentType("application/xml");
try {
response.getWriter().print(twiml.toXml());
} catch (TwiMLException e) {
e.printStackTrace();
}
}
}
You start off with a HashMap containing all your telephone numbers
Upon pressing a number, the /handle-key endpoint is called. This is where the logic for dialing another number happens
package com.twilio;
import com.twilio.twiml.Dial;
import com.twilio.twiml.Number;
import com.twilio.twiml.Say;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class TwilioHandleKeyServlet extends HttpServlet {
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
String digits = request.getParameter("Digits");
VoiceResponse twiml;
// Check if the user pressed "1" on their phone
if (digits != null && digits.equals("1")) {
// Connect 310 555 1212 to the incoming caller.
Number number = new Number.Builder("+13105551212").build();
Dial dial = new Dial.Builder().number(number).build();
// If the above dial failed, say an error message.
Say say = new Say.Builder("The call failed, or the remote party hung up. Goodbye.").build();
twiml = new VoiceResponse.Builder().dial(dial).say(say).build();
} else {
// If they didn't press 1, redirect them to the TwilioServlet
response.sendRedirect("/twiml");
return;
}
response.setContentType("application/xml");
try {
response.getWriter().print(twiml.toXml());
} catch (TwiMLException e) {
e.printStackTrace();
}
}
}
You can read a full explanation of this and find other examples in this quickstart.
Hope this helps you out.

How to call Fedora Commons findObjects method (web service)

I'm trying to make a search through the Fedora Commons web service. I'm interested in the findObjects method. How can I make a search in Java equal to the example described on the findObjects syntax documentation.
I'm particularly interested in this type of request:
http://localhost:8080/fedora/search?terms=fedora&pid=true&title=true
I'll attach some code, I have a class that can call my Fedora service already.
package test.fedora;
import info.fedora.definitions._1._0.types.DatastreamDef;
import info.fedora.definitions._1._0.types.MIMETypedStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.ws.BindingProvider;
import org.w3c.dom.Document;
public class FedoraAccessor {
info.fedora.definitions._1._0.api.FedoraAPIAService service;
info.fedora.definitions._1._0.api.FedoraAPIA port;
final String username = "xxxx";
final String password = "yyyy";
public FedoraAClient() {
service = new info.fedora.definitions._1._0.api.FedoraAPIAService();
port = service.getFedoraAPIAServiceHTTPPort();
((BindingProvider) port.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
}
public List findObjects() {
//how?
}
public List<DatastreamDef> listDatastreams(String pid, String asOfTime) {
List<DatastreamDef> result = null;
try {
result = port.listDatastreams(pid, asOfTime);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
It's easier using the client from mediashelf (http://mediashelf.github.com/fedora-client/). Here's an example searching for objects containing the string foobar in the title:
#Test
public void doTest() throws FedoraClientException {
connect();
FindObjectsResponse response = null;
response = findObjects().pid().title().query("title~foobar").execute(fedoraClient);
List<String> pids = response.getPids();
List<String> titles = new ArrayList<String>();
for (String pid : pids) {
titles.add(response.getObjectField(pid, "title").get(0));
}
assertEquals(7, titles.size());
}

JGroups: send(null, null, Message)vs send(Address, null, Message)

I've written simple test for using JGroups.
There are two simple applications like this
import org.jgroups.*;
import org.jgroups.conf.ConfiguratorFactory;
import org.jgroups.conf.ProtocolConfiguration;
import org.jgroups.conf.ProtocolStackConfigurator;
import java.util.List;
/**
* #author Sergii.Zagriichuk
*/
public class Test {
public static void main(String[] args) throws Exception {
JChannel ch = new JChannel();
ch.setReceiver(new ReceiverAdapter() {
public void receive(Message msg) {
System.out.println("received message " + msg.getObject());
}
});
ch.connect("one");
}
}
and this
package com.datacradle.example;
import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.conf.ConfiguratorFactory;
import org.jgroups.conf.ProtocolConfiguration;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.SingletonAddress;
import org.jgroups.util.Util;
import java.util.List;
/**
* #author Sergii.Zagriichuk
*/
public class Test {
void start(String props) throws Exception {
JChannel chanel = new JChannel();
String line = "Test message";
chanel.connect("one");
// Message msg = new Message(null, null, new TestData(line, 1111, line + " Test suffix"));
Message msg = new Message(new IpAddress("fe33:0:0:0:1986:ba23:d939:f226%12",55435) , null, new TestData(line,1111,line+" sdfasdfasdfasdfasdfa"));
chanel.send(msg);
}
public static void main(final String[] args) throws Exception {
new Test().start(null);
}
}
So, If I use this style for creating message
Message msg = new Message(null, null, new TestData(line, 1111, line + " Test suffix"));
I will receive just a one message(this is for all subscribers in current group),
but if I use this style
Message msg = new Message(new IpAddress("fe33:0:0:0:1986:ba23:d939:f226%12",55435) , null, new TestData(line,1111,line+" sdfasdfasdfasdfasdfa"));
I will receive a lot of messages like in a loop (this is for one dist address)
What is the problem or I should added some additional parameters?
P.S, JGroups 3.0.0 RC1
Thanks.
You should not create a member address using the IpAddress class, as this is something that's opaque. I suggest fetch the target address from a view, e.g.
List<Address> members=channel.getView().getMembers();
Address target=members.get(0);
Message msg=new Message(target, null, "hello");
channel.send(msg);

HTTP Request Object

Is there an object within the standard Java SE that can accept a HTTP request from a socket? I have found how to create and send one, however I have not found a way to retrieve a HTTP object from a socket. I can create one my self, but I would rather rely on a heavily tested object.
This seems like something that would be readily available given the structure of JSP.
There is a small HTTP server in the Java 6 SDK (not sure if it will be in the JRE or in non-Sun JVM's).
From http://www.java2s.com/Code/Java/JDK-6/LightweightHTTPServer.htm :
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class HttpServerDemo {
public static void main(String[] args) throws IOException {
InetSocketAddress addr = new InetSocketAddress(8080);
HttpServer server = HttpServer.create(addr, 0);
server.createContext("/", new MyHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8080" );
}
}
class MyHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
Headers requestHeaders = exchange.getRequestHeaders();
Set<String> keySet = requestHeaders.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext()) {
String key = iter.next();
List values = requestHeaders.get(key);
String s = key + " = " + values.toString() + "\n";
responseBody.write(s.getBytes());
}
responseBody.close();
}
}
}
Yeah, you make a new HTTP Request object from what you accept on the socket. What you do after that is up to you, but it should probably involve an HTTP Response.
import java.io.*;
import java.net.*;
import java.util.*;
public final class WebServer {
public static void main(String args[]) throws Exception {
int PORT = 8080;
ServerSocket listenSocket = new ServerSocket(PORT);
while(true) {
HttpRequest request = new HttpRequest(listenSocket.accept());
Thread thread = new Thread(request);
thread.start();
}
}
}
From: http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=396
There's some more work to be done in the tutorial, but it does look nice.
It looks like you are looking for a Servlet. A servlet is an API that lets you receive and respond to an HTTP request.
Your servlet gets deployed in a container, which is basically the actual Web server that will take care of all the protocol complexities. (The most populare are Tomcat and Jetty)

Categories

Resources