Open office sdk create xls, doc,ppt files in Java - 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;
}
}

Related

DCM4CHE, Network operations,Handling a C-Move call

Hi I'm trying to make a PACS server using Java. dcm4che appears to be quite popular. But I'm unable to find any good examples about it.
As a starting point I inspected dcmqrscp and it successfully stores a DICOM image. But I cannot manage to handle a C-MOVE call. Here's my CMove handler. It finds requested the DICOM file adds a URL and other stuff, it doesn't throw any exception yet client doesn't receive any files.
private final class CMoveSCPImpl extends BasicCMoveSCP {
private final String[] qrLevels;
private final QueryRetrieveLevel rootLevel;
public CMoveSCPImpl(String sopClass, String... qrLevels) {
super(sopClass);
this.qrLevels = qrLevels;
this.rootLevel = QueryRetrieveLevel.valueOf(qrLevels[0]);
}
#Override
protected RetrieveTask calculateMatches(Association as, PresentationContext pc, final Attributes rq, Attributes keys) throws DicomServiceException {
QueryRetrieveLevel level = QueryRetrieveLevel.valueOf(keys, qrLevels);
try {
level.validateRetrieveKeys(keys, rootLevel, relational(as, rq));
} catch (Exception e) {
e.printStackTrace();
}
String moveDest = rq.getString(Tag.MoveDestination);
final Connection remote = new Connection("reciverAE",as.getSocket().getInetAddress().getHostAddress(), 11113);
if (remote == null)
throw new DicomServiceException(Status.MoveDestinationUnknown, "Move Destination: " + moveDest + " unknown");
List<T> matches = DcmQRSCP.this.calculateMatches(keys);
if (matches.isEmpty())
return null;
AAssociateRQ aarq;
Association storeas = null;
try {
aarq = makeAAssociateRQ(as.getLocalAET(), moveDest, matches);
storeas = openStoreAssociation(as, remote, aarq);
} catch (Exception e) {
e.printStackTrace();
}
BasicRetrieveTask<T> retrieveTask = null;
retrieveTask = new BasicRetrieveTask<T>(Dimse.C_MOVE_RQ, as, pc, rq, matches, storeas, new BasicCStoreSCU<T>());
retrieveTask.setSendPendingRSPInterval(getSendPendingCMoveInterval());
return retrieveTask;
}
private Association openStoreAssociation(Association as, Connection remote, AAssociateRQ aarq)
throws DicomServiceException {
try {
return as.getApplicationEntity().connect(as.getConnection(),
remote, aarq);
} catch (Exception e) {
throw new DicomServiceException(
Status.UnableToPerformSubOperations, e);
}
}
private AAssociateRQ makeAAssociateRQ(String callingAET,
String calledAET, List<T> matches) {
AAssociateRQ aarq = new AAssociateRQ();
aarq.setCalledAET(calledAET);
aarq.setCallingAET(callingAET);
for (InstanceLocator match : matches) {
if (aarq.addPresentationContextFor(match.cuid, match.tsuid)) {
if (!UID.ExplicitVRLittleEndian.equals(match.tsuid))
aarq.addPresentationContextFor(match.cuid,
UID.ExplicitVRLittleEndian);
if (!UID.ImplicitVRLittleEndian.equals(match.tsuid))
aarq.addPresentationContextFor(match.cuid,
UID.ImplicitVRLittleEndian);
}
}
return aarq;
}
private boolean relational(Association as, Attributes rq) {
String cuid = rq.getString(Tag.AffectedSOPClassUID);
ExtendedNegotiation extNeg = as.getAAssociateAC().getExtNegotiationFor(cuid);
return QueryOption.toOptions(extNeg).contains(
QueryOption.RELATIONAL);
}
}
I added the code below to send a DICOM file as a response:
String cuid = rq.getString(Tag.AffectedSOPClassUID);
String iuid = rq.getString(Tag.AffectedSOPInstanceUID);
String tsuid = pc.getTransferSyntax();
try {
DcmQRSCP.this.as=as;
File f = new File("D:\\dcmqrscpTestDCMDir\\1.2.840.113619.2.30.1.1762295590.1623.978668949.886\\1.2.840.113619.2.30.1.1762295590.1623.978668949.887\\1.2.840.113619.2.30.1.1762295590.1623.978668949.888");
FileInputStream in = new FileInputStream(f);
InputStreamDataWriter data = new InputStreamDataWriter(in);
// !1! as.cmove(cuid,1,keys,tsuid,"STORESCU");
as.cstore(cuid,iuid,1,data,tsuid,rspHandlerFactory.createDimseRSPHandler(f));
} catch (Exception e) {
e.printStackTrace();
}
Throws this exception
org.dcm4che3.net.NoRoleSelectionException: No Role Selection for SOP Class 1.2.840.10008.5.1.4.1.2.2.2 - Study Root Query/Retrieve Information Model - MOVE as SCU negotiated
You should add a role to the application instance like:
applicationEntity.addTransferCapability(
new TransferCapability(null, "*", TransferCapability.Role.SCP, "*"));

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

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

item-not-found(404) when trying to get a node using Smackx pubsub

I'm trying to use the latest Smackx trunk to get and then subscribe to a pubsub node. However, openfire just sends me a back an error: item not found (404).
I am instantiating the java objects from ColdFusion, so my code snippets might look funny but maybe someone will be able to tell me what I've forgotten.
Here's how I create the node:
ftype = createObject("java", "org.jivesoftware.smackx.pubsub.FormType");
cform = createObject("java", "org.jivesoftware.smackx.pubsub.ConfigureForm").init(ftype.submit);
cform.setPersistentItems(true);
cform.setDeliverPayloads(true);
caccess = createObject("java", "org.jivesoftware.smackx.pubsub.AccessModel");
cform.setAccessModel(caccess.open);
cpublish = createObject("java", "org.jivesoftware.smackx.pubsub.PublishModel");
cform.setPublishModel(cpublish.open);
cform.setMaxItems(99);
manager = createObject("java", "org.jivesoftware.smackx.pubsub.PubSubManager").init(XMPPConnection);
myNode = manager.createNode("subber", cform);
And here's how I am trying to get to it (in a different section of code):
manager = createObject("java", "org.jivesoftware.smackx.pubsub.PubSubManager").init(XMPPConnection);
myNode = manager.getNode("subber");
Immediately upon creating the node I seem to be able to publish to it like so:
payload = createObject("java", "org.jivesoftware.smackx.pubsub.SimplePayload").init("book","pubsub:test:book","<book xmlns='pubsub:test:book'><title>Lord of the Rings</title></book>");
item = createObject("java", "org.jivesoftware.smackx.pubsub.Item").init(payload);
myNode.publish(item);
However, it is the getNode() call that is causing my code to error.
I have verified that the nodes are being created by checking the DB used by my openfire server. I can see them in there, properly attributed as leaf nodes, etc.
Any advice?
Anyone else out there doing anything with XMPP and ColdFusion?
I have had great success sending and receiving messages with CF and Smack just haven't had the pubsub working yet :)
Thanks!
This has been answered:
There is a second method on the PubSubManager class that accepts two arguments, a connection and a to parameter. Apparently Openfire requires this to parameter and after some experimenting i discovered that it works using pubsub.your.xmpp.address
manager = createObject("java", "org.jivesoftware.smackx.pubsub.PubSubManager").init(XMPPConnection,"pubsub.127.0.0.1");
Maybe this example can be used as a reference for you:
public void login(String Ip,String username,String passwaord)
{
try
{
connConfig = new AndroidConnectionConfiguration(Ip, 5222);
connection = new XMPPConnection(connConfig);
connection.connect();
connection.login(username, passwaord);
pubSubAddress = "pubsub."+ connection.getServiceName();
manager = new PubSubManager(connection,pubSubAddress);
Log.i("MyError","connection success");
}
catch (XMPPException e)
{
Log.i("MyError","connection failed");
e.printStackTrace();
}
}
A normalized example are showed as following:
Publish node:
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.SimplePayload;
public class XmppPubsub_Publisher {
private static XMPPConnection connection = new XMPPConnection("think");
private static String USRE_NAME = "test1";
private static String PASSWORD = "1";
static{
try {
connection.connect();
connection.login(USRE_NAME,PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception{
try{
PubSubManager manager = new PubSubManager(connection);
String nodeId = "test2";
LeafNode myNode = null;
try {
myNode = manager.getNode(nodeId);
} catch (Exception e) {
e.printStackTrace();
}
if(myNode == null){
myNode = manager.createNode(nodeId);
}
String msg = "fsadfasdfsadfasdfd---";
SimplePayload payload = new SimplePayload("message","pubsub:test:message", "<message xmlns='pubsub:test:message'><body>"+msg+"</body></message>");
PayloadItem<SimplePayload> item = new PayloadItem<SimplePayload>("5", payload);
myNode.publish(item);
System.out.println("-----publish-----------");
}
catch(Exception E)
{E.printStackTrace();}
}
}
Retrieve node:
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smackx.pubsub.ItemPublishEvent;
import org.jivesoftware.smackx.pubsub.Node;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.listener.ItemEventListener;
public class XmppPubsub_Reciever {
private static XMPPConnection connection = new XMPPConnection("think");
private static String USRE_NAME = "test1";
private static String PASSWORD = "1";
static {
try {
connection.connect();
connection.login(USRE_NAME, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
String nodeId = "test2";
PubSubManager manager = new PubSubManager(connection);
Node eventNode = manager.getNode(nodeId);
eventNode.addItemEventListener(new ItemEventListener<PayloadItem>() {
public void handlePublishedItems(ItemPublishEvent evt) {
for (Object obj : evt.getItems()) {
PayloadItem item = (PayloadItem) obj;
System.out.println("--:Payload=" + item.getPayload().toString());
}
}
});
eventNode.subscribe(connection.getUser());
while(true);
}
}

Categories