Example usage for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE

List of usage examples for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE.

Prototype

int SC_SERVICE_UNAVAILABLE

To view the source code for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE.

Click Source Link

Document

Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to handle the request.

Usage

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

public void doGet(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response)
        throws javax.servlet.ServletException, java.io.IOException {

    if (!isServePages()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Website is currently updating configuration. Please try again later.");
        return;// w w  w  .  j  a v  a2s .c o  m
    }

    Date startDate = new Date();

    if (this._contextPath == null) {
        this._contextPath = request.getContextPath();
        this._listenPort = request.getServerPort();
    }

    WGARequestInformation reqInfo = (WGARequestInformation) request
            .getAttribute(WGARequestInformation.REQUEST_ATTRIBUTENAME);

    try {

        // Parse request
        WGPRequestPath path = WGPRequestPath.parseRequest(this, request, response);
        request.setAttribute(WGACore.ATTRIB_REQUESTPATH, path);

        // If database login failed or access was denied exit immediately
        if (!path.isProceedRequest()) {
            return;
        }

        // Set access logging for this request
        if (path.getDatabase() != null) {
            String accessLoggingEnabled = (String) path.getDatabase()
                    .getAttribute(WGACore.DBATTRIB_ENABLE_ACCESSLOGGING);
            if (accessLoggingEnabled != null) {
                if (reqInfo != null) {
                    reqInfo.setLoggingEnabled(Boolean.parseBoolean(accessLoggingEnabled));
                }
            }
        }

        int iPathType = path.getPathType();

        // Treatment of special URL types
        String dbKey = path.getDatabaseKey();
        if (iPathType == WGPRequestPath.TYPE_INVALID) {
            throw new HttpErrorException(404, "Invalid path: " + path.getBasePath(), dbKey);
        }
        if (iPathType == WGPRequestPath.TYPE_INVALID_DB) {
            throw new HttpErrorException(404, "Specified application '" + dbKey + "' is unknown", null);
        }

        if (iPathType == WGPRequestPath.TYPE_UNKNOWN_CONTENT) {
            sendNoContentNotification(path, request, response, path.getDatabase());
            return;
        }

        if (iPathType == WGPRequestPath.TYPE_GOTO_HOMEPAGE) {
            iPathType = determineHomepage(request, path, iPathType);
        }

        if (iPathType == WGPRequestPath.TYPE_UNAVAILABLE_DB) {
            throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "The website is currently unavailable", path.getDatabaseKey());
        }

        if (iPathType == WGPRequestPath.TYPE_UNDEFINED_HOMEPAGE) {
            throw new HttpErrorException(
                    HttpServletResponse.SC_NOT_FOUND, "No home page was defined for app '"
                            + path.getDatabaseKey() + "'. Please specify an explicit content path.",
                    path.getDatabaseKey());
        }

        if (iPathType == WGPRequestPath.TYPE_TMLDEBUG) {
            _tmlDebugger.performDebugMode(request, response, request.getSession());
            return;
        }

        if (iPathType == WGPRequestPath.TYPE_JOBLOG) {
            sendJobLog(request, response, request.getSession());
            return;
        }

        if (iPathType == WGPRequestPath.TYPE_LOGOUT) {
            WGDatabase db = (WGDatabase) _core.getContentdbs().get(dbKey);
            String domain = (String) db.getAttribute(WGACore.DBATTRIB_DOMAIN);
            _core.logout(domain, request.getSession(), request, response, true);
            removeSessionCookie(response, request.getSession(), db);

            iPathType = WGPRequestPath.TYPE_REDIRECT;
        }

        if (iPathType == WGPRequestPath.TYPE_FAVICON) {
            String faviconPath = determineFavicon(request);
            if (faviconPath != null) {
                iPathType = WGPRequestPath.TYPE_REDIRECT;
                path.setResourcePath(faviconPath);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Favicon not defined");
                return;
            }
        }

        if (iPathType == WGPRequestPath.TYPE_TMLFORM) {
            dispatchTmlFormRequest(path, request, response);
            return;
        }

        // Treatment of base URL Types
        if (iPathType == WGPRequestPath.TYPE_REDIRECT) {
            String url = path.getResourcePath();
            if (path.appendQueryString() == true && request.getQueryString() != null
                    && !request.getQueryString().equals("")) {
                if (url.indexOf("?") != -1) {
                    url += "&" + request.getQueryString();
                } else {
                    url += "?" + request.getQueryString();
                }
            }

            if (path.isPermanentRedirect()) {
                sendPermanentRedirect(response, url);
            } else {
                sendRedirect(request, response, url);
            }
        } else if (iPathType != WGPRequestPath.TYPE_RESOURCE && iPathType != WGPRequestPath.TYPE_STATICTML
                && !_core.getContentdbs().containsKey(path.getDatabaseKey())) {
            throw new HttpErrorException(404, "Database '" + dbKey + "' is unknown", null);
        } else {

            String requestMethod = request.getMethod().toLowerCase();
            switch (iPathType) {
            case (WGPRequestPath.TYPE_TML):
            case (WGPRequestPath.TYPE_TITLE_PATH):

                // Fetch the redirect cookie
                Cookie lastRedirectCookie = null;
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals(COOKIE_LASTREDIRECT)) {
                            lastRedirectCookie = cookie;
                            break;
                        }
                    }
                }

                // If path is not complete redirect it to the complete path, if possible. Set redirect cookie to prevent endless redirections
                if (!path.isCompletePath()) {
                    String redirectPath = path.expandToCompletePath(request);
                    if (isRedirectable(request, redirectPath, lastRedirectCookie)) {
                        lastRedirectCookie = new WGCookie(COOKIE_LASTREDIRECT,
                                Hex.encodeHexString(redirectPath.getBytes("UTF-8")));
                        lastRedirectCookie.setMaxAge(-1);
                        lastRedirectCookie.setPath("/");
                        ((WGCookie) lastRedirectCookie).addCookieHeader(response);
                        sendRedirect(request, response, redirectPath);
                        break;
                    }
                }

                // Delete redirect cookie when exists on normal dispatching
                if (lastRedirectCookie != null) {
                    lastRedirectCookie = new WGCookie(COOKIE_LASTREDIRECT, "");
                    lastRedirectCookie.setMaxAge(0);
                    lastRedirectCookie.setPath("/");
                    ((WGCookie) lastRedirectCookie).addCookieHeader(response);
                }

                // Dispatch
                dispatchTmlRequest(path, request, response, startDate);
                break;

            case (WGPRequestPath.TYPE_FILE):
                dispatchFileRequest(path, request, response);
                break;

            case (WGPRequestPath.TYPE_CSS):
            case (WGPRequestPath.TYPE_JS):
                dispatchCssjsRequest(path, request, response);
                break;

            case (WGPRequestPath.TYPE_RESOURCE):
                dispatchResourceRequest(path, request, response);
                break;

            case (WGPRequestPath.TYPE_STATICTML):
                dispatchStaticTmlRequest(path, request, response);
                break;

            default:
                throw new HttpErrorException(500, "Invalid url format", dbKey);
            }
        }

        // moved from finally block to ensure errorpage can be displayed
        commitResponse(response);
    } catch (ClientAccessException exc) {
        response.sendError(403, exc.getMessage());
    } catch (AjaxFailureException exc) {
        handleAjaxFailure(exc, request, response);
    } catch (HttpErrorException exc) {
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, exc);
        ProblemOccasion occ = new PathDispatchingOccasion(request, exc.getDbHint());
        _core.getProblemRegistry().addProblem(
                Problem.create(occ, "dispatching.http404#" + request.getRequestURL(), ProblemSeverity.LOW));
        if (!response.isCommitted()) {
            // throw exception to display errorpage - with senderror() the
            // applicationserver use the buildin errorpage
            if (exc.getCode() == HttpServletResponse.SC_NOT_FOUND
                    || exc.getCode() == HttpServletResponse.SC_FORBIDDEN
                    || exc.getCode() == HttpServletResponse.SC_PRECONDITION_FAILED) {
                response.sendError(exc.getCode(), exc.getMessage());
            } else {
                _log.error("Exception in processing request from " + request.getRemoteAddr() + " to URL "
                        + String.valueOf(request.getRequestURL()));
                throw new ServletException(exc);
            }
        }
    } catch (SocketException exc) {
        _log.warn("Socket Exception: " + exc.getMessage());
    } catch (Exception exc) {
        _log.error("Exception in processing of request URL " + String.valueOf(request.getRequestURL()), exc);
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, exc);
        throw new ServletException(exc);
    } catch (Error err) {
        _log.error("Error in processing of request URL " + String.valueOf(request.getRequestURL()), err);
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, err);
        throw new ServletException(err);
    } finally {
        if (reqInfo != null) {
            reqInfo.setCommited(true);
        }
    }
}

From source file:org.georchestra.security.Proxy.java

private void handleRequest(HttpServletRequest request, HttpServletResponse finalResponse,
        RequestType requestType, String sURL, boolean localProxy) {
    HttpClientBuilder htb = HttpClients.custom().disableRedirectHandling();

    RequestConfig config = RequestConfig.custom().setSocketTimeout(this.httpClientTimeout).build();
    htb.setDefaultRequestConfig(config);

    ////from  ww  w . ja  v  a 2 s.  c o  m
    // Handle http proxy for external request.
    // Proxy must be configured by system variables (e.g.: -Dhttp.proxyHost=proxy -Dhttp.proxyPort=3128)
    htb.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
    HttpClient httpclient = htb.build();

    HttpResponse proxiedResponse = null;
    int statusCode = 500;

    try {
        URL url = null;
        try {
            url = new URL(sURL);
        } catch (MalformedURLException e) { // not an url
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        }

        // HTTP protocol is required
        if (!"http".equalsIgnoreCase(url.getProtocol()) && !"https".equalsIgnoreCase(url.getProtocol())) {
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "HTTP protocol expected. \"" + url.getProtocol() + "\" used.");
            return;
        }

        // check if proxy must filter on final host
        if (!strategyForFilteringRequests.allowRequest(url)) {
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Host \"" + url.getHost() + "\" is not allowed to be requested");
            return;
        }

        logger.debug("Final request -- " + sURL);

        HttpRequestBase proxyingRequest = makeRequest(request, requestType, sURL);
        headerManagement.configureRequestHeaders(request, proxyingRequest);

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Header[] originalHeaders = proxyingRequest.getHeaders("sec-org");
            String org = "";
            for (Header originalHeader : originalHeaders) {
                org = originalHeader.getValue();
            }
            // no OGC SERVICE log if request going through /proxy/?url=
            if (!request.getRequestURI().startsWith("/sec/proxy/")) {
                String[] roles = new String[] { "" };
                try {
                    Header[] rolesHeaders = proxyingRequest.getHeaders("sec-roles");
                    if (rolesHeaders.length > 0) {
                        roles = rolesHeaders[0].getValue().split(";");
                    }
                } catch (Exception e) {
                    logger.error("Unable to compute roles");
                }
                statsLogger.info(OGCServiceMessageFormatter.format(authentication.getName(), sURL, org, roles));

            }

        } catch (Exception e) {
            logger.error("Unable to log the request into the statistics logger", e);
        }

        if (localProxy) {
            //
            // Hack for geoserver
            // Should not be here. We must use a ProxyTarget class and
            // define
            // if Host header should be forwarded or not.
            //
            request.getHeader("Host");
            proxyingRequest.setHeader("Host", request.getHeader("Host"));

            if (logger.isDebugEnabled()) {
                logger.debug("Host header set to: " + proxyingRequest.getFirstHeader("Host").getValue()
                        + " for proxy request.");
            }
        }
        proxiedResponse = executeHttpRequest(httpclient, proxyingRequest);
        StatusLine statusLine = proxiedResponse.getStatusLine();
        statusCode = statusLine.getStatusCode();
        String reasonPhrase = statusLine.getReasonPhrase();

        if (reasonPhrase != null && statusCode > 399) {
            if (logger.isWarnEnabled()) {
                logger.warn("Error occurred. statuscode: " + statusCode + ", reason: " + reasonPhrase);
            }

            if (statusCode == 401) {
                //
                // Handle case of basic authentication.
                //
                Header authHeader = proxiedResponse.getFirstHeader("WWW-Authenticate");
                finalResponse.setHeader("WWW-Authenticate",
                        (authHeader == null) ? "Basic realm=\"Authentication required\""
                                : authHeader.getValue());
            }

            // 403 and 404 are handled by specific JSP files provided by the
            // security-proxy webapp
            if ((statusCode == 404) || (statusCode == 403)) {
                finalResponse.sendError(statusCode);
                return;
            }
        }

        headerManagement.copyResponseHeaders(request, request.getRequestURI(), proxiedResponse, finalResponse,
                this.targets);

        if (statusCode == 302 || statusCode == 301) {
            adjustLocation(request, proxiedResponse, finalResponse);
        }
        // get content type

        String contentType = null;
        if (proxiedResponse.getEntity() != null && proxiedResponse.getEntity().getContentType() != null) {
            contentType = proxiedResponse.getEntity().getContentType().getValue();
            logger.debug("content-type detected: " + contentType);
        }

        // content type has to be valid
        if (isCharsetRequiredForContentType(contentType)) {
            doHandleRequestCharsetRequired(request, finalResponse, requestType, proxiedResponse, contentType);
        } else {
            logger.debug("charset not required for contentType: " + contentType);
            doHandleRequest(request, finalResponse, requestType, proxiedResponse);
        }
    } catch (IOException e) {
        // connection problem with the host
        logger.error("Exception occured when trying to connect to the remote host: ", e);
        try {
            finalResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (IOException e2) {
            // error occured while trying to return the
            // "service unavailable status"
            finalResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.energy_home.jemma.internal.shapi.HapProxy.java

private ContentInstancesBatchResponse postBatchRequest(ContentInstancesBatchRequest batchRequest) {
    ContentInstancesBatchResponse batchResponse = new ContentInstancesBatchResponse();
    List<ContentInstanceItemsStatus> responseStatusList = batchResponse.getContentInstanceItemsStatuses();
    List<ContentInstanceItems> itemsList = batchRequest.getContentInstanceItems();
    for (Iterator iterator = itemsList.iterator(); iterator.hasNext();) {
        ContentInstanceItems contentInstanceItems = (ContentInstanceItems) iterator.next();
        ContentInstanceItemsStatus itemsStatus = new ContentInstanceItemsStatus();
        itemsStatus.setAddressedId(contentInstanceItems.getAddressedId());
        responseStatusList.add(itemsStatus);
        for (Iterator iterator2 = contentInstanceItems.getContentInstances().iterator(); iterator2.hasNext();) {
            ContentInstance ci = (ContentInstance) iterator2.next();
            ContentInstanceItemStatus itemStatus = new ContentInstanceItemStatus();
            itemStatus.setResourceId(new Long(System.currentTimeMillis()));
            itemsStatus.getContentInstanceItemStatuses().add(itemStatus);
            try {
                AHContainerAddress itemContainerAddress = new AHM2MContainerAddress(
                        contentInstanceItems.getAddressedId());
                if (!isValidLocalHagId(itemContainerAddress.getHagId())) {
                    itemStatus.setBatchStatus(HttpServletResponse.SC_NOT_FOUND);
                } else {
                    ci = postContentInstance(itemContainerAddress, ci);
                    if (ci == null)
                        itemStatus.setBatchStatus(HttpServletResponse.SC_NOT_FOUND);
                    else if (ServiceClusterProxy.isAnUnconfirmedCommand(itemContainerAddress))
                        itemStatus.setBatchStatus(HttpServletResponse.SC_ACCEPTED);
                    else
                        itemStatus.setBatchStatus(HttpServletResponse.SC_OK);
                }//from  w w w .  jav a2s  . co m
            } catch (Exception e) {
                log.error("", e);
                itemStatus.setBatchStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            }
        }
    }
    return batchResponse;
}

From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java

/**
 * PAIAauth services: Prfe jeweils die scopes und liefere die Daten
 *///from   w  w w .j  a  v  a 2s . c  om
private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String service, String access_token, String requestBody, String format, String language,
        String redirect_url) throws IOException {

    ObjectMapper mapper = new ObjectMapper();

    switch (service) {

    case "login": {

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

            AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
            // init Authorization Service
            authorizationInterface.init(this.config);

            // if access_token not equals "" >> delete token + new login
            if (!access_token.equals("")) {

                // AuthorizationInterface.revokeToken()
                try {

                    boolean isRevoked = authorizationInterface.revokeToken(access_token);
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }

                // delete cookie
                Cookie cookie = new Cookie("PaiaService", null);
                if (this.config.getProperty("service.cookie.domain") != null
                        && !this.config.getProperty("service.cookie.domain").equals("")) {
                    cookie.setDomain(this.config.getProperty("service.cookie.domain"));
                }
                cookie.setMaxAge(0);
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);

                // cleanup variable
                access_token = "";
            }

            // analyse on request data
            LoginRequest loginRequest = null;
            try {

                loginRequest = mapper.readValue(requestBody, LoginRequest.class);

                if (httpServletRequest.getParameter("redirect_url") != null
                        && !httpServletRequest.getParameter("redirect_url").equals("")) {

                    redirect_url = httpServletRequest.getParameter("redirect_url");
                }
            } catch (Exception e) {

                if (requestBody != null && !requestBody.equals("")) {

                    String[] params = requestBody.split("&");

                    if (params.length > 1) {

                        loginRequest = new LoginRequest();

                        for (String param : params) {

                            if (param.startsWith("grant_type")) {
                                loginRequest.setGrant_type(param.split("=")[1]);
                            } else if (param.startsWith("username")) {
                                loginRequest.setUsername(param.split("=")[1]);
                            } else if (param.startsWith("password")) {
                                loginRequest.setPassword(param.split("=")[1]);
                            } else if (param.startsWith("scope")) {
                                loginRequest.setScope(param.split("=")[1]);
                            } else if (param.startsWith("format")) {
                                format = param.split("=")[1];
                                this.logger.info("format = " + format);
                            } else if (param.startsWith("redirect_url")) {
                                redirect_url = URLDecoder.decode(param.split("=")[1], "UTF-8");
                                this.logger.info("redirect_url = " + redirect_url);
                            } else {
                                // Tu nix
                            }
                        }
                    }
                } else if (httpServletRequest.getParameter("grant_type") != null
                        && !httpServletRequest.getParameter("grant_type").equals("")
                        && httpServletRequest.getParameter("username") != null
                        && !httpServletRequest.getParameter("username").equals("")
                        && httpServletRequest.getParameter("password") != null
                        && !httpServletRequest.getParameter("password").equals("")) {

                    loginRequest = new LoginRequest();
                    loginRequest.setGrant_type(httpServletRequest.getParameter("grant_type"));
                    loginRequest.setUsername(httpServletRequest.getParameter("username"));
                    loginRequest.setPassword(httpServletRequest.getParameter("password"));
                    if (httpServletRequest.getParameter("scope") != null
                            && !httpServletRequest.getParameter("scope").equals("")) {
                        loginRequest.setScope(httpServletRequest.getParameter("scope"));
                    }
                    if (httpServletRequest.getParameter("redirect_url") != null
                            && !httpServletRequest.getParameter("redirect_url").equals("")) {

                        redirect_url = httpServletRequest.getParameter("redirect_url");
                    }
                } else {
                    loginRequest = null;
                }
            }

            // do login
            if (loginRequest != null && loginRequest.getUsername() != null && loginRequest.getPassword() != null
                    && loginRequest.getGrant_type() != null
                    && loginRequest.getGrant_type().equals("password")) {

                String scope = "read_patron read_fees read_items write_items"; // TODO config-properties
                if (loginRequest.getScope() != null && !loginRequest.getScope().equals("")) {

                    scope = loginRequest.getScope();
                }

                // AuthorizationInterface.getToken()
                String responseJson = "";
                try {

                    responseJson = authorizationInterface.getToken(scope, loginRequest.getUsername(),
                            loginRequest.getPassword());
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }

                if (!responseJson.equals("")) {

                    LoginResponse loginResponse = mapper.readValue(responseJson, LoginResponse.class);

                    // anpassen des loginResponse
                    loginResponse.setRefresh_token(null);
                    loginResponse.setRefresh_expires_in(null);
                    loginResponse.setPatron(loginRequest.getUsername());

                    httpServletResponse.setHeader("Access-Control-Allow-Origin",
                            this.config.getProperty("Access-Control-Allow-Origin"));
                    httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control"));
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    // add cookie
                    StringWriter stringWriter = new StringWriter();
                    mapper.writeValue(stringWriter, loginResponse);
                    Cookie cookie = new Cookie("PaiaService",
                            URLEncoder.encode(stringWriter.toString(), "UTF-8"));
                    if (this.config.getProperty("service.cookie.domain") != null
                            && !this.config.getProperty("service.cookie.domain").equals("")) {
                        cookie.setDomain(this.config.getProperty("service.cookie.domain"));
                    }
                    cookie.setMaxAge(-1);
                    cookie.setPath("/");
                    httpServletResponse.addCookie(cookie);

                    // extent redirect_url
                    this.logger.info("redirect_url: " + redirect_url);
                    if (redirect_url.startsWith(this.config.getProperty("service.base_url") + "/core")) {

                        if (redirect_url.endsWith("core/")) {
                            redirect_url += loginResponse.getPatron();
                        } else if (redirect_url.endsWith("core")) {
                            redirect_url += "/" + loginResponse.getPatron();
                        } else if (redirect_url.contains("/patronid/")) {

                            redirect_url = redirect_url.replaceAll("/patronid/",
                                    "/" + loginResponse.getPatron() + "/");
                        } else {
                            // nix
                        }
                    }
                    this.logger.info("redirect_url: " + redirect_url);

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(LoginResponse.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(loginResponse, httpServletResponse.getWriter());
                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), loginResponse);
                    }

                    // html >> redirect
                    if (format.equals("html")) {

                        // if QueryString contains redirect_url and value of it contains /paia/core/ >> expand URL with username
                        if (redirect_url.contains("/paia/core/")) {

                            // TODO redirect_url += loginResponse.getPatron();
                        }
                        this.logger.info("redirect_url = " + redirect_url);

                        httpServletResponse.sendRedirect(redirect_url);
                    }
                } else {

                    // 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) + ".2"));
                    requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                    requestError.setDescription(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }
            }
            // else Baue HTML-Seite mit login-Formular mittels XSLT
            else {

                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA auth\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin",
                        config.getProperty("Access-Control-Allow-Origin"));
                httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));

                // 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) + ".2"));
                requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                requestError.setDescription(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description"));
                requestError.setErrorUri(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri"));

                if (format.equals("html")) {

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

                        try {
                            ObjectToHtmlTransformation htmlTransformation = Lookup
                                    .lookup(ObjectToHtmlTransformation.class);
                            // init transformator
                            htmlTransformation.init(this.config);

                            HashMap<String, String> parameters = new HashMap<String, String>();
                            parameters.put("lang", language);
                            parameters.put("redirect_url", redirect_url);

                            //String provider = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/" + service;
                            String provider = this.config.getProperty("service.base_url")
                                    + this.config.getProperty("service.endpoint.auth") + "/" + service;
                            parameters.put("formURL", provider);

                            httpServletResponse.setContentType("text/html;charset=UTF-8");
                            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                            httpServletResponse.getWriter()
                                    .println(htmlTransformation.transform(new Document(), parameters));
                        } catch (TransformationException e) {
                            e.printStackTrace();
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering a HTML message.");
                        }
                    } else {
                        this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                        format = "json";
                    }
                }

                // XML-Ausgabe mit JAXB
                if (format.equals("xml")) {

                    try {

                        JAXBContext context = JAXBContext.newInstance(RequestError.class);
                        Marshaller m = context.createMarshaller();
                        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                        // Write to HttpResponse
                        httpServletResponse.setContentType("application/xml;charset=UTF-8");
                        m.marshal(requestError, httpServletResponse.getWriter());
                    } catch (JAXBException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    }
                }

                // JSON-Ausgabe mit Jackson
                if (format.equals("json")) {

                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    mapper.writeValue(httpServletResponse.getWriter(), requestError);
                }
            }
        } else {

            this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!");

            // 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"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }

        break;
    }
    case "logout": {

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

            AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
            // init Authorization Service
            authorizationInterface.init(this.config);

            if (!access_token.equals("")) {

                // AuthorizationInterface.revokeToken()
                try {

                    boolean isRevoked = authorizationInterface.revokeToken(access_token);
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }
            }

            httpServletResponse.setHeader("Access-Control-Allow-Origin",
                    config.getProperty("Access-Control-Allow-Origin"));
            httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);

            // delete cookie
            Cookie cookie = new Cookie("PaiaService", null);
            if (this.config.getProperty("service.cookie.domain") != null
                    && !this.config.getProperty("service.cookie.domain").equals("")) {
                cookie.setDomain(this.config.getProperty("service.cookie.domain"));
            }
            cookie.setMaxAge(0);
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);

            // html >> redirect
            if (format.equals("html")) {

                if (httpServletRequest.getParameter("redirect_url") != null
                        && !httpServletRequest.getParameter("redirect_url").equals("")) {

                    redirect_url = httpServletRequest.getParameter("redirect_url");
                } else {

                    redirect_url = this.config.getProperty("service.auth.logout.redirect.default");
                }

                httpServletResponse.sendRedirect(redirect_url);
            }

            if (format.equals("json")) {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                httpServletResponse.getWriter().println("{\"logged out\":\"true\"}");
            }

            if (format.equals("xml")) {
                httpServletResponse.setContentType("application/xml;charset=UTF-8");
                httpServletResponse.getWriter().println(
                        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><logout status=\"true\" />");
            }

        } else {

            this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!");

            // 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"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }

        break;
    }
    case "change": {

        // build ChangeRequest object
        ChangeRequest changeRequest = mapper.readValue(requestBody, ChangeRequest.class);

        // check token ...
        boolean isAuthorized = false;

        if (access_token != null && !access_token.equals("")) {

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

                AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
                // init Authorization Service
                authorizationInterface.init(this.config);

                try {

                    isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service,
                            changeRequest.getPatron(), access_token);
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }
            } else {

                // TODO correct error handling
                this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                        + "Authorization Interface not implemented!");
            }
        }

        this.logger.debug("Authorization: " + access_token + " - " + isAuthorized);

        if (!isAuthorized) {

            // Authorization
            this.authorize(httpServletRequest, httpServletResponse, format);
        } else {

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

                LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class);
                // init ILS
                libraryManagementSystem.init(this.config);

                // exists patron?
                // use LibraryManagementSystem.patron(): failed = Exception!
                try {

                    Patron patron = libraryManagementSystem.patron(changeRequest.getPatron(), false);

                    boolean isChanged = libraryManagementSystem.changePassword(changeRequest);

                    if (isChanged) {

                        // E-Mail to user
                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {

                            if (this.config.getProperty("isTestMode") != null
                                    && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) {
                                mailer.postMail(patron.getEmail(),
                                        this.config.getProperty("service.mailer.change.subject"),
                                        this.config.getProperty("service.mailer.change.message"));
                            } else {
                                mailer.postMail(this.config.getProperty("service.mailer.change.subject"),
                                        this.config.getProperty("service.mailer.change.message"));
                            }

                        } catch (MessagingException e1) {

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

                        this.logger.info("Password changed. Mail send to '" + patron.getEmail() + "'.");

                        // 200 OK
                        if (format.equals("html")) {

                            format = "json"; // TODO or what else?
                        }

                        Patron responsePatron = new Patron();
                        responsePatron.setUsername(patron.getUsername());
                        responsePatron.setStatus(patron.getStatus());
                        responsePatron.setEmail(new InternetAddress(patron.getEmail()));

                        if (format.equals("json")) {

                            httpServletResponse.setContentType("application/json;charset=UTF-8");
                            mapper.writeValue(httpServletResponse.getWriter(), responsePatron);
                        }

                        if (format.equals("xml")) {

                            JAXBContext context = JAXBContext.newInstance(Patron.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(responsePatron, httpServletResponse.getWriter());
                        }
                    } else {

                        // 401 UNAUTHORIZED
                        this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong old password!");

                        // 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_UNAUTHORIZED);
                        }

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

                        this.sendRequestError(httpServletResponse, requestError, format, language,
                                redirect_url);
                    }
                } catch (LibraryManagementSystemException e) {

                    // 401 UNAUTHORIZED
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": " + e.getMessage());

                    // 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_UNAUTHORIZED);
                    }

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

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                } catch (Exception e) {

                    this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }
            } else {

                this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

                // 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"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            }
        }

        break;
    }
    case "renew": {

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

            LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class);
            // init ILS
            libraryManagementSystem.init(this.config);

            // exists patron?
            // use LibraryManagementSystem.patron(): failed = Exception!
            try {

                // build NewPasswordRequest object
                NewPasswordRequest newPasswordRequest = mapper.readValue(requestBody, NewPasswordRequest.class);

                Patron patron = libraryManagementSystem.patron(newPasswordRequest.getPatron(), true);

                if (patron.getEmail() != null && !patron.getEmail().equals("")) {

                    boolean isRenewed = libraryManagementSystem.renewPassword(newPasswordRequest, patron);

                    if (isRenewed) {

                        // E-Mail to user
                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {

                            if (this.config.getProperty("isTestMode") != null
                                    && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) {
                                mailer.postMail(patron.getEmail(),
                                        this.config.getProperty("service.mailer.renew.subject"),
                                        this.config.getProperty("service.mailer.renew.message"));
                            } else {
                                mailer.postMail(this.config.getProperty("service.mailer.renew.subject"),
                                        this.config.getProperty("service.mailer.renew.message"));
                            }

                        } catch (MessagingException e1) {

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

                        this.logger.info("Password resetted. Mail send to '" + patron.getEmail() + "'.");

                        // 200 OK
                        if (format.equals("html")) {

                            format = "json"; // TODO or what else?
                        }

                        Patron responsePatron = new Patron();
                        responsePatron.setUsername(patron.getUsername());
                        responsePatron.setStatus(patron.getStatus());
                        responsePatron.setEmail(new InternetAddress(patron.getEmail()));

                        if (format.equals("json")) {

                            httpServletResponse.setContentType("application/json;charset=UTF-8");
                            mapper.writeValue(httpServletResponse.getWriter(), responsePatron);
                        }

                        if (format.equals("xml")) {

                            JAXBContext context = JAXBContext.newInstance(Patron.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(responsePatron, httpServletResponse.getWriter());
                        }
                    } else {

                        // 401 SC_UNAUTHORIZED
                        this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong usergroup!");

                        // 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_UNAUTHORIZED);
                        }

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

                        this.sendRequestError(httpServletResponse, requestError, format, language,
                                redirect_url);
                    }
                } else {

                    // 401 SC_UNAUTHORIZED
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": No E-Mail-Address exists!");

                    // 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_UNAUTHORIZED);
                    }

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

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }
            } catch (LibraryManagementSystemException e) {

                e.printStackTrace();

                // 400 SC_BAD_REQUEST
                this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + e.getMessage());

                // 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_BAD_REQUEST);
                }

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

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            } catch (Exception e) {

                this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

                // 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"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            }
        } else {

            this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

            // 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"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }

        break;
    }
    default: {

        this.logger.error(HttpServletResponse.SC_BAD_REQUEST + "Unknown function! (" + service + ")");

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

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

        this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
    }
    }
}

From source file:com.cognitivemedicine.nifi.http.PostHTTP2.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean();
    final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger();
    final String userAgent = context.getProperty(USER_AGENT).getValue();

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder/*from w w w  .j a v a2 s.c  om*/
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ProcessorLog logger = getLogger();

    final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B);
    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    DestinationAccepts destinationAccepts = null;
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final ObjectHolder<String> dnHolder = new ObjectHolder<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null || destinationAccepts == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.setUserAgent(userAgent);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final X509Certificate[] certChain = sslSession.getPeerCertificateChain();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        final X509Certificate cert = certChain[0];
                        dnHolder.set(cert.getSubjectDN().getName().trim());
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            final String username = context.getProperty(USERNAME).getValue();
            final String password = context.getProperty(PASSWORD).getValue();
            // set the credentials if appropriate
            if (username != null) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                if (password == null) {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username));
                } else {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
                }
                ;
                clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
            client = clientBuilder.build();

            // determine whether or not destination accepts flowfile/gzip
            destinationAccepts = config.getDestinationAccepts();
            if (destinationAccepts == null) {
                try {
                    if (sendAsFlowFile) {
                        destinationAccepts = getDestinationAcceptance(client, url, getLogger(), transactionId);
                    } else {
                        destinationAccepts = new DestinationAccepts(false, false, false, false, null);
                    }

                    config.setDestinationAccepts(destinationAccepts);
                } catch (IOException e) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                    logger.error(
                            "Unable to communicate with destination {} to determine whether or not it can accept flowfiles/gzip; routing {} to failure due to {}",
                            new Object[] { url, flowFile, e });
                    context.yield();
                    return;
                }
            }
        }

        // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format,
        // then only use a single FlowFile
        if (!sendAsFlowFile
                || (!destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted())) {
            break;
        }

        bytesToSend += flowFile.getSize();
        if (bytesToSend > maxBatchBytes.longValue()) {
            break;
        }
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;
    final DestinationAccepts accepts = destinationAccepts;
    final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null;

    final EntityTemplate entity = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream rawOut) throws IOException {
            final OutputStream throttled = (throttler == null) ? rawOut
                    : throttler.newThrottledOutputStream(rawOut);
            OutputStream wrappedOut = new BufferedOutputStream(throttled);
            if (compressionLevel > 0 && accepts.isGzipAccepted()) {
                wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel);
            }

            try (final OutputStream out = wrappedOut) {
                for (final FlowFile flowFile : flowFileList) {
                    session.read(flowFile, new InputStreamCallback() {
                        @Override
                        public void process(final InputStream rawIn) throws IOException {
                            try (final InputStream in = new BufferedInputStream(rawIn)) {

                                FlowFilePackager packager = null;
                                if (!sendAsFlowFile) {
                                    packager = null;
                                } else if (accepts.isFlowFileV3Accepted()) {
                                    packager = new FlowFilePackagerV3();
                                } else if (accepts.isFlowFileV2Accepted()) {
                                    packager = new FlowFilePackagerV2();
                                } else if (accepts.isFlowFileV1Accepted()) {
                                    packager = new FlowFilePackagerV1();
                                }

                                // if none of the above conditions is met, we should never get here, because
                                // we will have already verified that at least 1 of the FlowFile packaging
                                // formats is acceptable if sending as FlowFile.
                                if (packager == null) {
                                    StreamUtils.copy(in, out);
                                } else {
                                    final Map<String, String> flowFileAttributes;
                                    if (isDestinationLegacyNiFi) {
                                        // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path;
                                        // in order to maintain backward compatibility, we copy the filename & path to those attribute keys.
                                        flowFileAttributes = new HashMap<>(flowFile.getAttributes());
                                        flowFileAttributes.put("nf.file.name",
                                                flowFile.getAttribute(CoreAttributes.FILENAME.key()));
                                        flowFileAttributes.put("nf.file.path",
                                                flowFile.getAttribute(CoreAttributes.PATH.key()));
                                    } else {
                                        flowFileAttributes = flowFile.getAttributes();
                                    }

                                    packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize());
                                }
                            }
                        }
                    });
                }

                out.flush();
            }
        }
    });

    entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean());
    post.setEntity(entity);
    post.setConfig(requestConfig);

    final String contentType;
    if (sendAsFlowFile) {
        if (accepts.isFlowFileV3Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V3;
        } else if (accepts.isFlowFileV2Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V2;
        } else if (accepts.isFlowFileV1Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V1;
        } else {
            logger.error(
                    "Cannot send data to {} because the destination does not accept FlowFiles and this processor is configured to deliver FlowFiles; rolling back session",
                    new Object[] { url });
            session.rollback();
            context.yield();
            return;
        }
    } else {
        final String attributeValue = toSend.get(0).getAttribute(CoreAttributes.MIME_TYPE.key());
        contentType = (attributeValue == null) ? DEFAULT_CONTENT_TYPE : attributeValue;
    }

    final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue();
    if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) {
        final Pattern pattern = Pattern.compile(attributeHeaderRegex);

        final Map<String, String> attributes = flowFileList.get(0).getAttributes();
        for (final Map.Entry<String, String> entry : attributes.entrySet()) {
            final String key = entry.getKey();
            if (pattern.matcher(key).matches()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    post.setHeader(CONTENT_TYPE, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);
    if (compressionLevel > 0 && accepts.isGzipAccepted()) {
        post.setHeader(GZIPPED_HEADER, "true");
    }

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);

        // consume input stream entirely, ignoring its contents. If we
        // don't do this, the Connection will not be returned to the pool
        EntityUtils.consume(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (final FlowFile flowFile : toSend) {
            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }
        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            EntityUtils.consume(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (FlowFile flowFile : toSend) {
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

From source file:org.energy_home.jemma.internal.shapi.HapProxy.java

protected void doGet(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    String requestUri = servletRequest.getRequestURI();
    String method = servletRequest.getParameter("method");
    if (requestUri.endsWith(servletUri)) {
        writeStringObject(servletResponse, indexPage);
        return;/*from  w w w.j a va  2s . c o  m*/
    }
    initResponse(servletResponse);
    if (requestUri.endsWith(M2MConstants.URL_SLASH))
        requestUri = requestUri.substring(0, requestUri.length() - 1);
    if (requestUri.startsWith(M2MConstants.URL_SCL_BASE)) {
        if (networkScl == null) {
            servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }
        requestUri = replaceFilters(requestUri, true);
        HttpResponse proxyResponse = null;
        OutputStream out = null;

        try {
            String queryString = servletRequest.getQueryString();
            proxyResponse = networkScl.httpGet(requestUri + "?" + queryString);
            int statusCode = proxyResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                copyResponseEntity(proxyResponse, servletResponse);
            } else {
                // TODO check status code mapping
                servletResponse.sendError(statusCode);
            }
        } catch (Exception e) {
            log.error("service: error while sending request to hap service", e);
            servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else if (requestUri.startsWith(M2MConstants.URL_HAG_SCL_BASE)) {
        requestUri = replaceFilters(requestUri, false);
        try {
            M2MXmlObject xmlObject = null;
            if (requestUri.startsWith(subscriptionItemsAddressedId)) {
                if (requestUri.endsWith(M2MContainerAddress.ALL_ID_FILTER)) {
                    SubscriptionItems subscriptionItems = new SubscriptionItems();
                    for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) {
                        SubscriptionInfo subscriptionInfo = (SubscriptionInfo) iterator.next();
                        subscriptionItems.getSubscriptions().add(subscriptionInfo.subscription);
                    }
                    writeXmlObject(servletResponse, subscriptionItems);
                } else {
                    String subscriptionId = requestUri.substring(subscriptionItemsAddressedId.length() + 1,
                            requestUri.length());
                    SubscriptionInfo subscriptionInfo = null;
                    for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) {
                        subscriptionInfo = (SubscriptionInfo) iterator.next();
                        if (subscriptionInfo.subscription.getId().equals(subscriptionId)) {
                            break;
                        } else
                            subscriptionInfo = null;
                    }
                    if (subscriptionInfo != null)
                        writeXmlObject(servletResponse, subscriptionInfo.subscription);
                    else
                        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
            } else if (requestUri.endsWith(sclsListUri)) {
                scl.setOnLineStatus(hapService.getM2MHapService().isConnected() ? SclStatusEnumeration.ONLINE
                        : SclStatusEnumeration.DISCONNECTED);
                if (sclItems != null)
                    writeXmlObject(servletResponse, sclItems);
                else
                    servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            } else if (scl != null && requestUri.endsWith(scl.getSclBaseId())) {
                writeXmlObject(servletResponse, scl);
            } else if (scl != null && requestUri.startsWith(scl.getSclBaseId() + M2MConstants.URL_SLASH)) {
                long startInstanceId = M2MNetworkScl.CONTENT_INSTANCE_OLDEST_ID;
                String startInstanceIdStr = servletRequest.getParameter(START_INSTANCE_ID_REQUEST_PARAM);
                if (startInstanceIdStr != null && startInstanceIdStr.length() > 0) {
                    try {
                        startInstanceId = Long.parseLong(startInstanceIdStr);
                    } catch (Exception e) {
                        log.error("Error while parsing stratInstanceId parameter");
                    }
                }
                long endInstanceId = M2MNetworkScl.CONTENT_INSTANCE_LATEST_ID;
                String endInstanceIdStr = servletRequest.getParameter(END_INSTANCE_ID_REQUEST_PARAM);
                if (endInstanceIdStr != null && endInstanceIdStr.length() > 0) {
                    try {
                        endInstanceId = Long.parseLong(endInstanceIdStr);
                    } catch (Exception e) {
                        log.error("Error while parsing stratInstanceId parameter");
                    }
                }
                String contentInstanceId = null;
                if (requestUri.endsWith(M2MConstants.URL_CIS_ID_LATEST_ALIAS)) {
                    contentInstanceId = M2MConstants.URL_CIS_ID_LATEST_ALIAS;
                    requestUri = requestUri.replace(M2MConstants.URL_CIS_ID_LATEST_ALIAS, "");
                }
                if (requestUri.endsWith(M2MConstants.URL_CIS_ID_OLDEST_ALIAS)) {
                    contentInstanceId = M2MConstants.URL_CIS_ID_OLDEST_ALIAS;
                    requestUri = requestUri.replace(M2MConstants.URL_CIS_ID_OLDEST_ALIAS, "");
                }
                // TODO:!!! manage uri with a specific timestamp used for content instance id
                AHContainerAddress containerAddress = new AHM2MContainerAddress(requestUri);
                if (!isValidLocalHagId(containerAddress.getHagId()))
                    servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                boolean isFilter = containerAddress.isFilterAddress();
                String containerName = containerAddress.getContainerName();
                if (containerName != null
                        && containerName.equals(AHContainers.attrId_ah_zigbee_network_status)) {
                    xmlObject = getZigBeeNetworkContentInstance();
                    // If latest or oldest is specified a ContentInstance is returned, otherwise a ContentInstanceItems 
                    // with a single item is built
                    if (xmlObject != null && contentInstanceId == null) {
                        xmlObject = getSingleContentInstanceItems(requestUri, (ContentInstance) xmlObject,
                                startInstanceId, endInstanceId);
                    }
                } else if (!isFilter) {
                    String[] clusterAndAttributeNames = ServiceClusterProxy
                            .getClusterAndAttributeNamesForNotCachedAttributes(containerAddress);
                    if (clusterAndAttributeNames == null) {
                        xmlObject = hapService.getM2MHapService().getLocalContentInstance(containerAddress);
                    } else {
                        // A request is sent to the device   
                        ApplianceProxy applianceProxy = applianceProxyList
                                .getApplianceProxy(containerAddress.getAppliancePid());
                        IServiceCluster serviceCluster = applianceProxy.getServiceCluster(
                                new Integer(containerAddress.getEndPointId()).intValue(),
                                clusterAndAttributeNames[0]);
                        IAttributeValue av = serviceCluster.getAttributeValue(clusterAndAttributeNames[1],
                                applianceProxy.getApplicationRequestContext());
                        ContentInstance ci = new ContentInstance();
                        ci.setId(av.getTimestamp());
                        ci.setContent(av.getValue());
                        xmlObject = ci;
                    }
                    if (xmlObject != null && contentInstanceId == null) {
                        // If latest or oldest is specified a ContentInstance is returned, otherwise a ContentInstanceItems 
                        // with a single item is built
                        xmlObject = getSingleContentInstanceItems(requestUri, (ContentInstance) xmlObject,
                                startInstanceId, endInstanceId);
                    }
                } else {
                    xmlObject = hapService.getM2MHapService().getLocalContentInstanceItemsList(containerAddress,
                            startInstanceId, endInstanceId);
                }

                if (xmlObject == null) {
                    servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                } else {
                    writeXmlObject(servletResponse, xmlObject);
                }
            } else {
                servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (Exception e) {
            log.error("service: error while parsing local request", e);
            servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:de.tu_dortmund.ub.api.paia.core.PaiaCoreEndpoint.java

/**
 * PAIA core services: Prfe jeweils die scopes und liefere die Daten
 *///from   w ww  . j a  v a 2s  .  co  m
private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String patronid, String service, String format, String language, String redirect_url,
        DocumentList documents) throws IOException {

    httpServletResponse.setHeader("Access-Control-Allow-Origin",
            config.getProperty("Access-Control-Allow-Origin"));
    httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));

    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 "patron": {

                Patron patron = integratedLibrarySystem.patron(patronid, false);

                if (patron != null) {

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

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_patron");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(patron, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(Patron.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(patron, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), patron);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "fullpatron": {

                Patron patron = integratedLibrarySystem.patron(patronid, true);

                if (patron != null) {

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

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_patron");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(patron, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(Patron.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(patron, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), patron);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "items": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "all");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "items/borrowed": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "borrowed");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "items/borrowed/ill": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "borrowed", "ill");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "items/borrowed/renewed": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "borrowed", "renewed");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "items/borrowed/recalled": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "borrowed", "recalled");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "items/ordered": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "ordered");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "items/reserved": {

                DocumentList documentList = integratedLibrarySystem.items(patronid, "reserved");

                if (documentList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, documentList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "request": {

                DocumentList documentList = integratedLibrarySystem.request(patronid, documents);

                if (documentList != null) {

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

                    // set Cookie with new value for urlencoded DocumentList-JSON
                    StringWriter stringWriter = new StringWriter();
                    mapper.writeValue(stringWriter, documents);
                    Cookie cookie = new Cookie("PaiaServiceDocumentList",
                            URLEncoder.encode(stringWriter.toString(), "UTF-8"));
                    if (this.config.getProperty("service.cookie.domain") != null
                            && !this.config.getProperty("service.cookie.domain").equals("")) {
                        cookie.setDomain(this.config.getProperty("service.cookie.domain"));
                    }
                    cookie.setMaxAge(-1);
                    cookie.setPath("/");
                    httpServletResponse.addCookie(cookie);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            this.logger.info("redirect_url = " + redirect_url);
                            if (!redirect_url.equals("")) {

                                httpServletResponse.sendRedirect(redirect_url);
                            } else {

                                try {
                                    ObjectToHtmlTransformation htmlTransformation = Lookup
                                            .lookup(ObjectToHtmlTransformation.class);
                                    // init transformator
                                    htmlTransformation.init(this.config);

                                    HashMap<String, String> parameters = new HashMap<String, String>();
                                    parameters.put("lang", language);
                                    parameters.put("service", service);

                                    httpServletResponse.setContentType("text/html;charset=UTF-8");
                                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                    httpServletResponse.getWriter()
                                            .println(htmlTransformation.transform(documentList, parameters));
                                } catch (TransformationException e) {
                                    httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                            "Internal Server Error: Error while rendering a HTML message.");
                                }
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "renew": {

                DocumentList documentList = integratedLibrarySystem.renew(patronid, documents);

                if (documentList != null) {

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

                    // delete DocumentList cookie
                    Cookie cookie = new Cookie("PaiaServiceDocumentList", null);
                    if (this.config.getProperty("service.cookie.domain") != null
                            && !this.config.getProperty("service.cookie.domain").equals("")) {
                        cookie.setDomain(this.config.getProperty("service.cookie.domain"));
                    }
                    cookie.setMaxAge(0);
                    httpServletResponse.addCookie(cookie);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "cancel": {

                DocumentList documentList = integratedLibrarySystem.cancel(patronid, documents);

                if (documentList != null) {

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

                    // delete DocumentList cookie
                    Cookie cookie = new Cookie("PaiaServiceDocumentList", null);
                    if (this.config.getProperty("service.cookie.domain") != null
                            && !this.config.getProperty("service.cookie.domain").equals("")) {
                        cookie.setDomain(this.config.getProperty("service.cookie.domain"));
                    }
                    cookie.setMaxAge(0);
                    httpServletResponse.addCookie(cookie);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "write_items");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(documentList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(DocumentList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(documentList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), documentList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            case "fees": {

                FeeList feeList = integratedLibrarySystem.fees(patronid);

                if (feeList != null) {
                    StringWriter json = new StringWriter();
                    mapper = new ObjectMapper();
                    mapper.writeValue(json, feeList);
                    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

                    httpServletResponse.setHeader("X-Accepted-OAuth-Scopes", "read_fees");
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    if (format.equals("html")) {

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

                            try {
                                ObjectToHtmlTransformation htmlTransformation = Lookup
                                        .lookup(ObjectToHtmlTransformation.class);
                                // init transformator
                                htmlTransformation.init(this.config);

                                HashMap<String, String> parameters = new HashMap<String, String>();
                                parameters.put("lang", language);
                                parameters.put("service", service);

                                httpServletResponse.setContentType("text/html;charset=UTF-8");
                                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                                httpServletResponse.getWriter()
                                        .println(htmlTransformation.transform(feeList, parameters));
                            } catch (TransformationException e) {
                                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                        "Internal Server Error: Error while rendering a HTML message.");
                            }
                        } else {
                            this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                            format = "json";
                        }
                    }

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(FeeList.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(feeList, httpServletResponse.getWriter());

                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), feeList);
                    }
                } else {

                    // 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"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }

                break;
            }
            }
        } catch (ILSException e) {

            StringWriter json = new StringWriter();

            // TODO Frage nach "570-unknown patron" ist nicht gut! Lsung: Welche Typen von ILSExceptions treten auf? Erzeuge fr jeden Typ eine eigene Exception!
            if (e.getMessage().contains("570-unknown patron")) {

                this.logger.error("[" + this.config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_NOT_FOUND + ": '" + patronid + "'");

                // 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_NOT_FOUND);
                }

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

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            } else {

                this.logger.error("[" + this.config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                // 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"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    } else {

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

        // 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"));

        this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
    }
}

From source file:de.innovationgate.wgpublisher.WGPRequestPath.java

private void testGeneralAccess(javax.servlet.http.HttpServletRequest request)
        throws HttpErrorException, AdminLoginNeededException {

    Boolean updated = (Boolean) database.getAttribute(WGDatabase.ATTRIB_UPDATED);
    if (updated != null) {
        if (updated.booleanValue() == true) {
            throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "This application is currently being updated. Please try again later.", getDatabaseKey());
        }/*  ww w  .  ja v  a  2 s  .  com*/
    }

    boolean allowPublishing = database.getBooleanAttribute(WGACore.DBATTRIB_ALLOW_PUBLISHING, true);
    if (!allowPublishing) {
        throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN,
                "The application '" + database.getDbReference() + "' is not published", null);
    }

    boolean authoringApp = database.getBooleanAttribute(WGACore.DBATTRIB_AUTHORING_APP, false);
    if (authoringApp && !core.isAuthoringPort(request.getLocalPort())) {
        throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN,
                "Access to authoring applications is disabled", null);
    }

    boolean adminApp = database.getBooleanAttribute(WGACore.DBATTRIB_ADMIN_APP, false);
    if (adminApp) {
        if (!core.isAdministrativePort(request.getLocalPort())) {
            throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN,
                    "Access to administrative applications is disabled", null);
        }

        if (!core.isAdminLoggedIn(request)) {
            throw new AdminLoginNeededException();
        }
    }

    if (this.pathType != TYPE_CSS && this.pathType != TYPE_JS && this.pathType != TYPE_FILE) {
        if (!database.getSessionContext().getUserAccess().mayAccessDirectly()) {
            throw new IllegalDirectAccessException(database.getDbReference());
        }
    }

}

From source file:com.cognitivemedicine.nifi.http.PostAdvancedHTTP.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean();
    final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger();
    final String userAgent = context.getProperty(USER_AGENT).getValue();

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder//w w w.j  av  a 2 s . co  m
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ProcessorLog logger = getLogger();

    final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B);
    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    DestinationAccepts destinationAccepts = null;
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final ObjectHolder<String> dnHolder = new ObjectHolder<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null || destinationAccepts == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.setUserAgent(userAgent);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final X509Certificate[] certChain = sslSession.getPeerCertificateChain();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        final X509Certificate cert = certChain[0];
                        dnHolder.set(cert.getSubjectDN().getName().trim());
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            final String username = context.getProperty(USERNAME).getValue();
            final String password = context.getProperty(PASSWORD).getValue();
            // set the credentials if appropriate
            if (username != null) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                if (password == null) {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username));
                } else {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
                }
                ;
                clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
            client = clientBuilder.build();

            // determine whether or not destination accepts flowfile/gzip
            destinationAccepts = config.getDestinationAccepts();
            if (destinationAccepts == null) {
                try {
                    if (sendAsFlowFile) {
                        destinationAccepts = getDestinationAcceptance(client, url, getLogger(), transactionId);
                    } else {
                        destinationAccepts = new DestinationAccepts(false, false, false, false, null);
                    }

                    config.setDestinationAccepts(destinationAccepts);
                } catch (IOException e) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                    logger.error(
                            "Unable to communicate with destination {} to determine whether or not it can accept flowfiles/gzip; routing {} to failure due to {}",
                            new Object[] { url, flowFile, e });
                    context.yield();
                    return;
                }
            }
        }

        // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format,
        // then only use a single FlowFile
        if (!sendAsFlowFile
                || (!destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted())) {
            break;
        }

        bytesToSend += flowFile.getSize();
        if (bytesToSend > maxBatchBytes.longValue()) {
            break;
        }
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;
    final DestinationAccepts accepts = destinationAccepts;
    final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null;

    final EntityTemplate entity = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream rawOut) throws IOException {
            final OutputStream throttled = (throttler == null) ? rawOut
                    : throttler.newThrottledOutputStream(rawOut);
            OutputStream wrappedOut = new BufferedOutputStream(throttled);
            if (compressionLevel > 0 && accepts.isGzipAccepted()) {
                wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel);
            }

            try (final OutputStream out = wrappedOut) {
                for (final FlowFile flowFile : flowFileList) {
                    session.read(flowFile, new InputStreamCallback() {
                        @Override
                        public void process(final InputStream rawIn) throws IOException {
                            try (final InputStream in = new BufferedInputStream(rawIn)) {

                                FlowFilePackager packager = null;
                                if (!sendAsFlowFile) {
                                    packager = null;
                                } else if (accepts.isFlowFileV3Accepted()) {
                                    packager = new FlowFilePackagerV3();
                                } else if (accepts.isFlowFileV2Accepted()) {
                                    packager = new FlowFilePackagerV2();
                                } else if (accepts.isFlowFileV1Accepted()) {
                                    packager = new FlowFilePackagerV1();
                                }

                                // if none of the above conditions is met, we should never get here, because
                                // we will have already verified that at least 1 of the FlowFile packaging
                                // formats is acceptable if sending as FlowFile.
                                if (packager == null) {
                                    StreamUtils.copy(in, out);
                                } else {
                                    final Map<String, String> flowFileAttributes;
                                    if (isDestinationLegacyNiFi) {
                                        // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path;
                                        // in order to maintain backward compatibility, we copy the filename & path to those attribute keys.
                                        flowFileAttributes = new HashMap<>(flowFile.getAttributes());
                                        flowFileAttributes.put("nf.file.name",
                                                flowFile.getAttribute(CoreAttributes.FILENAME.key()));
                                        flowFileAttributes.put("nf.file.path",
                                                flowFile.getAttribute(CoreAttributes.PATH.key()));
                                    } else {
                                        flowFileAttributes = flowFile.getAttributes();
                                    }

                                    packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize());
                                }
                            }
                        }
                    });
                }

                out.flush();
            }
        }
    });

    entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean());
    post.setEntity(entity);
    post.setConfig(requestConfig);

    final String contentType;
    if (sendAsFlowFile) {
        if (accepts.isFlowFileV3Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V3;
        } else if (accepts.isFlowFileV2Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V2;
        } else if (accepts.isFlowFileV1Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V1;
        } else {
            logger.error(
                    "Cannot send data to {} because the destination does not accept FlowFiles and this processor is configured to deliver FlowFiles; rolling back session",
                    new Object[] { url });
            session.rollback();
            context.yield();
            return;
        }
    } else {
        final String attributeValue = toSend.get(0).getAttribute(CoreAttributes.MIME_TYPE.key());
        contentType = (attributeValue == null) ? DEFAULT_CONTENT_TYPE : attributeValue;
    }

    final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue();
    if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) {
        final Pattern pattern = Pattern.compile(attributeHeaderRegex);

        final Map<String, String> attributes = flowFileList.get(0).getAttributes();
        for (final Map.Entry<String, String> entry : attributes.entrySet()) {
            final String key = entry.getKey();
            if (pattern.matcher(key).matches()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    post.setHeader(CONTENT_TYPE, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);
    if (compressionLevel > 0 && accepts.isGzipAccepted()) {
        post.setHeader(GZIPPED_HEADER, "true");
    }

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    String responseContent;

    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);
        responseContent = EntityUtils.toString(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (FlowFile flowFile : toSend) {

            flowFile = this.setHttpPostResponse(context, session, responseContent, flowFile);

            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }

        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            responseContent = EntityUtils.toString(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (FlowFile flowFile : toSend) {
                flowFile = this.setHttpPostResponse(context, session, responseContent, flowFile);
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

From source file:org.dasein.cloud.aws.compute.EC2Method.java

public Document invoke(boolean debug) throws EC2Exception, CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + EC2Method.class.getName() + ".invoke(" + debug + ")");
    }/*from  ww  w. j a v a 2 s  . c o  m*/
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug("--------------------------------------------------------------------------------------");
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Talking to server at " + url);
        }

        HttpPost post = new HttpPost(url);
        HttpClient client = getClient();

        HttpResponse response;

        attempts++;
        post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
        if (wire.isDebugEnabled()) {
            wire.debug(post.getRequestLine().toString());
            for (Header header : post.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");

            try {
                wire.debug(EntityUtils.toString(post.getEntity()));
            } catch (IOException ignore) {
            }

            wire.debug("");
        }
        try {
            APITrace.trace(provider, parameters.get(AWSCloud.P_ACTION));
            response = client.execute(post);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
            }
        } catch (IOException e) {
            logger.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpServletResponse.SC_OK) {
            try {
                HttpEntity entity = response.getEntity();

                if (entity == null) {
                    throw new EC2Exception(status, null, "NoResponse", "No response body was specified");
                }
                InputStream input = entity.getContent();

                try {
                    return parseResponse(input);
                } finally {
                    input.close();
                }
            } catch (IOException e) {
                logger.error("Error parsing response from AWS: " + e.getMessage());
                e.printStackTrace();
                throw new CloudException(CloudErrorType.COMMUNICATION, status, null, e.getMessage());
            }
        } else if (status == HttpServletResponse.SC_FORBIDDEN) {
            String msg = "API Access Denied (403)";

            try {
                HttpEntity entity = response.getEntity();

                if (entity == null) {
                    throw new EC2Exception(status, null, "NoResponse", "No response body was specified");
                }
                InputStream input = entity.getContent();

                try {
                    BufferedReader in = new BufferedReader(new InputStreamReader(input));
                    StringBuilder sb = new StringBuilder();
                    String line;

                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                        sb.append("\n");
                    }
                    //System.out.println(sb);
                    try {
                        Document doc = parseResponse(sb.toString());

                        if (doc != null) {
                            NodeList blocks = doc.getElementsByTagName("Error");
                            String code = null, message = null, requestId = null;

                            if (blocks.getLength() > 0) {
                                Node error = blocks.item(0);
                                NodeList attrs;

                                attrs = error.getChildNodes();
                                for (int i = 0; i < attrs.getLength(); i++) {
                                    Node attr = attrs.item(i);

                                    if (attr.getNodeName().equals("Code")) {
                                        code = attr.getFirstChild().getNodeValue().trim();
                                    } else if (attr.getNodeName().equals("Message")) {
                                        message = attr.getFirstChild().getNodeValue().trim();
                                    }
                                }

                            }
                            blocks = doc.getElementsByTagName("RequestID");
                            if (blocks.getLength() > 0) {
                                Node id = blocks.item(0);

                                requestId = id.getFirstChild().getNodeValue().trim();
                            }
                            if (message == null && code == null) {
                                throw new CloudException(CloudErrorType.COMMUNICATION, status, null,
                                        "Unable to identify error condition: " + status + "/" + requestId + "/"
                                                + code);
                            } else if (message == null) {
                                message = code;
                            }
                            throw new EC2Exception(status, requestId, code, message);
                        }
                    } catch (RuntimeException ignore) {
                        // ignore me
                    } catch (Error ignore) {
                        // ignore me
                    }
                    msg = msg + ": " + sb.toString().trim().replaceAll("\n", " / ");
                } finally {
                    input.close();
                }
            } catch (IOException ignore) {
                // ignore me
            } catch (RuntimeException ignore) {
                // ignore me
            } catch (Error ignore) {
                // ignore me
            }
            throw new CloudException(msg);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Received " + status + " from " + parameters.get(AWSCloud.P_ACTION));
            }
            if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE
                    || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
                if (attempts >= 5) {
                    String msg;

                    if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
                        msg = "Cloud service is currently unavailable.";
                    } else {
                        msg = "The cloud service encountered a server error while processing your request.";
                        try {
                            HttpEntity entity = response.getEntity();

                            if (entity == null) {
                                throw new EC2Exception(status, null, "NoResponse",
                                        "No response body was specified");
                            }
                            msg = msg + "Response from server was:\n" + EntityUtils.toString(entity);
                        } catch (IOException ignore) {
                            // ignore me
                        } catch (RuntimeException ignore) {
                            // ignore me
                        } catch (Error ignore) {
                            // ignore me
                        }
                    }
                    logger.error(msg);
                    throw new CloudException(msg);
                } else {
                    try {
                        Thread.sleep(5000L);
                    } catch (InterruptedException e) {
                        /* ignore */ }
                    return invoke();
                }
            }
            try {
                HttpEntity entity = response.getEntity();

                if (entity == null) {
                    throw new EC2Exception(status, null, "NoResponse", "No response body was specified");
                }
                InputStream input = entity.getContent();
                Document doc;

                try {
                    doc = parseResponse(input);
                } finally {
                    input.close();
                }
                if (doc != null) {
                    NodeList blocks = doc.getElementsByTagName("Error");
                    String code = null, message = null, requestId = null;

                    if (blocks.getLength() > 0) {
                        Node error = blocks.item(0);
                        NodeList attrs;

                        attrs = error.getChildNodes();
                        for (int i = 0; i < attrs.getLength(); i++) {
                            Node attr = attrs.item(i);

                            if (attr.getNodeName().equals("Code")) {
                                code = attr.getFirstChild().getNodeValue().trim();
                            } else if (attr.getNodeName().equals("Message")) {
                                message = attr.getFirstChild().getNodeValue().trim();
                            }
                        }

                    }
                    blocks = doc.getElementsByTagName("RequestID");
                    if (blocks.getLength() > 0) {
                        Node id = blocks.item(0);

                        requestId = id.getFirstChild().getNodeValue().trim();
                    }
                    if (message == null) {
                        throw new CloudException(CloudErrorType.COMMUNICATION, status, null,
                                "Unable to identify error condition: " + status + "/" + requestId + "/" + code);
                    }
                    throw new EC2Exception(status, requestId, code, message);
                }
                throw new CloudException("Unable to parse error.");
            } catch (IOException e) {
                logger.error(e);
                e.printStackTrace();
                throw new CloudException(e);
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + EC2Method.class.getName() + ".invoke()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug(
                    "--------------------------------------------------------------------------------------");
            wire.debug("");
        }

    }
}