Example usage for javax.servlet.http HttpServletRequest getScheme

List of usage examples for javax.servlet.http HttpServletRequest getScheme

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getScheme.

Prototype

public String getScheme();

Source Link

Document

Returns the name of the scheme used to make this request, for example, <code>http</code>, <code>https</code>, or <code>ftp</code>.

Usage

From source file:ch.entwine.weblounge.dispatcher.impl.WebloungeDispatcherServlet.java

/**
 * {@inheritDoc}//w w w.  j a  v a  2s.c o  m
 * 
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ServletException, IOException {

    // Return the instance name if available
    if (instanceName != null) {
        httpResponse.addHeader("X-Weblounge-Instance", instanceName);
    }

    if (sites == null) {
        httpResponse.sendError(SC_SERVICE_UNAVAILABLE);
        return;
    }

    logger.debug("Serving {}", httpRequest.getRequestURI());

    // Get the site dispatcher
    Site site = securityService.getSite();
    if (site == null) {
        site = getSiteByRequest(httpRequest);
        securityService.setSite(site);
    }

    boolean isSpecialRequest = StringUtils.isNotBlank(httpRequest.getHeader("X-Weblounge-Special"));

    // See if a site dispatcher was found, and if so, if it's enabled
    if (site == null) {
        String serverName = httpRequest.getScheme() + "://" + httpRequest.getServerName();
        if (httpRequest.getServerPort() != 80)
            serverName += ":" + httpRequest.getServerPort();
        if (!wellknownFiles.contains(httpRequest.getRequestURI())
                && !missingSiteWarnings.contains(serverName)) {
            missingSiteWarnings.add(serverName);
            logger.warn("No site found to handle {}", serverName);
        }
        httpResponse.sendError(SC_NOT_FOUND);
        return;
    } else if (!site.isOnline() && !isSpecialRequest) {
        if (site.getContentRepository() == null) {
            if (!missingRepositoryWarnings.contains(site.getIdentifier())) {
                logger.warn("No content repository connected to site '{}'", site);
                missingRepositoryWarnings.add(site.getIdentifier());
            } else {
                logger.debug("No content repository connected to site '{}'", site);
            }
        } else {
            logger.debug("Ignoring request for disabled site '{}'", site);
        }
        httpResponse.sendError(SC_SERVICE_UNAVAILABLE);
        return;
    }

    // Make sure the response is buffered
    httpResponse = new BufferedHttpServletResponse(httpResponse);

    // Get the servlet that is responsible for the site's content
    Servlet siteServlet = sites.getSiteServlet(site);

    // Get the response cache, if available
    ResponseCache cache = caches.get(site.getIdentifier());

    // Wrap for caching
    if (cache != null) {
        httpResponse = cache.createCacheableResponse(httpRequest, httpResponse);
    }

    // Wrap request and response
    WebloungeRequestImpl request = new WebloungeRequestImpl(httpRequest, siteServlet, environment);
    WebloungeResponseImpl response = new WebloungeResponseImpl(httpResponse);

    // Configure request and response objects
    request.init(site);
    response.setRequest(request);
    response.setResponseCache(cache);
    response.setCharacterEncoding(DEFAULT_RESPONSE_ENCODING);
    response.setHeader("X-Powered-By", POWERED_BY);
    response.setDateHeader("Date", Calendar.getInstance().getTimeInMillis());

    // Notify listeners about starting request
    fireRequestStarted(request, response, site);

    boolean requestServed = false;

    // Ask the registered request handler if they are willing to handle
    // the request.
    try {
        securityService.setSite(site);
        request.setUser(securityService.getUser());
        for (RequestHandler handler : requestHandler) {
            try {
                logger.trace("Asking {} to serve {}", handler, request);
                if (handler.service(request, response)) {
                    requestServed = true;
                    logger.debug("{} served request {}", handler, request);
                    if (response.hasError()) {
                        logger.debug("Request processing failed on {}", request);
                        fireRequestFailed(request, response, site);
                    } else {
                        fireRequestDelivered(request, response, site);
                    }
                    return;
                }
            } catch (Throwable t) {
                response.invalidate();
                String params = RequestUtils.dumpParameters(request);
                if (t.getCause() != null) {
                    t = t.getCause();
                }
                logger.error("Request handler '{}' failed to handle {} {}",
                        new Object[] { handler, request, params });
                logger.error(t.getMessage(), t);
                DispatchUtils.sendInternalError(t.getMessage(), request, response);
                break;
            }
        }
    } finally {
        securityService.setSite(null);
        if (requestServed) {
            response.endResponse();
            response.flushBuffer();
            logger.debug("Finished processing of {}", httpRequest.getRequestURI());
        } else {
            logger.debug("No handler found for {}", request);
            DispatchUtils.sendNotFound(request, response);
            if (cache != null)
                cache.invalidate(response);
            fireRequestFailed(request, response, site);
        }
    }
}

From source file:org.cyk.ui.web.api.WebNavigationManager.java

public String url(String id, Object[] parameters, Boolean actionOutcome, Boolean partial, Boolean pretty) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    StringBuilder url = new StringBuilder();

    NavigationCase navigationCase = ((ConfigurableNavigationHandler) facesContext.getApplication()
            .getNavigationHandler()).getNavigationCase(facesContext, null, id);
    //System.out.println(id+" / "+navigationCase);
    if (navigationCase == null) {
        log.severe("No Navigation Case found for " + id);
        return url(OUTCOME_NOT_FOUND, new Object[] { "oc", id }, Boolean.FALSE, Boolean.FALSE);
    }/*from ww  w.  j a v a  2 s. c o m*/
    String s = navigationCase.getToViewId(facesContext);
    if (Boolean.TRUE.equals(actionOutcome))
        url.append(s);
    else
        url.append(StringUtils.replace(s, FILE_STATIC_EXTENSION, FILE_PROCESSING_EXTENSION));

    if (Boolean.TRUE.equals(actionOutcome))
        navigationHelper.addParameter(url, QUERY_PARAMETER_FACES_REDIRECT_NAME, navigationCase.isRedirect());
    if (parameters != null && parameters.length > 0) {
        for (int i = 0; i < parameters.length - 1; i = i + 2)
            if (parameters[i + 1] == null)
                ;
            else
                navigationHelper.addParameter(url, /*(String)*/ parameters[i], parameters[i + 1]);
    }
    if (Boolean.TRUE.equals(partial))
        ;
    else {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();

        //FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL() will trigger rewriting  

        //int countContextPath = StringUtils.countMatches(url, request.getContextPath());
        url = new StringBuilder(StringUtils.removeStartIgnoreCase(//TODO might not work always
                FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL(url.toString()),
                request.getContextPath()));
        //if(StringUtils.countMatches(url, request.getContextPath())>countContextPath)

        url.insert(0, request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath());
    }

    return url.toString();
}

From source file:org.openmrs.module.owa.web.controller.OwaRestController.java

@RequestMapping(value = "/rest/owa/addapp", method = RequestMethod.POST)
@ResponseBody/*from   w w w .java  2  s.c  o  m*/
public List<App> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    List<App> appList = new ArrayList<>();
    if (Context.hasPrivilege("Manage OWA")) {
        String message;
        HttpSession session = request.getSession();
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            File uploadedFile = new File(file.getOriginalFilename());
            file.transferTo(uploadedFile);
            try (ZipFile zip = new ZipFile(uploadedFile)) {
                if (zip.size() == 0) {
                    message = messageSourceService.getMessage("owa.blank_zip");
                    log.warn("Zip file is empty");
                    session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                    response.sendError(500, message);
                } else {
                    ZipEntry entry = zip.getEntry("manifest.webapp");
                    if (entry == null) {
                        message = messageSourceService.getMessage("owa.manifest_not_found");
                        log.warn("Manifest file could not be found in app");
                        uploadedFile.delete();
                        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                        response.sendError(500, message);
                    } else {
                        String contextPath = request.getScheme() + "://" + request.getServerName() + ":"
                                + request.getServerPort() + request.getContextPath();
                        appManager.installApp(uploadedFile, fileName, contextPath);
                        message = messageSourceService.getMessage("owa.app_installed");
                        session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, message);
                    }
                }
            } catch (Exception e) {
                message = messageSourceService.getMessage("owa.not_a_zip");
                log.warn("App is not a zip archive");
                uploadedFile.delete();
                session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                response.sendError(500, message);
            }
        }
        appManager.reloadApps();
        appList = appManager.getApps();
    }
    return appList;
}

From source file:de.uni_koeln.spinfo.maalr.webapp.controller.WebMVCController.java

@RequestMapping(value = "/persona/login", method = RequestMethod.POST)
@ResponseBody/* w  ww  .  j  av  a  2  s  . co  m*/
public String authenticateWithPersona(@RequestParam String assertion, HttpServletRequest request, Model model)
        throws IOException {

    String contextPath = Configuration.getInstance().getDictContext();

    if (SecurityContextHolder.getContext().getAuthentication() != null) {
        if (!SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser")) {
            Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext()
                    .getAuthentication().getAuthorities();
            for (GrantedAuthority grantedAuthority : authorities) {
                logger.info("GrantedAuthority: " + grantedAuthority.getAuthority());
                if (grantedAuthority.getAuthority().equals("ROLE_ADMIN"))
                    return contextPath + "/admin/admin";
                if (grantedAuthority.getAuthority().equals("ROLE_TRUSTED_IN"))
                    return contextPath + "/editor/editor";
                return contextPath;
            }
        }
    }

    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("assertion", assertion);
    params.add("audience", request.getScheme() + "://" + request.getServerName() + ":"
            + (request.getServerPort() == 80 ? "" : request.getServerPort()));

    // Initialize RestTamplate
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    PersonaVerificationResponse response = restTemplate.postForObject(
            "https://verifier.login.persona.org/verify", params, PersonaVerificationResponse.class);

    logger.info("PersonaAuth: PersonaVerificationResponse={}", response.toString());

    if (response.getStatus().equals("okay")) {
        request.getSession().setMaxInactiveInterval(30 * 60); // Set session timeout to 30 minutes
        MaalrUserInfo user = users.getByEmail(response.getEmail());
        if (user == null) {
            user = register(response);
            logger.info("PersonaAuth: signed up new user for email={}", user.getEmail());
            authUser(user);
            return contextPath;
        } else {
            logger.info("PersonaAuth: user found by email={}", user.getEmail());
            authUser(user);
            return contextPath;
        }
    } else {
        logger.warn("Persona authentication failed due to reason: " + response.getReason());
        throw new IllegalStateException("Authentication failed");
    }
}

From source file:com.provenance.cloudprovenance.policyhandler.ws.controler.PolicyRequestHandler.java

@Override
@POST/*from  w ww.j av  a  2  s. com*/
@Path(value = "/{serviceId}")
public Response policyRequest(@PathParam("serviceId") String serviceId, @Context HttpServletRequest request) {

    boolean outcome = false;
    String constructFileName, environmentId, response, responseURI, responseContent, policyRequestMsg;
    String[] policyToSelect;

    try {
        constructFileName = requestFileNamePrefix + counter + "." + fileNameSuffix;
        policyRequestMsg = getBody(request);

        // Store the request to the policy traceability (in traceability
        // store)
        outcome = policyTraceability.createRequestInstance(serviceId, traceabilityType, constructFileName,
                policyRequestMsg);
        logger.info("Saved policy request to the policy traceability store");

        // Call the policy controller to validate the policy, remove
        // namespace
        environmentId = (preqProcessor.getIdforPolicyMatch(policyRequestMsg, xpathToEnvironmentId))
                .split(":")[1];

        logger.info("The environment id to match a policy is: " + environmentId);

        policyToSelect = requestPolicyMappingMap.get(environmentId);
        logger.info("policy id is: " + policyToSelect[0]);

        response = preqProcessor.executePolicyRequest(serviceId, policyRequestMsg, policyToSelect, request);
        logger.info("policy execution response: " + response);

        responseURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getRequestURI() + "/" + responseFileNamePrefix + counter;

        // TODO - process the response store in in the hashmap
        responseContent = policyResponseGen.genPolicyIdResponse(serviceId, requestFileNamePrefix + counter,
                responseFileNamePrefix + counter, responseURI);

        logger.info("Storing response in a map: Key=> " + (responseFileNamePrefix + counter));

        // Store the response to the HashTable
        policyResponseMap.put((responseFileNamePrefix + counter), response);

        if (response != null) {
            ResponseBuilder rBuilder = Response.status(201);
            rBuilder.entity(responseContent);
            return rBuilder.build();
        } else {
            ResponseBuilder rBuilder = Response.status(400);
            return rBuilder.build();
        }
    } catch (Exception e) {
        e.printStackTrace();
        ResponseBuilder rBuilder = Response.status(500);
        return rBuilder.build();

    }
}

From source file:org.alfresco.repo.security.authentication.external.DefaultRemoteUserMapper.java

public String getRemoteUser(HttpServletRequest request) {
    if (logger.isDebugEnabled())
        logger.debug("Getting RemoteUser from http request.");
    if (!this.isEnabled) {
        if (logger.isDebugEnabled())
            logger.debug("DefaultRemoteUserMapper is disabled, returning null.");
        return null;
    }/*from  w  w  w  .  j  a  va  2 s. c  o  m*/
    String remoteUserId = request.getRemoteUser();
    String headerUserId = extractUserFromProxyHeader(request);
    if (logger.isDebugEnabled()) {
        logger.debug("The remote user id is: " + remoteUserId);
        logger.debug("The header user id is: " + headerUserId);
        logger.debug("The proxy user name is: " + this.proxyUserName);
    }
    if (this.proxyUserName == null) {
        // Normalize the user ID taking into account case sensitivity settings
        String normalizedUserId = normalizeUserId(headerUserId != null ? headerUserId : remoteUserId);
        if (logger.isDebugEnabled())
            logger.debug("Returning " + normalizedUserId);
        return normalizedUserId;
    } else if (remoteUserId == null) {
        String normalizedUserId = null;
        // Try to extract the remote user from SSL certificate
        // MNT-13989
        X509Certificate[] certs = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        if (request.getScheme().toLowerCase().equals("https") && certs != null && certs.length > 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Checking SSL certificate subject DN to match " + this.proxyUserName);
            }
            for (int i = 0; i < certs.length; i++) {
                String subjectDN = certs[i].getSubjectX500Principal().getName();
                if (logger.isDebugEnabled()) {
                    logger.debug("Found subject DN " + subjectDN);
                }
                if (subjectDN.equals(this.proxyUserName)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("The subject DN " + subjectDN + " matches " + this.proxyUserName);
                    }
                    // Found the subject distinguished name
                    remoteUserId = subjectDN;
                    // Normalize the user ID taking into account case sensitivity settings
                    normalizedUserId = normalizeUserId(headerUserId != null ? headerUserId : remoteUserId);
                    break;
                }
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Returning " + normalizedUserId);
        return normalizedUserId;
    } else {
        // Normalize the user ID taking into account case sensitivity settings
        String normalizedUserId = normalizeUserId(
                remoteUserId.equals(this.proxyUserName) ? headerUserId : remoteUserId);
        if (logger.isDebugEnabled())
            logger.debug("Returning " + normalizedUserId);
        return normalizedUserId;
    }
}

From source file:com.mirth.connect.server.servlets.WebStartServlet.java

private Document getAdministratorJnlp(HttpServletRequest request) throws Exception {
    InputStream is = ResourceUtil.getResourceStream(this.getClass(), "mirth-client.jnlp");
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
    IOUtils.closeQuietly(is);/*  www .  jav a  2 s.  co  m*/

    Element jnlpElement = document.getDocumentElement();

    // Change the title to include the version of Mirth Connect
    PropertiesConfiguration versionProperties = new PropertiesConfiguration();
    versionProperties.setDelimiterParsingDisabled(true);
    versionProperties.load(ResourceUtil.getResourceStream(getClass(), "version.properties"));
    String version = versionProperties.getString("mirth.version");

    Element informationElement = (Element) jnlpElement.getElementsByTagName("information").item(0);
    Element title = (Element) informationElement.getElementsByTagName("title").item(0);
    String titleText = title.getTextContent() + " " + version;

    // If a server name is set, prepend the application title with it
    String serverName = configurationController.getServerSettings().getServerName();
    if (StringUtils.isNotBlank(serverName)) {
        titleText = serverName + " - " + titleText;
    }

    title.setTextContent(titleText);

    String scheme = request.getScheme();
    String serverHostname = request.getServerName();
    int serverPort = request.getServerPort();
    String contextPath = request.getContextPath();
    String codebase = scheme + "://" + serverHostname + ":" + serverPort + contextPath;

    PropertiesConfiguration mirthProperties = new PropertiesConfiguration();
    mirthProperties.setDelimiterParsingDisabled(true);
    mirthProperties.load(ResourceUtil.getResourceStream(getClass(), "mirth.properties"));

    String server = null;

    if (StringUtils.isNotBlank(mirthProperties.getString("server.url"))) {
        server = mirthProperties.getString("server.url");
    } else {
        int httpsPort = mirthProperties.getInt("https.port", 8443);
        String contextPathProp = mirthProperties.getString("http.contextpath", "");

        // Add a starting slash if one does not exist
        if (!contextPathProp.startsWith("/")) {
            contextPathProp = "/" + contextPathProp;
        }

        // Remove a trailing slash if one exists
        if (contextPathProp.endsWith("/")) {
            contextPathProp = contextPathProp.substring(0, contextPathProp.length() - 1);
        }

        server = "https://" + serverHostname + ":" + httpsPort + contextPathProp;
    }

    jnlpElement.setAttribute("codebase", codebase);

    Element resourcesElement = (Element) jnlpElement.getElementsByTagName("resources").item(0);

    String maxHeapSize = request.getParameter("maxHeapSize");
    if (StringUtils.isBlank(maxHeapSize)) {
        maxHeapSize = mirthProperties.getString("administrator.maxheapsize");
    }
    if (StringUtils.isNotBlank(maxHeapSize)) {
        Element j2se = (Element) resourcesElement.getElementsByTagName("j2se").item(0);
        j2se.setAttribute("max-heap-size", maxHeapSize);
    }

    List<String> defaultClientLibs = new ArrayList<String>();
    defaultClientLibs.add("mirth-client.jar");
    defaultClientLibs.add("mirth-client-core.jar");
    defaultClientLibs.add("mirth-crypto.jar");
    defaultClientLibs.add("mirth-vocab.jar");

    for (String defaultClientLib : defaultClientLibs) {
        Element jarElement = document.createElement("jar");
        jarElement.setAttribute("download", "eager");
        jarElement.setAttribute("href", "webstart/client-lib/" + defaultClientLib);

        if (defaultClientLib.equals("mirth-client.jar")) {
            jarElement.setAttribute("main", "true");
        }

        resourcesElement.appendChild(jarElement);
    }

    List<String> clientLibs = ControllerFactory.getFactory().createExtensionController().getClientLibraries();

    for (String clientLib : clientLibs) {
        if (!defaultClientLibs.contains(clientLib)) {
            Element jarElement = document.createElement("jar");
            jarElement.setAttribute("download", "eager");
            jarElement.setAttribute("href", "webstart/client-lib/" + clientLib);
            resourcesElement.appendChild(jarElement);
        }
    }

    List<MetaData> allExtensions = new ArrayList<MetaData>();
    allExtensions
            .addAll(ControllerFactory.getFactory().createExtensionController().getConnectorMetaData().values());
    allExtensions
            .addAll(ControllerFactory.getFactory().createExtensionController().getPluginMetaData().values());

    // we are using a set so that we don't have duplicates
    Set<String> extensionPathsToAddToJnlp = new HashSet<String>();

    for (MetaData extension : allExtensions) {
        if (doesExtensionHaveClientOrSharedLibraries(extension)) {
            extensionPathsToAddToJnlp.add(extension.getPath());
        }
    }

    for (String extensionPath : extensionPathsToAddToJnlp) {
        Element extensionElement = document.createElement("extension");
        extensionElement.setAttribute("href", "webstart/extensions/" + extensionPath + ".jnlp");
        resourcesElement.appendChild(extensionElement);
    }

    Element applicationDescElement = (Element) jnlpElement.getElementsByTagName("application-desc").item(0);
    Element serverArgumentElement = document.createElement("argument");
    serverArgumentElement.setTextContent(server);
    applicationDescElement.appendChild(serverArgumentElement);
    Element versionArgumentElement = document.createElement("argument");
    versionArgumentElement.setTextContent(version);
    applicationDescElement.appendChild(versionArgumentElement);

    String[] protocols = configurationController.getHttpsClientProtocols();
    String[] cipherSuites = configurationController.getHttpsCipherSuites();

    // Only add arguments for the protocols / cipher suites if they are non-default
    if (!Arrays.areEqual(protocols, MirthSSLUtil.DEFAULT_HTTPS_CLIENT_PROTOCOLS)
            || !Arrays.areEqual(cipherSuites, MirthSSLUtil.DEFAULT_HTTPS_CIPHER_SUITES)) {
        Element sslArgumentElement = document.createElement("argument");
        sslArgumentElement.setTextContent("-ssl");
        applicationDescElement.appendChild(sslArgumentElement);

        Element protocolsArgumentElement = document.createElement("argument");
        protocolsArgumentElement.setTextContent(StringUtils.join(protocols, ','));
        applicationDescElement.appendChild(protocolsArgumentElement);

        Element cipherSuitesArgumentElement = document.createElement("argument");
        cipherSuitesArgumentElement.setTextContent(StringUtils.join(cipherSuites, ','));
        applicationDescElement.appendChild(cipherSuitesArgumentElement);
    }

    return document;
}

From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java

private Map<String, String> getRequestInfo(PortletRequest request) {
    Map<String, String> requestResult = new TreeMap<String, String>();

    HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);

    requestResult.put("RemoteUser", httpRequest.getRemoteUser());
    requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request));
    requestResult.put("RemoteAddr", httpRequest.getRemoteAddr());
    requestResult.put("RemoteHost", httpRequest.getRemoteHost());
    requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort()));
    requestResult.put("AuthType", httpRequest.getAuthType());
    requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding());
    requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength()));
    requestResult.put("ContentType", httpRequest.getContentType());
    requestResult.put("ContextPath", httpRequest.getContextPath());
    requestResult.put("LocalAddr", httpRequest.getLocalAddr());
    requestResult.put("Locale", httpRequest.getLocale().toString());
    requestResult.put("LocalName", httpRequest.getLocalName());
    requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort()));
    requestResult.put("Method", httpRequest.getMethod());
    requestResult.put("PathInfo", httpRequest.getPathInfo());
    requestResult.put("PathTranslated", httpRequest.getPathTranslated());
    requestResult.put("Protocol", httpRequest.getProtocol());
    requestResult.put("QueryString", httpRequest.getQueryString());
    requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId());
    requestResult.put("RequestURI", httpRequest.getRequestURI());
    requestResult.put("Scheme", httpRequest.getScheme());
    requestResult.put("ServerName", httpRequest.getServerName());
    requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort()));
    requestResult.put("ServletPath", httpRequest.getServletPath());

    return requestResult;
}

From source file:be.fedict.eid.dss.protocol.simple.client.SignatureRequestServlet.java

@SuppressWarnings("unchecked")
@Override//from  ww  w .j av  a2  s  . com
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doGet");

    String signatureRequest = (String) request.getSession().getAttribute(this.signatureRequestSessionAttribute);
    String signatureRequestId = (String) request.getSession()
            .getAttribute(this.signatureRequestIdSessionAttribute);
    String contentType = (String) request.getSession().getAttribute(this.contentTypeSessionAttribute);

    String dssDestination;
    String relayState;
    KeyStore.PrivateKeyEntry spIdentity = null;
    String language;

    SignatureRequestService service = this.signatureRequestServiceServiceLocator.locateService();
    if (null != service) {
        dssDestination = service.getDssDestination();
        relayState = service.getRelayState(request.getParameterMap());
        spIdentity = service.getSPIdentity();
        language = service.getLanguage();
    } else {
        dssDestination = this.target;
        relayState = (String) request.getSession().getAttribute(this.relayStateSessionAttribute);
        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;
        }
    }

    // generate and send a signature request
    try {
        SignatureRequestUtil.sendRequest(signatureRequest, signatureRequestId, contentType, dssDestination,
                spDestination, relayState, spIdentity, response, language);
    } catch (Exception e) {
        throw new ServletException(e);
    }

    // save state on session
    if (null != relayState) {
        setRelayState(relayState, request.getSession());
    }
    setTarget(spDestination, request.getSession());

}

From source file:org.apache.hadoop.hdfs.server.datanode.DatanodeJspHelper.java

static void generateDirectoryStructure(JspWriter out, HttpServletRequest req, HttpServletResponse resp,
        Configuration conf) throws IOException, InterruptedException {
    final String dir = JspHelper.validatePath(StringEscapeUtils.unescapeHtml(req.getParameter("dir")));
    if (dir == null) {
        out.print("Invalid input");
        return;/*from w w  w .  j  a  v a2s. co  m*/
    }
    String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);
    UserGroupInformation ugi = JspHelper.getUGI(req, conf);
    String namenodeInfoPortStr = req.getParameter("namenodeInfoPort");
    int namenodeInfoPort = -1;
    if (namenodeInfoPortStr != null)
        namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr);
    final String nnAddr = req.getParameter(JspHelper.NAMENODE_ADDRESS);
    if (nnAddr == null) {
        out.print(JspHelper.NAMENODE_ADDRESS + " url param is null");
        return;
    }

    DFSClient dfs = getDFSClient(ugi, nnAddr, conf);
    String target = dir;
    final HdfsFileStatus targetStatus = dfs.getFileInfo(target);
    if (targetStatus == null) { // not exists
        out.print("<h3>File or directory : " + StringEscapeUtils.escapeHtml(target) + " does not exist</h3>");
        JspHelper.printGotoForm(out, namenodeInfoPort, tokenString, target, nnAddr);
    } else {
        if (!targetStatus.isDir()) { // a file
            List<LocatedBlock> blocks = dfs.getNamenode().getBlockLocations(dir, 0, 1).getLocatedBlocks();

            LocatedBlock firstBlock = null;
            DatanodeInfo[] locations = null;
            if (blocks.size() > 0) {
                firstBlock = blocks.get(0);
                locations = firstBlock.getLocations();
            }
            if (locations == null || locations.length == 0) {
                out.print("Empty file");
            } else {
                DatanodeInfo chosenNode = JspHelper.bestNode(firstBlock, conf);
                int datanodePort = chosenNode.getXferPort();
                String redirectLocation = JspHelper.Url.url(req.getScheme(), chosenNode)
                        + "/browseBlock.jsp?blockId=" + firstBlock.getBlock().getBlockId() + "&blockSize="
                        + firstBlock.getBlock().getNumBytes() + "&genstamp="
                        + firstBlock.getBlock().getGenerationStamp() + "&filename="
                        + URLEncoder.encode(dir, "UTF-8") + "&datanodePort=" + datanodePort
                        + "&namenodeInfoPort=" + namenodeInfoPort
                        + JspHelper.getDelegationTokenUrlParam(tokenString)
                        + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr);
                resp.sendRedirect(redirectLocation);
            }
            return;
        }
        // directory
        // generate a table and dump the info
        String[] headings = { "Name", "Type", "Size", "Replication", "Block Size", "Modification Time",
                "Permission", "Owner", "Group" };
        out.print("<h3>Contents of directory ");
        JspHelper.printPathWithLinks(dir, out, namenodeInfoPort, tokenString, nnAddr);
        out.print("</h3><hr>");
        JspHelper.printGotoForm(out, namenodeInfoPort, tokenString, dir, nnAddr);
        out.print("<hr>");

        File f = new File(dir);
        String parent;
        if ((parent = f.getParent()) != null)
            out.print("<a href=\"" + req.getRequestURL() + "?dir=" + parent + "&namenodeInfoPort="
                    + namenodeInfoPort + JspHelper.getDelegationTokenUrlParam(tokenString)
                    + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr)
                    + "\">Go to parent directory</a><br>");

        DirectoryListing thisListing = dfs.listPaths(target, HdfsFileStatus.EMPTY_NAME);
        if (thisListing == null || thisListing.getPartialListing().length == 0) {
            out.print("Empty directory");
        } else {
            JspHelper.addTableHeader(out);
            int row = 0;
            JspHelper.addTableRow(out, headings, row++);
            String cols[] = new String[headings.length];
            do {
                HdfsFileStatus[] files = thisListing.getPartialListing();
                for (int i = 0; i < files.length; i++) {
                    String localFileName = files[i].getLocalName();
                    // Get the location of the first block of the file
                    if (!files[i].isDir()) {
                        cols[1] = "file";
                        cols[2] = StringUtils.byteDesc(files[i].getLen());
                        cols[3] = Short.toString(files[i].getReplication());
                        cols[4] = StringUtils.byteDesc(files[i].getBlockSize());
                    } else {
                        cols[1] = "dir";
                        cols[2] = "";
                        cols[3] = "";
                        cols[4] = "";
                    }
                    String datanodeUrl = req.getRequestURL() + "?dir="
                            + URLEncoder.encode(files[i].getFullName(target), "UTF-8") + "&namenodeInfoPort="
                            + namenodeInfoPort + JspHelper.getDelegationTokenUrlParam(tokenString)
                            + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr);
                    cols[0] = "<a href=\"" + datanodeUrl + "\">" + HtmlQuoting.quoteHtmlChars(localFileName)
                            + "</a>";
                    cols[5] = new SimpleDateFormat("yyyy-MM-dd HH:mm")
                            .format(new Date((files[i].getModificationTime())));
                    cols[6] = files[i].getPermission().toString();
                    cols[7] = files[i].getOwner();
                    cols[8] = files[i].getGroup();
                    JspHelper.addTableRow(out, cols, row++);
                }
                if (!thisListing.hasMore()) {
                    break;
                }
                thisListing = dfs.listPaths(target, thisListing.getLastName());
            } while (thisListing != null);
            JspHelper.addTableFooter(out);
        }
    }
    out.print("<br><a href=\"///" + JspHelper.canonicalize(nnAddr) + ":" + namenodeInfoPort
            + "/dfshealth.jsp\">Go back to DFS home</a>");
    dfs.close();
}