List of usage examples for javax.servlet.http HttpServletRequest getServerPort
public int getServerPort();
From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java
@Override public Configuration getConfiguration() throws IllegalArgumentException { if (firstTime) { firstTime = false;//from www. j a v a2 s . c om HttpServletRequest req = this.getThreadLocalRequest(); Integer identifiedPort = req.getServerPort(); if (identifiedPort != null && identifiedPort != 0) { CLIENT_WEBSITE_PORT = Integer.toString(identifiedPort); } String identifiedHostname = req.getServerName(); if (identifiedHostname == null || identifiedHostname.length() == 0 || identifiedHostname.equals("0.0.0.0")) { try { identifiedHostname = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { identifiedHostname = "127.0.0.1"; } } CLIENT_WEBSITE_HOSTNAME = identifiedHostname; if (CLIENT_WEBSITE_PORT.equals("8888")) { CLIENT_WEBSITE_CODESVR_PORT = "9997"; } else if (CLIENT_WEBSITE_PORT.equals("8777")) { CLIENT_WEBSITE_CODESVR_PORT = "9777"; } else { CLIENT_WEBSITE_CODESVR_PORT = "9777"; } } Configuration config = new Configuration(); config.put(Configuration.CLIENT_WEBSITE_HOSTNAME_KEY, CLIENT_WEBSITE_HOSTNAME); config.put(Configuration.CLIENT_WEBSITE_PORT_KEY, CLIENT_WEBSITE_PORT); config.put(Configuration.CLIENT_WEBSITE_CODESVR_PORT_KEY, CLIENT_WEBSITE_CODESVR_PORT); config.put(Configuration.CLIENT_ID_KEY, CLIENT_ID); config.put(Configuration.CLIENT_SECRET_KEY, CLIENT_SECRET); return config; }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarCreateNewAccountHtml.java
protected void sendConfirmationEMail(HttpServletRequest request, ICFAstSecUserObj confirmUser, ICFAstClusterObj cluster) throws IOException, MessagingException, NamingException { final String S_ProcName = "sendConfirmationEMail"; Properties props = System.getProperties(); String clusterDescription = cluster.getRequiredDescription(); String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI().toString(); int lastSlash = thisURI.lastIndexOf('/'); String baseURI = thisURI.substring(0, lastSlash); UUID confirmationUUID = confirmUser.getOptionalEMailConfirmationUuid(); String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n" + "<p>\n" + "You requested a new account for login " + confirmUser.getRequiredLoginId() + " with " + clusterDescription + ".\n" + "<p>" + "Please click on the following link to confirm your email address:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">" + baseURI + "/CFAstSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "</A>\n" + "<p>" + "Or click on the following link to cancel the request for a new account:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">" + baseURI + "/CFAstSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; CFAstSMWarUtil warUtil = new CFAstSMWarUtil(); warUtil.sendEMailToUser(confirmUser, "You requested an account with " + clusterDescription + "?", msgBody); }
From source file:org.apache.catalina.authenticator.BasicAuthenticator.java
/** * Authenticate the user making this request, based on the specified * login configuration. Return <code>true</code> if any specified * constraint has been satisfied, or <code>false</code> if we have * created a response challenge already. * * @param request Request we are processing * @param response Response we are creating * @param config Login configuration describing how authentication * should be performed//from ww w .j a va 2 s. c o m * * @exception IOException if an input/output error occurs */ public boolean authenticate(HttpRequest request, HttpResponse response, LoginConfig config) throws IOException { // Have we already authenticated someone? Principal principal = ((HttpServletRequest) request.getRequest()).getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) log.debug("Already authenticated '" + principal.getName() + "'"); // Associate the session with any existing SSO session if (ssoId != null) associate(ssoId, getSession(request, true)); return (true); } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) return true; } // Validate any credentials already included with this request HttpServletRequest hreq = (HttpServletRequest) request.getRequest(); HttpServletResponse hres = (HttpServletResponse) response.getResponse(); String authorization = request.getAuthorization(); String username = parseUsername(authorization); String password = parsePassword(authorization); principal = context.getRealm().authenticate(username, password); if (principal != null) { register(request, response, principal, Constants.BASIC_METHOD, username, password); return (true); } // Send an "unauthorized" response and an appropriate challenge String realmName = config.getRealmName(); if (realmName == null) realmName = hreq.getServerName() + ":" + hreq.getServerPort(); // if (log.isDebugEnabled()) // log.debug("Challenging for realm '" + realmName + "'"); hres.setHeader("WWW-Authenticate", "Basic realm=\"" + realmName + "\""); hres.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // hres.flushBuffer(); return (false); }
From source file:eu.supersede.fe.rest.NotificationRest.java
@RequestMapping("") public List<Notification> getByUserId(Authentication authentication, HttpServletRequest request, @RequestParam(defaultValue = "true") Boolean toRead) { String scheme;//from w w w. j a v a 2 s . c o m String host; String port; if (request.getHeader("x-forwarded-proto") != null || request.getHeader("x-forwarded-host") != null || request.getHeader("x-forwarded-port") != null) { scheme = request.getHeader("x-forwarded-proto") != null ? request.getHeader("x-forwarded-proto") : "http"; host = request.getHeader("x-forwarded-host") != null ? request.getHeader("x-forwarded-host") : request.getServerName(); port = request.getHeader("x-forwarded-port") != null ? request.getHeader("x-forwarded-port") : null; } else { scheme = request.getScheme(); host = request.getServerName(); port = new Integer(request.getServerPort()).toString(); } String baseUrl = port != null ? scheme + "://" + host + ":" + port + "/#/" : scheme + "://" + host + "/#/"; DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal(); User u = users.getOne(currentUser.getUserId()); List<Notification> ns; if (toRead) { ns = notifications.findByUserAndReadOrderByCreationTimeDesc(u, !toRead); } else { ns = notifications.findByUserOrderByCreationTimeDesc(u); } for (Notification n : ns) { if (n.getLink() != null && !n.getLink().equals("")) { try { URI uri = new URI(n.getLink()); if (!uri.isAbsolute()) { n.setLink(baseUrl + n.getLink()); } } catch (URISyntaxException e) { log.debug("Error inside link: " + e.getMessage()); } } } return ns; }
From source file:org.archive.wayback.webapp.AccessPoint.java
/** * Construct an absolute URL that points to the root of the context that * recieved the request, including a trailing "/". * /* w ww.j a va 2 s.c o m*/ * @return String absolute URL pointing to the Context root where the * request was revieved. */ private String getAbsoluteContextPrefix(HttpServletRequest httpRequest, boolean useRequestServer) { StringBuilder prefix = new StringBuilder(); prefix.append(WaybackConstants.HTTP_URL_PREFIX); String waybackPort = null; if (useRequestServer) { prefix.append(httpRequest.getLocalName()); waybackPort = String.valueOf(httpRequest.getLocalPort()); } else { prefix.append(httpRequest.getServerName()); waybackPort = String.valueOf(httpRequest.getServerPort()); } if (!waybackPort.equals(WaybackConstants.HTTP_DEFAULT_PORT)) { prefix.append(":").append(waybackPort); } String contextPath = getContextPath(httpRequest); prefix.append(contextPath); return prefix.toString(); }
From source file:com.baoqilai.core.sso.CasAuthenticationEntryPoint.java
public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response, final AuthenticationException authenticationException) throws IOException, ServletException { StringBuilder tempLoginUrl = new StringBuilder(); StringBuilder serverUrl = new StringBuilder(); StringBuilder clientUrl = new StringBuilder(); System.out.println("???"); tempLoginUrl.append(servletRequest.getScheme()).append("://"); tempLoginUrl.append(servletRequest.getServerName()); if (serverPort != null && !"".equals(serverPort)) { serverUrl.append(tempLoginUrl).append(":").append(serverPort); }/*from ww w .ja v a 2 s . c o m*/ serverUrl.append("/cas/login"); loginUrl = serverUrl.toString(); if (clientPort != null && !"".equals(clientPort)) { clientUrl.append(tempLoginUrl).append(":").append(servletRequest.getServerPort()); clientUrl.append(servletRequest.getContextPath()); clientUrl.append("/j_spring_cas_security_check"); serviceProperties.setService(clientUrl.toString()); } final String urlEncodedService = createServiceUrl(servletRequest, response); final String redirectUrl = createRedirectUrl(urlEncodedService); preCommence(servletRequest, response); response.sendRedirect(redirectUrl); }
From source file:be.fedict.eid.idp.protocol.openid.AbstractOpenIDProtocolService.java
@SuppressWarnings("unchecked") public ReturnResponse handleReturnResponse(HttpSession httpSession, String userId, Map<String, Attribute> attributes, SecretKey secretKey, PublicKey publicKey, String rpTargetUrl, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("handleReturnResponse"); ServerManager serverManager = getServerManager(request); RealmVerifier realmVerifier = serverManager.getRealmVerifier(); ParameterList parameterList = retrieveParameterList(httpSession); AuthRequest authRequest = AuthRequest.createAuthRequest(parameterList, realmVerifier); String location = "https://" + request.getServerName(); if (request.getServerPort() != 443) { location += ":" + request.getServerPort(); }/*from ww w . ja v a2 s . c om*/ location += "/eid-idp/endpoints/" + getPath(); String userIdentifier = location + "?" + userId; LOG.debug("user identifier: " + userIdentifier); UrlIdentifier urlIdentifier = new UrlIdentifier(userIdentifier); userIdentifier = urlIdentifier.getIdentifier(); LOG.debug("normalized user identifier: " + userIdentifier); Message message = serverManager.authResponse(parameterList, userIdentifier, userIdentifier, true, false); if (message instanceof AuthSuccess) { AuthSuccess authSuccess = (AuthSuccess) message; // Attribute Exchange Extension if (authRequest.hasExtension(AxMessage.OPENID_NS_AX)) { MessageExtension messageExtension = authRequest.getExtension(AxMessage.OPENID_NS_AX); if (messageExtension instanceof FetchRequest) { FetchRequest fetchRequest = (FetchRequest) messageExtension; Map<String, String> requiredAttributes = fetchRequest.getAttributes(true); Map<String, String> optionalAttributes = fetchRequest.getAttributes(false); FetchResponse fetchResponse = FetchResponse.createFetchResponse(); // required attributes for (Map.Entry<String, String> requiredAttribute : requiredAttributes.entrySet()) { String alias = requiredAttribute.getKey(); String typeUri = requiredAttribute.getValue(); LOG.debug("required attribute alias: " + alias); LOG.debug("required attribute typeUri: " + typeUri); String value = findAttribute(typeUri, attributes); if (null != value) { fetchResponse.addAttribute(alias, typeUri, value); } } // optional attributes for (Map.Entry<String, String> optionalAttribute : optionalAttributes.entrySet()) { String alias = optionalAttribute.getKey(); String typeUri = optionalAttribute.getValue(); LOG.debug("optional attribute alias: " + alias); LOG.debug("optional attribute typeUri: " + typeUri); String value = findAttribute(typeUri, attributes); if (null != value) { fetchResponse.addAttribute(alias, typeUri, value); } } authSuccess.addExtension(fetchResponse, "ax"); authSuccess.setSignExtensions(new String[] { AxMessage.OPENID_NS_AX }); } } // PaPe extension PapeResponse papeResponse = PapeResponse.createPapeResponse(); papeResponse.setAuthTime(new Date()); switch (getAuthenticationFlow()) { case IDENTIFICATION: papeResponse.setAuthPolicies(PapeResponse.PAPE_POLICY_PHISHING_RESISTANT); break; case AUTHENTICATION: papeResponse.setAuthPolicies(PapeResponse.PAPE_POLICY_MULTI_FACTOR_PHYSICAL); break; case AUTHENTICATION_WITH_IDENTIFICATION: papeResponse.addAuthPolicy(PapeResponse.PAPE_POLICY_PHISHING_RESISTANT); papeResponse.addAuthPolicy(PapeResponse.PAPE_POLICY_MULTI_FACTOR_PHYSICAL); break; } authSuccess.addExtension(papeResponse, "pape"); /* * We manually sign the auth response as we also want to add our own * attributes. */ serverManager.sign(authSuccess); } String destinationUrl = rpTargetUrl; if (null == destinationUrl) { destinationUrl = authRequest.getReturnTo(); } LOG.debug("destination URL: " + destinationUrl); Map<String, String> parameters = message.getParameterMap(); ReturnResponse returnResponse = new ReturnResponse(destinationUrl); for (String paramKey : parameters.keySet()) { String paramValue = parameters.get(paramKey); returnResponse.addAttribute(paramKey, paramValue); } return returnResponse; }
From source file:com.evon.injectTemplate.InjectTemplateFilter.java
private void loadTemplates(HttpServletRequest request) throws ServletException { if (templateLodaded) { return;/*w w w.j a v a 2 s . c o m*/ } templateLodadedStarted = true; try { for (TemplateBean template : TemplateConfig.templates) { if (template.path.startsWith(";")) { template.path = template.path.substring(1); } boolean firstCharIsUnecessarySeparator = template.path.startsWith("/") || template.path.startsWith("\\"); template.path = (firstCharIsUnecessarySeparator) ? template.path.substring(1) : template.path; loadHTMLInfo(template, request.getServerName(), request.getServerPort(), request.getProtocol().contains("HTTPS"), request); } } catch (Exception e) { templateLodaded = false; templateLodadedStarted = false; throw new ServletException("Exception:" + e.getMessage(), e); } templateLodaded = true; }
From source file:com.netflix.genie.web.controllers.JobRestControllerUnitTests.java
/** * Make sure directory forwarding happens when all conditions are met. * * @throws IOException on error//from w w w .j a v a2s. co m * @throws ServletException on error * @throws GenieException on error */ @Test public void canHandleForwardJobOutputRequestWithError() throws IOException, ServletException, GenieException { this.jobsProperties.getForwarding().setEnabled(true); final String jobId = UUID.randomUUID().toString(); final String forwardedFrom = null; final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.doNothing().when(this.genieResourceHttpRequestHandler).handleRequest(request, response); final String jobHostName = UUID.randomUUID().toString(); Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(jobHostName); //Mock parts of the http request final String http = "http"; Mockito.when(request.getScheme()).thenReturn(http); final int port = 8080; Mockito.when(request.getServerPort()).thenReturn(port); final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString(); Mockito.when(request.getRequestURI()).thenReturn(requestURI); Mockito.when(request.getHeaderNames()).thenReturn(null); final String requestUrl = UUID.randomUUID().toString(); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl)); final int errorCode = 404; Mockito.when(this.restTemplate.execute(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())) .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); this.controller.getJobOutput(jobId, forwardedFrom, request, response); Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(Mockito.eq(jobId)); Mockito.verify(this.restTemplate, Mockito.times(1)).execute(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); Mockito.verify(response, Mockito.times(1)).sendError(Mockito.eq(errorCode), Mockito.anyString()); Mockito.verify(this.genieResourceHttpRequestHandler, Mockito.never()).handleRequest(request, response); }
From source file:cn.bc.web.util.DebugUtils.java
public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) { @SuppressWarnings("rawtypes") Enumeration e;//from ww w . j av a 2s . c o m String name; StringBuffer html = new StringBuffer(); //session HttpSession session = request.getSession(); html.append("<div><b>session:</b></div><ul>"); html.append(createLI("Id", session.getId())); html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString())); html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString())); //session:attributes e = session.getAttributeNames(); html.append("<li>attributes:<ul>\r\n"); while (e.hasMoreElements()) { name = (String) e.nextElement(); html.append(createLI(name, String.valueOf(session.getAttribute(name)))); } html.append("</ul></li>\r\n"); html.append("</ul>\r\n"); //request html.append("<div><b>request:</b></div><ul>"); html.append(createLI("URL", request.getRequestURL().toString())); html.append(createLI("QueryString", request.getQueryString())); html.append(createLI("Method", request.getMethod())); html.append(createLI("CharacterEncoding", request.getCharacterEncoding())); html.append(createLI("ContentType", request.getContentType())); html.append(createLI("Protocol", request.getProtocol())); html.append(createLI("RemoteAddr", request.getRemoteAddr())); html.append(createLI("RemoteHost", request.getRemoteHost())); html.append(createLI("RemotePort", request.getRemotePort() + "")); html.append(createLI("RemoteUser", request.getRemoteUser())); html.append(createLI("ServerName", request.getServerName())); html.append(createLI("ServletPath", request.getServletPath())); html.append(createLI("ServerPort", request.getServerPort() + "")); html.append(createLI("Scheme", request.getScheme())); html.append(createLI("LocalAddr", request.getLocalAddr())); html.append(createLI("LocalName", request.getLocalName())); html.append(createLI("LocalPort", request.getLocalPort() + "")); html.append(createLI("Locale", request.getLocale().toString())); //request:headers e = request.getHeaderNames(); html.append("<li>Headers:<ul>\r\n"); while (e.hasMoreElements()) { name = (String) e.nextElement(); html.append(createLI(name, request.getHeader(name))); } html.append("</ul></li>\r\n"); //request:parameters e = request.getParameterNames(); html.append("<li>Parameters:<ul>\r\n"); while (e.hasMoreElements()) { name = (String) e.nextElement(); html.append(createLI(name, request.getParameter(name))); } html.append("</ul></li>\r\n"); html.append("</ul>\r\n"); //response html.append("<div><b>response:</b></div><ul>"); html.append(createLI("CharacterEncoding", response.getCharacterEncoding())); html.append(createLI("ContentType", response.getContentType())); html.append(createLI("BufferSize", response.getBufferSize() + "")); html.append(createLI("Locale", response.getLocale().toString())); html.append("<ul>\r\n"); return html; }