print request and response xml in Soap - java

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

Related

Open office sdk create xls, doc,ppt files in Java

How to create a xls file using open office sdk? Please give Java example source code. Also needed to create word and power point files. I’m not able to get any examples
Below is the code I tried. It tries to open in Open office App, that I don't want. I want to generate the .ods file in the WebSphere App Server under AIX environment, using Java. I'm using it to generate a report and download it to front end (web app).
import ooo.connector.BootstrapSocketConnector;
import com.sun.star.beans.PropertyValue;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.container.XIndexAccess;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.table.XCell;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
XComponentContext xContext = null;
// get the remote office component context
try {
String folder = "C:\\Program Files (x86)\\OpenOffice 4\\program";
xContext = BootstrapSocketConnector.bootstrap(folder);
} catch (BootstrapException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XSpreadsheetDocument myDoc = null;
System.out.println("Opening an empty Calc document");
myDoc = openCalc(xContext);
XSpreadsheet xSheet = null;
try {
System.out.println("Getting spreadsheet");
XSpreadsheets xSheets = myDoc.getSheets();
XIndexAccess oIndexSheets = (XIndexAccess) UnoRuntime
.queryInterface(XIndexAccess.class, xSheets);
xSheet = (XSpreadsheet) UnoRuntime.queryInterface(
XSpreadsheet.class, oIndexSheets.getByIndex(0));
} catch (Exception e) {
System.out.println("Couldn't get Sheet " + e);
e.printStackTrace(System.err);
}
System.out.println("Creating the Header") ;
insertIntoCell(1,0,"JAN",xSheet,"");
insertIntoCell(2,0,"FEB",xSheet,"");
insertIntoCell(3,0,"MAR",xSheet,"");
insertIntoCell(4,0,"APR",xSheet,"");
insertIntoCell(5,0,"MAI",xSheet,"");
insertIntoCell(6,0,"JUN",xSheet,"");
insertIntoCell(7,0,"JUL",xSheet,"");
insertIntoCell(8,0,"AUG",xSheet,"");
insertIntoCell(9,0,"SEP",xSheet,"");
insertIntoCell(10,0,"OCT",xSheet,"");
insertIntoCell(11,0,"NOV",xSheet,"");
insertIntoCell(12,0,"DEC",xSheet,"");
insertIntoCell(13,0,"SUM",xSheet,"");
System.out.println("Fill the lines");
insertIntoCell(0,1,"Smith",xSheet,"");
insertIntoCell(1,1,"42",xSheet,"V");
insertIntoCell(2,1,"58.9",xSheet,"V");
insertIntoCell(3,1,"-66.5",xSheet,"V");
insertIntoCell(4,1,"43.4",xSheet,"V");
insertIntoCell(5,1,"44.5",xSheet,"V");
insertIntoCell(6,1,"45.3",xSheet,"V");
insertIntoCell(7,1,"-67.3",xSheet,"V");
insertIntoCell(8,1,"30.5",xSheet,"V");
insertIntoCell(9,1,"23.2",xSheet,"V");
insertIntoCell(10,1,"-97.3",xSheet,"V");
insertIntoCell(11,1,"22.4",xSheet,"V");
insertIntoCell(12,1,"23.5",xSheet,"V");
insertIntoCell(13,1,"=SUM(B2:M2)",xSheet,"");
insertIntoCell(0,2,"Jones",xSheet,"");
insertIntoCell(1,2,"21",xSheet,"V");
insertIntoCell(2,2,"40.9",xSheet,"V");
insertIntoCell(3,2,"-57.5",xSheet,"V");
insertIntoCell(4,2,"-23.4",xSheet,"V");
insertIntoCell(5,2,"34.5",xSheet,"V");
insertIntoCell(6,2,"59.3",xSheet,"V");
insertIntoCell(7,2,"27.3",xSheet,"V");
insertIntoCell(8,2,"-38.5",xSheet,"V");
insertIntoCell(9,2,"43.2",xSheet,"V");
insertIntoCell(10,2,"57.3",xSheet,"V");
insertIntoCell(11,2,"25.4",xSheet,"V");
insertIntoCell(12,2,"28.5",xSheet,"V");
insertIntoCell(13,2,"=SUM(B3:M3)",xSheet,"");
insertIntoCell(0,3,"Brown",xSheet,"");
insertIntoCell(1,3,"31.45",xSheet,"V");
insertIntoCell(2,3,"-20.9",xSheet,"V");
insertIntoCell(3,3,"-117.5",xSheet,"V");
insertIntoCell(4,3,"23.4",xSheet,"V");
insertIntoCell(5,3,"-114.5",xSheet,"V");
insertIntoCell(6,3,"115.3",xSheet,"V");
insertIntoCell(7,3,"-171.3",xSheet,"V");
insertIntoCell(8,3,"89.5",xSheet,"V");
insertIntoCell(9,3,"41.2",xSheet,"V");
insertIntoCell(10,3,"71.3",xSheet,"V");
insertIntoCell(11,3,"25.4",xSheet,"V");
insertIntoCell(12,3,"38.5",xSheet,"V");
insertIntoCell(13,3,"=SUM(A4:L4)",xSheet,"");
}
public static void insertIntoCell(int CellX, int CellY, String theValue,
XSpreadsheet TT1, String flag) {
XCell xCell = null;
try {
xCell = TT1.getCellByPosition(CellX, CellY);
} catch (com.sun.star.lang.IndexOutOfBoundsException ex) {
System.err.println("Could not get Cell");
ex.printStackTrace(System.err);
}
if (flag.equals("V")) {
xCell.setValue((new Float(theValue)).floatValue());
} else {
xCell.setFormula(theValue);
}
}
public static XSpreadsheetDocument openCalc(XComponentContext xContext) {
// define variables
XMultiComponentFactory xMCF = null;
XComponentLoader xCLoader;
XSpreadsheetDocument xSpreadSheetDoc = null;
XComponent xComp = null;
try {
// get the servie manager rom the office
xMCF = xContext.getServiceManager();
// create a new instance of the the desktop
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
// query the desktop object for the XComponentLoader
xCLoader = (XComponentLoader) UnoRuntime.queryInterface(
XComponentLoader.class, oDesktop);
PropertyValue[] szEmptyArgs = new PropertyValue[0];
String strDoc = "private:factory/scalc";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0,
szEmptyArgs);
xSpreadSheetDoc = (XSpreadsheetDocument) UnoRuntime.queryInterface(
XSpreadsheetDocument.class, xComp);
} catch (Exception e) {
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xSpreadSheetDoc;
}
}

why my crawledURL is null?

I am following a tutorial to create a web crawler in java. When I run the code my crawledURL is null. *** Malformed URL :null in a infinite loop.
Can anyone explain to me why is this happening?
Here is the whole code:
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.net.*;
public class WebCrawler {
public static Queue<String> Queue = new LinkedList<>();
public static Set<String> marked = new HashSet<>();
public static String regex = "http[s]://(\\w+\\.)*(\\w+)";
public static void bfsAlgorithm(String root) throws IOException {
Queue.add(root);
while (!Queue.isEmpty()) {
String crawledURL = Queue.poll();
System.out.println("\n=== Site crawled : " + crawledURL + "===");
//Limiting to a 100 websites here
if(marked.size() > 100)
return;
boolean ok = false;
URL url = null;
BufferedReader br = null;
while (!ok) {
try {
url = new URL(crawledURL);
br = new BufferedReader(new InputStreamReader(url.openStream()));
ok = true;
} catch (MalformedURLException e) {
System.out.println("*** Malformed URL :" + crawledURL);
crawledURL = Queue.poll();
ok = false;
} catch (IOException ioe) {
System.out.println("*** IOException for URL :" + crawledURL);
crawledURL = Queue.poll();
ok = false;
}
}
StringBuilder sb = new StringBuilder();
while((crawledURL = br.readLine()) != null) {
sb.append(crawledURL);
}
crawledURL = sb.toString();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(crawledURL);
while (matcher.find()){
String w = matcher.group();
if (!marked.contains(w)) {
marked.add(w);
System.out.println("Site added for crawling : " + w);
Queue.add(w);
}
}
}
}
public static void showResults() {
System.out.println("\n\nResults :");
System.out.print("Web sites craweled: " + marked.size() + "\n");
for (String s : marked) {
System.out.println("* " + s);
}
}
public static void main(String[] args) {
try {
bfsAlgorithm("http://www.ssaurel.com/blog");
showResults();
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
while (!Queue.isEmpty()) {
String crawledURL = Queue.poll();
...
} catch (MalformedURLException e) {
crawledURL = Queue.poll();
second time you do not check is queue empty

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

config,properties file does not update in real time while running service via the browser

i try to implement some rest api for read mails service.
now i have a command that can stop/run the service.
after i run the service for some reason when i update my config file in the runService method into "RUNNING" i still get that the status of the service is "ONHOLD" and i dont undersatnd why. there for the do while loop terminated only after 1 iteration.
there is a delay while we working with files inside the program code?
this is my full code:
package com.javacodegeeks.snippets.enterprise;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/helloWorld")
public class HelloWorldController {
private final String layout = "ViewLayout";
private static enum Status{
RUNNING,ONHOLD,FINISHED,ERROR
}
Status status;
//setup method
#RequestMapping(value = "/setup/{username}/{password}/{host}/", method = RequestMethod.GET)
public String Setup(#PathVariable("username") String username,#PathVariable("password") String pass,#PathVariable("host") String host ,ModelMap model) throws IOException {
model.addAttribute("tag","Setup configuration");
OutputStream output = null;
File myfile = new File(username+".properties");
try{
if(!checkIfFileExists(myfile)){
myfile.createNewFile();
output = new FileOutputStream(myfile,false);
}
else{
model.addAttribute("msg","Error: Setup Failed, configuration for the user ="+" "+username+" "+"already exists!");
return layout;
}
Properties prop = new Properties();
prop.setProperty("username", username);
prop.setProperty("password", pass);
prop.setProperty("host", host);
prop.setProperty("status", status.FINISHED.toString());
prop.store(output, null);
}
catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
model.addAttribute("msg","Configuration successfully updated!");
return layout;
}
//run service method
#RequestMapping(value = "/run/{username}/{password}/", method = RequestMethod.GET)
public String runService(#PathVariable("username") String username,#PathVariable("password") String pass,ModelMap model){
model.addAttribute("tag","Running service procedure");
File myfile = new File(username+".properties");
if(!checkIfFileExists(myfile)){
model.addAttribute("msg","Error: Run Failed, configuration for the user ="+" "+username+" "+"not found!");
return layout;
}
else{
int i=0;
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(myfile);
prop.load(input);
if(!authenticatePassword(prop,pass)){
model.addAttribute("msg","Error: Run Failed, The password is inccorrect");
return layout;
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String stat = prop.getProperty("status");
if(stat.equals(status.FINISHED.toString()) || stat.equals(status.ONHOLD.toString()))
{
updateConfigfile(username+".properties","status",status.RUNNING.toString());
do{
i++;
model.addAttribute("msg","inside loop"+" "+"Counter is:"+" "+i+" "+"status is =" +prop.getProperty("status"));
}while(prop.getProperty("status").equals(status.RUNNING.toString()));
}else{
model.addAttribute("msg","Service is already running");
}
}
return layout;
}
//get status
#RequestMapping(value = "/getstatus/{username}/{password}/", method = RequestMethod.GET)
public String getServiceSatus(#PathVariable("username") String username,#PathVariable("password") String pass,ModelMap model) {
model.addAttribute("tag","Get Status");
Properties prop = loadProperties(username+".properties");
if(prop == null){
model.addAttribute("msg","Error: Status is not available: can not read properties file!");
return layout;
}
if(!authenticatePassword(prop,pass)){
model.addAttribute("msg","Error: Get status failed, password or username is inccorrect");
return layout;
}
String status = prop.getProperty("status");
model.addAttribute("msg", "Service status is:"+" "+status);
return layout;
}
//stop service
#RequestMapping(value = "/stop/{username}/{password}/", method = RequestMethod.GET)
public String stopService( #PathVariable("username") String username,#PathVariable("password") String pass,ModelMap model) {
String message = "";
Properties prop = loadProperties(username+".properties");
if(prop == null){
model.addAttribute("msg","Error: Can not stop service, properties file does not exist or username is inccorrect!");
return layout;
}
if(!authenticatePassword(prop,pass)){
model.addAttribute("msg","Error: Can not stop service, password or username is inccorrect");
return layout;
}
String stat = prop.getProperty("status");
if(stat.equals(status.RUNNING.toString()))
{
updateConfigfile(username+".properties","status",status.ONHOLD.toString());
message = "Service was stoped";
}else{
message = "service is not running status is = "+ " "+prop.getProperty("status");
}
model.addAttribute("tag","Stop Service");
model.addAttribute("msg",message);
return layout;
}
public boolean checkIfFileExists(File filename){
if(!filename.exists()){
return false;
}
return true;
}
//function that updating properties file
public void updateConfigfile(String filename ,String key,String val){
FileInputStream in = null;
Properties props = new Properties();
try {
in = new FileInputStream(filename);
props.load(in);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
props.setProperty(key, val);
props.store(out, null);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
//function that load properties file
public Properties loadProperties(String filename){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(filename);
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else{
return null;
}
}
return prop;
}
public boolean authenticatePassword(Properties prop,String pass){
if(!(prop.getProperty("password").equals(pass))){
return false;
}
return true;
}
}
I don't really understand your problem but, at least, I think that you have a problem inside runService method:
Note:added some comments into the code starting with '<--'
String stat = prop.getProperty("status"); <-- you read the property here
if(stat.equals(status.FINISHED.toString()) || stat.equals(status.ONHOLD.toString()))
{
updateConfigfile(username+".properties","status",status.RUNNING.toString());
do{
i++;
model.addAttribute("msg","inside loop"+" "+"Counter is:"+" "+i+" "+"status is =" +prop.getProperty("status")); <-- status contains FINISHED or ONHOLD! It is the same as using stat variable.
}while(prop.getProperty("status").equals(status.RUNNING.toString())); <--contains FINISHED or ONHOLD! so, always return false
}else{
model.addAttribute("msg","Service is already running");
}
In other words, if you change the file you need to read it again in order to have an updated properties into properties object.
Hope this helps!
I mean this referred to my last comment!
String stat = prop.getProperty("status");
if(stat.equals(status.FINISHED.toString()) || stat.equals(status.ONHOLD.toString()))
{
updateConfigfile(username+".properties","status",status.RUNNING.toString());
prop.setProperty("status",status.RUNNING.toString());
i++;
model.addAttribute("msg","inside loop"+" "+"Counter is:"+" "+i+" "+"status is =" +prop.getProperty("status"));
}else{
model.addAttribute("msg","Service is already running");
}

webserver is taking too long to respond in android

i have created a web server in android it works fine and it does not show any error and i have log saying server started on port 9000 but when i type the ip of my phone it says server is taking to long to connect.
Jhtts file: (the class which runs the server)
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.security.acl.Owner;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
import dolphin.devlopers.com.R;
public class JHTTS extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook);
try{
File documentRootDirectory = new File ("/sdcard/samer/");
JHTTP j = new JHTTP(documentRootDirectory,9000);
j.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JHTTP class:
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.util.Log;
public class JHTTP extends Thread {
private File documentRootDirectory;
private String indexFileName = "index.html";
private ServerSocket server;
private int numThreads = 50;
public JHTTP(File documentRootDirectory, int port,
String indexFileName) throws IOException {
if (!documentRootDirectory.isDirectory( )) {
throw new IOException(documentRootDirectory
+ " does not exist as a directory");
}
this.documentRootDirectory = documentRootDirectory;
this.indexFileName = indexFileName;
this.server = new ServerSocket(port);
}
public JHTTP(File documentRootDirectory, int port) throws IOException {
this(documentRootDirectory, port, "index.html");
}
public JHTTP(File documentRootDirectory) throws IOException {
this(documentRootDirectory, 80, "index.html");
}
public void run( ) {
try {
Process process = Runtime.getRuntime().exec("su");
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(
new RequestProcessor(documentRootDirectory, indexFileName));
t.start( );
}
System.out.println("Accepting connections on port " + server.getLocalPort( ));
System.out.println("Document Root: " + documentRootDirectory);
while (true) {
try {
Socket request = server.accept( );
request.setReuseAddress(true);
RequestProcessor.processRequest(request);
}
catch (IOException ex) {
}
}
}
public static void main(String[] args) {
// get the Document root
File docroot;
try {
docroot = new File("D:/");
}
catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Usage: java JHTTP docroot port indexfile");
return;
}
// set the port to listen on
try {
int port;
port = 9000;
JHTTP webserver = new JHTTP(docroot, port);
webserver.start( );
}
catch (IOException ex) {
System.out.println("Server could not start because of an "
+ ex.getClass( ));
System.out.println(ex);
}
}
}
Request Processor class :
package dolphin.developers.com;
import java.net.*;
import java.io.*;
import java.util.*;
public class RequestProcessor implements Runnable {
#SuppressWarnings("rawtypes")
private static List pool = new LinkedList( );
private File documentRootDirectory;
private String indexFileName = "index.html";
public RequestProcessor(File documentRootDirectory,
String indexFileName) {
if (documentRootDirectory.isFile( )) {
throw new IllegalArgumentException(
"documentRootDirectory must be a directory, not a file");
}
this.documentRootDirectory = documentRootDirectory;
try {
this.documentRootDirectory
= documentRootDirectory.getCanonicalFile( );
}
catch (IOException ex) {
}
if (indexFileName != null) this.indexFileName = indexFileName;
}
#SuppressWarnings("unchecked")
public static void processRequest(Socket request) {
synchronized (pool) {
pool.add(pool.size( ), request);
pool.notifyAll( );
}
}
public void run( ) {
// for security checks
String root = documentRootDirectory.getPath( );
while (true) {
Socket connection;
synchronized (pool) {
while (pool.isEmpty( )) {
try {
pool.wait( );
}
catch (InterruptedException ex) {
}
}
connection = (Socket) pool.remove(0);
}
try {
String filename;
String contentType;
OutputStream raw = new BufferedOutputStream(
connection.getOutputStream( )
);
Writer out = new OutputStreamWriter(raw);
Reader in = new InputStreamReader(
new BufferedInputStream(
connection.getInputStream( )
),"ASCII"
);
StringBuffer requestLine = new StringBuffer( );
int c;
while (true) {
c = in.read( );
if (c == '\r' || c == '\n') break;
requestLine.append((char) c);
}
String get = requestLine.toString( );
// log the request
System.out.println(get);
StringTokenizer st = new StringTokenizer(get);
String method = st.nextToken( );
String version = "";
if (method.equals("GET")) {
filename = st.nextToken( );
if (filename.endsWith("/")) filename += indexFileName;
contentType = guessContentTypeFromName(filename);
if (st.hasMoreTokens( )) {
version = st.nextToken( );
}
File theFile = new File(documentRootDirectory,
filename.substring(1,filename.length( )));
if (theFile.canRead( )
// Don't let clients outside the document root
&& theFile.getCanonicalPath( ).startsWith(root)) {
DataInputStream fis = new DataInputStream(
new BufferedInputStream(
new FileInputStream(theFile)
)
);
byte[] theData = new byte[(int) theFile.length( )];
fis.readFully(theData);
fis.close( );
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 200 OK\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP/1.0\r\n");
out.write("Content-length: " + theData.length + "\r\n");
out.write("Content-type: " + contentType + "\r\n\r\n");
out.flush( );
} // end if
// send the file; it may be an image or other binary data
// so use the underlying output stream
// instead of the writer
raw.write(theData);
raw.flush( );
} // end if
else { // can't find the file
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 404 File Not Found\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP/1.0\r\n");
out.write("Content-type: text/html\r\n\r\n");
}
out.write("<HTML>\r\n");
out.write("<HEAD><TITLE>File Not Found</TITLE>\r\n");
out.write("</HEAD>\r\n");
out.write("<BODY>");
out.write("<H1>HTTP Error 404: File Not Found</H1>\r\n");
out.write("</BODY></HTML>\r\n");
out.flush( );
}
}
else { // method does not equal "GET"
if (version.startsWith("HTTP ")) { // send a MIME header
out.write("HTTP/1.0 501 Not Implemented\r\n");
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP 1.0\r\n");
out.write("Content-type: text/html\r\n\r\n");
}
out.write("<HTML>\r\n");
out.write("<HEAD><TITLE>Not Implemented</TITLE>\r\n");
out.write("</HEAD>\r\n");
out.write("<BODY>");
out.write("<H1>HTTP Error 501: Not Implemented</H1>\r\n");
out.write("</BODY></HTML>\r\n");
out.flush( );
}
}
catch (IOException ex) {
}
finally {
try {
connection.close( );
}
catch (IOException ex) {}
}
} // end while
} // end run
public static String guessContentTypeFromName(String name) {
if (name.endsWith(".html") || name.endsWith(".htm")) {
return "text/html";
}
else if (name.endsWith(".txt") || name.endsWith(".java")) {
return "text/plain";
}
else if (name.endsWith(".gif")) {
return "image/gif";
}
else if (name.endsWith(".class")) {
return "application/octet-stream";
}
else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) {
return "image/jpeg";
}
else if (name.endsWith(".png") ) {
return "image/png";
}
else if (name.endsWith(".js")) {
return "text/javascript";
}
else if (name.endsWith(".js")) {
return "text/javascript";
}
else if (name.endsWith(".css")) {
return "text/css";
}
else return "text/plain";
}
} // end RequestProcessor
Logcat window:
Accepting connections on port 9000
Document Root: D:\
now when i connect to my web server in my log i get
Logcat Update:
07-29 14:42:46.175: D/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
07-29 14:47:46.195: D/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
The log says it's accepting connections on port 80, but your server runs on port 9000 - I guess that's the problem.

Categories