List of usage examples for javax.servlet.http HttpServletResponse getStatus
public int getStatus();
From source file:ge.taxistgela.servlet.RegistrationServlet.java
public void registerDriver(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!verify(request, response)) return;/* w ww.j a v a2s . c o m*/ DriverManagerAPI driverManager = (DriverManagerAPI) request.getServletContext() .getAttribute(DriverManagerAPI.class.getName()); CompanyManagerAPI companyManager = (CompanyManagerAPI) request.getServletContext() .getAttribute(CompanyManagerAPI.class.getName()); DriverPreference driverPreference = new DriverPreference(-1, 0.1, 0.0); ErrorCode code = driverManager.insertDriverPreference(driverPreference); if (code.errorAccrued()) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } Car car = new Car(RandomStringUtils.randomAlphanumeric(7), "Untitled", 1900, false, 0); code = driverManager.insertCar(car); if (code.errorAccrued()) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } Integer companyID = null; if (request.getParameter("drivercompanyCode") != "") { companyID = companyManager.getCompanyIDByCode(request.getParameter("drivercompanyCode")); if (companyID == null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } Driver driver = new Driver(-1, request.getParameter("driverpersonalID"), request.getParameter("driveremail"), request.getParameter("driverpassword"), null, request.getParameter("driverfirstName"), request.getParameter("driverlastName"), getGender(request.getParameter("drivergender")), request.getParameter("driverphoneNumber"), car, filterSocialID(request.getParameter("driverfacebookId")), filterSocialID(request.getParameter("drivergoogleplusId")), 5.0, driverPreference, false, false, false); registerSuper(driverManager, driver, request, response); if (response.getStatus() == HttpServletResponse.SC_CREATED) { Company company = (Company) companyManager.getByID(companyID); driver = (Driver) driverManager.getByEmail(driver.getEmail()); if (company != null && driver != null) { EmailSender.verifyCompany(driver, company); } } }
From source file:com.groupon.odo.Proxy.java
/** * Log modified request/*from w w w. j a v a 2 s . c o m*/ * * @param httpMethodProxyRequest * @param httpServletResponse * @param history */ private void logRequestHistory(HttpMethod httpMethodProxyRequest, HttpServletResponse httpServletResponse, History history) { try { if (requestInformation.get().handle && requestInformation.get().client.getIsActive()) { logger.info("Storing history"); String createdDate; SimpleDateFormat sdf = new SimpleDateFormat(); sdf.setTimeZone(new SimpleTimeZone(0, "GMT")); sdf.applyPattern("dd MMM yyyy HH:mm:ss"); createdDate = sdf.format(new Date()) + " GMT"; history.setCreatedAt(createdDate); history.setRequestURL(HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString())); history.setRequestParams(httpMethodProxyRequest.getQueryString() == null ? "" : httpMethodProxyRequest.getQueryString()); history.setRequestHeaders(HttpUtilities.getHeaders(httpMethodProxyRequest)); history.setResponseHeaders(HttpUtilities.getHeaders(httpServletResponse)); history.setResponseCode(Integer.toString(httpServletResponse.getStatus())); history.setResponseContentType(httpServletResponse.getContentType()); history.setResponseData(requestInformation.get().outputString); HistoryService.getInstance().addHistory(history); logger.info("Done storing"); } } catch (URIException e) { e.printStackTrace(); } }
From source file:com.ethercamp.harmony.web.filter.JsonRpcUsageFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if ((request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; // don't count alias as it redirects here final boolean isJsonRpcUrl = AppConst.JSON_RPC_PATH.equals(httpRequest.getRequestURI()); if (isJsonRpcUrl && httpRequest.getMethod().equalsIgnoreCase("POST")) { try { final ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest( httpRequest);//from w ww. j a v a 2 s . co m final String body = IOUtils.toString(wrappedRequest.getReader()); wrappedRequest.resetInputStream(); if (response.getCharacterEncoding() == null) { response.setCharacterEncoding("UTF-8"); } final HttpServletResponseCopier responseCopier = new HttpServletResponseCopier(httpResponse); try { chain.doFilter(wrappedRequest, responseCopier); responseCopier.flushBuffer(); } finally { // read response for stats and log final byte[] copy = responseCopier.getCopy(); final String responseText = new String(copy, response.getCharacterEncoding()); final JsonNode json = mapper.readTree(body); final JsonNode responseJson = mapper.readTree(responseText); if (json.isArray()) { for (int i = 0; i < json.size(); i++) { notifyInvocation(json.get(i), responseJson.get(i)); } } else { notifyInvocation(json, responseJson); } // According to spec, JSON-RPC 2 should return status 200 in case of error if (httpResponse.getStatus() == 500) { httpResponse.setStatus(200); } } } catch (IOException e) { log.error("Error parsing JSON-RPC request", e); } } else { chain.doFilter(request, response); } } else { throw new RuntimeException("JsonRpcUsageFilter supports only HTTP requests."); } }
From source file:org.structr.web.auth.HttpAuthenticator.java
/** * This method checks all configured external authentication services. * /*from w w w. j a va 2s. co m*/ * @param request * @param response * @return */ protected static Principal checkExternalAuthentication(final HttpServletRequest request, final HttpServletResponse response) { String path = PathHelper.clean(request.getPathInfo()); String[] uriParts = PathHelper.getParts(path); logger.log(Level.FINE, "Checking external authentication ..."); if (uriParts == null || uriParts.length != 3 || !("oauth".equals(uriParts[0]))) { logger.log(Level.FINE, "Incorrect URI parts for OAuth process, need /oauth/<name>/<action>"); return null; } String name = uriParts[1]; String action = uriParts[2]; // Try to getValue an OAuth2 server for the given name StructrOAuthClient oauthServer = StructrOAuthClient.getServer(name); if (oauthServer == null) { logger.log(Level.FINE, "No OAuth2 authentication server configured for {0}", path); return null; } if ("login".equals(action)) { try { response.sendRedirect(oauthServer.getEndUserAuthorizationRequestUri(request)); return null; } catch (Exception ex) { logger.log(Level.SEVERE, "Could not send redirect to authorization server", ex); } } else if ("auth".equals(action)) { String accessToken = oauthServer.getAccessToken(request); SecurityContext superUserContext = SecurityContext.getSuperUserInstance(); if (accessToken != null) { logger.log(Level.FINE, "Got access token {0}", accessToken); //securityContext.setAttribute("OAuthAccessToken", accessToken); String value = oauthServer.getCredential(request); logger.log(Level.FINE, "Got credential value: {0}", new Object[] { value }); if (value != null) { PropertyKey credentialKey = oauthServer.getCredentialKey(); Principal user = AuthHelper.getPrincipalForCredential(credentialKey, value); if (user == null && userAutoCreate) { user = RegistrationResource.createUser(superUserContext, credentialKey, value, true, userClass); } if (user != null) { final App app = StructrApp.getInstance(); try { app.beginTx(); user.setProperty(Principal.sessionId, HttpAuthenticator.getSessionId(request)); app.commitTx(); HtmlServlet.setNoCacheHeaders(response); try { logger.log(Level.FINE, "Response status: {0}", response.getStatus()); response.sendRedirect(oauthServer.getReturnUri()); } catch (Exception ex) { logger.log(Level.SEVERE, "Could not redirect to {0}: {1}", new Object[] { oauthServer.getReturnUri(), ex }); } return user; } catch (FrameworkException ex) { logger.log(Level.SEVERE, "Could not set session id for user {0}", user.toString()); } finally { app.finishTx(); } } } } } try { response.sendRedirect(oauthServer.getErrorUri()); } catch (Exception ex) { logger.log(Level.SEVERE, "Could not redirect to {0}: {1}", new Object[] { oauthServer.getReturnUri(), ex }); } return null; }
From source file:com.dreambox.web.logger.LoggingFilter.java
@Override protected void logResponse(HttpServletRequest request, HttpServletResponse response) { if (!(response instanceof HttpServletResponseLoggingWrapper) || !isJson(response)) { return;// w w w . jav a 2 s.c o m } String uri = request.getRequestURI(); if (isExcludeUri(uri)) { return; } if (isIgnoreUri(uri)) { return; } long startTime = (long) request.getAttribute(REQUEST_START_TIME); long endTime = System.currentTimeMillis(); long elapse = endTime - startTime; String id = (String) request.getAttribute(REQUEST_ID_ATTR); String status = ""; String message = ""; String respData = ""; try { ServletOutputStream output = response.getOutputStream(); if (output instanceof CopyResponseStreamWrapper) { String copy = ((CopyResponseStreamWrapper) output).getCopy(); if (StringUtils.isNotBlank(copy)) { try { ApiRespWrapper<?> apiRespWrapper = GsonUtils.fromJsonStr(copy, ApiRespWrapper.class); status = String.valueOf(apiRespWrapper.getStatus()); message = apiRespWrapper.getMessage(); if (needLogResponse(uri)) { Object d = apiRespWrapper.getData(); respData = d == null ? "" : d.toString(); } } catch (Exception e) { } } } } catch (IOException e) { } Map<String, String> commonPara = threadLocalMap.get(); String ip = commonPara == null ? IPUtil.getClientIP(request) : commonPara.get("ip"); String method = commonPara == null ? request.getMethod() : commonPara.get("method"); String queryStr = commonPara == null ? request.getQueryString() : commonPara.get("queryStr"); queryStr = StringUtils.replace(queryStr, "\r\n", ""); queryStr = StringUtils.replace(queryStr, "\n", ""); String parameter = commonPara == null ? getRequestParams(request) : commonPara.get("parameter"); parameter = StringUtils.replace(parameter, "\r\n", ""); parameter = StringUtils.replace(parameter, "\n", ""); String logInfo = now() + "\tId:" + id + "\ttype:response\tUri:" + uri + "\tIp:" + ip + "\tMethod:" + method + "\tQueryStr:" + queryStr + "\tParameter:" + parameter + "\tHttpStatus:" + response.getStatus() + "\tStatus:" + status + "\tMessage:" + message + "\telapseTime:" + elapse + "\tData:" + respData; requestLogger.info(logInfo); threadLocalMap.remove(); }
From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java
/** * Serve the specified resource, optionally including the data content. * * @param request/*w ww . j a v a 2 s . c o m*/ * The servlet request we are processing * @param response * The servlet response we are creating * @param content * Should the content be included? * * @exception IOException * if an input/output error occurs * @exception ServletException * if a servlet-specified error occurs */ protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String sessionId = extractSessionId(request); RepositoryHttpEndpointImpl elem = repoHttpManager.getHttpRepoItemElem(sessionId); if (elem == null) { if (debug > 0) { log("Resource with sessionId '" + sessionId + "' not found"); } response.sendError(SC_NOT_FOUND, request.getRequestURI()); return; } elem.fireStartedEventIfFirstTime(); RepositoryItem repositoryItem = elem.getRepositoryItem(); RepositoryItemAttributes attributes = repositoryItem.getAttributes(); if (debug > 0) { if (serveContent) { log("Serving resource with sessionId '" + sessionId + "' headers and data. This resource corresponds to repository item '" + repositoryItem.getId() + "'"); } else { log("Serving resource with sessionId '" + sessionId + "' headers only. This resource corresponds to repository item '" + repositoryItem.getId() + "'"); } } boolean malformedRequest = response.getStatus() >= SC_BAD_REQUEST; if (!malformedRequest && !checkIfHeaders(request, response, attributes)) { return; } String contentType = getContentType(elem, attributes); List<Range> ranges = null; if (!malformedRequest) { response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", attributes.getETag()); response.setHeader("Last-Modified", attributes.getLastModifiedHttp()); ranges = parseRange(request, response, attributes); } long contentLength = attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. boolean contentWritten = response.isCommitted(); if (contentWritten) { ranges = FULL; } boolean noRanges = ranges == null || ranges.isEmpty(); if (malformedRequest || noRanges && request.getHeader("Range") == null || ranges == FULL) { setContentType(response, contentType); if (contentLength >= 0) { // Don't set a content length if something else has already // written to the response. if (!contentWritten) { setContentLength(response, contentLength); } } // Copy the input stream to our output stream (if requested) if (serveContent) { copy(elem, response); } } else { if (noRanges) { return; } // Partial content response. response.setStatus(SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; setContentLength(response, length); setContentType(response, contentType); if (serveContent) { copy(elem, response, range); } } else { response.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATION); if (serveContent) { copy(elem, response, ranges, contentType); } } } elem.stopInTimeout(); }
From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java
/** * Serve the specified resource, optionally including the data content. * //ww w .ja v a 2 s . c om * @param request * The servlet request we are processing * @param response * The servlet response we are creating * @param content * Should the content be included? * * @exception IOException * if an input/output error occurs * @exception ServletException * if a servlet-specified error occurs */ protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { boolean serveContent = content; // Identify the requested resource path String sessionId = extractSessionId(request); RepositoryHttpEndpointImpl elem = repoHttpManager.getHttpRepoItemElem(sessionId); if (elem == null) { if (debug > 0) { log("Resource with sessionId '" + sessionId + "' not found"); } response.sendError(SC_NOT_FOUND, request.getRequestURI()); return; } elem.fireStartedEventIfFirstTime(); RepositoryItem repositoryItem = elem.getRepositoryItem(); RepositoryItemAttributes attributes = repositoryItem.getAttributes(); if (debug > 0) { if (serveContent) { log("Serving resource with sessionId '" + sessionId + "' headers and data. This resource corresponds to repository item '" + repositoryItem.getId() + "'"); } else { log("Serving resource with sessionId '" + sessionId + "' headers only. This resource corresponds to repository item '" + repositoryItem.getId() + "'"); } } boolean malformedRequest = response.getStatus() >= SC_BAD_REQUEST; if (!malformedRequest && !checkIfHeaders(request, response, attributes)) { return; } String contentType = getContentType(elem, attributes); List<Range> ranges = null; if (!malformedRequest) { response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", attributes.getETag()); response.setHeader("Last-Modified", attributes.getLastModifiedHttp()); ranges = parseRange(request, response, attributes); } long contentLength = attributes.getContentLength(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size if (contentLength == 0L) { serveContent = false; } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. boolean contentWritten = response.isCommitted(); if (contentWritten) { ranges = FULL; } boolean noRanges = (ranges == null || ranges.isEmpty()); if (malformedRequest || (noRanges && request.getHeader("Range") == null) || ranges == FULL) { setContentType(response, contentType); if (contentLength >= 0) { // Don't set a content length if something else has already // written to the response. if (!contentWritten) { setContentLength(response, contentLength); } } // Copy the input stream to our output stream (if requested) if (serveContent) { copy(elem, response); } } else { if (noRanges) { return; } // Partial content response. response.setStatus(SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; setContentLength(response, length); setContentType(response, contentType); if (serveContent) { copy(elem, response, range); } } else { response.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATION); if (serveContent) { copy(elem, response, ranges, contentType); } } } elem.stopInTimeout(); }
From source file:org.structr.web.servlet.HtmlServlet.java
@Override protected void doHead(final HttpServletRequest request, final HttpServletResponse response) { final Authenticator auth = getConfig().getAuthenticator(); SecurityContext securityContext;/*from ww w .ja va2s .c om*/ List<Page> pages = null; boolean requestUriContainsUuids = false; final App app; try { String path = request.getPathInfo(); // isolate request authentication in a transaction try (final Tx tx = StructrApp.getInstance().tx()) { securityContext = auth.initializeAndExamineRequest(request, response); tx.success(); } app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { // Ensure access mode is frontend securityContext.setAccessMode(AccessMode.Frontend); request.setCharacterEncoding("UTF-8"); // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4 response.setCharacterEncoding("UTF-8"); response.setContentLength(0); boolean dontCache = false; logger.log(Level.FINE, "Path info {0}", path); // don't continue on redirects if (response.getStatus() == 302) { tx.success(); return; } final Principal user = securityContext.getUser(false); if (user != null) { // Don't cache if a user is logged in dontCache = true; } final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response); renderContext.setResourceProvider(config.getResourceProvider()); final EditMode edit = renderContext.getEditMode(user); DOMNode rootElement = null; AbstractNode dataNode = null; String[] uriParts = PathHelper.getParts(path); if ((uriParts == null) || (uriParts.length == 0)) { // find a visible page rootElement = findIndexPage(securityContext, pages, edit); logger.log(Level.FINE, "No path supplied, trying to find index page"); } else { if (rootElement == null) { rootElement = findPage(securityContext, pages, path, edit); } else { dontCache = true; } } if (rootElement == null) { // No page found // Look for a file File file = findFile(securityContext, request, path); if (file != null) { //streamFile(securityContext, file, request, response, edit); tx.success(); return; } // store remaining path parts in request Matcher matcher = threadLocalUUIDMatcher.get(); for (int i = 0; i < uriParts.length; i++) { request.setAttribute(uriParts[i], i); matcher.reset(uriParts[i]); // set to "true" if part matches UUID pattern requestUriContainsUuids |= matcher.matches(); } if (!requestUriContainsUuids) { // Try to find a data node by name dataNode = findFirstNodeByName(securityContext, request, path); } else { dataNode = findNodeByUuid(securityContext, PathHelper.getName(path)); } if (dataNode != null && !(dataNode instanceof Linkable)) { // Last path part matches a data node // Remove last path part and try again searching for a page // clear possible entry points request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY); rootElement = findPage(securityContext, pages, StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit); renderContext.setDetailsDataObject(dataNode); // Start rendering on data node if (rootElement == null && dataNode instanceof DOMNode) { rootElement = ((DOMNode) dataNode); } } } // look for pages with HTTP Basic Authentication (must be done as superuser) if (rootElement == null) { final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path); switch (authResult.authState()) { // Element with Basic Auth found and authentication succeeded case Authenticated: final Linkable result = authResult.getRootElement(); if (result instanceof Page) { rootElement = (DOMNode) result; renderContext.pushSecurityContext(authResult.getSecurityContext()); } else if (result instanceof File) { //streamFile(authResult.getSecurityContext(), (File)result, request, response, EditMode.NONE); tx.success(); return; } break; // Page with Basic Auth found but not yet authenticated case MustAuthenticate: return; // no Basic Auth for given path, go on case NoBasicAuth: break; } } // Still nothing found, do error handling if (rootElement == null) { // Check if security context has set an 401 status if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) { try { UiAuthenticator.writeUnauthorized(response); } catch (IllegalStateException ise) { } } else { rootElement = notFound(response, securityContext); } } if (rootElement == null) { // no content response.setContentLength(0); response.getOutputStream().close(); tx.success(); return; } // check dont cache flag on page (if root element is a page) // but don't modify true to false dontCache |= rootElement.getProperty(Page.dontCache); if (EditMode.WIDGET.equals(edit) || dontCache) { setNoCacheHeaders(response); } if (!securityContext.isVisible(rootElement)) { rootElement = notFound(response, securityContext); if (rootElement == null) { tx.success(); return; } } if (securityContext.isVisible(rootElement)) { if (!EditMode.WIDGET.equals(edit) && !dontCache && notModifiedSince(request, response, rootElement, dontCache)) { response.getOutputStream().close(); } else { // prepare response response.setCharacterEncoding("UTF-8"); String contentType = rootElement.getProperty(Page.contentType); if (contentType == null) { // Default contentType = "text/html;charset=UTF-8"; } if (contentType.equals("text/html")) { contentType = contentType.concat(";charset=UTF-8"); } response.setContentType(contentType); setCustomResponseHeaders(response); response.getOutputStream().close(); } } else { notFound(response, securityContext); response.getOutputStream().close(); } tx.success(); } catch (Throwable fex) { fex.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", fex); } } catch (FrameworkException t) { t.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", t); UiAuthenticator.writeInternalServerError(response); } }
From source file:com.cisco.oss.foundation.http.server.MonitoringFilter.java
@Override public void doFilterImpl(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { regiterMonitoring();/*from w w w . j av a2s .c om*/ final long startTime = System.currentTimeMillis(); HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String tempMethodName = httpServletRequest.getMethod(); if (uniqueUriMonitoringEnabled) { tempMethodName += ":" + httpServletRequest.getRequestURI(); } boolean reportToMonitoring = true; try { LOGGER.trace("Monitoring filter: Request processing started at: {}", startTime); // methodName = httpServletRequest.getMethod() + ":" + httpServletRequest.getRequestURI().toString(); tempMethodName = updateMethodName(httpServletRequest, tempMethodName); LOGGER.trace("transaction method name is: {}", tempMethodName); CommunicationInfo.getCommunicationInfo().transactionStarted(serviceDetails, tempMethodName, threadPool != null ? threadPool.getThreads() : -1); } catch (Exception e) { LOGGER.error("can't report monitoring data as it has failed on:" + e); reportToMonitoring = false; } final String methodName = tempMethodName; try { chain.doFilter(httpServletRequest, httpServletResponse); if (request.isAsyncStarted()) { AsyncContext async = request.getAsyncContext(); async.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent event) throws IOException { final long endTime = System.currentTimeMillis(); final int processingTime = (int) (endTime - startTime); LOGGER.debug("Processing time: {} milliseconds", processingTime); } @Override public void onTimeout(AsyncEvent event) throws IOException { } @Override public void onError(AsyncEvent event) throws IOException { Throwable throwable = event.getThrowable(); if (throwable != null) { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true, throwable.toString()); } } @Override public void onStartAsync(AsyncEvent event) throws IOException { } }); } else { final long endTime = System.currentTimeMillis(); final int processingTime = (int) (endTime - startTime); LOGGER.debug("Processing time: {} milliseconds", processingTime); } } catch (Exception e) { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true, e.toString()); throw e; } if (reportToMonitoring) { try { int status = httpServletResponse.getStatus(); if (status >= 400) { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true, httpServletResponse.getStatus() + ""); } else { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, false, ""); } } catch (Exception e) { LOGGER.error("can't report monitoring data as it has failed on:" + e); } } }
From source file:org.structr.web.servlet.HtmlServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) { final Authenticator auth = getConfig().getAuthenticator(); List<Page> pages = null; boolean requestUriContainsUuids = false; SecurityContext securityContext;//from w w w. j a va2s . c o m final App app; try { final String path = request.getPathInfo(); // check for registration (has its own tx because of write access if (checkRegistration(auth, request, response, path)) { return; } // check for registration (has its own tx because of write access if (checkResetPassword(auth, request, response, path)) { return; } // isolate request authentication in a transaction try (final Tx tx = StructrApp.getInstance().tx()) { securityContext = auth.initializeAndExamineRequest(request, response); tx.success(); } app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { // Ensure access mode is frontend securityContext.setAccessMode(AccessMode.Frontend); request.setCharacterEncoding("UTF-8"); // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4 response.setCharacterEncoding("UTF-8"); boolean dontCache = false; logger.log(Level.FINE, "Path info {0}", path); // don't continue on redirects if (response.getStatus() == 302) { tx.success(); return; } final Principal user = securityContext.getUser(false); if (user != null) { // Don't cache if a user is logged in dontCache = true; } final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response); renderContext.setResourceProvider(config.getResourceProvider()); final EditMode edit = renderContext.getEditMode(user); DOMNode rootElement = null; AbstractNode dataNode = null; final String[] uriParts = PathHelper.getParts(path); if ((uriParts == null) || (uriParts.length == 0)) { // find a visible page rootElement = findIndexPage(securityContext, pages, edit); logger.log(Level.FINE, "No path supplied, trying to find index page"); } else { if (rootElement == null) { rootElement = findPage(securityContext, pages, path, edit); } else { dontCache = true; } } if (rootElement == null) { // No page found // Look for a file final File file = findFile(securityContext, request, path); if (file != null) { streamFile(securityContext, file, request, response, edit); tx.success(); return; } // store remaining path parts in request final Matcher matcher = threadLocalUUIDMatcher.get(); for (int i = 0; i < uriParts.length; i++) { request.setAttribute(uriParts[i], i); matcher.reset(uriParts[i]); // set to "true" if part matches UUID pattern requestUriContainsUuids |= matcher.matches(); } if (!requestUriContainsUuids) { // Try to find a data node by name dataNode = findFirstNodeByName(securityContext, request, path); } else { dataNode = findNodeByUuid(securityContext, PathHelper.getName(path)); } //if (dataNode != null && !(dataNode instanceof Linkable)) { if (dataNode != null) { // Last path part matches a data node // Remove last path part and try again searching for a page // clear possible entry points request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY); rootElement = findPage(securityContext, pages, StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit); renderContext.setDetailsDataObject(dataNode); // Start rendering on data node if (rootElement == null && dataNode instanceof DOMNode) { rootElement = ((DOMNode) dataNode); } } } // look for pages with HTTP Basic Authentication (must be done as superuser) if (rootElement == null) { final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path); switch (authResult.authState()) { // Element with Basic Auth found and authentication succeeded case Authenticated: final Linkable result = authResult.getRootElement(); if (result instanceof Page) { rootElement = (DOMNode) result; securityContext = authResult.getSecurityContext(); renderContext.pushSecurityContext(securityContext); } else if (result instanceof File) { streamFile(authResult.getSecurityContext(), (File) result, request, response, EditMode.NONE); tx.success(); return; } break; // Page with Basic Auth found but not yet authenticated case MustAuthenticate: tx.success(); return; // no Basic Auth for given path, go on case NoBasicAuth: break; } } // Still nothing found, do error handling if (rootElement == null) { rootElement = notFound(response, securityContext); } if (rootElement == null) { tx.success(); return; } // check dont cache flag on page (if root element is a page) // but don't modify true to false dontCache |= rootElement.getProperty(Page.dontCache); if (EditMode.WIDGET.equals(edit) || dontCache) { setNoCacheHeaders(response); } if (!securityContext.isVisible(rootElement)) { rootElement = notFound(response, securityContext); if (rootElement == null) { tx.success(); return; } } else { if (!EditMode.WIDGET.equals(edit) && !dontCache && notModifiedSince(request, response, rootElement, dontCache)) { ServletOutputStream out = response.getOutputStream(); out.flush(); //response.flushBuffer(); out.close(); } else { // prepare response response.setCharacterEncoding("UTF-8"); String contentType = rootElement.getProperty(Page.contentType); if (contentType == null) { // Default contentType = "text/html;charset=UTF-8"; } if (contentType.equals("text/html")) { contentType = contentType.concat(";charset=UTF-8"); } response.setContentType(contentType); setCustomResponseHeaders(response); final boolean createsRawData = rootElement.getProperty(Page.pageCreatesRawData); // async or not? if (isAsync && !createsRawData) { final AsyncContext async = request.startAsync(); final ServletOutputStream out = async.getResponse().getOutputStream(); final AtomicBoolean finished = new AtomicBoolean(false); final DOMNode rootNode = rootElement; threadPool.submit(new Runnable() { @Override public void run() { try (final Tx tx = app.tx()) { //final long start = System.currentTimeMillis(); // render rootNode.render(renderContext, 0); finished.set(true); //final long end = System.currentTimeMillis(); //System.out.println("Done in " + (end-start) + " ms"); tx.success(); } catch (Throwable t) { t.printStackTrace(); final String errorMsg = t.getMessage(); try { //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMsg); finished.set(true); } catch (IOException ex) { ex.printStackTrace(); } } } }); // start output write listener out.setWriteListener(new WriteListener() { @Override public void onWritePossible() throws IOException { try { final Queue<String> queue = renderContext.getBuffer().getQueue(); while (out.isReady()) { String buffer = null; synchronized (queue) { buffer = queue.poll(); } if (buffer != null) { out.print(buffer); } else { if (finished.get()) { async.complete(); response.setStatus(HttpServletResponse.SC_OK); // prevent this block from being called again break; } Thread.sleep(1); } } } catch (Throwable t) { t.printStackTrace(); } } @Override public void onError(Throwable t) { t.printStackTrace(); } }); } else { final StringRenderBuffer buffer = new StringRenderBuffer(); renderContext.setBuffer(buffer); // render rootElement.render(renderContext, 0); try { response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8")); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (IOException ioex) { ioex.printStackTrace(); } } } } tx.success(); } catch (FrameworkException fex) { fex.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", fex); } } catch (IOException | FrameworkException t) { t.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", t); UiAuthenticator.writeInternalServerError(response); } }