List of usage examples for javax.servlet.http HttpServletRequest getScheme
public String getScheme();
From source file:cn.tiup.httpproxy.ProxyServlet.java
private void setXForwardedProtoHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest) { String headerName = "X-Forwarded-Proto"; String newHeader = servletRequest.getScheme(); String existingHeader = servletRequest.getHeader(headerName); if (existingHeader != null) { newHeader = existingHeader + ", " + newHeader; }//ww w . j a v a 2 s .co m proxyRequest.setHeader("X-Forwarded-Proto", newHeader); }
From source file:fr.paris.lutece.portal.web.user.AdminLoginJspBean.java
/** * Process the login of user//from w ww . ja va 2 s. c o m * * @param request The HTTP Request * @return The Jsp URL of the process result * @throws Exception The exception */ public String doLogin(HttpServletRequest request) throws Exception { // recovery of the login attributes String strAccessCode = request.getParameter(Parameters.ACCESS_CODE); String strPassword = request.getParameter(Parameters.PASSWORD); if (request.getScheme().equals(CONSTANT_HTTP) && AppHTTPSService.isHTTPSSupportEnabled()) { return JSP_URL_ADMIN_LOGIN; } // Encryption password strPassword = AdminUserService.encryptPassword(strPassword); String strLoginUrl = AdminAuthenticationService.getInstance().getLoginPageUrl(); try { AdminAuthenticationService.getInstance().loginUser(request, strAccessCode, strPassword); } catch (FailedLoginException ex) { // Creating a record of connections log UserLog userLog = new UserLog(); userLog.setAccessCode(strAccessCode); userLog.setIpAddress(SecurityUtil.getRealIp(request)); userLog.setDateLogin(new java.sql.Timestamp(new java.util.Date().getTime())); userLog.setLoginStatus(UserLog.LOGIN_DENIED); // will be inserted only if access denied UserLogHome.addUserLog(userLog); return AdminMessageService.getMessageUrl(request, Messages.MESSAGE_AUTH_FAILURE, strLoginUrl, AdminMessage.TYPE_STOP); } catch (LoginException ex) { AppLogService.error("Error during connection for user access code :" + strAccessCode, ex); return AdminMessageService.getMessageUrl(request, Messages.MESSAGE_AUTH_FAILURE, strLoginUrl, AdminMessage.TYPE_STOP); } UrlItem url; AdminUser user = AdminUserHome.findUserByLogin(strAccessCode); if (user.isPasswordReset()) { String strRedirectUrl = AdminMessageService.getMessageUrl(request, Messages.MESSAGE_USER_MUST_CHANGE_PASSWORD, JSP_URL_MODIFY_DEFAULT_USER_PASSOWRD, AdminMessage.TYPE_ERROR); url = new UrlItem(strRedirectUrl); } else { String strNextUrl = AdminAuthenticationService.getInstance().getLoginNextUrl(request); if (StringUtils.isNotBlank(strNextUrl)) { url = new UrlItem(strNextUrl); } else { url = AppPathService.resolveRedirectUrl(request, AppPathService.getAdminMenuUrl()); } } return url.getUrl(); }
From source file:org.eclipse.orion.internal.server.servlets.site.SiteConfigurationResourceHandler.java
/** * Changes <code>site</code>'s hosting status to the desired status. The desired status * is given by the <code>HostingStatus.Status</code> field of the <code>requestJson</code>. * @param site The site configuration to act on. * @param requestJson The request body, which may or may not have a HostingStatus field. * @throws CoreException If a bogus value was found for <code>HostingStatus.Status</code>, * or if the hosting service threw an exception when trying to change the status. *//*from w w w. j a v a 2s . com*/ private void changeHostingStatus(HttpServletRequest req, HttpServletResponse resp, JSONObject requestJson, UserInfo user, SiteInfo site) throws CoreException { JSONObject hostingStatus = requestJson.optJSONObject(SiteConfigurationConstants.KEY_HOSTING_STATUS); if (hostingStatus == null) return; String status = hostingStatus.optString(SiteConfigurationConstants.KEY_HOSTING_STATUS_STATUS); try { if ("started".equalsIgnoreCase(status)) { //$NON-NLS-1$ String editServer = req.getScheme() + "://" + req.getHeader("Host"); //$NON-NLS-1$ //$NON-NLS-2$ getHostingService().start(site, user, editServer); } else if ("stopped".equalsIgnoreCase(status)) { //$NON-NLS-1$ getHostingService().stop(site, user); } else if (status == null) { // No Status; ignore it } else { // Status has a bogus value throw new CoreException(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Status not understood: {0}", status), null)); } } catch (NoMoreHostsException e) { // Give a JSON response object instead of stack trace throw new CoreException(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e)); } }
From source file:org.apache.ode.axis2.service.DeploymentBrowser.java
public boolean doFilter(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String requestURI = request.getRequestURI(); final int deplUri = requestURI.indexOf("/deployment"); if (deplUri > 0) { final String root = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + requestURI.substring(0, deplUri); int offset = requestURI.length() > (deplUri + 11) ? 1 : 0; final String[] segments = requestURI.substring(deplUri + 11 + offset).split("/"); if (segments.length == 0 || segments[0].length() == 0) { renderHtml(response, "ODE Deployment Browser", new DocBody() { public void render(Writer out) throws IOException { out.write("<p><a href=\"bundles/\">Deployed Bundles</a></p>"); out.write("<p><a href=\"services/\">Process Services</a></p>"); out.write("<p><a href=\"processes/\">Process Definitions</a></p>"); }// w ww. j av a 2 s .c o m }); } else if (segments.length > 0) { if ("services".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Services Implemented by Your Processes", new DocBody() { public void render(Writer out) throws IOException { for (Object serviceName : _config.getServices().keySet()) if (!"Version".equals(serviceName)) { AxisService service = _config.getService(serviceName.toString()); // The service can be one of the dynamically registered ODE services, a process // service or an unknown service deployed in the same Axis2 instance. String url = null; if ("DeploymentService".equals(service.getName()) || "InstanceManagement".equals(service.getName()) || "ProcessManagement".equals(service.getName())) url = service.getName(); else if (service.getFileName() != null) { String relative = bundleUrlFor(service.getFileName().getFile()); if (relative != null) url = root + relative; else url = root + "/services/" + service.getName() + "?wsdl"; } out.write("<p><a href=\"" + url + "\">" + serviceName + "</a></p>"); String axis2wsdl = root + "/processes/" + serviceName + "?wsdl"; out.write("<ul><li>Axis2 WSDL: <a href=\"" + axis2wsdl + "\">" + axis2wsdl + "</a></li>"); out.write( "<li>Endpoint: " + (root + "/processes/" + serviceName) + "</li>"); Iterator iter = service.getOperations(); ArrayList<String> ops = new ArrayList<String>(); while (iter.hasNext()) ops.add(((AxisOperation) iter.next()).getName().getLocalPart()); out.write("<li>Operations: " + StringUtils.join(ops, ", ") + "</li></ul>"); } } }); } else { final String serviceName = requestURI.substring(deplUri + 12 + 9); final AxisService axisService = _config.getService(serviceName); if (axisService != null) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { if ("InstanceManagement".equals(serviceName) || "ProcessManagement".equals(serviceName)) write(out, new File(_appRoot, "pmapi.wsdl").getPath()); else if (requestURI.indexOf("pmapi.xsd") > 0) write(out, new File(_appRoot, "pmapi.xsd").getPath()); else if ("DeploymentService".equals(serviceName)) write(out, new File(_appRoot, "deploy.wsdl").getPath()); else write(out, axisService.getFileName().getFile()); } }); } else { renderHtml(response, "Service Not Found", new DocBody() { public void render(Writer out) throws IOException { out.write("<p>Couldn't find service " + serviceName + "</p>"); } }); } } } else if ("processes".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Deployed Processes", new DocBody() { public void render(Writer out) throws IOException { for (QName process : _store.getProcesses()) { String url = root + bundleUrlFor( _store.getProcessConfiguration(process).getBpelDocument()); String[] nameVer = process.getLocalPart().split("-"); out.write("<p><a href=\"" + url + "\">" + nameVer[0] + "</a> (v" + nameVer[1] + ")"); out.write(" - " + process.getNamespaceURI() + "</p>"); } } }); } } else if ("bundles".equals(segments[0])) { if (segments.length == 1) { renderHtml(response, "Deployment Bundles", new DocBody() { public void render(Writer out) throws IOException { for (String bundle : _store.getPackages()) out.write("<p><a href=\"" + bundle + "\">" + bundle + "</a></p>"); } }); } else if (segments.length == 2) { renderHtml(response, "Files in Bundle " + segments[1], new DocBody() { public void render(Writer out) throws IOException { List<QName> processes = _store.listProcesses(segments[1]); if (processes != null && processes.size() > 0) { List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); for (File file : files) { String relativePath = file.getPath() .substring(file.getPath().indexOf("processes") + 10) .replaceAll("\\\\", "/"); out.write( "<p><a href=\"" + relativePath + "\">" + relativePath + "</a></p>"); } } else { out.write("<p>Couldn't find bundle " + segments[1] + "</p>"); } } }); } else if (segments.length > 2) { List<QName> processes = _store.listProcesses(segments[1]); if (processes != null && processes.size() > 0) { List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); for (final File file : files) { String relativePath = requestURI.substring(deplUri + 12 + 9 + segments[1].length()); // replace slashes with the correct file separator so the match below is not always false relativePath = relativePath.replace('/', File.separatorChar); if (file.getPath().endsWith(relativePath)) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { write(out, file.getPath()); } }); return true; } } } else { renderHtml(response, "No Bundle Found", new DocBody() { public void render(Writer out) throws IOException { out.write("<p>Couldn't find bundle " + segments[2] + "</p>"); } }); } } } else if ("getBundleDocs".equals(segments[0])) { if (segments.length == 1) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getBundleDocsResponse>"); out.write("<error>Not enough args..</error>"); out.write("</getBundleDocsResponse>"); } }); } else if (segments.length == 2) { final String bundleName = segments[1]; final List<QName> processes = _store.listProcesses(bundleName); if (processes != null) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getBundleDocsResponse><name>" + bundleName + "</name>"); //final List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles(); //final String pid = _store.getProcessConfiguration(processes.get(0)).getProcessId().toString(); for (final QName process : processes) { List<File> files = _store.getProcessConfiguration(process).getFiles(); String pid = _store.getProcessConfiguration(process).getProcessId() .toString(); out.write("<process><pid>" + pid + "</pid>"); for (final File file : files) { if (file.getPath().endsWith(".wsdl")) { String relativePath = file.getPath().substring( _store.getDeployDir().getCanonicalPath().length() + 1) .replace(File.separatorChar, '/'); out.write("<wsdl>" + relativePath + "</wsdl>"); } if (file.getPath().endsWith(".bpel")) { String relativePath = file.getPath().substring( _store.getDeployDir().getCanonicalPath().length() + 1) .replace(File.separatorChar, '/'); out.write("<bpel>" + relativePath + "</bpel>"); } } out.write("</process>"); } out.write("</getBundleDocsResponse>"); } }); } } } else if ("getProcessDefinition".equals(segments[0])) { if (segments.length == 1) { renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getProcessDefinitionResponse>"); out.write("<error>Not enough args..</error>"); out.write("</getProcessDefinitionResponse>"); } }); } else if (segments.length == 2) { String processName = segments[1]; for (QName process : _store.getProcesses()) { String[] nameVer = process.getLocalPart().split("-"); if (processName.equals(nameVer[0])) { final String url = root + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument()); renderXml(response, new DocBody() { public void render(Writer out) throws IOException { out.write("<getProcessDefinition>"); out.write("<url>" + url + "</url>"); out.write("</getProcessDefinition>"); } }); } } } } } return true; } return false; }
From source file:org.eclipse.gyrex.http.jetty.internal.app.ApplicationHandlerCollection.java
private void doHandle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { // check async requests // get map//w ww. j ava 2s . co m final UrlMap map = urlMap.get(); if (map == null) { if (JettyDebug.handlers) { LOG.debug("null URL map, no handler matched!"); } return; } // perform lookup final MappedEntry<Handler> entry = map.getMatch(request.getScheme(), request.getServerName(), request.getServerPort(), target); if (entry == null) { if (JettyDebug.handlers) { LOG.debug("no matching handler for {}", request.getRequestURL()); } return; } final String oldContextPath = baseRequest.getContextPath(); try { // adjust context path and execute final String mapped = entry.getMapped(); baseRequest.setContextPath((mapped != null) && (mapped.length() > 0) ? mapped : URIUtil.SLASH); // get handler final Handler handler = entry.getValue(); if (JettyDebug.handlers) { LOG.debug("found matching handler for {}: {}", request.getRequestURL(), handler); LOG.debug("adjusted context path for {} to {}", request.getRequestURL(), baseRequest.getContextPath()); } // lazy start handler if (!handler.isStarted()) { if (JettyDebug.handlers) { LOG.debug("lazy start of handler {}", handler); } try { handler.start(); } catch (final Exception e) { if (Platform.inDebugMode()) { LOG.debug("Exception starting handler {}. {}", new Object[] { handler, ExceptionUtils.getRootCauseMessage(e), e }); throw new IllegalStateException( String.format("Failed to start registered handler '%s' for mapping '%s'. %s", handler, mapped, ExceptionUtils.getRootCauseMessage(e)), e); } else { LOG.warn("Exception starting handler {}. {}", new Object[] { handler, ExceptionUtils.getRootCauseMessage(e) }); throw new IllegalStateException("Application Not Available"); } } } // handle handler.handle(target, baseRequest, request, response); } finally { baseRequest.setContextPath(oldContextPath); } }
From source file:org.eclipse.orion.server.authentication.formpersona.PersonaHelper.java
/** * If the request appears to be from a loopback interface, returns an audience constructed from the server name. * Otherwise returns null./*from w ww. ja v a 2 s . co m*/ */ private String getLoopbackAudience(HttpServletRequest req) throws PersonaException { try { String serverName = req.getServerName(); try { // First ensure the request is coming from the IP of a loopback device if (isLoopback(InetAddress.getByName(req.getLocalAddr()))) { // Verify that the server name resolves to a loopback device, to prevent spoofing/proxying InetAddress addr = InetAddress.getByName(serverName); if (isLoopback(addr)) return new URI(req.getScheme(), req.getRemoteUser(), serverName, req.getServerPort(), null, null, null).toString(); } } catch (UnknownHostException e) { // Bogus serverName, ignore } } catch (URISyntaxException e) { throw new PersonaException(e); } return null; }
From source file:org.kew.rmf.reconciliation.ws.ReconciliationServiceController.java
/** * Retrieve reconciliation service metadata. *//* ww w.j a v a 2 s . c o m*/ @RequestMapping(value = "/reconcile/{configName}", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=UTF-8") public ResponseEntity<String> getMetadata(HttpServletRequest request, @PathVariable String configName, @RequestParam(value = "callback", required = false) String callback, Model model) throws JsonGenerationException, JsonMappingException, IOException { logger.info("{}: Get Metadata request", configName); String myUrl = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() == 80 ? "" : (":" + request.getServerPort())); String basePath = servletContext.getContextPath() + "/reconcile/" + configName; Metadata metadata; try { metadata = reconciliationService.getMetadata(configName); } catch (MatchExecutionException e) { return new ResponseEntity<String>(e.toString(), HttpStatus.NOT_FOUND); } if (metadata != null) { String metadataJson = jsonMapper.writeValueAsString(metadata).replace("LOCAL", myUrl).replace("BASE", basePath); return new ResponseEntity<String>(wrapResponse(callback, metadataJson), HttpStatus.OK); } return null; }
From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java
/** * This method is copied from hadoop auth lib, code added for error handling and fallback to other auth methods * * If the request has a valid authentication token it allows the request to continue to the target resource, * otherwise it triggers an authentication sequence using the configured {@link org.apache.hadoop.security.authentication.server.AuthenticationHandler}. * * @param request the request object. * @param response the response object. * @param filterChain the filter chain object. * * @throws IOException thrown if an IO error occurred. * @throws ServletException thrown if a processing error occurred. *///from ww w .j a v a2 s. c o m public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChainWrapper, 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()); AuthenticationHandler authHandler = getAuthenticationHandler(); 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 (authHandler.managementOperation(token, httpRequest, httpResponse)) { if (token == null) { if (LOG.isDebugEnabled()) { LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest)); } token = authHandler.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 [{}] user [{}] 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 = signer.sign(token.toString()); createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), isHttps); } filterChainWrapper.doFilter(httpRequest, httpResponse); } } else { unauthorizedResponse = false; } } catch (AuthenticationException ex) { // exception from the filter itself is fatal errCode = HttpServletResponse.SC_FORBIDDEN; authenticationEx = ex; LOG.warn("Authentication exception: {}", ex.getMessage(), ex); } 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(KerberosAuthenticator.WWW_AUTHENTICATE))) { errCode = HttpServletResponse.SC_FORBIDDEN; } if (authenticationEx == null) { // added this code for atlas error handling and fallback if (!supportKeyTabBrowserLogin && isBrowser(httpRequest.getHeader("User-Agent"))) { filterChain.doFilter(request, response); } else { boolean chk = true; Collection<String> headerNames = httpResponse.getHeaderNames(); for (String headerName : headerNames) { String value = httpResponse.getHeader(headerName); if (headerName.equalsIgnoreCase("Set-Cookie") && value.startsWith("ATLASSESSIONID")) { chk = false; break; } } String authHeader = httpRequest.getHeader("Authorization"); if (authHeader == null && chk) { filterChain.doFilter(request, response); } else if (authHeader != null && authHeader.startsWith("Basic")) { filterChain.doFilter(request, response); } } } else { httpResponse.sendError(errCode, authenticationEx.getMessage()); } } } }