List of usage examples for javax.servlet.http HttpServletRequest getServerPort
public int getServerPort();
From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.SetEmailDA.java
public ActionForward setEmail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final String host = HostAccessControl.getRemoteAddress(request); final String ip = request.getRemoteAddr(); final String password = request.getParameter("password"); final String userUId = request.getParameter("userUId"); final String email = URLDecoder.decode(request.getParameter("email"), "UTF-8"); String message = "ko"; try {/*from ww w . ja v a 2 s . co m*/ SetEmail.run(host, ip, password, userUId, email); final User user = User.findByUsername(userUId); if (user.getPerson() != null && user.getPerson().getStudent() != null) { final Student student = user.getPerson().getStudent(); for (final Registration registration : student.getRegistrationsSet()) { final StudentCandidacy candidacy = registration.getStudentCandidacy(); if (candidacy != null && (candidacy instanceof DegreeCandidacy || candidacy instanceof IMDCandidacy) && candidacy.getExecutionYear().isCurrent() && !candidacy.getCandidacySituationsSet().isEmpty()) { new PDFGeneratorThread(candidacy.getExternalId(), request.getServerName(), request.getServerPort(), request.getContextPath(), request.getServletPath()) .start(); } } } message = "ok"; } catch (NotAuthorizedException ex) { message = "Not authorized"; } catch (UserAlreadyHasEmailException ex) { message = "User already has email."; } catch (UserDoesNotExistException ex) { message = "User does not exist."; } catch (Throwable ex) { message = ex.getMessage(); logger.error(ex.getMessage(), ex); } finally { final ServletOutputStream servletOutputStream = response.getOutputStream(); response.setContentType("text/html"); servletOutputStream.print(message); servletOutputStream.flush(); response.flushBuffer(); } return null; }
From source file:com.boyuanitsm.fort.web.rest.AccountResource.java
/** * POST /register : register the user.//from w w w. j a va 2s . c om * * @param managedUserDTO the managed user DTO * @param request the HTTP request * @return the ResponseEntity with status 201 (Created) if the user is registred or 400 (Bad Request) if the login or e-mail is already in use */ @RequestMapping(value = "/register", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }) @Timed public ResponseEntity<?> registerAccount(@Valid @RequestBody ManagedUserDTO managedUserDTO, HttpServletRequest request) { HttpHeaders textPlainHeaders = new HttpHeaders(); textPlainHeaders.setContentType(MediaType.TEXT_PLAIN); return userRepository.findOneByLogin(managedUserDTO.getLogin().toLowerCase()) .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST)) .orElseGet(() -> userRepository.findOneByEmail(managedUserDTO.getEmail()) .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders, HttpStatus.BAD_REQUEST)) .orElseGet(() -> { User user = userService.createUserInformation(managedUserDTO.getLogin(), managedUserDTO.getPassword(), managedUserDTO.getFirstName(), managedUserDTO.getLastName(), managedUserDTO.getEmail().toLowerCase(), managedUserDTO.getLangKey()); String baseUrl = request.getScheme() + // "http" "://" + // "://" request.getServerName() + // "myhost" ":" + // ":" request.getServerPort() + // "80" request.getContextPath(); // "/myContextPath" or "" if deployed in root context mailService.sendActivationEmail(user, baseUrl); return new ResponseEntity<>(HttpStatus.CREATED); })); }
From source file:be.fedict.eid.idp.sp.protocol.saml2.AuthenticationRequestServlet.java
/** * {@inheritDoc}/*from www.ja v a 2 s . c om*/ */ @SuppressWarnings("unchecked") @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doGet"); String idpDestination; String relayState; KeyStore.PrivateKeyEntry spIdentity = null; String language; AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService(); if (null != service) { idpDestination = service.getIdPDestination(); relayState = service.getRelayState(request.getParameterMap()); spIdentity = service.getSPIdentity(); language = service.getLanguage(); } else { idpDestination = this.idpDestination; relayState = null; language = this.language; } // sp-destination String spDestination = null; if (null != service) { spDestination = service.getSPDestination(); } if (null == spDestination) { // not provided by the service, check web.xml... if (null != this.spDestination) { spDestination = this.spDestination; } else { spDestination = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + this.spDestinationPage; } } // issuer String issuer = null; if (null != service) { issuer = service.getIssuer(); } if (null == issuer) { issuer = spDestination; } // generate and send an authentication request AuthnRequest authnRequest = AuthenticationRequestUtil.sendRequest(issuer, idpDestination, spDestination, relayState, spIdentity, response, language); // save state on session setRequestIssuer(authnRequest.getIssuer().getValue(), request.getSession()); setRequestId(authnRequest.getID(), request.getSession()); setRecipient(authnRequest.getAssertionConsumerServiceURL(), request.getSession()); setRelayState(relayState, request.getSession()); }
From source file:com.frequentis.maritime.mcsr.web.rest.AccountResource.java
/** * POST /register : register the user.//www. j a v a 2s . c o m * * @param managedUserDTO the managed user DTO * @param request the HTTP request * @return the ResponseEntity with status 201 (Created) if the user is registered or 400 (Bad Request) if the login or e-mail is already in use */ @RequestMapping(value = "/register", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }) @Timed public ResponseEntity<?> registerAccount(@Valid @RequestBody ManagedUserDTO managedUserDTO, HttpServletRequest request) { HttpHeaders textPlainHeaders = new HttpHeaders(); textPlainHeaders.setContentType(MediaType.TEXT_PLAIN); return userRepository.findFirstByLogin(managedUserDTO.getLogin().toLowerCase()) .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST)) .orElseGet(() -> userRepository.findFirstByEmail(managedUserDTO.getEmail()) .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders, HttpStatus.BAD_REQUEST)) .orElseGet(() -> { User user = userService.createUserInformation(managedUserDTO.getLogin(), managedUserDTO.getPassword(), managedUserDTO.getFirstName(), managedUserDTO.getLastName(), managedUserDTO.getEmail().toLowerCase(), managedUserDTO.getLangKey()); String baseUrl = request.getScheme() + // "http" "://" + // "://" request.getServerName() + // "myhost" ":" + // ":" request.getServerPort() + // "80" request.getContextPath(); // "/myContextPath" or "" if deployed in root context mailService.sendActivationEmail(user, baseUrl); return new ResponseEntity<>(HttpStatus.CREATED); })); }
From source file:org.apereo.services.persondir.support.web.RequestAttributeSourceFilter.java
/** * Add other properties from the request to the attributes map. * * @param httpServletRequest Http Servlet Request * @param attributes Map of attributes to add additional attributes to from the Http Request */// w w w.j a v a 2 s . c o m protected void addRequestProperties(final HttpServletRequest httpServletRequest, final Map<String, List<Object>> attributes) { if (this.remoteUserAttribute != null) { final String remoteUser = httpServletRequest.getRemoteUser(); attributes.put(this.remoteUserAttribute, list(remoteUser)); } if (this.remoteAddrAttribute != null) { final String remoteAddr = httpServletRequest.getRemoteAddr(); attributes.put(this.remoteAddrAttribute, list(remoteAddr)); } if (this.remoteHostAttribute != null) { final String remoteHost = httpServletRequest.getRemoteHost(); attributes.put(this.remoteHostAttribute, list(remoteHost)); } if (this.serverNameAttribute != null) { final String serverName = httpServletRequest.getServerName(); attributes.put(this.serverNameAttribute, list(serverName)); } if (this.serverPortAttribute != null) { final int serverPort = httpServletRequest.getServerPort(); attributes.put(this.serverPortAttribute, list(serverPort)); } }
From source file:com.pagecrumb.proxy.ProxyServlet.java
@SuppressWarnings("unchecked") protected void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost) throws ServletException, IOException { log.info("contextPath=" + req.getContextPath()); // Setup the headless browser WebClient webClient = new WebClient(); webClient.setWebConnection(new UrlFetchWebConnection(webClient)); HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); // GAE constraint // Originally, the design was to use HttpClient to execute methods // Now, it uses WebClient ClientConnectionManager connectionManager = new GAEConnectionManager(); HttpClient httpclient = new DefaultHttpClient(connectionManager, httpParams); StringBuffer sb = new StringBuffer(); log.info(getClass().toString() + " " + "URI Component=" + req.getRequestURI()); log.info(getClass().toString() + " " + "URL Component=" + req.getRequestURL()); if (req.getQueryString() != null) { //sb.append("?" + req.getQueryString()); String s1 = Util.decodeURIComponent(req.getQueryString()); log.info(getClass().toString() + " " + "QueryString=" + req.getQueryString()); target = req.getQueryString();//from w w w. j a v a2s. co m int port = req.getServerPort(); String domain = req.getServerName(); URL url = new URL(SCHEME, domain, port, target); /* HtmlPage page = webClient.getPage(target); //gae hack because its single threaded webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME); pageString = page.asXml(); */ } sb.append(target); log.info(getClass().toString() + " " + "sb=" + sb.toString()); HttpRequestBase targetRequest = null; if (isPost) { HttpPost post = new HttpPost(sb.toString()); Enumeration<String> paramNames = req.getParameterNames(); String paramName = null; List<NameValuePair> params = new ArrayList<NameValuePair>(); while (paramNames.hasMoreElements()) { paramName = paramNames.nextElement(); params.add(new BasicNameValuePair(paramName, req.getParameterValues(paramName)[0])); } post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); targetRequest = post; } else { HttpGet get = new HttpGet(sb.toString()); targetRequest = get; } // log.info("Request Headers"); // Enumeration<String> headerNames = req.getHeaderNames(); // String headerName = null; // while(headerNames.hasMoreElements()){ // headerName = headerNames.nextElement(); // targetRequest.addHeader(headerName, req.getHeader(headerName)); // log.info(headerName + " : " + req.getHeader(headerName)); // } HttpResponse targetResponse = httpclient.execute(targetRequest); HttpEntity entity = targetResponse.getEntity(); // Send the Response InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); String line = reader.readLine(); /* * To use the HttpClient instead the HtmlUnit's WebClient: */ while (line != null) { writer.write(line + "\n"); line = reader.readLine(); } // Scanner scanner = new Scanner(pageString); // while (scanner.hasNextLine()) { // String s = scanner.nextLine(); // writer.write(s + "\n"); // } if (webClient != null) { webClient.closeAllWindows(); } reader.close(); writer.close(); httpclient.getConnectionManager().shutdown(); }
From source file:es.itecban.deployment.executionmanager.gui.swf.service.CommonCreationManager.java
public String getXMLDependencyGraphURL(HttpServletRequest request, String unitName, String unitVersion, String selectedEnv, String containerGraphList) throws Exception { String file = request.getRequestURI(); file = file.substring(0, file.indexOf("/", file.indexOf("/") + 1)); if (request.getQueryString() != null) { // file += '?' + // request.getQueryString()+"&_eventId_getXMLGraph=true&name="+ // unitName+"&version="+unitVersion+"&environment="+selectedEnv; file += "/unitInverseDependencies.htm" + '?' + "name=" + unitName + "&version=" + unitVersion + "&environment=" + selectedEnv.replace(' ', '+') + "&justGraph=true" + "&containerGraphList=" + containerGraphList;//from w w w .jav a 2s . c o m } URL reconstructedURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), file); return (reconstructedURL.toString()).substring(request.getScheme().length(), (reconstructedURL.toString().length())); }
From source file:org.apache.axis2.transport.http.AxisServlet.java
/** * Preprocess the request. This will://from w ww .j av a2s . c o m * <ul> * <li>Set the context root if it is not set already (by calling * {@link #initContextRoot(HttpServletRequest)}). * <li>Remember the port number if port autodetection is enabled. * <li>Reject the request if no {@link AxisServletListener} has been registered for the * protocol. * </ul> * * @param req the request to preprocess */ // This method should not be part of the public API. In particular we must not allow subclasses // to override this method because we don't make any guarantees as to when exactly this method // is called. private void preprocessRequest(HttpServletRequest req) throws ServletException { initContextRoot(req); TransportInDescription transportInDescription = req.isSecure() ? this.axisConfiguration.getTransportIn(Constants.TRANSPORT_HTTPS) : this.axisConfiguration.getTransportIn(Constants.TRANSPORT_HTTP); if (transportInDescription == null) { throw new ServletException(req.getScheme() + " is forbidden"); } else { if (transportInDescription.getReceiver() instanceof AxisServletListener) { AxisServletListener listner = (AxisServletListener) transportInDescription.getReceiver(); // Autodetect the port number if necessary if (listner.getPort() == -1) { listner.setPort(req.getServerPort()); } } } }
From source file:net.daw.control.upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a v a2 s . c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String name = ""; String strMessage = ""; HashMap<String, String> hash = new HashMap<>(); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); item.write(new File(".//..//webapps//images//" + name)); } else { hash.put(item.getFieldName(), item.getString()); } } Gson oGson = new Gson(); Map<String, String> data = new HashMap<>(); Iterator it = hash.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); data.put(e.getKey().toString(), e.getValue().toString()); } data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + name); out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}"); } catch (Exception ex) { strMessage += "File Upload Failed: " + ex; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } else { strMessage += "Only serve file upload requests"; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } }
From source file:com.sun.socialsite.business.DefaultURLStrategy.java
/** * Get the appropriate Gadget Server URL for the specified request. * The returned URL will not end with a trailing slash. If the * "socialsite.gadgets.server.url" property is populated and contains * any wildcards ("*"), they will be replaced with the specified * replacementValue./* w ww . j a v a 2s . c o m*/ */ public String getGadgetServerURL(HttpServletRequest request, String replacementValue) { StringBuilder sb = new StringBuilder(); try { String propVal = Config.getProperty("socialsite.gadgets.server.url"); if (propVal != null) { String actualValue = propVal.replace("*", replacementValue); sb.append(actualValue); } else { if (Config.getBooleanProperty("socialsite.gadgets.use-cookie-jail")) { // For now, we'll use an IP-based URL to provide a cookie jail InetAddress addr = InetAddress.getByName(request.getServerName()); if (addr instanceof Inet6Address) { sb.append(request.getScheme()).append("://[").append(addr.getHostAddress()).append("]"); } else { sb.append(request.getScheme()).append("://").append(addr.getHostAddress()); } } else { sb.append(request.getScheme()).append("://").append(request.getServerName()); } switch (request.getServerPort()) { case 80: if (!(request.getScheme().equalsIgnoreCase("http"))) { sb.append(":").append(request.getServerPort()); } break; case 443: if (!(request.getScheme().equalsIgnoreCase("https"))) { sb.append(":").append(request.getServerPort()); } break; default: sb.append(":").append(request.getServerPort()); } sb.append(request.getContextPath()); sb.append("/gadgets"); } } catch (Exception e) { log.warn(e); } // We don't want our result to end with a slash while (sb.charAt(sb.length() - 1) == '/') { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); }