List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_IMPLEMENTED
int SC_NOT_IMPLEMENTED
To view the source code for javax.servlet.http HttpServletResponse SC_NOT_IMPLEMENTED.
Click Source Link
From source file:com.att.ajsc.csilogging.common.CSILoggingUtils.java
public void finalizeRequest(HttpServletRequest request, HttpServletResponse response) { logger.debug("In...:finalizeRequest"); String servicename = UtilLib.getServiceName(request); PerformanceTrackingBean perfTrackerBean = (PerformanceTrackingBean) request .getAttribute(PERFORMANCE_TRACKER_BEAN); long startTime = (long) request.getAttribute(CommonNames.START_TIME); AuditRecord ar = new AuditRecord(); try {//from w w w.j av a2s .co m logger.debug("Starting application specific handling...:finalizeRequest"); // request.setAttribute(CommonNames.AUDIT_RECORD, ar); // request.setAttribute(CommonNames.ATTR_START_TIME, // Long.valueOf(startTime).toString()); perfTrackerBean.setAuditRecord(ar); servicename = LoggerNameConverter.convertNormalizedName(request, servicename); perfTrackerBean.setServiceName(servicename); perfTrackerBean.setRequestContentLen(request.getContentLength()); perfTrackerBean.setResponseMsgSize(getResponseLength(request)); perfTrackerBean.setMethod(request.getMethod()); ar.setInstanceName(SystemParams.instance().getInstanceName()); ar.setInitiatedTimestamp(UtilLib.epochToXmlGC(startTime)); ar.setVtier(SystemParams.instance().getVtier()); ar.setCluster(SystemParams.instance().getCluster()); ar.setHostName(SystemParams.instance().getHostName()); ar.setHostIPAddress(SystemParams.instance().getIpAddress()); ar.setSubject("CW.pub.spm2." + servicename + ".response"); ar.setMode(""); ar.setServiceKeyData1(""); ar.setServiceKeyData2(""); ar.setSourceClass(CommonNames.SOURCE_CLASS); ar.setSourceMethod(CommonNames.AUDIT_LOGGER_NAME); ar.setTransactionName(servicename); /* * ar.setApplicationId(request.getAttribute(CommonNames. * CSI_USER_NAME)); * ar.setConversationId(request.getAttribute(CommonNames. * CSI_CONVERSATION_ID)); * ar.setUniqueTransactionId(request.getAttribute(CommonNames. * CSI_UNIQUE_TXN_ID)); * ar.setOriginalMessageId(request.getAttribute(CommonNames. * CSI_MESSAGE_ID)); * ar.setOriginatorId(request.getAttribute(CommonNames. * CSI_ORIGINATOR_ID)); * ar.setClientApp(UtilLib.ifNullThenEmpty(request.getAttribute( * CommonNames.CSI_CLIENT_APP))); ar.setOriginationSystemId("N/A"); * ar.setOriginationSystemName(request.getAttribute(CommonNames. * CSI_USER_NAME)); * ar.setOriginationSystemVersion(request.getAttribute(CommonNames. * CSI_VERSION)); */ ar.setApplicationId(perfTrackerBean.getUserName()); ar.setConversationId(perfTrackerBean.getConversationId()); ar.setUniqueTransactionId(perfTrackerBean.getUniqueTransactionId()); ar.setOriginalMessageId(perfTrackerBean.getOriginalMessageId()); ar.setOriginatorId(perfTrackerBean.getOriginatorId()); ar.setClientApp(UtilLib.ifNullThenEmpty(perfTrackerBean.getClientApp())); ar.setOriginationSystemId("N/A"); ar.setOriginationSystemName(perfTrackerBean.getUserName()); ar.setOriginationSystemVersion(perfTrackerBean.getOriginationSystemVersion()); // new fields added per new schema ar.setClientIP(request.getRemoteAddr()); ar.setHttpMethod(perfTrackerBean.getMethod()); ar.setRequestURL(request.getPathInfo()); // PerformanceTracking.initPerfTrack(request,servicename); PerformanceTracking.initPerfTrack(perfTrackerBean, servicename); // PerformanceTracking.addPerfTrack(request, "Main", "I", // startTime.toString(), servicename); int httpCode = response.getStatus(); if (httpCode == HttpServletResponse.SC_UNAUTHORIZED) { ar.setResponseCode(CommonNames.CSI_AUTH_ERROR); ar.setResponseDescription(CommonErrors.DEF_401_FAULT_DESC); ar.setFaultCode(CommonErrors.DEF_401_FAULT_CODE); ar.setFaultDescription(CommonErrors.DEF_401_FAULT_DESC); ar.setFaultLevel("ERROR"); ar.setTransactionStatus("E"); ar.setFaultEntity("CSI"); ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis())); ar.setExternalFaultCode(String.valueOf(httpCode)); ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR); } else if (httpCode == HttpServletResponse.SC_FORBIDDEN) { ar.setResponseCode(CommonNames.CSI_AUTH_ERROR); ar.setResponseDescription(CommonErrors.DEF_403_FAULT_DESC); ar.setFaultCode(CommonErrors.DEF_403_FAULT_CODE); ar.setFaultDescription(CommonErrors.DEF_403_FAULT_DESC); ar.setFaultLevel("ERROR"); ar.setTransactionStatus("E"); ar.setFaultEntity("CSI"); ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis())); ar.setExternalFaultCode(String.valueOf(httpCode)); ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR); } else if (httpCode == HttpServletResponse.SC_NOT_IMPLEMENTED) { ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR); ar.setResponseDescription(CommonErrors.DEF_501_FAULT_DESC); ar.setFaultCode(CommonErrors.DEF_501_FAULT_CODE); ar.setFaultDescription(CommonErrors.DEF_501_FAULT_DESC); ar.setFaultLevel("ERROR"); ar.setTransactionStatus("E"); ar.setFaultEntity("CSI"); ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis())); ar.setExternalFaultCode(String.valueOf(httpCode)); ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR); } else if (httpCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) { ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR); ar.setResponseDescription(CommonErrors.DEF_503_FAULT_DESC); ar.setFaultCode(CommonErrors.DEF_503_FAULT_CODE); ar.setFaultDescription(CommonErrors.DEF_503_FAULT_DESC); ar.setFaultLevel("ERROR"); ar.setTransactionStatus("E"); ar.setFaultEntity("CSI"); ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis())); ar.setExternalFaultCode(String.valueOf(httpCode)); ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR); } else if (400 <= httpCode && httpCode <= 499) { ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR); ar.setResponseDescription(CommonErrors.DEF_4NN_FAULT_DESC); ar.setFaultCode(CommonErrors.DEF_4NN_FAULT_CODE); ar.setFaultDescription(CommonErrors.DEF_4NN_FAULT_DESC); ar.setFaultLevel("ERROR"); ar.setFaultEntity("CSI"); ar.setTransactionStatus("E"); ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis())); ar.setExternalFaultCode(String.valueOf(httpCode)); ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR); } else if (httpCode == 500) { ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR); ar.setResponseDescription(CommonErrors.DEF_500_FAULT_DESC); ar.setFaultCode(CommonErrors.DEF_500_FAULT_CODE); ar.setFaultDescription(CommonErrors.DEF_500_FAULT_DESC); ar.setFaultLevel("ERROR"); ar.setFaultEntity("CSI"); ar.setTransactionStatus("E"); // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new // Double(System.nanoTime()/1000000)).longValue())); ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis())); ar.setExternalFaultCode(String.valueOf(httpCode)); ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR); } else { ar.setResponseDescription(CommonNames.CSI_SUCCESS); ar.setResponseCode(CommonNames.CSI_SUCCESS_RESPONSE_CODE); ar.setTransactionStatus("C"); } // Enhance CSI logging to use the CAET error code if (response.getHeader(CommonNames.CAET_RestErrorCode) != null || response.getHeader(CommonNames.CAET_CingularErrorCode) != null) { // if(request.getHeader("X-CAET-CingularErrorCode") != null){ if ("Y".equals(request.getAttribute(CommonNames.AJSC_CAET_IS_REST_SERVICE))) { ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCategory)); ar.setResponseDescription(response.getHeader(CommonNames.CAET_RestErrorDescription)); } else { ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCode)); ar.setResponseDescription(response.getHeader(CommonNames.CAET_CingularErrorDescription)); } ar.setFaultCode(response.getHeader(CommonNames.CAET_FaultCode)); ar.setFaultDescription(response.getHeader(CommonNames.CAET_FaultDesc)); ar.setFaultLevel(CommonNames.ERROR); ar.setFaultEntity(response.getHeader(CommonNames.CAET_FaultEntity)); ar.setTransactionStatus("E"); ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis())); // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new // Double(System.nanoTime()/1000000)).longValue())); ar.setExternalFaultCode(String.valueOf(httpCode)); ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR); } } catch (Exception e) { // AuditRecord ar = // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD); ar.setResponseCode(CommonNames.CSI_GENERIC_UNKNOWN_ERROR); ar.setResponseDescription(CommonErrors.DEF_5NN_FAULT_DESC); ar.setFaultEntity("CSI"); ar.setFaultCode(CommonErrors.DEF_5NN_FAULT_CODE); ar.setFaultDescription(e.getMessage()); ar.setFaultLevel("ERROR"); ar.setFaultSequenceNumber("1"); ar.setTransactionStatus("E"); ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis())); // ar.setFaultTimestamp(UtilLib.epochToXmlGC(((Long)System.nanoTime()/1000000).longValue())); logger.error("EXCEPTION - " + e.getMessage()); } finally { // AuditRecord ar = // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD); if (ar != null) { if (perfTrackerBean != null && !perfTrackerBean.isAsync()) { perfTrackerBean.setAuditRecord(ar); logger.debug("Before calling completeLogging"); completeLogging(request, servicename); } } else { logger.debug("Audit Record is null,abort logging"); } } }
From source file:ch.entwine.weblounge.dispatcher.impl.handler.PageRequestHandlerImpl.java
/** * Handles the request for a simple url available somewhere in the system. The * handler sets the response type, does the url history and then forwards * request to the corresponding JSP page or XSLT stylesheet. * <p>// w w w .java2s. co m * This method returns <code>true</code> if the handler is decided to handle * the request, <code>false</code> otherwise. * * @param request * the weblounge request * @param response * the weblounge response */ public boolean service(WebloungeRequest request, WebloungeResponse response) { logger.debug("Page handler agrees to handle {}", request.getUrl()); Mode processingMode = Mode.Default; WebUrl url = request.getUrl(); String path = url.getPath(); RequestFlavor contentFlavor = request.getFlavor(); if (contentFlavor == null || contentFlavor.equals(ANY)) contentFlavor = RequestFlavor.HTML; // Check the request flavor // TODO: Criteria would be loading the page from the repository // TODO: Think about performance, page lookup is expensive if (!HTML.equals(contentFlavor)) { logger.debug("Skipping request for {}, flavor {} is not supported", path, request.getFlavor()); return false; } // Determine the editing state boolean isEditing = RequestUtils.isEditingState(request); // Check if the request is controlled by an action. Action action = (Action) request.getAttribute(WebloungeRequest.ACTION); // Get the renderer id that has been registered with the url. For this, // we first have to load the page data, then get the associated renderer // bundle. try { Page page = null; ResourceURI pageURI = null; Site site = request.getSite(); // Check if a page was passed as an attribute if (request.getAttribute(WebloungeRequest.PAGE) != null) { page = (Page) request.getAttribute(WebloungeRequest.PAGE); pageURI = page.getURI(); } // Load the page from the content repository else { ContentRepository contentRepository = site.getContentRepository(); if (contentRepository == null) { logger.debug("No content repository found for site '{}'", site); return false; } else if (contentRepository.isIndexing()) { logger.debug("Content repository of site '{}' is currently being indexed", site); DispatchUtils.sendServiceUnavailable(request, response); return true; } ResourceURI requestURI = null; ResourceURI requestedURI = null; // Load the page. Note that we are taking care of the special case where // a user may have created a page with a url that matches a valid // language identifier, in which case it would have been stripped from // request.getUrl(). try { if (action != null) { pageURI = getPageURIForAction(action, request); requestURI = pageURI; } else if (path.startsWith(URI_PREFIX)) { String uriSuffix = StringUtils.substringBefore(path.substring(URI_PREFIX.length()), "/"); uriSuffix = URLDecoder.decode(uriSuffix, "utf-8"); ResourceURI uri = new PageURIImpl(site, null, uriSuffix, request.getVersion()); requestURI = uri; WebUrl requestedUrl = request.getRequestedUrl(); if (requestedUrl.hasLanguagePathSegment()) { String requestedPath = UrlUtils.concat(path, request.getLanguage().getIdentifier()); String requestedUriSuffix = StringUtils .substringBefore(requestedPath.substring(URI_PREFIX.length()), "/"); requestedUriSuffix = URLDecoder.decode(requestedUriSuffix, "utf-8"); requestedURI = new PageURIImpl(site, requestedUriSuffix, null, request.getVersion()); } } else { long version = isEditing ? Resource.WORK : Resource.LIVE; ResourceURI uri = new PageURIImpl(request); uri.setVersion(version); requestURI = uri; WebUrl requestedUrl = request.getRequestedUrl(); if (requestedUrl.hasLanguagePathSegment()) { String requestedPath = UrlUtils.concat(path, request.getLanguage().getIdentifier()); requestedPath = URLDecoder.decode(requestedPath, "utf-8"); requestedURI = new PageURIImpl(site, requestedPath, null, version); } } // Is this a request with potential path clashes? if (requestedURI != null) { long version = requestedURI.getVersion(); if (contentRepository.existsInAnyVersion(requestedURI)) { if (!isEditing && version == Resource.LIVE && contentRepository.exists(requestedURI)) { pageURI = requestedURI; ((WebloungeRequestImpl) request).setLanguage(request.getSessionLanguage()); } else if (isEditing && version == Resource.WORK && !contentRepository.exists(requestedURI)) { requestedURI.setVersion(Resource.LIVE); pageURI = requestedURI; ((WebloungeRequestImpl) request).setLanguage(request.getSessionLanguage()); } else if (isEditing && version == Resource.WORK && !contentRepository.exists(requestedURI)) { pageURI = requestedURI; ((WebloungeRequestImpl) request).setLanguage(request.getSessionLanguage()); } } } // Does the page exist? if (pageURI == null && contentRepository.existsInAnyVersion(requestURI)) { long version = requestURI.getVersion(); // If the work version is requested, we need to make sure // a) it exists and b) the user is in editing mode if (version == Resource.WORK && isEditing) { if (contentRepository.exists(requestURI)) { pageURI = requestURI; } else { requestURI.setVersion(Resource.LIVE); if (contentRepository.exists(requestURI)) pageURI = requestURI; } } else if (contentRepository.exists(requestURI)) { pageURI = requestURI; } } // Did we find a matching uri? if (pageURI == null) { DispatchUtils.sendNotFound(request, response); return true; } page = (Page) contentRepository.get(pageURI); if (page == null) { DispatchUtils.sendNotFound(request, response); return true; } } catch (ContentRepositoryException e) { logger.error("Unable to load page {} from {}: {}", new Object[] { pageURI, contentRepository, e.getMessage(), e }); DispatchUtils.sendInternalError(request, response); return true; } } // Check the request method. This handler only supports GET, POST and // OPTIONS String requestMethod = request.getMethod().toUpperCase(); if ("OPTIONS".equals(requestMethod)) { String verbs = "OPTIONS, GET, POST"; logger.trace("Answering options request to {} with {}", url, verbs); response.setHeader("Allow", verbs); response.setContentLength(0); return true; } else if (!"GET".equals(requestMethod) && !"POST".equals(requestMethod) && !RequestUtils.containsAction(request)) { logger.debug("Url {} does not handle {} requests", url, requestMethod); DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response); return true; } // Is it published? if (!page.isPublished() && !(page.getVersion() == Resource.WORK)) { logger.debug("Access to unpublished page {}", pageURI); response.sendError(HttpServletResponse.SC_NOT_FOUND); return true; } // Can the page be accessed by the current user? User user = request.getUser(); try { // TODO: Check permission // PagePermission p = new PagePermission(page, user); // AccessController.checkPermission(p); } catch (SecurityException e) { logger.warn("Accessed to page {} denied for user {}", pageURI, user); DispatchUtils.sendAccessDenied(request, response); return true; } // Check for explicit no cache instructions boolean ignoreCache = request.getParameter(ResponseCache.NOCACHE_PARAM) != null; // Check if the page is already part of the cache. If so, our task is // already done! if (!ignoreCache && request.getVersion() == Resource.LIVE && !isEditing) { // Create the set of tags that identify the page CacheTagSet cacheTags = createPrimaryCacheTags(request); if (action == null) { long expirationTime = Renderer.DEFAULT_VALID_TIME; long revalidationTime = Renderer.DEFAULT_RECHECK_TIME; // Check if the page is already part of the cache if (response.startResponse(cacheTags.getTags(), expirationTime, revalidationTime)) { logger.debug("Page handler answered request for {} from cache", request.getUrl()); return true; } } processingMode = Mode.Cached; cacheTags.add(CacheTag.Resource, page.getURI().getIdentifier()); response.addTags(cacheTags); } else if (Http11Constants.METHOD_HEAD.equals(requestMethod)) { // handle HEAD requests Http11Utils.startHeadResponse(response); processingMode = Mode.Head; } else if (request.getVersion() == Resource.WORK) { response.setCacheExpirationTime(0); } // Set the default maximum render and valid times for pages response.setClientRevalidationTime(Renderer.DEFAULT_RECHECK_TIME); response.setCacheExpirationTime(Renderer.DEFAULT_VALID_TIME); // Store the page in the request request.setAttribute(WebloungeRequest.PAGE, page); // Get hold of the page template PageTemplate template = null; try { template = getPageTemplate(page, request); template.setEnvironment(request.getEnvironment()); } catch (IllegalStateException e) { logger.debug(e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } // Does the template support the requested flavor? if (!template.supportsFlavor(contentFlavor)) { logger.warn("Template '{}' does not support requested flavor {}", template, contentFlavor); DispatchUtils.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, request, response); return true; } // Suggest a last modified data. Note that this may not be the final date // as the page may contain content embedded from other pages that feature // more recent modification dates response.setModificationDate(page.getLastModified()); // Set the content type String characterEncoding = response.getCharacterEncoding(); if (StringUtils.isNotBlank(characterEncoding)) response.setContentType("text/html; charset=" + characterEncoding.toLowerCase()); else response.setContentType("text/html"); // Add the template's HTML header elements to the response if it's not // only used in editing mode for (HTMLHeadElement header : template.getHTMLHeaders()) { if (!HTMLInclude.Use.Editor.equals(header.getUse())) response.addHTMLHeader(header); } // Select the actual renderer by method and have it render the // request. Since renderers are being pooled by the bundle, we // have to return it after the request has finished. try { logger.debug("Rendering {} using page template '{}'", path, template); template.render(request, response); } catch (Throwable t) { String params = RequestUtils.dumpParameters(request); String msg = "Error rendering template '" + template + "' on '" + path + "' " + params; Throwable o = t.getCause(); if (o != null) { msg += ": " + o.getMessage(); logger.error(msg, o); } else { logger.error(msg, t); } DispatchUtils.sendInternalError(request, response); } return true; } catch (EOFException e) { logger.debug("Error writing page '{}' back to client: connection closed by client", url); return true; } catch (IOException e) { logger.error("I/O exception while sending error status: {}", e.getMessage(), e); return true; } finally { if (action == null) { switch (processingMode) { case Cached: response.endResponse(); break; case Head: Http11Utils.endHeadResponse(response); break; default: break; } } } }
From source file:de.kp.ames.web.core.service.ServiceImpl.java
/** * Send Not Implemented response/*from w ww .j a v a2 s . c om*/ * * @param ctx */ protected void sendNotImplemented(RequestContext ctx) { String errorMessage = "[" + this.getClass().getName() + "] Required parameters not provided."; int errorStatus = HttpServletResponse.SC_NOT_IMPLEMENTED; try { sendErrorResponse(errorMessage, errorStatus, ctx.getResponse()); } catch (IOException e1) { // do nothing } }
From source file:org.dspace.app.dav.DAVServlet.java
/** * Pass this request along to the appropriate resource and method. Includes * authentication, where needed. Return true if we handle this request, * false otherwise. True means response has been "sent", false not. * /* www .j a v a 2 s . com*/ * @param method the method * @param request the request * @param response the response * * @return true, if service internal * @throws IOException Signals that an I/O exception has occurred. */ protected static boolean serviceInternal(String method, HttpServletRequest request, HttpServletResponse response) throws IOException { // Fake new DAV methods not understood by the Apache Servlet base class // (returns HTTP/500 when it sees unrecognised method) // The way it is faked is by submitting "delete=true" in the PUT URL's // query parameters (for a delete) // The way it is faked is by submitting "mkcol=true" in the PUT URL's // query parameters (for a mk-collection) if (method.equals(METHOD_PUT) && request.getQueryString().indexOf("delete=true") >= 0) { method = METHOD_DELETE; } if (method.equals(METHOD_PUT) && request.getQueryString().indexOf("mkcol=true") >= 0) { method = METHOD_MKCOL; } // if not a DAV method (i.e. POST), defer to superclass. if (!(method.equals(METHOD_PROPFIND) || method.equals(METHOD_PROPPATCH) || method.equals(METHOD_MKCOL) || method.equals(METHOD_COPY) || method.equals(METHOD_MOVE) || method.equals(METHOD_DELETE) || method.equals(METHOD_GET) || method.equals(METHOD_PUT))) { return false; } // set all incoming encoding to UTF-8 request.setCharacterEncoding("UTF-8"); String pathElt[] = getDavResourcePath(request).split("/"); Context context = null; try { // this sends a response on failure, unless it throws. context = authenticate(request, response, null, null); if (context == null) { return true; } // Note: findResource sends error response if it fails. DAVResource resource = DAVResource.findResource(context, request, response, pathElt); if (resource != null) { if (method.equals(METHOD_PROPFIND)) { resource.propfind(); } else if (method.equals(METHOD_PROPPATCH)) { resource.proppatch(); } else if (method.equals(METHOD_COPY)) { resource.copy(); } else if (method.equals(METHOD_DELETE)) { resource.delete(); } else if (method.equals(METHOD_MKCOL)) { resource.mkcol(); } else if (method.equals(METHOD_GET)) { resource.get(); } else if (method.equals(METHOD_PUT)) { resource.put(); } else { response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } context.complete(); context = null; } } catch (SQLException e) { log.error(e.toString(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, truncateForStatus("Database access error: " + e.toString())); } catch (AuthorizeException e) { if (log.isDebugEnabled()) { log.debug(e.toString(), e); } else { log.info(e.toString()); } response.sendError(HttpServletResponse.SC_FORBIDDEN, truncateForStatus("Access denied: " + e.toString())); } catch (DAVStatusException e) { log.error(e.toString(), e); response.sendError(e.getStatus(), truncateForStatus(e.getMessage())); } catch (IOException e) { log.error(e.toString(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, truncateForStatus("IO Error: " + e.toString())); } catch (Exception e) { log.error(e.toString(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, truncateForStatus("IO Error: " + e.toString())); } finally { // Abort the context if it's still valid if (context != null && context.isValid()) { context.abort(); } } return true; }
From source file:com.jpeterson.littles3.StorageEngine.java
/** * Process HTTP HEAD and GET/*from ww w . j a v a 2 s . co m*/ * * @param req * an HttpServletRequest object that contains the request the * client has made of the servlet * @param resp * an HttpServletResponse object that contains the response the * servlet sends to the client * @throws IOException * if an input or output error is detected when the servlet * handles the GET request * @throws ServletException * if the request for the GET could not be handled */ @SuppressWarnings("unchecked") public void processHeadGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (logger.isDebugEnabled()) { logger.debug("Context path: " + req.getContextPath()); logger.debug("Path info: " + req.getPathInfo()); logger.debug("Path translated: " + req.getPathTranslated()); logger.debug("Query string: " + req.getQueryString()); logger.debug("Request URI: " + req.getRequestURI()); logger.debug("Request URL: " + req.getRequestURL()); logger.debug("Servlet path: " + req.getServletPath()); logger.debug("Servlet name: " + this.getServletName()); for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) { String headerName = (String) headerNames.nextElement(); String headerValue = req.getHeader(headerName); logger.debug("Header- " + headerName + ": " + headerValue); } } try { S3ObjectRequest or; try { or = S3ObjectRequest.create(req, resolvedHost(), (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR)); } catch (InvalidAccessKeyIdException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId"); return; } catch (InvalidSecurityException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } catch (RequestTimeTooSkewedException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed"); return; } catch (SignatureDoesNotMatchException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch"); return; } catch (AuthenticatorException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } if (or.getKey() != null) { S3Object s3Object; StorageService storageService; try { storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); s3Object = storageService.load(or.getBucket(), or.getKey()); if (s3Object == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey"); return; } } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey"); return; } if (req.getParameter(PARAMETER_ACL) != null) { // retrieve access control policy String response; Acp acp = s3Object.getAcp(); try { acp.canRead(or.getRequestor()); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } response = Acp.encode(acp); resp.setContentLength(response.length()); resp.setContentType("application/xml"); resp.setStatus(HttpServletResponse.SC_OK); Writer out = resp.getWriter(); out.write(response); out.flush(); // commit response out.close(); out = null; } else { // retrieve object InputStream in = null; OutputStream out = null; byte[] buffer = new byte[4096]; int count; String value; try { s3Object.canRead(or.getRequestor()); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } // headers resp.setContentType(s3Object.getContentType()); if ((value = s3Object.getContentDisposition()) != null) { resp.setHeader("Content-Disposition", value); } // TODO: set the Content-Range, if request includes Range // TODO: add "x-amz-missing-meta", if any // add the "x-amz-meta-" headers for (Iterator<String> names = s3Object.getMetadataNames(); names.hasNext();) { String name = names.next(); String headerName = HEADER_PREFIX_USER_META + name; String prefix = ""; StringBuffer buf = new StringBuffer(); for (Iterator<String> values = s3Object.getMetadataValues(name); values.hasNext();) { buf.append(values.next()).append(prefix); prefix = ","; } resp.setHeader(headerName, buf.toString()); } resp.setDateHeader("Last-Modified", s3Object.getLastModified()); if ((value = s3Object.getETag()) != null) { resp.setHeader("ETag", value); } if ((value = s3Object.getContentMD5()) != null) { resp.setHeader("Content-MD5", value); } if ((value = s3Object.getContentDisposition()) != null) { resp.setHeader("Content-Disposition", value); } resp.setHeader("Accept-Ranges", "bytes"); String rangeRequest = req.getHeader("Range"); if (rangeRequest != null) { // request for a range RangeSet rangeSet = RangeFactory.processRangeHeader(rangeRequest); // set content length rangeSet.resolve(s3Object.getContentLength()); if (rangeSet.size() > 1) { // requires multi-part response // TODO: implement resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } Range[] ranges = (Range[]) rangeSet.toArray(new Range[0]); resp.setHeader("Content-Range", formatRangeHeaderValue(ranges[0], s3Object.getContentLength())); resp.setHeader("Content-Length", Long.toString(rangeSet.getLength())); in = new RangeInputStream(s3Object.getInputStream(), ranges[0]); resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); } else { // request for entire content // Used instead of resp.setContentLength((int)); because // Amazon // limit is 5 gig, which is bigger than an int resp.setHeader("Content-Length", Long.toString(s3Object.getContentLength())); in = s3Object.getInputStream(); resp.setStatus(HttpServletResponse.SC_OK); } // body out = resp.getOutputStream(); while ((count = in.read(buffer, 0, buffer.length)) > 0) { out.write(buffer, 0, count); } out.flush(); // commit response out.close(); out = null; } return; } else if (or.getBucket() != null) { // operation on a bucket StorageService storageService; String prefix; String marker; int maxKeys = Integer.MAX_VALUE; String delimiter; String response; String value; storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); if (req.getParameter(PARAMETER_ACL) != null) { // retrieve access control policy Acp acp; try { acp = storageService.loadBucket(or.getBucket()).getAcp(); } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } try { acp.canRead(or.getRequestor()); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } response = Acp.encode(acp); resp.setContentLength(response.length()); resp.setContentType("application/xml"); resp.setStatus(HttpServletResponse.SC_OK); Writer out = resp.getWriter(); out.write(response); out.flush(); // commit response out.close(); out = null; } else { Bucket bucket; prefix = req.getParameter("prefix"); if (prefix == null) { prefix = ""; } marker = req.getParameter("marker"); value = req.getParameter("max-keys"); if (value != null) { try { maxKeys = Integer.parseInt(value); } catch (NumberFormatException e) { logger.info("max-keys must be numeric: " + value); } } delimiter = req.getParameter("delimiter"); try { bucket = storageService.loadBucket(or.getBucket()); } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } try { bucket.canRead(or.getRequestor()); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } response = storageService.listKeys(bucket, prefix, marker, delimiter, maxKeys); resp.setContentLength(response.length()); resp.setContentType("application/xml"); resp.setStatus(HttpServletResponse.SC_OK); Writer out = resp.getWriter(); out.write(response); if (logger.isTraceEnabled()) { logger.trace("Response: " + response); } } return; } else { // operation on the service StorageService storageService; List buckets; storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); buckets = storageService.findBuckets(""); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"); buffer.append("<Owner>"); buffer.append("<ID/>"); // TODO: implement buffer.append("<DisplayName/>"); // TODO: implementF buffer.append("</Owner>"); buffer.append("<Buckets>"); for (Iterator iter = buckets.iterator(); iter.hasNext();) { Bucket bucket = (Bucket) iter.next(); buffer.append("<Bucket>"); buffer.append("<Name>").append(bucket.getName()).append("</Name>"); buffer.append("<CreationDate>").append(iso8601.format(bucket.getCreated())) .append("</CreationDate>"); buffer.append("</Bucket>"); } buffer.append("</Buckets>"); buffer.append("</ListAllMyBucketsResult>"); resp.setContentLength(buffer.length()); resp.setContentType("application/xml"); resp.setStatus(HttpServletResponse.SC_OK); Writer out = resp.getWriter(); out.write(buffer.toString()); return; } } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidURI"); return; } }
From source file:org.ejbca.extra.ra.ScepRAServlet.java
private void service(String operation, String message, String remoteAddr, HttpServletResponse response) throws IOException { try {/*from w w w. j a v a 2 s . co m*/ if ((operation == null) || (message == null)) { log.error("Got request missing operation and/or message parameters."); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameters 'operation' and 'message' must be supplied!"); return; } log.debug("Got request '" + operation + "'"); log.debug("Message: " + message); log.debug("Operation is : " + operation); String alias = scepraks.getAlias(); log.debug("SCEP RA Keystore alias : " + alias); KeyStore raks = scepraks.getKeyStore(); Certificate[] chain = raks.getCertificateChain(alias); X509Certificate cacert = null; if (chain.length > 1) { // This should absolutely be more than one! cacert = (X509Certificate) chain[1]; } else { log.error( "Certificate chain in RA keystore is only 1 certificate long! This is en error, because there should also be CA certificates."); } X509Certificate racert = (X509Certificate) raks.getCertificate(alias); String kspwd = ExtraConfiguration.instance() .getString(ExtraConfiguration.SCEPKEYSTOREPWD + keyStoreNumber); PrivateKey rapriv = (PrivateKey) raks.getKey(alias, kspwd.toCharArray()); if (operation.equals("PKIOperation")) { byte[] scepmsg = Base64.decode(message.getBytes()); // Read the message end get the cert, this also checks authorization boolean includeCACert = true; if (StringUtils.equals("0", getInitParameter("includeCACert"))) { includeCACert = false; } byte[] reply = null; ScepRequestMessage reqmsg = new ScepRequestMessage(scepmsg, includeCACert); String transId = reqmsg.getTransactionId(); log.debug("Received a message of type: " + reqmsg.getMessageType()); if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL) { log.info("Received a GetCertInitial message from host: " + remoteAddr); Message msg = null; try { msg = msgHome.findByMessageId(transId); } catch (Exception e) { // TODO: internal resources log.info("Error looking for message with transId " + transId + " :", e); } if (msg != null) { if (msg.getStatus().equals(Message.STATUS_PROCESSED)) { log.debug("Request is processed with status: " + msg.getStatus()); SubMessages submessagesresp = msg.getSubMessages(null, null, null); Iterator<ISubMessage> iter = submessagesresp.getSubMessages().iterator(); PKCS10Response resp = (PKCS10Response) iter.next(); // create proper ScepResponseMessage IResponseMessage ret = reqmsg.createResponseMessage( org.ejbca.core.protocol.scep.ScepResponseMessage.class, reqmsg, racert, rapriv, cryptProvider); ret.setCACert(cacert); X509Certificate respCert = resp.getCertificate(); if (resp.isSuccessful() && (respCert != null)) { ret.setCertificate(respCert); } else { ret.setStatus(ResponseStatus.FAILURE); ret.setFailInfo(FailInfo.BAD_REQUEST); String failText = resp.getFailInfo(); ret.setFailText(failText); } ret.create(); reply = ret.getResponseMessage(); } else { log.debug("Request is not yet processed, status: " + msg.getStatus()); reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider) .getResponseMessage(); log.debug("Responding with pending response, still pending."); } } else { // User doesn't exist } } else { if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_PKCSREQ) { log.debug("Received a PKCSReq message from host: " + remoteAddr); // Decrypt the Scep message and extract the pkcs10 request if (reqmsg.requireKeyInfo()) { // scep encrypts message with the RAs certificate reqmsg.setKeyInfo(racert, rapriv, cryptProvider); } // Verify the request if (reqmsg.verify() == false) { String msg = "POPO verification failed."; log.error(msg); throw new SignRequestSignatureException(msg); } String username = reqmsg.getUsername(); if (username == null) { String msg = "No username in request, request DN: " + reqmsg.getRequestDN(); log.error(msg); throw new SignRequestException(msg); } log.info("Received a SCEP/PKCS10 request for user: " + username + ", from host: " + remoteAddr); String authPwd = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPAUTHPWD); if (StringUtils.isNotEmpty(authPwd) && !StringUtils.equals(authPwd, "none")) { log.debug("Requiring authPwd in order to precess SCEP requests"); String pwd = reqmsg.getPassword(); if (!StringUtils.equals(authPwd, pwd)) { log.error("Wrong auth password received in SCEP request: " + pwd); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Auth pwd missmatch"); return; } log.debug("Request passed authPwd test."); } else { log.debug("Not requiring authPwd in order to precess SCEP requests"); } // Try to find the CA name from the issuerDN, if we can't find it (i.e. not defined in web.xml) we use the default String issuerDN = CertTools.stringToBCDNString(reqmsg.getIssuerDN()); String caName = ExtraConfiguration.instance().getString(issuerDN); if (StringUtils.isEmpty(caName)) { caName = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPDEFAULTCA); log.info("Did not find a CA name from issuerDN: " + issuerDN + ", using the default CA '" + caName + "'"); } else { log.debug("Found a CA name '" + caName + "' from issuerDN: " + issuerDN); } // Get altNames if we can find them String altNames = reqmsg.getRequestAltNames(); byte[] encoded = reqmsg.getCertificationRequest().getEncoded(); String pkcs10 = new String(Base64.encode(encoded, false)); // Create a pkcs10 request String certificateProfile = ExtraConfiguration.instance() .getString(ExtraConfiguration.SCEPCERTPROFILEKEY); String entityProfile = ExtraConfiguration.instance() .getString(ExtraConfiguration.SCEPENTITYPROFILEKEY); boolean createOrEditUser = ExtraConfiguration.instance() .getBoolean(ExtraConfiguration.SCEPEDITUSER); PKCS10Request req = new PKCS10Request(100, username, reqmsg.getRequestDN(), altNames, null, null, entityProfile, certificateProfile, caName, pkcs10); req.setCreateOrEditUser(createOrEditUser); SubMessages submessages = new SubMessages(); submessages.addSubMessage(req); msgHome.create(transId, submessages); reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider) .getResponseMessage(); } } if (reply == null) { // This is probably a getCert message? log.debug("Sending HttpServletResponse.SC_NOT_IMPLEMENTED (501) response"); response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Can not handle request"); return; } // Send back SCEP response, PKCS#7 which contains the end entity's certificate, or pending, or failure sendBinaryBytes(reply, response, "application/x-pki-message", null); } else if (operation.equals("GetCACert")) { // The response has the content type tagged as application/x-x509-ca-cert. // The body of the response is a DER encoded binary X.509 certificate. // For example: "Content-Type:application/x-x509-ca-cert\n\n"<BER-encoded X509> // IF we are not an RA, which in case we should return the same thing as GetCACertChain log.info("Got SCEP cert request for CA '" + message + "'"); if (chain != null) { if (chain.length > 1) { // We are an RA, so return the same as GetCACertChain, but with other content type getCACertChain(message, remoteAddr, response, alias, raks, false); } else { // The CA certificate is no 0 X509Certificate cert = (X509Certificate) chain[0]; if (chain.length > 1) { cert = (X509Certificate) chain[1]; } log.debug("Found cert with DN '" + cert.getSubjectDN().toString() + "'"); log.info("Sent certificate for CA '" + message + "' to SCEP client with ip " + remoteAddr); sendBinaryBytes(cert.getEncoded(), response, "application/x-x509-ca-cert", null); } } else { log.error("No CA certificates found"); response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found."); } } else if (operation.equals("GetCACertChain")) { // The response for GetCACertChain is a certificates-only PKCS#7 // SignedDatato carry the certificates to the end entity, with a // Content-Type of application/x-x509-ca-ra-cert-chain. log.info("Got SCEP cert chain request for CA '" + message + "'"); getCACertChain(message, remoteAddr, response, alias, raks, true); } else if (operation.equals("GetCACaps")) { // The response for GetCACaps is a <lf> separated list of capabilities /* "GetNextCACert" CA Supports the GetNextCACert message. "POSTPKIOperation" PKIOPeration messages may be sent via HTTP POST. "SHA-1" CA Supports the SHA-1 hashing algorithm in signatures and fingerprints. If present, the client SHOULD use SHA-1. If absent, the client MUST use MD5 to maintain backward compatability. "Renewal" Clients may use current certificate and key to authenticate an enrollment request for a new certificate. */ log.info("Got SCEP CACaps request for CA '" + message + "'"); response.setContentType("text/plain"); response.getOutputStream().print("POSTPKIOperation\nSHA-1"); } } catch (java.lang.ArrayIndexOutOfBoundsException ae) { log.error("Empty or invalid request received.", ae); // TODO: Send back proper Failure Response response.sendError(HttpServletResponse.SC_BAD_REQUEST, ae.getMessage()); } catch (Exception e) { log.error("Error in ScepRAServlet:", e); // TODO: Send back proper Failure Response response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private boolean checkPutPreconditions(HttpServletRequest req, HttpServletResponse resp) { if (req.getContentLength() <= 0) { resp.setStatus(HttpServletResponse.SC_LENGTH_REQUIRED); return false; }//ww w.j a v a 2s .co m if (req.getContentType() == null || !req.getContentType().startsWith("text/xml")) { resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return false; } if (req.getHeader("Content-Transfer-Encoding") != null || req.getHeader("Content-Encoding") != null || req.getHeader("Content-Base") != null || req.getHeader("Content-Location") != null || req.getHeader("Content-MD5") != null || req.getHeader("Content-Range") != null) { resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); return false; } return true; }
From source file:com.orange.api.atmosdav.AtmosDavServlet.java
/** * Process a PUT request for the specified resource. * * Note: PUT method currently does not support Content-Range parameter. * It will throw a 501 error if Content-Range is present in the header, * as expected by RFC./*from ww w . ja va 2s . com*/ * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { AtmosApi api = getAPIFromAuthent(req, resp); ObjectPath obj_path = getAtmosPath(getPathFromReq(req), api); UploadHelper up_helper = new UploadHelper(api.api); up_helper.setMinReadSize(UploadHelper.DEFAULT_BUFFSIZE); // first test if object exists AtmosType obj_type = getObjectType(getObjectMetadata(api.api, obj_path)); boolean partial = false; // RFC says we MUST reject request containing Content-Range if we don't support it if (req.getHeader("Content-Range") != null) { resp.sendError(resp.SC_NOT_IMPLEMENTED); return; } if (!partial) { if (obj_type == AtmosType.NON_EXISTENT) { up_helper.createObjectOnPath(obj_path, req.getInputStream(), null, null, false); resp.setStatus(HttpServletResponse.SC_CREATED); } else if (obj_type == AtmosType.REGULAR) { up_helper.updateObject(obj_path, req.getInputStream(), null, null, false); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); // Cannot PUT on a directory } } else { resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); // if (!exists) // api.createObjectOnPath(obj_path, null, null, null, null); // Extent extent = new Extent(range.start, range.length); // api.updateObject(obj_path, null, null, extent, content, null); } }
From source file:org.jahia.bin.Render.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp, RenderContext renderContext, URLResolver urlResolver) throws Exception { if (req.getParameter(JahiaPortalURLParserImpl.PORTLET_INFO) != null) { Resource resource = urlResolver.getResource(); renderContext.setMainResource(resource); JCRSiteNode site = resource.getNode().getResolveSite(); renderContext.setSite(site);//from w ww . j a v a 2 s. c o m doGet(req, resp, renderContext, resource, System.currentTimeMillis()); return; } Map<String, List<String>> parameters = new HashMap<String, List<String>>(); if (checkForUploadedFiles(req, resp, urlResolver.getWorkspace(), urlResolver.getLocale(), parameters, urlResolver)) { if (parameters.isEmpty()) { return; } } if (parameters.isEmpty()) { parameters = toParameterMapOfListOfString(req); } Action action; Resource resource = null; if (urlResolver.getPath().endsWith(".do") || isWebflowRequest(req)) { resource = urlResolver.getResource(); renderContext.setMainResource(resource); try { JCRSiteNode site = resource.getNode().getResolveSite(); renderContext.setSite(site); } catch (RepositoryException e) { logger.warn("Cannot get site for action context", e); } if (isWebflowRequest(req)) { action = webflowAction; } else { action = templateService.getActions().get(resource.getResolvedTemplate()); } } else { final String path = urlResolver.getPath(); String resourcePath = JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(null, urlResolver.getWorkspace(), urlResolver.getLocale(), new JCRCallback<String>() { public String doInJCR(JCRSessionWrapper session) throws RepositoryException { String resourcePath = path.endsWith("*") ? StringUtils.substringBeforeLast(path, "/") : path; do { try { session.getNode(resourcePath); break; } catch (PathNotFoundException e) { resourcePath = StringUtils.substringBeforeLast(resourcePath, "/"); } } while (resourcePath.contains("/")); return resourcePath; } }); resource = urlResolver.getResource(resourcePath + ".html"); renderContext.setMainResource(resource); try { JCRSiteNode site = resource.getNode().getResolveSite(); renderContext.setSite(site); } catch (RepositoryException e) { } action = defaultPostAction; } if (action == null) { if (urlResolver.getPath().endsWith(".do")) { logger.error("Couldn't resolve action named [" + resource.getResolvedTemplate() + "]"); } resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } else { doAction(req, resp, urlResolver, renderContext, resource, action, parameters); } }
From source file:com.vmware.identity.samlservice.AuthnRequestState.java
/** * Perform authentication if needed and prepare a Document with a saml token * in it. Should not throw, but will set ValidationResult on exception. - * 401 UNAUTHORIZED if more auth data is needed - Response:Responder, * Internal processing error for unexpected exceptions - ... * * @param tenant/*from w w w . j av a 2 s . c o m*/ * @return */ public Document authenticate(String tenant, AuthenticationFilter<AuthnRequestState> authenticator) { Document retval = null; log.debug("authenticate, tenant " + tenant); Validate.notNull(this.idmAccessor); Validate.notNull(this.authnRequest); Validate.notNull(authenticator); // authentication call try { this.idmAccessor.setTenant(tenant); authenticator.authenticate(this); } catch (SamlServiceException e) { // more auth data is required log.error("Caught Saml Service Exception from authenticate " + e.toString()); if (this.getValidationResult() == null || this.getValidationResult().isValid()) { this.validationResult = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized", null); } return null; } catch (Exception e) { // unexpected processing error log.error("Caught Exception from authenticate " + e.toString()); if (this.getValidationResult() == null || this.getValidationResult().isValid()) { this.validationResult = new ValidationResult(OasisNames.RESPONDER); } return null; } if (this.getPrincipalId() == null || this.getIdentityFormat() == null || this.getSessionId() == null) { // assume that user could not be authenticated and validation result // was set by other code return null; } // get our token authority try { if (!this.isProxying) { this.idmAccessor.setTenant(tenant); retval = createToken(); } } catch (SamlServiceException e) { log.error("Caught Saml Service Exception in creating token." + e); this.validationResult = new ValidationResult(OasisNames.RESPONDER); } catch (com.vmware.identity.saml.SystemException e) { log.error("Caught SystemException in creating token. ", e); if (e.getCause() instanceof IDMReferralException) { this.validationResult = new ValidationResult(HttpServletResponse.SC_NOT_IMPLEMENTED, "LdapReferralNotSupported", null); } else { this.validationResult = new ValidationResult(OasisNames.RESPONDER); } } return retval; }