+++ /dev/null
-package org.open_ils;
-
-import org.opensrf.*;
-import org.opensrf.util.*;
-import org.open_ils.*;
-import org.open_ils.idl.*;
-import org.opensrf.util.*;
-
-import java.util.Map;
-import java.util.HashMap;
-import java.io.IOException;
-
-
-public class Sys {
-
- private static IDLParser idlParser = null;
-
- /**
- * Initializes the connection to the OpenSRF network and parses the IDL file.
- * @param attrs A map of configuration attributes. Options include:<br/>
- * <ul>
- * <li>configFile - The OpenSRF core config file</li>
- * <li>configContext - The path to the config chunk in the config XML, typically "opensrf"</li>
- * <li>logProtocol - Currently supported option is "file".</li>
- * <li>logLevel - The log level. Options are 1,2,3, or 4 (error, warn, info, debug)</li>
- * <li>syslogFacility - For future use, when syslog is a supported log option</li>
- * <li>idlFile - The path to the IDL file. May be relative or absolute. If this option is
- * not provided, the system will ask the OpenSRF Settings server for the IDL file path.</li>
- * </ul>
- */
- public static void init(Map<String, String> attrs) throws ConfigException, SessionException, IOException, IDLException {
-
- String configFile = attrs.get("configFile");
- String configContext = attrs.get("configContext");
- String logProto = attrs.get("logProtocol");
- String logFile = attrs.get("logFile");
- String logLevel = attrs.get("logLevel");
- String syslogFacility = attrs.get("syslogFacility");
- String idlFile = attrs.get("idlFile");
-
-
- if(idlParser != null) {
- /** if we've parsed the IDL file, then all of the global setup has been done.
- * We just need to verify this thread is connected to the OpenSRF network. */
- org.opensrf.Sys.bootstrapClient(configFile, configContext);
- return;
- }
-
- /** initialize the logging infrastructure */
- if("file".equals(logProto))
- Logger.init(Short.parseShort(logLevel), new FileLogger(logFile));
-
- if("syslog".equals(logProto))
- throw new ConfigException("syslog not yet implemented");
-
- /** connect to the opensrf network. */
- org.opensrf.Sys.bootstrapClient(configFile, configContext);
-
- /** Grab the IDL file setting if not explicitly provided */
- if(idlFile == null) {
- SettingsClient client = SettingsClient.instance();
- idlFile = client.getString("/IDL");
- }
-
- /** Parse the IDL if necessary */
- idlParser = new IDLParser(idlFile);
- idlParser.parse();
- }
-}
-
+++ /dev/null
-package org.open_ils.util;
-import org.open_ils.*;
-import org.opensrf.*;
-import org.opensrf.util.*;
-import java.util.Map;
-import java.util.HashMap;
-import java.security.MessageDigest;
-
-public class Utils {
-
- /**
- * Logs in.
- * @param params Login arguments, which may consist of<br/>
- * username<br/>
- * barcode - if username is provided, barcode will be ignored<br/>
- * password<br/>
- * workstation - name of the workstation where the login is occuring<br/>
- * type - type of login, currently "opac", "staff", and "temp"<br/>
- * org - optional org ID to provide login context when no workstation is used.
- * @return An Event object. On success, the event 'payload' will contain
- * 'authtoken' and 'authtime' fields, which represent the session key and
- * session inactivity timeout, respectively.
- */
- public static Event login(Map params) throws MethodException {
-
- Map<String, String> initMap = new HashMap<String, String>();
- String init = (params.get("username") != null) ?
- params.get("username").toString() : params.get("barcode").toString();
- System.out.println("login1");
-
- Object resp = ClientSession.atomicRequest(
- "open-ils.auth",
- "open-ils.auth.authenticate.init", new Object [] {initMap});
-
- System.out.println("login2");
- /** see if the server responded with some type of unexpected event */
- Event evt = Event.parseEvent(resp);
- if(evt != null) return evt;
-
- params.put("password", md5Hex(resp + md5Hex(params.get("password").toString())));
-
- resp = ClientSession.atomicRequest(
- "open-ils.auth",
- "open-ils.auth.authenticate.complete", new Object[]{params});
-
- return Event.parseEvent(resp);
- }
-
- /**
- * Generates the hex md5sum of a string.
- * @param s The string to md5sum
- * @return The 32-character hex md5sum
- */
- public static String md5Hex(String s) {
- StringBuffer sb = new StringBuffer();
- MessageDigest md;
- try {
- md = MessageDigest.getInstance("MD5");
- } catch(Exception e) {
- return null;
- }
-
- md.update(s.getBytes());
- byte[] digest = md.digest();
- for (int i = 0; i < digest.length; i++) {
- int b = digest[i] & 0xff;
- String hex = Integer.toHexString(b);
- if (hex.length() == 1) sb.append("0");
- sb.append(hex);
- }
- return sb.toString();
- }
-}
-
-
-
<project version="4">
<component name="CompilerConfiguration">
<option name="DEFAULT_COMPILER" value="Javac" />
- <excludeFromCompile>
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/util/Cache.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/test/TestCache.java" />
- </excludeFromCompile>
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<project version="4">
<component name="CompilerConfiguration">
<option name="DEFAULT_COMPILER" value="Javac" />
- <excludeFromCompile>
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/util/Cache.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/Stack.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/Session.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/Sys.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/Request.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/ClientSession.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/MultiSession.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/ServerSession.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/util/SettingsClient.java" />
- <file url="file://$PROJECT_DIR$/../core/src/org/open_ils/util/Utils.java" />
- <file url="file://$PROJECT_DIR$/../core/src/org/open_ils/Sys.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/util/XMLFlattener.java" />
- </excludeFromCompile>
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
</profile>
</annotationProcessing>
</component>
-</project>
\ No newline at end of file
+</project>
<project version="4">
<component name="CompilerConfiguration">
<option name="DEFAULT_COMPILER" value="Javac" />
- <excludeFromCompile>
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/util/Cache.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/Stack.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/Session.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/Sys.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/Request.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/ClientSession.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/MultiSession.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/ServerSession.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/util/SettingsClient.java" />
- <file url="file://$PROJECT_DIR$/../core/src/org/open_ils/util/Utils.java" />
- <file url="file://$PROJECT_DIR$/../core/src/org/open_ils/Sys.java" />
- <file url="file://$PROJECT_DIR$/../opensrf/src/org/opensrf/util/XMLFlattener.java" />
- </excludeFromCompile>
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
</profile>
</annotationProcessing>
</component>
-</project>
\ No newline at end of file
+</project>
+++ /dev/null
-package org.opensrf;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.ArrayList;
-import java.util.Random;
-import java.util.Arrays;
-
-import org.opensrf.util.*;
-import org.opensrf.net.xmpp.*;
-
-
-/**
- * Models an OpenSRF client session.
- */
-public class ClientSession extends Session {
-
- /** The remote service to communicate with */
- private String service;
- /** OpenSRF domain */
- private String domain;
- /** Router name */
- private String router;
-
- /**
- * original remote node. The current remote node will change based
- * on server responses. This is used to reset the remote node to
- * its original state.
- */
- private String origRemoteNode;
- /** The next request id */
- private int nextId;
- /** The requests this session has sent */
- private Map<Integer, Request> requests;
-
- /**
- * Creates a new client session. Initializes the
- * @param service The remote service.
- */
- public ClientSession(String service) throws ConfigException {
- this(service, null);
- }
-
- /**
- * Creates a new client session. Initializes the
- * @param service The remote service.
- * @param locale The locale for this session.
- */
- public ClientSession(String service, String locale) throws ConfigException {
- this.service = service;
- if(locale != null)
- setLocale(locale);
-
- /** generate the remote node string */
- domain = (String) Config.global().getFirst("/domain");
- router = Config.global().getString("/router_name");
- setRemoteNode(router + "@" + domain + "/" + service);
- origRemoteNode = getRemoteNode();
-
-
- /** create a random thread */
- long time = new Date().getTime();
- Random rand = new Random(time);
- setThread(rand.nextInt()+""+rand.nextInt()+""+time+Thread.currentThread().getId());
-
- nextId = 0;
- requests = new HashMap<Integer, Request>();
- cacheSession();
- }
-
- /**
- * Creates a new request to send to our remote service.
- * @param method The method API name
- * @param params The list of method parameters
- * @return The request object.
- */
- public Request request(String method, List<Object> params) throws SessionException {
- return request(new Request(this, nextId++, method, params));
- }
-
- /**
- * Creates a new request to send to our remote service.
- * @param method The method API name
- * @param params The list of method parameters
- * @return The request object.
- */
- public Request request(String method, Object[] params) throws SessionException {
- return request(new Request(this, nextId++, method, Arrays.asList(params)));
- }
-
-
- /**
- * Creates a new request to send to our remote service.
- * @param method The method API name
- * @return The request object.
- */
- public Request request(String method) throws SessionException {
- return request(new Request(this, nextId++, method));
- }
-
-
- private Request request(Request req) throws SessionException {
- if(getConnectState() != ConnectState.CONNECTED)
- resetRemoteId();
- requests.put(new Integer(req.getId()), req);
- req.send();
- return req;
- }
-
-
- /**
- * Resets the remoteNode to its original state.
- */
- public void resetRemoteId() {
- setRemoteNode(origRemoteNode);
- }
-
-
- /**
- * Pushes a response onto the result queue of the appropriate request.
- * @param msg The received RESULT Message
- */
- public void pushResponse(Message msg) {
-
- Request req = findRequest(msg.getId());
- if(req == null) {
- /** LOG that we've received a result to a non-existant request */
- System.err.println(msg.getId() +" has no corresponding request");
- return;
- }
- OSRFObject payload = (OSRFObject) msg.get("payload");
-
- /** build a result and push it onto the request's result queue */
- req.pushResponse(
- new Result(
- payload.getString("status"),
- payload.getInt("statusCode"),
- payload.get("content")
- )
- );
- }
-
- public Request findRequest(int reqId) {
- return requests.get(new Integer(reqId));
- }
-
- /**
- * Removes a request for this session's request set
- */
- public void cleanupRequest(int reqId) {
- requests.remove(new Integer(reqId));
- }
-
- public void setRequestComplete(int reqId) {
- Request req = findRequest(reqId);
- if(req == null) return;
- req.setComplete();
- }
-
- public static Object atomicRequest(String service, String method, Object[] params) throws MethodException {
- try {
- ClientSession session = new ClientSession(service);
- Request osrfRequest = session.request(method, params);
- Result result = osrfRequest.recv(600000);
- if(result.getStatusCode() != 200)
- throw new MethodException(
- "Request "+service+":"+method+":"+" failed with status code " + result.getStatusCode());
- return result.getContent();
- } catch(Exception e) {
- throw new MethodException(e);
- }
- }
-}
-
+++ /dev/null
-package org.opensrf;
-import java.util.List;
-import java.util.ArrayList;
-import org.opensrf.util.ConfigException;
-
-public class MultiSession {
-
- class RequestContainer {
- Request request;
- int id;
- RequestContainer(Request r) {
- request = r;
- }
- }
-
- private boolean complete;
- private List<RequestContainer> requests;
- private int lastId;
-
- public MultiSession() {
- requests = new ArrayList<RequestContainer>();
- }
-
- public boolean isComplete() {
- return complete;
- }
-
- public int lastId() {
- return lastId;
- }
-
- /**
- * Adds a new request to the set of requests.
- * @param service The OpenSRF service
- * @param method The OpenSRF method
- * @param params The array of method params
- * @return The request ID, which is used to map results from recv() to the original request.
- */
- public int request(String service, String method, Object[] params) throws SessionException, ConfigException {
- ClientSession ses = new ClientSession(service);
- return request(ses.request(method, params));
- }
-
-
- public int request(String service, String method) throws SessionException, ConfigException {
- ClientSession ses = new ClientSession(service);
- return request(ses.request(method));
- }
-
- private int request(Request req) {
- RequestContainer c = new RequestContainer(req);
- c.id = requests.size();
- requests.add(c);
- return c.id;
- }
-
-
- /**
- * Calls recv on all pending requests until there is data to return. The ID which
- * maps the received object to the request can be retrieved by calling lastId().
- * @param millis Number of milliseconds to wait for some data to arrive.
- * @return The object result or null if all requests are complete
- * @throws MethodException Thrown if no response is received within
- * the given timeout or the method fails.
- */
- public Object recv(int millis) throws MethodException {
- if(complete) return null;
-
- Request req = null;
- Result res = null;
- RequestContainer cont = null;
-
- long duration = 0;
- long blockTime = 100;
-
- /* if there is only 1 outstanding request, don't poll */
- if(requests.size() == 1)
- blockTime = millis;
-
- while(true) {
- for(int i = 0; i < requests.size(); i++) {
-
- cont = requests.get(i);
- req = cont.request;
-
- try {
- if(i == 0) {
- res = req.recv(blockTime);
- } else {
- res = req.recv(0);
- }
- } catch(SessionException e) {
- throw new MethodException(e);
- }
-
- if(res != null) break;
- }
-
- if(res != null) break;
- duration += blockTime;
-
- if(duration >= millis) {
- System.out.println("duration = " + duration + " millis = " + millis);
- throw new MethodException("No request received within " + millis + " milliseconds");
- }
- }
-
- if(res.getStatusCode() != 200) {
- throw new MethodException("Request " + cont.id + " failed with status code " +
- res.getStatusCode() + " and status message " + res.getStatus());
- }
-
- if(req.isComplete())
- requests.remove(requests.indexOf(cont));
-
- if(requests.size() == 0)
- complete = true;
-
- lastId = cont.id;
- return res.getContent();
- }
-}
-
+++ /dev/null
-package org.opensrf;
-import java.util.Queue;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.List;
-import java.util.Date;
-import org.opensrf.net.xmpp.XMPPException;
-import org.opensrf.util.Logger;
-
-public class Request {
-
- /** This request's controlling session */
- private ClientSession session;
- /** The method */
- private Method method;
- /** The ID of this request */
- private int id;
- /** Queue of Results */
- private Queue<Result> resultQueue;
- /** If true, the receive timeout for this request should be reset */
- private boolean resetTimeout;
-
- /** If true, the server has indicated that this request is complete. */
- private boolean complete;
-
- /**
- * @param ses The controlling session for this request.
- * @param id This request's ID.
- * @param method The requested method.
- */
- public Request(ClientSession ses, int id, Method method) {
- this.session = ses;
- this.id = id;
- this.method = method;
- resultQueue = new ConcurrentLinkedQueue<Result>();
- complete = false;
- resetTimeout = false;
- }
-
- /**
- * @param ses The controlling session for this request.
- * @param id This request's ID.
- * @param methodName The requested method's API name.
- */
- public Request(ClientSession ses, int id, String methodName) {
- this(ses, id, new Method(methodName));
- }
-
- /**
- * @param ses The controlling session for this request.
- * @param id This request's ID.
- * @param methodName The requested method's API name.
- * @param params The list of request params
- */
- public Request(ClientSession ses, int id, String methodName, List<Object> params) {
- this(ses, id, new Method(methodName, params));
- }
-
- /**
- * Sends the request to the server.
- */
- public void send() throws SessionException {
- session.send(new Message(id, Message.REQUEST, method, session.getLocale()));
- }
-
- /**
- * Receives the next result for this request. This method
- * will wait up to the specified number of milliseconds for
- * a response.
- * @param millis Number of milliseconds to wait for a result. If
- * negative, this method will wait indefinitely.
- * @return The result or null if none arrives in time
- */
- public Result recv(long millis) throws SessionException, MethodException {
-
- Result result = null;
-
- if((result = resultQueue.poll()) != null)
- return result;
-
- if(millis < 0 && !complete) {
- /** wait potentially forever for a result to arrive */
- while(!complete) {
- session.waitForMessage(millis);
- if((result = resultQueue.poll()) != null)
- return result;
- }
-
- } else {
-
- while(millis >= 0 && !complete) {
-
- /** wait up to millis milliseconds for a result. waitForMessage()
- * will return if a response to any request arrives, so we keep track
- * of how long we've been waiting in total for a response to
- * this request */
-
- long start = new Date().getTime();
- session.waitForMessage(millis);
- millis -= new Date().getTime() - start;
- if((result = resultQueue.poll()) != null)
- return result;
- }
- }
-
- return null;
- }
-
- /**
- * Pushes a result onto the result queue
- * @param result The result to push
- */
- public void pushResponse(Result result) {
- resultQueue.offer(result);
- }
-
- /**
- * @return This request's ID
- */
- public int getId() {
- return id;
- }
-
- /**
- * Removes this request from the controlling session's request set
- */
- public void cleanup() {
- session.cleanupRequest(id);
- }
-
- /** Sets this request as complete */
- public void setComplete() {
- complete = true;
- }
-
- public boolean isComplete() {
- return complete;
- }
-}
+++ /dev/null
-package org.opensrf;
-
-/**
- * Models an OpenSRF server session.
- */
-public class ServerSession extends Session {
-}
-
+++ /dev/null
-package org.opensrf;
-import org.opensrf.util.JSONWriter;
-import org.opensrf.net.xmpp.*;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.Arrays;
-
-public abstract class Session {
-
- /** Represents the different connection states for a session */
- public enum ConnectState {
- DISCONNECTED,
- CONNECTING,
- CONNECTED
- };
-
- /** local cache of existing sessions */
- private static Map<String, Session>
- sessionCache = new HashMap<String, Session>();
-
- /** the current connection state */
- private ConnectState connectState;
-
- /** The address of the remote party we are communicating with */
- private String remoteNode;
-
- /** Session locale */
- protected String locale;
- /** Default session locale */
- protected static String defaultLocale = "en-US";
-
- /**
- * The thread is used to link messages to a given session.
- * In other words, each session has a unique thread, and all messages
- * in that session will carry this thread around as an indicator.
- */
- private String thread;
-
- public Session() {
- connectState = ConnectState.DISCONNECTED;
- }
-
- /**
- * Sends a Message to our remoteNode.
- */
- public void send(Message omsg) throws SessionException {
-
- /** construct the XMPP message */
- XMPPMessage xmsg = new XMPPMessage();
- xmsg.setTo(remoteNode);
- xmsg.setThread(thread);
- xmsg.setBody(new JSONWriter(Arrays.asList(new Message[] {omsg})).write());
-
- try {
- XMPPSession.getThreadSession().send(xmsg);
- } catch(XMPPException e) {
- connectState = ConnectState.DISCONNECTED;
- throw new SessionException("Error sending message to " + remoteNode, e);
- }
- }
-
- /**
- * Waits for a message to arrive over the network and passes
- * all received messages to the stack for processing
- * @param millis The number of milliseconds to wait for a message to arrive
- */
- public static void waitForMessage(long millis) throws SessionException, MethodException {
- try {
- Stack.processXMPPMessage(
- XMPPSession.getThreadSession().recv(millis));
- } catch(XMPPException e) {
- throw new SessionException("Error waiting for message", e);
- }
- }
-
- /**
- * Removes this session from the session cache.
- */
- public void cleanup() {
- sessionCache.remove(thread);
- }
-
- /**
- * Searches for the cached session with the given thread.
- * @param thread The session thread.
- * @return The found session or null.
- */
- public static Session findCachedSession(String thread) {
- return sessionCache.get(thread);
- }
-
- /**
- * Puts this session into session cache.
- */
- protected void cacheSession() {
- sessionCache.put(thread, this);
- }
-
- /**
- * Sets the remote address
- * @param nodeName The name of the remote node.
- */
- public void setRemoteNode(String nodeName) {
- remoteNode = nodeName;
- }
- /**
- * @return The remote node
- */
- public String getRemoteNode() {
- return remoteNode;
- }
-
-
- /**
- * Get thread.
- * @return thread as String.
- */
- public String getThread() {
- return thread;
- }
-
- /**
- * Set thread.
- * @param thread the value to set.
- */
- public void setThread(String thread) {
- this.thread = thread;
- }
-
- /**
- * Get locale.
- * @return locale as String.
- */
- public String getLocale() {
- if(locale == null)
- return defaultLocale;
- return locale;
- }
-
- /**
- * Set locale.
- * @param locale the value to set.
- */
- public void setLocale(String locale) {
- this.locale = locale;
- }
-
- /**
- * Get defaultLocale.
- * @return defaultLocale as String.
- */
- public String getDefaultLocale() {
- return defaultLocale;
- }
-
- /**
- * Set defaultLocale.
- * @param defaultLocale the value to set.
- */
- public void setDefaultLocale(String defaultLocale) {
- this.defaultLocale = defaultLocale;
- }
-
-
- /**
- * Get connectState.
- * @return connectState as ConnectState.
- */
- public ConnectState getConnectState() {
- return connectState;
- }
-
- /**
- * Set connectState.
- * @param connectState the value to set.
- */
- public void setConnectState(ConnectState connectState) {
- this.connectState = connectState;
- }
-}
+++ /dev/null
-package org.opensrf;
-import org.opensrf.net.xmpp.XMPPMessage;
-import org.opensrf.util.*;
-import java.util.Date;
-import java.util.List;
-import java.util.Iterator;
-
-
-public class Stack {
-
- public static void processXMPPMessage(XMPPMessage msg) throws MethodException {
-
- if(msg == null) return;
-
- //System.out.println(msg.getBody());
-
- /** fetch this session from the cache */
- Session ses = Session.findCachedSession(msg.getThread());
-
- if(ses == null) {
- /** inbound client request, create a new server session */
- return;
- }
-
- /** parse the JSON message body, which should result in a list of OpenSRF messages */
- List msgList;
-
- try {
- msgList = new JSONReader(msg.getBody()).readArray();
- } catch(JSONException e) {
- /** XXX LOG error */
- e.printStackTrace();
- return;
- }
-
- Iterator itr = msgList.iterator();
-
- OSRFObject obj = null;
- long start = new Date().getTime();
-
- /** cycle through the messages and push them up the stack */
- while(itr.hasNext()) {
-
- /** Construct a Message object from the parsed generic OSRFObject */
- obj = (OSRFObject) itr.next();
-
- processOSRFMessage(
- ses,
- new Message(
- obj.getInt("threadTrace"),
- obj.getString("type"),
- obj.get("payload")
- )
- );
- }
-
- /** LOG the duration */
- }
-
- private static void processOSRFMessage(Session ses, Message msg) throws MethodException {
-
- Logger.debug("received id=" + msg.getId() +
- " type=" + msg.getType() + " payload=" + msg.getPayload());
-
- if( ses instanceof ClientSession )
- processResponse((ClientSession) ses, msg);
- else
- processRequest((ServerSession) ses, msg);
- }
-
- /**
- * Process a server response
- */
- private static void processResponse(ClientSession session, Message msg) throws MethodException {
- String type = msg.getType();
-
- if(msg.RESULT.equals(type)) {
- session.pushResponse(msg);
- return;
- }
-
- if(msg.STATUS.equals(type)) {
-
- OSRFObject obj = (OSRFObject) msg.getPayload();
- Status stat = new Status(obj.getString("status"), obj.getInt("statusCode"));
- int statusCode = stat.getStatusCode();
- String status = stat.getStatus();
-
- switch(statusCode) {
- case Status.COMPLETE:
- session.setRequestComplete(msg.getId());
- break;
- case Status.NOTFOUND:
- session.setRequestComplete(msg.getId());
- throw new MethodException(status);
- }
- }
- }
-
- /**
- * Process a client request
- */
- private static void processRequest(ServerSession session, Message msg) {
- }
-}
+++ /dev/null
-package org.opensrf;
-
-import org.opensrf.util.*;
-import org.opensrf.net.xmpp.*;
-import java.util.Random;
-import java.util.Date;
-import java.net.InetAddress;
-
-
-public class Sys {
-
- private static void initLogger(Config config) {
- if(Logger.instance() == null) {
- try {
- String logFile = config.getString("/logfile");
- int logLevel = config.getInt("/loglevel");
- Logger.init( (short) config.getInt("/loglevel"), new FileLogger(logFile));
- /** add syslog support... */
- } catch(Exception e) {
- /* by default, log to stderr at WARN level */
- Logger.init(Logger.WARN, new Logger());
- }
- }
- }
-
- /**
- * Connects to the OpenSRF network so that client sessions may communicate.
- * @param configFile The OpenSRF config file
- * @param configContext Where in the XML document the config chunk lives. This
- * allows an OpenSRF client config chunk to live in XML files where other config
- * information lives.
- */
- public static void bootstrapClient(String configFile, String configContext)
- throws ConfigException, SessionException {
-
-
- /** see if the current thread already has a connection */
- XMPPSession existing = XMPPSession.getThreadSession();
- if(existing != null && existing.connected())
- return;
-
- /** create the config parser */
- Config config = new Config(configContext);
- config.parse(configFile);
- Config.setConfig(config); /* set this as the global config */
-
- initLogger(config);
-
- /** Collect the network connection info from the config */
- String username = config.getString("/username");
- String passwd = config.getString("/passwd");
- String host = (String) config.getFirst("/domain");
- int port = config.getInt("/port");
-
-
- /** Create a random login resource string */
- String res = "java_";
- try {
- res += InetAddress.getLocalHost().getHostAddress();
- } catch(java.net.UnknownHostException e) {}
- res += "_"+Math.abs(new Random(new Date().getTime()).nextInt())
- + "_t"+ Thread.currentThread().getId();
-
-
-
- try {
-
- /** Connect to the Jabber network */
- Logger.info("attempting to create XMPP session "+username+"@"+host+"/"+res);
- XMPPSession xses = new XMPPSession(host, port);
- xses.connect(username, passwd, res);
- XMPPSession.setThreadSession(xses);
-
- } catch(XMPPException e) {
- throw new SessionException("Unable to bootstrap client", e);
- }
- }
-
- /**
- * Shuts down the connection to the opensrf network
- */
- public static void shutdown() {
- XMPPSession.getThreadSession().disconnect();
- }
-}
-
+++ /dev/null
-package org.opensrf.util;
-import com.danga.MemCached.*;
-import java.util.List;
-
-/**
- * Memcache client
- */
-public class Cache extends MemCachedClient {
-
- public Cache() {
- super();
- setCompressThreshold(4096); /* ?? */
- }
-
- /**
- * Initializes the cache client
- * @param serverList Array of server:port strings specifying the
- * set of memcache servers this client will talk to
- */
- public static void initCache(String[] serverList) {
- SockIOPool pool = SockIOPool.getInstance();
- pool.setServers(serverList);
- pool.initialize();
- com.danga.MemCached.Logger logger =
- com.danga.MemCached.Logger.getLogger(MemCachedClient.class.getName());
- logger.setLevel(logger.LEVEL_ERROR);
- }
-
- /**
- * Initializes the cache client
- * @param serverList List of server:port strings specifying the
- * set of memcache servers this client will talk to
- */
- public static void initCache(List<String> serverList) {
- initCache(serverList.toArray(new String[]{}));
- }
-}
-
+++ /dev/null
-package org.opensrf.util;
-import org.opensrf.*;
-import java.util.Map;
-
-/**
- * Connects to the OpenSRF Settings server to fetch the settings config.
- * Provides a Config interface for fetching settings via path
- */
-public class SettingsClient extends Config {
-
- /** Singleton SettingsClient instance */
- private static SettingsClient client = new SettingsClient();
-
- public SettingsClient() {
- super("");
- }
-
- /**
- * @return The global settings client instance
- */
- public static SettingsClient instance() throws ConfigException {
- if(client.getConfigObject() == null)
- client.fetchConfig();
- return client;
- }
-
- /**
- * Fetches the settings object from the settings server
- */
- private void fetchConfig() throws ConfigException {
-
- ClientSession ses = new ClientSession("opensrf.settings");
- try {
-
- Request req = ses.request(
- "opensrf.settings.host_config.get",
- new String[]{(String)Config.global().getFirst("/domain")});
-
- Result res = req.recv(12000);
- if(res == null) {
- /** throw exception */
- }
- setConfigObject((Map) res.getContent());
-
- } catch(Exception e) {
- throw new ConfigException("Error fetching settings config", e);
-
- } finally {
- ses.cleanup();
- }
- }
-}
-
+++ /dev/null
-package org.opensrf.util;
-
-import javax.xml.stream.*;
-import javax.xml.stream.events.* ;
-import javax.xml.namespace.QName;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.ListIterator;
-import java.io.InputStream;
-import org.opensrf.util.JSONWriter;
-import org.opensrf.util.JSONReader;
-
-/**
- * Flattens an XML file into a properties map. Values are stored as JSON strings or arrays.
- * An array is created if more than one value resides at the same key.
- * e.g. html.head.script = "alert('hello');"
- */
-public class XMLFlattener {
-
- /** Flattened properties map */
- private Map<String, String> props;
- /** Incoming XML stream */
- private InputStream inStream;
- /** Runtime list of encountered elements */
- private List<String> elementList;
-
- /**
- * Creates a new reader. Initializes the message queue.
- * Sets the stream state to disconnected, and the xml
- * state to in_nothing.
- * @param inStream the inbound XML stream
- */
- public XMLFlattener(InputStream inStream) {
- props = new HashMap<String, String>();
- this.inStream = inStream;
- elementList = new ArrayList<String>();
- }
-
- /** Turns an array of strings into a dot-separated key string */
- private String listToString() {
- ListIterator itr = elementList.listIterator();
- StringBuffer sb = new StringBuffer();
- while(itr.hasNext()) {
- sb.append(itr.next());
- if(itr.hasNext())
- sb.append(".");
- }
- return sb.toString();
- }
-
- /**
- * Parses XML data from the provided stream.
- */
- public Map read() throws javax.xml.stream.XMLStreamException {
-
- XMLInputFactory factory = XMLInputFactory.newInstance();
-
- /** disable as many unused features as possible to speed up the parsing */
- factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
- factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
- factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
- factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
- factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
-
- /** create the stream reader */
- XMLStreamReader reader = factory.createXMLStreamReader(inStream);
- int eventType;
-
- while(reader.hasNext()) {
- /** cycle through the XML events */
-
- eventType = reader.next();
- if(reader.isWhiteSpace()) continue;
-
- switch(eventType) {
-
- case XMLEvent.START_ELEMENT:
- elementList.add(reader.getName().toString());
- break;
-
- case XMLEvent.CHARACTERS:
- String text = reader.getText();
- String key = listToString();
-
- if(props.containsKey(key)) {
-
- /* something in the map already has this key */
-
- Object o = null;
- try {
- o = new JSONReader(props.get(key)).read();
- } catch(org.opensrf.util.JSONException e){}
-
- if(o instanceof List) {
- /* if the map contains a list, append to the list and re-encode */
- ((List) o).add(text);
-
- } else {
- /* if the map just contains a string, start building a new list
- * with the old string and append the new string */
- List<String> arr = new ArrayList<String>();
- arr.add((String) o);
- arr.add(text);
- o = arr;
- }
-
- props.put(key, new JSONWriter(o).write());
-
- } else {
- props.put(key, new JSONWriter(text).write());
- }
- break;
-
- case XMLEvent.END_ELEMENT:
- elementList.remove(elementList.size()-1);
- break;
- }
- }
-
- return props;
- }
-}
-
-
-
-