List of usage examples for javax.servlet.http HttpServletRequest getServerName
public String getServerName();
From source file:org.mitre.ptmatchadapter.service.ServerAuthorizationService.java
/** * Process a request to create a Server Authorization (i.e., request to grant * ptmatchadapter authorization to access a particular fhir server) * //from w w w . ja v a2 s. co m * @param serverAuth * @param reqHdrs * @param respHdrs * @return */ private final ServerAuthorization processServerAuthRequest(ServerAuthorization serverAuth, @Headers Map<String, Object> reqHdrs, @OutHeaders Map<String, Object> respHdrs) { final String serverUrl = serverAuth.getServerUrl(); final String accessToken = serverAuth.getAccessToken(); // if request doesn't contain a server URL, it is an error if (serverUrl == null || serverUrl.isEmpty()) { respHdrs.put(Exchange.HTTP_RESPONSE_CODE, 400); // BAD REQUEST return null; } // else if the request body doesn't include an access token, redirect user // to an authorization server else if (accessToken == null || accessToken.isEmpty()) { // create a state identifier final String stateKey = newStateKey(); respHdrs.put(STATE_PARAM, stateKey); final AuthorizationRequestInfo requestInfo = new AuthorizationRequestInfo(); requestInfo.put(SERVER_AUTH, serverAuth); sessionData.put(stateKey, requestInfo); // Construct URL we will invoke on authorization server // GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz // &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb final StringBuilder authUrl = new StringBuilder(100); if (getAuthorizationServer() != null) { authUrl.append(getAuthorizationServer()); } authUrl.append(getAuthorizationEndpoint()); authUrl.append("?"); authUrl.append("response_type=code&client_id="); try { authUrl.append(URLEncoder.encode(getClientId(), "UTF-8")); authUrl.append("&"); authUrl.append(STATE_PARAM); authUrl.append("="); authUrl.append(stateKey); authUrl.append("&redirect_uri="); final HttpServletRequest req = (HttpServletRequest) reqHdrs.get(Exchange.HTTP_SERVLET_REQUEST); final String redirectUri = URLEncoder.encode( getClientAuthRedirectUri(req.getScheme(), req.getServerName(), req.getServerPort()), "UTF-8"); authUrl.append(redirectUri); // we need to provide redirect uri with access token request, so save it requestInfo.put("redirectUri", redirectUri); } catch (UnsupportedEncodingException e) { // Should never happen, which is why I wrap all above once LOG.error("Usupported encoding used on authorization redirect", e); } respHdrs.put(Exchange.HTTP_RESPONSE_CODE, 302); // FOUND respHdrs.put(Exchange.CONTENT_TYPE, "text/plain"); respHdrs.put("Location", authUrl.toString()); return null; } else { LOG.warn("NOT IMPLEMENTED"); return null; } }
From source file:de.appsolve.padelcampus.utils.LoginUtil.java
public void updateLoginCookie(HttpServletRequest request, HttpServletResponse response) { Player player = sessionUtil.getUser(request); if (player != null) { UUID cookieUUID = UUID.randomUUID(); UUID cookieValue = UUID.randomUUID(); String cookieValueHash = BCrypt.hashpw(cookieValue.toString(), BCrypt.gensalt()); LoginCookie loginCookie = new LoginCookie(); loginCookie.setUUID(cookieUUID.toString()); loginCookie.setPlayerUUID(player.getUUID()); loginCookie.setLoginCookieHash(cookieValueHash); loginCookie.setValidUntil(new LocalDate().plusYears(1)); loginCookieDAO.saveOrUpdate(loginCookie); Cookie cookie = new Cookie(COOKIE_LOGIN_TOKEN, cookieUUID.toString() + ":" + cookieValue.toString()); cookie.setDomain(request.getServerName()); cookie.setMaxAge(ONE_YEAR_SECONDS); cookie.setPath("/"); response.addCookie(cookie);/* w w w. jav a 2 s . c o m*/ } }
From source file:edu.isi.wings.portal.classes.config.Config.java
private void createDefaultPortalConfig(HttpServletRequest request) { String server = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); String storageDir = null;//from w ww . j a v a 2 s. c om String home = System.getProperty("user.home"); if (home != null && !home.equals("")) storageDir = home + File.separator + ".wings" + File.separator + "storage"; else storageDir = System.getProperty("java.io.tmpdir") + File.separator + "wings" + File.separator + "storage"; if (!new File(storageDir).mkdirs()) System.err.println("Cannot create storage directory: " + storageDir); PropertyListConfiguration config = new PropertyListConfiguration(); config.addProperty("storage.local", storageDir); config.addProperty("storage.tdb", storageDir + File.separator + "TDB"); config.addProperty("server", server); File loc1 = new File("/usr/bin/dot"); File loc2 = new File("/usr/local/bin/dot"); config.addProperty("graphviz", loc2.exists() ? loc2.getAbsolutePath() : loc1.getAbsolutePath()); config.addProperty("ontology.data", ontdirurl + "/data.owl"); config.addProperty("ontology.component", ontdirurl + "/component.owl"); config.addProperty("ontology.workflow", ontdirurl + "/workflow.owl"); config.addProperty("ontology.execution", ontdirurl + "/execution.owl"); config.addProperty("ontology.resource", ontdirurl + "/resource.owl"); this.addEngineConfig(config, new ExeEngine("Local", LocalExecutionEngine.class.getCanonicalName(), ExeEngine.Type.BOTH)); this.addEngineConfig(config, new ExeEngine("Distributed", DistributedExecutionEngine.class.getCanonicalName(), ExeEngine.Type.BOTH)); /*this.addEngineConfig(config, new ExeEngine("OODT", OODTExecutionEngine.class.getCanonicalName(), ExeEngine.Type.PLAN)); this.addEngineConfig(config, new ExeEngine("Pegasus", PegasusExecutionEngine.class.getCanonicalName(), ExeEngine.Type.PLAN));*/ try { config.save(this.configFile); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.myjerry.evenstar.web.feed.FeedController.java
public ModelAndView view(HttpServletRequest request, HttpServletResponse response) throws Exception { String uri = request.getRequestURI(); FeedFormat feedFormat = null;/*from www . j a va2 s. com*/ // strip off the 'feeds/' from the URI uri = uri.substring(7); int extIndex = uri.lastIndexOf("."); if (extIndex != -1) { String extension = uri.substring(extIndex + 1); uri = uri.substring(0, extIndex); feedFormat = FeedFormat.getFeedFormat(extension); } if (feedFormat == null) { // bad request response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return null; } Long blogID = this.blogService.getBlogIDForServerName(request.getServerName()); if (blogID == null) { // try and see if the URI contains the blog ID String alias = uri; int index = uri.indexOf("/"); if (index != -1) { alias = uri.substring(0, index); } Long id = this.blogService.getBlogIDForAlias(alias); if (id != null) { blogID = id; uri = uri.substring(index + 1); } else { // just can't do anything now // no feed found response.setStatus(HttpServletResponse.SC_NOT_FOUND); return null; } } // decipher the type of feed if ("posts/default".equals(uri)) { return blogPostsFeed(feedFormat, blogID); } else if ("comments/default".equals(uri)) { return blogCommentsFeed(feedFormat, blogID); } else if (uri.startsWith("posts/")) { // try and get the post ID from this uri = uri.substring(6); int index = uri.indexOf("/"); if (index != -1) { Long postID = StringUtils.getLong(uri.substring(0, index)); if (postID != null) { uri = uri.substring(index + 1); if ("default".equals(uri)) { return blogPostFeed(feedFormat, blogID, postID); } else if ("comments".equals(uri)) { return blogPostCommentFeed(feedFormat, blogID, postID); } } } } response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return null; }
From source file:com.pivotal.gemfire.tools.pulse.internal.controllers.PulseController.java
@RequestMapping(value = "/pulseVersion", method = RequestMethod.GET) public void pulseVersion(HttpServletRequest request, HttpServletResponse response) throws IOException { // json object to be sent as response JSONObject responseJSON = new JSONObject(); try {/* w ww.j a v a2s . c o m*/ // Reference to repository Repository repository = Repository.get(); // set pulse web app url String pulseWebAppUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); repository.setPulseWebAppUrl(pulseWebAppUrl); // Response responseJSON.put("pulseVersion", PulseController.pulseVersion.getPulseVersion()); responseJSON.put("buildId", PulseController.pulseVersion.getPulseBuildId()); responseJSON.put("buildDate", PulseController.pulseVersion.getPulseBuildDate()); responseJSON.put("sourceDate", PulseController.pulseVersion.getPulseSourceDate()); responseJSON.put("sourceRevision", PulseController.pulseVersion.getPulseSourceRevision()); responseJSON.put("sourceRepository", PulseController.pulseVersion.getPulseSourceRepository()); } catch (JSONException eJSON) { LOGGER.logJSONError(eJSON, new String[] { "pulseVersionData :" + PulseController.pulseVersion }); } catch (Exception e) { if (LOGGER.fineEnabled()) { LOGGER.fine("Exception Occured : " + e.getMessage()); } } // Send json response response.getOutputStream().write(responseJSON.toString().getBytes()); }
From source file:com.worldsmostinterestinginfographic.servlet.CallbackServlet.java
/** * Servlet to handle initial callback in response to an authorization request. * * Will check for the presence of an authorization code. If present, will attempt to make an access token request * using the authorization code. This is all done in accordance with the authorization code grant workflow in the * OAuth 2 specification [RFC 6749]. If no authorization code is detected, the authorization code is expired, or any * other errors occur, the user will be sent to an error page. * * @param request The HTTP request sent by the client * @param response The HTTP response that the server will send back to the client * * @see <a href="https://tools.ietf.org/html/rfc6749">RFC 6749 - The OAuth 2.0 Authorization Framework</a> *///from www.ja v a2s . c o m @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check for the presence of an authorization code String authorizationCode = request.getParameter("code"); if (!StringUtils.isEmpty(authorizationCode)) { // Get access token log.info("[" + request.getSession().getId() + "] Starting session. Requesting access token with authorization code " + LoggingUtils.anonymize(authorizationCode)); String tokenEndpoint = Model.TOKEN_ENDPOINT + "?grant_type=authorization_code&code=" + authorizationCode + "&redirect_uri=" + URLEncoder.encode( (request.getScheme() + "://" + request.getServerName() + Model.REDIRECTION_ENDPOINT), StandardCharsets.UTF_8.name()) + "&client_id=" + Model.CLIENT_ID + "&client_secret=" + Model.CLIENT_SECRET; String accessToken = OAuth2Utils.requestAccessToken(tokenEndpoint); if (StringUtils.isEmpty(accessToken)) { response.sendRedirect("/uh-oh"); return; } // Get profile data log.info("[" + request.getSession().getId() + "] Access token " + LoggingUtils.anonymize(accessToken) + " received. Requesting profile data."); User user = facebookService.getProfile(accessToken); if (user == null) { response.sendRedirect("/uh-oh"); return; } // Here we go log.info("[" + request.getSession().getId() + "] Hello, " + LoggingUtils.anonymize(Objects.toString(user.getId())) + "!"); Model.cache.put(request.getSession().getId() + ".profile", user); Model.cache.put(request.getSession().getId() + ".token", accessToken); response.sendRedirect("/you-rock"); } else if (request.getParameter("error") != null) { // An error happened during authorization code request String error = request.getParameter("error"); String errorDescription = request.getParameter("error_description"); request.getSession().setAttribute("error", error); request.getSession().setAttribute("errorDescription", errorDescription); log.severe("[" + request.getSession().getId() + "] Error encountered during authorization code request: " + error + " - " + errorDescription); response.sendRedirect("/uh-oh"); } else { log.warning("[" + request.getSession().getId() + "] No authorization code or error message detected at redirection endpoint"); response.sendRedirect("/uh-oh"); } }
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 w w .j a va2s . c om*/ * @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:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarCreateNewAccountHtml.java
protected void sendConfirmationEMail(HttpServletRequest request, ICFSecuritySecUserObj confirmUser, ICFSecurityClusterObj 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 + "/CFAsteriskSMWarConfirmEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarConfirmEMailAddressHtml?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 + "/CFAsteriskSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarCancelEMailAddressHtml?ConfirmationUUID=" + confirmationUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; CFAsteriskSMWarUtil warUtil = new CFAsteriskSMWarUtil(); warUtil.sendEMailToUser(confirmUser, "You requested an account with " + clusterDescription + "?", msgBody); }
From source file:org.jahia.modules.defaultmodule.actions.ChainAction.java
public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource, JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver) throws Exception { List<String> chainOfactions = parameters.get(CHAIN_OF_ACTION); if (chainOfactions != null) { String[] actions = chainOfactions.get(0).split(","); Map<String, Action> actionsMap = templateService.getActions(); ActionResult result = null;/*from w ww . j av a 2 s. c o m*/ String path = null; for (String actionToDo : actions) { if (DefaultPostAction.ACTION_NAME.equals(actionToDo)) { String s = urlResolver.getUrlPathInfo().replace(".chain.do", "/*"); URLResolver resolver = urlResolverFactory.createURLResolver(s, req.getServerName(), req); resolver.setSiteKey(urlResolver.getSiteKey()); result = defaultPostAction.doExecute(req, renderContext, resource, session, parameters, resolver); } else { Action action = actionsMap.get(actionToDo); if (action.getRequiredPermission() == null || resource.getNode().hasPermission(action.getRequiredPermission())) { result = action.doExecute(req, renderContext, resource, session, parameters, urlResolver); } else { throw new AccessDeniedException(); } if (actionToDo.equals("redirect") && result != null && result.getUrl() != null) { path = result.getUrl(); } } } if (path != null) { result.setUrl(path); } return result; } return ActionResult.BAD_REQUEST; }
From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java
private String addCookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final String cookieName, final String cookieValue) { if (httpRequest == null || httpResponse == null || cookieName == null || cookieValue == null) { throw new PreconditionException("Required parameter is null"); }//from www.j ava2 s . co m final Cookie cookie = new Cookie(cookieName, ""); cookie.setValue(cookieValue); cookie.setMaxAge(-1); cookie.setSecure(true); cookie.setDomain(httpRequest.getServerName()); cookie.setPath("/"); cookie.setHttpOnly(true); httpResponse.addCookie(cookie); return cookie.getValue(); }