List of usage examples for javax.servlet ServletRequest getAttribute
public Object getAttribute(String name);
Object
, or null
if no attribute of the given name exists. From source file:org.codice.ddf.pax.web.jetty.JettyAuthenticator.java
@Override public Authentication validateRequest(ServletRequest servletRequest, ServletResponse servletResponse, boolean mandatory) throws ServerAuthException { TreeSet<ServiceReference<SecurityFilter>> sortedSecurityFilterServiceReferences = null; final BundleContext bundleContext = getContext(); if (bundleContext == null) { throw new ServerAuthException( "Unable to get BundleContext. No servlet SecurityFilters can be applied. Blocking the request processing."); }//from ww w . j a v a 2 s .c om try { sortedSecurityFilterServiceReferences = new TreeSet<>( bundleContext.getServiceReferences(SecurityFilter.class, null)); } catch (InvalidSyntaxException ise) { LOGGER.debug("Should never get this exception as there is no filter being passed."); } if (!CollectionUtils.isEmpty(sortedSecurityFilterServiceReferences)) { LOGGER.debug("Found {} filter(s), now filtering...", sortedSecurityFilterServiceReferences.size()); final ProxyFilterChain chain = new ProxyFilterChain(); // Insert the SecurityFilters into the chain one at a time (from lowest service ranking // to highest service ranking). The SecurityFilter with the highest service-ranking will // end up at index 0 in the FilterChain, which means that the SecurityFilters will be // run in order of highest to lowest service ranking. for (ServiceReference<SecurityFilter> securityFilterServiceReference : sortedSecurityFilterServiceReferences) { final SecurityFilter securityFilter = bundleContext.getService(securityFilterServiceReference); if (!hasBeenInitialized(securityFilterServiceReference, bundleContext)) { initializeSecurityFilter(bundleContext, securityFilterServiceReference, securityFilter); } chain.addSecurityFilter(securityFilter); } try { chain.doFilter(servletRequest, servletResponse); } catch (IOException e) { throw new ServerAuthException( "Unable to process security filter. Blocking the request processing."); } catch (AuthenticationChallengeException e) { return new Authentication.Challenge() { }; } catch (AuthenticationException e) { return new Authentication.Failure() { }; } } else { LOGGER.debug("Did not find any SecurityFilters. Send auth failure..."); return new Authentication.Failure() { }; } Subject subject = (Subject) servletRequest.getAttribute(SecurityConstants.SECURITY_SUBJECT); UserIdentity userIdentity = new JettyUserIdentity(getSecuritySubject(subject)); return new JettyAuthenticatedUser(userIdentity); }
From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java
public void test_ServletContextHelper13() throws Exception { BundleContext bundleContext = getBundleContext(); Bundle bundle = bundleContext.getBundle(); // test that the helper handlesecurity is called before the filter by setting an attribute on the request ServletContextHelper servletContextHelper = new ServletContextHelper(bundle) { @Override/*from ww w . j a v a2 s . co m*/ public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setAttribute(getName(), Boolean.TRUE); return super.handleSecurity(request, response); } }; Filter f1 = new Filter() { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getAttribute(getName()) == Boolean.TRUE) { request.setAttribute(getName() + ".fromFilter", Boolean.TRUE); } chain.doFilter(request, response); } @Override public void destroy() { } }; Servlet s1 = new HttpServlet() { private static final long serialVersionUID = 1L; @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.getWriter().print(req.getAttribute(getName() + ".fromFilter")); } }; Collection<ServiceRegistration<?>> registrations = new ArrayList<ServiceRegistration<?>>(); try { Dictionary<String, String> contextProps = new Hashtable<String, String>(); contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME, "a"); contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH, "/"); registrations.add( bundleContext.registerService(ServletContextHelper.class, servletContextHelper, contextProps)); Dictionary<String, String> filterProps = new Hashtable<String, String>(); filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN, "/*"); filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=a)"); registrations.add(bundleContext.registerService(Filter.class, f1, filterProps)); Dictionary<String, String> servletProps = new Hashtable<String, String>(); servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S1"); servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/s1"); servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=a)"); registrations.add(bundleContext.registerService(Servlet.class, s1, servletProps)); String actual = requestAdvisor.request("s1"); Assert.assertEquals(Boolean.TRUE.toString(), actual); } finally { for (ServiceRegistration<?> registration : registrations) { registration.unregister(); } } }
From source file:esg.node.filters.AccessLoggingFilter.java
@SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return;/*from w w w .j a va2s .co m*/ int id = -1; //Record identifying tuple String userID = null; String email = null; String url = null; String fileID = null; String remoteAddress = null; String userAgent = null; long dateFetched = 0L; long batchUpdateTime = 0L; boolean hasNoBackingFile = false; //(note: serviceName defined in global scope) //firewall off any errors so that nothing stops the show... try { log.debug("accessLogging DAO -> " + accessLoggingDAO); if (accessLoggingDAO != null) { //This filter should only appy to specific requests //in particular requests for data files (*.nc) HttpServletRequest req = (HttpServletRequest) request; url = req.getRequestURL().toString().trim(); System.out.println("Requested URL: [" + url + "]"); //Don't need this anymore... but too much of a pain at the moment to change //Remember to change the filter xml entry file in the installer //filters/esg-access-logging-filter b/filters/esg-access-logging-filter Matcher exemptFilesMatcher = exemptUrlPattern.matcher(url); if (exemptFilesMatcher.matches()) { System.out.println( "I am not logging requested file with this extension..., punting on: [" + url + "]"); chain.doFilter(request, response); return; } Matcher exemptServiceMatcher = exemptServicePattern.matcher(url); if (exemptServiceMatcher.matches()) { System.out.println( "I am not logging this, it is an exempt service..., punting on: [" + url + "]"); chain.doFilter(request, response); return; } Matcher allowedFilesMatcher = urlExtensionPattern.matcher(url); if (!allowedFilesMatcher.matches()) { System.out.println("This is not an url that we are interested in logging: [" + url + "]"); chain.doFilter(request, response); return; } // only proceed if the request has been authorized final Boolean requestIsAuthorized = (Boolean) request.getAttribute(AUTHORIZATION_REQUEST_ATTRIBUTE); log.debug("AUTHORIZATION_REQUEST_ATTRIBUTE=" + requestIsAuthorized); if (requestIsAuthorized == null || requestIsAuthorized == false) { System.out.println( "**UnAuthorized Request, punting on: " + req.getRequestURL().toString().trim()); chain.doFilter(request, response); return; } System.out.println("Executing filter on: " + url); //------------------------------------------------------------------------------------------ //For Token authentication there is a Validation Map present with user and email information //------------------------------------------------------------------------------------------ Map<String, String> validationMap = (Map<String, String>) req.getAttribute("validationMap"); if (validationMap != null) { userID = validationMap.get("user"); email = validationMap.get("email"); //Want to make sure that any snooping filters //behind this one does not have access to this //information (posted by the //authorizationTokenValidationFilter, which should //immediately preceed this one). This is in //effort to limit information exposure the //best we can. req.removeAttribute("validationMap"); } else { log.warn("Validation Map is [" + validationMap + "] - (not a token based request)"); } //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ //For TokenLESS authentication the userid information is in a parameter called "esg.openid" //------------------------------------------------------------------------------------------ if (userID == null || userID.isEmpty()) { userID = ((req.getAttribute("esg.openid") == null) ? "<no-id>" : req.getAttribute("esg.openid").toString()); if (userID == null || userID.isEmpty()) { log.warn( "This request is apparently not a \"tokenless\" request either - no openid attribute!!!!!"); } log.warn("AccessLoggingFilter - Tokenless: UserID = [" + userID + "]"); } //------------------------------------------------------------------------------------------ fileID = "0A"; remoteAddress = req.getRemoteAddr(); userAgent = (String) req.getAttribute("userAgent"); dateFetched = System.currentTimeMillis() / 1000; batchUpdateTime = dateFetched; //For the life of my I am not sure why this is there, something from the gridftp metrics collection. -gmb id = accessLoggingDAO.logIngressInfo(userID, email, url, fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched); System.out.println("myID: [" + id + "] = accessLoggingDAO.logIngressInfo(userID: [" + userID + "], email, url: [" + url + "], fileID, remoteAddress, userAgent, serviceName, batchUpdateTime, dateFetched)"); } else { log.error("DAO is null :[" + accessLoggingDAO + "]"); HttpServletResponse resp = (HttpServletResponse) response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid State Of ESG Access Logging Filter: DAO=[" + accessLoggingDAO + "]"); } } catch (Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse) response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter"); } try { ByteCountListener byteCountListener = new ByteCountListener() { int myID = -1; long duration = -1; long startTime = -1; long dataSize = -1; long byteCount = -1; boolean success = false; public void setRecordID(int id) { this.myID = id; } public void setStartTime(long startTime) { this.startTime = startTime; } public void setDataSizeBytes(long dataSize) { this.dataSize = dataSize; } //This callback method should get called by the ByteCountingResponseStream when it is *closed* public void setByteCount(long xferSize) { byteCount = xferSize; System.out.println("**** setByteCount(" + xferSize + ")"); if ((AccessLoggingFilter.this.accessLoggingDAO != null) && (myID > 0)) { if (dataSize == xferSize) { success = true; } duration = System.currentTimeMillis() - startTime; System.out.println("AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID: [" + myID + "], success: [" + success + "], duration: [" + duration + "]ms, dataSize [" + dataSize + "], xferSize: [" + xferSize + "] );"); AccessLoggingFilter.this.accessLoggingDAO.logEgressInfo(myID, success, duration, dataSize, xferSize); } } public long getByteCount() { return byteCount; } }; byteCountListener.setRecordID(id); byteCountListener.setDataSizeBytes(resolveUrlToFile(url).length()); byteCountListener.setStartTime(System.currentTimeMillis()); AccessLoggingResponseWrapper accessLoggingResponseWrapper = new AccessLoggingResponseWrapper( (HttpServletResponse) response, byteCountListener); chain.doFilter(request, accessLoggingResponseWrapper); } catch (Throwable t) { log.error(t); HttpServletResponse resp = (HttpServletResponse) response; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Caught unforseen Exception in ESG Access Logging Filter (url may not be resolvable to an exisiting file) " + t.getMessage()); } }
From source file:ca.uhn.fhir.rest.server.interceptor.ResponseHighlighterInterceptor.java
private void streamResponse(RequestDetails theRequestDetails, HttpServletResponse theServletResponse, IBaseResource resource, ServletRequest theServletRequest) { IParser p;//from ww w.j a v a2s. c om Map<String, String[]> parameters = theRequestDetails.getParameters(); if (parameters.containsKey(Constants.PARAM_FORMAT)) { p = RestfulServerUtils.getNewParser(theRequestDetails.getServer().getFhirContext(), theRequestDetails); } else { EncodingEnum defaultResponseEncoding = theRequestDetails.getServer().getDefaultResponseEncoding(); p = defaultResponseEncoding.newParser(theRequestDetails.getServer().getFhirContext()); RestfulServerUtils.configureResponseParser(theRequestDetails, p); } // This interceptor defaults to pretty printing unless the user // has specifically requested us not to boolean prettyPrintResponse = true; String[] prettyParams = parameters.get(Constants.PARAM_PRETTY); if (prettyParams != null && prettyParams.length > 0) { if (Constants.PARAM_PRETTY_VALUE_FALSE.equals(prettyParams[0])) { prettyPrintResponse = false; } } if (prettyPrintResponse) { p.setPrettyPrint(prettyPrintResponse); } EncodingEnum encoding = p.getEncoding(); String encoded = p.encodeResourceToString(resource); theServletResponse.setContentType(Constants.CT_HTML_WITH_UTF8); StringBuilder b = new StringBuilder(); b.append("<html lang=\"en\">\n"); b.append(" <head>\n"); b.append(" <meta charset=\"utf-8\" />\n"); b.append(" <style>\n"); b.append(".hlQuot {\n"); b.append(" color: #88F;\n"); b.append("}\n"); b.append(".hlAttr {\n"); b.append(" color: #888;\n"); b.append("}\n"); b.append(".hlTagName {\n"); b.append(" color: #006699;\n"); b.append("}\n"); b.append(".hlControl {\n"); b.append(" color: #660000;\n"); b.append("}\n"); b.append(".hlText {\n"); b.append(" color: #000000;\n"); b.append("}\n"); b.append(".hlUrlBase {\n"); b.append("}"); b.append(".headersDiv {\n"); b.append(" background: #EEE;"); b.append("}"); b.append(".headerName {\n"); b.append(" color: #888;\n"); b.append(" font-family: monospace;\n"); b.append("}"); b.append(".headerValue {\n"); b.append(" color: #88F;\n"); b.append(" font-family: monospace;\n"); b.append("}"); b.append("BODY {\n"); b.append(" font-family: Arial;\n"); b.append("}"); b.append(" </style>\n"); b.append(" </head>\n"); b.append("\n"); b.append(" <body>"); b.append("<p>"); b.append("This result is being rendered in HTML for easy viewing. "); b.append("You may access this content as "); b.append("<a href=\""); b.append(createLinkHref(parameters, Constants.FORMAT_JSON)); b.append("\">Raw JSON</a> or "); b.append("<a href=\""); b.append(createLinkHref(parameters, Constants.FORMAT_XML)); b.append("\">Raw XML</a>, "); b.append(" or view this content in "); b.append("<a href=\""); b.append(createLinkHref(parameters, Constants.FORMATS_HTML_JSON)); b.append("\">HTML JSON</a> "); b.append("or "); b.append("<a href=\""); b.append(createLinkHref(parameters, Constants.FORMATS_HTML_XML)); b.append("\">HTML XML</a>."); Date startTime = (Date) theServletRequest.getAttribute(RestfulServer.REQUEST_START_TIME); if (startTime != null) { long time = System.currentTimeMillis() - startTime.getTime(); b.append(" Response generated in "); b.append(time); b.append("ms."); } b.append("</p>"); b.append("\n"); // if (isEncodeHeaders()) { // b.append("<h1>Request Headers</h1>"); // b.append("<div class=\"headersDiv\">"); // for (int next : theRequestDetails.get) // b.append("</div>"); // b.append("<h1>Response Headers</h1>"); // b.append("<div class=\"headersDiv\">"); // b.append("</div>"); // b.append("<h1>Response Body</h1>"); // } b.append("<pre>"); b.append(format(encoded, encoding)); b.append("</pre>"); b.append(" </body>"); b.append("</html>"); //@formatter:off String out = b.toString(); //@formatter:on try { theServletResponse.getWriter().append(out); theServletResponse.getWriter().close(); } catch (IOException e) { throw new InternalErrorException(e); } }
From source file:de.innovationgate.wgpublisher.filter.WGAFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { WGARequestInformation info = new WGARequestInformation(); try {// w ww .jav a2 s .co m info.setStartTime(System.currentTimeMillis()); info.setThread(Thread.currentThread()); request.setAttribute(WGARequestInformation.REQUEST_ATTRIBUTENAME, info); _wgaFilterChain.init(request, chain); _currentRequests.put(request, info); // F000037B2 if (_core.getCharacterEncoding() != null) { request.setCharacterEncoding(_core.getCharacterEncoding()); // B000041DA response.setCharacterEncoding(_core.getCharacterEncoding()); } // add/ delete jvmRoute String lbRoute = _core.getClusterService().getLBRoute(); if (lbRoute != null && !lbRoute.trim().equals("")) { WGCookie jvmRouteCookie = new WGCookie(COOKIE_NAME_LBROUTE, lbRoute); jvmRouteCookie.setPath("/"); jvmRouteCookie.setMaxAge(-1); jvmRouteCookie.addCookieHeader((HttpServletResponse) response); } else { Cookie cookie = getCookie((HttpServletRequest) request, COOKIE_NAME_LBROUTE); if (cookie != null) { WGCookie jvmRouteCookie = WGCookie.from(cookie); jvmRouteCookie.setMaxAge(0); jvmRouteCookie.addCookieHeader((HttpServletResponse) response); } } RequestWrapper wrappedRequest = createRequestWrapper(response, (HttpServletRequest) request); /* * #00005078: don't store original URL. Store converted URL instead. * Will be used in WGA.urlBuilder() and other sources */ request.setAttribute(REQATTRIB_ORIGINAL_URL, wrappedRequest.getRequestURL().toString()); request.setAttribute(REQATTRIB_ORIGINAL_URI, wrappedRequest.getRequestURI()); request.setAttribute(REQATTRIB_ORIGINAL_QUERYSTRING, wrappedRequest.getQueryString()); FinalCharacterEncodingResponseWrapper wrappedResponse = createResponseWrapper(response, wrappedRequest); _holdRequestsLock.readLock().lock(); try { _wgaFilterChain.doFilter(wrappedRequest, wrappedResponse); } finally { _holdRequestsLock.readLock().unlock(); } info.setStatusCode(wrappedResponse.getStatusCode()); info.setStatusMessage(wrappedResponse.getStatusMessage()); AbstractWGAHttpSessionManager sessionManager = _core.getHttpSessionManager(); if (sessionManager != null) { sessionManager.requestFinished(wrappedRequest, wrappedResponse); } } catch (ServletException e) { info.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); info.setStatusMessage(e.getMessage()); _core.getLog().error("Internal Server Error.", e); throw e; } finally { info.setEndTime(System.currentTimeMillis()); try { WGALoggerWrapper logger = _core.getAccessLogger(); if (logger != null) { logger.logRequest(request); } } catch (Exception e) { _core.getLog().error("Unable to log request.", e); } WGFactory.getInstance().closeSessions(); if (!Boolean.TRUE.equals(request.getAttribute(WGPDeployer.REQATTRIB_TML_DEPLOYED)) && info.getEndTime() > info.getStartTime() + REQUEST_LENGTH_NOTIFICATION_THRESHOLD) { String uri = ((HttpServletRequest) request).getRequestURI(); Problem.Vars vars = Problem.var("reqinfo", info) .var("completeurl", ((HttpServletRequest) request).getRequestURL().toString()) .var("host", ((HttpServletRequest) request).getServerName()).var("uri", uri); String problemKey = "requestProblem.longRequest#" + uri; if (info.getDatabase() != null) { _core.getProblemRegistry() .addProblem(Problem.create(new FilterRequestOccasion(), new DatabaseScope(info.getDatabase().getDbReference()), problemKey, ProblemSeverity.LOW, vars)); } else { _core.getProblemRegistry().addProblem( Problem.create(new FilterRequestOccasion(), problemKey, ProblemSeverity.LOW, vars)); } } // close opened lucene-resultsets LuceneManager luceneManager = _core.getLuceneManager(); if (luceneManager != null) { luceneManager.closeOpenedResultSets(); } _currentRequests.remove(request); } }
From source file:org.ms123.common.jetty.LoginFilter.java
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { long before = System.currentTimeMillis(); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String pathInfo = request.getPathInfo(); infob("\n\n<==========================================> "); info("doFilter -> " + pathInfo); infob("date: " + new Date()); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); debug("\t" + headerName + " = " + request.getHeader(headerName)); }// ww w .j av a 2s . co m if (pathInfo == null) { info("==== NOK:pathInfo is null"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); infob("<##############################################\n\n"); return; } String[] arr = pathInfo.split("/"); String namespace = null; if (arr.length < 2) { namespace = "RPC"; } else { if (arr[1].equals("repo")) { namespace = arr[2]; } else { namespace = arr[1]; } } for (int i = 0; i < arr.length; i++) { debug("\tpathinfo[" + i + "]:" + arr[i]); } debug("\tNamespace:" + namespace); if (pathInfo.indexOf("/checkcredentials") != -1) { String cred = request.getParameter("credentials"); if (checkCredentials(namespace, cred, true)) { response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } infob("<##############################################\n\n"); return; } String auth = request.getHeader("Authorization"); debug("auth:" + auth); String credentials = null; if (auth != null || request.getParameter("credentials") != null) { String a = null; if (auth != null && auth.toLowerCase().startsWith("basic ")) { a = auth.trim().split(" ")[1]; } else { a = request.getParameter("credentials"); } credentials = Base64.decode(a); int ind = credentials.indexOf(":"); if (ind != -1) { String username = credentials.substring(0, ind); req.setAttribute(USERNAME, username); } } String firstSegment = arr[1]; String method = request.getMethod(); boolean isStaticResource = false; boolean ok = false; if (method != null && "get".equals(method.toLowerCase())) { if (arr.length > 3 && "sw".equals(arr[1]) && "website".equals(arr[3])) { ok = true; } else if ("sw".equals(firstSegment) || "repo".equals(firstSegment)) { if (isStaticResource(pathInfo)) { ok = true; isStaticResource = true; } } else if (pathInfo.equals("/robots.txt")) { ok = true; } else if (pathInfo.startsWith("/openfire")) { ok = true; } else if (pathInfo.startsWith("/sw/common") || pathInfo.startsWith("/sw/website") || pathInfo.startsWith("/sw/legacy") || pathInfo.startsWith("/sw/resource")) { ok = true; } } else if (request.getHeader("Origin") != null && method != null && "options".equals(method.toLowerCase())) { ok = true; } if (request.getParameter("rpc") != null || request.getRequestURI().startsWith("/rpc")) { ok = false; } if (request.getParameter("ws") != null || request.getRequestURI().startsWith("/ws")) { ok = false; } Map<String, Object> accessRule = null; if (isStaticResource && isRepoRequest(pathInfo)) { List<Map<String, Object>> rules = getAccessRules(namespace); accessRule = getMatchingAccessRule(namespace, pathInfo, rules); if (accessRule != null) { ok = false; } } info(pathInfo + ";" + credentials + "/ok:" + ok + "/accessRule:" + accessRule); if (ok || checkCredentials(namespace, credentials, false)) { if (accessRule != null) { String username = (String) req.getAttribute(USERNAME); if (!m_permissionService.isFileAccesPermitted(username, (List) accessRule.get(PermissionService.PERMITTED_USERS), (List) accessRule.get(PermissionService.PERMITTED_ROLES))) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } } info(">>>> OK," + Thread.currentThread().getName()); RequestMapper rm = new RequestMapper(request); ThreadContext.loadThreadContext(rm, response); info(request.getPathInfo() + "|" + request.getMethod() + "|Uri:" + request.getRequestURI()); info(request.getRequestURL() + "|Url:" + request.getServletPath() + "|QS:" + request.getQueryString()); chain.doFilter(rm, response); info(">>>> End FILTER:" + ThreadContext.getThreadContext().get(ThreadContext.SESSION_MANAGER) + "/" + new Date().getTime()); Date startTime = ThreadContext.getThreadContext().getStartTime(); ThreadContext.getThreadContext().finalize(null); ThreadContext.getThreadContext().remove(); displayInfo("Finish", startTime); } else { info("==== NOK"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } infob("<##############################################\n\n"); }
From source file:org.commoncrawl.service.listcrawler.MultiPartFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) *//*from w w w . ja v a 2 s .c o m*/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { LOG.info("Hit doFilter"); HttpServletRequest srequest = (HttpServletRequest) request; if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) { LOG.info(srequest.toString()); LOG.info("Rejecting. Invalid mime type:" + srequest.getContentType()); chain.doFilter(request, response); return; } LOG.info("OK Looks Good So Far"); BufferedInputStream in = new BufferedInputStream(request.getInputStream()); String content_type = srequest.getContentType(); // TODO - handle encodings String boundary = "--" + value(content_type.substring(content_type.indexOf("boundary="))); byte[] byteBoundary = (boundary + "--").getBytes(StringUtil.__ISO_8859_1); MultiMap params = new MultiMap(); try { // Get first boundary byte[] bytes = TypeUtil.readLine(in); String line = bytes == null ? null : new String(bytes, "UTF-8"); if (line == null || !line.equals(boundary)) { throw new IOException("Missing initial multi part boundary"); } // Read each part boolean lastPart = false; String content_disposition = null; String file_content_type = null; while (!lastPart) { while (true) { bytes = TypeUtil.readLine(in); // If blank line, end of part headers if (bytes == null || bytes.length == 0) break; line = new String(bytes, "UTF-8"); // place part header key and value in map int c = line.indexOf(':', 0); if (c > 0) { String key = line.substring(0, c).trim().toLowerCase(); String value = line.substring(c + 1, line.length()).trim(); if (key.equals("content-disposition")) content_disposition = value; else if (key.equals("content-type")) file_content_type = value; } } // Extract content-disposition boolean form_data = false; if (content_disposition == null) { throw new IOException("Missing content-disposition"); } StringTokenizer tok = new StringTokenizer(content_disposition, ";"); String name = null; String filename = null; while (tok.hasMoreTokens()) { String t = tok.nextToken().trim(); String tl = t.toLowerCase(); if (t.startsWith("form-data")) form_data = true; else if (tl.startsWith("name=")) name = value(t); else if (tl.startsWith("filename=")) filename = value(t); } // Check disposition if (!form_data) { continue; } if (name == null || name.length() == 0) { continue; } OutputStream out = null; File file = null; try { if (filename != null && filename.length() > 0) { file = File.createTempFile("MultiPart", "", tempdir); LOG.info("Got FileName:" + filename + " Creating Temp File:" + file); out = new FileOutputStream(file); UploadFileData uploadData = new UploadFileData(); uploadData.fieldName = name; uploadData.incomingFile = file; uploadData.incomingFilename = filename; uploadData.incomingContentType = file_content_type; request.setAttribute(name, uploadData); params.put(name, filename); if (_deleteFiles) { //file.deleteOnExit(); ArrayList<UploadFileData> files = (ArrayList<UploadFileData>) request .getAttribute(FILES); if (files == null) { files = new ArrayList<UploadFileData>(); request.setAttribute(FILES, files); } files.add(uploadData); } } else out = new ByteArrayOutputStream(); int state = -2; int c; boolean cr = false; boolean lf = false; // loop for all lines` while (true) { int b = 0; while ((c = (state != -2) ? state : in.read()) != -1) { state = -2; // look for CR and/or LF if (c == 13 || c == 10) { if (c == 13) state = in.read(); break; } // look for boundary if (b >= 0 && b < byteBoundary.length && c == byteBoundary[b]) b++; else { // this is not a boundary if (cr) out.write(13); if (lf) out.write(10); cr = lf = false; if (b > 0) out.write(byteBoundary, 0, b); b = -1; out.write(c); } } // check partial boundary if ((b > 0 && b < byteBoundary.length - 2) || (b == byteBoundary.length - 1)) { if (cr) out.write(13); if (lf) out.write(10); cr = lf = false; out.write(byteBoundary, 0, b); b = -1; } // boundary match if (b > 0 || c == -1) { if (b == byteBoundary.length) lastPart = true; if (state == 10) state = -2; break; } // handle CR LF if (cr) out.write(13); if (lf) out.write(10); cr = (c == 13); lf = (c == 10 || state == 10); if (state == 10) state = -2; } } finally { if (out != null) { out.close(); } } if (file == null) { bytes = ((ByteArrayOutputStream) out).toByteArray(); params.add(name, bytes); } } // handle request chain.doFilter(new Wrapper(srequest, params), response); } catch (IOException e) { LOG.error("###Exception In Multipart:" + CCStringUtils.stringifyException(e)); throw e; } finally { LOG.info("Deleting Files Here"); deleteFiles(request); } }