List of usage examples for javax.servlet.http HttpServletRequest getScheme
public String getScheme();
From source file:net.sf.qooxdoo.rpc.RpcServlet.java
protected String getDomainURL(HttpServletRequest request) { // reconstruct the start of the URL StringBuffer domainURL = new StringBuffer(); String scheme = request.getScheme(); int port = request.getServerPort(); domainURL.append(scheme);/*w w w . j av a 2s. co m*/ domainURL.append("://"); domainURL.append(request.getServerName()); if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) { domainURL.append(':'); domainURL.append(request.getServerPort()); } domainURL.append('/'); return domainURL.toString(); }
From source file:net.sf.qooxdoo.rpc.RpcServlet.java
protected String getContextURL(HttpServletRequest request) { // reconstruct the start of the URL StringBuffer contextURL = new StringBuffer(); String scheme = request.getScheme(); int port = request.getServerPort(); contextURL.append(scheme);/*from ww w .jav a2s . c o m*/ contextURL.append("://"); contextURL.append(request.getServerName()); if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) { contextURL.append(':'); contextURL.append(request.getServerPort()); } contextURL.append(request.getContextPath()); return contextURL.toString(); }
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)) {//from www . j ava 2s . co 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:org.bonitasoft.console.common.application.ApplicationURLUtils.java
/** * Retrieve the dedicated application URL and set it in the * /*from w w w .ja v a 2 s . c o m*/ * @param request the current request * @param aProcessDefinitionUUID the process definition UUID * @return the URL of the dedicated application (null if no dedicated application is deployed for the process) * @throws ProcessNotFoundException */ public String getOrSetURLMetaData(final HttpServletRequest request, final ProcessDefinitionUUID aProcessDefinitionUUID) throws ProcessNotFoundException { String theResult = null; final String theMeta = AccessorUtil.getQueryDefinitionAPI().getProcessMetaData(aProcessDefinitionUUID, DEDICATED_APP_URL_META_NAME); if (theMeta == null || theMeta.length() == 0) { // The Metadata is not set yet. // Try to autodetect it. final String theScheme = request.getScheme(); final String theServerName = request.getServerName(); final int theServerPort = request.getServerPort(); URL theApplicationURL; try { theApplicationURL = new URL(theScheme + "://" + theServerName + ":" + theServerPort + "/" + aProcessDefinitionUUID + HOSTPAGE_PATH); final boolean urlIsReachable = checkURLConnection(theApplicationURL); if (urlIsReachable) { setProcessApplicationURLMetadata(aProcessDefinitionUUID, theApplicationURL.toString()); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Adding the " + DEDICATED_APP_URL_META_NAME + " metadata for the process " + aProcessDefinitionUUID + ": " + theApplicationURL.toString()); } theResult = theApplicationURL.toString(); } else { theResult = HOMEPAGE_SERVLET_ID_IN_PATH + "?" + THEME_PARAM + "=" + aProcessDefinitionUUID; } } catch (final MalformedURLException e) { e.printStackTrace(); } } else { theResult = theMeta; } /* * If the meta is set do not modify it else { URL theApplicationURL; try { theApplicationURL = new URL(theMeta); boolean * urlIsReachable = checkURLConnection(theApplicationURL); if (!urlIsReachable) { // Remove the meta as it seems to be * obsolete. AccessorUtil.getManagementAPI().deleteMetaData (DEDICATED_APP_URL_META_NAME + "-" + * aProcessDefinitionUUID); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Deleting metadata :" + * DEDICATED_APP_URL_META_NAME + "-" + aProcessDefinitionUUID + " : " + theMeta); } } else { theResult = theMeta; } } * catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } */ return theResult; }
From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java
public static String getServerURL(HttpServletRequest req, String relativeServletPath, boolean preserveQS) { // for now, only store the servlet context and the serverUrl String path = req.getContextPath(); Integer identifiedPort = req.getServerPort(); String identifiedHostname = req.getServerName(); if (identifiedHostname == null || identifiedHostname.length() == 0 || identifiedHostname.equals("0.0.0.0")) { try {//from w ww . j a v a 2 s . c o m identifiedHostname = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { identifiedHostname = "127.0.0.1"; } } String identifiedScheme = "http"; if (identifiedPort == null || identifiedPort == 0) { if (req.getScheme().equals(identifiedScheme)) { identifiedPort = req.getServerPort(); } else { identifiedPort = HtmlConsts.WEB_PORT; } } boolean expectedPort = (identifiedScheme.equalsIgnoreCase("http") && identifiedPort == HtmlConsts.WEB_PORT) || (identifiedScheme.equalsIgnoreCase("https") && identifiedPort == HtmlConsts.SECURE_WEB_PORT); String serverUrl; if (!expectedPort) { serverUrl = identifiedScheme + "://" + identifiedHostname + BasicConsts.COLON + Integer.toString(identifiedPort) + path; } else { serverUrl = identifiedScheme + "://" + identifiedHostname + path; } String query = req.getQueryString(); if (query == null) { if (req.getServletPath().equals("/demowebclient/greet")) { if (CLIENT_WEBSITE_CODESVR_PORT.length() != 0) { query = "gwt.codesvr=127.0.0.1:" + CLIENT_WEBSITE_CODESVR_PORT; } else { query = ""; } } else { query = ""; } } if (query.length() != 0) { query = "?" + query; } return serverUrl + BasicConsts.FORWARDSLASH + relativeServletPath + (preserveQS ? query : ""); }
From source file:com.searchbox.framework.web.Auth0LoginController.java
@RequestMapping("/index") protected String login(final Map<String, Object> model, final HttpServletRequest req) { logger.info("Performing login"); detectError(model);//w w w .j av a2s. com // add a Nonce value to session storage NonceUtils.addNonceToStorage(req); model.put("clientId", appConfig.getClientId()); model.put("clientDomain", appConfig.getDomain()); model.put("loginCallback", appConfig.getLoginCallback()); model.put("state", SessionUtils.getState(req)); int port = req.getServerPort(); String url; if (port == 80) { url = String.format("%s://%s/", req.getScheme(), req.getServerName()); } else { url = String.format("%s://%s:%d/", req.getScheme(), req.getServerName(), req.getServerPort()); } String redirectUrl = appConfig.getIssuer() + "authorize?" + "response_type=code&scope=openid%20profile&" + "client_id=" + appConfig.getClientId() + "&" + "state=" + SessionUtils.getState(req) + "&redirect_uri=" + url + "callback"; return "redirect:" + redirectUrl; }
From source file:be.fedict.eid.applet.service.KmlServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doGet"); HttpSession httpSession = request.getSession(); EIdData eIdData = (EIdData) httpSession.getAttribute("eid"); byte[] document; try {//from ww w. j a v a2 s .c om document = this.kmlGenerator.generateKml(eIdData); } catch (IOException e) { throw new ServletException("KML generator error: " + e.getMessage(), e); } response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1 if (false == request.getScheme().equals("https")) { // else the download fails in IE response.setHeader("Pragma", "no-cache"); // http 1.0 } else { response.setHeader("Pragma", "public"); } response.setDateHeader("Expires", -1); response.setHeader("Content-disposition", "attachment"); response.setContentLength(document.length); response.setContentType(KmlLight.MIME_TYPE); response.setContentLength(document.length); ServletOutputStream out = response.getOutputStream(); out.write(document); out.flush(); }
From source file:pt.sapo.pai.vip.VipServlet.java
private void processRequest(HttpServletRequest request, HttpServletResponse response, Supplier<HttpRequestBase> supplier) throws ServletException, IOException { try (OutputStream out = response.getOutputStream(); CloseableHttpClient http = builder.build()) { Optional.ofNullable(servers[rand.nextInt(2)]).map(server -> server.split(":")) .map(parts -> Tuple.of(parts[0], Integer.valueOf(parts[1]))).ifPresent(server -> { try { HttpRequestBase method = supplier.get(); method.setURI(new URI(request.getScheme(), null, server._1, server._2, request.getRequestURI(), request.getQueryString(), null)); HttpResponse rsp = http.execute(method); Collections.list(request.getHeaderNames()) .forEach(name -> Collections.list(request.getHeaders(name)) .forEach(value -> method.setHeader(name, value))); response.setStatus(rsp.getStatusLine().getStatusCode()); response.setContentType(rsp.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()); IOUtils.copy(rsp.getEntity().getContent(), out); } catch (IOException | URISyntaxException ex) { log.error(null, ex); }/*from www. j a v a 2 s . c o m*/ }); } }
From source file:org.infoglue.calendar.actions.ViewEntrySearchAction.java
/** * This is the entry point for the main listing. *//*from w w w . j a v a 2 s .c o m*/ public String execute() throws Exception { Session dbSession = getSession(true); initialize(dbSession); if (this.searchHashCode != null && !this.searchHashCode.equals("")) { log.debug("Getting search args from session..." + this.searchHashCode); HttpSession session = ServletActionContext.getRequest().getSession(); this.searchFirstName = (String) session.getAttribute("request_" + searchHashCode + "_searchFirstName"); this.searchLastName = (String) session.getAttribute("request_" + searchHashCode + "_searchLastName"); this.searchEmail = (String) session.getAttribute("request_" + searchHashCode + "_searchEmail"); this.onlyFutureEvents = Boolean .parseBoolean((String) session.getAttribute("request_" + searchHashCode + "_onlyFutureEvents")); this.searchEventId = (Long[]) session.getAttribute("request_" + searchHashCode + "_searchEventId"); this.categoryAttributesMap = (Map) session .getAttribute("request_" + searchHashCode + "_categoryAttributesMap"); this.andSearch = (String) session.getAttribute("request_" + searchHashCode + "_andSearch"); this.locationId = (String[]) session.getAttribute("request_" + searchHashCode + "_locationId"); } else { log.debug("Getting search args from request..."); int i = 0; String idKey = ServletActionContext.getRequest().getParameter("categoryAttributeId_" + i); log.info("idKey:" + idKey); while (idKey != null && idKey.length() > 0) { String[] categoryIds = ServletActionContext.getRequest() .getParameterValues("categoryAttribute_" + idKey + "_categoryId"); log.info("categoryIds:" + categoryIds); if (categoryIds != null) { Long[] categoryIdsLong = new Long[categoryIds.length]; for (int j = 0; j < categoryIds.length; j++) categoryIdsLong[j] = new Long(categoryIds[j]); categoryAttributesMap.put(idKey, categoryIdsLong); } i++; idKey = ServletActionContext.getRequest().getParameter("categoryAttributeId_" + i); log.info("idKey:" + idKey); } log.info("searchEventId:::::" + this.searchEventId); log.info("andSearch:" + this.andSearch); this.andSearch = ServletActionContext.getRequest().getParameter("andSearch"); log.info("andSearch:" + andSearch); } this.entries = EntryController.getController().getEntryList(this.getInfoGlueRemoteUser(), this.getInfoGlueRemoteUserRoles(), this.getInfoGlueRemoteUserGroups(), searchFirstName, searchLastName, searchEmail, onlyFutureEvents, searchEventId, categoryAttributesMap, Boolean.parseBoolean(andSearch), locationId, dbSession); List<Event> events = new ArrayList<Event>(); String eventName = ""; String emailAddresses = ""; Long entryTypeId = null; Iterator entriesIterator = entries.iterator(); while (entriesIterator.hasNext()) { Entry entry = (Entry) entriesIterator.next(); if (!events.contains(entry.getEvent())) { String name = entry.getEvent().getLocalizedName(this.getLanguageCode(), "sv"); if (name == null) { EventVersion eventVersion = this.getEventVersion(entry.getEvent()); if (eventVersion != null) name = eventVersion.getLocalizedName(this.getLanguageCode(), "sv"); } eventName += (eventName.equals("") ? "" : ", ") + name; events.add(entry.getEvent()); } if (entryTypeId == null) entryTypeId = entry.getEvent().getEntryFormId(); if (emailAddresses.length() != 0) emailAddresses += ";" + entry.getEmail(); else emailAddresses += entry.getEmail(); } HttpSession session = ServletActionContext.getRequest().getSession(); this.searchHashCode = "" + ServletActionContext.getRequest().hashCode(); log.debug("searchHashCode:" + searchHashCode); session.setAttribute("request_" + searchHashCode + "_emailAddresses", emailAddresses); session.setAttribute("request_" + searchHashCode + "_searchFirstName", searchFirstName); session.setAttribute("request_" + searchHashCode + "_searchLastName", searchLastName); session.setAttribute("request_" + searchHashCode + "_searchEmail", searchEmail); session.setAttribute("request_" + searchHashCode + "_onlyFutureEvents", "" + onlyFutureEvents); session.setAttribute("request_" + searchHashCode + "_searchEventId", searchEventId); session.setAttribute("request_" + searchHashCode + "_categoryAttributesMap", categoryAttributesMap); session.setAttribute("request_" + searchHashCode + "_andSearch", andSearch); session.setAttribute("request_" + searchHashCode + "_locationId", locationId); // should we create result files? boolean exportEntryResults = PropertyHelper.getBooleanProperty("exportEntryResults"); if (entries.size() > 0 && exportEntryResults) { Map parameters = new HashMap(); parameters.put("headLine", "Entries found for: " + eventName); EventType eventType = EventTypeController.getController().getEventType(entryTypeId, getSession()); List attributes = ContentTypeDefinitionController.getController() .getContentTypeAttributes(eventType.getSchemaValue()); List attributeNames = new ArrayList(); Iterator attributesIterator = attributes.iterator(); while (attributesIterator.hasNext()) { ContentTypeAttribute attribute = (ContentTypeAttribute) attributesIterator.next(); attributeNames.add(attribute.getName()); } parameters.put("attributes", attributes); parameters.put("attributeNames", attributeNames); HttpServletRequest request = ServletActionContext.getRequest(); EntrySearchResultfilesConstructor results = new EntrySearchResultfilesConstructor(parameters, entries, getTempFilePath(), request.getScheme(), request.getServerName(), request.getServerPort(), resultValues, this, entryTypeId.toString()); searchResultFiles = results.getResults(); } return Action.SUCCESS; }
From source file:eu.europeana.uim.gui.cp.server.RetrievalServiceImpl.java
/** * Private method that determines the application context so that this does not have to be defined in configuration properties. * Ideally this should be put in the context of an overriden init() method but unfortunately it does not work there. *///ww w. j a v a 2 s . c om private void determinelocaladress() { if (REPOSITORY_PREVIEW_URL == null) { HttpServletRequest request = this.getThreadLocalRequest(); String scheme = request.getScheme(); String serverName = request.getServerName(); int serverPort = request.getServerPort(); String contextPath = request.getContextPath(); REPOSITORY_PREVIEW_URL = scheme + "://" + serverName + ":" + serverPort + contextPath + "/EuropeanaIngestionControlPanel/mongoImageView"; } }