Java Code Examples for javax.servlet.http.HttpServletRequest#getScheme()

The following examples show how to use javax.servlet.http.HttpServletRequest#getScheme() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DfsServlet.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/** Create a URI for redirecting request to a datanode */
protected URI createRedirectUri(String servletpath, UserGroupInformation ugi,
    DatanodeID host, HttpServletRequest request, NameNode nn) throws URISyntaxException {
  final String hostname = host instanceof DatanodeInfo?
      ((DatanodeInfo)host).getHostName(): host.getHost();
  final String scheme = request.getScheme();
  final int port = "https".equals(scheme)?
      (Integer)getServletContext().getAttribute("datanode.https.port")
      : host.getInfoPort();
  // Add namenode address to the URL params
  final String nnAddr = NameNode.getHostPortString(nn.getNameNodeAddress());
  final String filename = request.getPathInfo();
  return new URI(scheme, null, hostname, port, servletpath,
      "filename=" + filename + "&ugi=" + ugi +
      JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr), null);
}
 
Example 2
Source File: IndexController.java    From MybatisGenerator-UI with MIT License 6 votes vote down vote up
@RequestMapping("/gen")
@ResponseBody
public String generator(HttpServletRequest request) {

    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code", genService.genCode(request));
    jsonObject.put("basepath", basePath);


    return jsonObject.toJSONString();
}
 
Example 3
Source File: RMWebServices.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/apps/{appid}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public AppInfo getApp(@Context HttpServletRequest hsr,
    @PathParam("appid") String appId) {
  init();
  if (appId == null || appId.isEmpty()) {
    throw new NotFoundException("appId, " + appId + ", is empty or null");
  }
  ApplicationId id;
  id = ConverterUtils.toApplicationId(recordFactory, appId);
  if (id == null) {
    throw new NotFoundException("appId is null");
  }
  RMApp app = rm.getRMContext().getRMApps().get(id);
  if (app == null) {
    throw new NotFoundException("app with id: " + appId + " not found");
  }
  return new AppInfo(rm, app, hasAccess(app, hsr), hsr.getScheme() + "://");
}
 
Example 4
Source File: EmailConfirmationServlet.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private void confirmEmail(UserInfo userInfo, HttpServletRequest req, HttpServletResponse resp) throws IOException {
	if (userInfo.getProperty(UserConstants.EMAIL_CONFIRMATION_ID) == null) {
		resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
		resp.setContentType(ProtocolConstants.CONTENT_TYPE_HTML);
		resp.getWriter().write("<html><body><p>Your email address has already been confirmed. Thank you!</p></body></html>");
		return;
	}

	if (req.getParameter(UserConstants.EMAIL_CONFIRMATION_ID) == null
			|| !req.getParameter(UserConstants.EMAIL_CONFIRMATION_ID).equals(userInfo.getProperty(UserConstants.EMAIL_CONFIRMATION_ID))) {
		resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Email could not be confirmed.");
		return;
	}

	try {
		userInfo.setProperty(UserConstants.EMAIL_CONFIRMATION_ID, null);
		userInfo.setProperty(UserConstants.BLOCKED, null);
		OrionConfiguration.getMetaStore().updateUser(userInfo);
	} catch (CoreException e) {
		LogHelper.log(e);
		resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
		return;
	}

	resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
	resp.setContentType(ProtocolConstants.CONTENT_TYPE_HTML);
	StringBuffer host = new StringBuffer();
	String scheme = req.getScheme();
	host.append(scheme);
	host.append(":////");
	String servername = req.getServerName();
	host.append(servername);
	host.append(":");
	int port = req.getServerPort();
	host.append(port);
	resp.getWriter().write("<html><body><p>Your email address has been confirmed. Thank you! <a href=\"" + host
			+ "\">Click here</a> to continue and login to your account.</p></body></html>");
	return;
}
 
Example 5
Source File: JnlpFileHandler.java    From webstart with MIT License 5 votes vote down vote up
private String getUrlPrefix( HttpServletRequest req )
{
    StringBuilder url = new StringBuilder();
    String scheme = req.getScheme();
    int port = req.getServerPort();
    url.append( scheme );        // http, https
    url.append( "://" );
    url.append( req.getServerName() );
    if ( ( scheme.equals( "http" ) && port != 80 ) || ( scheme.equals( "https" ) && port != 443 ) )
    {
        url.append( ':' );
        url.append( req.getServerPort() );
    }
    return url.toString();
}
 
Example 6
Source File: SwaggerResource.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@POST
@Path("/clients/{language}")
@ApiOperation(
        value = "Generates a client library",
        notes = "Accepts a `GeneratorInput` options map for spec location and generation options",
        response = ResponseCode.class, tags = "clients")
public Response generateClient(
        @Context HttpServletRequest request,
        @ApiParam(value = "The target language for the client library", required = true) @PathParam("language") String language,
        @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts)
        throws Exception {

    String filename = Generator.generateClient(language, opts);
    String host = System.getenv("GENERATOR_HOST");

    if (StringUtils.isBlank(host)) {
        String scheme = request.getHeader("X-SSL");
        String port = "";
        if ("1".equals(scheme)) {
            scheme = "https";
        } else {
            scheme = request.getScheme();
            port = ":" + request.getServerPort();
        }
        host = scheme + "://" + request.getServerName() + port;
    }

    if (filename != null) {
        String code = String.valueOf(UUID.randomUUID().toString());
        Generated g = new Generated();
        g.setFilename(filename);
        g.setFriendlyName(language + "-client");
        fileMap.put(code, g);
        System.out.println(code + ", " + filename);
        String link = host + "/api/gen/download/" + code;
        return Response.ok().entity(new ResponseCode(code, link)).build();
    } else {
        return Response.status(500).build();
    }
}
 
Example 7
Source File: HeimdallDecorationFilter.java    From heimdall with Apache License 2.0 5 votes vote down vote up
protected void addProxyHeaders(RequestContext ctx) {

        HttpServletRequest request = ctx.getRequest();
        String host = toHostHeader(request);
        String port = String.valueOf(request.getServerPort());
        String proto = request.getScheme();
        if (hasHeader(request, X_FORWARDED_HOST_HEADER)) {
            host = request.getHeader(X_FORWARDED_HOST_HEADER) + "," + host;
        }
        if (!hasHeader(request, X_FORWARDED_PORT_HEADER)) {
            if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) {
                StringBuilder builder = new StringBuilder();
                for (String previous : StringUtils.commaDelimitedListToStringArray(request.getHeader(X_FORWARDED_PROTO_HEADER))) {
                    if (builder.length() > 0) {
                        builder.append(",");
                    }
                    builder.append(HTTPS_SCHEME.equals(previous) ? HTTPS_PORT : HTTP_PORT);
                }
                builder.append(",").append(port);
                port = builder.toString();
            }
        } else {
            port = request.getHeader(X_FORWARDED_PORT_HEADER) + "," + port;
        }
        if (hasHeader(request, X_FORWARDED_PROTO_HEADER)) {
            proto = request.getHeader(X_FORWARDED_PROTO_HEADER) + "," + proto;
        }
        ctx.addZuulRequestHeader(X_FORWARDED_HOST_HEADER, host);
        ctx.addZuulRequestHeader(X_FORWARDED_PORT_HEADER, port);
        ctx.addZuulRequestHeader(X_FORWARDED_PROTO_HEADER, proto);
    }
 
Example 8
Source File: SysAdminParamsBaseUrlGenerator.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected String getServerName(HttpServletRequest request)
{
	String hostname = sysAdminParams.getAlfrescoHost();
       if (hostname == null)
       {
       	hostname = request.getScheme();
       }
       hostname = request.getServerName();
       return hostname;
}
 
Example 9
Source File: URLManager.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void addBaseURL(StringBuilder link, HttpServletRequest request) throws ApsSystemException {
    if (null == request) {
        link.append(this.getConfigManager().getParam(SystemConstants.PAR_APPL_BASE_URL));
        return;
    }
    if (this.isForceAddSchemeHost()) {
        String reqScheme = request.getScheme();
        link.append(reqScheme);
        link.append("://");
        String serverName = request.getServerName();
        link.append(serverName);
        boolean checkPort = false;
        String hostName = request.getHeader("Host");
        if (null != hostName && hostName.startsWith(serverName)) {
            checkPort = true;
            if (hostName.length() > serverName.length()) {
                link.append(hostName.substring(serverName.length()));
            }
        }
        if (!checkPort) {
            link.append(":").append(request.getServerPort());
        }
        if (this.addContextName()) {
            link.append(request.getContextPath());
        }
    } else if (this.isRelativeBaseUrl()) {
        if (this.addContextName()) {
            link.append(request.getContextPath());
        }
    } else {
        link.append(this.getConfigManager().getParam(SystemConstants.PAR_APPL_BASE_URL));
    }
}
 
Example 10
Source File: DefinedFileServlet.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    final String path = request.getServletPath();
    if(_expectedPath == null || _expectedPath.equals(path == null ? "" : path))
    {
        try (OutputStream output = HttpManagementUtil.getOutputStream(request, response))
        {
            try (InputStream fileInput = getClass().getResourceAsStream("/resources/" + _filename))
            {
                if (fileInput != null)
                {
                    byte[] buffer = new byte[1024];
                    response.setStatus(HttpServletResponse.SC_OK);
                    int read = 0;

                    while ((read = fileInput.read(buffer)) > 0)
                    {
                        output.write(buffer, 0, read);
                    }
                }
                else
                {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "unknown file: " + _filename);
                }
            }
        }
    }
    else
    {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        try (OutputStream output = HttpManagementUtil.getOutputStream(request, response))
        {
            final String notFoundMessage = "Unknown path '"
                             + request.getServletPath()
                             + "'. Please read the api docs at "
                             + request.getScheme()
                             + "://" + request.getServerName() + ":" + request.getServerPort() + _apiDocsPath + "\n";
            output.write(notFoundMessage.getBytes(StandardCharsets.UTF_8));
        }
    }
}
 
Example 11
Source File: ResourceUtil.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 获取当前域名路径
 * @param request
 * @return
 */
public static String getBasePath() {
	HttpServletRequest request = ContextHolderUtils.getRequest();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
	return basePath;
}
 
Example 12
Source File: Globals.java    From poi with Apache License 2.0 4 votes vote down vote up
public static String getBasePath(HttpServletRequest request) {
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName()
			+ ":" + request.getServerPort() + path + "/";
	return basePath;
}
 
Example 13
Source File: LoginServiceImpl.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void resetPassword(String username, String emailAddress, String productName) throws ServerException {
	UserDAO userDao = (UserDAO) Context.get().getBean(UserDAO.class);
	User user = userDao.findByUsername(username);

	if (user == null)
		throw new ServerException(String.format("User %s not found", username));
	else if (!user.getEmail().trim().equals(emailAddress.trim()))
		throw new ServerException(String.format("Email %s is wrong", emailAddress));

	try {
		EMail email;
		email = new EMail();
		email.setHtml(1);
		email.setTenantId(user.getTenantId());
		Recipient recipient = new Recipient();
		recipient.setAddress(user.getEmail());
		recipient.setRead(1);
		email.addRecipient(recipient);
		email.setFolder("outbox");

		// Prepare a new download ticket
		String ticketid = (UUID.randomUUID().toString());
		Ticket ticket = new Ticket();
		ticket.setTicketId(ticketid);
		ticket.setDocId(0L);
		ticket.setUserId(user.getId());
		ticket.setTenantId(user.getTenantId());
		ticket.setType(Ticket.PSW_RECOVERY);
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MINUTE, +5);
		ticket.setExpired(cal.getTime());

		// Store the ticket
		TicketDAO ticketDao = (TicketDAO) Context.get().getBean(TicketDAO.class);
		ticketDao.store(ticket);

		// Try to clean the DB from old tickets
		ticketDao.deleteExpired();

		Locale locale = user.getLocale();

		email.setLocale(locale);
		email.setSentDate(new Date());
		email.setUsername(user.getUsername());

		HttpServletRequest request = this.getThreadLocalRequest();
		String urlPrefix = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath();
		String address = urlPrefix + "/pswrecovery?ticketId=" + ticketid + "&userId=" + user.getId();

		/*
		 * Prepare the template
		 */
		Map<String, Object> dictionary = new HashMap<String, Object>();
		dictionary.put("product", productName);
		dictionary.put("url", address);
		dictionary.put("user", user);
		dictionary.put(Automation.LOCALE, locale);

		EMailSender sender = new EMailSender(user.getTenantId());
		sender.send(email, "psw.rec2", dictionary);
	} catch (Throwable e) {
		log.error(e.getMessage(), e);
		throw new ServerException(e.getMessage());
	}
}
 
Example 14
Source File: FIDOUtil.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public static String getOrigin(HttpServletRequest request) {

		return request.getScheme() + "://" + request.getServerName() + ":" +
		       request.getServerPort();
	}
 
Example 15
Source File: Config.java    From wings with Apache License 2.0 4 votes vote down vote up
private void createDefaultPortalConfig(HttpServletRequest request) {
      String server = request.getScheme() + "://" + request.getServerName() + ":"
              + request.getServerPort();
      String storageDir = null;
      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";
      
      File storageDirFile = new File(storageDir);
      if (!storageDirFile.exists() && !storageDirFile.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();
      }
  }
 
Example 16
Source File: WsHandshakeRequest.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private static URI buildRequestUri(HttpServletRequest req) {

        StringBuffer uri = new StringBuffer();
        String scheme = req.getScheme();
        int port = req.getServerPort();
        if (port < 0) {
            // Work around java.net.URL bug
            port = 80;
        }

        if ("http".equals(scheme)) {
            uri.append("ws");
        } else if ("https".equals(scheme)) {
            uri.append("wss");
        } else {
            // Should never happen
            throw new IllegalArgumentException(
                    sm.getString("wsHandshakeRequest.unknownScheme", scheme));
        }

        uri.append("://");
        uri.append(req.getServerName());

        if ((scheme.equals("http") && (port != 80))
            || (scheme.equals("https") && (port != 443))) {
            uri.append(':');
            uri.append(port);
        }

        uri.append(req.getRequestURI());

        if (req.getQueryString() != null) {
            uri.append("?");
            uri.append(req.getQueryString());
        }

        try {
            return new URI(uri.toString());
        } catch (URISyntaxException e) {
            // Should never happen
            throw new IllegalArgumentException(
                    sm.getString("wsHandshakeRequest.invalidUri", uri.toString()), e);
        }
    }
 
Example 17
Source File: ServletRequestCopy.java    From onedev with MIT License 4 votes vote down vote up
public ServletRequestCopy(HttpServletRequest request) {
	this.servletPath = request.getServletPath();
	this.contextPath = request.getContextPath();
	this.pathInfo = request.getPathInfo();
	this.requestUri = request.getRequestURI();
	this.requestURL = request.getRequestURL();
	this.method = request.getMethod();
	this.serverName = request.getServerName();
	this.serverPort = request.getServerPort();
	this.protocol = request.getProtocol();
	this.scheme = request.getScheme();
	
	
	/*
	 * have to comment out below two lines as otherwise web socket will
	 * report UnSupportedOperationException upon connection
	 */
	//this.characterEncoding = request.getCharacterEncoding();
	//this.contentType = request.getContentType();
	//this.requestedSessionId = request.getRequestedSessionId();
	this.characterEncoding = null;
	this.contentType = null;
	this.requestedSessionId = null;
	
	this.locale = request.getLocale();
	this.locales = request.getLocales();
	this.isSecure = request.isSecure();
	this.remoteUser = request.getRemoteUser();
	this.remoteAddr = request.getRemoteAddr();
	this.remoteHost = request.getRemoteHost();
	this.remotePort = request.getRemotePort();
	this.localAddr = request.getLocalAddr();
	this.localName = request.getLocalName();
	this.localPort = request.getLocalPort();
	this.pathTranslated = request.getPathTranslated();
	this.principal = request.getUserPrincipal();

	HttpSession session = request.getSession(true);
	httpSession = new HttpSessionCopy(session);

	String s;
	Enumeration<String> e = request.getHeaderNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		Enumeration<String> headerValues = request.getHeaders(s);
		this.headers.put(s, headerValues);
	}

	e = request.getAttributeNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		attributes.put(s, request.getAttribute(s));
	}

	e = request.getParameterNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		parameters.put(s, request.getParameterValues(s));
	}
}
 
Example 18
Source File: SwaggerMappingSupport.java    From swagger with Apache License 2.0 4 votes vote down vote up
private String resolveBaseUrl(HttpServletRequest request) {
    return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + this.urlPrefix;
}
 
Example 19
Source File: MetadataController.java    From spring-security-saml-java-sp with Apache License 2.0 3 votes vote down vote up
protected String getBaseURL(HttpServletRequest request) {

        String baseURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        log.debug("Base URL {}", baseURL);
        return baseURL;

    }
 
Example 20
Source File: HttpKit.java    From spring-boot-demo-all with Apache License 2.0 2 votes vote down vote up
/**
 * 获取项目路径和项目名
 *
 * @return
 */
public static String getServerPath() {
    HttpServletRequest request = HttpKit.getRequest();
    return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}