How to expose soap webservices as REST API - java

I wrote the below code for making soap webservice call. How do I expose it as REST api? The below code makes a soap call and sends username and password as headers. The output will be from a webservice callled SR_spcWeb_spcServiceStub. Thanks in advance
SR_spcWeb_spcService srv;
try {
srv = new UNINServiceRequestWSLocator().getSR_spcWeb_spcService(new java.net.URL("http://crmuat.un.org//eai_enu/start.swe?SWEExtSource=WebService&SWEExtCmd=Execute&WSSOAP=1"));
((SR_spcWeb_spcServiceStub)srv).setUsername("username");
((SR_spcWeb_spcServiceStub)srv).setPassword("password");
((SR_spcWeb_spcServiceStub)srv).setHeader("http://siebel.com/webservices", "UsernameToken","username");
((SR_spcWeb_spcServiceStub)srv).setHeader("http://siebel.com/webservices", "PasswordText","password");
((SR_spcWeb_spcServiceStub)srv).setHeader("http://siebel.com/webservices", "SessionType","Stateless");
String timeStamp = new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime());
String fullName = firstName+" "+lastName;
System.out.println(timeStamp);
if (filename == null)
{
uploadFileName = "";
extension = "";
encodedString = "";
}
FileAttachment[] fileattachments = { new FileAttachment( uploadFileName, extension, encodedString ) } ;
CreateSR_Input sr=new CreateSR_Input("3-Medium", "",emailAddr,"","Reported By","","","",fullName,"",indexNum, indexNum,
"CRM Tier 3 Support","Incident",emailAddr,"","","Medium","",help_area, timeStamp,"","","","Low", indexNum,
subarea, area,emailAddr,"","", fileattachments,indexNum,requesteditem, "","", "Web",subarea1,
emailAddr, justification,"", "", "3-Medium", location_name, "");
System.out.println("srgroupe + "+ srgroup);
System.out.println("subarea + "+ subarea);
System.out.println("area + "+ area);
System.out.println("requesteditem + "+ requesteditem);
System.out.println("subarea1 + "+ subarea1);
CreateSR_Output srvo;
try {
srvo = srv.createSR(sr);
System.out.println("Got from webservice + "+ srvo.getSRNum());
System.out.println("Got from webservice + "+ srvo.getStatusMsg());
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

Notify client in client server application

first of all, I'm rather new to socket programming to go easy on me ;).
I have a Java program that uses client-server programming to communicate between 1 or more clients and the server. So the clients can send any number of messages to the server where the messages are dealt with and all is fine so far. Now I want to notify the clients of e.g. database changes on the server side. So for example if one client changes for example table A, the other clients should also be notified about this change.
What I have so far is the following (server):
ExecutorService executor = null;
try (ServerSocket socket = new ServerSocket(port);)
{
executor = Executors.newFixedThreadPool(getThreadCount(5));
while(true)
{
Socket clientSocket = socket.accept();
Runnable worker = new PCRequestMapper(clientSocket);
executor.execute(worker);
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
finally
{
if(executor != null)
{
executor.shutdown();
}
}
The request mapper class then looks like this:
public class PCRequestMapper implements Runnable
{
private Socket client = null;
private static Map<Integer, PCRequestData> requestData = null;
public PCRequestMapper(Socket client)
{
this.client = client;
}
#Override
public void run()
{
try (ObjectInputStream in = new ObjectInputStream(
client.getInputStream());
ObjectOutputStream writer = new ObjectOutputStream(
client.getOutputStream());)
{
System.out.println("Thread started in PCRequestHandler with name: "
+ Thread.currentThread().getName());
Object recObj = in.readObject();
// ToDo Do something
PCBaseRequest req = (PCBaseRequest) recObj;
System.out.println("Req type: " + req.getRequestType() + " name: "
+ req.getName());
PCRequestData data = requestData.get(req.getRequestType());
if(data == null)
{
PCException ex = new PCException();
ex.setStackTrace(new Throwable().getStackTrace());
PCBaseReply reply = getErrorReply("No mapped request handler found in services.xml for request: "+req.getRequestType()+" - "+req.getName(),
PCException.NO_MAPPED_HANDLER, ex);
writer.writeObject(reply);
}
else
{
Class<?> c = Class.forName(data.getMappedClass());
Constructor<?> cons = c.getConstructor();
PCIRequestHandler object = (PCIRequestHandler)cons.newInstance();
PCBaseReply reply = object.heyHo(req);
System.out.println("Writing reply: "+reply.getClass());
writer.writeObject(reply);
}
} catch (IOException ioe)
{
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
} catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It basically takes a message (request), maps it to a configured class and then that class performs whatever action needed.
On the client side, I have a class called RequestSender, which is used to send arbitrary requests to the server:
public class PCRequestSender
{
private static int getPort(int defaultPort)
{
final String port = PCConfigHandler.getStringProperty("serverPort");
if (null != port)
{
try
{
return Integer.parseInt(port);
} catch (NumberFormatException e)
{
System.out.println("Value of port property"
+ " is not a valid positive integer [" + port + "]."
+ " Reverting to default [" + defaultPort + "].");
}
}
return defaultPort;
}
public static PCBaseReply sendRequest(PCBaseRequest req)
{
PCBaseReply reply = null;
int port = getPort(8081);
String address = PCConfigHandler.getStringProperty("serverAddress");
try (Socket serverSocket = new Socket(address, port);
ObjectOutputStream out = new ObjectOutputStream(
serverSocket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(
serverSocket.getInputStream());)
{
out.writeObject(req);
Object recObj = in.readObject();
reply = (PCBaseReply) recObj;
System.out.println("Reply: "+reply);
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
return reply;
}
}
Now I'm a bit at a loss, because I would also like to constantly listen to a server socket to catch notifications. Do I need another socket on the server side? Is my setup not tooooo ideal?
I'm helpful for any hints...thanks!

How to connect with Azure cloud (blob storage) using dasein API

Can anyone help me with example or sample? I need to get & put files on the blob storage
I have managed to code following,
try {
CloudProvider provider = (CloudProvider) Class.forName("org.dasein.cloud.azure.Azure").newInstance();
ProviderContext providerContext = new ProviderContext("DEV","West US");
//providerContext.setStorage("");
providerContext.setStorageAccountNumber("mypackages");
providerContext.setStoragePublic("XXX".getBytes());
providerContext.setEndpoint("http://XXX.blob.core.windows.net/");
providerContext.setStorageX509Key("YYY".getBytes());
provider.connect(providerContext, provider);
System.out.println("here "+provider.testContext());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
On executing above code I am getting NPE as below
org.dasein.cloud.InternalException: java.lang.NullPointerException
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:64)
at org.dasein.cloud.azure.AzureMethod.getClient(AzureMethod.java:386)
at org.dasein.cloud.azure.AzureMethod.getAsStream(AzureMethod.java:124)
at org.dasein.cloud.azure.Azure.testContext(Azure.java:258)
at com.gehcit.dasein.App.main(App.java:27)
Caused by: java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:58)
... 4 more
org.dasein.cloud.InternalException: java.lang.NullPointerException
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:64)
at org.dasein.cloud.azure.AzureMethod.getClient(AzureMethod.java:386)
at org.dasein.cloud.azure.AzureMethod.getAsStream(AzureMethod.java:124)
at org.dasein.cloud.azure.Azure.testContext(Azure.java:258)
at com.gehcit.dasein.App.main(App.java:27)
Caused by: java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:58)
... 4 more
This Works for me:
public static final String storageConnectionString =
"DefaultEndpointsProtocol=http;"
+ "AccountName=<Your accountname>;"
+ "AccountKey=<Your key>";
public static synchronized String upLoadSelected(String containername, String path, String directory, String pathPartRemover) {
List<File> filListe = new ArrayList<>();
if (storageConnectionString.isEmpty() != true) {
String respons = "";
try {
CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);
CloudBlobClient serviceClient = account.createCloudBlobClient();
CloudBlobContainer container = null;
String source = "" + path;
container = serviceClient.getContainerReference("" + containername);
container.createIfNotExists();
String temp = "" + directory;
filListe = listf(source);
for (File file : filListe) {
if (file.isDirectory() == true && file.getParentFile().getName().equalsIgnoreCase(temp) != true) {
temp = (temp + "\\" + file.getName());
}
if (file.isDirectory() != true) {
CloudBlockBlob blob = container.getBlockBlobReference("" + file.getCanonicalPath().replace("" + pathPartRemover, ""));
File sourceFile = new File("" + file.getAbsolutePath());
blob.upload(new FileInputStream(sourceFile), sourceFile.length());
}
}
} catch (FileNotFoundException fileNotFoundException) {
respons = respons + "FileNotFoundException encountered: " + fileNotFoundException.getMessage();
} catch (StorageException storageException) {
respons = respons + "StorageException encountered: " + storageException.getMessage();
} catch (IOException e) {
respons = respons + "IOexception encountered: " + e.getMessage();
} catch (URISyntaxException e) {
respons = respons + "URIexception encountered: " + e.getMessage();
} catch (InvalidKeyException ex) {
respons = respons + "InvalidKeyException encountered: " + ex.getMessage();
}
return respons;
}
return "No connection";
}
public static synchronized List<File> listf(String directoryName) {
File directory = new File(directoryName);
List<File> resultList = new ArrayList<>();
File[] fList = directory.listFiles();
resultList.addAll(Arrays.asList(fList));
for (File file : fList) {
if (file.isFile()) {
} else if (file.isDirectory()) {
resultList.addAll(listf(file.getAbsolutePath()));
}
}
return resultList;
}

Java - Jackson to a file

I have a JSON file like this:
{
"Product":
{
"ID": "08-17-96-71-D9-68",
"Licences":
{
"total": 40,
"used": 0,
"remain": 40
}
}
}
I used jackson to convert it to a Java Object and I get all the values (so far, so good).
My problem is that I want to change these values and re-write the JSON file but when I do that, the result is like this:
"{\"Product\":{\"IaD\": \"08-17-96-71-D9-68\",\"Licences\":{\"total\": 40,\"used\": 1,\"remain\": 39}}}"
So when I tried to read it again it gives me an error because it cannot read the first and last character (") and also it reads the \ character.
This is my code:
public class UsingJason {
String theJsonString = "";
ObjectMapper mapper = new ObjectMapper();
public class Product{
Licences lic;
public class Licences{
int total;
int used;
int remain;
}
}
public void readJson(){
if(new File("asset/testJson.json").exists()){
theJsonString = "";
try {
BufferedReader in = new BufferedReader(new FileReader("asset/testJson.json"));
String line;
while ((line = in.readLine()) != null){
theJsonString += line;
}
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("JSON String: "+ theJsonString);
}else{
System.out.println("NO FILE FOUND");
}
JsonNode rootNode = null;
try {
rootNode = mapper.readValue(theJsonString, JsonNode.class);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JsonNode totalNode = rootNode.get("Product").get("Licences").get("total");
JsonNode usedNode = rootNode.get("Product").get("Licences").get("used");
JsonNode remainNode = rootNode.get("Product").get("Licences").get("remain");
JsonNode idStringNode = rootNode.get("Product").get("ID");
// Parse it into a Java object.
try {
int totalObject = mapper.readValue(totalNode, Integer.class);
System.out.println("INTEGER? HAS TO BE... 40: "+totalObject);
String idString = mapper.readValue(idStringNode, String.class);
System.out.println("String? Has to be 08-17-96-71-D9-68: "+idString + " True? "
+ idString.equals("08-17-96-71-D9-68") );
int usedObject = mapper.readValue(usedNode, int.class);
int remainObject = mapper.readValue(remainNode, int.class);
System.out.println("Going to rest 1");
usedObject ++;
remainObject = totalObject - usedObject;
String toJackson = "{\"Product\":{\"I\\D\": \"08-17-96-71-D9-68\",\"Licences\":{\"total\": "+totalObject+",\"used\": "+usedObject+",\"remain\": "+remainObject+"}}}";
System.out.println("String created: " +toJackson);
// THIS toJackson String returns the string without \ and without the "
// IT PRINT THIS: {"Product":{"ID": "08-17-96-71-D9-68","Licences":{"total": 40,"used": 1,"remain": 39}}}
// EXACTLY WHAT I WANT TO Write in the Json file but it writes the \ ..
mapper.writeValue(new File("asset/testJson.json"), toJackson);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anyone tell me what I am doing wrong?
In your code here:
mapper.writeValue(new File("asset/testJson.json"), toJackson);
You are serializing not an object, but the string to the file. I suppose this is the reason why it gets escaped, like any string.
The input value should be an object with your structure.
Something like this:
// Initialize an object
Product myProduct = new Product();
myProduct.lic = new Procuct.Licences();
myProduct.lic.total = totalObject;
myProduct.lic.used = usedObject;
myProduct.lic.remain = remainObject;
// Serialize the object into JSON
mapper.writeValue(new File("asset/testJson.json"), myProduct);

how can i instantiate an object from a compilationunit

I am trying to develop a plugin, which from a java file generate test and tables classes... when I select a Java source, I will be able to have an option "generate class test", the problem that I am recupering the Java file as ICompliationUnit, then I have a method that xtract methods of an object, that's why; I want to parse the IComplilationUnit to an instance of the class which represents, I tried to use Class.forName but it doesn't work , that's the code:
private void write(String dir, ICompilationUnit cu) throws JavaModelException
{
try
{
cu.getCorrespondingResource().getName();
System.out.println("0000000000000" + cu.getJavaProject().getProject().toString());
}
catch (JavaModelException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
String test = cu.getCorrespondingResource().getName();
IPackageDeclaration[] test1 = cu.getPackageDeclarations();
// Need
String[] name = test.split("\\.");
String contentFile = dir + "\\" + name[0] + "content.txt";
GenerateFitnessTable inst = new GenerateFitnessTable();
try
{
String pack = test1[0].toString().substring(7, test1[0].toString().indexOf("[") - 1) + "." + name[0];
#SuppressWarnings("rawtypes")
Class classe = Class.forName(cu.getJavaProject().getProject().toString()
.substring(cu.getJavaProject().getProject().toString().indexOf("/"), cu.getJavaProject().getProject().toString().length())
+ pack);
try
{
classe.newInstance();
}
catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (ClassNotFoundException e1)
{
System.out.print("****************************la classe n'existe pas");
}
try
{
inst.generateContent(cu, contentFile);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this the right way ;)) , i found it :
// nouveau region
region = JavaCore.newRegion();
// ajout de la classe selectionné a cette region
region.add(cu);
if (JavaCore.getGeneratedResources(region, true).length == 0)
{
// bug
}
// recuperer l'url de .class
String url = "file:" + JavaCore.getGeneratedResources(region, true)[0].getLocation().makeAbsolute();
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();
while (data != -1)
{
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();
clas = defineClass(pack.substring(1, pack.length()), classData, 0, classData.length);

sending multiple sms using SMSLib within same process

I am using SMSLib to send sms using my samsung gsm modem.
I created a seperate thread that gets the messages from server in every 20 seconds
and if it gets the message it calls the SendMessage.. here is the code for SendMessage
public class SendMessage {
public boolean doIt(String num, String umsg) {
try {
OutboundNotification outboundNotification = new OutboundNotification();
System.out.println("Example: Send message from a serial gsm modem.");
System.out.println(Library.getLibraryDescription());
System.out.println("Version: " + Library.getLibraryVersion());
SerialModemGateway gateway = new SerialModemGateway("modem.com10","COM10", 115200, "Samsung", "");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin("0000");
gateway.setSmscNumber("+919826012311");
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
System.out.println();
System.out.println("Modem Information:");
System.out.println(" Manufacturer: " + gateway.getManufacturer());
System.out.println(" Model: " + gateway.getModel());
System.out.println(" Serial No: " + gateway.getSerialNo());
System.out.println(" SIM IMSI: " + gateway.getImsi());
System.out.println(" Signal Level: " + gateway.getSignalLevel()+ " dBm");
System.out.println(" Battery Level: " + gateway.getBatteryLevel()+ "%");
System.out.println();
OutboundMessage msg = new OutboundMessage(num, umsg);
Service.getInstance().sendMessage(msg);
System.out.println(msg);
Service.getInstance().stopService();
gateway.stopGateway();
return true;
} catch (GatewayException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SMSLibException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
Service.getInstance().stopService();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GatewayException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SMSLibException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
public class OutboundNotification implements IOutboundMessageNotification {
public void process(AGateway gateway, OutboundMessage msg) {
System.out.println("Outbound handler called from Gateway: "
+ gateway.getGatewayId());
System.out.println(msg);
}
}
}
This code is working great for the first time i call doIt. but If my thread gets more sms
from server and then if i call doIt , it throws an exception
org.smslib.GatewayException: Comm library exception: java.lang.RuntimeException: javax.comm.PortInUseException: Port currently owned by org.smslib
at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:102)
at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114)
at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189)
at org.smslib.Service$1Starter.run(Service.java:275)
where is the problem ?
Looks like you are not closing down SmsLib correctly as the exception seems to implicate that the connection to the serial port is left open.
it works for me. Use
Service.getInstance().sendMessages(myList, gateway.getGatewayId());
function instead of using sendmessage mylist.add(msg);
mylist is list containing outboung msg

Categories