@Override public void init(FilterConfig fc) throws ServletException { log.info("DispatcherFilter starting ..."); log.info("java.version = {}", JdkUtils.JAVA_VERSION); log.info("webmvc.version = {}", WebConfig.VERSION); log.info("user.dir = {}", System.getProperty("user.dir")); log.info("java.io.tmpdir = {}", System.getProperty("java.io.tmpdir")); log.info("user.timezone = {}", System.getProperty("user.timezone")); log.info("file.encoding = {}", System.getProperty("file.encoding")); try { long ts = System.currentTimeMillis(); ServletContext sc = fc.getServletContext(); String configLocation = fc.getInitParameter("configLocation"); WebInitializer.initialize(sc, configLocation); httpEncoding = WebConfig.getHttpEncoding(); httpCache = WebConfig.isHttpCache(); router = WebConfig.getRouter(); bypassRequestUrls = WebConfig.getBypassRequestUrls(); corsRequestProcessor = WebConfig.getCORSRequestProcessor(); resultHandlerResolver = WebConfig.getResultHandlerResolver(); fileUploadResolver = WebConfig.getFileUploadResolver(); exceptionHandler = WebConfig.getExceptionHandler(); log.info("web.root = {}", WebConfig.getWebroot()); log.info("web.development = {}", WebConfig.isDevelopment()); log.info("web.upload.dir = {}", WebConfig.getUploaddir()); log.info("web.urls.router = {}", router.getClass().getName()); log.info( "web.urls.bypass = {}", (bypassRequestUrls == null) ? null : bypassRequestUrls.getClass().getName()); log.info( "web.urls.cors = {}", (corsRequestProcessor == null) ? null : corsRequestProcessor.getClass().getName()); for (Plugin plugin : WebConfig.getPlugins()) { log.info("load plugin: {}", plugin.getClass().getName()); plugin.initialize(); } for (Interceptor interceptor : WebConfig.getInterceptors()) { log.info("load interceptor: {}", interceptor.getClass().getName()); interceptor.initialize(); } log.info( "DispatcherFilter initialize successfully, Time elapsed: {} ms.", System.currentTimeMillis() - ts); } catch (Exception e) { log.error("Failed to initialize DispatcherFilter", e); log.error("*************************************"); log.error(" System.exit(1) "); log.error("*************************************"); System.exit(1); } }
boolean handleLoggedInUser( FilterChain chain, HttpServletRequest httpRequest, HttpServletResponse httpResponse, ServiceAccess serviceAccess, AuthorizationRequestData rdo) throws ServletException, IOException { VOUserDetails userDetails = rdo.getUserDetails(); if (userDetails != null) { httpRequest.getSession().setAttribute(PORTAL_HAS_BEEN_REQUESTED, !rdo.isMarketplace()); // if the user wants to use another organization he must login // again (the service sessions are destroyed as well) // don't let a user with status PASSWORD_MUST_BE_CHANGED see any // site but the one to change the pwd if (!authSettings.isServiceProvider()) { if (userDetails.getStatus() == UserAccountStatus.PASSWORD_MUST_BE_CHANGED && !rdo.isRequestedToChangePwd()) { forwardToPwdPage(userDetails.getUserId(), httpRequest, httpResponse); return true; } } // TODO stavreva: check this again if (authSettings.isServiceProvider() || !rdo.isRequestedToChangePwd()) { long t = System.currentTimeMillis(); if (ADMStringUtils.isBlank(httpRequest.getServletPath()) || httpRequest.getServletPath().startsWith(MenuBean.LINK_DEFAULT)) { String defaultUrl = getDefaultUrl(serviceAccess, rdo, httpRequest); forward(defaultUrl, httpRequest, httpResponse); } if (loginPage.equalsIgnoreCase(httpRequest.getServletPath())) { sendRedirect(httpRequest, httpResponse, MenuBean.LINK_DEFAULT); } if (isPageForbiddenToAccess(httpRequest, rdo, serviceAccess)) { forward(insufficientAuthoritiesUrl, httpRequest, httpResponse); } chain.doFilter(httpRequest, httpResponse); if (logger.isDebugLoggingEnabled()) { logger.logDebug( "URL='" + rdo.getRelativePath() + "' processed in " + (System.currentTimeMillis() - t) + "ms"); } return true; } } return false; }
/** * This filter is used in production, to put HTTP cache headers with a long (1 month) expiration * time. */ public class CachingHttpHeadersFilter implements Filter { // Cache period is 1 month (in ms) private static final long CACHE_PERIOD = TimeUnit.DAYS.toMillis(31L); // We consider the last modified date is the start up time of the server private static final long LAST_MODIFIED = System.currentTimeMillis(); @Override public void init(FilterConfig filterConfig) throws ServletException { // Nothing to initialize } @Override public void destroy() { // Nothing to destroy } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Cache-Control", "max-age=2678400000, public"); httpResponse.setHeader("Pragma", "cache"); // Setting Expires header, for proxy caching httpResponse.setDateHeader("Expires", CACHE_PERIOD + System.currentTimeMillis()); // Setting the Last-Modified header, for browser caching httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED); chain.doFilter(request, response); } }
@Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; // Skip oauth for local connections if (!"127.0.0.1".equals(servletRequest.getRemoteAddr())) { // Read the OAuth parameters from the request OAuthServletRequest request = new OAuthServletRequest(httpRequest); OAuthParameters params = new OAuthParameters(); params.readRequest(request); String consumerKey = params.getConsumerKey(); // Set the secret(s), against which we will verify the request OAuthSecrets secrets = new OAuthSecrets(); secrets.setConsumerSecret(m_tokenStore.getToken(consumerKey)); // Check that the timestamp has not expired String timestampStr = params.getTimestamp(); if (timestampStr == null) { logger.warn("Missing OAuth headers"); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing OAuth headers"); return; } long msgTime = Util.parseLong(timestampStr) * 1000L; // Message time is in seconds long currentTime = System.currentTimeMillis(); // if the message is older than 5 min it is no good if (Math.abs(msgTime - currentTime) > 300000) { logger.warn( "OAuth message time out, msg time: " + msgTime + " current time: " + currentTime); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Message expired"); return; } // Verify the signature try { if (!OAuthSignature.verify(request, params, secrets)) { logger.warn("Invalid OAuth signature"); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth signature"); return; } } catch (OAuthSignatureException e) { logger.warn("OAuth exception", e); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth request"); return; } } filterChain.doFilter(servletRequest, servletResponse); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final long startTime = System.currentTimeMillis(); PerformanceFilterResponse filterResponse = new PerformanceFilterResponse((HttpServletResponse) response); chain.doFilter(request, filterResponse); try { processResponse(request, filterResponse, startTime); } catch (Throwable t) { Log logger = LogFactory.getLog(PerformanceMeasurementFilter.class); logger.error(t.getMessage(), t); } }
/** @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(); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Cache-Control", "max-age=" + CACHE_TIME_TO_LIVE + ", public"); httpResponse.setHeader("Pragma", "cache"); // Setting Expires header, for proxy caching httpResponse.setDateHeader("Expires", CACHE_TIME_TO_LIVE + System.currentTimeMillis()); // Setting the Last-Modified header, for browser caching httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED); chain.doFilter(request, response); }
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; }
/** * This filter is used in production, to put HTTP cache headers with a long (1 month) expiration * time. */ public class CachingHttpHeadersFilter implements Filter { // We consider the last modified date is the start up time of the server private static final long LAST_MODIFIED = System.currentTimeMillis(); private long CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(31L); private Environment env; public CachingHttpHeadersFilter(Environment env) { this.env = env; } @Override public void init(FilterConfig filterConfig) throws ServletException { CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis( env.getProperty("jhipster.http.cache.timeToLiveInDays", Long.class, 31L)); } @Override public void destroy() { // Nothing to destroy } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Cache-Control", "max-age=" + CACHE_TIME_TO_LIVE + ", public"); httpResponse.setHeader("Pragma", "cache"); // Setting Expires header, for proxy caching httpResponse.setDateHeader("Expires", CACHE_TIME_TO_LIVE + System.currentTimeMillis()); // Setting the Last-Modified header, for browser caching httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED); chain.doFilter(request, response); } }
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 processResponse( ServletRequest request, PerformanceFilterResponse response, final long startTime) { final int elapsedTime = (int) (System.currentTimeMillis() - startTime); final String outputDirectory = filterConfig .getServletContext() .getInitParameter("org.kuali.kra.perftest.REPORT_DIRECTORY"); final HttpSample httpSample = new HttpSample( (HttpServletRequest) request, response, outputDirectory, startTime, elapsedTime); Thread t = new Thread( new Runnable() { public void run() { logSample(httpSample, outputDirectory); } }); t.start(); }
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); } } }
@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"); } }
// 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
/** * 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(); } }
/** 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 void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); writer.println( (new StringBuilder("Request Received at ")) .append(new Timestamp(System.currentTimeMillis())) .toString()); writer.println( (new StringBuilder(" characterEncoding=")) .append(request.getCharacterEncoding()) .toString()); writer.println( (new StringBuilder(" contentLength=")).append(request.getContentLength()).toString()); writer.println( (new StringBuilder(" contentType=")).append(request.getContentType()).toString()); writer.println( (new StringBuilder(" locale=")).append(request.getLocale()).toString()); writer.print(" locales="); Enumeration locales = request.getLocales(); boolean first = true; Locale locale; for (; locales.hasMoreElements(); writer.print(locale.toString())) { locale = (Locale) locales.nextElement(); if (first) first = false; else writer.print(", "); } writer.println(); for (Enumeration names = request.getParameterNames(); names.hasMoreElements(); writer.println()) { String name = (String) names.nextElement(); writer.print((new StringBuilder(" parameter=")).append(name).append("=").toString()); String values[] = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) writer.print(", "); writer.print(values[i]); } } writer.println( (new StringBuilder(" protocol=")).append(request.getProtocol()).toString()); writer.println( (new StringBuilder(" remoteAddr=")).append(request.getRemoteAddr()).toString()); writer.println( (new StringBuilder(" remoteHost=")).append(request.getRemoteHost()).toString()); writer.println( (new StringBuilder(" scheme=")).append(request.getScheme()).toString()); writer.println( (new StringBuilder(" serverName=")).append(request.getServerName()).toString()); writer.println( (new StringBuilder(" serverPort=")).append(request.getServerPort()).toString()); writer.println( (new StringBuilder(" isSecure=")).append(request.isSecure()).toString()); if (request instanceof HttpServletRequest) { writer.println("---------------------------------------------"); HttpServletRequest hrequest = (HttpServletRequest) request; writer.println( (new StringBuilder(" contextPath=")).append(hrequest.getContextPath()).toString()); Cookie cookies[] = hrequest.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) writer.println( (new StringBuilder(" cookie=")) .append(cookies[i].getName()) .append("=") .append(cookies[i].getValue()) .toString()); String name; String value; for (Enumeration names = hrequest.getHeaderNames(); names.hasMoreElements(); writer.println( (new StringBuilder(" header=")) .append(name) .append("=") .append(value) .toString())) { name = (String) names.nextElement(); value = hrequest.getHeader(name); } writer.println( (new StringBuilder(" method=")).append(hrequest.getMethod()).toString()); writer.println( (new StringBuilder(" pathInfo=")).append(hrequest.getPathInfo()).toString()); writer.println( (new StringBuilder(" queryString=")).append(hrequest.getQueryString()).toString()); writer.println( (new StringBuilder(" remoteUser="******"requestedSessionId=")) .append(hrequest.getRequestedSessionId()) .toString()); writer.println( (new StringBuilder(" requestURI=")).append(hrequest.getRequestURI()).toString()); writer.println( (new StringBuilder(" servletPath=")).append(hrequest.getServletPath()).toString()); } writer.println("============================================="); writer.flush(); filterConfig.getServletContext().log(sw.getBuffer().toString()); chain.doFilter(request, response); }
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; }
/** * 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; }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String longAddr = null, shortAddr, s, transactionKey = null; int count; boolean ignorable = false; synchronized (simultaneousRequestsByShortIPAddr) { if (totalSimultaneousRequests >= maxTotalSimultaneousRequests) { log.error( "This system has exceeded the maxTotalSimultaneousRequests limit of " + maxTotalSimultaneousRequests); log.error(simultaneousRequestsByShortIPAddr); for (String str : simultaneousRequests) log.error(str); ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAVAILABLE); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html><body><h1>Service Temporarily Unavailable</h1>"); writer.println( "The system is experiencing a severe load and is temporarily unable to accept new requests"); if (contactInfo != null) writer.println("<p>Contact " + contactInfo + " for more information</p>"); writer.println("</body></html>"); writer.close(); return; } if (addressInHeader != null) { @SuppressWarnings("unchecked") Enumeration<String> addrs = ((HttpServletRequest) request).getHeaders(addressInHeader); while (addrs.hasMoreElements()) { longAddr = addrs.nextElement(); if (longAddr == null) { if (++addressInHeaderErrorCount < 10) log.error("Expected a " + addressInHeader + " header but got null"); continue; } if (longAddr.lastIndexOf('.') >= 0) break; } } if (longAddr == null) longAddr = request.getRemoteAddr(); int i = longAddr.lastIndexOf('.'); if (i < 0) { log.error("bogus IP address: '" + longAddr + "'"); longAddr = "0.0.0.0"; } shortAddr = longAddr.substring(0, i); // trim off 4th number group // that lets us spot requests from clusters s = equivalentAddresses.get(shortAddr); // map one short addr to another? if (s != null) shortAddr = s; if (ignorableAddresses.contains(shortAddr)) { ignorable = true; } else { Integer icount = simultaneousRequestsByShortIPAddr.get(shortAddr); if (icount != null) count = icount; else count = 0; int maxSimultaneousRequests = (maxTotalSimultaneousRequests - totalSimultaneousRequests) / 4; if (maxSimultaneousRequests == 0) maxSimultaneousRequests = 1; if (count >= maxSimultaneousRequests) { log.error( "IP addr " + shortAddr + ".* has exceeded " + maxSimultaneousRequests + " simultaneous requests!"); log.error("maxTotalSimultaneousRequests=" + maxTotalSimultaneousRequests); log.error("totalSimultaneousRequests=" + totalSimultaneousRequests); for (String str : simultaneousRequests) log.error(str); // // ((HttpServletResponse)response).setStatus(HttpURLConnection.HTTP_TOO_MANY_REQUESTS); // // someday ((HttpServletResponse) response).setStatus(429); // too many requests response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println( "<html><head><title>Too Many Requests</title></head><body><h1>Too Many Requests</h1>"); writer.println( "You have exceeded the maximum simultaneous request value of " + maxSimultaneousRequests); writer.println("<p>This message and your IP address have been logged and reported</p>"); if (contactInfo != null) writer.println("<p>Contact " + contactInfo + " for more information</p>"); writer.println("</body></html>"); writer.close(); return; } simultaneousRequestsByShortIPAddr.put(shortAddr, count + 1); icount = totalRequests.get(shortAddr); if (icount != null) count = icount; else count = 0; totalRequests.put(shortAddr, count + 1); totalSimultaneousRequests++; transactionKey = new StringBuilder((new Date(System.currentTimeMillis())).toString()) .append('|') .append(shortAddr) .append('|') .append(((HttpServletRequest) request).getQueryString()) .toString(); simultaneousRequests.add(transactionKey); } } try { HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response); chain.doFilter(request, wrapper); } finally { if (!ignorable) synchronized (simultaneousRequestsByShortIPAddr) { totalSimultaneousRequests--; simultaneousRequests.remove(transactionKey); count = simultaneousRequestsByShortIPAddr.get(shortAddr); if (count == 1) // prune them from the table simultaneousRequestsByShortIPAddr.remove(shortAddr); else simultaneousRequestsByShortIPAddr.put(shortAddr, count - 1); } } Calendar c = new GregorianCalendar(); int hour = c.get(Calendar.HOUR_OF_DAY); if (hour == 0 && nextReportingHour == 24) { // new day! // you could reset your daily limits table here nextReportingHour = 0; } if (hour >= nextReportingHour) { // generate the hourly report // you could reset your hourly limits table here nextReportingHour = hour + 1; if (log.isInfoEnabled()) { HashMap<String, Integer> map = new LinkedHashMap<String, Integer>(); List<String> yourMapKeys = new ArrayList<String>(totalRequests.keySet()); List<Integer> yourMapValues = new ArrayList<Integer>(totalRequests.values()); TreeSet<Integer> sortedSet = new TreeSet<Integer>(yourMapValues); Integer[] sortedArray = sortedSet.descendingSet().toArray(new Integer[0]); int size = sortedArray.length; for (int i = 0; i < size; i++) map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])), sortedArray[i]); Iterator<String> it = map.keySet().iterator(); String key; StringBuilder sb = new StringBuilder("Top 10 users in the last hour"); for (int i = 0; i < 10 && it.hasNext(); i++) { key = it.next(); sb.append("\n ").append(key).append(" : ").append(map.get(key)); } log.info(sb); } totalRequests.clear(); } }
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; }
/** * 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 }
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("/"); }