List of usage examples for javax.servlet.http HttpServletRequest getRequestURL
public StringBuffer getRequestURL();
From source file:com.erudika.para.security.LinkedInAuthFilter.java
/** * Handles an authentication request.// ww w . jav a 2 s . c o m * @param request HTTP request * @param response HTTP response * @return an authentication object that contains the principal object if successful. * @throws IOException ex */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { final String requestURI = request.getRequestURI(); UserAuthentication userAuth = null; if (requestURI.endsWith(LINKEDIN_ACTION)) { String authCode = request.getParameter("code"); if (!StringUtils.isBlank(authCode)) { String url = Utils.formatMessage(TOKEN_URL, authCode, request.getRequestURL().toString(), Config.LINKEDIN_APP_ID, Config.LINKEDIN_SECRET); HttpPost tokenPost = new HttpPost(url); CloseableHttpResponse resp1 = httpclient.execute(tokenPost); if (resp1 != null && resp1.getEntity() != null) { Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent()); if (token != null && token.containsKey("access_token")) { userAuth = getOrCreateUser(null, (String) token.get("access_token")); } EntityUtils.consumeQuietly(resp1.getEntity()); } } } User user = SecurityUtils.getAuthenticatedUser(userAuth); if (userAuth == null || user == null || user.getIdentifier() == null) { throw new BadCredentialsException("Bad credentials."); } else if (!user.getActive()) { throw new LockedException("Account is locked."); } return userAuth; }
From source file:com.epam.cme.storefront.filters.cms.CMSSiteFilter.java
/** * Processing normal request (i.e. when user goes directly to that application - not from * cmscockpit)/*from w w w .ja va2 s .c o m*/ * <p/> * <b>Note:</b> <br/> * We preparing application by setting correct: * <ul> * <li>Current Site</li> * <li>Current Catalog Versions</li> * <li>Enabled language fallback</li> * </ul> * * @see ContextInformationLoader#initializeSiteFromRequest(String) * @see ContextInformationLoader#setCatalogVersions() * @param httpRequest * current request * @param httpResponse * the http response * @throws java.io.IOException */ protected boolean processNormalRequest(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws IOException { final String queryString = httpRequest.getQueryString(); final String currentRequestURL = httpRequest.getRequestURL().toString(); // set current site CMSSiteModel cmsSiteModel = getCurrentCmsSite(); if (cmsSiteModel == null || StringUtils.contains(queryString, CLEAR_CMSSITE_PARAM)) { final String absoluteURL = StringUtils.removeEnd(currentRequestURL, "/") + (StringUtils.isBlank(queryString) ? "" : "?" + queryString); cmsSiteModel = getContextInformationLoader().initializeSiteFromRequest(absoluteURL); } if (cmsSiteModel == null) { // Failed to lookup CMS site httpResponse.sendError(MISSING_CMS_SITE_ERROR_STATUS, MISSING_CMS_SITE_ERROR_MESSAGE); return false; } else if (!SiteChannel.B2C.equals(cmsSiteModel.getChannel()) && !SiteChannel.TELCO.equals(cmsSiteModel.getChannel())) // Restrict to B2C and // Telco channel { // CMS site that we looked up was for an unsupported channel httpResponse.sendError(MISSING_CMS_SITE_ERROR_STATUS, INCORRECT_CMS_SITE_CHANNEL_ERROR_MESSAGE); return false; } if (!isActiveSite(cmsSiteModel)) { throw new IllegalStateException( "Site is not active. Active flag behaviour must be implement for this project."); } getContextInformationLoader().setCatalogVersions(); // set fall back language enabled setFallbackLanguage(httpRequest, Boolean.TRUE); return true; }
From source file:com.github.safrain.remotegsh.server.RgshFilter.java
private void performWelcomeScreen(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().println(getResource(RESOURCE_PATH + "welcome.txt", DEFAULT_CHARSET) .replaceAll(PLACEHOLDER_SERVER, request.getRequestURL().toString())); response.setStatus(200);//from w w w.j a va2s. c om }
From source file:com.epam.trade.storefront.controllers.misc.StoreSessionController.java
protected String getReturnRedirectUrlForUrlEncoding(final HttpServletRequest request, final String old, final String current) { final String originalReferer = (String) request.getAttribute(StorefrontFilter.ORIGINAL_REFERER); if (StringUtils.isNotBlank(originalReferer)) { return REDIRECT_PREFIX + StringUtils.replace(originalReferer, "/" + old + "/", "/" + current + "/"); }//ww w . java 2 s . c o m String referer = StringUtils.remove(request.getRequestURL().toString(), request.getServletPath()); if (!StringUtils.endsWith(referer, "/")) { referer = referer + "/"; } if (referer != null && !referer.isEmpty() && StringUtils.contains(referer, "/" + old + "/")) { return REDIRECT_PREFIX + StringUtils.replace(referer, "/" + old + "/", "/" + current + "/"); } return REDIRECT_PREFIX + referer; }
From source file:com.npower.dl.SoftwareDownloadServlet.java
public void doDownloadJAD(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestUri = request.getRequestURI(); log.info("Download Service: Download Content: uri: " + requestUri); String requestUrl = request.getRequestURL().toString(); String packageID = parserPackageID(requestUri); ManagementBeanFactory factory = null; try {//from ww w .j a v a2s . c o m factory = ManagementBeanFactory.newInstance(EngineConfig.getProperties()); SoftwareBean bean = factory.createSoftwareBean(); SoftwarePackage pkg = bean.getPackageByID(Long.parseLong(packageID)); if (pkg == null) { throw new DMException("Could not found download package by package ID: " + packageID); } if (pkg.getMimeType().equalsIgnoreCase("text/vnd.sun.j2me.app-descriptor")) { // Content is JAD InputStream ins = pkg.getBinary().getBinaryBlob().getBinaryStream(); if (pkg.getSize() > 0) { response.setContentType(pkg.getMimeType()); response.setContentLength(pkg.getSize()); OutputStream out = response.getOutputStream(); byte[] buf = new byte[1024]; int len = ins.read(buf); while (len > 0) { out.write(buf, 0, len); len = ins.read(buf); } out.flush(); //out.close(); return; } } else if (pkg.getMimeType().equalsIgnoreCase("application/java-archive") || pkg.getMimeType().equalsIgnoreCase("application/java") || pkg.getMimeType().equalsIgnoreCase("application/x-java-archive")) { // JAR Format, generate a JAD File jarFile = File.createTempFile("software_tmp", "jar"); InputStream ins = pkg.getBinary().getBinaryBlob().getBinaryStream(); if (pkg.getSize() > 0) { OutputStream out = new FileOutputStream(jarFile); byte[] buf = new byte[1024]; int len = ins.read(buf); while (len > 0) { out.write(buf, 0, len); len = ins.read(buf); } out.flush(); out.close(); String url4Jar = StringUtils.replace(requestUrl, ".jad", ".jar"); JADCreator creator = new JADCreator(); Manifest manifest = creator.getJADManufest(jarFile, url4Jar); response.setContentType(pkg.getMimeType()); manifest.write(response.getOutputStream()); // Clean temp file jarFile.delete(); return; } } // Return Not Found Code. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (Exception ex) { throw new ServletException(ex); } finally { if (factory != null) { factory.release(); } } }
From source file:com.nec.harvest.servlet.interceptor.LoggerInterceptor.java
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { final long startEcecutionTime = (Long) request.getAttribute(STRAT_EXECUTION_TIME_KEY); final long endExecutionTime = System.currentTimeMillis(); final long timeUse = endExecutionTime - startEcecutionTime; logger.info("Start execution time :" + startEcecutionTime + " & End execution time :" + endExecutionTime + " & Time use: " + timeUse + "[milliseconds] on the request Url: " + request.getRequestURL().toString()); super.postHandle(request, response, handler, modelAndView); }
From source file:com.ibm.liberty.starter.api.v1.LibertyFileUploader.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String tech = request.getParameter(PARAMETER_TECH); String workspaceId = request.getParameter(PARAMETER_WORKSPACE); //specify the unique workspace directory to upload the file(s) to. Collection<Part> filePartCollection = request.getParts(); String serverHostPort = request.getRequestURL().toString().replace(request.getRequestURI(), ""); int schemeLength = request.getScheme().toString().length(); String internalHostPort = "http" + serverHostPort.substring(schemeLength); log.log(Level.FINER, "serverHostPort : " + serverHostPort); final ServiceConnector serviceConnector = new ServiceConnector(serverHostPort, internalHostPort); HashMap<Part, String> fileNames = new HashMap<Part, String>(); if (!isValidRequest(request, response, tech, workspaceId, filePartCollection, serviceConnector, fileNames)) {/* ww w .j a va 2 s .c o m*/ return; } Service techService = serviceConnector.getServiceObjectFromId(tech); String techDirPath = StarterUtil.getWorkspaceDir(workspaceId) + "/" + techService.getId(); File techDir = new File(techDirPath); if (techDir.exists() && techDir.isDirectory() && "true".equalsIgnoreCase(request.getParameter(PARAMETER_CLEANUP))) { FileUtils.cleanDirectory(techDir); log.log(Level.FINER, "Cleaned up tech workspace directory : " + techDirPath); } for (Part filePart : filePartCollection) { if (!techDir.exists()) { FileUtils.forceMkdir(techDir); log.log(Level.FINER, "Created tech directory :" + techDirPath); } String filePath = techDirPath + "/" + fileNames.get(filePart); log.log(Level.FINER, "File path : " + filePath); File uploadedFile = new File(filePath); Files.copy(filePart.getInputStream(), uploadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); log.log(Level.FINE, "Copied file to " + filePath); } if ("true".equalsIgnoreCase(request.getParameter(PARAMETER_PROCESS))) { // Process uploaded file(s) String processResult = serviceConnector.processUploadedFiles(techService, techDirPath); if (!processResult.equalsIgnoreCase("success")) { log.log(Level.INFO, "Error processing the files uploaded to " + techDirPath + " : Result=" + processResult); response.sendError(500, processResult); return; } log.log(Level.FINE, "Processed the files uploaded to " + techDirPath); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("success"); out.close(); }
From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.Cas2Authenticator.java
protected String checkCasTicket(String ticket, HttpServletRequest httpRequest) { log.debug(String.format("checkCasTicket %s", httpRequest.getRequestURL().toString())); ServiceTicketValidator ticketValidator; try {/*from w ww . jav a 2s . c om*/ ticketValidator = (ServiceTicketValidator) Framework.getRuntime().getContext() .loadClass(ticketValidatorClassName).newInstance(); } catch (InstantiationException e) { log.error( "checkCasTicket during the ServiceTicketValidator initialization with InstantiationException:", e); return null; } catch (IllegalAccessException e) { log.error( "checkCasTicket during the ServiceTicketValidator initialization with IllegalAccessException:", e); return null; } catch (ClassNotFoundException e) { log.error( "checkCasTicket during the ServiceTicketValidator initialization with ClassNotFoundException:", e); return null; } ticketValidator.setCasValidateUrl(getServiceURL(httpRequest, VALIDATE_ACTION)); ticketValidator.setService(getAppURL(httpRequest)); ticketValidator.setServiceTicket(ticket); try { ticketValidator.validate(); } catch (IOException e) { log.error("checkCasTicket failed with IOException:", e); return null; } catch (SAXException e) { log.error("checkCasTicket failed with SAXException:", e); return null; } catch (ParserConfigurationException e) { log.error("checkCasTicket failed with ParserConfigurationException:", e); return null; } log.debug("checkCasTicket : validation executed without error"); String username = ticketValidator.getUser(); log.debug("checkCasTicket: validation returned username = " + username); return username; }
From source file:org.n52.tamis.rest.controller.processes.jobs.DeleteRequestController.java
@RequestMapping("") public ResponseEntity delete(@PathVariable(URL_Constants_TAMIS.SERVICE_ID_VARIABLE_NAME) String serviceId, @PathVariable(URL_Constants_TAMIS.PROCESS_ID_VARIABLE_NAME) String processId, @PathVariable(URL_Constants_TAMIS.JOB_ID_VARIABLE_NAME) String jobId, HttpServletRequest request, HttpServletResponse response) {//from w w w.ja va2 s . co m logger.info("Received delete request for service id \"{}\", process id \"{}\" and job id \"{}\" !", serviceId, processId, jobId); initializeParameterValueStore(serviceId, processId, jobId); // prepare response entity with HTTP status 404, not found ResponseEntity responseEntity = new ResponseEntity(HttpStatus.NOT_FOUND); try { logger.info("Trying to delete resource at \"{}\"", request.getRequestURL()); responseEntity = deleteRequestForwarder.forwardRequestToWpsProxy(request, null, parameterValueStore); } catch (Exception e) { logger.info("DELETE request for resouce at \"{}\" failed.", request.getRequestURL()); response.setStatus(HttpStatus.NOT_FOUND.value()); return new ResponseEntity(HttpStatus.NOT_FOUND); } return responseEntity; }
From source file:org.artifactory.webapp.servlet.RepoFilter.java
private boolean isDockerRequest(HttpServletRequest request) { String dockerApiPath = "/api/docker"; String joinedRequestPath = request.getServletPath() + request.getPathInfo(); return joinedRequestPath.contains(dockerApiPath) || request.getRequestURL().toString().contains(dockerApiPath); }