public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String strCallResult = ""; resp.setContentType("text/plain"); String strId = req.getParameter("id"); String strCount = req.getParameter("count"); int id = -1; int count = -1; try { id = Integer.valueOf(strId); count = Integer.valueOf(strCount); } catch (NumberFormatException e) { e.printStackTrace(); } try { TopsCalculator.getTopUrlsForDay(); TopsCalculator.getTopUrlsForMonth(); TopsCalculator.getTopUrlsForYear(); TopsCalculator.getTopHostsForDay(); TopsCalculator.getTopHostsForMonth(); TopsCalculator.getTopHostsForYear(); if (id == 0) { DbHelper.setStartTime(System.currentTimeMillis()); } else if (id == count - 1) { DbHelper.setRunTime(System.currentTimeMillis() - DbHelper.getStartTime()); } } catch (Exception ex) { strCallResult = "FAIL: Fetching top lists"; System.out.println(strCallResult); } }
public void processAlgorithm() { List<List<Double>> testData = data.getTestData(); int testNum = data.getTestNum(); long begin = System.currentTimeMillis(); for (int i = 0; i < testNum; i++) { List<Double> test = testData.get(i); result[i][0] = Arith.convertsToInt(test.get(0)); result[i][1] = Math.round(Float.parseFloat((knn(data.getTrainData(), test, 3)))); if (result[i][0] != result[i][1]) { ma.setWrong(ma.getWrong() + 1); } } long end = System.currentTimeMillis(); ma.setTime(begin, end); ma.setAccuracyRate(ma.getWrong(), testNum); ma.setErrorRate(ma.getWrong(), testNum); }
// The default constructor public CrownCounselIndexGetList_Access() { String traceProp = null; if ((traceProp = System.getProperty(HOSTPUBLISHER_ACCESSBEAN_TRACE)) != null) { try { Class c = Class.forName(HOSTPUBLISHER_ACCESSTRACE_OBJECT); Method m = c.getMethod("getInstance", null); o = m.invoke(null, null); Class parmTypes[] = {String.class}; m = c.getMethod("initTrace", parmTypes); Object initTraceArgs[] = {traceProp}; BitSet tracingBS = (BitSet) m.invoke(o, initTraceArgs); Class parmTypes2[] = {Object.class, String.class}; traceMethod = c.getMethod("trace", parmTypes2); tracing = tracingBS.get(HOSTPUBLISHER_ACCESSBEAN_TRACING); Class parmTypes3[] = {String.class, HttpSession.class}; auditMethod = c.getMethod("audit", parmTypes3); auditing = tracingBS.get(HOSTPUBLISHER_ACCESSBEAN_AUDITING); } catch (Exception e) { // no tracing will be done System.err.println( (new Date(System.currentTimeMillis())).toString() + " hostpublisher.accessbean.trace=" + traceProp + ", Exception=" + e.toString()); } } if (tracing == true) { traceArgs[0] = this; traceArgs[1] = " CrownCounselIndexGetList_Access()"; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { System.err.println( (new Date(System.currentTimeMillis())).toString() + " traceMethod.invoke(null, traceArgs)" + ", Exception=" + x.toString()); } } inputProps = new CrownCounselIndexGetList_Properties(); return; }
@Override protected Response process(HttpServletRequest req, HttpServletResponse res) throws Exception { Scanner scanner = new Scanner(req.getInputStream()); setSysTime(getControllerTime(scanner)); PingResponse response = new PingResponse(); DriverInfo info = driver.getDriverInfo(); response.setName(info.getName()); response.setAddress(info.getUrl()); response.setTimeStamp(String.valueOf(System.currentTimeMillis())); return response; }
/** @service the servlet service request. called once for each servlet request. */ public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException { String name; String value[]; String val; servRes.setHeader("AUTHORIZATION", "user fred:mypassword"); ServletOutputStream out = servRes.getOutputStream(); HttpSession session = servReq.getSession(true); session.setAttribute("timemilis", new Long(System.currentTimeMillis())); if (session.isNew()) { out.println("<p> Session is new "); } else { out.println("<p> Session is not new "); } Long l = (Long) session.getAttribute("timemilis"); out.println("<p> Session id = " + session.getId()); out.println("<p> TimeMillis = " + l); out.println("<H2>Servlet Params</H2>"); Enumeration e = servReq.getParameterNames(); while (e.hasMoreElements()) { name = (String) e.nextElement(); value = servReq.getParameterValues(name); out.println(name + " : "); for (int i = 0; i < value.length; ++i) { out.println(value[i]); } out.println("<p>"); } out.println("<H2> Request Headers : </H2>"); e = servReq.getHeaderNames(); while (e.hasMoreElements()) { name = (String) e.nextElement(); val = (String) servReq.getHeader(name); out.println("<p>" + name + " : " + val); } try { BufferedReader br = servReq.getReader(); String line = null; while (null != (line = br.readLine())) { out.println(line); } } catch (IOException ie) { ie.printStackTrace(); } session.invalidate(); }
private synchronized Scope _scope() { if (_inScopeSetup) return _scope; if (_getScopeTime() > _lastScopeInitTime) _scopeInited = false; if (_scopeInited) return _scope; _scopeInited = true; _lastScopeInitTime = System.currentTimeMillis(); _setupScope(); _setStaticAdapterType(); _setAdapterSelectorFunction(); return _scope; }
private void setNoCacheHeaders(HttpServletResponse pResp) { pResp.setHeader("Cache-Control", "no-cache"); pResp.setHeader("Pragma", "no-cache"); // Check for a date header and set it accordingly to the recommendations of // RFC-2616 (http://tools.ietf.org/html/rfc2616#section-14.21) // // "To mark a response as "already expired," an origin server sends an // Expires date that is equal to the Date header value. (See the rules // for expiration calculations in section 13.2.4.)" // // See also #71 long now = System.currentTimeMillis(); pResp.setDateHeader("Date", now); // 1h in the past since it seems, that some servlet set the date header on their // own so that it cannot be guaranteed that these headers are really equals. // It happened on Tomcat that Date: was finally set *before* Expires: in the final // answers some times which seems to be an implementation peculiarity from Tomcat pResp.setDateHeader("Expires", now - 3600000); }
private void logOut(String browserId) throws Exception { // ttt2 the right way to do it is to go through all the sessions of the current browser, which // would require a new field and a new index; // not sure if it's worth it, but this would work: A logs in, forgets to log out, B delets the // cookies, logs in, A sees B is logged in, then B // restores the cookies and uses A's account if (browserId == null) { return; } List<LoginInfo> loginInfos = loginInfoDb.getLoginsForBrowser(browserId); long expireTarget = System.currentTimeMillis() - Utils.ONE_DAY; for (LoginInfo loginInfo : loginInfos) { if (loginInfo.expiresOn <= expireTarget) { LOG.info(String.format("LoginInfo %s is enough in the past", loginInfo)); } else { LOG.info(String.format("Logging out: %s", loginInfo)); loginInfoDb.updateExpireTime(browserId, loginInfo.sessionId, expireTarget); } } }
public static synchronized void sessionCreated(HttpSessionEvent ev) { HttpSession httpSession = ev.getSession(); String id = httpSession.getId(); // Remember HTTP-session: { lookupHttpSessionById.put(id, httpSession); } AbstractSession session = null; synchronized (lookupSessionById) { session = lookupSessionById.get(id); } if (session == null) { Principal userPrincipal = null; Date timeCreation = new Date(httpSession.getCreationTime()); Date timeLastAccess = new Date(httpSession.getLastAccessedTime()); List<String> urisForLastRequests = null; Properties properties = null; session = new DefaultSession( id, userPrincipal, timeCreation, timeLastAccess, urisForLastRequests, properties); synchronized (lookupSessionById) { lookupSessionById.put(id, session); // Update 'sessionCountMax': { int sessionCount = lookupSessionById.size(); if (sessionCount > sessionCountMax) { sessionCountMax = sessionCount; sessionCountMaxTime = System.currentTimeMillis(); } } } } }
/** all processing methods end up here */ private void startHereCommon() throws BeanException { // try to get the linkKey if already set in input properties try { hPubLinkKey = inputProps.getHPubLinkKey(); } catch (Exception e) { } // if running in Web environment and either the ejb access handle or // the linkKey are null, try to get them from the HttpSession if (oHttpServletRequest != null) { HttpSession theWebsession = oHttpServletRequest.getSession(false); if (theWebsession != null) { synchronized (theWebsession) { try { if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "HttpSession.getId()=" + theWebsession.getId(); try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } String theKey = KEY_WEBCONN + inputProps.getHPubStartChainName(); // if linkKey or access handle is null try to get it from Websession HPubEJB2HttpSessionBindingListener sbl = (HPubEJB2HttpSessionBindingListener) theWebsession.getAttribute(theKey); if ((hPubLinkKey == null) && (sbl != null)) { hPubLinkKey = sbl.getLinkKey(); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "HttpSession.getAttribute(hPubLinkKey)=" + hPubLinkKey; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } inputProps.setHPubLinkKey(hPubLinkKey); } if ((hPubAccessHandle == null) && (sbl != null)) { hPubAccessHandle = sbl.getEjbHandle(); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "HttpSession.getAttribute(hPubAccessHandle)=" + hPubAccessHandle; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } } // set the ejb handle to null before removing the Session Binding // Listener object if (auditing == true) { if (sbl != null) auditArgs[0] = "\n---\nOUT:" + this.getClass().getName() + " " + theKey + " " + hPubAccessHandle + " " + hPubLinkKey + " " + theWebsession.getId(); else // error - object not found in HttpSession auditArgs[0] = "\n---\nERR:" + this.getClass().getName() + " " + theKey + " " + theWebsession.getId(); auditArgs[1] = theWebsession; try { auditMethod.invoke(o, auditArgs); } catch (Exception x) { } } if (sbl != null) sbl.setEjbHandle(null); theWebsession.removeAttribute(theKey); } catch (IllegalStateException e) { } } } } // if either of required properties are still null then the ejb cannot // be accessed - throw an exception. if ((hPubAccessHandle == null) || (hPubLinkKey == null)) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5951 " + this.getClass().getName() + ": hPubAccessHandle==null || hPubLinkKey==null"; System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } else { if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "hPubAccessHandle=" + hPubAccessHandle + ",hPubLinkKey=" + hPubLinkKey; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } } // get the EJB object from the handle try { ejb = (com.ibm.HostPublisher.EJB.HPubEJB2) javax.rmi.PortableRemoteObject.narrow( hPubAccessHandle.getEJBObject(), com.ibm.HostPublisher.EJB.HPubEJB2.class); } catch (Exception e) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5952 " + this.getClass().getName() + ": getEJBObject(): " + e.getClass().getName() + ": " + e.getMessage(); System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } // if ejb handle, go invoke the HPubEJB's main business method. if (ejb != null) { try { outputProps = (CrownCounselIndexGetList_Properties) ejb.processIO(inputProps); inputProps = outputProps; inputProps.setInitialCall(false); } catch (Exception e) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5953 " + this.getClass().getName() + ": processIO(" + inputProps.getClass().getName() + "): " + e.getClass().getName() + ": " + e.getMessage(); System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } } endHereCommon(); return; }
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // All request in GET method must be certificated Object obj = session.getAttribute("device_id"); if (!(obj instanceof Long)) { // Client must be login first, then use Mobile service response.setStatus(404); return; } response.setContentType("text/plain"); PrintWriter out = response.getWriter(); // Here is tracked's id Long device_id = (Long) obj; // Determine operation type String op = request.getParameter("op"); if (op == null) op = ""; // Get current track Long track_id = null; obj = session.getAttribute("track_id"); if (obj instanceof Long) { track_id = (Long) obj; } if (op.equals("logout")) { // Client request a logout operation session.removeAttribute("device_id"); session.removeAttribute("track_id"); out.print("OK," + device_id); } else if (op.equals("latlng")) { // Client insert update it's location in latitude/longitude // If it's a first waypoint, create a new track if (track_id == null) { track_id = db.newTrack(device_id).getResult().getTrackID(); session.setAttribute("track_id", track_id); } // Parse latitude, longitude from request double lat = Double.parseDouble(request.getParameter("lat")); double lng = Double.parseDouble(request.getParameter("lng")); long speed = -1L; try { // Try to get speed from request speed = Long.parseLong(request.getParameter("spd")); } catch (Exception ex) { } if (speed < 0) { // Client don't send speed to server try { // Calculate speed manually double lastLat = (Double) session.getAttribute("latitude"); double lastLng = (Double) session.getAttribute("longitude"); long time = (Long) session.getAttribute("time"); long distance = Utils.getDistance(lastLat, lastLng, lat, lng); speed = distance * 1000 / Math.abs(time - System.currentTimeMillis()); } catch (Exception ex) { speed = 0L; } } // Insert new point into server ServiceResult<CWaypoint> result = db.insertWaypoint(track_id, lat, lng, speed); CWaypoint cwaypoint = result.getResult(); if (result.isOK()) { // OK,latitude,longitude,speed(m/s),time,trackid session.setAttribute("latitude", lat); session.setAttribute("longitude", lng); session.setAttribute("time", cwaypoint.getTime().getTime()); out.print( "OK," + cwaypoint.getLat() + "," + cwaypoint.getLng() + "," + cwaypoint.getSpeed() + "," + cwaypoint.getTime().getTime() + "," + cwaypoint.getTrackID()); } } else if (op.equals("cellid")) { // Client send it's location by cellular technique if (track_id == null) { track_id = db.newTrack(device_id).getResult().getTrackID(); session.setAttribute("track_id", track_id); } try { int cell = Integer.parseInt(request.getParameter("cell")); int lac = Integer.parseInt(request.getParameter("lac")); Geocode geocode = Utils.getLocation(cell, lac); out.println(geocode.getLatitude() + "," + geocode.getLongitude()); } catch (Exception ex) { } // TODO Implements cellular method to calculate location of a mobile out.println("Not implement"); } else if (op.equals("newtrack")) { // Client request to create a new track track_id = db.newTrack(device_id).getResult().getTrackID(); session.setAttribute("track_id", track_id); out.print("OK," + track_id); } else if (op.equals("changepass")) { String newpass = request.getParameter("newpass"); if (newpass != null) { CTracked ctracked = new CTracked(); ctracked.setUsername(device_id); ctracked.setPassword(newpass); if (db.updateTracked(ctracked).isOK()) { out.println("OK," + device_id); } } } else if (op.equals("config")) { CTracked ctracked = db.getTracked(device_id).getResult(); Integer interval = ctracked.getIntervalGps(); if (interval == null) interval = 10; out.print("OK," + interval + ","); byte[] b = ctracked.getSchedule(); if (b == null) { for (int i = 0; i < 23; i++) { out.print("1."); } out.println(1); } else { for (int i = 0; i < 23; i++) { out.print(b[i] + "."); } out.println(b[23]); } } else if (op.equals("amilogin")) { out.println("OK"); } }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Long timeIni = System.currentTimeMillis(); HttpSession sesion = request.getSession(); try { // usuario actual Usuario usuario = new Usuario(); if (sesion.getAttribute("usuario") != null) { usuario = (Usuario) sesion.getAttribute("usuario"); } // configuración de paginación String path = getServletContext().getRealPath("WEB-INF/config.xml"); int docsPagina = Config.getInitPages(usuario.getId(), path, "documents"); sesion.setAttribute("configPath", path); // privacidad de los documentos String cond = "(PRIVADO = 0 OR (PRIVADO = 1 AND ID_USUARIO = " + usuario.getId() + "))"; // filtro de búsqueda String buscar = request.getParameter("buscar"); if (buscar != null) { if (Convert.isValidDate(buscar)) { buscar = Utiles.dateToMySQLDate(Convert.parseDate(buscar), false); } cond += " AND (TITULO LIKE('%" + buscar + "%') "; cond += " OR CONTENIDO LIKE('%" + buscar + "%') "; cond += " OR ETIQUETAS LIKE('%" + buscar + "%') "; cond += " OR FECHA LIKE ('%" + buscar + "%') "; for (Usuario u : new UsuarioDAO().findAllUsuario()) { if (u.getNombre().toLowerCase().contains(buscar.toLowerCase()) || u.getApe1().toLowerCase().contains(buscar.toLowerCase()) || u.getApe2().toLowerCase().contains(buscar.toLowerCase())) { cond += " OR ID_USUARIO = " + u.getId(); } } cond += ") "; } DocumentoDAO documentoDAO = new DocumentoDAO(); sesion.setAttribute( "allDocuments", (ArrayList) documentoDAO.findAllDocumento(docsPagina, cond)); if (count == 1) { sesion.setAttribute("dataMenu", (ArrayList) documentoDAO.findAllDocumento(cond)); count++; } } catch (Exception ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } finally { Long timeEnd = System.currentTimeMillis(); System.out.println("Duración de procesado " + getServletName() + ": " + (timeEnd - timeIni)); ServletContext cont = getServletConfig().getServletContext(); RequestDispatcher reqDispatcher = cont.getRequestDispatcher("/index.jsp"); reqDispatcher.forward(request, response); } }
/** * TODO: Decide if we want to alter the jam:start() behavior so it connects to the server as a test. * This has the benefit that any server restart will HUP a client halfway through something because * the context will disappear rather than be implicitly recreated to an empty state. TODO: Consider * adding a feature so jam:start() can provide a user-specified stale-out duration for the context. */ public class MLJAM extends HttpServlet { private static HashMap<String, Interpreter> interpreters = new HashMap<String, Interpreter>(); // Need to retire interpreters after some period of inactivity. // Temporary interpreters (those w/ client assigned names) expire faster private static long lastClean = System.currentTimeMillis(); private static long CLEAN_INTERVAL = 5 * 60 * 1000; // five minutes private static long STALE_TIMEOUT = 60 * 60 * 1000; // one hour private static long TEMP_STALE_TIMEOUT = 60 * 60 * 1000; // ten minutes private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ"); /* public void init(ServletConfig config) throws ServletException { super.init(config); } */ private static Interpreter getInterpreter(String contextId) throws EvalError { // Get the appropriate interpreter Interpreter i = null; boolean createdInterp = false; synchronized (interpreters) { // serialize two gets of the same name i = interpreters.get(contextId); if (i == null) { i = new Interpreter(); interpreters.put(contextId, i); createdInterp = true; } } if (createdInterp) { Log.log("Created context: " + contextId + " (" + i + ")"); // Now configure stdin and stdout to capture 10k of content // Store references to the circular buffers within the interpreter itself. // This provides a nice place to store them plus theoretically allows // advanced use from within the bsh environment. // On Windows print() outputs \r\n but in XQuery that's normalized to \n // so the 10k of Java buffer may produce less than 10k of content in XQuery! OutputStream circularOutput = new CircularByteArrayOutputStream(10240); PrintStream printOutput = new PrintStream(circularOutput); i.setOut(printOutput); i.set("mljamout", circularOutput); OutputStream circularError = new CircularByteArrayOutputStream(10240); PrintStream printError = new PrintStream(circularError); i.setErr(printError); i.set("mljamerr", circularError); // Capture the built-in System.out and System.err also. // (Commented out since System appears global, can't do per interpreter.) // i.set("mljamprintout", printOutput); // i.set("mljamprinterr", printError); // i.eval("System.setOut(mljamprintout);"); // i.eval("System.setErr(mljamprinterr);"); // Need to expose hexdecode() and base64decode() built-in functions i.eval("hexdecode(String s) { return com.xqdev.jam.MLJAM.hexDecode(s); }"); i.eval("base64decode(String s) { return com.xqdev.jam.MLJAM.base64Decode(s); }"); // Let's tell the context what its id is i.set("mljamid", contextId); } // Update the last accessed time, used for cleaning i.set("mljamlast", System.currentTimeMillis()); // If it's been long enough, go snooping for stale contexts if (System.currentTimeMillis() > lastClean + CLEAN_INTERVAL) { Log.log("Initiated periodic scan for stale context objects"); lastClean = System.currentTimeMillis(); Iterator<Interpreter> itr = interpreters.values().iterator(); while (itr.hasNext()) { Interpreter interp = itr.next(); Long last = (Long) interp.get("mljamlast"); if (System.currentTimeMillis() > last + STALE_TIMEOUT) { itr.remove(); Log.log("Staled context: " + interp.get("mljamid") + " (" + interp + ")"); } else if ((System.currentTimeMillis() > last + TEMP_STALE_TIMEOUT) && ("" + interp.get("mljamid")).startsWith("temp:")) { itr.remove(); Log.log("Staled temp context: " + interp.get("mljamid") + " (" + interp + ")"); } } } return i; } private static void endInterpreter(String contextId) throws EvalError { Interpreter i = interpreters.get(contextId); if (i == null) return; i.eval("clear();"); // can't hurt to tell bsh to clean up internally interpreters.remove(contextId); // now wait for GC Log.log("Destroyed context: " + contextId + " (" + i + ")"); } private static String getBody(HttpServletRequest req) { try { // Try reading the post body using characters. // This might throw an exception if something on the // server side already called getInputStream(). // In that case we'll pull as bytes. Reader reader = null; try { reader = new BufferedReader(req.getReader()); } catch (IOException e) { reader = new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")); } StringBuffer sbuf = new StringBuffer(); char[] cbuf = new char[4096]; int count = 0; while ((count = reader.read(cbuf)) != -1) { sbuf.append(cbuf, 0, count); } return sbuf.toString(); } catch (IOException e2) { throw new ServerProblemException("IOException in reading POST body: " + e2.getMessage()); } } protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { // A good request looks like /mljam/contextid/verb?name=varname // The extra path info includes the context id and verb String extra = req.getPathInfo(); // "/contextid/verb" if (extra == null || extra.equals("")) { throw new ClientProblemException( "Request requires a context id and verb in its extra path info"); } String[] parts = extra.split("/"); // { "", "contextid", "verb" } if (parts.length < 2) { throw new ClientProblemException( "Request requires a context id and verb in its extra path info"); } else if (parts.length < 3) { throw new ClientProblemException("Request requires a verb in its extra path info"); } String contextId = parts[1]; String verb = parts[2]; String method = req.getMethod(); if (method.equalsIgnoreCase("get")) { // We have three GET verbs: get, get-stdout, get-stderr. // These are all idempotent, while the POST verbs aren't. The get // verb accept a "name" query string parameter. The get verb returns // either XQuery to evaluate (indicated by x-marklogic/xquery content type) // or a raw binary (indicated by an application/binary-encoded content type). if (verb.equalsIgnoreCase("get")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The get verb requires a name parameter"); } Interpreter i = getInterpreter(contextId); Object o = i.get(name); if (o instanceof byte[]) { sendBinaryResponse(res, (byte[]) o); } else if (o instanceof String) { sendStringResponse(res, (String) o); } else { sendXQueryResponse(res, o); } } else if (verb.equalsIgnoreCase("get-stdout")) { Interpreter i = getInterpreter(contextId); i.getOut().flush(); CircularByteArrayOutputStream circ = (CircularByteArrayOutputStream) i.get("mljamout"); if (circ != null) { sendStringResponse(res, circ.toString()); circ.reset(); } else { throw new ServerProblemException("Could not fetch mljamout from interpreter context"); } } else if (verb.equalsIgnoreCase("get-stderr")) { Interpreter i = getInterpreter(contextId); i.getErr().flush(); CircularByteArrayOutputStream circ = (CircularByteArrayOutputStream) i.get("mljamerr"); if (circ != null) { sendStringResponse(res, circ.toString()); circ.reset(); } else { throw new ServerProblemException("Could not fetch mljamerr from interpreter context"); } } else { throw new ClientProblemException("Unrecognized GET verb: " + verb); } } else if (method.equalsIgnoreCase("post")) { // We have six POST verbs: eval, unset, end, source, set-string, and set-binary. // These are POST verbs because they aren't idempotent. // The set-string, set-binary, unset, and source verbs accept a "name" // query string parameter. The set-string and set-binary verbs accept // a value in their post body. The eval verb accepts code in its post body. if (verb.equalsIgnoreCase("set-string")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The set-string verb requires a name parameter"); } String body = getBody(req); // a value of "" is legit Interpreter i = getInterpreter(contextId); i.unset(name); i.set(name, body); sendNoResponse(res); } else if (verb.equalsIgnoreCase("set-binary")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The set-binary verb requires a name parameter"); } String body = getBody(req); // a value of "" is legit byte[] bodyBytes = hexDecode(body); // later could do this streaming for speed Interpreter i = getInterpreter(contextId); i.unset(name); i.set(name, bodyBytes); sendNoResponse(res); } else if (verb.equalsIgnoreCase("eval")) { String body = getBody(req); if (body == null || body.equals("")) { throw new ClientProblemException( "The eval verb requires a post body containing code to eval"); } Interpreter i = getInterpreter(contextId); i.eval(body); sendNoResponse(res); } else if (verb.equalsIgnoreCase("eval-get")) { String body = getBody(req); if (body == null || body.equals("")) { throw new ClientProblemException( "The eval-get verb requires a post body containing code to eval"); } Interpreter i = getInterpreter(contextId); Object o = i.eval(body); if (o instanceof byte[]) { sendBinaryResponse(res, (byte[]) o); } else if (o instanceof String) { sendStringResponse(res, (String) o); } else { sendXQueryResponse(res, o); } } else if (verb.equalsIgnoreCase("unset")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The unset verb requires a name parameter"); } Interpreter i = getInterpreter(contextId); i.unset(name); sendNoResponse(res); } else if (verb.equalsIgnoreCase("end")) { endInterpreter(contextId); sendNoResponse(res); } else if (verb.equalsIgnoreCase("source")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The source verb requires a name parameter"); } Interpreter i = getInterpreter(contextId); i.source(name); sendNoResponse(res); } else { throw new ClientProblemException("Unrecognized POST verb: " + verb); } } } catch (TargetError e) { Throwable target = e.getTarget(); Log.log(e); Log.log("Target: " + target); sendServerProblemResponse( res, target.getClass().getName() + ": " + target.getMessage() + " when executing Java code: " + e.getErrorText()); // include full trace? } catch (EvalError e) { Log.log(e); sendServerProblemResponse( res, e.getClass().getName() + ": " + e.getMessage()); // include full trace? } catch (ClientProblemException e) { Log.log(e); sendClientProblemResponse(res, e.getMessage()); } catch (ServerProblemException e) { Log.log(e); sendServerProblemResponse(res, e.getMessage()); } } private static String escapeSingleQuotes(String s) { return s.replaceAll("'", "''"); } public static byte[] hexDecode(String s) { try { return Hex.decodeHex(s.toCharArray()); } catch (DecoderException e) { throw new ClientProblemException( "Hex content is not valid hex: " + e.getMessage() + ": " + s); } } private static String hexEncode(byte[] bytes) { return new String(Hex.encodeHex(bytes)); } public static byte[] base64Decode(String s) { try { return Base64.decodeBase64(s.getBytes("ISO-8859-1")); } catch (UnsupportedEncodingException e) { throw new ServerProblemException("Server does not recognize ISO-8859-1 encoding"); } } private static void sendClientProblemResponse(HttpServletResponse res, String s) throws IOException { // Commenting out the status code because we want the client to eval the error() call // res.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (s != null && s.length() > 4096) { // Cap super long errors s = s.substring(0, 2048) + " ...[trimmed]... " + s.substring(s.length() - 2048); } res.setContentType("x-marklogic/xquery; charset=UTF-8"); Writer writer = res.getWriter(); writer.write("error('" + escapeSingleQuotes(s) + "')"); writer.flush(); } private static void sendServerProblemResponse(HttpServletResponse res, String s) throws IOException { // Commenting out the status code because we want the client to eval the error() call // res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); res.setContentType("x-marklogic/xquery; charset=UTF-8"); if (s != null && s.length() > 4096) { // Cap super long errors s = s.substring(0, 2048) + " ...[trimmed]... " + s.substring(s.length() - 2048); } Writer writer = res.getWriter(); writer.write("error('" + escapeSingleQuotes(s) + "')"); writer.flush(); } private static void sendNoResponse(HttpServletResponse res) { res.setStatus(HttpServletResponse.SC_NO_CONTENT); } private static void sendBinaryResponse(HttpServletResponse res, byte[] bytes) throws IOException { res.setContentType("application/binary-encoded"); OutputStream out = res.getOutputStream(); // care to handle errors later? out.write(bytes); out.flush(); } private static void sendStringResponse(HttpServletResponse res, String s) throws IOException { res.setContentType("text/plain; charset=UTF-8"); Writer w = res.getWriter(); w.write(s); w.flush(); } private static void sendXQueryResponse(HttpServletResponse res, Object o) throws IOException { // Make sure to leave the status code alone. It defaults to 200, but sometimes // callers of this method will have set it to a custom code. res.setContentType("x-marklogic/xquery; charset=UTF-8"); // res.setContentType("text/plain"); Writer writer = res.getWriter(); // care to handle errors later? if (o == null) { writer.write("()"); } else if (o instanceof byte[]) { writer.write("binary {'"); writer.write(hexEncode((byte[]) o)); writer.write("'}"); } else if (o instanceof Object[]) { Object[] arr = (Object[]) o; writer.write("("); for (int i = 0; i < arr.length; i++) { sendXQueryResponse(res, arr[i]); if (i + 1 < arr.length) writer.write(", "); } writer.write(")"); } else if (o instanceof String) { writer.write("'"); writer.write(escapeSingleQuotes(o.toString())); writer.write("'"); } else if (o instanceof Integer) { writer.write("xs:int("); writer.write(o.toString()); writer.write(")"); } else if (o instanceof Long) { writer.write("xs:integer("); writer.write(o.toString()); writer.write(")"); } else if (o instanceof Float) { Float flt = (Float) o; writer.write("xs:float("); if (flt.equals(Float.POSITIVE_INFINITY)) { writer.write("'INF'"); } else if (flt.equals(Float.NEGATIVE_INFINITY)) { writer.write("'-INF'"); } else if (flt.equals(Float.NaN)) { writer.write("fn:number(())"); // poor man's way to write NaN } else { writer.write(o.toString()); } writer.write(")"); } else if (o instanceof Double) { Double dbl = (Double) o; writer.write("xs:double("); if (dbl.equals(Double.POSITIVE_INFINITY)) { writer.write("'INF'"); } else if (dbl.equals(Double.NEGATIVE_INFINITY)) { writer.write("'-INF'"); } else if (dbl.equals(Double.NaN)) { writer.write("fn:number(())"); // poor man's way to write NaN } else { writer.write(o.toString()); } writer.write(")"); } else if (o instanceof Boolean) { writer.write("xs:boolean('"); writer.write(o.toString()); writer.write("')"); } else if (o instanceof BigDecimal) { writer.write("xs:decimal("); writer.write(o.toString()); writer.write(")"); } else if (o instanceof Date) { // We want something like: 2006-04-30T01:28:30.499-07:00 // We format to get: 2006-04-30T01:28:30.499-0700 // Then we add in the colon writer.write("xs:dateTime('"); String d = dateFormat.format((Date) o); writer.write(d.substring(0, d.length() - 2)); writer.write(":"); writer.write(d.substring(d.length() - 2)); writer.write("')"); } else if (o instanceof XMLGregorianCalendar) { XMLGregorianCalendar greg = (XMLGregorianCalendar) o; QName type = greg.getXMLSchemaType(); if (type.equals(DatatypeConstants.DATETIME)) { writer.write("xs:dateTime('"); } else if (type.equals(DatatypeConstants.DATE)) { writer.write("xs:date('"); } else if (type.equals(DatatypeConstants.TIME)) { writer.write("xs:time('"); } else if (type.equals(DatatypeConstants.GYEARMONTH)) { writer.write("xs:gYearMonth('"); } else if (type.equals(DatatypeConstants.GMONTHDAY)) { writer.write("xs:gMonthDay('"); } else if (type.equals(DatatypeConstants.GYEAR)) { writer.write("xs:gYear('"); } else if (type.equals(DatatypeConstants.GMONTH)) { writer.write("xs:gMonth('"); } else if (type.equals(DatatypeConstants.GDAY)) { writer.write("xs:gDay('"); } writer.write(greg.toXMLFormat()); writer.write("')"); } else if (o instanceof Duration) { Duration dur = (Duration) o; /* // The following fails on Xerces QName type = dur.getXMLSchemaType(); if (type.equals(DatatypeConstants.DURATION)) { writer.write("xs:duration('"); } else if (type.equals(DatatypeConstants.DURATION_DAYTIME)) { writer.write("xdt:dayTimeDuration('"); } else if (type.equals(DatatypeConstants.DURATION_YEARMONTH)) { writer.write("xdt:yearMonthDuration('"); } */ // If no years or months, must be DURATION_DAYTIME if (dur.getYears() == 0 && dur.getMonths() == 0) { writer.write("xdt:dayTimeDuration('"); } // If has years or months but nothing else, must be DURATION_YEARMONTH else if (dur.getDays() == 0 && dur.getHours() == 0 && dur.getMinutes() == 0 && dur.getSeconds() == 0) { writer.write("xdt:yearMonthDuration('"); } else { writer.write("xs:duration('"); } writer.write(dur.toString()); writer.write("')"); } else if (o instanceof org.jdom.Element) { org.jdom.Element elt = (org.jdom.Element) o; writer.write("xdmp:unquote('"); // Because "<" in XQuery is the same as "<" I need to double escape any ampersands writer.write( new org.jdom.output.XMLOutputter() .outputString(elt) .replaceAll("&", "&") .replaceAll("'", "''")); writer.write("')/*"); // make sure to return the root elt } else if (o instanceof org.jdom.Document) { org.jdom.Document doc = (org.jdom.Document) o; writer.write("xdmp:unquote('"); writer.write( new org.jdom.output.XMLOutputter() .outputString(doc) .replaceAll("&", "&") .replaceAll("'", "''")); writer.write("')"); } else if (o instanceof org.jdom.Text) { org.jdom.Text text = (org.jdom.Text) o; writer.write("text {'"); writer.write(escapeSingleQuotes(text.getText())); writer.write("'}"); } else if (o instanceof org.jdom.Attribute) { // <fake xmlns:pref="http://uri.com" pref:attrname="attrvalue"/>/@*:attrname // <fake xmlns="http://uri.com" attrname="attrvalue"/>/@*:attrname org.jdom.Attribute attr = (org.jdom.Attribute) o; writer.write("<fake xmlns"); if ("".equals(attr.getNamespacePrefix())) { writer.write("=\""); } else { writer.write(":" + attr.getNamespacePrefix() + "=\""); } writer.write(attr.getNamespaceURI()); writer.write("\" "); writer.write(attr.getQualifiedName()); writer.write("=\""); writer.write(escapeSingleQuotes(attr.getValue())); writer.write("\"/>/@*:"); writer.write(attr.getName()); } else if (o instanceof org.jdom.Comment) { org.jdom.Comment com = (org.jdom.Comment) o; writer.write("comment {'"); writer.write(escapeSingleQuotes(com.getText())); writer.write("'}"); } else if (o instanceof org.jdom.ProcessingInstruction) { org.jdom.ProcessingInstruction pi = (org.jdom.ProcessingInstruction) o; writer.write("processing-instruction "); writer.write(pi.getTarget()); writer.write(" {'"); writer.write(escapeSingleQuotes(pi.getData())); writer.write("'}"); } else if (o instanceof QName) { QName q = (QName) o; writer.write("fn:expanded-QName('"); writer.write(escapeSingleQuotes(q.getNamespaceURI())); writer.write("','"); writer.write(q.getLocalPart()); writer.write("')"); } else { writer.write( "error('XQuery tried to retrieve unsupported type: " + o.getClass().getName() + "')"); } writer.flush(); } }
private static Interpreter getInterpreter(String contextId) throws EvalError { // Get the appropriate interpreter Interpreter i = null; boolean createdInterp = false; synchronized (interpreters) { // serialize two gets of the same name i = interpreters.get(contextId); if (i == null) { i = new Interpreter(); interpreters.put(contextId, i); createdInterp = true; } } if (createdInterp) { Log.log("Created context: " + contextId + " (" + i + ")"); // Now configure stdin and stdout to capture 10k of content // Store references to the circular buffers within the interpreter itself. // This provides a nice place to store them plus theoretically allows // advanced use from within the bsh environment. // On Windows print() outputs \r\n but in XQuery that's normalized to \n // so the 10k of Java buffer may produce less than 10k of content in XQuery! OutputStream circularOutput = new CircularByteArrayOutputStream(10240); PrintStream printOutput = new PrintStream(circularOutput); i.setOut(printOutput); i.set("mljamout", circularOutput); OutputStream circularError = new CircularByteArrayOutputStream(10240); PrintStream printError = new PrintStream(circularError); i.setErr(printError); i.set("mljamerr", circularError); // Capture the built-in System.out and System.err also. // (Commented out since System appears global, can't do per interpreter.) // i.set("mljamprintout", printOutput); // i.set("mljamprinterr", printError); // i.eval("System.setOut(mljamprintout);"); // i.eval("System.setErr(mljamprinterr);"); // Need to expose hexdecode() and base64decode() built-in functions i.eval("hexdecode(String s) { return com.xqdev.jam.MLJAM.hexDecode(s); }"); i.eval("base64decode(String s) { return com.xqdev.jam.MLJAM.base64Decode(s); }"); // Let's tell the context what its id is i.set("mljamid", contextId); } // Update the last accessed time, used for cleaning i.set("mljamlast", System.currentTimeMillis()); // If it's been long enough, go snooping for stale contexts if (System.currentTimeMillis() > lastClean + CLEAN_INTERVAL) { Log.log("Initiated periodic scan for stale context objects"); lastClean = System.currentTimeMillis(); Iterator<Interpreter> itr = interpreters.values().iterator(); while (itr.hasNext()) { Interpreter interp = itr.next(); Long last = (Long) interp.get("mljamlast"); if (System.currentTimeMillis() > last + STALE_TIMEOUT) { itr.remove(); Log.log("Staled context: " + interp.get("mljamid") + " (" + interp + ")"); } else if ((System.currentTimeMillis() > last + TEMP_STALE_TIMEOUT) && ("" + interp.get("mljamid")).startsWith("temp:")) { itr.remove(); Log.log("Staled temp context: " + interp.get("mljamid") + " (" + interp + ")"); } } } return i; }
/** Business logic to execute. */ public final Response executeCommand( Object inputPar, UserSessionParameters userSessionPars, HttpServletRequest request, HttpServletResponse response, HttpSession userSession, ServletContext context) { Connection conn = null; PreparedStatement pstmt = null; try { conn = ConnectionManager.getConnection(context); // fires the GenericEvent.CONNECTION_CREATED event... EventsManager.getInstance() .processEvent( new GenericEvent( this, getRequestName(), GenericEvent.CONNECTION_CREATED, (JAIOUserSessionParameters) userSessionPars, request, response, userSession, context, conn, inputPar, null)); Response responseVO = bean.insertItem( conn, (JournalHeaderVO) inputPar, userSessionPars, request, response, userSession, context); if (responseVO.isError()) { conn.rollback(); return responseVO; } if (inputPar instanceof JournalHeaderWithVatVO) { JournalHeaderWithVatVO vo = (JournalHeaderWithVatVO) inputPar; // insert vat rows in the specified vat register... Response regRes = vatRegisterAction.insertVatRows( conn, vo.getVats(), userSessionPars, request, response, userSession, context); if (regRes.isError()) { conn.rollback(); return regRes; } // retrieve payment instalments... Response payRes = payAction.executeCommand( new LookupValidationParams(vo.getPaymentCodeREG10(), new HashMap()), userSessionPars, request, response, userSession, context); if (payRes.isError()) { conn.rollback(); return payRes; } PaymentVO payVO = (PaymentVO) ((VOListResponse) payRes).getRows().get(0); GridParams gridParams = new GridParams(); gridParams .getOtherGridParams() .put(ApplicationConsts.PAYMENT_CODE_REG10, vo.getPaymentCodeREG10()); payRes = paysAction.executeCommand( gridParams, userSessionPars, request, response, userSession, context); if (payRes.isError()) { conn.rollback(); return payRes; } java.util.List rows = ((VOListResponse) payRes).getRows(); // create expirations in DOC19 ONLY if: // - there are more than one instalment OR // - there is only one instalment and this instalment has more than 0 instalment days if (rows.size() > 1 || (rows.size() == 1 && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() > 0)) { // retrieve internationalization settings (Resources object)... ServerResourcesFactory factory = (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY); Resources resources = factory.getResources(userSessionPars.getLanguageId()); PaymentInstalmentVO inVO = null; pstmt = conn.prepareStatement( "insert into DOC19_EXPIRATIONS(COMPANY_CODE_SYS01,DOC_TYPE,DOC_YEAR,DOC_NUMBER,DOC_SEQUENCE,PROGRESSIVE,DOC_DATE,EXPIRATION_DATE,NAME_1,NAME_2,VALUE,PAYED,DESCRIPTION,CUSTOMER_SUPPLIER_CODE,PROGRESSIVE_REG04,CURRENCY_CODE_REG03) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); long startTime = vo.getItemDateACC05().getTime(); // item date... if (payVO.getStartDayREG10().equals(ApplicationConsts.START_DAY_END_MONTH)) { Calendar cal = Calendar.getInstance(); if (cal.get(cal.MONTH) == 10 || cal.get(cal.MONTH) == 3 || cal.get(cal.MONTH) == 5 || cal.get(cal.MONTH) == 8) cal.set(cal.DAY_OF_MONTH, 30); else if (cal.get(cal.MONTH) == 1) { if (cal.get(cal.YEAR) % 4 == 0) cal.set(cal.DAY_OF_MONTH, 29); else cal.set(cal.DAY_OF_MONTH, 28); } else cal.set(cal.DAY_OF_MONTH, 31); startTime = cal.getTime().getTime(); } BigDecimal amount = null; for (int i = 0; i < rows.size(); i++) { inVO = (PaymentInstalmentVO) rows.get(i); pstmt.setString(1, vo.getCompanyCodeSys01ACC05()); pstmt.setString(2, vo.getDocTypeDOC19()); pstmt.setBigDecimal(3, vo.getItemYearACC05()); pstmt.setBigDecimal(4, null); pstmt.setBigDecimal(5, vo.getDocSequenceDOC19()); pstmt.setBigDecimal( 6, ProgressiveUtils.getConsecutiveProgressive( "DOC19_EXPIRATIONS", "PROGRESSIVE", conn)); pstmt.setDate(7, vo.getItemDateACC05()); pstmt.setDate( 8, new java.sql.Date( startTime + inVO.getInstalmentDaysREG17().longValue() * 86400 * 1000)); // expiration date pstmt.setString(9, vo.getName_1REG04()); pstmt.setString(10, vo.getName_2REG04()); amount = vo.getTotalValue() .multiply(inVO.getPercentageREG17()) .divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP) .setScale(vo.getTotalValue().scale(), BigDecimal.ROUND_HALF_UP); // value pstmt.setBigDecimal(11, amount); pstmt.setString(12, "N"); if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) pstmt.setString( 13, resources.getResource("sale generic document") + " " + vo.getDocSequenceDOC19() + "/" + vo.getItemYearACC05() + " - " + resources.getResource("valueREG01") + " " + resources.getResource("rateNumberREG17") + " " + (i + 1) + " - " + inVO.getPaymentTypeDescriptionSYS10()); // description else pstmt.setString( 13, resources.getResource("purchase generic document") + " " + vo.getDocSequenceDOC19() + "/" + vo.getItemYearACC05() + " - " + resources.getResource("valueREG01") + " " + resources.getResource("rateNumberREG17") + " " + (i + 1) + " - " + inVO.getPaymentTypeDescriptionSYS10()); // description pstmt.setString(14, vo.getCustomerCodeSAL07()); pstmt.setBigDecimal(15, vo.getProgressiveREG04()); pstmt.setString(16, vo.getCurrencyCodeREG01()); pstmt.execute(); } pstmt.close(); } // create an item registration for proceeds, according to expiration settings (e.g. retail // selling): // there must be only one instalment and this instalment has 0 instalment days if (rows.size() == 1 && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() == 0) { // retrieve internationalization settings (Resources object)... ServerResourcesFactory factory = (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY); Resources resources = factory.getResources(userSessionPars.getLanguageId()); HashMap map = new HashMap(); map.put(ApplicationConsts.COMPANY_CODE_SYS01, vo.getCompanyCodeSys01ACC05()); map.put(ApplicationConsts.PARAM_CODE, ApplicationConsts.CASE_ACCOUNT); Response res = userParamAction.executeCommand( map, userSessionPars, request, response, userSession, context); if (res.isError()) { conn.rollback(); return res; } String caseAccountCode = ((VOResponse) res).getVo().toString(); JournalHeaderVO jhVO = new JournalHeaderVO(); jhVO.setCompanyCodeSys01ACC05(vo.getCompanyCodeSys01ACC05()); if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) { jhVO.setDescriptionACC05( resources.getResource("sale generic document") + " " + vo.getDocSequenceDOC19() + "/" + vo.getItemYearACC05() + " - " + resources.getResource("customer") + " " + vo.getName_1REG04() + " " + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04())); jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_INVOICE_PROCEEDS); } else { jhVO.setDescriptionACC05( resources.getResource("purchase generic document") + " " + vo.getDocSequenceDOC19() + "/" + vo.getItemYearACC05() + " - " + resources.getResource("supplier") + " " + vo.getName_1REG04() + " " + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04())); jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_PURCHASE_INVOICE_PAYED); } jhVO.setItemDateACC05(new java.sql.Date(System.currentTimeMillis())); jhVO.setItemYearACC05(new BigDecimal(Calendar.getInstance().get(Calendar.YEAR))); JournalRowVO jrVO = new JournalRowVO(); jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05()); if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) { jrVO.setAccountCodeAcc02ACC06(vo.getCreditAccountCodeAcc02SAL07()); jrVO.setAccountCodeACC06(vo.getCustomerCodeSAL07()); jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_CUSTOMER); jrVO.setCreditAmountACC06(vo.getTotalValue()); } else { jrVO.setAccountCodeAcc02ACC06(vo.getDebitAccountCodeAcc02PUR01()); jrVO.setAccountCodeACC06(vo.getSupplierCodePUR01()); jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_SUPPLIER); jrVO.setDebitAmountACC06(vo.getTotalValue()); } jrVO.setDescriptionACC06(""); jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05()); jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05()); jhVO.addJournalRow(jrVO); jrVO = new JournalRowVO(); jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05()); jrVO.setAccountCodeAcc02ACC06(caseAccountCode); jrVO.setAccountCodeACC06(caseAccountCode); jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_ACCOUNT); if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) { jrVO.setDebitAmountACC06(vo.getTotalValue()); } else { jrVO.setCreditAmountACC06(vo.getTotalValue()); } jrVO.setDescriptionACC06(""); jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05()); jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05()); jhVO.addJournalRow(jrVO); Response proceedsRes = bean.insertItem(conn, jhVO, userSessionPars, request, response, userSession, context); if (proceedsRes.isError()) { conn.rollback(); return proceedsRes; } } } Response answer = responseVO; // fires the GenericEvent.BEFORE_COMMIT event... EventsManager.getInstance() .processEvent( new GenericEvent( this, getRequestName(), GenericEvent.BEFORE_COMMIT, (JAIOUserSessionParameters) userSessionPars, request, response, userSession, context, conn, inputPar, answer)); conn.commit(); // fires the GenericEvent.AFTER_COMMIT event... EventsManager.getInstance() .processEvent( new GenericEvent( this, getRequestName(), GenericEvent.AFTER_COMMIT, (JAIOUserSessionParameters) userSessionPars, request, response, userSession, context, conn, inputPar, answer)); return answer; } catch (Throwable ex) { Logger.error( userSessionPars.getUsername(), this.getClass().getName(), "executeCommand", "Error while inserting a new item in the journal", ex); try { conn.rollback(); } catch (Exception ex3) { } return new ErrorResponse(ex.getMessage()); } finally { try { pstmt.close(); } catch (Exception ex2) { } try { ConnectionManager.releaseConnection(conn, context); } catch (Exception ex1) { } } }
/** * this is the main method of the servlet that will service all get requests. * * @param request HttpServletRequest * @param responce HttpServletResponce */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/html"); ServletOutputStream out = res.getOutputStream(); hitCount++; long totalMemory = Runtime.getRuntime().totalMemory(); long maxMemoryBeforeGC = Runtime.getRuntime().maxMemory(); long freeMemoryBeforeGC = Runtime.getRuntime().freeMemory(); long startTime = System.currentTimeMillis(); System.gc(); // Invoke the GC. long endTime = System.currentTimeMillis(); long maxMemoryAfterGC = Runtime.getRuntime().maxMemory(); long freeMemoryAfterGC = Runtime.getRuntime().freeMemory(); out.println( "<html><head><title>ExplicitGC</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Explicit Garbage Collection<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR><BR></FONT> <B>Hit Count: " + hitCount + "<br>" + "<table border=\"0\"><tr>" + "<td align=\"right\">Total Memory</td><td align=\"right\">" + totalMemory + "</td>" + "</tr></table>" + "<table width=\"350\"><tr><td colspan=\"2\" align=\"left\">" + "Statistics before GC</td></tr>" + "<tr><td align=\"right\">" + "Max Memory</td><td align=\"right\">" + maxMemoryBeforeGC + "</td></tr>" + "<tr><td align=\"right\">" + "Free Memory</td><td align=\"right\">" + freeMemoryBeforeGC + "</td></tr>" + "<tr><td align=\"right\">" + "Used Memory</td><td align=\"right\">" + (totalMemory - freeMemoryBeforeGC) + "</td></tr>" + "<tr><td colspan=\"2\" align=\"left\">Statistics after GC</td></tr>" + "<tr><td align=\"right\">" + "Max Memory</td><td align=\"right\">" + maxMemoryAfterGC + "</td></tr>" + "<tr><td align=\"right\">" + "Free Memory</td><td align=\"right\">" + freeMemoryAfterGC + "</td></tr>" + "<tr><td align=\"right\">" + "Used Memory</td><td align=\"right\">" + (totalMemory - freeMemoryAfterGC) + "</td></tr>" + "<tr><td align=\"right\">" + "Total Time in GC</td><td align=\"right\">" + Float.toString((endTime - startTime) / 1000) + "s</td></tr>" + "</table>" + "</body></html>"); } catch (Exception e) { Log.error(e, "ExplicitGC.doGet(...): general exception caught"); res.sendError(500, e.toString()); } }
public int doEndTag() throws JspException { try { HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest()); String file_ext = pageContext.getServletContext().getInitParameter("FileExtention"); String dbfs_ext = pageContext.getServletContext().getInitParameter("DatabaseExtention"); String db_name = pageContext.getServletContext().getInitParameter("DatabaseName"); String db_query = pageContext.getServletContext().getInitParameter("DatabaseQuery"); JspWriter out = pageContext.getOut(); int KEEP_CACHE_TIME = 300; long current_time = System.currentTimeMillis(); if (pagebody != null || pageurl != null || dbfsurl != null) { VariableTable vt = new VariableTable(); vt.loadContent(FileCache.getFileContent(getPhysicalPath("/global" + file_ext))); vt.loadContent(FileCache.getFileContent(getPhysicalPath("default" + file_ext))); if (pageurl != null) vt.loadContent(FileCache.getFileContent(getPhysicalPath(pageurl))); if (dbfsurl != null) { VariableTable dbparam = new VariableTable(); dbparam.add("path", java.sql.Types.VARCHAR); dbparam.setValue("path", dbfsurl); String pagebody = TextCache.getTextContent("source::" + dbfsurl); if (pagebody == null) { try { DBPooledConnection dbconn = DBLogicalManager.getPoolConnection(db_name); try { pagebody = DBOperation.getString(dbconn, db_query, dbparam); vt.loadContent(pagebody); TextCache.putContent( System.currentTimeMillis(), "source::" + dbfsurl, pagebody, 20); } catch (java.sql.SQLException sqle) { } dbconn.close(); } catch (java.lang.Exception sqle) { } } else { vt.loadContent(pagebody); } } if (pagebody != null) vt.loadContent(pagebody); getEnv(vt); vt.add("JSP.TAG", java.sql.Types.VARCHAR); vt.setValue("JSP.TAG", "YES"); vt.add("REQUEST.URL", java.sql.Types.VARCHAR); vt.setValue("REQUEST.URL", request.getRequestURI()); if (vt.exists("WEBCHART.KEEP_CACHE_TIME")) { KEEP_CACHE_TIME = vt.getInt("WEBCHART.KEEP_CACHE_TIME", 300); if (KEEP_CACHE_TIME < 5) KEEP_CACHE_TIME = 5; } java.io.File xsl_file = null; if (vt.getString("WEBCHART.XSLDOC") != null) xsl_file = new java.io.File(getPhysicalPath(vt.getString("WEBCHART.XSLDOC"))); String cachekey = vt.parseString(vt.getString("WEBCHART.CACHE")); String cache_content = null; if (cachekey != null && !vt.exists("WEBCHART.FORCECACHE")) cache_content = TextCache.getTextContent(cachekey); if (cache_content == null) { java.io.StringWriter xmlbuf = new java.io.StringWriter(); writeXMLHeader(xmlbuf, vt); xmlbuf.write("<root>\n"); WebChart2.generateChart(xmlbuf, null, vt, file_ext); xmlbuf.write("</root>\n"); java.io.StringWriter htmlbuf = new java.io.StringWriter(); if (xsl_file != null && xsl_file.exists()) BaseServlet.XML2HTML( htmlbuf, new java.io.StringReader(xmlbuf.toString()), new java.io.StringReader(FileCache.getFileContent(xsl_file)), FileCache.getFileContent(xsl_file)); else BaseServlet.XML2HTML( htmlbuf, new java.io.StringReader(xmlbuf.toString()), new java.io.StringReader(StaticResource.getTextResource("defaultxsl")), StaticResource.getTextResource("defaultxsl")); cache_content = htmlbuf.toString(); out.write(cache_content); if (cachekey != null) TextCache.putContent(current_time, cachekey, cache_content, KEEP_CACHE_TIME); } else { out.write(cache_content); } } } catch (IOException ioe) { throw new JspException("Error: " + ioe.getMessage()); } return EVAL_PAGE; }
// get pathInfo and parmameters from servlet call public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter pw = null; try { long startms = System.currentTimeMillis(); if (cat == null || rm.nexradList == null) { // something major wrong res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "radarServer Radar Station/Catalog initialization problem"); return; } // setup String pathInfo = req.getPathInfo(); if (pathInfo == null) pathInfo = ""; RadarType radarType = RadarType.nexrad; // default if (pathInfo.indexOf('/', 1) > 1) { String rt = pathInfo.substring(1, pathInfo.indexOf('/', 1)); radarType = RadarType.valueOf(rt); } // default is xml, assume errors will be recorded by logger from this point if (!pathInfo.endsWith("html")) { pw = res.getWriter(); res.setContentType("text/xml; charset=iso-8859-1"); // default } // radar query if (req.getQueryString() != null) { // log.debug("RadarServer query ="+ req.getQueryString() ); if (log.isDebugEnabled()) log.debug("<documentation>\n" + req.getQueryString() + "</documentation>\n"); rm.radarQuery(radarType, req, res, pw); if (log.isDebugEnabled()) log.debug("after doGet " + (System.currentTimeMillis() - startms)); pw.flush(); return; } // return radarCollections catalog xml or html if (pathInfo.startsWith("/catalog.xml") || pathInfo.startsWith("/dataset.xml")) { InvCatalogFactory factory = InvCatalogFactory.getDefaultFactory(false); // no validation String catAsString = factory.writeXML(cat); pw.println(catAsString); res.setStatus(HttpServletResponse.SC_OK); pw.flush(); return; } else if (pathInfo.startsWith("/catalog.html") || pathInfo.startsWith("/dataset.html")) { try { int i = HtmlWriter.getInstance().writeCatalog(req, res, cat, true); // show catalog as HTML } catch (Exception e) { log.error("Radar HtmlWriter failed ", e); res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "radarServer HtmlWriter error " + pathInfo); return; } return; } // level2 and level3 catalog/dataset if (pathInfo.contains("level2/catalog.") || pathInfo.contains("level3/catalog.") || pathInfo.contains("level2/dataset.") || pathInfo.contains("level3/dataset.")) { level2level3catalog(radarType, pathInfo, pw, req, res); return; } // return stations of dataset if (pathInfo.endsWith("stations.xml")) { pathInfo = pathInfo.replace("/stations.xml", ""); Element rootElem = new Element("stationsList"); Document doc = new Document(rootElem); doc = rm.stationsXML(radarType, doc, rootElem, pathInfo.substring(1)); XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat()); pw.println(fmt.outputString(doc)); pw.flush(); return; } // return specific dataset information, ie IDD if (pathInfo.endsWith("dataset.xml") || pathInfo.endsWith("catalog.xml")) { datasetInfoXml(radarType, pathInfo, pw); return; } // needs work nobody using it now // return Dataset information in html form format if (pathInfo.endsWith("dataset.html") || pathInfo.endsWith("catalog.html")) { datasetInfoHtml(radarType, pathInfo, pw, res); return; } // mal formed request with no exceptions res.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (FileNotFoundException e) { if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (Throwable e) { log.error("RadarServer.doGet failed", e); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } // end doGet
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { UserService userService = UserServiceFactory.getUserService(); String retUrl = req.getParameter("url"); if (retUrl == null) retUrl = "/"; String pathInfo = req.getPathInfo(); if (pathInfo.equals("/current")) { User user = userService.getCurrentUser(); if (user == null) { res.setStatus(401); res.setContentType("text/plain; charset=utf-8"); res.getWriter().write("Not login"); return; } UserBean ub = getByEmail(user.getEmail()); res.setContentType("application/json; charset=utf-8"); res.setHeader("Cache-control", "no-cache"); res.getWriter().write("{\"email\":\"" + user.getEmail() + "\""); if (ub != null) { res.getWriter().write(",\"nickName\":\"" + ub.getNickName() + "\""); res.getWriter().write(",\"isRegister\":true"); } else { String nn = user.getNickname(); if (nn == null) nn = user.getEmail(); res.getWriter().write(",\"nickName\":\"" + nn + "\""); res.getWriter().write(",\"isRegister\":false"); } res.getWriter().write("}"); } else if (pathInfo.equals("/login")) { String url = userService.createLoginURL(retUrl); res.sendRedirect(url); } else if (pathInfo.equals("/logout")) { String url = userService.createLogoutURL(retUrl); res.sendRedirect(url); } else if (pathInfo.equals("/register")) { User user = userService.getCurrentUser(); if (user == null) { res.setStatus(401); res.setContentType("text/plain; charset=utf-8"); res.getWriter().write("Not login"); return; } String nickName = req.getParameter("nickName"); UserBean ub = getByNeckName(nickName); if (ub != null) { res.setStatus(403); res.setContentType("text/plain; charset=utf-8"); res.getWriter().write("ニックネーム(" + nickName + ")は既に使われています。"); return; } ub = new UserBean(); ub.setEmail(user.getEmail()); ub.setNickName(nickName); usbs.put(user.getEmail(), ub); ursbs.put(nickName, ub); FileBean fb = new FileBean(); fb.setParentName(""); fb.setLastName(nickName); fb.setDirectory(true); fb.setLastModified(System.currentTimeMillis()); fb.setOwner(user.getEmail()); fb.setNickName(nickName); sbs.put("/" + nickName, fb); res.sendRedirect(retUrl); } }
private void handleLoginPost( Request request, HttpServletResponse httpServletResponse, boolean secured) throws Exception { String userId = request.getParameter(PARAM_USER_ID); String password = request.getParameter(PARAM_PASSWORD); String rememberAccountStr = request.getParameter(PARAM_REMEMBER_ACCOUNT); boolean rememberAccount = Boolean.parseBoolean(rememberAccountStr); LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request); logOut(sessionInfo.browserId); User user = userDb.get(userId); if (user == null) { WebUtils.redirectToError("User " + userId + " not found", request, httpServletResponse); return; } if (!user.checkPassword(password)) { WebUtils.redirectToError("Invalid password", request, httpServletResponse); return; } if (!user.active) { WebUtils.redirectToError( "Account for User " + userId + " needs to be activated", request, httpServletResponse); return; } LOG.info("Logged in user " + userId); sessionInfo.sessionId = null; if (sessionInfo.browserId == null) { sessionInfo.browserId = getRandomId(); } else { for (LoginInfo loginInfo : loginInfoDb.getLoginsForBrowser(sessionInfo.browserId)) { if (userId.equals(loginInfo.userId)) { sessionInfo.sessionId = loginInfo.sessionId; break; } } } long expireOn = System.currentTimeMillis() + Config.getConfig().loginExpireInterval; if (sessionInfo.sessionId == null) { sessionInfo.sessionId = getRandomId(); Config config = Config.getConfig(); loginInfoDb.add( new LoginInfo( sessionInfo.browserId, sessionInfo.sessionId, userId, expireOn, rememberAccount, config.defaultStyle, config.defaultItemsPerPage, config.defaultFeedDateFormat)); LOG.info(String.format("Logging in in a new session. User: %s", user)); } else { loginInfoDb.updateExpireTime(sessionInfo.browserId, sessionInfo.sessionId, expireOn); LOG.info(String.format("Logging in in an existing session. User: %s", user)); } WebUtils.saveCookies( httpServletResponse, secured, sessionInfo.browserId, sessionInfo.sessionId); httpServletResponse.sendRedirect("/"); }
/** * Normally sets the path and a few attributes that the JSPs are likely to need. Also verifies the * login information. If necessary, just redirects to the login page. * * @param target * @param request * @param httpServletResponse * @param secured * @return true if the request is already handled so the .jsp shouldn't get called * @throws Exception */ private boolean prepareForJspGet( String target, Request request, HttpServletResponse httpServletResponse, boolean secured) throws Exception { LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request); LOG.info( String.format( "hndl - %s ; %s; %s ; %s", target, request.getPathInfo(), request.getMethod(), secured ? "secured" : "not secured")); String path = request.getUri().getDecodedPath(); boolean redirectToLogin = path.equals(PATH_LOGOUT); LoginInfo loginInfo = null; if (sessionInfo.isNull()) { redirectToLogin = true; LOG.info("Null session info. Logging in again."); } else { loginInfo = loginInfoDb.get( sessionInfo.browserId, sessionInfo.sessionId); // ttt2 use a cache, to avoid going to DB if (loginInfo == null || loginInfo.expiresOn < System.currentTimeMillis()) { LOG.info("Session has expired. Logging in again. Info: " + loginInfo); redirectToLogin = true; } } if (!path.equals(PATH_LOGIN) && !path.equals(PATH_SIGNUP) && !path.equals(PATH_ERROR)) { if (redirectToLogin) { // ttt2 perhaps store URI, to return to it after login logOut(sessionInfo.browserId); addLoginParams(request, loginInfo); httpServletResponse.sendRedirect(PATH_LOGIN); return true; } User user = userDb.get(loginInfo.userId); if (user == null) { WebUtils.redirectToError("Unknown user", request, httpServletResponse); return true; } if (!user.active) { WebUtils.redirectToError("Account is not active", request, httpServletResponse); return true; } request.setAttribute(VAR_FEED_DB, feedDb); request.setAttribute(VAR_USER_DB, userDb); request.setAttribute(VAR_ARTICLE_DB, articleDb); request.setAttribute(VAR_READ_ARTICLES_COLL_DB, readArticlesCollDb); request.setAttribute(VAR_USER, user); request.setAttribute(VAR_LOGIN_INFO, loginInfo); MultiMap<String> params = new MultiMap<>(); params.put(PARAM_PATH, path); request.setParameters(params); } if (path.equals(PATH_LOGIN)) { addLoginParams(request, loginInfo); } return false; }
private void endHereCommon() throws BeanException { // save EJB object handle in property if (ejb != null) { try { hPubAccessHandle = ejb.getHandle(); } catch (Exception e) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5955 " + this.getClass().getName() + ": ejb.getHandle(), ejb=" + ejb + ": " + e.getClass().getName() + ": " + e.getMessage(); System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } } // save ejb accessHandle and hpubLinkKey in HttpSession if ((oHttpServletRequest != null) && (outputProps != null)) { // a new HPubEjb2HttpSessionBindingListener object containing the ejb access // handle and hPubLinkKey for the connection is bound to the session using // a prefix and the ending connection state of the IO just processed. // This hPubLinkKey uniquely identifies the connection associated with the // IO chain for that HP Runtime JVM. // The ejb access handle is contained within the HPubEjb2HttpSessionBindingListener // object so that an ejb remove can be issued in the case where a session // timeout or session invalidation occurs for an incomplete IO chain. HttpSession theWebsession = oHttpServletRequest.getSession(true); if (theWebsession != null) { synchronized (theWebsession) { try { String theKey = KEY_WEBCONN + outputProps.getHPubEndChainName(); hPubLinkKey = outputProps.getHPubLinkKey(); theWebsession.setAttribute( theKey, new HPubEJB2HttpSessionBindingListener(hPubAccessHandle, hPubLinkKey)); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = "theWebsession.setAttribute(" + theKey + ",new HPubEJB2HttpSessionBindingListener(" + hPubAccessHandle + ", " + hPubLinkKey + "))"; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } if (auditing == true) { auditArgs[0] = "\n---\nIN:" + this.getClass().getName() + " " + theKey + " " + hPubAccessHandle + " " + hPubLinkKey + " " + theWebsession.getId(); auditArgs[1] = theWebsession; try { auditMethod.invoke(o, auditArgs); } catch (Exception x) { } } } catch (Exception e) { hPubLinkKey = null; // set to null to force following error logic } } } // if an error occurred throw an exception to cause ejb remove to be issued. if ((theWebsession == null) || (hPubLinkKey == null)) { String errMsg = (new Date(System.currentTimeMillis())).toString() + " HPS5956 " + this.getClass().getName() + ": HttpServletRequest.getSession(true), hPubLinkKey=" + hPubLinkKey; System.err.println(errMsg); if (tracing == true) { traceArgs[0] = this; traceArgs[1] = errMsg; try { traceMethod.invoke(o, traceArgs); } catch (Exception x) { } } throw new BeanException(errMsg); } } // send Event to User indicating that the Query request is complete RequestCompleteEvent hPubEvent = new RequestCompleteEvent(this); fireHPubReqCompleteEvent(hPubEvent); return; }
/** * Main service method for TradeScenarioServlet * * @param request Object that encapsulates the request to the servlet * @param response Object that encapsulates the response from the servlet */ public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Scenario generator for Trade2 char action = ' '; String userID = null; // String to create full dispatch path to TradeAppServlet w/ request Parameters String dispPath = null; // Dispatch Path to TradeAppServlet String scenarioAction = (String) req.getParameter("action"); if ((scenarioAction != null) && (scenarioAction.length() >= 1)) { action = scenarioAction.charAt(0); if (action == 'n') { // null; try { resp.setContentType("text/html"); PrintWriter out = new PrintWriter(resp.getOutputStream()); out.println("<HTML><HEAD>TradeScenarioServlet</HEAD><BODY>Hello</BODY></HTML>"); out.close(); return; } catch (Exception e) { Log.error( "trade_client.TradeScenarioServlet.service(...)" + "error creating printwriter from responce.getOutputStream", e); resp.sendError( 500, "trade_client.TradeScenarioServlet.service(...): erorr creating and writing to PrintStream created from response.getOutputStream()"); } // end of catch } // end of action=='n' } ServletContext ctx = null; HttpSession session = null; try { ctx = getServletConfig().getServletContext(); // These operations require the user to be logged in. Verify the user and if not logged in // change the operation to a login session = req.getSession(true); userID = (String) session.getAttribute("uidBean"); } catch (Exception e) { Log.error( "trade_client.TradeScenarioServlet.service(...): performing " + scenarioAction + "error getting ServletContext,HttpSession, or UserID from session" + "will make scenarioAction a login and try to recover from there", e); userID = null; action = 'l'; } if (userID == null) { action = 'l'; // change to login TradeConfig.incrementScenarioCount(); } else if (action == ' ') { // action is not specified perform a random operation according to current mix // Tell getScenarioAction if we are an original user or a registered user // -- sellDeficits should only be compensated for with original users. action = TradeConfig.getScenarioAction(userID.startsWith(TradeConfig.newUserPrefix)); } switch (action) { case 'q': // quote dispPath = tasPathPrefix + "quotes&symbols=" + TradeConfig.rndSymbols(); ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'a': // account dispPath = tasPathPrefix + "account"; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'u': // update account profile dispPath = tasPathPrefix + "account"; ctx.getRequestDispatcher(dispPath).include(req, resp); String fullName = "rnd" + System.currentTimeMillis(); String address = "rndAddress"; String password = "******"; String email = "rndEmail"; String creditcard = "rndCC"; dispPath = tasPathPrefix + "update_profile&fullname=" + fullName + "&password="******"&cpassword="******"&address=" + address + "&email=" + email + "&creditcard=" + creditcard; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'h': // home dispPath = tasPathPrefix + "home"; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'l': // login userID = TradeConfig.getUserID(); String password2 = "xxx"; dispPath = tasPathPrefix + "login&inScenario=true&uid=" + userID + "&passwd=" + password2; ctx.getRequestDispatcher(dispPath).include(req, resp); // login is successful if the userID is written to the HTTP session if (session.getAttribute("uidBean") == null) { System.out.println("TradeScenario login failed. Reset DB between runs"); } break; case 'o': // logout dispPath = tasPathPrefix + "logout"; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'p': // portfolio dispPath = tasPathPrefix + "portfolio"; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'r': // register // Logout the current user to become a new user // see note in TradeServletAction req.setAttribute("TSS-RecreateSessionInLogout", Boolean.TRUE); dispPath = tasPathPrefix + "logout"; ctx.getRequestDispatcher(dispPath).include(req, resp); userID = TradeConfig.rndNewUserID(); String passwd = "yyy"; fullName = TradeConfig.rndFullName(); creditcard = TradeConfig.rndCreditCard(); String money = TradeConfig.rndBalance(); email = TradeConfig.rndEmail(userID); String smail = TradeConfig.rndAddress(); dispPath = tasPathPrefix + "register&Full Name=" + fullName + "&snail mail=" + smail + "&email=" + email + "&user id=" + userID + "&passwd=" + passwd + "&confirm passwd=" + passwd + "&money=" + money + "&Credit Card Number=" + creditcard; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 's': // sell dispPath = tasPathPrefix + "portfolioNoEdge"; ctx.getRequestDispatcher(dispPath).include(req, resp); Collection holdings = (Collection) req.getAttribute("holdingDataBeans"); int numHoldings = holdings.size(); if (numHoldings > 0) { // sell first available security out of holding Iterator it = holdings.iterator(); boolean foundHoldingToSell = false; while (it.hasNext()) { HoldingDataBean holdingData = (HoldingDataBean) it.next(); if (!(holdingData.getPurchaseDate().equals(new java.util.Date(0)))) { Integer holdingID = holdingData.getHoldingID(); dispPath = tasPathPrefix + "sell&holdingID=" + holdingID; ctx.getRequestDispatcher(dispPath).include(req, resp); foundHoldingToSell = true; break; } } if (foundHoldingToSell) break; if (Log.doTrace()) Log.trace( "TradeScenario: No holding to sell -switch to buy -- userID = " + userID + " Collection count = " + numHoldings); } // At this point: A TradeScenario Sell was requested with No Stocks in Portfolio // This can happen when a new registered user happens to request a sell before a buy // In this case, fall through and perform a buy instead /* Trade 2.037: Added sell_deficit counter to maintain correct buy/sell mix. * When a users portfolio is reduced to 0 holdings, a buy is requested instead of a sell. * This throws off the buy/sell mix by 1. This results in unwanted holding table growth * To fix this we increment a sell deficit counter to maintain the correct ratio in getScenarioAction * The 'z' action from getScenario denotes that this is a sell action that was switched from a buy * to reduce a sellDeficit */ if (userID.startsWith(TradeConfig.newUserPrefix) == false) { TradeConfig.incrementSellDeficit(); } case 'b': // buy String symbol = TradeConfig.rndSymbol(); String amount = TradeConfig.rndQuantity() + ""; dispPath = tasPathPrefix + "quotes&symbols=" + symbol; ctx.getRequestDispatcher(dispPath).include(req, resp); dispPath = tasPathPrefix + "buy&quantity=" + amount + "&symbol=" + symbol; ctx.getRequestDispatcher(dispPath).include(req, resp); break; } // end of switch statement }