@Override public void parseRequestParameters( final Map<String, String> params, final Map<String, com.bradmcevoy.http.FileItem> files) throws RequestParseException { try { if (isMultiPart()) { parseQueryString(params, req.getQueryString()); @SuppressWarnings("unchecked") final List<FileItem> items = new ServletFileUpload().parseRequest(req); for (final FileItem item : items) { if (item.isFormField()) params.put(item.getFieldName(), item.getString()); else files.put(item.getFieldName(), new FileItemWrapper(item)); } } else { final Enumeration<String> en = req.getParameterNames(); while (en.hasMoreElements()) { final String nm = en.nextElement(); final String val = req.getParameter(nm); params.put(nm, val); } } } catch (final FileUploadException ex) { throw new RequestParseException("FileUploadException", ex); } catch (final Throwable ex) { throw new RequestParseException(ex.getMessage(), ex); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Tracking Example"; HttpSession session = request.getSession(true); String heading; Integer accessCount = (Integer) session.getAttribute("accessCount"); if (accessCount == null) { accessCount = new Integer(0); heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } session.setAttribute("accessCount", accessCount); out.println( "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Info Type<TH>Value\n" + "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getId() + "\n" + "<TR>\n" + " <TD>Creation Time\n" + " <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" + " <TD>Time of Last Access\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" + " <TD>Number of Previous Accesses\n" + " <TD>" + accessCount + "\n" + "</TR>" + "</TABLE>\n"); // the following two statements show how to retrieve parameters in // the request. The URL format is something like: // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li String myname = request.getParameter("myname"); if (myname != null) out.println("Hey " + myname + "<br><br>"); out.println("</BODY></HTML>"); }
private String getOriginOrReferer(HttpServletRequest pReq) { String origin = pReq.getHeader("Origin"); if (origin == null) { origin = pReq.getHeader("Referer"); } return origin != null ? origin.replaceAll("[\\n\\r]*", "") : null; }
/** * Return the request parameters as a Map<String,String>. Only the first value of multivalued * parameters is included. */ Map<String, String> getParamsAsMap() { Map<String, String> map = new HashMap<String, String>(); for (Enumeration en = req.getParameterNames(); en.hasMoreElements(); ) { String name = (String) en.nextElement(); map.put(name, req.getParameter(name)); } return map; }
/** * Return the request parameters as a Properties. Only the first value of multivalued parameters * is included. */ Properties getParamsAsProps() { Properties props = new Properties(); for (Enumeration en = req.getParameterNames(); en.hasMoreElements(); ) { String name = (String) en.nextElement(); props.setProperty(name, req.getParameter(name)); } return props; }
/** * OPTION requests are treated as CORS preflight requests * * @param req the original request * @param resp the response the answer are written to */ @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String, String> responseHeaders = requestHandler.handleCorsPreflightRequest( req.getHeader("Origin"), req.getHeader("Access-Control-Request-Headers")); for (Map.Entry<String, String> entry : responseHeaders.entrySet()) { resp.setHeader(entry.getKey(), entry.getValue()); } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("[Servlet3.doPost]"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("FILTER-REQUEST:" + request.getSession().getAttribute("FILTER-REQUEST")); out.println("FILTER-FORWARD:" + request.getSession().getAttribute("FILTER-FORWARD")); out.println("FILTER-INCLUDE:" + request.getSession().getAttribute("FILTER")); }
@Override public Map<String, String> getHeaders() { final Map<String, String> map = new HashMap<>(); final Enumeration<String> en = req.getHeaderNames(); while (en.hasMoreElements()) { final String name = en.nextElement(); final String val = req.getHeader(name); map.put(name, val); } return map; }
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { traceRequest(req); String pathInfoString = req.getPathInfo(); String queryString = getQueryString(req); IPath pathInfo = new Path( null /*don't parse host:port as device*/, pathInfoString == null ? "" : pathInfoString); // $NON-NLS-1$ if (pathInfo.segmentCount() > 0) { String hostedHost = pathInfo.segment(0); IHostedSite site = HostingActivator.getDefault().getHostingService().get(hostedHost); if (site != null) { IPath path = pathInfo.removeFirstSegments(1); IPath contextPath = new Path(req.getContextPath()); IPath contextlessPath = path.makeRelativeTo(contextPath).makeAbsolute(); URI[] mappedPaths; try { mappedPaths = getMapped(site, contextlessPath, queryString); } catch (URISyntaxException e) { handleException( resp, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Could not create target URI ", e)); return; } if (mappedPaths != null) { serve(req, resp, site, mappedPaths); } else { handleException( resp, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, NLS.bind("No mappings matched {0}", path), null)); } } else { String msg = NLS.bind("Hosted site {0} is stopped", hostedHost); handleException( resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } } else { super.doGet(req, resp); } }
/** * @param request The servlet request we are processing * @param result The servlet response we are creating * @param chain The filter chain we are processing * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // once session invalidated, go back to login screen HttpServletRequest req = (HttpServletRequest) request; HttpSession session = req.getSession(); String login = (String) session.getAttribute("login"); if (login != null && login.equals("Y")) { chain.doFilter(request, response); } else { RequestDispatcher rd = request.getRequestDispatcher("/myadmin/logout.jsp"); rd.forward(request, response); } // chain.doFilter(request, response); }
private void serve( HttpServletRequest req, HttpServletResponse resp, IHostedSite site, URI[] mappedURIs) throws ServletException, IOException { for (int i = 0; i < mappedURIs.length; i++) { URI uri = mappedURIs[i]; // Bypass a 404 if any workspace or remote paths remain to be checked. boolean failEarlyOn404 = i + 1 < mappedURIs.length; if (uri.getScheme() == null) { if ("GET".equals(req.getMethod())) { // $NON-NLS-1$ if (serveOrionFile(req, resp, site, new Path(uri.getPath()), failEarlyOn404)) return; } else { String message = "Only GET method is supported for workspace paths"; handleException( resp, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_METHOD_NOT_ALLOWED, NLS.bind(message, mappedURIs), null)); } } else { if (proxyRemotePath( req, new LocationHeaderServletResponseWrapper(req, resp, site), uri, failEarlyOn404)) return; } } }
// callRestfulApi - Calls restful API and returns results as a string public String callRestfulApi( String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(API_ROOT + addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } return output.toString(); } catch (IOException e) { System.out.println(e.getMessage()); return null; } } // TESTED
// Extract mime type for response (if not JSONP) private String getMimeType(HttpServletRequest pReq) { String requestMimeType = pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue()); if (requestMimeType != null) { return requestMimeType; } return configMimeType; }
protected void logParams() { Enumeration en = req.getParameterNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); String vals[]; String dispval; if (StringUtil.indexOfIgnoreCase(name, "passw") >= 0) { dispval = req.getParameter(name).length() == 0 ? "" : "********"; } else if (log.isDebug2() && (vals = req.getParameterValues(name)).length > 1) { dispval = StringUtil.separatedString(vals, ", "); } else { dispval = req.getParameter(name); } log.debug(name + " = " + dispval); } }
@Override public Cookie getCookie(final String name) { for (final javax.servlet.http.Cookie c : req.getCookies()) { if (c.getName().equals(name)) return new BXServletCookie(c); } return null; }
// Get parameter map either directly from an Servlet 2.4 compliant implementation // or by looking it up explictely (thanks to codewax for the patch) private Map<String, String[]> getParameterMap(HttpServletRequest pReq) { try { // Servlet 2.4 API return pReq.getParameterMap(); } catch (UnsupportedOperationException exp) { // Thrown by 'pseudo' 2.4 Servlet API implementations which fake a 2.4 API // As a service for the parameter map is build up explicitely Map<String, String[]> ret = new HashMap<String, String[]>(); Enumeration params = pReq.getParameterNames(); while (params.hasMoreElements()) { String param = (String) params.nextElement(); ret.put(param, pReq.getParameterValues(param)); } return ret; } }
// postToRestfulApi - // Note: params in the addr field need to be URLEncoded private String postToRestfulApi( String addr, String data, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); String result = ""; try { URLConnection connection = new URL(API_ROOT + addr).openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); } connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); // Post JSON string to URL OutputStream os = connection.getOutputStream(); byte[] b = data.getBytes("UTF-8"); os.write(b); // Receive results back from API InputStream is = connection.getInputStream(); result = IOUtils.toString(is, "UTF-8"); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } } catch (Exception e) { // System.out.println("Exception: " + e.getMessage()); } return result; } // TESTED
// Set an appropriate CORS header if requested and if allowed private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) { String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin")); if (origin != null) { pResp.setHeader("Access-Control-Allow-Origin", origin); pResp.setHeader("Access-Control-Allow-Credentials", "true"); } }
protected String getRequestKey() { String key = req.getPathInfo(); if (key != null && key.startsWith("/")) { return key.substring(1); } return key; }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); System.out.println("queryString: " + request.getQueryString()); out.println("FILTER-QUERYSTRING:" + (request.getQueryString() != null ? "PASS" : "FAIL")); }
/** * This calls the itemselection.jsp and list all items available for a WorkOrder and a WorkOrder's * item list * * @param workorderid - the WO_ID of the parent WorkOrder * @param request - servlet request * @param response - servlet response */ private void listProducts( long workorderId, WorkOrderDetailRemote workorderdetEJBean, HttpSession session, HttpServletRequest req, HttpServletResponse resp) { try { // If any product object is left over in session remove it session.removeValue("itemObj"); // Create db connection for EJB workorderdetEJBean.connect(); // Get the 2D Array which has the List of Items for the WorkOrder // grouped by the Billing System. Object[][] productList = workorderdetEJBean.getWorkOrderItems(workorderId); // Get the WorkOrder Object WorkOrder workorderObj = workorderdetEJBean.getWorkOrderInfo(workorderId); // Get the List of all Product Names for the WorkOrder String[] productNameList = workorderdetEJBean.getProdList(workorderId); for (int w = 0; w < productNameList.length; w++) USFEnv.getLog() .writeDebug("VALUES INSIDE productNameList is" + productNameList[w], this, null); // Set the attributes to the itemselection JSP req.setAttribute("productNameList", productNameList); req.setAttribute("productList", productList); req.setAttribute("workorderObj", workorderObj); // Release db connection for EJB workorderdetEJBean.release(); // Include the JSP includeJSP(req, resp, ITEM_JSP_PATH, "itemselection"); return; } catch (Exception e) { String errorMsg = "Fail to list products for a WORKORDER " + workorderId; USFEnv.getLog().writeCrit(errorMsg, this, e); errorJSP(req, resp, errorMsg); } }
/** Get the current session, creating it if necessary (and set the timeout if so) */ protected HttpSession getSession() { if (session == null) { session = req.getSession(true); if (session.isNew()) { setSessionTimeout(session); } } return session; }
public URL getUrl(HttpServletRequest req) throws IOException { String servletPath = req.getServletPath(); String selectedServerFullPath = getServerAddress(servletPath); String queryString = req.getQueryString(); String newUrl = ""; HttpSession session = req.getSession(false); newUrl = selectedServerFullPath + servletPath; if (req.getRequestedSessionId() != null) newUrl = newUrl + ";jsessionid=" + req.getRequestedSessionId(); if (queryString != null) newUrl = newUrl + "?" + queryString; // if (session != null) newUrl = newUrl + ";jsessionid=" + session.getId(); return new URL(newUrl); }
// getBrowserInfiniteCookie public static String getBrowserInfiniteCookie(HttpServletRequest request) { Cookie[] cookieJar = request.getCookies(); if (cookieJar != null) { for (Cookie cookie : cookieJar) { if (cookie.getName().equals("infinitecookie")) { return cookie.getValue() + ";"; } } } return null; } // TESTED
/** * Returns an array with all accepted content types. if the root directory was specified. * * @return database */ public String[] produces() { final String accept = req.getHeader("Accept"); if (accept == null) return new String[0]; final String[] acc = accept.split("\\s*,\\s*"); final int as = acc.length; for (int a = 0; a < as; a++) { if (acc[a].indexOf(';') != -1) acc[a] = acc[a].replaceAll("\\w*;.*", ""); } return acc; }
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write('\n'); out.write('\n'); out.write("\n<!DOCTYPE html>\n<html>\n<head>\n"); JspHelper.createTitle(out, request, request.getParameter("filename")); out.write("\n</head>\n<body onload=\"document.goto.dir.focus()\">\n"); Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF); generateFileChunks(out, request, conf); out.write("\n<hr>\n"); generateFileDetails(out, request, conf); out.write("\n\n<h2>Local logs</h2>\n<a href=\"/logs/\">Log</a> directory\n\n"); out.println(ServletUtil.htmlFooter()); out.write('\n'); } catch (Throwable t) { if (!(t instanceof SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
// Update the agent URL in the agent details if not already done private void updateAgentDetailsIfNeeded(HttpServletRequest pReq) { // Lookup the Agent URL if needed AgentDetails details = backendManager.getAgentDetails(); if (details.isInitRequired()) { synchronized (details) { if (details.isInitRequired()) { if (details.isUrlMissing()) { String url = getBaseUrl( NetworkUtil.sanitizeLocalUrl(pReq.getRequestURL().toString()), extractServletPath(pReq)); details.setUrl(url); } if (details.isSecuredMissing()) { details.setSecured(pReq.getAuthType() != null); } details.seal(); } } } }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); int i, j; String amount = req.getParameter("amount"); String from = req.getParameter("from"); String to = req.getParameter("to"); String ch = req.getParameter("choice"); String answer, answer1, answer2, answer3; if ("INFO".equals(ch)) { Redirect_info newurl = (Redirect_info) getServletContext().getAttribute("redirect"); res.sendRedirect(newurl.getUrl()); } else { out.println("<html>"); out.println("<title>Currency Converter</title>"); String addr = "http://www.google.com/ig/calculator?hl=en&q=" + amount + from + "=?" + to; URL convert = new URL(addr); BufferedReader in = new BufferedReader(new InputStreamReader(convert.openStream())); answer = in.readLine(); answer = new String(answer.getBytes("ISO-8859-1"), "ISO-8859-7"); from = new String(from.getBytes("ISO-8859-1"), "ISO-8859-7"); to = new String(to.getBytes("ISO-8859-1"), "ISO-8859-7"); amount = new String(amount.getBytes("ISO-8859-1"), "ISO-8859-7"); in.close(); i = answer.indexOf('"'); answer = answer.substring(i + 1); i = answer.indexOf('"'); answer = answer.substring(i + 1); i = answer.indexOf('"'); answer = answer.substring(i + 1); i = answer.indexOf('"'); answer = answer.substring(0, i); out.println("<p ALIGN=CENTER>" + amount + " " + from + " == " + answer + "(" + to + ")</p>"); out.println("</body>"); out.println("</html>"); } }
@SuppressWarnings({"PMD.AvoidCatchingThrowable", "PMD.AvoidInstanceofChecksInCatchClause"}) private void handle( ServletRequestHandler pReqHandler, HttpServletRequest pReq, HttpServletResponse pResp) throws IOException { JSONAware json = null; try { // Check access policy requestHandler.checkAccess( pReq.getRemoteHost(), pReq.getRemoteAddr(), getOriginOrReferer(pReq)); // Remember the agent URL upon the first request. Needed for discovery updateAgentDetailsIfNeeded(pReq); // Dispatch for the proper HTTP request method json = handleSecurely(pReqHandler, pReq, pResp); } catch (Throwable exp) { json = requestHandler.handleThrowable( exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp); } finally { setCorsHeader(pReq, pResp); String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue()); String answer = json != null ? json.toJSONString() : requestHandler .handleThrowable(new Exception("Internal error while handling an exception")) .toJSONString(); if (callback != null) { // Send a JSONP response sendResponse(pResp, "text/javascript", callback + "(" + answer + ");"); } else { sendResponse(pResp, getMimeType(pReq), answer); } } }
/** * 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]); } } }