getting a worklist and saving it to a file - java

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

Related

Why do I get zero-filled messages from dynamic queue

A requester is sending messages over a normal queue to a responder, indicating a dynamic queue it created as a reply queue. The responder puts these same messages on the reply queue. The responder retrieves all messages correctly.
For each message sent the requester obtains a message from the reply queue, but its body is filled with zeroes. Both programs are written in Java, using com.ibm.mq.allclient-9.2.2.0.jar. When I wrote the same in JavaScript with Node.js and ibmmq for node, everything worked fine.
Requester.java:
package com.hellerim.imq.comm.requester;
import static com.ibm.mq.constants.CMQC.MQENC_INTEGER_NORMAL;
import static com.ibm.mq.constants.CMQC.MQFMT_STRING;
import static com.ibm.mq.constants.CMQC.MQGMO_FAIL_IF_QUIESCING;
import static com.ibm.mq.constants.CMQC.MQGMO_NO_SYNCPOINT;
import static com.ibm.mq.constants.CMQC.MQGMO_NO_WAIT;
import static com.ibm.mq.constants.CMQC.MQGMO_WAIT;
import static com.ibm.mq.constants.CMQC.MQMT_REQUEST;
import static com.ibm.mq.constants.CMQC.MQOO_FAIL_IF_QUIESCING;
import static com.ibm.mq.constants.CMQC.MQOO_INPUT_EXCLUSIVE;
import static com.ibm.mq.constants.CMQC.MQOO_OUTPUT;
import static com.ibm.mq.constants.CMQC.MQPMO_NO_SYNCPOINT;
import static com.ibm.mq.constants.CMQC.MQRC_NO_MSG_AVAILABLE;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import io.netty.util.CharsetUtil;
import net.jcip.annotations.GuardedBy;
public class Requester
{
private static final int WAIT_WHILE_EMPTY = 100; // ms
private static int MAX_MILLIS_BETWEEN_REQUESTS = 100;
private static int LONG_WIDTH_IN_HEX_CHARS = 16;
private static final Charset charset = CharsetUtil.ISO_8859_1;
private MQQueueManager qMgr;
private final MQQueue requestQueue;
private final String queueNamePattern = "TEST.SESSION.*";
private String replyQueueName;
private final MQQueue replyQueue;
private final MQGetMessageOptions getOptions = new MQGetMessageOptions();
private static final String MQ_MANAGER = "MY_QM";
private static final String REQUEST_QUEUE = "TEST.REQUESTS";
private static final String MODEL_QUEUE = "TEST.SESSION.MODEL";
final private Object locker = new Object();
#GuardedBy("this")
boolean stopped = false;
int rcvd = 0;
public static void main(String[] args) {
try {
Requester rq = new Requester(MQ_MANAGER, REQUEST_QUEUE, MODEL_QUEUE);
List<String> poem = writePoem();
Random requestIds = new Random();
Random delays = new Random(1000);
int cnt = 0;
int position = 0;
for (int i = 0; i < 50; ++i) {
if (i == poem.size()) {
int requestId = requestIds.nextInt(99999) + 1;
String text = poem.stream().collect(Collectors.joining("\n"));
String request = appRequestFrom(text, requestId);
rq.write(request);
System.out.println("Requester: sent request no " + (++cnt) + " - " + requestId);
}
position %= poem.size();
String line = poem.get(position);
int requestId = requestIds.nextInt(99999) + 1;
String request = appRequestFrom(line, requestId);
rq.write(request);
System.out.println("Requester: sent request no " + (++cnt) + " - " + requestId);
position++;
try {
Thread.sleep((long) Math.ceil((Math.pow(
delays.nextDouble(), 4) * MAX_MILLIS_BETWEEN_REQUESTS) + 1));
} catch (InterruptedException e) {
// ignore
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// ignore
}
rq.close();
} catch (MQException e) {
e.printStackTrace();
}
}
public Requester(String mqManagerName, String requestQueueName, String modelQueueName) throws MQException {
super();
System.out.println("Requester: establishing mq session (mq manager: " + mqManagerName +
"/ request queue: " + requestQueueName + " / model queue: " + modelQueueName +")");
qMgr = new MQQueueManager(mqManagerName);
// get request queue
int openOptions = MQOO_OUTPUT + MQOO_FAIL_IF_QUIESCING;
requestQueue = qMgr.accessQueue(requestQueueName, openOptions);
// get dynamic reply queue
int inputOptions = MQOO_INPUT_EXCLUSIVE + MQOO_FAIL_IF_QUIESCING;
replyQueue = new MQQueue(qMgr,
modelQueueName,
inputOptions,
"",
queueNamePattern,
"");
replyQueueName = replyQueue.getName();
System.out.println("Requester: created temporary reply queue " + replyQueueName);
getOptions.options = MQGMO_NO_SYNCPOINT +
MQGMO_NO_WAIT +
MQGMO_FAIL_IF_QUIESCING;
// catch-up (for those replies not retrieved after a request was put)
Executors.newSingleThreadExecutor().execute(new Runnable() {
#Override
public void run() {
// read options
MQGetMessageOptions getOptions = new MQGetMessageOptions();
getOptions.options = MQGMO_NO_SYNCPOINT +
MQGMO_WAIT +
MQGMO_FAIL_IF_QUIESCING;
getOptions.waitInterval = WAIT_WHILE_EMPTY;
while(proceed()) {
try {
if (!retrieveMessage(getOptions)) {
try {
Thread.sleep(getOptions.waitInterval);
} catch (InterruptedException e1) {}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private boolean retrieveMessage(MQGetMessageOptions getOptions) throws IOException {
MQMessage msg = new MQMessage();
try {
msg.clearMessage();
msg.seek(0);
replyQueue.get(msg, getOptions);
System.out.println("Requester: reply no " + ++rcvd + " received - id: " +
Long.parseLong(new String(msg.messageId, Charset.forName("ISO_8859_1")), 16));
byte[] buf = new byte[msg.getDataLength()];
String message = new String(buf, charset);
System.out.println("Requester: message received:\n" + message);
} catch (MQException e) {
if (e.reasonCode == MQRC_NO_MSG_AVAILABLE) {
return false;
}
}
return true;
}
public byte[] write(String message) {
int positionRequestId = 24;
int endIndex = positionRequestId + 16;
CharSequence requestId = message.substring(positionRequestId, endIndex);
StringBuffer sb = new StringBuffer("00000000");
sb.append(requestId);
byte[] id = sb.toString().getBytes(charset);
MQMessage mqMsg = new MQMessage();
mqMsg.characterSet = 819;
mqMsg.encoding = MQENC_INTEGER_NORMAL;
mqMsg.format = MQFMT_STRING;
mqMsg.messageType = MQMT_REQUEST;
mqMsg.messageId = id;
mqMsg.correlationId = id;
mqMsg.replyToQueueName = replyQueueName;
try {
mqMsg.writeString(message);
mqMsg.seek(0);
MQPutMessageOptions pmo = new MQPutMessageOptions();
pmo.options = MQPMO_NO_SYNCPOINT;
requestQueue.put(mqMsg, pmo);
} catch (IOException e) {
e.printStackTrace();
} catch (MQException e) {
e.printStackTrace();
}
// try to read from reply queue fail immediately
try {
retrieveMessage(getOptions);
} catch (IOException e) {
e.printStackTrace();
}
return id;
}
public void close() {
stop();
try {
Thread.sleep(2 * WAIT_WHILE_EMPTY);
} catch (InterruptedException e1) {
// ignore
}
try {
if (requestQueue != null) {
requestQueue.close();
}
if (qMgr != null) {
qMgr.disconnect();
}
} catch (MQException e) {
// ignore
}
}
public boolean proceed() {
synchronized(locker) {
return !stopped;
}
}
public void stop() {
synchronized(locker) {
stopped = true;
}
}
private static List<String> writePoem() {
List<String> poem = new ArrayList<>();
poem.add("Das Nasobem");
poem.add("von Joachim Ringelnatz");
poem.add("");
poem.add("Auf seiner Nase schreitet");
poem.add("einher das Nasobem,");
poem.add("von seineme Kind begleitet -");
poem.add("es steht noch nicht im Brehm.");
poem.add("");
poem.add("Es steht noch nicht im Meyer");
poem.add("und auch im Brockhaus nicht -");
poem.add("es tritt aus meiner Leier");
poem.add("zum ersten Mal ans Licht.");
poem.add("");
poem.add("Auf seiner Nase schreitet");
poem.add("- wie schon gesagt - seitdem");
poem.add("von seinem Kind begleitet");
poem.add("einher das Nasobem.");
poem.add("");
poem.add("");
return poem;
}
private static String iToHex(int num, int places) {
StringBuilder sb = new StringBuilder();
char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
for (int i = 0; i < places; ++i) {
sb.append(digits[num % places]);
num /= places;
}
return sb.reverse().toString();
}
private static String iToHex(int num) {
return iToHex(num, LONG_WIDTH_IN_HEX_CHARS);
}
private static String appRequestFrom(String msgBody, int requestId) {
int headerLength = 72;
// includes message body length field here!
int bodyLength = msgBody.length();
StringBuilder sb = new StringBuilder();
sb.append("GHI "); // magic
sb.append("1"); // version major
sb.append("0"); // version minor
sb.append("0"); // flags
sb.append("1"); // app message type SYNCHRONOUS REQUEST
sb.append(iToHex(headerLength + bodyLength)); // message length
sb.append(iToHex(requestId)); // request id
sb.append(iToHex(0)); // timeout
sb.append(iToHex(bodyLength)); // message body length
sb.append(msgBody); // message body
return sb.toString();
}
}
Responder.java:
package com.hellerim.imq.comm.responder;
import static com.ibm.mq.constants.CMQC.*;
import java.io.EOFException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import io.netty.util.CharsetUtil;
import net.jcip.annotations.GuardedBy;
public class Responder
{
private MQQueueManager qMgr;
private MQQueue requestQueue;
private Map<String, MQQueue> replyQueues = new HashMap<>();
private final Object locker = new Object();
static final private int WAIT_WHILE_EMPTY = 100; // ms
#GuardedBy("locker")
private boolean stopped = false;
Thread fetcherThread = null;
private final static byte MESSAGE_TYPE_REPLY = 52; // '4'
public final static String MQ_MANAGER = "MY_QM";
public final static String REQUEST_QUEUE = "TEST.REQUESTS";
public static void main( String[] args ) throws MQException, IOException
{
System.out.println( "running reponder application" );
try {
new Responder(MQ_MANAGER, REQUEST_QUEUE).start();
} catch(Exception e) {
e.printStackTrace();
}
}
public Responder(String mqManagerName, String requestQueueName) throws MQException {
System.out.println("establishing mq session (mq manager: " + mqManagerName +
" / request queue: " + requestQueueName + ")");
qMgr = new MQQueueManager(mqManagerName);
int openOptions = MQOO_INPUT_SHARED + MQOO_FAIL_IF_QUIESCING;
requestQueue = qMgr.accessQueue(requestQueueName, openOptions);
}
public MQQueue getReplyQueue(String replyQueueName) throws MQException {
if (replyQueues.containsKey(replyQueueName)) {
return replyQueues.get(replyQueueName);
}
int openOptions = MQOO_OUTPUT + MQOO_FAIL_IF_QUIESCING;
MQQueue replyQueue = qMgr.accessQueue(replyQueueName, openOptions);
replyQueues.put(replyQueueName, replyQueue);
System.out.println("Responder: opened dynamic reply queue");
return replyQueue;
}
private void start() throws IOException {
Runnable fetcher = new Runnable() {
#Override
public void run() {
int cnt = 0;
while(proceed()) {
MQMessage msg = new MQMessage();
try {
//msg.clearMessage();
MQGetMessageOptions getOptions = new MQGetMessageOptions();
getOptions.options = MQGMO_NO_SYNCPOINT +
MQGMO_WAIT +
MQGMO_FAIL_IF_QUIESCING;
getOptions.waitInterval = WAIT_WHILE_EMPTY;
requestQueue.get(msg, getOptions);
System.out.println("Responder: message no " + ++cnt + " received");
MQQueue replyQueue = null;
try {
replyQueue = getReplyQueue(msg.replyToQueueName);
} catch(MQException e) {
if (e.completionCode == MQCC_FAILED && e.reasonCode == MQRC_UNKNOWN_OBJECT_NAME) {
// dynamic reply queue does not exist any more => message out of date
continue;
}
throw e;
}
// set message type for reply
if (msg.getDataLength() < 56) {
System.out.println("invalid message:");
System.out.println(Msg2Text(msg));
continue;
}
System.out.println(Msg2Text(msg));
int typePosition = 7;
msg.seek(typePosition);
msg.writeByte(MESSAGE_TYPE_REPLY);
msg.seek(0);
String text = Msg2Text(msg);
MQMessage msgOut = new MQMessage();
msgOut.characterSet = 819;
msgOut.encoding = MQENC_INTEGER_NORMAL;
msgOut.format = MQFMT_STRING;
msgOut.messageType = MQMT_REPLY;
msgOut.messageId = msg.messageId;
msgOut.correlationId = msg.correlationId;
msgOut.seek(0);
msgOut.writeString(text);
msgOut.seek(0);
System.out.println(text);
// System.out.println("Responder: message received");
MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the defaults, same
pmo.options = MQPMO_NO_SYNCPOINT;
replyQueue.put(msgOut, pmo);
System.out.println("Responder: message no " + cnt + " returned");
} catch (MQException e) {
if (e.reasonCode == MQRC_NO_MSG_AVAILABLE) {
; // NOOP
} else {
try {
msg.seek(0);
System.out.println(msg);
} catch (EOFException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
e.printStackTrace();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {}
}
} catch (IOException e) {
e.printStackTrace();
}
}
shutdown();
}
};
Thread task = new Thread(fetcher);
task.run();
System.out.print("press <ENTER> to terminate ");
System.in.read();
System.out.println();
synchronized(locker) {
stopped = true;
}
try {
task.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String Msg2Text(MQMessage msg) {
int length;
String text = "";
try {
length = msg.getDataLength();
byte[] buf = new byte[length];
msg.seek(0);
msg.readFully(buf);
text = new String(buf, CharsetUtil.ISO_8859_1);
msg.seek(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
private boolean proceed() {
synchronized(locker) {
return !stopped;
}
}
private void shutdown() {
System.out.print("\nshutting down responder... ");
for (MQQueue queue : replyQueues.values()) {
try {
queue.close();
} catch (MQException e) { }
}
replyQueues.clear();
try {
qMgr.close();
} catch (MQException e) { }
System.out.println("done.");
}
}
Is there any idea what might be wrong?
It looks like you have created a buffer the right size for the message data and printed that, without moving the data into it.
In retrieveMessage:
byte[] buf = new byte[msg.getDataLength()];
String message = new String(buf, charset);
System.out.println("Requester: message received:\n" + message);
You might need to call the readFully (or similar) method to get the data.
If you know that your message payload is text (string) then you can do this:
String msgStr = msg.readStringOfByteLength(msg.getMessageLength());
System.out.println("Requester: message received:\n" + msgStr);

How can I use spring on the following class?

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

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

ObjectInputStream wont load Array of Objects after second Run - Java

I've been trying to apply the followed code in a wider scheme. Right now I am just trying to understand the concept of ObjectInput/outputStreams and how they handle Array of objects.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class WritFile {
private FileInputStream output;
private ObjectInputStream outPut;
private FileOutputStream input;
private ObjectOutputStream inPut;
private Haha obj[];
public static void main(String args[]) throws Exception {
WritFile obj = new WritFile();
obj.Shazam("src\\Aloha.txt");
}
public void Shazam(String path) {
obj = new Haha[30];
for (int i = 0; i < obj.length; i++) {
obj[i] = new Haha();
}
for (int i = 0; i < 5; i++) {
obj[i].q1 = " Name" + i;
obj[i].x = i;
}
int No = 5;
saveToFile(obj, path);
int counter = 0;
try {
for (int i = 0; i < ReadFromFile(path).length; i++) {
if (ReadFromFile(path)[i].q1 != null) {
counter++;
}
}
for (int i = 0; i < counter; i++) {
if (ReadFromFile(path)[i] != null) {
obj[No++].q1 = ReadFromFile(path)[i].q1;
}
}
} catch (Exception e) {
System.out.printf("error1 : %s", e.getMessage());
e.printStackTrace();
}
try {
for (int i = 0; i < ReadFromFile(path).length; i++) {
if (ReadFromFile(path)[i] != null) {
System.out.println(ReadFromFile(path)[i].q1);
}
}
} catch (Exception e) {
System.out.printf("error2 : %s", e.getMessage());
}
System.out.printf("%s %n", "*******************");
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i].q1);
}
saveToFile(obj, path);
}
public void saveToFile(Haha arr[], String path) {
try {
input = new FileOutputStream(path, true);
inPut = new ObjectOutputStream(input);
inPut.writeObject(arr);
inPut.close();
} catch (Exception e) {
System.out.printf("Crashd : %s", e.getMessage());
}
}
public Haha[] ReadFromFile(String path) throws Exception {
output = new FileInputStream(path);
outPut = new ObjectInputStream(output);
return ((Haha[]) outPut.readObject());
}
}
My goal with this code is to store some data into an array of objects (OBJ) then save that array to a file using the function I created. Then read the data from the file and store it in the First empty index in the same array and so on.
For some reason it doesn't seem to write the data to the file after the first run :( !
Help!
public class SerializableArray implements Serializable, AutoCloseable{
/**
*
*/
private static final long serialVersionUID = 1L;
private static File ardatei;
transient Integer[] currentarray;
private int cntoverwrite;
FileInputStream fi;
BufferedReader br;
ObjectInputStream in;
int cnt;
public SerializableArray(Integer[] integers, String filename) throws IOException {
ardatei = new File(filename);
currentarray = integers;
if (!ardatei.exists())
{
try {
ardatei.createNewFile();
System.out.println("your file is created....");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("could not create File");
System.exit(-1);
}
FileOutputStream fos = new FileOutputStream(ardatei);
ObjectOutputStream o = new ObjectOutputStream(fos);
o.writeObject(integers);
o.flush();
o.close();
} else if (ardatei.exists() || zustand > 0) {
FileOutputStream fos =
new FileOutputStream(ardatei);
ObjectOutputStream o =
new ObjectOutputStream(fos);
o.writeObject(integers);
o.writeObject("\n " + "your file was overwrite.");
System.out.println("your file exists and become overwritten");
o.flush();
o.close();
}
}
method to read data from given file
public SerializableArray(String filename) {
File f = new File (filename);
fi = null;
br= null;
in = null;
if (f.exists()){
try {
try {
fi = new FileInputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw new FileNotFoundException("Loading file failed...");
}
in = new ObjectInputStream(fi);
System.out.println("Read data....");
//Cast to integer because readObject returns a object
currentarray =(Integer[]) in.readObject();
} catch (IOException | ClassNotFoundException e) {
System.out.println("could not read file....);
}
} else {
throw new RuntimeException ("this file doesnt exist yet");
}
}
that code works in my case ^^

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