protected Link retrieveLink(final HttpServletRequest httpServletRequest) { String uri = httpServletRequest .getRequestURI() .substring(httpServletRequest.getRequestURI().lastIndexOf("/") + 1); _log.debug("Extracted URI: " + uri); return Link.create(uri); }
/** * Attempts to send an internal server error HTTP error, if possible. Otherwise simply pushes the * exception message to the output stream. * * @param message Message to be printed to the logger and to the output stream. * @param t Exception that caused the error. */ protected void filterError(String message, Throwable t) { log.error("XSLT filter error: " + message, t); if (false == origResponse.isCommitted()) { // Reset the buffer and previous status code. origResponse.reset(); origResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); origResponse.setContentType("text/html; charset=UTF-8"); } // Response committed. Just push the error to the output stream. try { final OutputStream os = origResponse.getOutputStream(); final PrintWriter osw = new PrintWriter(new OutputStreamWriter(os, "iso8859-1")); osw.write("<html><body><!-- " + XSLTFilterConstants.ERROR_TOKEN + " -->"); osw.write("<h1 style=\"color: red; margin-top: 1em;\">"); osw.write("Internal server exception"); osw.write("</h1>"); osw.write("<b>URI</b>: " + origRequest.getRequestURI() + "\n<br/><br/>"); serializeException(osw, t); if (t instanceof ServletException && ((ServletException) t).getRootCause() != null) { osw.write("<br/><br/><h2>ServletException root cause:</h2>"); serializeException(osw, ((ServletException) t).getRootCause()); } osw.write("</body></html>"); osw.flush(); } catch (IOException e) { // Not much to do in such case (connection broken most likely). log.debug("Filter error could not be returned to client."); } }
private void rotateTokens(HttpServletRequest request) { HttpSession session = request.getSession(true); /** rotate master token * */ String tokenFromSession = null; try { tokenFromSession = RandomGenerator.generateRandomId(getPrng(), getTokenLength()); } catch (Exception e) { throw new RuntimeException( String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e); } session.setAttribute(getSessionKey(), tokenFromSession); /** rotate page token * */ if (isTokenPerPageEnabled()) { @SuppressWarnings("unchecked") Map<String, String> pageTokens = (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY); try { pageTokens.put( request.getRequestURI(), RandomGenerator.generateRandomId(getPrng(), getTokenLength())); } catch (Exception e) { throw new RuntimeException( String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e); } } }
void sendHTML( HttpServletRequest request, HttpServletResponse response, String script, Exception scriptError, Object scriptResult, StringBuffer scriptOutput, boolean capture) throws IOException { // Format the output using a simple templating utility SimpleTemplate st = new SimpleTemplate(BshServlet.class.getResource("page.template")); st.replace("version", getBshVersion()); // String requestURI = HttpUtils.getRequestURL( request ).toString() // I was told this should work String requestURI = request.getRequestURI(); st.replace("servletURL", requestURI); if (script != null) st.replace("script", script); else st.replace("script", exampleScript); if (capture) st.replace("captureOutErr", "CHECKED"); else st.replace("captureOutErr", ""); if (script != null) st.replace( "scriptResult", formatScriptResultHTML(script, scriptResult, scriptError, scriptOutput)); response.setContentType("text/html"); PrintWriter out = response.getWriter(); st.write(out); out.flush(); }
public void updateTokens(HttpServletRequest request) { /** cannot create sessions if response already committed * */ HttpSession session = request.getSession(false); if (session != null) { /** create master token if it does not exist * */ updateToken(session); /** create page specific token * */ if (isTokenPerPageEnabled()) { @SuppressWarnings("unchecked") Map<String, String> pageTokens = (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY); /** first time initialization * */ if (pageTokens == null) { pageTokens = new HashMap<String, String>(); session.setAttribute(CsrfGuard.PAGE_TOKENS_KEY, pageTokens); } /** create token if it does not exist * */ if (isProtectedPageAndMethod(request)) { createPageToken(pageTokens, request.getRequestURI()); } } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); if (request.getParameter("setcookie") != null) { Cookie cookie = new Cookie("Learningjava", "Cookies!"); cookie.setMaxAge(3600); response.addCookie(cookie); out.println("<html><body><h1>Cookie Set...</h1>"); } else { out.println("<html><body>"); Cookie[] cookies = request.getCookies(); if (cookies.length == 0) { out.println("<h1>No cookies found...</h1>"); } else { for (int i = 0; i < cookies.length; i++) out.print( "<h1>Name: " + cookies[i].getName() + "<br>" + "Value: " + cookies[i].getValue() + "</h1>"); } out.println( "<p><a href=\"" + request.getRequestURI() + "?setcookie=true\">" + "Reset the Learning Java cookie.</a>"); } out.println("</body></html>"); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Showing Request Headers"; StringBuilder sb = new StringBuilder(); sb.append("<html>\n<head>\n"); sb.append("<title>" + title + "</title>\n"); sb.append("</head>\n"); sb.append("<body bgcolor='#FDF5E6'>\n"); sb.append("<h1 align='center'>" + title + "</h1>\n"); sb.append("<b> Request Method: </b>" + request.getMethod() + "<br>\n"); sb.append("<b> Request URI: </b>" + request.getRequestURI() + "<br>\n"); sb.append("<b> Request Protocol: </b>" + request.getProtocol() + "<br>\n"); sb.append("<table border=1 align='center'>\n"); sb.append("<tr bgcolor='#FFAD00'>\n"); sb.append("<th> Header Name </th><th> Header Value </th></tr>\n"); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); sb.append("<tr><td>" + headerName + "</td>"); sb.append("<td>" + request.getHeader(headerName) + "</td></tr>\n"); } sb.append("</table>\n"); sb.append("</body></html>"); out.println(sb.toString()); out.close(); }
private void insertLog(HttpServletRequest req, Connection connection) throws SQLException { try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO LOGGING (date,ip,url) VALUES (?,?,?)")) { stmt.setTimestamp(1, new Timestamp((new java.util.Date()).getTime())); stmt.setString(2, req.getRemoteAddr()); stmt.setString(3, req.getRequestURI()); stmt.executeUpdate(); } }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println( "MyProtectedServlet.processRequest " + request.getRequestURI() + " " + request.getQueryString()); String myUrl = request.getRequestURI(); if (myUrl.indexOf("login") >= 0) { login(request, response); return; } else if (myUrl.indexOf("redirect") >= 0) { redirect(request, response); return; } if (request.getRemoteUser() == null) { String callUrl = request.getRequestURI(); String query = request.getQueryString(); if (query != null) { callUrl = callUrl + "?" + query; } String nextEncUrl = java.net.URLEncoder.encode(callUrl); String redirectUrl = request.getContextPath() + "/application/redirect?nextencurl=" + nextEncUrl; response.sendRedirect(redirectUrl); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet MyProtectedServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet MyProtectedServlet at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); out.close(); } }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // read the last post id here ....................... String url = req.getRequestURI(); String urlprt[] = url.split("/"); int urlcount = urlprt.length - 1; JSONParser parserPost = new JSONParser(); JSONObject post = null; String id = urlprt[urlcount]; // read the post here ............................. try { if (id != null) { Object objPost = parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json")); post = (JSONObject) objPost; String postauthor = post.get("author").toString(); String posttitle = post.get("title").toString(); String postcontent = post.get("content").toString(); JSONArray arr = (JSONArray) post.get("comments"); List<String> list = new ArrayList<String>(); Iterator<String> iterator = arr.iterator(); while (iterator.hasNext()) { list.add(iterator.next()); } int listsz = list.size(); String[] comments = new String[listsz]; for (int i = 0; i < listsz; i++) { comments[i] = list.get(i); } req.setAttribute("title", posttitle); req.setAttribute("content", postcontent); req.setAttribute("author", postauthor); req.setAttribute("comments", comments); req.setAttribute("id", id); req.getRequestDispatcher("/view.jsp").forward(req, res); } } catch (Exception e) { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("get POST ......................"); out.println(e); out.println("......................"); } }
public static void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) { // res.setContentType("text/html"); // Get the current session object, create one if necessary HttpSession session = req.getSession(); // Increment the hit count for this page. The value is saved // in this client's session under the name "snoop.count". Integer count = (Integer) session.getAttribute("snoop.count"); if (count == null) { count = 1; } else count = count + 1; session.setAttribute("snoop.count", count); out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag()); out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>"); out.println("<BODY><H1>Session Snoop</H1>"); // Display the hit count for this page out.println( "You've visited this page " + count + ((!(count.intValue() != 1)) ? " time." : " times.")); out.println("<P>"); out.println("<H3>Here is your saved session data:</H3>"); Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String name = (String) atts.nextElement(); out.println(name + ": " + session.getAttribute(name) + "<BR>"); } out.println("<H3>Here are some vital stats on your session:</H3>"); out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>"); out.println("New session: " + session.isNew() + "<BR>"); out.println("Timeout: " + session.getMaxInactiveInterval()); out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>"); out.println("Creation time: " + session.getCreationTime()); out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>"); out.println("Last access time: " + session.getLastAccessedTime()); out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>"); out.println( "Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>"); out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>"); out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>"); out.println("<H3>Test URL Rewriting</H3>"); out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>"); out.println("to test that session tracking works via URL"); out.println("rewriting even when cookies aren't supported."); out.println("</BODY></HTML>"); }
/** * 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)"; }
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); String path = request.getRequestURI(); // use routes if present if (this.routes != null) { String route = this.routes.getProperty(path); if (route != null) { path = route; // then we also need to replace the HttpServletRequest.getRequestURI method // request = getRequestWrapper(request, path); } } if (path.endsWith("/")) path += "index"; String source = null; // check for changes first if (this.debug && contextCache.checkForChanges()) { if (this.pageInfoCache != null) this.pageInfoCache.clear(); } ScriptContext context = contextCache.getContext(); try { serve(request, response, context, path, null); } catch (Exception e) { int status = getStatus(e); response.setStatus(status); response.setContentType("text/plain"); System.out.println(e.toString()); if (errorPath != null && status >= 500) { try { serve(request, response, context, errorPath, e); } catch (Exception f) { e.printStackTrace(response.getWriter()); response.getWriter().write("ERROR IN ERROR HANDLER PAGE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); f.printStackTrace(response.getWriter()); } } else if (debug && status == 500) { e.printStackTrace(response.getWriter()); } else if (e instanceof JavaScriptException) { JavaScriptException je = (JavaScriptException) e; response.getWriter().write(je.getValue().toString()); } else { response.getWriter().write(e.getMessage()); } } finally { contextCache.returnContext(context); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] uri = request.getRequestURI().split("/"); if (uri.length < 4) { response.getWriter().print(XavaResources.getString(request, "module_name_missing")); return; } String url = "/naviox/index.jsp?application=" + uri[1] + "&module=" + uri[3]; RequestDispatcher dispatcher = request.getRequestDispatcher(url); Style.setPotalInstance( NaviOXStyle .getInstance()); // We manage style in NaviOX as in the portal case, to override the // style defined in xava.properties and by device dispatcher.forward(request, response); }
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // read the last post id here ....................... String url = req.getRequestURI(); String urlprt[] = url.split("/"); int urlcount = urlprt.length - 1; JSONParser parserPost = new JSONParser(); JSONObject post = null; String id = urlprt[urlcount]; // read the post here ............................. try { if (id != null) { Object objPost = parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json")); post = (JSONObject) objPost; JSONArray msg = (JSONArray) post.get("toapprove"); msg.add(req.getParameter("content")); post.remove("toapprove"); post.put("toapprove", msg); File file = new File("..\\webapps\\Blog\\post\\" + id + ".json"); file.createNewFile(); FileWriter filew = new FileWriter(file); filew.write(post.toJSONString()); filew.flush(); filew.close(); doGet(req, res); } } catch (Exception e) { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("get POST ......................"); out.println(e); out.println("......................"); } }
private void verifyPageToken(HttpServletRequest request) throws CsrfGuardException { HttpSession session = request.getSession(true); @SuppressWarnings("unchecked") Map<String, String> pageTokens = (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY); String tokenFromPages = (pageTokens != null ? pageTokens.get(request.getRequestURI()) : null); String tokenFromSession = (String) session.getAttribute(getSessionKey()); String tokenFromRequest = request.getParameter(getTokenName()); if (tokenFromRequest == null) { /** FAIL: token is missing from the request * */ throw new CsrfGuardException("required token is missing from the request"); } else if (tokenFromPages != null) { if (!tokenFromPages.equals(tokenFromRequest)) { /** FAIL: request does not match page token * */ throw new CsrfGuardException("request token does not match page token"); } } else if (!tokenFromSession.equals(tokenFromRequest)) { /** FAIL: the request token does not match the session token * */ throw new CsrfGuardException("request token does not match session token"); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Locales.setCurrent(request); if (Users.getCurrent() == null) { // for a bug in websphere portal 5.1 with Domino LDAP Users.setCurrent((String) request.getSession().getAttribute("xava.user")); } request.getParameter("application"); // for a bug in websphere 5.1 request.getParameter("module"); // for a bug in websphere 5.1 Tab tab = (Tab) request.getSession().getAttribute("xava_reportTab"); int[] selectedRowsNumber = (int[]) request.getSession().getAttribute("xava_selectedRowsReportTab"); Map[] selectedKeys = (Map[]) request.getSession().getAttribute("xava_selectedKeysReportTab"); int[] selectedRows = getSelectedRows(selectedRowsNumber, selectedKeys, tab); request.getSession().removeAttribute("xava_selectedRowsReportTab"); Integer columnCountLimit = (Integer) request.getSession().getAttribute("xava_columnCountLimitReportTab"); request.getSession().removeAttribute("xava_columnCountLimitReportTab"); setDefaultSchema(request); String user = (String) request.getSession().getAttribute("xava_user"); request.getSession().removeAttribute("xava_user"); Users.setCurrent(user); String uri = request.getRequestURI(); if (uri.endsWith(".pdf")) { InputStream is; JRDataSource ds; Map parameters = new HashMap(); synchronized (tab) { tab.setRequest(request); parameters.put("Title", tab.getTitle()); parameters.put("Organization", getOrganization()); parameters.put("Date", getCurrentDate()); for (String totalProperty : tab.getTotalPropertiesNames()) { parameters.put(totalProperty + "__TOTAL__", getTotal(request, tab, totalProperty)); } TableModel tableModel = getTableModel(request, tab, selectedRows, false, true, null); tableModel.getValueAt(0, 0); if (tableModel.getRowCount() == 0) { generateNoRowsPage(response); return; } is = getReport(request, response, tab, tableModel, columnCountLimit); ds = new JRTableModelDataSource(tableModel); } JasperPrint jprint = JasperFillManager.fillReport(is, parameters, ds); response.setContentType("application/pdf"); response.setHeader( "Content-Disposition", "inline; filename=\"" + getFileName(tab) + ".pdf\""); JasperExportManager.exportReportToPdfStream(jprint, response.getOutputStream()); } else if (uri.endsWith(".csv")) { String csvEncoding = XavaPreferences.getInstance().getCSVEncoding(); if (!Is.emptyString(csvEncoding)) { response.setCharacterEncoding(csvEncoding); } response.setContentType("text/x-csv"); response.setHeader( "Content-Disposition", "inline; filename=\"" + getFileName(tab) + ".csv\""); synchronized (tab) { tab.setRequest(request); response .getWriter() .print( TableModels.toCSV( getTableModel(request, tab, selectedRows, true, false, columnCountLimit))); } } else { throw new ServletException( XavaResources.getString("report_type_not_supported", "", ".pdf .csv")); } } catch (Exception ex) { log.error(ex.getMessage(), ex); throw new ServletException(XavaResources.getString("report_error")); } finally { request.getSession().removeAttribute("xava_reportTab"); } }
public boolean isProtectedPageAndMethod(HttpServletRequest request) { return isProtectedPageAndMethod(request.getRequestURI(), request.getMethod()); }
public void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HttpSession session = req.getSession(true); root = req.getContextPath(); String addButton = req.getParameter("addButton"); try { session = req.getSession(true); if (session.isNew()) { session.invalidate(); res.setContentType("text/html;charset=UTF-8"); PrintWriter out = res.getWriter(); out.println( (new StringBuilder()) .append("<html><HEAD><META HTTP-EQUIV='Refresh' CONTENT='0; URL=") .append(root) .append("/AID'/></HEAD></html>") .toString()); out.close(); } } catch (IllegalStateException e) { res.sendRedirect((new StringBuilder()).append(root).append("/AID").toString()); } String originalQuery = (String) session.getAttribute("query"); if (addButton != null) { String newQueryTerms[] = (String[]) req.getParameterValues("newQueryTerms"); if ((newQueryTerms == null) || (newQueryTerms.length == 0)) { res.sendRedirect( res.encodeURL( root.concat( (new StringBuilder()) .append("/AID?query=") .append(originalQuery.replaceAll("\\s+", "+")) .toString()))); } else { String newQuery = originalQuery.replaceAll("\\s+", "+"); for (int i = 0; i < newQueryTerms.length; i++) { newQuery = (new StringBuilder()) .append(newQuery) .append("+") .append(newQueryTerms[i]) .toString(); } res.sendRedirect( res.encodeURL( root.concat( (new StringBuilder()).append("/AID?query=").append(newQuery).toString()))); } } else { String spellMatrix[] = (String[]) session.getAttribute("retSpellSuggestions"); String termsInQuery[] = (String[]) session.getAttribute("termsInQuery"); String wordnetMatrix[][] = (String[][]) session.getAttribute("retWordnetSynsMatrix"); String synonymMatrix[][] = (String[][]) session.getAttribute("retSynsMatrix"); String onlineSynMatrix[][] = (String[][]) session.getAttribute("onlineSynMatrix"); res.setContentType("text/html;charset=UTF-8"); PrintWriter out = res.getWriter(); out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"); out.println("<html>"); out.println("<head>"); out.println("<title>AID Search interface</title>"); out.println( (new StringBuilder()) .append("<style type='text/css'>@import url(") .append(root) .append("/css/qckcss.css);") .toString()); out.println("</style>"); out.println( (new StringBuilder()) .append("<link REL=\"SHORTCUT ICON\" HREF=\"") .append(root) .append("/images/favicon.ico\">") .toString()); out.println( (new StringBuilder()) .append("<script type=\"text/javascript\" src=\"") .append(root) .append("/javascript/overlib.js\">") .toString()); out.println("<!-- bla -->"); out.println("</script>"); out.println("</head>"); out.println( (new StringBuilder()) .append("<body bgcolor=white background=\"") .append(root) .append("/images/background.gif\">") .toString()); out.println("<div id=\"AIDfp\">"); out.println("<a name=\"top\"/>"); out.println(" <table border=\"0\" width=600>"); out.println("<tr><td colspan=3>"); out.println("<table>"); out.println("\t<tr valign=\"top\" bgcolor=white><td class=\"navtext\">"); out.println("\t<div id=\"navlinks\">"); out.println( (new StringBuilder()) .append("\t\t<img src=\"") .append(root) .append( "/images/top.png\" width=\"709\" height=\"200\" border=\"0\"><!-- bla --> </img>") .toString()); out.println( (new StringBuilder()) .append( "\t\t<div style=\"position: relative;top: -55px;margin-left: 15px;\"><a href=\"") .append(root) .append("/\">Home</a></div>") .toString()); out.println( "\t\t<div style=\"position: relative;top: -71px;margin-left: 180px;\">Concept Finder</div>"); out.println( "\t\t<div style=\"position: relative;top: -87px;margin-left: 410px;\">Search Details</div>"); out.println( "\t\t<div style=\"position: relative;top: -103px;margin-left: 620px;\">History</div>"); out.println("</div></td></tr></table>"); out.println("</td></tr>"); out.println( (new StringBuilder()) .append(" <form name=\"selectionForm\" method=\"get\" action=\"") .append(res.encodeURL(req.getRequestURI())) .append("\">") .toString()); out.println(" <tr>"); out.println(" <td width=33% class='resultItemCenter'>"); if (synonymMatrix != null) { out.println(" Found index-specific syonyms:<br>"); out.println(" <select name='newQueryTerms' multiple>"); for (int i = 0; i < synonymMatrix.length; i++) { for (int j = 0; j < synonymMatrix[i].length; j++) { if (synonymMatrix[i][j] != null) { out.println( (new StringBuilder()) .append(" <option value='") .append(synonymMatrix[i][j]) .append("'>") .append(synonymMatrix[i][j]) .append("</option>") .toString()); } } } out.println(" </select>"); } out.println(" </td>"); out.println(" <td width=33% class='resultItemCenter'>"); if (wordnetMatrix != null) { out.println(" Found Wordnet syonyms:<br>"); out.println(" <select name='newQueryTerms' multiple>"); for (int i = 0; i < wordnetMatrix.length; i++) { for (int j = 0; j < wordnetMatrix[i].length; j++) { if (wordnetMatrix[i][j] != null) { out.println( (new StringBuilder()) .append(" <option value='") .append(wordnetMatrix[i][j]) .append("'>") .append(wordnetMatrix[i][j]) .append("</option>") .toString()); } } } out.println(" </select>"); } out.println(" </td>"); out.println(" <td width=33% class='resultItemCenter'>"); if (onlineSynMatrix != null) { out.println(" Found online acronyms:<br>"); out.println(" <select name='newQueryTerms' multiple>"); for (int i = 0; i < onlineSynMatrix.length; i++) { for (int j = 0; j < onlineSynMatrix[i].length; j++) { if (onlineSynMatrix[i][j] != null) { out.println( (new StringBuilder()) .append(" <option value='") .append(onlineSynMatrix[i][j]) .append("'>") .append(onlineSynMatrix[i][j]) .append("</option>") .toString()); } } } out.println(" </select>"); } out.println(" </td> </tr>"); out.println(" <tr>"); out.println(" <td class='resultItemCenter' width=100% colspan=3>"); out.println(" <hr/>"); out.println(" </td>"); out.println(" </tr>"); out.println(" <tr>"); out.println(" <td class='resultItemCenter' width=100% colspan=3>"); out.println(" <input type=submit name=\"addButton\" value=\"Add\">"); out.println(" </td>"); out.println(" </tr>"); out.println(" </form>"); out.println(" </table>"); out.println("<div id=\"footer\">"); out.println("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\">"); out.println("<tr>"); out.println( (new StringBuilder()) .append("<td width=\"1%\"><img src=\"") .append(root) .append( "/images/footer-leftcurve.gif\" width=\"10\" height=\"31\" border=\"0\"/></td>") .toString()); out.println("<td width=\"98%\" bgcolor=\"#\" class=\"footertext\">"); out.println("<a href=\"#top\">Top</a>"); out.println(" |\t\t"); out.println( (new StringBuilder()) .append("<a href=\"") .append(root) .append("/synonym\">Synonym client</a>") .toString()); out.println(" |\t\t"); out.println("<a href=\"http://www.vl-e.nl\">Vl-e</a>"); out.println("</td>"); out.println( (new StringBuilder()) .append("<td width=\"1%\"><img src=\"") .append(root) .append( "/images/footer-rightcurve.gif\" width=\"10\" height=\"31\" border=\"0\"/></td>") .toString()); out.println("</tr>"); out.println("</table>"); out.println("</div>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); out.close(); } }
public String getTokenValue(HttpServletRequest request) { return getTokenValue(request, request.getRequestURI()); }
private String extractServletPath(HttpServletRequest pReq) { return pReq.getRequestURI().substring(0, pReq.getContextPath().length()); }
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; }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 权限判断 StringBuffer sb = new StringBuffer(); String actionType = null; String queryString = null; String userid = null; String isCanAccess = "1"; HttpServletRequest hrequest = (HttpServletRequest) request; String strContext = hrequest.getContextPath(); if (request instanceof HttpServletRequest) { // 获取用户信息 userid = (String) hrequest.getSession().getAttribute("AuthorizedUserID"); strContext = hrequest.getContextPath(); queryString = hrequest.getQueryString(); // 整个参数串 actionType = hrequest.getParameter("actionType"); // 一般操作 if (actionType == null) { actionType = hrequest.getParameter("formSN"); // 针对查询的操作 if (actionType != null) { actionType = "formSN=" + actionType; } } else { actionType = "actionType=" + actionType; } } if (actionType != null) { // 如果参数不为空,则判断权限,通过存储过程判断 DBConnectionManager dbManager = new DBConnectionManager(); CallableStatement cstmt = null; Connection conn = null; try { conn = dbManager.getConnection(); String query = "{call pkg_security.userAccessFunction(?,?,?,?)}"; cstmt = conn.prepareCall(query); cstmt.registerOutParameter(1, OracleTypes.VARCHAR); cstmt.setString(2, userid); cstmt.setString(3, actionType == null ? null : actionType.trim()); cstmt.setString(4, queryString == null ? null : queryString.trim()); cstmt.execute(); isCanAccess = cstmt.getString(1); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (cstmt != null) { cstmt.close(); } } catch (Exception ex) { if (conn != null) try { conn.close(); } catch (SQLException e1) { e1.printStackTrace(); } } if (conn != null) try { conn.close(); } catch (SQLException e1) { e1.printStackTrace(); } } } // 如果没有权限,定位到提示页面。 if (!isCanAccess.equals("1")) { HttpServletResponse out = (HttpServletResponse) response; out.sendRedirect(strContext + "/common/erroraccess.jsp"); return; } else { // 汉字问题 HttpServletRequest httpRequest = (HttpServletRequest) request; httpRequest.setCharacterEncoding(encoding); // chain.doFilter(request, response); // 压缩传输 HttpServletResponse httpResponse = (HttpServletResponse) response; String uri = httpRequest.getRequestURI(); String transferEncoding = getGZIPEncoding((HttpServletRequest) request); if (transferEncoding == null) { setResponseHeader(httpResponse, uri, transferEncoding); chain.doFilter(request, response); } else { if (!uri.endsWith("dd.xml")) // 不处理的有哪些?????? { chain.doFilter(request, response); } else { System.out.println("FrameworkFilter:: Filter handle dd.xml"); setResponseHeader(httpResponse, uri, transferEncoding); httpResponse.setHeader("Content-Encoding", transferEncoding); GZIPEncodableResponse wrappedResponse = new GZIPEncodableResponse((HttpServletResponse) response); chain.doFilter(request, wrappedResponse); wrappedResponse.flush(); } } } // Pass control on to the next filter // chain.doFilter(request, response); }
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>"); } }
/** * 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(); }
@Override public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (!path.equals(request.getRequestURI())) { return; } response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/plain"); PrintWriter out = null; try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); out = response.getWriter(); Map<String, Endpoint> endpointMap = tracker.getEndpointMap(); Map<String, Long> expirationMap = tracker.getExpirationMap(); out.println("Active sessions:"); out.println(); for (Map.Entry<String, Endpoint> ep : endpointMap.entrySet()) { String key = ep.getKey(); out.print(ep.getKey()); out.print(" => "); out.print(ep.getValue()); Long expiration = expirationMap.get(key); if (expiration == null) { out.println(" (expiration unknown)"); } else { out.print(" (expires "); out.print(df.format(new Date(expiration))); out.println(")"); } } out.println(); out.println("Events:"); out.println(); for (EndpointEvent event : tracker.getEvents()) { out.print(df.format(new Date(event.getTimestamp()))); out.print(" "); out.print(event.getStatus().name()); out.print(" "); out.print(event.getConnectionId()); out.print(" "); out.print(event.getDetails()); out.println(); } } finally { try { if (out != null) { out.close(); } } catch (Throwable ignored) { } } baseRequest.setHandled(true); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; // create input/output dir patterns String contextPath = httpRequest.getContextPath(); if (this.inDirPattern == null) { // NOTE: Have to do this here because the context path is not // available in init(). this.inDirPattern = Pattern.compile("^" + escape(contextPath) + escape(this.inDirName) + "/(.*)"); this.outDirPattern = Pattern.compile("^" + escape(contextPath) + "/help/[a-z]{2}(?:_[A-Z]{2})?/.*"); if (ZimbraLog.webclient.isDebugEnabled()) { ZimbraLog.webclient.debug("### indir pattern: " + this.inDirPattern.pattern()); ZimbraLog.webclient.debug("### outdir pattern: " + this.outDirPattern.pattern()); } } // check to see if we need to redirect this request String requestUri = httpRequest.getRequestURI(); if (this.outDirPattern.matcher(requestUri).matches()) { // allow it to go through chain.doFilter(request, response); return; } // make list of potential locales to check Locale preferredLocale = getLocale(httpRequest); String language = preferredLocale.getLanguage(); String country = preferredLocale.getCountry(); Locale[] locales = {preferredLocale, country != null ? new Locale(language) : null, Locale.US}; if (ZimbraLog.webclient.isDebugEnabled()) { for (Locale locale : locales) { ZimbraLog.webclient.debug("locale: " + locale); } } // find out which version of the requested file exists Locale actualLocale = preferredLocale; Matcher matcher = this.inDirPattern.matcher(requestUri); if (!matcher.matches()) { httpResponse.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Help URL doesn't match input pattern."); return; } if (ZimbraLog.webclient.isDebugEnabled()) { ZimbraLog.webclient.debug("### filename: " + matcher.group(1)); } String filename = decode(matcher.group(1)).replace('/', File.separatorChar); if (ZimbraLog.webclient.isDebugEnabled()) { ZimbraLog.webclient.debug("### filename: " + filename); } File baseDir = new File(this.context.getRealPath("/")); if (ZimbraLog.webclient.isDebugEnabled()) { ZimbraLog.webclient.debug("### basedir: " + baseDir); } for (Locale locale : locales) { if (locale == null) continue; File file = new File( baseDir, this.outDirName.replaceAll("\\{locale\\}", locale.toString()) + File.separatorChar + filename); if (file.exists()) { actualLocale = locale; break; } } // redirect String redirectUrl = contextPath + this.outDirName.replaceAll("\\{locale\\}", actualLocale.toString()) + "/" + filename; if (ZimbraLog.webclient.isDebugEnabled()) { ZimbraLog.webclient.debug("redirecting to: " + redirectUrl); } httpResponse.sendRedirect(redirectUrl); }