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:dk.teachus.frontend.TeachUsApplication.java

public String getServerUrl() {
    String serverUrl = getConfiguration().getConfiguration(ApplicationConfiguration.SERVER_URL);

    /*/*from www  .j a  va 2 s . com*/
     * If the server URL is empty, then the administrator have misconfigured the system (forgot to set the
     * server URL in the settings). We will get the server URL from the current server, but we will also
     * warn the administrator by adding an entry to the log.
     */
    if (Strings.isEmpty(serverUrl)) {
        log.error("No server url is set for the system. It's very important that you set it."); //$NON-NLS-1$

        RequestCycle cycle = RequestCycle.get();
        ServletWebRequest request = (ServletWebRequest) cycle.getRequest();
        HttpServletRequest httpServletRequest = request.getContainerRequest();

        StringBuilder b = new StringBuilder();
        b.append(httpServletRequest.getScheme()).append("://"); //$NON-NLS-1$
        b.append(httpServletRequest.getServerName());
        if (httpServletRequest.getServerPort() != 80 && httpServletRequest.getServerPort() != 443) {
            b.append(":").append(httpServletRequest.getServerPort()); //$NON-NLS-1$
        }

        serverUrl = b.toString();
    }

    return serverUrl;
}

From source file:org.esigate.servlet.impl.RequestFactory.java

public IncomingRequest create(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException {
    HttpServletRequestContext context = new HttpServletRequestContext(request, response, servletContext,
            filterChain);// www . j a  v  a  2 s.c o m
    // create request line
    String uri = UriUtils.createURI(request.getScheme(), request.getServerName(), request.getServerPort(),
            request.getRequestURI(), request.getQueryString(), null);
    ProtocolVersion protocolVersion = BasicLineParser.parseProtocolVersion(request.getProtocol(), null);
    IncomingRequest.Builder builder = IncomingRequest
            .builder(new BasicRequestLine(request.getMethod(), uri, protocolVersion));
    builder.setContext(context);
    // copy headers
    @SuppressWarnings("rawtypes")
    Enumeration names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        @SuppressWarnings("rawtypes")
        Enumeration values = request.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            builder.addHeader(name, value);
        }
    }
    // create entity
    HttpServletRequestEntity entity = new HttpServletRequestEntity(request);
    builder.setEntity(entity);

    builder.setRemoteAddr(request.getRemoteAddr());
    builder.setRemoteUser(request.getRemoteUser());
    HttpSession session = request.getSession(false);
    if (session != null) {
        builder.setSessionId(session.getId());
    }
    builder.setUserPrincipal(request.getUserPrincipal());

    // Copy cookies
    // As cookie header contains only name=value so we don't need to copy
    // all attributes!
    javax.servlet.http.Cookie[] src = request.getCookies();
    if (src != null) {
        for (int i = 0; i < src.length; i++) {
            javax.servlet.http.Cookie c = src[i];
            BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue());
            builder.addCookie(dest);
        }
    }
    builder.setSession(new HttpServletSession(request));
    builder.setContextPath(request.getContextPath());
    return builder.build();
}

From source file:br.gov.jfrj.siga.base.SigaHTTP.java

/**
 * @param URL/*w ww .  j  av  a  2s .c o m*/
 * @param request (se for modulo play, setar pra null)
 * @param cookieValue (necessario apenas nos modulos play)
 */
public String get(String URL, HttpServletRequest request, String cookieValue) {
    String html = "";

    if (URL.startsWith("/"))
        URL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + URL;

    try {
        // Efetua o request para o Service Provider (mdulo)
        Request req = Request.Get(URL);
        //    req.addHeader(COOKIE, JSESSIONID_PREFIX+getCookie(request, cookieValue));
        // Atribui o html retornado e pega o header do Response
        // Se a aplicao j efetuou a autenticao entre o mdulo da URL o contedo ser trago nesse primeiro GET
        // Caso contrrio passar pelo processo de autenticao (if abaixo)
        html = req.execute().handleResponse(new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse httpResponse)
                    throws ClientProtocolException, IOException {
                // O atributo que importa nesse header  o set-cookie que ser utilizado posteriormente
                headers = httpResponse.getAllHeaders();
                return IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
            }
        });

        // Verifica se retornou o form de autenticao do picketlink 
        if (html.contains(HTTP_POST_BINDING_REQUEST)) {
            // Atribui o cookie recuperado no response anterior
            String setCookie = null;
            try {
                setCookie = extractCookieFromHeader(getHeader(SET_COOKIE));
            } catch (ElementNotFoundException elnf) {
                log.warning("Nao encontrou o set-cookie");
                setCookie = getCookie(request, cookieValue);
            }

            // Atribui o valor do SAMLRequest contido no html retornado no GET efetuado.
            String SAMLRequestValue = getAttributeValueFromHtml(html, SAMLRequest);
            // Atribui a URL do IDP (sigaidp)
            String idpURL = getAttributeActionFromHtml(html);

            // Faz um novo POST para o IDP com o SAMLRequest como parametro e utilizando o sessionID do IDP
            html = Request.Post(idpURL).addHeader(COOKIE, JSESSIONID_PREFIX + getIdp(request))
                    .bodyForm(Form.form().add(SAMLRequest, SAMLRequestValue).build()).execute().returnContent()
                    .toString();

            // Extrai o valor do SAMLResponse
            // Caso o SAMLResponse no esteja disponvel aqui,  porque o JSESSIONID utilizado no foi o do IDP.
            String SAMLResponseValue = getAttributeValueFromHtml(html, SAMLResponse);

            // Faz um POST para o SP com o atributo SAMLResponse utilizando o sessionid do primeiro GET
            // O retorno  discartado pois o resultado  um 302.
            Request.Post(URL).addHeader(COOKIE, JSESSIONID_PREFIX + setCookie)
                    .bodyForm(Form.form().add(SAMLResponse, SAMLResponseValue).build()).execute()
                    .discardContent();

            // Agora que estamos autenticado efetua o GET para pgina desejada.
            html = Request.Get(URL).addHeader(COOKIE, JSESSIONID_PREFIX + setCookie).execute().returnContent()
                    .toString();
            if (html.contains(HTTP_POST_BINDING_REQUEST)) {
                log.info("Alguma coisa falhou na autenticao!: " + idpURL);
            }
        }
    } catch (Exception io) {
        io.printStackTrace();
    }

    return html;
}

From source file:org.cloudfoundry.identity.uaa.varz.VarzEndpoint.java

/**
 * Compute a base url for links.//from   w  w w.j  a v a  2 s. com
 * 
 * @param request the current request
 * @return a computed base url for this application, or the hard-coded {@link #setBaseUrl(String) value} if set
 */
@ModelAttribute("baseUrl")
public String getBaseUrl(HttpServletRequest request) {
    if (this.baseUrl != null) {
        return this.baseUrl;
    }
    String scheme = request.getScheme();
    StringBuffer url = new StringBuffer(scheme + "://");
    url.append(request.getServerName());
    int port = request.getServerPort();
    if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
        url.append(":" + port);
    }
    url.append(request.getContextPath());
    return url.toString();
}

From source file:org.elissa.server.AMLSupport.java

/**
 * The POST request.EPCUpload.java/*  www.j  a va 2 s .  c om*/
 */
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {

    PrintWriter out = null;

    FileItem fileItem = null;

    try {
        String oryxBaseUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath() + "/";

        // Get the PrintWriter
        res.setContentType("text/plain");
        res.setCharacterEncoding("utf-8");

        out = res.getWriter();

        // No isMultipartContent => Error
        final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req);
        if (!isMultipartContent) {
            printError(out, "No Multipart Content transmitted.");
            return;
        }

        // Get the uploaded file
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        servletFileUpload.setSizeMax(-1);
        final List<?> items;

        items = servletFileUpload.parseRequest(req);
        if (items.size() != 1) {
            printError(out, "Not exactly one File.");
            return;
        }

        fileItem = (FileItem) items.get(0);

        // replace dtd reference by existing reference /oryx/lib/ARIS-Export.dtd
        String amlStr = fileItem.getString("UTF-8");

        amlStr = amlStr.replaceFirst("\"ARIS-Export.dtd\"", "\"" + oryxBaseUrl + "lib/ARIS-Export.dtd\"");

        FileOutputStream fileout = null;
        OutputStreamWriter outwriter = null;

        try {
            fileout = new FileOutputStream(((DiskFileItem) fileItem).getStoreLocation());
            outwriter = new OutputStreamWriter(fileout, "UTF-8");
            outwriter.write(amlStr);
            outwriter.flush();

        } finally {
            if (outwriter != null)
                outwriter.close();
            if (fileout != null)
                fileout.close();
        }

        //parse AML file
        AMLParser parser = new AMLParser(((DiskFileItem) fileItem).getStoreLocation().getAbsolutePath());
        parser.parse();
        Collection<EPC> epcs = new HashSet<EPC>();
        Iterator<String> ids = parser.getModelIds().iterator();
        while (ids.hasNext()) {
            String modelId = ids.next();
            epcs.add(parser.getEPC(modelId));
        }

        // serialize epcs to eRDF oryx format
        OryxSerializer oryxSerializer = new OryxSerializer(epcs, oryxBaseUrl);
        oryxSerializer.parse();

        Document outputDocument = oryxSerializer.getDocument();

        // get document as string
        String docAsString = "";

        Source source = new DOMSource(outputDocument);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer transformer = tfactory.newTransformer();
        transformer.transform(source, result);
        docAsString = stringWriter.getBuffer().toString();

        // write response
        out.print("" + docAsString + "");

    } catch (Exception e) {
        handleException(out, e);
    } finally {
        if (fileItem != null) {
            fileItem.delete();
        }
    }
}

From source file:com.francelabs.datafari.servlets.URL.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)//from  www. j a va2 s .  c om
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    final String protocol = request.getScheme() + ":";

    final Map<String, String[]> requestMap = new HashMap<>();
    requestMap.putAll(request.getParameterMap());
    final IndexerQuery query = IndexerServerManager.createQuery();
    query.addParams(requestMap);
    // get the AD domain
    String domain = "";
    HashMap<String, String> h;
    try {
        h = RealmLdapConfiguration.getConfig(request);

        if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) {
            final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase();
            final String[] parts = userBase.split(",");
            domain = "";
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].indexOf("dc=") != -1) { // Check if the current
                    // part is a domain
                    // component
                    if (!domain.isEmpty()) {
                        domain += ".";
                    }
                    domain += parts[i].substring(parts[i].indexOf('=') + 1);
                }
            }
        }

        // Add authentication
        if (request.getUserPrincipal() != null) {
            String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", "");
            if (AuthenticatedUserName.contains("@")) {
                AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@"));
            }
            if (!domain.equals("")) {
                AuthenticatedUserName += "@" + domain;
            }
            query.setParam("AuthenticatedUserName", AuthenticatedUserName);
        }
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    StatsPusher.pushDocument(query, protocol);

    // String surl = URLDecoder.decode(request.getParameter("url"),
    // "ISO-8859-1");
    final String surl = request.getParameter("url");

    if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true")
            && !surl.startsWith("file://///")) {

        final int BUFSIZE = 4096;
        String fileName = null;

        /**
         * File Display/Download --> <!-- Written by Rick Garcia -->
         */
        if (SystemUtils.IS_OS_LINUX) {
            // try to open the file locally
            final String fileNameA[] = surl.split(":");
            fileName = URLDecoder.decode(fileNameA[1], "UTF-8");

        } else if (SystemUtils.IS_OS_WINDOWS) {
            fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", "");
        }

        final File file = new File(fileName);
        int length = 0;
        final ServletOutputStream outStream = response.getOutputStream();
        final ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(fileName);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";

        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());

        // sets HTTP header
        response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\"");

        final byte[] byteBuffer = new byte[BUFSIZE];
        final DataInputStream in = new DataInputStream(new FileInputStream(file));

        // reads the file's bytes and writes them to the response stream
        while (in != null && (length = in.read(byteBuffer)) != -1) {
            outStream.write(byteBuffer, 0, length);
        }

        in.close();
        outStream.close();
    } else {

        final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl);
        rd.forward(request, response);
    }
}

From source file:be.fedict.eid.dss.sp.servlet.DownloadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doGet");
    HttpSession httpSession = request.getSession();
    byte[] document = (byte[]) httpSession.getAttribute("document");

    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    if (!request.getScheme().equals("https")) {
        // else the download fails in IE
        response.setHeader("Pragma", "no-cache"); // http 1.0
    } else {/*  w  w w. j  av  a2 s  . c o m*/
        response.setHeader("Pragma", "public");
    }
    response.setDateHeader("Expires", -1);
    response.setContentLength(document.length);

    String contentType = (String) httpSession.getAttribute("ContentType");
    LOG.debug("content-type: " + contentType);
    response.setContentType(contentType);
    response.setContentLength(document.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(document);
    out.flush();
}

From source file:com.saint.spring.saml.web.MetadataController.java

protected String getBaseURL(HttpServletRequest request) {

    String baseURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath();/*w ww . j  ava 2s . co m*/
    log.debug("Base URL {}", baseURL);
    return baseURL;

}

From source file:fi.okm.mpass.shibboleth.authn.impl.BaseInitializeWilmaContext.java

/**
 * Constructs an URL where the user is redirected for authentication.
 * @param flowExecutionUrl The current flow execution URL, to be included in the redirect URL.
 * @param authenticationContext The context, also containing {@link WilmaAuthenticationContext}.
 * @return The redirect URL containing the checksum.
 *///from  w  ww .  j a v  a 2s  .  c om
public String getRedirect(final String flowExecutionUrl, final AuthenticationContext authenticationContext) {
    final HttpServletRequest httpRequest = getHttpServletRequest();
    final WilmaAuthenticationContext wilmaContext = authenticationContext
            .getSubcontext(WilmaAuthenticationContext.class);
    final StringBuffer redirectToBuffer = new StringBuffer(
            httpRequest.getScheme() + "://" + httpRequest.getServerName());
    if (httpRequest.getServerPort() != 443) {
        redirectToBuffer.append(":" + httpRequest.getServerPort());
    }
    redirectToBuffer.append(flowExecutionUrl).append(getAsParameter("&", "_eventId_proceed", "1"));
    redirectToBuffer
            .append(getAsParameter("&", WilmaAuthenticationContext.PARAM_NAME_NONCE, wilmaContext.getNonce()));
    final URLCodec urlCodec = new URLCodec();
    try {
        final StringBuffer unsignedUrlBuffer = new StringBuffer(wilmaContext.getRedirectUrl());
        unsignedUrlBuffer.append(getAsParameter("?", WilmaAuthenticationContext.PARAM_NAME_REDIRECT_TO,
                urlCodec.encode(redirectToBuffer.toString())));
        if (authenticationContext.isForceAuthn()) {
            unsignedUrlBuffer
                    .append(getAsParameter("&", WilmaAuthenticationContext.PARAM_NAME_FORCE_AUTH, "true"));
        }
        final String redirectUrl = unsignedUrlBuffer.toString() + getAsParameter("&",
                WilmaAuthenticationContext.PARAM_NAME_CHECKSUM,
                calculateChecksum(Mac.getInstance(algorithm), unsignedUrlBuffer.toString(), signatureKey));
        return redirectUrl;
    } catch (EncoderException | NoSuchAlgorithmException e) {
        log.error("{}: Could not encode the following URL {}", getLogPrefix(), redirectToBuffer, e);
    }
    return null;
}

From source file:com.oscgc.security.saml.idp.web.contoller.MetadataController.java

protected String getBaseURL(HttpServletRequest request) {

    StringBuffer sb = new StringBuffer();
    sb.append(request.getScheme()).append("://").append(request.getServerName()).append(":")
            .append(request.getServerPort());
    sb.append(request.getContextPath());

    String baseURL = sb.toString();
    log.debug("Base URL {}", baseURL);
    return baseURL;

}