List of usage examples for javax.servlet.http HttpServletResponse isCommitted
public boolean isCommitted();
From source file:org.cloudifysource.rest.controllers.ServiceController.java
/** * Exception handler for all of the internal server's exceptions. * * @param response/*from www . ja va2s . com*/ * The response object to edit, if not committed yet. * @param e * The exception that occurred, from which data is read for logging and for the response error message. * @throws IOException * Reporting failure to edit the response object */ @ExceptionHandler(Exception.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public void resolveDocumentNotFoundException(final HttpServletResponse response, final Exception e) throws IOException { if (response.isCommitted()) { logger.log(Level.WARNING, "Caught exception, but response already commited. Not sending error message based on exception", e); } else { String message; if (e instanceof AccessDeniedException || e instanceof BadCredentialsException) { message = "{\"status\":\"error\", \"error\":\"" + CloudifyErrorMessages.NO_PERMISSION_ACCESS_DENIED.getName() + "\"}"; logger.log(Level.INFO, e.getMessage(), e); } else { // Some sort of unhandled application exception. logger.log(Level.WARNING, "An unexpected error was thrown: " + e.getMessage(), e); final Map<String, Object> restErrorMap = RestUtils.verboseErrorStatus( CloudifyErrorMessages.GENERAL_SERVER_ERROR.getName(), ExceptionUtils.getStackTrace(e), e.getMessage()); message = new ObjectMapper().writeValueAsString(restErrorMap); } final ServletOutputStream outputStream = response.getOutputStream(); final byte[] messageBytes = message.getBytes(); outputStream.write(messageBytes); } }
From source file:org.nuxeo.ecm.platform.auth.saml.SAMLAuthenticationProvider.java
@Override public UserIdentificationInfo handleRetrieveIdentity(HttpServletRequest request, HttpServletResponse response) { HttpServletRequestAdapter inTransport = new HttpServletRequestAdapter(request); SAMLBinding binding = getBinding(inTransport); // Check if we support this binding if (binding == null) { return null; }// w w w .j a v a2 s .c o m HttpServletResponseAdapter outTransport = new HttpServletResponseAdapter(response, request.isSecure()); // Create and populate the context SAMLMessageContext context = new BasicSAMLMessageContext(); context.setInboundMessageTransport(inTransport); context.setOutboundMessageTransport(outTransport); populateLocalContext(context); // Decode the message try { binding.decode(context); } catch (org.opensaml.xml.security.SecurityException | MessageDecodingException e) { log.error("Error during SAML decoding", e); return null; } // Set Peer context info if needed try { if (context.getPeerEntityId() == null) { context.setPeerEntityId(getIdPDescriptor().getEntityID()); } if (context.getPeerEntityMetadata() == null) { context.setPeerEntityMetadata(getIdPDescriptor()); } if (context.getPeerEntityRole() == null) { context.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); } } catch (MetadataProviderException e) { // } // Check for a response processor for this profile AbstractSAMLProfile processor = getProcessor(context); if (processor == null) { log.warn("Unsupported profile encountered in the context " + context.getCommunicationProfileId()); return null; } // Set the communication profile context.setCommunicationProfileId(processor.getProfileIdentifier()); // Delegate handling the message to the processor SAMLObject message = context.getInboundSAMLMessage(); // Handle SLO // TODO - Try to handle IdP initiated SLO somewhere else if (processor instanceof SLOProfile) { SLOProfile slo = (SLOProfile) processor; try { // Handle SLO response if (message instanceof LogoutResponse) { slo.processLogoutResponse(context); // Handle SLO request } else if (message instanceof LogoutRequest) { SAMLCredential credential = getSamlCredential(request); slo.processLogoutRequest(context, credential); } } catch (SAMLException e) { log.debug("Error processing SAML message", e); } return null; } // Handle SSO SAMLCredential credential; try { credential = ((WebSSOProfile) processor).processAuthenticationResponse(context); } catch (SAMLException e) { log.error("Error processing SAML message", e); sendError(request, ERROR_AUTH); return null; } String userId = userResolver.findOrCreateNuxeoUser(credential); if (userId == null) { log.warn("Failed to resolve user with NameID \"" + credential.getNameID().getValue() + "\"."); sendError(request, ERROR_USER); return null; } // Store session id in a cookie if (credential.getSessionIndexes() != null && !credential.getSessionIndexes().isEmpty()) { String nameValue = credential.getNameID().getValue(); String nameFormat = credential.getNameID().getFormat(); String sessionId = credential.getSessionIndexes().get(0); addCookie(response, SAML_SESSION_KEY, sessionId + "|" + nameValue + "|" + nameFormat); } // Redirect to URL in relay state if any HttpSession session = request.getSession(!response.isCommitted()); if (session != null) { if (StringUtils.isNotEmpty(credential.getRelayState())) { session.setAttribute(NXAuthConstants.START_PAGE_SAVE_KEY, credential.getRelayState()); } } return new UserIdentificationInfo(userId, userId); }
From source file:io.druid.security.kerberos.KerberosAuthenticator.java
@Override public Filter getFilter() { return new AuthenticationFilter() { private Signer mySigner; @Override//ww w . j av a2s .c om public void init(FilterConfig filterConfig) throws ServletException { ClassLoader prevLoader = Thread.currentThread().getContextClassLoader(); try { // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader. // In case of druid since the class is actually loaded as an extension and filter init is done in main thread. // We need to set the classloader explicitly to extension class loader. Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader()); super.init(filterConfig); String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX); configPrefix = (configPrefix != null) ? configPrefix + "." : ""; Properties config = getConfiguration(configPrefix, filterConfig); String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET); if (signatureSecret == null) { signatureSecret = Long.toString(new Random().nextLong()); log.warn("'signature.secret' configuration not set, using a random value as secret"); } final byte[] secretBytes = StringUtils.toUtf8(signatureSecret); SignerSecretProvider signerSecretProvider = new SignerSecretProvider() { @Override public void init(Properties config, ServletContext servletContext, long tokenValidity) throws Exception { } @Override public byte[] getCurrentSecret() { return secretBytes; } @Override public byte[][] getAllSecrets() { return new byte[][] { secretBytes }; } }; mySigner = new Signer(signerSecretProvider); } finally { Thread.currentThread().setContextClassLoader(prevLoader); } } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper @Override protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException { AuthenticationToken token = null; String tokenStr = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) { tokenStr = cookie.getValue(); try { tokenStr = mySigner.verifyAndExtract(tokenStr); } catch (SignerException ex) { throw new AuthenticationException(ex); } break; } } } if (tokenStr != null) { token = AuthenticationToken.parse(tokenStr); if (!token.getType().equals(getAuthenticationHandler().getType())) { throw new AuthenticationException("Invalid AuthenticationToken type"); } if (token.isExpired()) { throw new AuthenticationException("AuthenticationToken expired"); } } return token; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; // If there's already an auth result, then we have authenticated already, skip this. if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) { filterChain.doFilter(request, response); return; } if (loginContext == null) { initializeKerberosLogin(); } String path = ((HttpServletRequest) request).getRequestURI(); if (isExcluded(path)) { filterChain.doFilter(request, response); } else { String clientPrincipal = null; try { Cookie[] cookies = httpReq.getCookies(); if (cookies == null) { clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request); } else { clientPrincipal = null; for (Cookie cookie : cookies) { if ("hadoop.auth".equals(cookie.getName())) { Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue()); if (matcher.matches()) { clientPrincipal = matcher.group(1); break; } } } } } catch (Exception ex) { clientPrincipal = null; } if (clientPrincipal != null) { request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, new AuthenticationResult(clientPrincipal, authorizerName, null)); } } doFilterSuper(request, response, filterChain); } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { boolean unauthorizedResponse = true; int errCode = HttpServletResponse.SC_UNAUTHORIZED; AuthenticationException authenticationEx = null; HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; boolean isHttps = "https".equals(httpRequest.getScheme()); try { boolean newToken = false; AuthenticationToken token; try { token = getToken(httpRequest); } catch (AuthenticationException ex) { log.warn("AuthenticationToken ignored: " + ex.getMessage()); // will be sent back in a 401 unless filter authenticates authenticationEx = ex; token = null; } if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) { if (token == null) { if (log.isDebugEnabled()) { log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest)); } token = getAuthenticationHandler().authenticate(httpRequest, httpResponse); if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) { token.setExpires(System.currentTimeMillis() + getValidity() * 1000); } newToken = true; } if (token != null) { unauthorizedResponse = false; if (log.isDebugEnabled()) { log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest), token.getUserName()); } final AuthenticationToken authToken = token; httpRequest = new HttpServletRequestWrapper(httpRequest) { @Override public String getAuthType() { return authToken.getType(); } @Override public String getRemoteUser() { return authToken.getUserName(); } @Override public Principal getUserPrincipal() { return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null; } }; if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) { String signedToken = mySigner.sign(token.toString()); createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), isHttps); } doFilter(filterChain, httpRequest, httpResponse); } } else { unauthorizedResponse = false; } } catch (AuthenticationException ex) { // exception from the filter itself is fatal errCode = HttpServletResponse.SC_FORBIDDEN; authenticationEx = ex; if (log.isDebugEnabled()) { log.debug("Authentication exception: " + ex.getMessage(), ex); } else { log.warn("Authentication exception: " + ex.getMessage()); } } if (unauthorizedResponse) { if (!httpResponse.isCommitted()) { createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps); // If response code is 401. Then WWW-Authenticate Header should be // present.. reset to 403 if not found.. if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) { errCode = HttpServletResponse.SC_FORBIDDEN; } if (authenticationEx == null) { // Don't send an error response here, unlike the base AuthenticationFilter implementation. // This request did not use Kerberos auth. // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow // other Authenticator implementations to check the request. filterChain.doFilter(request, response); } else { // Do send an error response here, we attempted Kerberos authentication and failed. httpResponse.sendError(errCode, authenticationEx.getMessage()); } } } } }; }
From source file:org.apache.roller.weblogger.ui.rendering.servlets.FeedServlet.java
/** * Handle GET requests for weblog feeds. *///from ww w .j a v a2 s . c om public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entering"); Weblog weblog = null; boolean isSiteWide = false; WeblogFeedRequest feedRequest = null; try { // parse the incoming request and extract the relevant data feedRequest = new WeblogFeedRequest(request); weblog = feedRequest.getWeblog(); if (weblog == null) { throw new WebloggerException("unable to lookup weblog: " + feedRequest.getWeblogHandle()); } // is this the site-wide weblog? isSiteWide = WebloggerRuntimeConfig.isSiteWideWeblog(feedRequest.getWeblogHandle()); } catch (Exception e) { // invalid feed request format or weblog doesn't exist log.debug("error creating weblog feed request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // determine the lastModified date for this content long lastModified = System.currentTimeMillis(); if (isSiteWide) { lastModified = siteWideCache.getLastModified().getTime(); } else if (weblog.getLastModified() != null) { lastModified = weblog.getLastModified().getTime(); } // Respond with 304 Not Modified if it is not modified. if (ModDateHeaderUtil.respondIfNotModified(request, response, lastModified)) { return; } // set last-modified date ModDateHeaderUtil.setLastModifiedHeader(response, lastModified); // set content type String accepts = request.getHeader("Accept"); String userAgent = request.getHeader("User-Agent"); if (WebloggerRuntimeConfig.getBooleanProperty("site.newsfeeds.styledFeeds") && accepts != null && accepts.indexOf("*/*") != -1 && userAgent != null && userAgent.startsWith("Mozilla")) { // client is a browser and feed style is enabled so we want // browsers to load the page rather than popping up the download // dialog, so we provide a content-type that browsers will display response.setContentType("text/xml"); } else if ("rss".equals(feedRequest.getFormat())) { response.setContentType("application/rss+xml; charset=utf-8"); } else if ("atom".equals(feedRequest.getFormat())) { response.setContentType("application/atom+xml; charset=utf-8"); } // generate cache key String cacheKey = null; if (isSiteWide) { cacheKey = siteWideCache.generateKey(feedRequest); } else { cacheKey = weblogFeedCache.generateKey(feedRequest); } // cached content checking CachedContent cachedContent = null; if (isSiteWide) { cachedContent = (CachedContent) siteWideCache.get(cacheKey); } else { cachedContent = (CachedContent) weblogFeedCache.get(cacheKey, lastModified); } if (cachedContent != null) { log.debug("HIT " + cacheKey); response.setContentLength(cachedContent.getContent().length); response.getOutputStream().write(cachedContent.getContent()); return; } else { log.debug("MISS " + cacheKey); } // validation. make sure that request input makes sense. boolean invalid = false; if (feedRequest.getLocale() != null) { // locale view only allowed if weblog has enabled it if (!feedRequest.getWeblog().isEnableMultiLang()) { invalid = true; } } if (feedRequest.getWeblogCategoryName() != null) { // category specified. category must exist. if (feedRequest.getWeblogCategory() == null) { invalid = true; } } else if (feedRequest.getTags() != null && feedRequest.getTags().size() > 0) { try { // tags specified. make sure they exist. WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); invalid = !wmgr.getTagComboExists(feedRequest.getTags(), (isSiteWide) ? null : weblog); } catch (WebloggerException ex) { invalid = true; } } if (invalid) { if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // do we need to force a specific locale for the request? if (feedRequest.getLocale() == null && !weblog.isShowAllLangs()) { feedRequest.setLocale(weblog.getLocale()); } // looks like we need to render content HashMap model = new HashMap(); String pageId = null; try { // determine what template to render with boolean siteWide = WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle()); if (siteWide && "entries".equals(feedRequest.getType()) && feedRequest.getTerm() != null) { pageId = "site-search-atom.vm"; } else if ("entries".equals(feedRequest.getType()) && feedRequest.getTerm() != null) { pageId = "feeds/weblog-search-atom.vm"; } else if (siteWide) { pageId = "site-" + feedRequest.getType() + "-" + feedRequest.getFormat() + ".vm"; } else { pageId = "weblog-" + feedRequest.getType() + "-" + feedRequest.getFormat() + ".vm"; } // populate the rendering model Map initData = new HashMap(); initData.put("parsedRequest", feedRequest); // define url strategy initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy()); // Load models for feeds String feedModels = WebloggerConfig.getProperty("rendering.feedModels"); ModelLoader.loadModels(feedModels, model, initData, true); // Load special models for site-wide blog if (siteWide) { String siteModels = WebloggerConfig.getProperty("rendering.siteModels"); ModelLoader.loadModels(siteModels, model, initData, true); } // Load weblog custom models ModelLoader.loadCustomModels(weblog, model, initData); // Load search models if search feed if ("entries".equals(feedRequest.getType()) && feedRequest.getTerm() != null) { ModelLoader.loadModels(SearchResultsFeedModel.class.getName(), model, initData, true); } } catch (WebloggerException ex) { log.error("ERROR loading model for page", ex); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // lookup Renderer we are going to use Renderer renderer = null; try { log.debug("Looking up renderer"); Template template = new StaticTemplate(pageId, "velocity"); renderer = RendererManager.getRenderer(template, MobileDeviceRepository.DeviceType.standard); } catch (Exception e) { // nobody wants to render my content :( // TODO: this log message has been disabled because it fills up // the logs with useless errors due to the fact that the way these // template ids are formed comes directly from the request and it // often gets bunk data causing invalid template ids. // at some point we should have better validation on the input so // that we can quickly dispatch invalid feed requests and only // get this far if we expect the template to be found //log.error("Couldn't find renderer for page "+pageId, e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // render content. use default size of about 24K for a standard page CachedContent rendererOutput = new CachedContent(24567); try { log.debug("Doing rendering"); renderer.render(model, rendererOutput.getCachedWriter()); // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); } catch (Exception e) { // bummer, error during rendering log.error("Error during rendering for page " + pageId, e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // post rendering process // flush rendered content to response log.debug("Flushing response output"); response.setContentLength(rendererOutput.getContent().length); response.getOutputStream().write(rendererOutput.getContent()); // cache rendered content. only cache if user is not logged in? log.debug("PUT " + cacheKey); if (isSiteWide) { siteWideCache.put(cacheKey, rendererOutput); } else { weblogFeedCache.put(cacheKey, rendererOutput); } log.debug("Exiting"); }
From source file:com.alfaariss.oa.profile.saml2.profile.sso.SingleLogout.java
private void processSAMLRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException { SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context = null; String sBinding = null;//from w w w.j a v a2 s . c o m try { //Decode message AbstractDecodingFactory decFactory = AbstractDecodingFactory.resolveInstance(servletRequest, servletResponse, _bindingProperties); if (decFactory == null) { _logger.debug("Decoding factory not created: Invalid request"); throw new MessageDecodingException("Could not determine binding"); } SAMLMessageDecoder decoder = decFactory.getDecoder(); sBinding = decoder.getBindingURI(); _logger.debug("Binding URI: " + sBinding); context = decFactory.getContext(); context.setLocalEntityId(_sEntityID); context.setLocalEntityMetadata(_entityDescriptor); //Decode request try { decoder.decode(context); } catch (SecurityException e) { _logger.debug("Could not decode inbound message due to security exception", e); throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID); } //verify saml message in request SignableSAMLObject requestMessage = context.getInboundSAMLMessage(); if (_logger.isDebugEnabled()) { if (requestMessage != null) logXML(requestMessage); } if (requestMessage instanceof LogoutRequest) { //DD <LogoutRequest> signing is forced by code for HTTP POST or Redirect binding [saml-profiles-2.0-os r1223]. boolean bMandatorySinging = sBinding.equals(SAMLConstants.SAML2_POST_BINDING_URI) || sBinding.equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI); HTTPInTransport inTransport = (HTTPInTransport) context.getInboundMessageTransport(); String sigParam = inTransport.getParameterValue("Signature"); boolean bSigned = !DatatypeHelper.isEmpty(sigParam) || requestMessage.isSigned(); if (bMandatorySinging && !bSigned) { _logger.debug("LogoutRequest MUST be signed if the HTTP POST or Redirect binding is used"); throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID); } //synchronous bindings: The requester MUST authenticate itself //to the identity provider, either by signing the //<LogoutRequest> or using any other binding-supported //mechanism. //DD <LogoutRequest> signing is not forced by code for synchronous bindings, but should be enabled by configuration in a production environment LogoutRequest lr = (LogoutRequest) requestMessage; String sReason = lr.getReason(); processLogoutRequest(servletRequest, servletResponse, context, sBinding, sReason); } else { _logger.debug("Unsupported SAML message in request"); throw new MessageDecodingException("Unsupported SAML message"); } } catch (StatusException e) //SAML processing error { _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null, servletRequest.getRemoteAddr(), e.getRequestorID(), this, e.getMessage())); sendResponse(context, servletRequest, servletResponse, sBinding); } catch (MessageDecodingException e) //Binding processing error { _logger.debug("Decoding error", e); _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.REQUEST_INVALID, null, servletRequest.getRemoteAddr(), null, this, null)); if (sBinding != null && sBinding.equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) { SOAP11Utils.sendSOAPFault(context, RequestorEvent.REQUEST_INVALID); } else { try { if (!servletResponse.isCommitted()) servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST); } catch (IOException e1) { _logger.warn("Could not send response", e1); } } } catch (SAML2SecurityException e) //The message does not meet the required security constraints { _logger.debug("Security error", e); _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null, servletRequest.getRemoteAddr(), null, this, "Security Fault")); //DD Security error -> Return a "403 Forbidden" response try { if (!servletResponse.isCommitted()) servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN); } catch (IOException e1) { _logger.warn("Could not send response", e1); } } catch (OAException e) //Internal error { throw e; } catch (Exception e) { _logger.fatal("Could not process SAML request message", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } }
From source file:org.sakaiproject.cheftool.VelocityPortletPaneledAction.java
/** * Dispatch to a "do" method based on reflection. Override ToolServlet to support the old "build" ways. * /*from w ww . j a v a2s . co m*/ * @param methodBase * The base name of the method to call. * @param methodExt * The end name of the method to call. * @param req * The HttpServletRequest. * @param res * The HttpServletResponse */ protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res) throws ToolException { // the context wraps our real vm attribute set Context context = (Context) req.getAttribute(ATTR_CONTEXT); // other wrappers VelocityPortlet portlet = (VelocityPortlet) req.getAttribute(ATTR_PORTLET); JetspeedRunData rundata = (JetspeedRunData) req.getAttribute(ATTR_RUNDATA); // "panel" is used to identify the specific panel in the URL context.put("param_panel", ActionURL.PARAM_PANEL); // set the "action" context.put("action", getState(req).getAttribute(STATE_ACTION)); // set the "pid" context.put("param_pid", ActionURL.PARAM_PID); context.put("pid", getPid(req)); String collectionId = contentHostingService .getSiteCollection(ToolManager.getCurrentPlacement().getContext()); context.put(CONTEXT_SITE_COLLECTION_ID, collectionId); // indicate which WYSIWYG editor to use in legacy tools String editor = EditorConfiguration.getWysiwigEditor(); context.put("sakai_editor", editor); context.put("editorConfig", new EditorConfiguration()); UsageSession session = UsageSessionService.getSession(); if (session != null) { // SAK-23047 Set the proper country code in the chef_start generated markup String userId = session.getUserId(); ResourceLoader rl = new ResourceLoader(userId); Locale locale = rl.getLocale(); String languageCode = locale.getLanguage(); String countryCode = locale.getCountry(); if (countryCode != null && countryCode.length() > 0) { languageCode += "_" + countryCode; } context.put("language", languageCode); context.put("dir", rl.getOrientation(locale)); String browserId = session.getBrowserId(); if (UsageSession.WIN_IE.equals(browserId) || UsageSession.WIN_MZ.equals(browserId) || UsageSession.WIN_NN.equals(browserId) || UsageSession.MAC_MZ.equals(browserId) || UsageSession.MAC_NN.equals(browserId)) { context.put("wysiwyg", "true"); } } try { // dispatch panels (Note: panel must be in the URL, not the body - this is not from the parsed params) String panel = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(ActionURL.PARAM_PANEL); /* * TODO: float support from before... // special case for floating and the Main panel: if (LAYOUT_MAIN.equals(panel)) { if (handleFloat(portlet, context, rundata, state)) return; } */ if (panel == null || "".equals(panel) || "null".equals(panel)) { // default to main panel panel = LAYOUT_MAIN; } else { // sanitize value panel = panel.replaceAll("[\r\n]", ""); } context.put("panel", panel); // form a method name "build" + panel name (first letter caps) + "PanelContext" // buildPanelContext( VelocityPortlet, Context, ControllerState, RunData ) Class[] types = new Class[4]; types[0] = VelocityPortlet.class; types[1] = Context.class; types[2] = RunData.class; types[3] = SessionState.class; // let our extension classes override the pannel name for the method String methodName = panelMethodName(panel); Method method = getClass().getMethod(methodName, types); Object[] args = new Object[4]; args[0] = portlet; args[1] = context; args[2] = rundata; args[3] = getState(req); String template = (String) method.invoke(this, args); // if the method did something like a redirect, we don't want to try to put out any more if (!res.isCommitted()) { if (template == null) { // pick the template for the panel - the base + "-" + panel template = (String) getContext(rundata).get("template") + "-" + panel; } // the vm file needs a path and an extension template = "/vm/" + template + ".vm"; // setup for old style alert StringBuilder buf = new StringBuilder(); String msg = (String) getState(req).getAttribute(STATE_MESSAGE); if (msg != null) { buf.append(msg); getState(req).removeAttribute(STATE_MESSAGE); } Alert alert = getAlert(req); if (!alert.isEmpty()) { buf.append(alert.peekAlert()); setVmReference(ALERT_ATTR, alert, req); } if (buf.length() > 0) { setVmReference("alertMessage", buf.toString(), req); } // setup for old style validator setVmReference("validator", m_validator, req); // set standard no-cache headers setNoCacheHeaders(res); // add a standard header includeVm("chef_header.vm", req, res); includeVm(template, req, res); // add a standard footer includeVm("chef_footer.vm", req, res); } } catch (NoSuchMethodException e) { try { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "NoSuchMethodException for panel name"); } catch (IOException e1) { // ignore } } catch (IllegalAccessException e) { throw new ToolException(e); } catch (InvocationTargetException e) { throw new ToolException(e); } catch (ServletException e) { throw new ToolException(e); } }
From source file:org.apache.roller.weblogger.ui.rendering.servlets.SearchServlet.java
/** * Handle GET requests for weblog pages. *//* www. ja va 2s. c om*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entering"); Weblog weblog = null; WeblogSearchRequest searchRequest = null; // first off lets parse the incoming request and validate it try { searchRequest = new WeblogSearchRequest(request); // now make sure the specified weblog really exists weblog = WebloggerFactory.getWeblogger().getWeblogManager() .getWeblogByHandle(searchRequest.getWeblogHandle(), Boolean.TRUE); } catch (Exception e) { // invalid search request format or weblog doesn't exist log.debug("error creating weblog search request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Get the deviceType from user agent MobileDeviceRepository.DeviceType deviceType = MobileDeviceRepository.getRequestType(request); // for previews we explicitly set the deviceType attribute if (request.getParameter("type") != null) { deviceType = request.getParameter("type").equals("standard") ? MobileDeviceRepository.DeviceType.standard : MobileDeviceRepository.DeviceType.mobile; } // do we need to force a specific locale for the request? if (searchRequest.getLocale() == null && !weblog.isShowAllLangs()) { searchRequest.setLocale(weblog.getLocale()); } // lookup template to use for rendering ThemeTemplate page = null; try { // try looking for a specific search page page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_SEARCH); // if not found then fall back on default page if (page == null) { page = weblog.getTheme().getDefaultTemplate(); } // if still null then that's a problem if (page == null) { throw new WebloggerException("Could not lookup default page " + "for weblog " + weblog.getHandle()); } } catch (Exception e) { log.error("Error getting default page for weblog " + weblog.getHandle(), e); } // set the content type response.setContentType("text/html; charset=utf-8"); // looks like we need to render content Map model = new HashMap(); try { PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, "", false, 8192, true); // populate the rendering model Map initData = new HashMap(); initData.put("request", request); initData.put("pageContext", pageContext); // this is a little hacky, but nothing we can do about it // we need the 'weblogRequest' to be a pageRequest so other models // are properly loaded, which means that searchRequest needs its // own custom initData property aside from the standard weblogRequest. // possible better approach is make searchRequest extend pageRequest. WeblogPageRequest pageRequest = new WeblogPageRequest(); pageRequest.setWeblogHandle(searchRequest.getWeblogHandle()); pageRequest.setWeblogCategoryName(searchRequest.getWeblogCategoryName()); initData.put("parsedRequest", pageRequest); initData.put("searchRequest", searchRequest); // define url strategy initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy()); // Load models for pages String searchModels = WebloggerConfig.getProperty("rendering.searchModels"); ModelLoader.loadModels(searchModels, model, initData, true); // Load special models for site-wide blog if (WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle())) { String siteModels = WebloggerConfig.getProperty("rendering.siteModels"); ModelLoader.loadModels(siteModels, model, initData, true); } // Load weblog custom models ModelLoader.loadCustomModels(weblog, model, initData); // ick, gotta load pre-3.0 model stuff as well :( ModelLoader.loadOldModels(model, request, response, pageContext, pageRequest, WebloggerFactory.getWeblogger().getUrlStrategy()); // manually add search model again to support pre-3.0 weblogs Model searchModel = new SearchResultsModel(); searchModel.init(initData); model.put("searchResults", searchModel); } catch (WebloggerException ex) { log.error("Error loading model objects for page", ex); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // Development only. Reload if theme has been modified if (themeReload && !weblog.getEditorTheme().equals(WeblogTemplate.ACTION_CUSTOM) && (searchRequest.getPathInfo() == null || searchRequest.getPathInfo() != null && !searchRequest.getPathInfo().endsWith(".css"))) { try { ThemeManager manager = WebloggerFactory.getWeblogger().getThemeManager(); boolean reloaded = manager.reLoadThemeFromDisk(weblog.getEditorTheme()); if (reloaded) { if (WebloggerRuntimeConfig.isSiteWideWeblog(searchRequest.getWeblogHandle())) { SiteWideCache.getInstance().clear(); } else { WeblogPageCache.getInstance().clear(); } I18nMessages.reloadBundle(weblog.getLocaleInstance()); } } catch (Exception ex) { log.error("ERROR - reloading theme " + ex); } } // lookup Renderer we are going to use Renderer renderer = null; try { log.debug("Looking up renderer"); renderer = RendererManager.getRenderer(page, deviceType); } catch (Exception e) { // nobody wants to render my content :( log.error("Couldn't find renderer for rsd template", e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // render content CachedContent rendererOutput = new CachedContent(4096); try { log.debug("Doing rendering"); renderer.render(model, rendererOutput.getCachedWriter()); // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); } catch (Exception e) { // bummer, error during rendering log.error("Error during rendering for rsd template", e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // post rendering process // flush rendered content to response log.debug("Flushing response output"); response.setContentLength(rendererOutput.getContent().length); response.getOutputStream().write(rendererOutput.getContent()); log.debug("Exiting"); }
From source file:org.openhab.ui.cometvisu.servlet.CometVisuServlet.java
/** * Service./*from www. jav a 2s. c o m*/ */ private final void phpService(File file, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Env env = null; WriteStream ws = null; QuercusHttpServletRequest req = new QuercusHttpServletRequestImpl(request); QuercusHttpServletResponse res = new QuercusHttpServletResponseImpl(response); try { Path path = getPath(file, req); logger.info("phpService path: " + path); QuercusPage page; try { page = engine.getQuercus().parse(path); } catch (FileNotFoundException e) { // php/2001 logger.debug(e.toString(), e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } ws = openWrite(response); // php/2002 // for non-Resin containers // for servlet filters that do post-request work after Quercus ws.setDisableCloseSource(true); // php/6006 ws.setNewlineString("\n"); QuercusContext quercus = engine.getQuercus(); env = quercus.createEnv(page, ws, req, res); // php/815d env.setPwd(path.getParent()); logger.info("setting user dir to " + path.getParent().getNativePath()); System.setProperty("user.dir", path.getParent().getNativePath()); quercus.setServletContext(new QuercusServletContextImpl(_servletContext)); try { env.start(); // php/2030, php/2032, php/2033 // Jetty hides server classes from web-app // http://docs.codehaus.org/display/JETTY/Classloading // // env.setGlobalValue("request", env.wrapJava(request)); // env.setGlobalValue("response", env.wrapJava(response)); // env.setGlobalValue("servletContext", // env.wrapJava(_servletContext)); StringValue prepend = quercus.getIniValue("auto_prepend_file").toStringValue(env); if (prepend.length() > 0) { Path prependPath = env.lookup(prepend); if (prependPath == null) env.error(L.l("auto_prepend_file '{0}' not found.", prepend)); else { QuercusPage prependPage = engine.getQuercus().parse(prependPath); prependPage.executeTop(env); } } env.executeTop(); StringValue append = quercus.getIniValue("auto_append_file").toStringValue(env); if (append.length() > 0) { Path appendPath = env.lookup(append); if (appendPath == null) env.error(L.l("auto_append_file '{0}' not found.", append)); else { QuercusPage appendPage = engine.getQuercus().parse(appendPath); appendPage.executeTop(env); } } // return; } catch (QuercusExitException e) { throw e; } catch (QuercusErrorException e) { throw e; } catch (QuercusLineRuntimeException e) { logger.debug(e.toString(), e); ws.println(e.getMessage()); // return; } catch (QuercusValueException e) { logger.debug(e.toString(), e); ws.println(e.toString()); // return; } catch (StackOverflowError e) { RuntimeException myException = new RuntimeException( L.l("StackOverflowError at {0}", env.getLocation()), e); throw myException; } catch (Throwable e) { if (response.isCommitted()) e.printStackTrace(ws.getPrintWriter()); ws = null; throw e; } finally { if (env != null) env.close(); // don't want a flush for an exception if (ws != null && env != null && env.getDuplex() == null) ws.close(); System.setProperty("user.dir", defaultUserDir); } } catch (QuercusDieException e) { // normal exit logger.trace(e.getMessage(), e); } catch (QuercusExitException e) { // normal exit logger.trace(e.getMessage(), e); } catch (QuercusErrorException e) { // error exit logger.error(e.getMessage(), e); } catch (RuntimeException e) { throw e; } catch (Throwable e) { handleThrowable(response, e); } }
From source file:org.apache.druid.security.kerberos.KerberosAuthenticator.java
@Override public Filter getFilter() { return new AuthenticationFilter() { private Signer mySigner; @Override//from w w w.j a v a 2 s . c o m public void init(FilterConfig filterConfig) throws ServletException { ClassLoader prevLoader = Thread.currentThread().getContextClassLoader(); try { // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader. // In case of druid since the class is actually loaded as an extension and filter init is done in main thread. // We need to set the classloader explicitly to extension class loader. Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader()); super.init(filterConfig); String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX); configPrefix = (configPrefix != null) ? configPrefix + "." : ""; Properties config = getConfiguration(configPrefix, filterConfig); String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET); if (signatureSecret == null) { signatureSecret = Long.toString(ThreadLocalRandom.current().nextLong()); log.warn("'signature.secret' configuration not set, using a random value as secret"); } final byte[] secretBytes = StringUtils.toUtf8(signatureSecret); SignerSecretProvider signerSecretProvider = new SignerSecretProvider() { @Override public void init(Properties config, ServletContext servletContext, long tokenValidity) { } @Override public byte[] getCurrentSecret() { return secretBytes; } @Override public byte[][] getAllSecrets() { return new byte[][] { secretBytes }; } }; mySigner = new Signer(signerSecretProvider); } finally { Thread.currentThread().setContextClassLoader(prevLoader); } } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper @Override protected AuthenticationToken getToken(HttpServletRequest request) throws AuthenticationException { AuthenticationToken token = null; String tokenStr = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) { tokenStr = cookie.getValue(); try { tokenStr = mySigner.verifyAndExtract(tokenStr); } catch (SignerException ex) { throw new AuthenticationException(ex); } break; } } } if (tokenStr != null) { token = AuthenticationToken.parse(tokenStr); if (!token.getType().equals(getAuthenticationHandler().getType())) { throw new AuthenticationException("Invalid AuthenticationToken type"); } if (token.isExpired()) { throw new AuthenticationException("AuthenticationToken expired"); } } return token; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; // If there's already an auth result, then we have authenticated already, skip this. if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) { filterChain.doFilter(request, response); return; } if (loginContext == null) { initializeKerberosLogin(); } String path = ((HttpServletRequest) request).getRequestURI(); if (isExcluded(path)) { filterChain.doFilter(request, response); } else { String clientPrincipal = null; try { Cookie[] cookies = httpReq.getCookies(); if (cookies == null) { clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request); } else { clientPrincipal = null; for (Cookie cookie : cookies) { if ("hadoop.auth".equals(cookie.getName())) { Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue()); if (matcher.matches()) { clientPrincipal = matcher.group(1); break; } } } } } catch (Exception ex) { clientPrincipal = null; } if (clientPrincipal != null) { request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, new AuthenticationResult(clientPrincipal, authorizerName, name, null)); } } doFilterSuper(request, response, filterChain); } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { boolean unauthorizedResponse = true; int errCode = HttpServletResponse.SC_UNAUTHORIZED; AuthenticationException authenticationEx = null; HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; boolean isHttps = "https".equals(httpRequest.getScheme()); try { boolean newToken = false; AuthenticationToken token; try { token = getToken(httpRequest); } catch (AuthenticationException ex) { log.warn("AuthenticationToken ignored: " + ex.getMessage()); // will be sent back in a 401 unless filter authenticates authenticationEx = ex; token = null; } if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) { if (token == null) { if (log.isDebugEnabled()) { log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest)); } token = getAuthenticationHandler().authenticate(httpRequest, httpResponse); if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) { token.setExpires(System.currentTimeMillis() + getValidity() * 1000); } newToken = true; } if (token != null) { unauthorizedResponse = false; if (log.isDebugEnabled()) { log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest), token.getUserName()); } final AuthenticationToken authToken = token; httpRequest = new HttpServletRequestWrapper(httpRequest) { @Override public String getAuthType() { return authToken.getType(); } @Override public String getRemoteUser() { return authToken.getUserName(); } @Override public Principal getUserPrincipal() { return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null; } }; if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) { String signedToken = mySigner.sign(token.toString()); tokenToAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), !token.isExpired() && token.getExpires() > 0, isHttps); request.setAttribute(SIGNED_TOKEN_ATTRIBUTE, tokenToCookieString(signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), !token.isExpired() && token.getExpires() > 0, isHttps)); } // Since this request is validated also set DRUID_AUTHENTICATION_RESULT request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, new AuthenticationResult(token.getName(), authorizerName, name, null)); doFilter(filterChain, httpRequest, httpResponse); } } else { unauthorizedResponse = false; } } catch (AuthenticationException ex) { // exception from the filter itself is fatal errCode = HttpServletResponse.SC_FORBIDDEN; authenticationEx = ex; if (log.isDebugEnabled()) { log.debug(ex, "Authentication exception: " + ex.getMessage()); } else { log.warn("Authentication exception: " + ex.getMessage()); } } if (unauthorizedResponse) { if (!httpResponse.isCommitted()) { tokenToAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, false, isHttps); // If response code is 401. Then WWW-Authenticate Header should be // present.. reset to 403 if not found.. if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) { errCode = HttpServletResponse.SC_FORBIDDEN; } if (authenticationEx == null) { // Don't send an error response here, unlike the base AuthenticationFilter implementation. // This request did not use Kerberos auth. // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow // other Authenticator implementations to check the request. filterChain.doFilter(request, response); } else { // Do send an error response here, we attempted Kerberos authentication and failed. httpResponse.sendError(errCode, authenticationEx.getMessage()); } } } } }; }