javax.servlet.http.HttpServletRequest#getScheme()源码实例Demo

下面列出了javax.servlet.http.HttpServletRequest#getScheme() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: RDFS   文件: DfsServlet.java
/** 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);
}
 
源代码2 项目: MybatisGenerator-UI   文件: IndexController.java
@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();
}
 
源代码3 项目: hadoop   文件: RMWebServices.java
@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() + "://");
}
 
源代码4 项目: orion.server   文件: EmailConfirmationServlet.java
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;
}
 
@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();
    }
}
 
源代码6 项目: heimdall   文件: HeimdallDecorationFilter.java
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);
    }
 
protected String getServerName(HttpServletRequest request)
{
	String hostname = sysAdminParams.getAlfrescoHost();
       if (hostname == null)
       {
       	hostname = request.getScheme();
       }
       hostname = request.getServerName();
       return hostname;
}
 
源代码8 项目: entando-core   文件: URLManager.java
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));
    }
}
 
源代码9 项目: webstart   文件: JnlpFileHandler.java
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();
}
 
源代码10 项目: wings   文件: Config.java
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();
      }
  }
 
源代码11 项目: swagger   文件: SwaggerMappingSupport.java
private String resolveBaseUrl(HttpServletRequest request) {
    return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + this.urlPrefix;
}
 
源代码12 项目: onedev   文件: ServletRequestCopy.java
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));
	}
}
 
源代码13 项目: Tomcat8-Source-Read   文件: WsHandshakeRequest.java
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);
        }
    }
 
源代码14 项目: qpid-broker-j   文件: DefinedFileServlet.java
@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));
        }
    }
}
 
源代码15 项目: carbon-identity   文件: FIDOUtil.java
public static String getOrigin(HttpServletRequest request) {

		return request.getScheme() + "://" + request.getServerName() + ":" +
		       request.getServerPort();
	}
 
@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());
	}
}
 
源代码17 项目: poi   文件: Globals.java
public static String getBasePath(HttpServletRequest request) {
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName()
			+ ":" + request.getServerPort() + path + "/";
	return basePath;
}
 
源代码18 项目: jeecg   文件: ResourceUtil.java
/**
 * 获取当前域名路径
 * @param request
 * @return
 */
public static String getBasePath() {
	HttpServletRequest request = ContextHolderUtils.getRequest();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
	return basePath;
}
 
protected String getBaseURL(HttpServletRequest request) {

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

    }
 
源代码20 项目: spring-boot-demo-all   文件: HttpKit.java
/**
 * 获取项目路径和项目名
 *
 * @return
 */
public static String getServerPath() {
    HttpServletRequest request = HttpKit.getRequest();
    return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}