protected void handleDocument( HttpServletRequest request, HttpServletResponse response, Document doc) throws IOException { if (request.getPathInfo().equalsIgnoreCase("/load")) getXmlScoreBoard().loadDocument(doc); else if (request.getPathInfo().equalsIgnoreCase("/merge")) getXmlScoreBoard().mergeDocument(doc); else response.sendError( HttpServletResponse.SC_NOT_FOUND, "Must specify to load or merge document"); response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); }
protected String getRequestKey() { String key = req.getPathInfo(); if (key != null && key.startsWith("/")) { return key.substring(1); } return key; }
/** * Constructor. * * @param rq request * @param rs response * @throws IOException I/O exception */ public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException { req = rq; res = rs; final String m = rq.getMethod(); method = HTTPMethod.get(m); final StringBuilder uri = new StringBuilder(req.getRequestURL()); final String qs = req.getQueryString(); if (qs != null) uri.append('?').append(qs); log(false, m, uri); // set UTF8 as default encoding (can be overwritten) res.setCharacterEncoding(UTF8); segments = toSegments(req.getPathInfo()); path = join(0); user = System.getProperty(DBUSER); pass = System.getProperty(DBPASS); // set session-specific credentials final String auth = req.getHeader(AUTHORIZATION); if (auth != null) { final String[] values = auth.split(" "); if (values[0].equals(BASIC)) { final String[] cred = Base64.decode(values[1]).split(":", 2); if (cred.length != 2) throw new LoginException(NOPASSWD); user = cred[0]; pass = cred[1]; } else { throw new LoginException(WHICHAUTH, values[0]); } } }
/** * Show the pieces of the request, for debugging * * @param req the HttpServletRequest * @return parsed request */ public static String getRequestParsed(HttpServletRequest req) { return req.getRequestURI() + " = " + req.getContextPath() + "(context), " + req.getServletPath() + "(servletPath), " + req.getPathInfo() + "(pathInfo), " + req.getQueryString() + "(query)"; }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getPathInfo(); boolean htmlOutput = true; String language = null; String contentType = "text/html; charset='utf-8'"; if (path != null) { if (path.endsWith(".rdf")) { contentType = "application/rdf+xml; charset='utf-8'"; htmlOutput = false; language = "RDF/XML"; } else if (path.endsWith(".xml")) { contentType = "application/xml; charset='utf-8'"; htmlOutput = false; language = "RDF/XML"; } else if (path.endsWith(".n3")) { contentType = "text/n3; charset='utf-8'"; htmlOutput = false; language = "N3"; } } response.setContentType(contentType); response.setStatus(HttpServletResponse.SC_OK); Writer writer = response.getWriter(); synchronized (board) { if (htmlOutput) { writer.write( "<!DOCTYPE html>\n" + "<html lang='en'>" + "<head><meta charset='utf-8'/><title>MATe model</title></head>" + "<body><ul>"); StmtIterator it = model.listStatements(); /* TODO: well, this could be prettier */ while (it.hasNext()) writer.write("<li>" + it.nextStatement() + "</li>"); writer.write("<ul></body></html>"); } else model.write(writer, language); } }
/** * Constructor. * * @param rq request * @param rs response * @param servlet calling servlet instance * @throws IOException I/O exception */ public HTTPContext( final HttpServletRequest rq, final HttpServletResponse rs, final BaseXServlet servlet) throws IOException { req = rq; res = rs; params = new HTTPParams(this); method = rq.getMethod(); final StringBuilder uri = new StringBuilder(req.getRequestURL()); final String qs = req.getQueryString(); if (qs != null) uri.append('?').append(qs); log('[' + method + "] " + uri, null); // set UTF8 as default encoding (can be overwritten) res.setCharacterEncoding(UTF8); segments = decode(toSegments(req.getPathInfo())); // adopt servlet-specific credentials or use global ones final GlobalOptions mprop = context().globalopts; user = servlet.user != null ? servlet.user : mprop.get(GlobalOptions.USER); pass = servlet.pass != null ? servlet.pass : mprop.get(GlobalOptions.PASSWORD); // overwrite credentials with session-specific data final String auth = req.getHeader(AUTHORIZATION); if (auth != null) { final String[] values = auth.split(" "); if (values[0].equals(BASIC)) { final String[] cred = org.basex.util.Base64.decode(values[1]).split(":", 2); if (cred.length != 2) throw new LoginException(NOPASSWD); user = cred[0]; pass = cred[1]; } else { throw new LoginException(WHICHAUTH, values[0]); } } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String actionName = ""; String pathInfo = request.getPathInfo(); String destinationPage = ERROR_PAGE; if (inventory == null) { String errorMessage = "Inventory EJB reference is null."; request.setAttribute(ERROR_KEY, errorMessage); } else { if (pathInfo != null) { actionName = pathInfo.substring(1); // Get the action name from the HTTP Request. } // perform action if (VIEW_CAR_LIST_ACTION.equals(actionName)) { request.setAttribute("carList", inventory.listAvailableCars()); destinationPage = "/carList.jsp"; } else if (ADD_CAR_ACTION.equals(actionName)) { request.setAttribute("car", new CarDTO()); destinationPage = "/carForm.jsp"; } else if (EDIT_CAR_ACTION.equals(actionName)) { int id = Integer.parseInt(request.getParameter("id")); request.setAttribute("car", inventory.findCar(id)); destinationPage = "/carForm.jsp"; } else if (SAVE_CAR_ACTION.equals(actionName)) { // build the car from the request parameters CarDTO car = new CarDTO(); car.setId(Integer.parseInt(request.getParameter("id"))); car.setMake(request.getParameter("make")); car.setModel(request.getParameter("model")); car.setModelYear(request.getParameter("modelYear")); // save the car inventory.saveCar(car); // prepare the list request.setAttribute("carList", inventory.listAvailableCars()); destinationPage = "/carList.jsp"; } else if (DELETE_CAR_ACTION.equals(actionName)) { // get list of ids to delete String[] ids = request.getParameterValues("id"); // delete the list of ids inventory.deleteCars(ids); // prepare the list request.setAttribute("carList", inventory.listAvailableCars()); destinationPage = "/carList.jsp"; } else if (VIEW_BUY_CAR_FORM_ACTION.equals(actionName)) { int id = Integer.parseInt(request.getParameter("id")); request.setAttribute("car", inventory.findCar(id)); destinationPage = "/buyCarForm.jsp"; } else if (BUY_CAR_ACTION.equals(actionName)) { int carId = Integer.parseInt(request.getParameter("id")); double price; // Use $5000.00 as the default price if the user enters bad data. try { price = Double.parseDouble(request.getParameter("price")); } catch (NumberFormatException nfe) { price = 5000.00; } System.out.println("carId = [" + carId + "], price = [" + price + "]"); // mark the car as sold inventory.buyCar(carId, price); // prepare the list request.setAttribute("carList", inventory.listAvailableCars()); destinationPage = "/carList.jsp"; } else { String errorMessage = "[" + actionName + "] is not a valid action."; request.setAttribute(ERROR_KEY, errorMessage); } } // Redirect to destination page. RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(destinationPage); dispatcher.forward(request, response); }
public String getPathInfo() { return request.getPathInfo(); }
/** * Return the request URL relative to the server (i.e., starting with the context path). * * @param req request * @return URL relative to the server */ public static String getReletiveURL(HttpServletRequest req) { return req.getContextPath() + req.getServletPath() + req.getPathInfo(); }
/** * Show details about the request * * @param servlet used to get teh servlet context, may be null * @param req the request * @return string showing the details of the request. */ public static String showRequestDetail(HttpServlet servlet, HttpServletRequest req) { StringBuilder sbuff = new StringBuilder(); sbuff.append("Request Info\n"); sbuff.append(" req.getServerName(): ").append(req.getServerName()).append("\n"); sbuff.append(" req.getServerPort(): ").append(req.getServerPort()).append("\n"); sbuff.append(" req.getContextPath:").append(req.getContextPath()).append("\n"); sbuff.append(" req.getServletPath:").append(req.getServletPath()).append("\n"); sbuff.append(" req.getPathInfo:").append(req.getPathInfo()).append("\n"); sbuff.append(" req.getQueryString:").append(req.getQueryString()).append("\n"); sbuff .append(" getQueryStringDecoded:") .append(EscapeStrings.urlDecode(req.getQueryString())) .append("\n"); /*try { sbuff.append(" getQueryStringDecoded:").append(URLDecoder.decode(req.getQueryString(), "UTF-8")).append("\n"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); }*/ sbuff.append(" req.getRequestURI:").append(req.getRequestURI()).append("\n"); sbuff.append(" getRequestBase:").append(getRequestBase(req)).append("\n"); sbuff.append(" getRequestServer:").append(getRequestServer(req)).append("\n"); sbuff.append(" getRequest:").append(getRequest(req)).append("\n"); sbuff.append("\n"); sbuff.append(" req.getPathTranslated:").append(req.getPathTranslated()).append("\n"); String path = req.getPathTranslated(); if ((path != null) && (servlet != null)) { ServletContext context = servlet.getServletContext(); sbuff.append(" getMimeType:").append(context.getMimeType(path)).append("\n"); } sbuff.append("\n"); sbuff.append(" req.getScheme:").append(req.getScheme()).append("\n"); sbuff.append(" req.getProtocol:").append(req.getProtocol()).append("\n"); sbuff.append(" req.getMethod:").append(req.getMethod()).append("\n"); sbuff.append("\n"); sbuff.append(" req.getContentType:").append(req.getContentType()).append("\n"); sbuff.append(" req.getContentLength:").append(req.getContentLength()).append("\n"); sbuff.append(" req.getRemoteAddr():").append(req.getRemoteAddr()); try { sbuff .append(" getRemoteHost():") .append(java.net.InetAddress.getByName(req.getRemoteHost()).getHostName()) .append("\n"); } catch (java.net.UnknownHostException e) { sbuff.append(" getRemoteHost():").append(e.getMessage()).append("\n"); } sbuff.append(" getRemoteUser():").append(req.getRemoteUser()).append("\n"); sbuff.append("\n"); sbuff.append("Request Parameters:\n"); Enumeration params = req.getParameterNames(); while (params.hasMoreElements()) { String name = (String) params.nextElement(); String values[] = req.getParameterValues(name); if (values != null) { for (int i = 0; i < values.length; i++) { sbuff .append(" ") .append(name) .append(" (") .append(i) .append("): ") .append(values[i]) .append("\n"); } } } sbuff.append("\n"); sbuff.append("Request Headers:\n"); Enumeration names = req.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Enumeration values = req.getHeaders(name); // support multiple values if (values != null) { while (values.hasMoreElements()) { String value = (String) values.nextElement(); sbuff.append(" ").append(name).append(": ").append(value).append("\n"); } } } sbuff.append(" ------------------\n"); return sbuff.toString(); }
/** * servletPath + pathInfo * * @param req the HttpServletRequest * @return parsed request servletPath + pathInfo */ public static String getRequestPath(HttpServletRequest req) { StringBuffer buff = new StringBuffer(); if (req.getServletPath() != null) buff.append(req.getServletPath()); if (req.getPathInfo() != null) buff.append(req.getPathInfo()); return buff.toString(); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); String title = rb.getString("requestinfo.title"); out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body bgcolor=\"white\">"); // img stuff not req'd for source code html showing // all links relative! // XXX // making these absolute till we work out the // addition of a PathInfo issue out.println("<a href=\"../reqinfo.html\">"); out.println( "<img src=\"../images/code.gif\" height=24 " + "width=24 align=right border=0 alt=\"view code\"></a>"); out.println("<a href=\"../index.html\">"); out.println( "<img src=\"../images/return.gif\" height=24 " + "width=24 align=right border=0 alt=\"return\"></a>"); out.println("<h3>" + title + "</h3>"); out.println("<table border=0><tr><td>"); out.println(rb.getString("requestinfo.label.method")); out.println("</td><td>"); out.println(request.getMethod()); out.println("</td></tr><tr><td>"); out.println(rb.getString("requestinfo.label.requesturi")); out.println("</td><td>"); out.println(HTMLFilter.filter(request.getRequestURI())); out.println("</td></tr><tr><td>"); out.println(rb.getString("requestinfo.label.protocol")); out.println("</td><td>"); out.println(request.getProtocol()); out.println("</td></tr><tr><td>"); out.println(rb.getString("requestinfo.label.pathinfo")); out.println("</td><td>"); out.println(HTMLFilter.filter(request.getPathInfo())); out.println("</td></tr><tr><td>"); out.println(rb.getString("requestinfo.label.remoteaddr")); String cipherSuite = (String) request.getAttribute("javax.servlet.request.cipher_suite"); out.println("</td><td>"); out.println(request.getRemoteAddr()); out.println("</table>"); if (cipherSuite != null) { out.println("</td></tr><tr><td>"); out.println("SSLCipherSuite:"); out.println("</td>"); out.println("<td>"); out.println(request.getAttribute("javax.servlet.request.cipher_suite")); out.println("</td>"); } }
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()); } }
// 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