List of usage examples for javax.servlet.http HttpServletRequest getLocalPort
public int getLocalPort();
From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java
public String saveNetworkPrivilegedUsersPage() { HttpServletRequest request = (HttpServletRequest) this.getExternalContext().getRequest(); String hostName = request.getLocalName(); int port = request.getLocalPort(); String portStr = ""; if (port != 80) { portStr = ":" + port; }/*from ww w . ja v a2 s . c o m*/ // Needed to send an approval email to approved creators String creatorUrl = "http://" + hostName + portStr + request.getContextPath() + "/faces/site/AddSitePage.xhtml"; privileges.save(creatorUrl); getVDCRenderBean().getFlash().put("successMessage", "Successfully updated network permissions."); tab2 = ""; return "/networkAdmin/NetworkOptionsPage.xhtml?faces-redirect=true&tab=permissions"; }
From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {/*w w w . ja v a2 s . com*/ throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:se.natusoft.osgi.aps.rpchttpextender.servlet.RPCServlet.java
/** * Handles the first page with general information inlcuding protocols and services. * * @param html The HTMLWriter to write to. * @param req The HttpServletRequest.//w ww. j a v a 2 s . c o m * @throws IOException */ private void handleFirstPage(HTMLWriter html, HttpServletRequest req) throws IOException { html.tag("html"); { html.tag("body", "", BG_COLOR); { html.tagc("h1", "ApplicationPlatformServices (APS) Remote service call over HTTP transport provider"); html.tagc("p", "This provides an http transport for simple remote requests to OSGi services that have the \"APS-Externalizable: " + "true\" in their META-INF/MANIFEST.MF. This follows the OSGi extender pattern and makes any registered " + "OSGi services of bundles having the above manifest entry available for remote calls over HTTP. This " + "transport makes use of the aps-external-protocol-extender which exposes services with the above " + "mentioned manifest entry with each service method available as an APSExternallyCallable." + "The aps-ext-protocol-http-transport acts as a mediator between the protocol implementations and " + "aps-external-protocol-extender for requests over HTTP."); html.tagc("p", "<b>Please note</b> that depending on protocol not every service method will be callable. It depends on " + "its arguments and return value. It mostly depends on how well the protocol handles types and can convert " + "between the caller and the service. Also note that bundles can specify \"APS-Externalizable: false\" in their " + "META-INF/MANIFEST.MF. In that case none of the bundles services will be callable this way!"); html.tagc("p", "This does not provide any protocol, only transport! For services " + "to be able to be called at least one protocol is needed. Protocols are provided by providing an " + "implementation of se.natusoft.osgi.aps.api.net.rpc.service.StreamedRPCProtocolService and registering " + "it as an OSGi service. The StreamedRPCProtocolService API provides a protocol name and protocol " + "version getter which is used to identify it. A call to an RPC service looks like this:"); html.text( "<ul><code>http://host:port/apsrpc/<i>protocol</i>/<i>version</i>[/<i>service</i>][/<i>method</i>]</code></ul>"); html.text("<ul>" + "<i>protocol</i>" + "<ul>" + "This is the name of the protocol to use. An implementation of that protocol must of course be available " + "for this to work. If it isn't you will get a 404 back!" + "</ul>" + "</ul>"); html.text("<ul>" + "<i>version</i>" + "<ul>" + "This is the version of the protocol. If this doesn't match any protocols available you will also get a " + "404 back." + "</ul>" + "</ul>"); html.text("<ul>" + "<i>service</i>" + "<ul>" + "This is the service to call. Depending on the protocol you might not need this. But for protocols that " + "only provide method in the stream data like JSONRPC for example, then this is needed. When provided it " + "has to be a fully qualified service interface class name." + "</ul>" + "</ul>"); html.text("<ul>" + "<i>method</i>" + "<ul>" + "This is a method of the service to call. The requirement for this also depends on the protocol. " + "The JSONRPC protocols does not need this since they provide the method in the request. A REST " + "protocol however would need this." + "</ul>" + "</ul>"); html.tagc("h2", "Security"); html.tagc("p", "This help page always require authentication. This is because it register itself with the APSAdminWeb and " + "is available as a tab there and thereby joins in the admin web authentication. For service calls however " + "authentication is only required if you enable it in the configuration (network/rpc-http-transport). " + "There are 2 variants of authentication for services:" + "<ul>" + "<li>http://.../apsrpc/<b>auth:user:password</b>/protocol/...</li>" + "<li>Basic HTTP authentication using header: 'Authorization: Basic {base 64 encoded user:password}'.</li>" + "</ul>"); html.tagc("p", "Note that this is only a transport (over http)! It has nothing to say about protocols which is why the " + "above auth methods are outside of the protocol, only part of this transport. If you make services that you " + "expose this way it is also possible to leave the authentication config at false and provide authentication " + "in your service by using the APSSimpleUserService or something else."); html.tagc("h2", "Found Protocols"); for (StreamedRPCProtocol protocol : this.externalProtocolService.getAllStreamedProtocols()) { html.tagc("h3", protocol.getServiceProtocolName() + " : " + protocol.getServiceProtocolVersion()); html.tagc("p", protocol.getRPCProtocolDescription()); html.tagc("p", "<b>Request URL:</b> http://" + req.getLocalName() + ":" + req.getLocalPort() + "/apsrpc/" + protocol.getServiceProtocolName() + "/" + protocol.getServiceProtocolVersion() + "[/<service>][/<method>]"); String reqContentType = protocol.getRequestContentType(); String respContentType = protocol.getResponseContentType(); if (reqContentType != null && reqContentType.trim().length() > 0) { html.tagc("p", "<b>Request Content-type:</b> " + reqContentType); } if (respContentType != null && respContentType.trim().length() > 0) { html.tagc("p", "<b>Response Content-type:</b> " + respContentType); } } html.tagc("h2", "Found Services"); for (String service : this.externalProtocolService.getAvailableServices()) { ServiceReference sref = this.bundleContext.getServiceReference(service); if (sref != null) { html.tagc("p", "<a href=\"" + service + "\">" + service + "</a> <i>Bundle version:</i> " + sref.getBundle().getVersion() + ", <i>Bundle symbolic name:</i> " + sref.getBundle().getSymbolicName() + ", " + "<i>Bundle id:</i> " + sref.getBundle().getBundleId()); } } } html.tage("body"); } html.tage("html"); }
From source file:org.openqa.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {//from www . j av a 2 s . c o m throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:com.esd.cs.worker.WorkerController.java
/** * ?/*from w w w . j a v a 2s .c o m*/ */ @RequestMapping(value = "/importworker", method = RequestMethod.POST) public ModelAndView importworker(HttpServletRequest request, HttpServletResponse response, HttpSession session) { Integer userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()); // ??????workerTemp? wtService.deleteByUserId(userId); logger.debug("importWorker:{}"); // ? String upload = "upload"; String workerFolder = "worker"; String url = request.getServletContext().getRealPath("/"); String upLoadPath = url + upload + File.separator + workerFolder + File.separator; File uploadPath = new File(url + "upload"); File tempPath = new File(uploadPath + File.separator + workerFolder); // if (!uploadPath.exists()) { logger.debug(upload + " Does not exist,Create " + upload + " Folder"); uploadPath.mkdir(); } if (!tempPath.exists()) { logger.debug(workerFolder + " Does not exist,Create " + workerFolder + " Folder"); tempPath.mkdir(); } // Map<String, String> paramMap = importfile(upLoadPath, request, response); String fileError = paramMap.get("fileError");// ? if (fileError != null) { // ? request.setAttribute("errorInfo", fileError); return new ModelAndView("basicInfo/worker_importInfo"); } // ?? String filePath = paramMap.get("filePath");// Integer companyId = Integer.valueOf(paramMap.get("companyId"));// companyID String year = paramMap.get("year");// AuditParameter auditParameter = auditParameterService.getByYear(year); // ?? // List<Worker> workerErrorList = new ArrayList<Worker>();// ? // List<Worker> workerCorrectList = new ArrayList<Worker>();// ? List<Worker> list = null; if (fileError == null) { try { File f = new File(filePath); // ?excel list = WorkerUtil.parse(f, 0); // ?? workerCount = list.size(); if (list == null || list.size() <= 0) { // excel?? logger.error("importWorkerError:{}", WORDERROR); request.setAttribute("errorInfo", WORDERROR); // ?? return new ModelAndView("basicInfo/worker_importInfo"); } for (int i = 0; i < list.size(); i++) { // WorkerTemp t = new WorkerTemp(); t.setUserId(userId); // false--???? t.setIsOk(false); Worker w = null; // ?? currentCount = i + 1; try { Worker worker = list.get(i); // String workerHandicapCode = worker.getWorkerHandicapCode(); // ?? String workerName = worker.getWorkerName().replace(" ", "");// w = new Worker(); w.setWorkerName(worker.getWorkerName()); w.setWorkerHandicapCode(workerHandicapCode); // t.setWorkerName(workerName); t.setWorkerHandicapCode(workerHandicapCode); // 1.??? if (StringUtils.isEmpty(workerName) || StringUtils.equals(workerName, "null")) { // ? w.setRemark(NAMENULL); // workerErrorList.add(w); t.setRemark(NAMENULL); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, NAMENULL); continue; } // 2.?? if (workerName.length() > 20) { // ? w.setRemark("???"); // workerErrorList.add(w); t.setRemark("???"); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, "???"); continue; } // 3.??? if (StringUtils.isBlank(workerHandicapCode) || StringUtils.equals(workerHandicapCode, "null")) { // ? w.setRemark(LENGTHERROR); // workerErrorList.add(w); t.setRemark(LENGTHERROR); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, LENGTHERROR); continue; } // ?? workerHandicapCode.replace(" ", "");// // 4.?? if (workerHandicapCode.length() < MIN_HANDICAPCODE || workerHandicapCode.length() > MAX_HANDICAPCODE) { // ? w.setRemark(LENGTHERROR); // workerErrorList.add(w); t.setRemark(LENGTHERROR); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, LENGTHERROR); continue; } // 5.???? if (CommonUtil.chineseValid(workerHandicapCode)) { // ? w.setRemark(ILLEGALSTR); // workerErrorList.add(w); t.setRemark(ILLEGALSTR); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, LENGTHERROR); continue; } // 6.20?? String handicapStr = workerHandicapCode.substring(0, 19); if (!handicapStr.matches("\\d+")) { w.setRemark("???20??"); // workerErrorList.add(w); t.setRemark("???20??"); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, TYPEERROR); continue; } // 7. String handicapTypeStr = workerHandicapCode.substring(18, 19); boolean ishandicapType = handicapTypeStr.matches("\\d+");// true,?? // 8.? if (ishandicapType) { int handicapType = Integer.valueOf(handicapTypeStr); if (handicapType > 7 || handicapType == 0) { w.setRemark(TYPEERROR); // workerErrorList.add(w); t.setRemark(TYPEERROR); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, TYPEERROR); continue; } } // 9.?? String handicapLevelStr = workerHandicapCode.substring(19, 20); boolean ishandicapLevel = handicapLevelStr.matches("\\d+");// true,?? if (ishandicapLevel) { int handicapLevel = Integer.valueOf(handicapLevelStr); if (handicapLevel > 4 || handicapLevel == 0) { w.setRemark(LEVELERROR); // workerErrorList.add(w); t.setRemark(LEVELERROR); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, LEVELERROR); continue; } } // 10.? List<String> ageResult = new WorkerUtil().ageVerifi(workerHandicapCode, auditParameter); if (ageResult != null) { String ageErrorInfo = "" + ageResult.get(0).toString() + "," + ageResult.get(1).toString() + "" + ageResult.get(2).toString(); w.setRemark(ageErrorInfo); // workerErrorList.add(w); t.setRemark(ageErrorInfo); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, ageErrorInfo); continue; } // 11.???? List<Map<String, String>> validateList = validateOrganizationCode( workerHandicapCode.substring(0, 18), year); Map<String, String> validateResult = validateList.get(0); logger.debug("LineNumber:{},validataType:{}", i, validateResult.get("type")); // 12.? ? if (StringUtils.equals(validateResult.get("type"), "1")) { // ? String errinfo = "?" + validateList.get(1).get("companyName") + " ?????" + validateList.get(1).get("companyCode"); w.setRemark(errinfo); // workerErrorList.add(w); t.setRemark(errinfo); wtService.save(t); logger.error("impoerWorkerError:{},info:{}", w, errinfo); continue; } // .???? ? ?? if (StringUtils.equals(validateResult.get("type"), "2") || StringUtils.equals(validateResult.get("type"), "3")) { Worker workerUp = new Worker(); workerUp.setWorkerName(worker.getWorkerName()); workerUp.setWorkerHandicapCode(workerHandicapCode); Worker workerCorrect = WorkerUtil.assembly(workerUp); // workerCorrectList.add(workerCorrect); // ??? t.setWorkerName(workerCorrect.getWorkerName()); t.setWorkerHandicapCode(workerCorrect.getWorkerHandicapCode()); t.setIsOk(true); t.setWorkerBirth(workerCorrect.getWorkerBirth()); t.setWorkerBirthYear(workerCorrect.getWorkerBirthYear()); t.setWorkerGender(workerCorrect.getWorkerGender()); t.setWorkerHandicapLevel(workerCorrect.getWorkerHandicapLevel().getId()); t.setWorkerHandicapType(workerCorrect.getWorkerHandicapType().getId()); t.setWorkerIdCard(workerCorrect.getWorkerIdCard()); // , ??, ?id?? if (StringUtils.equals(validateResult.get("type"), "2")) { t.setPreId(Integer.parseInt(validateResult.get("workerId").toString())); } wtService.save(t); continue; } } catch (Exception e) { w.setRemark(""); // workerErrorList.add(w); t.setRemark(""); wtService.save(t); logger.error("impoerWorkerUpError:{}", "false"); } } // ? // ?? List<WorkerTemp> workerErrorList = wtService.getByCheck(false, userId);// ? if (workerErrorList.size() != 0) { String errorFilePath = upLoadPath + companyId + ".xls"; // ?? if (PoiCreateExcel.createExcel(errorFilePath, workerErrorList)) { logger.debug("upLoadErrorListCreateSuccess!"); String destPath = request.getLocalAddr() + ":" + request.getLocalPort() + request.getContextPath(); // ? request.setAttribute("errorFilePath", "http://" + destPath + "/" + upload + "/" + workerFolder + "/" + companyId + ".xls");// } else { logger.error("upLoadErrorListCreateError"); request.setAttribute("errorInfo", CREATEERRORFILE); } } // f.delete(); // int totalLength = wtService.getCountByCheck(null, userId, // null); // int succesLength = wtService.getCountByCheck(true, userId, // null); // int errorLength = totalLength - succesLength; int totalLength = 0; int succesLength = 0; int errorLength = 0; // ?? if (workerErrorList != null) { errorLength = workerErrorList.size(); } // // ?? if (list != null) { totalLength = list.size(); succesLength = totalLength - errorLength; } request.setAttribute("totalLength", totalLength);// ? request.setAttribute("errorLength", errorLength);// ? request.setAttribute("succesLength", succesLength);// ?? // request.setAttribute("workerCorrectList", workerCorrectList); // //?, ??? // // ?? request.setAttribute("errorInfo", "null");// ?? request.setAttribute("companyId", companyId);// ??iD request.setAttribute("year", year);// logger.debug("totalLength:{}", totalLength);// ? logger.debug("errorLength:{}", errorLength);// ? logger.debug("succesLength:{}", succesLength);// ?? // ? list.clear(); list = null; workerErrorList.clear();// ? workerErrorList = null; } catch (IllegalStateException e) { e.printStackTrace(); logger.error("importWorkerError:{}", e.getMessage()); } catch (IOException e) { logger.error("importWorkerError:{}", e.getMessage()); } } // ?? return new ModelAndView("basicInfo/worker_importInfo"); }