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:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpEmailFrom");
    }/*from  w  w w .jav  a  2  s.c  o m*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser,
        ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpEmailFrom");
    }//from w w  w . ja  v  a  2 s  .com

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:com.provenance.cloudprovenance.traceabilitystore.ws.controler.TraceabilityStoreController.java

@Override
@POST/*from   w w  w  . java 2 s.co  m*/
@Path(value = "/{serviceId}/{traceabilityType}")
public Response createTraceabilityDocument(@PathParam("serviceId") String serviceId,
        @PathParam("traceabilityType") String traceabilityType, @Context HttpServletRequest request) {

    boolean response = false;
    String bodyText = null;

    // Read the http message body contents
    try {
        bodyText = getBody(request);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Check if the current traceability record Id exists
    if (currentTraceabilityRecordId == null) {
        currentTraceabilityRecordId = "TraceabilityRecord-" + (System.currentTimeMillis());
        String currentTraceabilityRecordIdFileName = constructTraceabilityFileName(currentTraceabilityRecordId);

        // create a blank document first
        response = traceabilityStoreService.createTraceabilityInstance(serviceId, traceabilityType,
                currentTraceabilityRecordIdFileName);
    }

    if (bodyText == null || bodyText.equals("")) {
        // add template content
        String tempelateProvText = this.getTemplateProvFile();
        logger.info("Creating traceability record with template content ");
        response = traceabilityStoreService.createTraceabilityEntry(serviceId, traceabilityType,
                constructTraceabilityFileName(currentTraceabilityRecordId), "", tempelateProvText);
        logger.info("Traceability record created successfully");
    } else {

        // add sent traceability data
        logger.info("Creating traceability record with the content from the request: \n" + bodyText);
        response = traceabilityStoreService.createTraceabilityEntry(serviceId, traceabilityType,
                constructTraceabilityFileName(currentTraceabilityRecordId), "", bodyText);

        logger.info("traceability record created successfully");
    }

    String responseUri = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI() + "/" + currentTraceabilityRecordId;

    String responseContent = trResponse.genTraceabilityRecordIdResponse(currentTraceabilityRecordId, serviceId,
            defaultFileExtensionOfrecord, responseUri);

    logger.info("response content: " + responseUri);

    if (response == true) {
        ResponseBuilder rBuilder = Response.status(201);
        rBuilder.entity(responseContent);
        return rBuilder.build();
    } else {
        ResponseBuilder rBuilder = Response.status(400);
        return rBuilder.build();

    }
}

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Sets the http request data.//  www .ja  va 2s.c  o  m
 * 
 * @param request the request
 * @param requestContainer the request container
 */
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
    requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
    requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
    requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
    requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
    requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
    requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
    requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
    requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
    requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
    if (request.getUserPrincipal() != null)
        requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE,
            String.valueOf(request.isRequestedSessionIdFromCookie()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL,
            String.valueOf(request.isRequestedSessionIdFromURL()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID,
            String.valueOf(request.isRequestedSessionIdValid()));
    requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        requestContainer.setAttribute(headerName, headerValue);
    } // while (headerNames.hasMoreElements())
    requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
    requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}

From source file:fr.hoteia.qalingo.core.web.util.impl.RequestUtilImpl.java

/**
  * /*from   w ww. j  a v a  2 s.  c  om*/
  */
public String getCustomerAvatar(final HttpServletRequest request, final Customer customer) throws Exception {
    String customerAvatar = null;
    if (customer != null) {
        if (StringUtils.isNotEmpty(customer.getAvatarImg())) {
            customerAvatar = customer.getAvatarImg();
        } else {
            String email = customer.getEmail().toLowerCase().trim();
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(email.getBytes("CP1252"));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
            String gravatarId = sb.toString();
            if ("https".equals(request.getScheme())) {
                customerAvatar = "https://secure.gravatar.com/avatar/" + gravatarId;
            } else {
                customerAvatar = "http://www.gravatar.com/avatar/" + gravatarId;
            }
        }
    }
    return customerAvatar;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebServices.java

@GET
@Path("/apps/{appid}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public AppInfo getApp(@Context HttpServletRequest hsr, @PathParam("appid") String appId) {
    init();// w w w  .  j a v a2s.c o  m
    ApplicationId id = WebAppUtils.parseApplicationId(recordFactory, appId);
    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() + "://");
}

From source file:org.acegisecurity.ui.savedrequest.SavedRequest.java

public SavedRequest(HttpServletRequest request, PortResolver portResolver) {
    Assert.notNull(request, "Request required");
    Assert.notNull(portResolver, "PortResolver required");

    // Cookies//from ww  w.  ja  v a  2s  .co m
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            this.addCookie(cookies[i]);
        }
    }

    // Headers
    Enumeration names = request.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = request.getHeaders(name);

        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            this.addHeader(name, value);
        }
    }

    // Locales
    Enumeration locales = request.getLocales();

    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        this.addLocale(locale);
    }

    // Parameters
    Map parameters = request.getParameterMap();
    Iterator paramNames = parameters.keySet().iterator();

    while (paramNames.hasNext()) {
        String paramName = (String) paramNames.next();
        Object o = parameters.get(paramName);
        if (o instanceof String[]) {
            String[] paramValues = (String[]) o;
            this.addParameter(paramName, paramValues);
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("ServletRequest.getParameterMap() returned non-String array");
            }
        }
    }

    // Primitives
    this.method = request.getMethod();
    this.pathInfo = request.getPathInfo();
    this.queryString = request.getQueryString();
    this.requestURI = request.getRequestURI();
    this.serverPort = portResolver.getServerPort(request);
    this.requestURL = request.getRequestURL().toString();
    this.scheme = request.getScheme();
    this.serverName = request.getServerName();
    this.contextPath = request.getContextPath();
    this.servletPath = request.getServletPath();
}

From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java

@Override
protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta)
        throws ServletException, IOException {

    String tipo = requisicao.getContentType();
    if (tipo == null || tipo.isEmpty())
        tipo = "text/plain";

    String codificacao = requisicao.getCharacterEncoding();
    if (codificacao == null || codificacao.isEmpty())
        codificacao = "UTF-8";

    resposta.setCharacterEncoding(codificacao);
    PrintWriter saida = resposta.getWriter();

    try {/*w w  w. j  a  v  a  2  s  .c  om*/

        JSON json;

        if (tipo.contains("json")) {
            json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao));
        } else {
            json = new JSON();
        }

        Enumeration<String> parametros = requisicao.getParameterNames();

        while (parametros.hasMoreElements()) {
            String chave = parametros.nextElement();
            String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao);
            json.put(chave, valor);
        }

        if (tipo.contains("multipart")) {

            Collection<Part> arquivos = requisicao.getParts();

            if (!arquivos.isEmpty()) {

                File diretorio = new File(uxiAmarelo.getDiretorio());

                if (!diretorio.isAbsolute()) {
                    diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator
                            + uxiAmarelo.getDiretorio());
                }

                if (!diretorio.exists())
                    diretorio.mkdirs();

                String diretorioStr = diretorio.getAbsolutePath();

                String url = uxiAmarelo.getDiretorioURL();

                if (uxiAmarelo.isDiretorioURLRelativo()) {
                    String url_esquema = requisicao.getScheme();
                    String url_servidor = requisicao.getServerName();
                    int url_porta = requisicao.getServerPort();
                    String url_contexto = requisicao.getContextPath();
                    url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url;
                }

                if (url.charAt(url.length() - 1) == '/') {
                    url = url.substring(0, url.length() - 1);
                }

                Map<String, List<JSON>> mapa_arquivos = new HashMap<>();

                for (Part arquivo : arquivos) {

                    String chave = arquivo.getName();
                    String nome_original = getNome(arquivo, codificacao);
                    String nome = nome_original;

                    if (nome == null || nome.isEmpty()) {
                        try (InputStream is = arquivo.getInputStream()) {
                            String valor = IOUtils.toString(is, codificacao);
                            valor = URLDecoder.decode(valor, codificacao);
                            json.put(chave, valor);
                            continue;
                        }
                    }

                    if (uxiAmarelo.getArquivoNome().equals("uuid")) {
                        nome = UUID.randomUUID().toString();
                    }

                    while (new File(diretorioStr + File.separator + nome).exists()) {
                        nome = UUID.randomUUID().toString();
                    }

                    arquivo.write(diretorioStr + File.separator + nome);

                    List<JSON> lista = mapa_arquivos.get(chave);

                    if (lista == null) {
                        lista = new LinkedList<>();
                        mapa_arquivos.put(chave, lista);
                    }

                    lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome));

                }

                for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) {
                    List<JSON> lista = entrada.getValue();
                    if (lista.size() > 1) {
                        json.put(entrada.getKey(), lista);
                    } else {
                        json.put(entrada.getKey(), lista.get(0));
                    }
                }

            }

        }

        String copaiba = (String) json.remove("copaiba");
        if (StringUtil.tamanho(copaiba) == 0) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String[] copaibaParam = copaiba.split("@");
        if (copaibaParam.length != 3) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String comando = (String) json.remove("uxicmd");
        if (StringUtil.tamanho(comando) == 0)
            comando = null;

        if (uxiAmarelo.isCookieEnviar()) {
            Cookie[] cookies = requisicao.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String nome = cookie.getName();
                    if (uxiAmarelo.cookieBloqueado(nome))
                        continue;
                    if (!json.has(nome)) {
                        try {
                            json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            json.put(nome, cookie.getValue());
                        }
                    }
                }
            }
        }

        if (uxiAmarelo.isEncapsulamentoAutomatico()) {
            final String sepstr = uxiAmarelo.getEncapsulamentoSeparador();
            final char sep0 = sepstr.charAt(0);
            for (String chave : new HashSet<>(json.keySet())) {
                if (chave.indexOf(sep0) == -1)
                    continue;
                String[] caminho = chave.split(sepstr);
                if (caminho.length > 1) {
                    Util.encapsular(caminho, json.remove(chave), json);
                }
            }
        }

        String resultado;

        if (comando == null) {
            try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) {
                resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]);
                if (resultado == null)
                    resultado = "";
            }
        } else if (comando.equals("voltar")) {
            resultado = json.toString();
            comando = null;
        } else {
            resultado = "";
        }

        if (comando == null) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("application/json");

            saida.write(resultado);

        } else if (comando.startsWith("redirecionar")) {

            resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado));

        } else if (comando.startsWith("base64")) {

            String url = comando.substring("base64.".length());

            resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8")));

        } else if (comando.startsWith("html_url")) {

            HttpURLConnection con = (HttpURLConnection) new URL(
                    Util.obterStringDeJSON("html_url", comando, resultado)).openConnection();
            con.setRequestProperty("User-Agent", "Uxi-amarelo");

            if (con.getResponseCode() != HttpServletResponse.SC_OK)
                throw new IOException("HTTP = " + con.getResponseCode());

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            try (InputStream is = con.getInputStream()) {
                saida.write(IOUtils.toString(is));
            }

            con.disconnect();

        } else if (comando.startsWith("html")) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            saida.write(Util.obterStringDeJSON("html", comando, resultado));

        } else {

            throw new IllegalArgumentException(comando);

        }

    } catch (Exception e) {

        resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resposta.setContentType("application/json");

        saida.write(Util.gerarRespostaErro(e).toString());

    }

    saida.flush();

}

From source file:com.reachcall.pretty.http.ProxyServlet.java

private void execute(Match match, HttpRequestBase method, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    LOG.log(Level.FINE, "Requesting {0}", method.getURI());

    HttpClient client = this.getClient();
    HttpResponse response = client.execute(method);

    for (Header h : response.getHeaders("Set-Cookie")) {
        String line = parseCookie(h.getValue());
        LOG.log(Level.FINER, method.getURI() + "{0}", new Object[] { line });

        if (line != null) {
            LOG.log(Level.INFO, "Bonding session {0} to host {1}",
                    new Object[] { line, match.destination.hostAndPort() });

            try {
                resolver.bond(line, match);
            } catch (ExecutionException ex) {
                Logger.getLogger(ProxyServlet.class.getName()).log(Level.SEVERE, null, ex);
                this.releaseClient(client);

                throw new ServletException(ex);
            }/*from  w  w w .j  a v  a  2  s  . c om*/
        }
    }

    int rc = response.getStatusLine().getStatusCode();

    if ((rc >= HttpServletResponse.SC_MULTIPLE_CHOICES) && (rc < HttpServletResponse.SC_NOT_MODIFIED)) {
        String location = response.getFirstHeader(HEADER_LOCATION).getValue();

        if (location == null) {
            throw new ServletException("Recieved status code: " + rc + " but no " + HEADER_LOCATION
                    + " header was found in the response");
        }

        String hostname = req.getServerName();

        if ((req.getServerPort() != 80) && (req.getServerPort() != 443)) {
            hostname += (":" + req.getServerPort());
        }

        hostname += req.getContextPath();

        String replaced = location.replace(match.destination.hostAndPort() + match.path.getDestination(),
                hostname);

        if (replaced.startsWith("http://")) {
            replaced = replaced.replace("http:", req.getScheme() + ":");
        }

        resp.sendRedirect(replaced);
        this.releaseClient(client);

        return;
    } else if (rc == HttpServletResponse.SC_NOT_MODIFIED) {
        resp.setIntHeader(HEADER_CONTENT_LENTH, 0);
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        this.releaseClient(client);

        return;
    }

    resp.setStatus(rc);

    Header[] headerArrayResponse = response.getAllHeaders();

    for (Header header : headerArrayResponse) {
        resp.setHeader(header.getName(), header.getValue());
    }

    if (response.getEntity() != null) {
        resp.setContentLength((int) response.getEntity().getContentLength());

        response.getEntity().writeTo(resp.getOutputStream());
    }

    this.releaseClient(client);

    LOG.finer("Done.");
}

From source file:nl.b3p.viewer.util.SelectedContentCache.java

private JSONObject processCache(HttpServletRequest request, JSONObject cached, EntityManager em)
        throws JSONException {
    Set<String> roles = Authorizations.getRoles(request, em);

    JSONObject levels = cached.getJSONObject("levels");
    JSONObject appLayers = cached.getJSONObject("appLayers");
    JSONArray selectedContent = cached.getJSONArray("selectedContent");
    JSONObject services = cached.has("services") ? cached.getJSONObject("services") : new JSONObject();

    // sortedKeys() was removed form the api in https://github.com/stleary/JSON-java/commit/9a0471d5a100f6cfb253db52353a2595f5866582
    // not sure if sorting is relevant here, but it was doing 
    // TreeSet keySet = new TreeSet(appLayers.keySet());
    // so if sorting is required we can do
    // for (Iterator<String> it = new TreeSet(appLayers.keySet()).iterator(); it.hasNext();) {
    for (Iterator<String> it = appLayers.keys(); it.hasNext();) {
        String key = it.next();/*  ww w .  j  a va 2 s  . c  o m*/
        JSONObject appLayer = appLayers.getJSONObject(key);
        boolean allowed = isAppLayerAllowed(appLayer, roles);
        if (!allowed) {
            it.remove();
        }
    }

    for (Iterator it = levels.keys(); it.hasNext();) {
        String key = (String) it.next();
        JSONObject level = levels.getJSONObject(key);
        boolean allowed = isLevelAllowed(level, roles);
        if (!allowed) {
            it.remove();
        }
        JSONArray newLayers = new JSONArray();
        if (level.has("layers")) {
            JSONArray layers = level.getJSONArray("layers");
            for (int i = 0; i < layers.length(); i++) {
                String layerId = layers.getString(i);
                if (appLayers.has(layerId)) {
                    newLayers.put(layerId);
                }
            }
            level.put("layers", newLayers);
        }
    }

    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = request.getServerPort();
    String contextPath = request.getContextPath();
    StringBuilder url = new StringBuilder();
    String servletPath = "/action/proxy/wms";
    url.append(scheme).append("://").append(serverName);

    if ((serverPort != 80) && (serverPort != 443)) {
        url.append(":").append(serverPort);
    }

    url.append(contextPath).append(servletPath);
    final String proxyUrl = url.toString();
    for (Iterator<String> it = services.keys(); it.hasNext();) {

        String key = it.next();
        JSONObject service = services.getJSONObject(key);
        if (service.has(GeoService.DETAIL_USE_PROXY) && service.getBoolean(GeoService.DETAIL_USE_PROXY)) {
            try {
                String actualURL = service.getString("url");
                String param = URLEncoder.encode(actualURL, "UTF-8");
                StringBuilder newUrl = new StringBuilder(proxyUrl);
                newUrl.append("?url=");
                newUrl.append(param);
                if (service.has(GeoService.PARAM_MUST_LOGIN)
                        && service.getBoolean(GeoService.PARAM_MUST_LOGIN)) {
                    newUrl.append("&mustLogin=true&serviceId=");
                    newUrl.append(service.get("id"));
                }
                service.put("url", newUrl);
            } catch (UnsupportedEncodingException ex) {
                log.error("Cannot add proxy url for service: ", ex);
            }
        }
    }

    JSONArray newSelectedContent = new JSONArray();
    for (int i = 0; i < selectedContent.length(); i++) {
        JSONObject obj = selectedContent.getJSONObject(i);
        String type = obj.getString("type");
        String id = obj.getString("id");
        if (type.equalsIgnoreCase("level")) {
            if (isLevelAllowed(id, levels)) {
                newSelectedContent.put(obj);
            }
        }
    }

    cached.put("selectedContent", newSelectedContent);
    return cached;
}