How can I use spring on the following class? - java

I am learning how to use sprint and to be honest I think it's useful when you know what to inject. I am having a dilemma on the following class:
package Edamam;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
#Component
public class EdamamApi {
private String ApplicationIDRecipes;
private String ApplicationKeyRecipes;
private String ApplicationIDIngredients;
private String ApplicationKeyIngredients;
public EdamamApi(){
Properties prop = new Properties();
InputStream input = null;
try{
input = new FileInputStream("src/main/java/Edamam/Edamam.properties");
prop.load(input);
this.ApplicationIDRecipes = prop.getProperty("Application_ID_Recipes");
this.ApplicationKeyRecipes = prop.getProperty("Application_Keys_Recipes");
this.ApplicationIDIngredients = prop.getProperty("Application_ID_Ingredients");
this.ApplicationKeyIngredients = prop.getProperty("Application_Keys_Ingredients");
}
catch(IOException ex){
ex.printStackTrace();
}finally{
if(input != null){
try{
input.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
private String makeUrlForRecipes(ArrayList<String> ingredients){
boolean isFirst = true;
String url = "https://api.edamam.com/search?q=";
for(String ingredient : ingredients){
if(!isFirst)
url = url + "%20";
isFirst = false;
url = url + ingredient;
}
url = url + "&app_id=" + this.ApplicationIDRecipes + "&app_key=" + this.ApplicationKeyRecipes;
return url;
}
private String makeUrlForIngredients(String ingredient){
String url = "https://api.edamam.com/api/nutrition-data?app_id="+this.ApplicationIDIngredients+
"&app_key="+this.ApplicationKeyIngredients+"&ingr=1%20large%20"+ingredient;
return url;
}
private ArrayList<String> toArrayList(JSONArray arr){
ArrayList<String> StringList = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++)
StringList.add(arr.getString(i));
return StringList;
}
public ArrayList<RecipePojo> getRecipes(ArrayList<String> ingredients){
String url = makeUrlForRecipes(ingredients);
ArrayList<RecipePojo> recipes = new ArrayList<RecipePojo>();
try {
JSONObject response = JsonReader.readJsonFromUrl(url);
JSONArray jsonArray = response.getJSONArray("hits");
int NumberOfRecipes = 20;
int jsonIndex = 0;
while(jsonIndex < jsonArray.length() && NumberOfRecipes > 0){
JSONObject objectInArray = jsonArray.getJSONObject(jsonIndex);
String recipe = objectInArray.getJSONObject("recipe").getString("label");
String ImgURL = objectInArray.getJSONObject("recipe").getString("image");
ArrayList<String> IngredientLines = toArrayList(objectInArray.getJSONObject("recipe").
getJSONArray("ingredientLines"));
RecipePojo newRecipe = new RecipePojo(recipe, ImgURL, IngredientLines);
recipes.add(newRecipe);
jsonIndex++;
NumberOfRecipes--;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return recipes;
}
public NutritionFactsIngredient getNutritionFacts(String ingredient){
String url = makeUrlForIngredients(ingredient);
System.out.println("the url is: " + url);
NutritionFactsIngredient facts = null;
try{
JSONObject response = JsonReader.readJsonFromUrl(url);
int Calories = response.getInt("calories");
int TotalWeight = response.getInt("totalWeight");
JSONArray DietLabelsJson = response.getJSONArray("dietLabels");
JSONArray HealthLabelsJson = response.getJSONArray("healthLabels");
JSONArray CautionsJson = response.getJSONArray("cautions");
ArrayList<String> DietLabels = this.toArrayList(DietLabelsJson);
ArrayList<String> HealthLabels = this.toArrayList(HealthLabelsJson);
ArrayList<String> Cautions = this.toArrayList(CautionsJson);
facts = new NutritionFactsIngredient(Calories,TotalWeight,
DietLabels,HealthLabels,Cautions, ingredient);
}catch (JSONException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return facts;
}
}
I don't know if we should let spring handle the life-cycle of every object in our application. I just added the #component annotation on my class to get a taste of Spring, but I think that it's not enough. I am still instantiating objects with the new keyword inside of my methods. Should I make the classes RecipePojo and NutritionFactsIngredients components?. This is so confusing because the instances of these classes are not unique. They depend on user input. How can I use Spring on this class?
Edit: So people are telling me that instead of doing this:
#Component
public class EdamamApi{
public EdmamApi(){}
public Recipe getRecipe(String recipe ){
Recipe rep = Recipe(recipe);
return rep;
}
}
I should do this
#Component
public class EdamamApi{
public EdmamApi(){}
public void makeRecipe(String recipe, Recipe rep){
rep.setRecipeName(recipe);
}
}
In that way, the class is not tied down to Recipe and I can just use a bean Recipe.
--->THIS IS NOT RIGHT BUT IT'S WHAT I AM TRYING TO ACCOMPLISH <------
#Component
public class EdamamApi{
public EdmamApi(){}
public Recipe getRecipe(String name){
#Autowired
Recipe rep;
rep.setName(name);
return rep;
}
}

Related

How to return a value in nested try catch and while loop in java

I am using the below piece of code to SSH to a remote machine and get api_key.
I have used a try-catch block and if and while loop to return the API key value.
Below are the steps -
SSH to Remote machine
run cat command
cat command returns JSON array like below -
[
{
"apikey": "ewr34234gfdg435",
"app": "app1",
"role": "superadmin",
"user": "req1"
},
{
"apikey": "23rsgsfg3434",
"app": "app1",
"role": "superadmin",
"user": "req2"
}
]
Now, I want to retrieve the API key which has user="req2" only.
Below is the code -
package app1;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.jcraft.jsch.JSchException;
import com.pastdev.jsch.DefaultSessionFactory;
import com.pastdev.jsch.command.CommandRunner;
public class GetAPIKeyValue {
public String getAPIKeyValue(String remote_machine_user,String remote_machine_host, String remote_machine_password) {
String api_key_value = null;
DefaultSessionFactory sessionFactory = new DefaultSessionFactory(remote_machine_user, remote_machine_host, 22);
System.out.println("Connecting to Host : " + remote_machine_host + " As user : " + remote_machine_user);
Map<String, String> props = new HashMap<String, String>();
props.put("StrictHostKeyChecking", "no");
sessionFactory.setConfig(props);
System.out.println("Entering Password on Remote Machine to connect");
sessionFactory.setPassword(remote_machine_password);
CommandRunner runner = new CommandRunner(sessionFactory);
System.out.println("Executing cat command to get apikey on host");
String command = "cat /etc/usr/apikey.sh";
CommandRunner.ExecuteResult result;
try {
result = runner.execute(command);
if (result.getStderr().isEmpty()) {
System.out.println(result.getStdout());
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(result.getStdout());
JSONArray arrayObj = (JSONArray) obj;
Iterator<JSONObject> iterator = arrayObj.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
api_key_value = (String) jsonObj.get("apikey");
String requestor = (String) jsonObj.get("user");
// Would like to condition here i.e if user=="req2" return the API key of user req2.
}
} else {
System.out.println(result.getStderr());
}
} catch (JSchException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
try {
runner.close();
} catch (IOException e) {
e.printStackTrace();
}
return api_key_value;
}
}
Currently i am returning at the end of try catch "return api_key_value;". Instead how can i return in while statement itself
Maybe use Thread can help.
if(user =="req2") {
String finalApi_key_value = api_key_value;
new Thread(new Runnable() {
#Override
public void run() {
sendApiKeyValue(finalApi_key_value);
}
}).start();
}
And creat a method called sendApiKeyValue:
private void sendApiKeyValue(String finalApi_key_value) {
// Do something.
}
I fixed the issue myself.
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
String user = (String) jsonObj.get("user");
if (user.equals("req2")) {
System.out.println("Got User's API Key");
api_key_value = (String) jsonObj.get("apikey");
break;
} else {
System.out.println("Searching user's API Key");
}
}
Be simple. Just refactor your code first.
public class GetAPIKeyValue {
public static String getApiKeyValue(String remoteMachineUser, String remoteMachineHost, String remoteMachinePassword) throws Exception {
DefaultSessionFactory sessionFactory = new DefaultSessionFactory(remoteMachineUser, remoteMachineHost, 22);
sessionFactory.setConfig(Map.of("StrictHostKeyChecking", "no"));
sessionFactory.setPassword(remoteMachinePassword);
return executeAndGetApiKeyForUser(sessionFactory, "req2");
}
private static String executeAndGetApiKeyForUser(SessionFactory sessionFactory, String user) throws Exception {
try (CommandRunner runner = new CommandRunner(sessionFactory)) {
System.out.println("Executing cat command to get apikey on host");
String command = "cat /etc/usr/apikey.sh";
CommandRunner.ExecuteResult result = runner.execute(command);
if (result.getStderr().isEmpty())
return getApiKeyForUser(result.getStdout(), user);
System.out.println(result.getStderr());
return null;
}
}
private static String getApiKeyForUser(String json, String user) throws ParseException {
JSONArray arrayObj = (JSONArray)new JSONParser().parse(json);
Iterator<JSONObject> it = (Iterator<JSONObject>)arrayObj.iterator();
while (it.hasNext()) {
JSONObject obj = it.next();
if (obj.get("user").equals(user))
return String.valueOf(obj.get("apikey"));
}
return null;
}
}

getting a worklist and saving it to a file

I'm trying to retrieve the work list from the pacs server and saving it to a file "worklist.properties". I'm working on this code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.dcm4che2.data.BasicDicomObject;
import org.dcm4che2.data.DicomElement;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.SpecificCharacterSet;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4che2.net.Association;
import org.dcm4che2.net.CommandUtils;
import org.dcm4che2.net.Device;
import org.dcm4che2.net.DimseRSP;
import org.dcm4che2.net.NetworkApplicationEntity;
import org.dcm4che2.net.NetworkConnection;
import org.dcm4che2.net.NewThreadExecutor;
import org.dcm4che2.net.NoPresentationContextException;
import org.dcm4che2.net.TransferCapability;
public class TestGetMwl {
/**
* #param args
*/
public static void main(String[] args/*,String aet, String host, Integer port*/) {
new TestGetMwl(/*aet,host,port*/);
}
private static final int[] RETURN_KEYS = {
Tag.AccessionNumber,
Tag.ReferringPhysicianName,
Tag.PatientName,
Tag.PatientID,
Tag.PatientBirthDate,
Tag.PatientSex,
Tag.PatientWeight,
Tag.MedicalAlerts,
Tag.Allergies,
Tag.PregnancyStatus,
Tag.StudyInstanceUID,
Tag.RequestingPhysician,
Tag.RequestingService,
Tag.RequestedProcedureDescription,
Tag.AdmissionID,
Tag.SpecialNeeds,
Tag.CurrentPatientLocation,
Tag.PatientState,
Tag.RequestedProcedureID,
Tag.RequestedProcedurePriority,
Tag.PatientTransportArrangements,
Tag.PlacerOrderNumberImagingServiceRequest,
Tag.FillerOrderNumberImagingServiceRequest,
Tag.ConfidentialityConstraintOnPatientDataDescription,
};
private static final int[] SPS_RETURN_KEYS = {
Tag.Modality,
Tag.RequestedContrastAgent,
Tag.ScheduledStationAETitle,
Tag.ScheduledProcedureStepStartDate,
Tag.ScheduledProcedureStepStartTime,
Tag.ScheduledPerformingPhysicianName,
Tag.ScheduledProcedureStepDescription,
Tag.ScheduledProcedureStepID,
Tag.ScheduledStationName,
Tag.ScheduledProcedureStepLocation,
Tag.PreMedication,
Tag.ScheduledProcedureStepStatus
};
private static final String[] LE_TS = {
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian };
private static final byte[] EXT_NEG_INFO_FUZZY_MATCHING = { 1, 1, 1 };
private Device device;
private final NetworkApplicationEntity remoteAE = new NetworkApplicationEntity();
private final NetworkConnection remoteConn = new NetworkConnection();
private final NetworkApplicationEntity ae = new NetworkApplicationEntity();
private final NetworkConnection conn = new NetworkConnection();
private final DicomObject keys = new BasicDicomObject();
private final DicomObject spsKeys = new BasicDicomObject();
private Association assoc;
private int priority = 0;
private int cancelAfter = Integer.MAX_VALUE;//ÐœÐ°ÐºÑ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑтво Ñтрок
private boolean fuzzySemanticPersonNameMatching;
public TestGetMwl(/*String aet, String host, Integer port*/) {
String name = "DCMMWL";
device = new Device(name);
NewThreadExecutor executor = new NewThreadExecutor(name);
remoteAE.setInstalled(true);
remoteAE.setAssociationAcceptor(true);
remoteAE.setNetworkConnection(new NetworkConnection[] { remoteConn });
device.setNetworkApplicationEntity(ae);
device.setNetworkConnection(conn);
ae.setNetworkConnection(conn);
ae.setAssociationInitiator(true);
ae.setAETitle(name);
for (int i = 0; i < RETURN_KEYS.length; i++) {
keys.putNull(RETURN_KEYS[i], null);
}
keys.putNestedDicomObject(Tag.RequestedProcedureCodeSequence,
new BasicDicomObject());
keys.putNestedDicomObject(Tag.ScheduledProcedureStepSequence, spsKeys);
for (int i = 0; i < SPS_RETURN_KEYS.length; i++) {
spsKeys.putNull(SPS_RETURN_KEYS[i], null);
}
spsKeys.putNestedDicomObject(Tag.ScheduledProtocolCodeSequence,
new BasicDicomObject());
/////////
// remoteAE.setAETitle(aet);
// remoteConn.setHostname(host);
// remoteConn.setPort(port);
remoteAE.setAETitle("DCM4CHEE");
remoteConn.setHostname("localhost");
remoteConn.setPort(11112);
// addSpsMatchingKey(Tag.Modality, "CR");
//addSpsMatchingKey(Tag.Modality, "CR");
// addSpsMatchingKey(Tag.ScheduledProcedureStepStartDate,"20131030");
// addSpsMatchingKey(Tag.ScheduledProcedureStepStartTime,"11111");
setTransferSyntax(LE_TS);
long t1 = System.currentTimeMillis();
try {
assoc = ae.connect(remoteAE, executor);
} catch (Exception e) {
System.err.println("ERROR: Failed to establish association:");
e.printStackTrace(System.err);
System.exit(2);
}
long t2 = System.currentTimeMillis();
System.out.println("Connected to " + remoteAE + " in "
+ ((t2 - t1) / 1000F) + "s");
try {
List<DicomObject> result = query();
long t3 = System.currentTimeMillis();
System.out.println("Received " + result.size()
+ " matching entries in " + ((t3 - t2) / 1000F) + "s");
for(DicomObject dcm : result) {
// DicomElement pn = dcm.get(Tag.PatientName);
Properties worklist = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("C:\\properties\\worklist.properties");
// set the properties value
worklist.setProperty("1",dcm.getString(Tag.PatientName));
worklist.setProperty("2",dcm.getString(Tag.PatientName));
// save properties to project root folder
worklist.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("!!! PatientName="+dcm.getString(Tag.PatientName));
// }
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
assoc.release(true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Released connection to " + remoteAE);
}
public void setTransferSyntax(String[] ts) {
TransferCapability tc = new TransferCapability(
UID.ModalityWorklistInformationModelFIND, ts,
TransferCapability.SCU);
if (fuzzySemanticPersonNameMatching)
tc.setExtInfo(EXT_NEG_INFO_FUZZY_MATCHING);
ae.setTransferCapability(new TransferCapability[]{tc});
}
public void addSpsMatchingKey(int tag, String value) {
spsKeys.putString(tag, null, value);
}
public List<DicomObject> query() throws IOException, InterruptedException {
TransferCapability tc = assoc.getTransferCapabilityAsSCU(
UID.ModalityWorklistInformationModelFIND);
if (tc == null) {
throw new NoPresentationContextException(
"Modality Worklist not supported by "
+ remoteAE.getAETitle());
}
//System.out.println("Send Query Request:");
//System.out.println(keys.toString());
DimseRSP rsp = assoc.cfind(UID.ModalityWorklistInformationModelFIND,
priority, keys, tc.getTransferSyntax()[0], cancelAfter);
List<DicomObject> result = new ArrayList<DicomObject>();
while (rsp.next()) {
DicomObject cmd = rsp.getCommand();
if (CommandUtils.isPending(cmd)) {
DicomObject data = rsp.getDataset();
result.add(data);
//System.out.println("\nReceived Query Response #"
// + result.size() + ":");
//System.out.println(data.toString());
}
}
return result;
}
}
when my worklist containes just one element it works perfectly. But, when the worklist containes more than one element, I get as a result just the last element saved in the worklist file.
please any idea how to fix that?
I thinks your code has got following problems:
Firstly,
output = new FileOutputStream("C:\\properties\\worklist.properties");
is inside for loop
for(DicomObject dcm : result) {
-> the worklist.properties file will be overwritten again and again.
The second,
worklist.setProperty("1",dcm.getString(Tag.PatientName));
worklist.setProperty("2",dcm.getString(Tag.PatientName));
got same property keys (1 and 2) so the value will be overwritten too.
EDIT:
Add sample code:
output = new FileOutputStream("C:\\properties\\worklist.properties");
// For example
int propid = 1;
for(DicomObject dcm : result) {
String key = "patientName" + new Integer(propid++).toString();
worklist.setProperty(key,dcm.getString(Tag.PatientName));
}
worklist.store(output, null);

print request and response xml in Soap

Can anybody know how to print the soap request and response xml.
Please find the code below.
Code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Vector;
import org.apache.soap.Constants;
import org.apache.soap.Fault;
import org.apache.soap.SOAPException;
import org.apache.soap.encoding.SOAPMappingRegistry;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;
import org.apache.soap.transport.http.SOAPHTTPConnection;
public class SPMyBenefitsService {
private Call call;
private URL url = null;
private java.lang.reflect.Method setTcpNoDelayMethod;
private org.w3c.dom.Element rslts = null;
private ArrayList myBenefitsProducts = new ArrayList();
public static void main(String arg[]){
System.out.println("Test");//105843
SPMyBenefitsService service = new SPMyBenefitsService(9258347, "");
}
public SPMyBenefitsService(int group, String sessKey) {
System.out.println("Intializing starts..");
//IBwLogContext ctx = SPUtility.getBwLogContext(sessKey);
try {
setTcpNoDelayMethod = SOAPHTTPConnection.class.getMethod("setTcpNoDelay", new Class[] { Boolean.class });
} catch (Exception e) {
}
call = createCall();
try {
rslts = getProductList(group,"");
loadMyBenefitsData(rslts,"");
} catch (SOAPException ex) {
System.out.println("SPMetLinkService SOAP Exception = " + ex.toString());
}
}
private final URL getURL(String ctx) {
try {
String tul ="http://****.com/MyBenefits/webservices";
url = new URL(tul);
} catch (Exception Ex) {
System.out.println("exceptioon"+ Ex);
url = null;
}
return url;
}
public org.w3c.dom.Element getProductList(int grpnum, String ctx) throws SOAPException {
String targetObjectURI = "urn:com.metlife.us.ins.mybenefits.webservices.portal.PortalBusinessObjectProviderService";
String SOAPActionURI = "";
if (getURL(ctx) == null) {
throw new SOAPException(
Constants.FAULT_CODE_CLIENT,
"A URL must be specified via PortalBusinessObjectProviderServiceProxy.setEndPoint(URL).");
}
System.out.println("test:::"+Constants.NS_URI_LITERAL_XML);
System.out.println("NS_URI_SOAP_ENC:::"+ Constants.NS_URI_SOAP_ENC);
call.setMethodName("getProductList");
call.setEncodingStyleURI(Constants.NS_URI_LITERAL_XML);
call.setTargetObjectURI(targetObjectURI);
Vector<Parameter> params = new Vector<Parameter>();
System.out.println("grpnum"+grpnum);
Parameter grpnumParam = new Parameter("grpnum", int.class, new Integer(grpnum), Constants.NS_URI_SOAP_ENC);
params.addElement(grpnumParam);
call.setParams(params);
System.out.println("fff--?"+call.getParams());
long st = System.currentTimeMillis();
System.out.println("Before call - " + st + " milli seconds");
Response resp = call.invoke(getURL(ctx),SOAPActionURI);
long et = System.currentTimeMillis();
System.out.println("After call - " + et + " milli seconds");
System.out.println("Diff Mybenefit - " + (et-st) + " milli seconds");
System.out.println("Diff Mybenefit - " + (et-st) + " milli seconds" );
//Check the response.
if (resp.generatedFault()) {
Fault fault = resp.getFault();
call.setFullTargetObjectURI(targetObjectURI);
throw new SOAPException(fault.getFaultCode(), fault.getFaultString());
} else {
Parameter refValue = resp.getReturnValue();
System.out.println("resp"+refValue.getValue());
File file = new File("H:\\filename.txt");
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(
file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(resp.toString());
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ((org.w3c.dom.Element) refValue.getValue());
}
}
private boolean loadMyBenefitsData(org.w3c.dom.Element doc,String ctx) {
System.out.println("doc"+doc.toString());
/*IXml idoc = XmlUtil.create(doc);
IXml child = idoc.getFirstChildElement();*/
/*StringBuffer sb = null;
while ((child != null) && child.getName().equalsIgnoreCase("Product")) {
if (child.getText("Status").equalsIgnoreCase("Approved")) {
sb = new StringBuffer();
sb.append(child.getAttribute("productCode")).append("\011");
sb.append(child.getText("ShortName")).append("\011");
sb.append(child.getText("Status")).append("\011");
sb.append(child.getText("LiveDate")).append("\011");
myBenefitsProducts.add(sb.toString());
}
child = child.getNextSiblingElement();
}*/
return true;
}
protected Call createCall() {
SOAPHTTPConnection soapHTTPConnection = new SOAPHTTPConnection();
soapHTTPConnection.setTimeout(Integer.parseInt("90000"));
if (setTcpNoDelayMethod != null) {
try {
setTcpNoDelayMethod.invoke(soapHTTPConnection, new Object[] { Boolean.TRUE });
} catch (Exception ex) {
}
}
Call call = new Call();
call.setSOAPTransport(soapHTTPConnection);
SOAPMappingRegistry smr = call.getSOAPMappingRegistry();
return call;
}
}
I may be wrong but, using a software called SoapUI, you can:
Start a SoapUI MockService
Set SoapUI MockService's URL as an endpoint of your service
In SoapUI, open the tab which has the name of the method you want to call
Run your program (while SoapUI MockService is running)
Read the request sent by your program in SoapUI
Hope it helps
edit: Tutorials which are much better than my explanations can be found on the internet if you are a beginner on SoapUI
For a given SOAPMessage you can do the following:
SOAPMessage soapMessage = ...
try {
soapMessage.writeTo(System.out);
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Java HashMap Create, edit and delete

I am trying to update a HashMap use it directly in the next method, but it isn't working. From what I read I couldn't find a solution. Some say'd it is impossible and some say use an iterator, but even with the iterator it's not working. the error is the printing method it is not printing or even getting inside the while loop because it is empty but i cant find why
This is the two methods I'm trying to update and print some information.
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class OrderList {
// Storage for an arbitrary number of details.
private HashMap<String, Order> orderList = new HashMap<String, Order>();
/**
* Perform any initialization .
*/
public OrderList() {
orderList = new HashMap<String, Order>();
}
public HashMap<String, Order> getOrders() {
return orderList;
}
public void readOrderFile(String OrderListPath) {
try {
File file = new File(OrderListPath);
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String readLine = scan.nextLine();
if (readLine != null) {
getSplitLinesOrders(readLine);
}
}
} catch (Exception e) {
}
}
public void getSplitLinesOrders(String readLine) {
String id = "";
String customerId = "";
String itemId = "";
int quantity = 0;
try {
String[] splitedLine = readLine.split(",");
if (splitedLine.length == 4) {
id = splitedLine[0];
customerId = splitedLine[1];
itemId = splitedLine[2];
quantity = Integer.parseInt(splitedLine[3]);
Order newOrder = new Order(id, customerId, itemId, quantity);
orderList.put(id, newOrder);
}
} catch (Exception e) {
}
}
/**
* Add a new set of details to the list
* #param details The details of the staff
*/
// public void addDetails(Order details) {
// orderList.add(details);
// }
public boolean hasOrder() {
return orderList.size() != 0;
}
public Order getNextOrder() {
Order order = orderList.remove(0);
return order;
}
/**
* #return All the details
*/
public String listDetails() {
StringBuffer allEntries = new StringBuffer();
for (Map.Entry<String, Order> details : orderList.entrySet()) {
String Key = details.getKey();
Object value = details.getValue();
allEntries.append(Key + " " + value);
}
return allEntries.toString();
}
public void PrintListOfOrders() {
Iterator it = getOrders().entrySet().iterator();
try {
while (it.hasNext()) {
Order value = (Order) it.next();
System.out.println(value.getOrderId() + " " + value.getCustomerId() + " " + value.getItemId() + " " + value.getQuantity());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
You're probably getting a NullPointerException? Next time tell us what is going wrong and provide stacktraces if applicable.
The code you posted doesn't create an instance of orderList, so if it's not done elsewhere that code will throw a NullPointerException
Try adding:
private HashMap<String, Order> orderList = new HashMap<String, Order>;
Swallowing an Exception like this:
} catch (Exception e) {
}
is not a good practice since it will hide all information about what's going wrong, at least do:
catch (Exception e) {
e.printStacktrace();
}
You could do something like this:
Set<String> s = List.keySet();
Iterator<String> i = s.iterator();
Which is the initialization of the iterator, and then you could iterate through the keys using i.next(), getting a String each time and asking orderList.get(thatString) to get the value.

Json object from database in java

Can anyone help me how to create a JSON Object from the database?
This is what the JSON output should look like:
{“devicelist”:{
“device”: [
{“id”: “01”, “type”: “CAM”, “name”: “Livingroom”}
{“id”: “15”, “type”: “CAM”, “name”: “Kitchen”}
]
}}
This is my code:
if (reg!=null)
{
try
{
con = ds.getConnection();
Statement select = con.createStatement();
ResultSet result=select.executeQuery("Select type,name,demo from register_device");
while (result.next())
{
String type_json=result.getString("type");
String name_json=result.getString("name");
String id_json=result.getString("demo");
JSONArray arrayObj=new JSONArray();
}
}
catch(Exception e)
{
}
}
I am able to get the selected type,name,demo from the database.
I don't know how to start the JSON coding.
If you want to extract the data from the DB and construct the JSON Object yourself, you can do:
JsonArray jArray = new JsonArray();
while (result.next())
{
String type_json=result.getString("type");
String name_json=result.getString("name");
String id_json=result.getString("demo");
JsonObject jObj = new JsonObject();
jobj.put("id", id_json);
jobj.put("type", type_json);
jobj.put("name", name_json);
jArray.put(jObj);
}
JsonObject jObjDevice = new JsonObject();
jObjDevice.put("device", jArray);
JsonObject jObjDeviceList = new JsonObject();
jObjDevice.put("devicelist", jObjDevice );
now jObjDeviceList contains all the data.
If you have a Device objects, json-lib can serialize the object using get() methods as JSON.
import java.util.*;
import net.sf.json.*;
public class JsonEncode {
public static void main(String[] args) throws Exception {
Device d1 = new Device("01", "CAM", "LivingRoom");
Device d2 = new Device("15", "CAM", "Kitchen");
List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2));
JSONArray serializedDevices = JSONArray.fromObject(devices);
JSONObject jsonDevices = new JSONObject();
jsonDevices.put("devices", serializedDevices);
JSONObject json = new JSONObject();
json.put("deviceList", jsonDevices);
System.out.println(json);
}
public static class Device {
Device(String id, String type, String name) {
this.id = id;
this.type = type;
this.name = name;
}
private String id;
public String getId() { return id; }
private String type;
public String getType() { return type; }
private String name;
public String getName() { return name; }
}
}
Saved as: JsonEncode.java
Compiled with:
javac -cp json-lib-2.4-jdk15.jar JsonEncode.java
Executed with (Note: classpath has DOS separator):
java -cp .;json-lib-2.4-jdk15.jar;commons-lang-2.6.jar;commons-logging-1.1.1.jar;commons-collections-3.2.1.jar;ezmorph-1.0.6.jar;commons-beanutils-1.8.0.jar JsonEncode
Dependencies:
json-lib-2.4-jdk15.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
commons-collections-3.2.1.jar
commons-beanutils-1.8.0.jar
ezmorph-1.0.6.jar
With jOOQ, you could produce a similar JSON list from your database:
String json = create.select(TYPE, NAME, DEMO)
.from(REGISTER_DEVICE)
.fetch()
.formatJSON();
The JSON String would look like this (configurable):
{fields:["TYPE","NAME","DEMO"],
records:[["01","CAM","Livingroom"],["15","CAM","Kitchen"]]}
See more here. Alternatively, you can use your RDBMS's native SQL/JSON capabilities to create arbitrarily nested JSON documents.
(Disclaimer: I work for the company behind jOOQ)
package com.idal.cib;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnector {
static Connection conn1 = null;
public static Connection getDbConnection(String driver, String url,
String username, String password) {
// TODO Auto-generated constructor stub
try {
Class.forName(driver);
conn1 = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn1;
}
}
package com.idal.cib;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class DBJsonConverter {
static ArrayList<String> data = new ArrayList<String>();
static Connection conn = null;
static PreparedStatement ps = null;
static ResultSet rs = null;
static String path = "";
static String driver="";
static String url="";
static String username="";
static String password="";
static String query="";
#SuppressWarnings({ "unchecked" })
public static void dataLoad(String path) {
JSONObject obj1 = new JSONObject();
JSONArray jsonArray = new JSONArray();
conn = DatabaseConnector.getDbConnection(driver, url, username,
password);
try {
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
ArrayList<String> columnNames = new ArrayList<String>();
if (rs != null) {
ResultSetMetaData columns = rs.getMetaData();
int i = 0;
while (i < columns.getColumnCount()) {
i++;
columnNames.add(columns.getColumnName(i));
}
while (rs.next()) {
JSONObject obj = new JSONObject();
for (i = 0; i < columnNames.size(); i++) {
data.add(rs.getString(columnNames.get(i)));
{
for (int j = 0; j < data.size(); j++) {
if (data.get(j) != null) {
obj.put(columnNames.get(i), data.get(j));
}else {
obj.put(columnNames.get(i), "");
}
}
}
}
jsonArray.add(obj);
obj1.put("header", jsonArray);
FileWriter file = new FileWriter(path);
file.write(obj1.toJSONString());
file.flush();
file.close();
}
ps.close();
} else {
JSONObject obj2 = new JSONObject();
obj2.put(null, null);
jsonArray.add(obj2);
obj1.put("header", jsonArray);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
rs.close();
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#SuppressWarnings("static-access")
public static void main(String[] args) {
// TODO Auto-generated method stub
driver = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:#10.11.34.134:1521:COREMUAT";
username = "oasisusr";
password = "p#g_ay0w";
path = "D:\\VF_Polaris\\968670\\category_list1.json";
query = "select * from temp_employee";
DatabaseConnector dc = new DatabaseConnector();
dc.getDbConnection(driver,url,username,password);
DBJsonConverter formatter = new DBJsonConverter();
formatter.dataLoad(path);
}
}

Categories