Example usage for javax.servlet.http HttpServletRequest getServerPort

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

Introduction

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

Prototype

public int getServerPort();

Source Link

Document

Returns the port number to which the request was sent.

Usage

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

/**
 * Sets the http request data.// w  w  w  .j a v a2 s  . com
 * 
 * @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:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void buildRequestInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response,
        boolean showResponse) {
    sb.append("Request class=" + request.getClass().getName());
    sb.append(", RequestedSessionId=").append(request.getRequestedSessionId());

    sb.append(LF).append(IND);/* ww  w .  jav  a2 s .c  o  m*/
    sb.append(", REQUEST_URI=").append(request.getRequestURI());
    sb.append(", SERVLET_PATH=").append(request.getServletPath());
    sb.append(", CharacterEncoding=" + request.getCharacterEncoding());
    sb.append(", ContentLength=").append(request.getContentLength());

    sb.append(LF).append(IND);
    sb.append(", ContentType=").append(request.getContentType());
    sb.append(", Locale=").append(request.getLocale());
    sb.append(", Locales=");
    final Enumeration<?> locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        final Locale locale = (Locale) locales.nextElement();
        if (first) {
            first = false;
        } else {
            sb.append(", ");
        }
        sb.append(locale.toString());
    }
    sb.append(", Scheme=").append(request.getScheme());
    sb.append(", isSecure=").append(request.isSecure());

    sb.append(LF).append(IND);
    sb.append(", SERVER_PROTOCOL=").append(request.getProtocol());
    sb.append(", REMOTE_ADDR=").append(request.getRemoteAddr());
    sb.append(", REMOTE_HOST=").append(request.getRemoteHost());
    sb.append(", SERVER_NAME=").append(request.getServerName());
    sb.append(", SERVER_PORT=").append(request.getServerPort());

    sb.append(LF).append(IND);
    sb.append(", ContextPath=").append(request.getContextPath());
    sb.append(", REQUEST_METHOD=").append(request.getMethod());
    sb.append(", PathInfo=").append(request.getPathInfo());
    sb.append(", RemoteUser=").append(request.getRemoteUser());

    sb.append(LF).append(IND);
    sb.append(", REQUEST_URL=").append(request.getRequestURL());
    sb.append(LF).append(IND);
    sb.append(", QUERY_STRING=").append(request.getQueryString());
    if (showResponse) {
        sb.append(LF).append(IND);
        buildResponseInfo(sb, request, response);
    }

    sb.append(LF);
    buildRequestHeaders(sb, request);
    buildRequestParameters(sb, request);
    buildCookies(sb, request);
    buildRequestAttributes(sb, request);
    buildSessionAttributes(sb, request);
}

From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java

/**
 * PAAA services//w w w  .  j a v  a  2 s .com
 */
private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String format, String patronid, String token, String service) throws IOException {

    String baseurl = httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort();
    this.logger.info("[" + config.getProperty("service.name") + "] " + "baseurl = " + baseurl);

    ObjectMapper mapper = new ObjectMapper();

    if (Lookup.lookupAll(IntegratedLibrarySystem.class).size() > 0) {

        try {
            IntegratedLibrarySystem integratedLibrarySystem = Lookup.lookup(IntegratedLibrarySystem.class);
            // init ILS
            integratedLibrarySystem.init(this.config);

            switch (service) {

            case "signup": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2create = mapper.readValue(jb.toString(), Patron.class);
                if (patron2create.getAccount() == null || patron2create.getAccount().equals("")) {
                    if (!patronid.equals("")) {
                        patron2create.setAccount(patronid);
                    } else {
                        patron2create.setAccount(UUID.randomUUID().toString());
                    }
                }

                patron = integratedLibrarySystem.signup(patron2create);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    Block block = new Block();
                    LocalDateTime timePoint = LocalDateTime.now();
                    block.setDate(timePoint.getYear() + "-"
                            + (timePoint.getMonthValue() < 10 ? "0" + timePoint.getMonthValue()
                                    : timePoint.getMonthValue())
                            + "-" + (timePoint.getDayOfMonth() < 10 ? "0" + timePoint.getDayOfMonth()
                                    : timePoint.getDayOfMonth()));
                    block.setKey("93");
                    integratedLibrarySystem.blockpatron(patron, block);

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "newpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2create = mapper.readValue(jb.toString(), Patron.class);
                patron2create.setAccount(patronid);

                patron = integratedLibrarySystem.newpatron(patron2create);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "updatepatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2update = mapper.readValue(jb.toString(), Patron.class);
                patron2update.setAccount(patronid);

                // TODO Was tun bei nderung des 'status'?

                patron = integratedLibrarySystem.updatepatron(patron2update);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "blockpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2block = new Patron();
                patron2block.setAccount(patronid);
                Block block = mapper.readValue(jb.toString(), Block.class);

                patron = integratedLibrarySystem.blockpatron(patron2block, block);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "unblockpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2unblock = new Patron();
                patron2unblock.setAccount(patronid);
                Block block = mapper.readValue(jb.toString(), Block.class);

                patron = integratedLibrarySystem.unblockpatron(patron2unblock, block);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "deletepatron": {

                Patron patron = null;

                Patron patron2delete = new Patron();
                patron2delete.setAccount(patronid);

                patron = integratedLibrarySystem.deletepatron(patron2delete);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "newfee": {

                Patron patron = null;
                Fee resultFee = null;

                patron = new Patron();
                patron.setAccount(patronid);

                // read Fee
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Fee = " + jb);

                Fee fee = mapper.readValue(jb.toString(), Fee.class);

                resultFee = integratedLibrarySystem.newfee(patron, fee);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");
                StringWriter stringWriter = new StringWriter();
                mapper.writeValue(stringWriter, resultFee);
                this.logger.debug(
                        "[" + config.getProperty("service.name") + "] " + "Fee: " + stringWriter.toString());

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, resultFee);
                    this.logger.debug(json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            default: {
                // TODO: keine gltige Funktion
            }
            }
        } catch (ILSException e) {

            this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service
                    + "' event for patron '" + patronid + "' >>> failed!");
            this.logger.error("[" + config.getProperty("service.name") + "] "
                    + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": ILS Error! " + e.getMessage());

            // TODO e.getMessage = 403
            if (e.getMessage().equals("403")) {

                // TODO >> properties
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(
                        this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN)));
                requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                requestError.setDescription(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".description"));
                requestError.setErrorUri(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".uri"));

                StringWriter json = new StringWriter();
                mapper.writeValue(json, requestError);
                this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                // send response
                httpServletResponse.getWriter().println(json);
            } else {

                // Mail to Bib-IT wg. Socket-Error
                try {

                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);

                    Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));
                    mailer.postMail(
                            "[" + this.config.getProperty("service.name") + "] ILS Error! " + e.getMessage(),
                            sw.toString());

                } catch (MessagingException | IOException e1) {

                    this.logger.error(e1.getMessage(), e1.getCause());
                }

                // TODO >> properties
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
                requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

                StringWriter json = new StringWriter();
                mapper.writeValue(json, requestError);
                this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                // send response
                httpServletResponse.getWriter().println(json);
            }
        }
    } else {

        this.logger.error("[" + config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

        httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
        httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
        requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        requestError.setDescription(this.config.getProperty(
                "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
        requestError.setErrorUri(this.config.getProperty(
                "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

        StringWriter json = new StringWriter();
        mapper.writeValue(json, requestError);
        this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

        // send response
        httpServletResponse.getWriter().println(json);
    }

}

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 {//  ww  w.  j a v  a  2s  .c o m

        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:org.apache.jsp.communities_jsp.java

public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) {
      if (localCookie)
          CookieHandler.setDefault(cm);

      try {/*from   w  ww . java  2  s.  com*/
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          URL url = new URL(API_ROOT + addr);
          URLConnection urlConnection = url.openConnection();
          String cookieVal = getBrowserInfiniteCookie(request);
          if (cookieVal != null) {
              urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
              urlConnection.setDoInput(true);
              urlConnection.setDoOutput(true);
              urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
          }
          IOUtils.copy(urlConnection.getInputStream(), output);
          String newCookie = getConnectionInfiniteCookie(urlConnection);
          if (newCookie != null && response != null) {
              setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
          }
          return output.toString();
      } catch (IOException e) {
          System.out.println(e.getMessage());
          return null;
      }
  }

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();//from  w  w w.java2  s.co 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;
}

From source file:org.apache.sling.resourceresolver.impl.ResourceResolverImpl.java

/**
 * full implementation - apply sling:alias from the resource path - apply
 * /etc/map mappings (inkl. config backwards compat) - return absolute uri
 * if possible// w  ww  .j a  v a  2  s.c o m
 *
 * @see org.apache.sling.api.resource.ResourceResolver#map(javax.servlet.http.HttpServletRequest,
 *      java.lang.String)
 */
@Override
public String map(final HttpServletRequest request, final String resourcePath) {
    checkClosed();

    // find a fragment or query
    int fragmentQueryMark = resourcePath.indexOf('#');
    if (fragmentQueryMark < 0) {
        fragmentQueryMark = resourcePath.indexOf('?');
    }

    // cut fragment or query off the resource path
    String mappedPath;
    final String fragmentQuery;
    if (fragmentQueryMark >= 0) {
        fragmentQuery = resourcePath.substring(fragmentQueryMark);
        mappedPath = resourcePath.substring(0, fragmentQueryMark);
        logger.debug("map: Splitting resource path '{}' into '{}' and '{}'",
                new Object[] { resourcePath, mappedPath, fragmentQuery });
    } else {
        fragmentQuery = null;
        mappedPath = resourcePath;
    }

    // cut off scheme and host, if the same as requested
    final String schemehostport;
    final String schemePrefix;
    if (request != null) {
        schemehostport = MapEntry.getURI(request.getScheme(), request.getServerName(), request.getServerPort(),
                "/");
        schemePrefix = request.getScheme().concat("://");
        logger.debug("map: Mapping path {} for {} (at least with scheme prefix {})",
                new Object[] { resourcePath, schemehostport, schemePrefix });

    } else {

        schemehostport = null;
        schemePrefix = null;
        logger.debug("map: Mapping path {} for default", resourcePath);

    }

    ParsedParameters parsed = new ParsedParameters(mappedPath);
    final Resource res = resolveInternal(parsed.getRawPath(), parsed.getParameters());

    if (res != null) {

        // keep, what we might have cut off in internal resolution
        final String resolutionPathInfo = res.getResourceMetadata().getResolutionPathInfo();

        logger.debug("map: Path maps to resource {} with path info {}", res, resolutionPathInfo);

        // find aliases for segments. we can't walk the parent chain
        // since the request session might not have permissions to
        // read all parents SLING-2093
        final LinkedList<String> names = new LinkedList<String>();

        Resource current = res;
        String path = res.getPath();
        while (path != null) {
            String alias = null;
            if (current != null && !path.endsWith(JCR_CONTENT_LEAF)) {
                if (factory.getMapEntries().isOptimizeAliasResolutionEnabled()) {
                    logger.debug("map: Optimize Alias Resolution is Enabled");
                    String parentPath = ResourceUtil.getParent(path);
                    if (parentPath != null) {
                        final Map<String, String> aliases = factory.getMapEntries().getAliasMap(parentPath);
                        if (aliases != null && aliases.containsValue(current.getName())) {
                            for (String key : aliases.keySet()) {
                                if (current.getName().equals(aliases.get(key))) {
                                    alias = key;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    logger.debug("map: Optimize Alias Resolution is Disabled");
                    alias = ResourceResolverControl.getProperty(current, PROP_ALIAS);
                }
            }
            if (alias == null || alias.length() == 0) {
                alias = ResourceUtil.getName(path);
            }
            names.add(alias);
            path = ResourceUtil.getParent(path);
            if ("/".equals(path)) {
                path = null;
            } else if (path != null) {
                current = res.getResourceResolver().resolve(path);
            }
        }

        // build path from segment names
        final StringBuilder buf = new StringBuilder();

        // construct the path from the segments (or root if none)
        if (names.isEmpty()) {
            buf.append('/');
        } else {
            while (!names.isEmpty()) {
                buf.append('/');
                buf.append(names.removeLast());
            }
        }

        // reappend the resolutionPathInfo
        if (resolutionPathInfo != null) {
            buf.append(resolutionPathInfo);
        }

        // and then we have the mapped path to work on
        mappedPath = buf.toString();

        logger.debug("map: Alias mapping resolves to path {}", mappedPath);

    }

    boolean mappedPathIsUrl = false;
    for (final MapEntry mapEntry : this.factory.getMapEntries().getMapMaps()) {
        final String[] mappedPaths = mapEntry.replace(mappedPath);
        if (mappedPaths != null) {

            logger.debug("map: Match for Entry {}", mapEntry);

            mappedPathIsUrl = !mapEntry.isInternal();

            if (mappedPathIsUrl && schemehostport != null) {

                mappedPath = null;

                for (final String candidate : mappedPaths) {
                    if (candidate.startsWith(schemehostport)) {
                        mappedPath = candidate.substring(schemehostport.length() - 1);
                        mappedPathIsUrl = false;
                        logger.debug("map: Found host specific mapping {} resolving to {}", candidate,
                                mappedPath);
                        break;
                    } else if (candidate.startsWith(schemePrefix) && mappedPath == null) {
                        mappedPath = candidate;
                    }
                }

                if (mappedPath == null) {
                    mappedPath = mappedPaths[0];
                }

            } else {

                // we can only go with assumptions selecting the first entry
                mappedPath = mappedPaths[0];

            }

            logger.debug("resolve: MapEntry {} matches, mapped path is {}", mapEntry, mappedPath);

            break;
        }
    }

    // this should not be the case, since mappedPath is primed
    if (mappedPath == null) {
        mappedPath = resourcePath;
    }

    // [scheme:][//authority][path][?query][#fragment]
    try {
        // use commons-httpclient's URI instead of java.net.URI, as it can
        // actually accept *unescaped* URIs, such as the "mappedPath" and
        // return them in proper escaped form, including the path, via
        // toString()
        final URI uri = new URI(mappedPath, false);

        // 1. mangle the namespaces in the path
        String path = mangleNamespaces(uri.getPath());

        // 2. prepend servlet context path if we have a request
        if (request != null && request.getContextPath() != null && request.getContextPath().length() > 0) {
            path = request.getContextPath().concat(path);
        }
        // update the path part of the URI
        uri.setPath(path);

        mappedPath = uri.toString();
    } catch (final URIException e) {
        logger.warn("map: Unable to mangle namespaces for " + mappedPath + " returning unmangled", e);
    }

    logger.debug("map: Returning URL {} as mapping for path {}", mappedPath, resourcePath);

    // reappend fragment and/or query
    if (fragmentQuery != null) {
        mappedPath = mappedPath.concat(fragmentQuery);
    }

    return mappedPath;
}

From source file:crds.pub.FCKeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it.//w  ww.j  ava  2  s. c o m
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    FormUserOperation formUser = Constant.getFormUserOperation(request);
    String fck_task_id = (String) request.getSession().getAttribute("fck_task_id");
    if (fck_task_id == null) {
        fck_task_id = "temp_task_id";
    }

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String typeStr = request.getParameter("Type");

    String currentPath = baseDir + formUser.getCompany_code() + "/" + fck_task_id + "/" + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdirs();
    }

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');

            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);

            //???IP
            String server_ip = (String) session.getAttribute("server_ip");
            if (server_ip == null) {
                server_ip = CommonMethod.getServerIP(request) + ":" + request.getServerPort();//???IP?
            }
            String url = "http://" + server_ip + currentPath.substring(2, currentPath.length());

            fileUrl = url + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    fileUrl = url + "/" + newName;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } else {
                retVal = "202";
                errorMessage = "";
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

}

From source file:org.apache.jsp.sources_jsp.java

public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) {
       if (localCookie)
           CookieHandler.setDefault(cm);

       try {/*www.  j  av  a  2 s . c  o  m*/
           ByteArrayOutputStream output = new ByteArrayOutputStream();
           URL url = new URL(API_ROOT + addr);
           URLConnection urlConnection = url.openConnection();
           String cookieVal = getBrowserInfiniteCookie(request);
           if (cookieVal != null) {
               urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
               urlConnection.setDoInput(true);
               urlConnection.setDoOutput(true);
               urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
           }
           IOUtils.copy(urlConnection.getInputStream(), output);
           String newCookie = getConnectionInfiniteCookie(urlConnection);
           if (newCookie != null && response != null) {
               setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
           }
           return output.toString();
       } catch (IOException e) {
           System.out.println(e.getMessage());
           return null;
       }
   }