Example usage for javax.mail MessagingException getMessage

List of usage examples for javax.mail MessagingException getMessage

Introduction

In this page you can find the example usage for javax.mail MessagingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:mailbox.EmailHandler.java

private static void handleMessage(@Nonnull IMAPMessage msg) {
    Exception exception = null;/*from  ww w .j  a va2 s.c  om*/
    long startTime = System.currentTimeMillis();
    User author;

    try {
        // Ignore auto-replied emails to avoid suffering from tons of
        // vacation messages. For more details about auto-replied emails,
        // see https://tools.ietf.org/html/rfc3834
        if (isAutoReplied(msg)) {
            return;
        }
    } catch (MessagingException e) {
        play.Logger.warn("Failed to determine whether the email is auto-replied or not: " + msg, e);
    }

    try {
        // Ignore the email if there is an email with the same id. It occurs
        // quite frequently because mail servers send an email twice if the
        // email has two addresses differ from each other: e.g.
        // yobi+my/proj@mail.com and yobi+your/proj@mail.com.
        OriginalEmail sameMessage = OriginalEmail.finder.where().eq("messageId", msg.getMessageID())
                .findUnique();
        if (sameMessage != null) {
            // Warn if the older email was handled one hour or more ago. Because it is
            // quite long time so that possibly the ignored email is actually
            // new one which should be handled.
            if (sameMessage.getHandledDate().before(new DateTime().minusHours(1).toDate())) {
                String warn = String.format(
                        "This email '%s' is ignored because an email with"
                                + " the same id '%s' was already handled at '%s'",
                        msg, sameMessage.messageId, sameMessage.getHandledDate());
                play.Logger.warn(warn);
            }
            return;
        }
    } catch (MessagingException e) {
        play.Logger.warn("Failed to determine whether the email is duplicated or not: " + msg, e);
    }

    InternetAddress[] senderAddresses;

    try {
        senderAddresses = (InternetAddress[]) msg.getFrom();
    } catch (Exception e) {
        play.Logger.error("Failed to get senders from an email", e);
        return;
    }

    if (senderAddresses == null || senderAddresses.length == 0) {
        play.Logger.warn("This email has no sender: " + msg);
        return;
    }

    for (InternetAddress senderAddress : senderAddresses) {
        List<String> errors = new ArrayList<>();

        author = User.findByEmail(senderAddress.getAddress());

        if (author.isAnonymous()) {
            continue;
        }

        try {
            createResources(msg, author, errors);
        } catch (MailHandlerException e) {
            exception = e;
            errors.add(e.getMessage());
        } catch (Exception e) {
            exception = e;
            String shortDescription;
            try {
                shortDescription = IMAPMessageUtil.asString(msg);
            } catch (MessagingException e1) {
                shortDescription = msg.toString();
            }
            play.Logger.warn("Failed to process an email: " + shortDescription, e);
            errors.add("Unexpected error occurs");
        }

        if (errors.size() > 0) {
            String username = senderAddress.getPersonal();
            String emailAddress = senderAddress.getAddress();
            String helpMessage = getHelpMessage(Lang.apply(author.getPreferredLanguage()), username, errors);
            reply(msg, username, emailAddress, helpMessage);
        }

        try {
            log(msg, startTime, exception);
        } catch (MessagingException e) {
            play.Logger.warn("Failed to log mail request", e);
        }

        try {
            MailboxService.updateLastSeenUID(msg);
        } catch (MessagingException e) {
            play.Logger.warn("Failed to update the lastSeenUID", e);
        }
    }
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.BatchClassManagementServiceImpl.java

/**
 * API to validate email configuration.//  ww w  .  ja v a  2 s .c om
 * 
 * @param emailConfigDTO {@link EmailConfigurationDTO} Email Configuration to be verified.
 * @return {@link Boolean} returns true if valid email configuration otherwise false.
 * @throws {@link GWTException}
 */
@Override
public Boolean validateEmailConfig(final EmailConfigurationDTO emailConfigDTO) throws GWTException {
    LOGGER.info("Entering method validateEmailConfig.");
    EmailConfigurationData emailConfigData = createEmailConfigData(emailConfigDTO);
    boolean isValid = false;
    try {
        isValid = EmailUtil.testEmailConfiguration(emailConfigData);
        if (!isValid) {
            throw new GWTException("Unable to connect to email configuration. See server logs for details.");
        }
    } catch (AuthenticationFailedException authExcep) {
        throw new GWTException(authExcep.getMessage());
    } catch (MessagingException messageException) {
        throw new GWTException(messageException.getMessage());
    }
    LOGGER.info("Exiting method validateEmailConfig.");
    return isValid;
}

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

/**
 * PAIAauth services: Prfe jeweils die scopes und liefere die Daten
 *//*w ww  .j a v a2  s.  co  m*/
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:net.wastl.webmail.server.WebMailSession.java

public void refreshFolderInformation(String folderhash) {
    Folder folder = getFolder(folderhash);
    Element xml_folder = model.getFolder(folderhash);

    if (xml_folder.getAttribute("holds_messages").toLowerCase().equals("true")) {
        try {/*from w  w w. j a v a2  s .  c om*/
            Element messagelist = model.createMessageList();

            int total_messages = folder.getMessageCount();
            int new_messages = folder.getNewMessageCount();

            if ((total_messages == -1 || new_messages == -1) && !folder.isOpen()) {
                folder.open(Folder.READ_ONLY);
                total_messages = folder.getMessageCount();
                new_messages = folder.getNewMessageCount();
            }
            if (folder.isOpen())
                folder.close(false);

            messagelist.setAttribute("total", total_messages + "");
            messagelist.setAttribute("new", new_messages + "");

            model.removeMessageList(xml_folder);
            xml_folder.appendChild(messagelist);

        } catch (MessagingException ex) {
            xml_folder.setAttribute("error", ex.getMessage());
        }
    }
}

From source file:eu.peppol.outbound.transmission.As2MessageSender.java

/**
 * Handles the HTTP 200 POST response (the MDN with status indications)
 *
 * @param transmissionId the transmissionId (used in HTTP headers as Message-ID)
 * @param outboundMic    the calculated mic of the payload (should be verified against the one returned in MDN)
 * @param postResponse   the http response to be decoded as MDN
 * @return//from   w  w  w. ja  v  a2s .  co  m
 */
MimeMessage handleTheHttpResponse(TransmissionId transmissionId, Mic outboundMic,
        CloseableHttpResponse postResponse, SmpLookupManager.PeppolEndpointData peppolEndpointData) {

    try {

        HttpEntity entity = postResponse.getEntity(); // Any textual results?
        if (entity == null) {
            throw new IllegalStateException(
                    "No contents in HTTP response with rc=" + postResponse.getStatusLine().getStatusCode());
        }

        String contents = EntityUtils.toString(entity);

        if (traceEnabled) {
            log.debug("HTTP-headers:");
            Header[] allHeaders = postResponse.getAllHeaders();
            for (Header header : allHeaders) {
                log.debug("" + header.getName() + ": " + header.getValue());
            }
            log.debug("Contents:\n" + contents);
            log.debug("---------------------------");
        }

        Header contentTypeHeader = postResponse.getFirstHeader("Content-Type");
        if (contentTypeHeader == null) {
            throw new IllegalStateException("No Content-Type header in response, probably a server error");
        }
        String contentType = contentTypeHeader.getValue();

        MimeMessage mimeMessage = null;
        try {
            mimeMessage = MimeMessageHelper.parseMultipart(contents, new MimeType(contentType));

            try {
                mimeMessage.writeTo(System.out);
            } catch (MessagingException e) {
                throw new IllegalStateException("Unable to print mime message");
            }

        } catch (MimeTypeParseException e) {
            throw new IllegalStateException("Invalid Content-Type header");
        }

        // verify the signature of the MDN, we warn about dodgy signatures
        try {
            SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage);
            X509Certificate cert = signedMimeMessage.getSignersX509Certificate();
            cert.checkValidity();

            // Verify if the certificate used by the receiving Access Point in
            // the response message does not match its certificate published by the SMP
            if (peppolEndpointData.getCommonName() == null || !CommonName
                    .valueOf(cert.getSubjectX500Principal()).equals(peppolEndpointData.getCommonName())) {
                throw new CertificateException(
                        "Common name in certificate from SMP does not match common name in AP certificate");
            }

            log.debug("MDN signature was verfied for : " + cert.getSubjectDN().toString());
        } catch (Exception ex) {
            log.warn("Exception when verifying MDN signature : " + ex.getMessage());
        }

        // Verifies the actual MDN
        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();

        if (mdnMimeMessageInspector.isOkOrWarning(outboundMic)) {

            return mimeMessage;
        } else {
            log.error("AS2 transmission failed with some error message, msg :" + msg);
            log.error(contents);
            throw new IllegalStateException("AS2 transmission failed : " + msg);
        }

    } catch (IOException e) {
        throw new IllegalStateException("Unable to obtain the contents of the response: " + e.getMessage(), e);
    } finally {
        try {
            postResponse.close();
        } catch (IOException e) {
            throw new IllegalStateException("Unable to close http connection: " + e.getMessage(), e);
        }
    }

}

From source file:de.tu_dortmund.ub.api.daia.DaiaOpenUrlEndpoint.java

private void provideService(HttpServletRequest request, HttpServletResponse response, String format,
        HashMap<String, String> latinParameters, boolean isTUintern, boolean isUBintern, boolean is52bIBA)
        throws IOException {

    String openurl = "";

    try {/* w  w w.ja  v a  2 s . co m*/

        // build openurl
        for (String k : latinParameters.keySet()) {

            // repeat input-openurl
            if (!k.equals("format") && !k.equals("system") && !latinParameters.get(k).equals("")) {

                if (latinParameters.get(k).contains("/>")) {
                    latinParameters.put(k, latinParameters.get(k).replaceAll("/>", ""));
                }
                if (latinParameters.get(k).contains(">")) {
                    latinParameters.put(k, latinParameters.get(k).replaceAll(">", ""));
                }

                String prefix = "";
                if (!k.startsWith("rft")) {
                    prefix = "rft.";
                }

                String value = "";

                if (k.contains("title") || k.contains("au")) {
                    value = latinParameters.get(k);
                } else if (k.contains("issn") && !latinParameters.get(k).equals("")) {

                    if (latinParameters.get(k).contains("-")) {
                        value = latinParameters.get(k);
                    } else {
                        value = latinParameters.get(k).subSequence(0, 4) + "-"
                                + latinParameters.get(k).subSequence(4, 8);
                    }
                } else {
                    value = latinParameters.get(k);
                }

                openurl += "&" + prefix + k + "=" + URLEncoder.encode(value, "UTF-8");
            }
        }
        this.logger.debug("\n" + "\tOpenURL-Parameter = " + this.config.getProperty("linkresolver.baseurl")
                + this.config.getProperty("linkresolver.parameters") + openurl);

        ArrayList<Document> daiaDocuments = new ArrayList<Document>();

        // falls OpenURL contains isbn: Anfrage an "normalen DaiaService Endpoint
        String isbn = "";
        if (latinParameters.get("rft.isbn") != null && !latinParameters.get("rft.isbn").equals("")) {
            isbn = latinParameters.get("rft.isbn");
        } else if (latinParameters.get("isbn") != null && !latinParameters.get("isbn").equals("")) {
            isbn = latinParameters.get("isbn");
        } else if (latinParameters.get("id") != null && latinParameters.get("id").contains("isbn:")) {
            isbn = latinParameters.get("id").split(":")[1];
        }
        this.logger.debug("ISBN = " + isbn);

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

            if (Lookup.lookupAll(IntegratedLibrarySystem.class).size() > 0) {
                // erst DAIA isbn fragen
                if (isbn.contains("; ")) {
                    isbn = isbn.replaceAll("; ", ",");
                }
                String daiaUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                        + "/daia/?id=isbn:" + isbn;
                this.logger.debug("daiaUrl = " + daiaUrl);
                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(daiaUrl);
                httpGet.addHeader("Accept", "application/xml");

                CloseableHttpResponse httpResponse = httpclient.execute(httpGet);

                try {

                    int statusCode = httpResponse.getStatusLine().getStatusCode();
                    HttpEntity httpEntity = httpResponse.getEntity();

                    switch (statusCode) {

                    case 200: {

                        JAXBContext jaxbContext = JAXBContext.newInstance(Daia.class);
                        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                        Daia daia = (Daia) unmarshaller.unmarshal(httpEntity.getContent());

                        if (daia.getDocument() != null) {

                            daiaDocuments.addAll(daia.getDocument());
                        }

                        break;
                    }
                    default: {

                        // TODO Evaluieren: Das mssten die Flle sein, in denen E-Books in der Knowledgebase eingetragen sind
                        if (Lookup.lookupAll(LinkResolver.class).size() > 0) {

                            Document daiaDocument = null;

                            LinkResolver linkResolver = Lookup.lookup(LinkResolver.class);
                            // init Linkresolver
                            linkResolver.init(this.config);

                            // get items
                            ArrayList<Document> linkresolverDocument = linkResolver.items("openurl", openurl);

                            if (linkresolverDocument != null && linkresolverDocument.size() > 0) {

                                daiaDocument = new Document();

                                daiaDocument.setId("urn:isbn:" + isbn);

                                if (daiaDocument.getItem() == null || daiaDocument.getItem().size() == 0) {

                                    daiaDocument.setItem(linkresolverDocument.get(0).getItem());
                                } else {
                                    daiaDocument.getItem().addAll(linkresolverDocument.get(0).getItem());
                                }

                                if (daiaDocument != null) {

                                    daiaDocuments.add(daiaDocument);
                                }
                            }
                        }
                    }
                    }

                    EntityUtils.consume(httpEntity);
                } finally {
                    httpResponse.close();
                }
            }
        } else {

            // Wenn JOP registriert ist
            if (Lookup.lookupAll(JournalOnlinePrintService.class).size() > 0) {

                // build OpenURL for JOP
                String issn = "";
                if (latinParameters.get("rft.issn") != null && !latinParameters.get("rft.issn").equals("")) {
                    issn = latinParameters.get("rft.issn");
                } else if (latinParameters.get("issn") != null && !latinParameters.get("issn").equals("")) {
                    issn = latinParameters.get("issn");
                }
                if (latinParameters.get("rft.eissn") != null && !latinParameters.get("rft.eissn").equals("")) {
                    issn = latinParameters.get("rft.eissn");
                } else if (latinParameters.get("eissn") != null && !latinParameters.get("eissn").equals("")) {
                    issn = latinParameters.get("eissn");
                } else if (latinParameters.get("id") != null && latinParameters.get("id").contains("issn:")) {
                    issn = latinParameters.get("id").split(":")[1];
                }
                this.logger.debug("ISSN = " + issn);

                String jop_openurl = "";

                for (String k : latinParameters.keySet()) {

                    // mit rft
                    if ((latinParameters.keySet().contains("rft.atitle")
                            || latinParameters.keySet().contains("atitle")) && k.equals("rft.date")
                            && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&date=" + latinParameters.get(k);
                    }
                    if (k.equals("rft.volume") && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&volume=" + latinParameters.get(k);
                    }
                    if (k.equals("rft.issue") && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&issue=" + latinParameters.get(k);
                    }

                    // ohne rft
                    if ((latinParameters.keySet().contains("rft.atitle")
                            || latinParameters.keySet().contains("atitle")) && k.equals("date")
                            && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&date=" + latinParameters.get(k);
                    }
                    if (k.equals("volume") && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&volume=" + latinParameters.get(k);
                    }
                    if (k.equals("issue") && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&issue=" + latinParameters.get(k);
                    }
                }

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

                    if (issn.contains("-")) {
                        jop_openurl += "&issn=" + issn;
                    } else {
                        jop_openurl += "&issn=" + issn.subSequence(0, 4) + "-" + issn.subSequence(4, 8);
                    }
                }

                if (latinParameters.keySet().contains("rft.atitle")
                        || latinParameters.keySet().contains("atitle")) {
                    jop_openurl += "&genre=article";
                } else {
                    jop_openurl += "&genre=journal";
                }

                this.logger.debug("\n" + jop_openurl + "\tOpenURL-Parameter (JOP) = "
                        + this.config.getProperty("jop.url.openurl") + jop_openurl);

                if (!jop_openurl.equals("&genre=journal")
                        && (jop_openurl.contains("&title=") || jop_openurl.contains("&issn="))) {

                    // get data
                    try {

                        JournalOnlinePrintService journalOnlinePrintService = Lookup
                                .lookup(JournalOnlinePrintService.class);
                        // init JOP
                        journalOnlinePrintService.init(this.config);

                        // get items
                        ArrayList<de.tu_dortmund.ub.api.daia.jop.model.Document> jopDocuments = journalOnlinePrintService
                                .items("openurl", jop_openurl);

                        if (jopDocuments != null && jopDocuments.size() > 0) {

                            Document daiaDocument = new Document();

                            this.logger.debug("JOP hits: " + jopDocuments.size());

                            if (jopDocuments.get(0).getId() != null && jopDocuments.get(0).getHref() != null) {
                                daiaDocument.setId(jopDocuments.get(0).getId());
                                daiaDocument.setHref(jopDocuments.get(0).getHref());
                            } else {
                                daiaDocument.setId("urn:issn:" + issn);
                            }

                            // print
                            if (jopDocuments.get(0).getItem() != null
                                    && jopDocuments.get(0).getItem().size() > 0) {
                                daiaDocument.setItem(jopDocuments.get(0).getItem());
                            }

                            // digital
                            if (jopDocuments.get(0).isExistsDigitalItems()
                                    && Lookup.lookupAll(LinkResolver.class).size() > 0) {

                                // TODO define a boolean variable for executing a linkresolver request
                                // TODO auslagern!
                                LinkResolver linkResolver = Lookup.lookup(LinkResolver.class);
                                // init Linkresolver
                                linkResolver.init(this.config);

                                // get items
                                ArrayList<Document> linkresolverDocument = linkResolver.items("openurl",
                                        openurl);

                                if (linkresolverDocument != null && linkresolverDocument.size() > 0
                                        && linkresolverDocument.get(0).getItem().size() >= jopDocuments.get(0)
                                                .getCountDigitlItems()) {

                                    if (daiaDocument.getItem() == null || daiaDocument.getItem().size() == 0) {
                                        daiaDocument.setItem(linkresolverDocument.get(0).getItem());
                                    } else {
                                        daiaDocument.getItem().addAll(linkresolverDocument.get(0).getItem());
                                    }
                                } else {

                                    // TODO Ticket 11679

                                    // E-Mail an katalogplus@ub.tu-dortmund.de mit Betreff-Prefix [Content]

                                    boolean isNatLic = true;

                                    if (isNatLic) {

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

                                            // request JOP again with only ISSN
                                            jopDocuments = journalOnlinePrintService.eonly("issn", issn);

                                            if (jopDocuments != null && jopDocuments.size() > 0) {

                                                this.logger.debug("JOP hits: " + jopDocuments.size());

                                                if (daiaDocument.getItem() == null
                                                        || daiaDocument.getItem().size() == 0) {
                                                    daiaDocument.setItem(jopDocuments.get(0).getItem());
                                                } else {
                                                    if (jopDocuments.get(0).getItem() != null) {
                                                        daiaDocument.getItem()
                                                                .addAll(jopDocuments.get(0).getItem());
                                                    } else {

                                                        // Error-E-Mail "JOP<>LinkResolver: Not an NatLic"
                                                        Mailer mailer = new Mailer(
                                                                this.config.getProperty("service.mailer.conf"));

                                                        try {

                                                            int cnt = 0;
                                                            if (linkresolverDocument != null) {
                                                                cnt = linkresolverDocument.get(0).getItem()
                                                                        .size();
                                                            }

                                                            mailer.postMail(
                                                                    "[DAIAopenurl] JOP-Document ohne Items ",
                                                                    "JOP-Link "
                                                                            + jopDocuments.get(0)
                                                                                    .getCountDigitlItems()
                                                                            + ": "
                                                                            + this.config.getProperty(
                                                                                    "jop.url.openurl")
                                                                            + jop_openurl + ".\n");

                                                        } catch (MessagingException e) {

                                                            this.logger.error(e.getMessage(), e.getCause());
                                                            this.logger.debug("[DAIAopenurl] CONTENT-ERROR");
                                                            this.logger.debug("OpenUrl: " + openurl
                                                                    + "\n\n\tJOP-URL: " + jop_openurl);
                                                        }

                                                        if (daiaDocument.getItem() == null
                                                                || daiaDocument.getItem().size() == 0) {
                                                            daiaDocument = null;
                                                        }
                                                    }
                                                }

                                            }
                                        } else {

                                            // Error-E-Mail "JOP<>LinkResolver: Not an NatLic"
                                            Mailer mailer = new Mailer(
                                                    this.config.getProperty("service.mailer.conf"));

                                            try {

                                                int cnt = 0;
                                                if (linkresolverDocument != null) {
                                                    cnt = linkresolverDocument.get(0).getItem().size();
                                                }

                                                mailer.postMail(
                                                        "[DAIAopenurl] JOP<>LinkResolver: NatLic without ISSN ",
                                                        "Laut ZDB/EZB gibt es "
                                                                + jopDocuments.get(0).getCountDigitlItems()
                                                                + "-mal elektronischen Bestand (vgl. "
                                                                + this.config.getProperty("jop.url.openurl")
                                                                + jop_openurl + ").\n" + "Laut 360 Link aber "
                                                                + cnt + "-mal (vgl. "
                                                                + this.config
                                                                        .getProperty("linkresolver.baseurl")
                                                                + this.config
                                                                        .getProperty("linkresolver.parameters")
                                                                + openurl + ").");

                                            } catch (MessagingException e) {

                                                this.logger.error(e.getMessage(), e.getCause());
                                                this.logger.debug("[DAIAopenurl] CONTENT-ERROR");
                                                this.logger.debug("OpenUrl: " + openurl + "\n\n\tJOP-URL: "
                                                        + jop_openurl);
                                            }

                                            if (daiaDocument.getItem() == null
                                                    || daiaDocument.getItem().size() == 0) {
                                                daiaDocument = null;
                                            }
                                        }
                                    } else {
                                        // Hier kann man nix machen!
                                    }
                                }
                            }

                            if (daiaDocument != null) {

                                daiaDocuments.add(daiaDocument);
                            }
                        }

                    } catch (LinkResolverException e) {

                        // daiaDocuments bleibt leer
                        this.logger.error("[DaiaService OpenUrl Endpoint] Exception: "
                                + HttpServletResponse.SC_SERVICE_UNAVAILABLE
                                + " Service unavailable (LinkResolver).");
                        this.logger.error(e.getMessage(), e.getCause());
                        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                            this.logger.error("\t" + stackTraceElement.toString());
                        }

                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {
                            mailer.postMail(
                                    "[DaiaService OpenUrl Endpoint] Exception: "
                                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE
                                            + " Service unavailable (LinkResolver).",
                                    e.getMessage() + "\n" + this.config.getProperty("linkresolver.baseurl")
                                            + this.config.getProperty("linkresolver.parameters") + openurl);

                        } catch (MessagingException e1) {

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

                    } catch (JOPException e) {

                        // daiaDocuments bleibt leer
                        this.logger.error("[DaiaService OpenUrl Endpoint] Exception: "
                                + HttpServletResponse.SC_SERVICE_UNAVAILABLE
                                + " Service unavailable (Journals Online & Print).");
                        this.logger.error(e.getMessage(), e.getCause());
                        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                            this.logger.error("\t" + stackTraceElement.toString());
                        }

                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {
                            mailer.postMail(
                                    "[DaiaService OpenUrl Endpoint] Exception: "
                                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE
                                            + " Service unavailable (Journals Online & Print).",
                                    e.getMessage() + "\n" + this.config.getProperty("jop.url.openurl")
                                            + jop_openurl);

                        } catch (MessagingException e1) {

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

                    // tue nix: daiaDocuments bleibt leer
                }
            }
        }

        // Abschlusskorrektur fr ACM, IEEE und LNCS vor dem response
        // LNCS
        if (Lookup.lookupAll(LncsResolver.class).size() > 0
                && Boolean.parseBoolean(this.config.getProperty("licenced.lncs"))) {

            if (daiaDocuments.size() > 0) {

                for (Document daiaDocument : daiaDocuments) {

                    if (daiaDocument != null && daiaDocument.getId() != null
                            && daiaDocument.getId().contains("urn:issn:03029743")
                            && ((latinParameters.keySet().contains("id")
                                    && latinParameters.get("id").startsWith("doi:10.1007"))
                                    || (latinParameters.keySet().contains("rft.id")
                                            && latinParameters.get("rft.id").startsWith("doi:10.1145")))) {

                        daiaDocument.setItem(null);

                        LncsResolver lncsResolver = Lookup.lookup(LncsResolver.class);
                        lncsResolver.init(this.config);

                        Document lncsDocument = lncsResolver.items(latinParameters);

                        daiaDocument.setId(lncsDocument.getId());
                        daiaDocument.setHref(lncsDocument.getHref());
                        daiaDocument.setItem(lncsDocument.getItem());
                    }
                }
            }
        }

        // ACM
        if (Lookup.lookupAll(AcmResolver.class).size() > 0
                && Boolean.parseBoolean(this.config.getProperty("licenced.acm"))) {

            if ((latinParameters.keySet().contains("id") && latinParameters.get("id").contains("10.1145"))
                    || (latinParameters.keySet().contains("rft.id")
                            && latinParameters.get("rft.id").contains("10.1145"))) {

                if (daiaDocuments.size() > 0) {

                    for (Document daiaDocument : daiaDocuments) {

                        daiaDocument.setItem(null);

                        AcmResolver acmResolver = Lookup.lookup(AcmResolver.class);
                        acmResolver.init(this.config);

                        Document acmDocument = acmResolver.items(latinParameters);

                        daiaDocument.setId(acmDocument.getId());
                        daiaDocument.setHref(acmDocument.getHref());

                        if (daiaDocument.getItem() == null) {
                            daiaDocument.setItem(acmDocument.getItem());
                        } else {
                            daiaDocument.getItem().addAll(acmDocument.getItem());
                        }
                    }
                } else {

                    Document daiaDocument = new Document();

                    AcmResolver acmResolver = Lookup.lookup(AcmResolver.class);
                    acmResolver.init(this.config);

                    Document acmDocument = acmResolver.items(latinParameters);

                    daiaDocument.setId(acmDocument.getId());
                    daiaDocument.setHref(acmDocument.getHref());

                    if (daiaDocument.getItem() == null) {
                        daiaDocument.setItem(acmDocument.getItem());
                    } else {
                        daiaDocument.getItem().addAll(acmDocument.getItem());
                    }

                    daiaDocuments.add(daiaDocument);
                }
            }
        }

        // IEEE
        if (Lookup.lookupAll(IeeeResolver.class).size() > 0
                && Boolean.parseBoolean(this.config.getProperty("licenced.ieee"))) {

            if ((latinParameters.keySet().contains("id") && latinParameters.get("id").contains("10.1109"))
                    || (latinParameters.keySet().contains("rft.id")
                            && latinParameters.get("rft.id").contains("10.1109"))) {

                if (daiaDocuments.size() > 0) {

                    for (Document daiaDocument : daiaDocuments) {

                        daiaDocument.setItem(null);

                        IeeeResolver ieeeResolver = Lookup.lookup(IeeeResolver.class);
                        ieeeResolver.init(this.config);

                        Document ieeeDocument = ieeeResolver.items(latinParameters);

                        daiaDocument.setId(ieeeDocument.getId());
                        daiaDocument.setHref(ieeeDocument.getHref());

                        if (daiaDocument.getItem() == null) {
                            daiaDocument.setItem(ieeeDocument.getItem());
                        } else {
                            daiaDocument.getItem().addAll(ieeeDocument.getItem());
                        }
                    }
                } else {

                    Document daiaDocument = new Document();

                    IeeeResolver ieeeResolver = Lookup.lookup(IeeeResolver.class);
                    ieeeResolver.init(this.config);

                    Document ieeeDocument = ieeeResolver.items(latinParameters);

                    daiaDocument.setId(ieeeDocument.getId());
                    daiaDocument.setHref(ieeeDocument.getHref());

                    if (daiaDocument.getItem() == null) {
                        daiaDocument.setItem(ieeeDocument.getItem());
                    } else {
                        daiaDocument.getItem().addAll(ieeeDocument.getItem());
                    }

                    daiaDocuments.add(daiaDocument);
                }
            }
        }

        if (daiaDocuments.size() > 0) {

            this.logger.debug("200 Document Found");

            // TODO query footnotes from ils if configured

            // Ausgabe
            Daia daia = new Daia();
            daia.setVersion(this.config.getProperty("daia.version"));
            daia.setSchema(this.config.getProperty("daia.schema"));

            GregorianCalendar gc = new GregorianCalendar();
            gc.setTimeInMillis(new Date().getTime());
            try {
                DatatypeFactory df = DatatypeFactory.newInstance();

                daia.setTimestamp(df.newXMLGregorianCalendar(gc).toString());

            } catch (DatatypeConfigurationException dce) {
                this.logger.error("ERROR: Service unavailable.", dce.getCause());
            }

            Institution institution = new Institution();
            institution.setId(this.config.getProperty("daia.institution.id"));
            institution.setHref(this.config.getProperty("daia.institution.href"));
            institution.setContent(this.config.getProperty("daia.institution.content"));
            daia.setInstitution(institution);

            daia.setDocument(daiaDocuments);

            // Ausgabe
            if (daia.getDocument() == null || daia.getDocument().size() == 0) {

                // HTML-Ausgabe via XSLT
                if (format.equals("html")) {

                    try {

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

                        // Write to HttpResponse
                        StringWriter stringWriter = new StringWriter();
                        m.marshal(daia, stringWriter);

                        org.jdom2.Document doc = new org.jdom2.Document();
                        doc.setRootElement(new Element("daia"));

                        HashMap<String, String> parameters = new HashMap<String, String>();
                        parameters.put("lang", "de");
                        parameters.put("isTUintern", Boolean.toString(isTUintern));
                        parameters.put("isUBintern", Boolean.toString(isUBintern));
                        parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                        parameters.put("id", "openurl:" + URLDecoder.decode(openurl, "UTF-8"));

                        ObjectMapper mapper = new ObjectMapper();
                        StringWriter json = new StringWriter();
                        mapper.writeValue(json, daia);
                        parameters.put("json", json.toString());

                        String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"),
                                parameters);

                        response.setContentType("text/html;charset=UTF-8");
                        response.setStatus(HttpServletResponse.SC_OK);
                        response.getWriter().println(html);
                    } catch (PropertyException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'.");
                    } catch (JAXBException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'.");
                    }
                } else {

                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "Document not found.");
                }
            } else {

                this.logger.debug("format = " + format);

                // HTML-Ausgabe via XSLT
                if (format.equals("html")) {

                    try {

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

                        // Write to HttpResponse
                        StringWriter stringWriter = new StringWriter();
                        m.marshal(daia, stringWriter);

                        org.jdom2.Document doc = new SAXBuilder()
                                .build(new StringReader(this.cleanup(stringWriter.toString())));

                        HashMap<String, String> parameters = new HashMap<String, String>();
                        parameters.put("lang", "de");
                        parameters.put("isTUintern", Boolean.toString(isTUintern));
                        parameters.put("isUBintern", Boolean.toString(isUBintern));
                        parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                        parameters.put("id", "openurl:" + URLDecoder.decode(openurl, "UTF-8"));

                        ObjectMapper mapper = new ObjectMapper();
                        StringWriter json = new StringWriter();
                        mapper.writeValue(json, daia);
                        parameters.put("json", json.toString());

                        String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"),
                                parameters);

                        response.setContentType("text/html;charset=UTF-8");
                        response.setStatus(HttpServletResponse.SC_OK);
                        response.getWriter().println(html);
                    } catch (PropertyException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    } catch (JAXBException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    } catch (JDOMException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    } catch (IOException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    }
                }

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

                    try {

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

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

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

                    ObjectMapper mapper = new ObjectMapper();

                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_OK);

                    mapper.writeValue(response.getWriter(), daia);
                }

                // RDF-Ausgabe mit XSLT auf XML-Ausgabe
                if (format.equals("rdf")) {

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

                        // Write to HttpResponse
                        response.setContentType("application/xml;charset=UTF-8");
                        response.setStatus(HttpServletResponse.SC_OK);

                        StringWriter xml = new StringWriter();
                        m.marshal(daia, xml);

                        XMLOutputter out = new XMLOutputter();
                        out.output(
                                new SAXBuilder().build(new StringReader(
                                        xmlOutputter(new SAXBuilder().build(new StringReader(xml.toString())),
                                                config.getProperty("xslt_xml2rdf"), null))),
                                response.getWriter());

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

            this.logger.debug("404 Document Not Found + (format=" + format + ")");

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

                try {

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

                    // Write to HttpResponse
                    org.jdom2.Document doc = new org.jdom2.Document();
                    doc.setRootElement(new Element("daia"));

                    HashMap<String, String> parameters = new HashMap<String, String>();
                    parameters.put("lang", "de");
                    parameters.put("isTUintern", Boolean.toString(isTUintern));
                    parameters.put("isUBintern", Boolean.toString(isUBintern));
                    parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                    parameters.put("id", "openurl:" + URLDecoder.decode(openurl, "UTF-8"));

                    String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"),
                            parameters);

                    response.setContentType("text/html;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.getWriter().println(html);
                } catch (PropertyException e) {
                    this.logger.error(e.getMessage(), e.getCause());
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'.");
                } catch (JAXBException e) {
                    this.logger.error(e.getMessage(), e.getCause());
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'.");
                }
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Document not found.");
            }
        }
    } catch (Exception e) {

        this.logger.error("[DaiaService OpenUrl Endpoint] Exception: "
                + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable.");
        this.logger.error(e.getMessage(), e.getCause());
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            this.logger.error("\t" + stackTraceElement.toString());
        }

        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

        try {
            mailer.postMail("[DaiaService OpenUrl Endpoint] Exception: "
                    + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable.",
                    e.getMessage() + "\n" + request.getRequestURL());

        } catch (MessagingException e1) {

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

        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Service unavailable.");
    }
}

From source file:davmail.exchange.ews.EwsExchangeSession.java

@Override
public void sendMessage(MimeMessage mimeMessage) throws IOException, MessagingException {
    String itemClass = null;/*w w  w . j a  v  a2  s  . c  o  m*/
    if (mimeMessage.getContentType().startsWith("multipart/report")) {
        itemClass = "REPORT.IPM.Note.IPNRN";
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        mimeMessage.writeTo(baos);
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
    sendMessage(itemClass, baos.toByteArray());
}

From source file:davmail.exchange.ews.EwsExchangeSession.java

@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties,
        MimeMessage mimeMessage) throws IOException {
    EWSMethod.Item item = new EWSMethod.Item();
    item.type = "Message";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*from   w w  w  .j  ava2s. c  o m*/
        mimeMessage.writeTo(baos);
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
    baos.close();
    item.mimeContent = Base64.encodeBase64(baos.toByteArray());

    List<FieldUpdate> fieldUpdates = buildProperties(properties);
    if (!properties.containsKey("draft")) {
        // need to force draft flag to false
        if (properties.containsKey("read")) {
            fieldUpdates.add(Field.createFieldUpdate("messageFlags", "1"));
        } else {
            fieldUpdates.add(Field.createFieldUpdate("messageFlags", "0"));
        }
    }
    fieldUpdates.add(Field.createFieldUpdate("urlcompname", messageName));
    item.setFieldUpdates(fieldUpdates);
    CreateItemMethod createItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly,
            getFolderId(folderPath), item);
    executeMethod(createItemMethod);
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Construct the folder subtree for the given folder and append it to
 * xml_parent./*from w  ww.  j a  v a 2s .co m*/
 *
 * N.b. this method does not necessarily create a new XML Folder Element.
 * If called with subscribed_only and the target Folder (and in some
 * cases its descendants) are not subscribed, no Element will be created
 * and 0 will be returned.
 * <P>
 * Pop servers don't support nesting at all, so you'll just get a single
 * level out of this method.
 * <P>
 * There is a critical subscribed_only difference in behavior between
 * Maildir and mbox type mail servers.
 * Maildir folders are all HOLDS_MESSAGES, whether empty or not, and
 * these folders have a subscribed attribute which the user can set,
 * and which we honor.
 * mbox folders, on the other hand, have no subscribed attribute for
 * their !HOLDS_MESSAGE folders, so we must recurse to all of the
 * descendant HOLDS_MESSAGE folders to see if we should show.
 *
 * @param folder the folder where we begin
 * @param xml_parent XML Element where the gathered information will be
 *                   appended
 * @param subscribed_only Only add 'subscribed' folders
 * @param doCount Whether to generate message counts for Elements
 *                corresponding to HOLDS_MESSAGE folders.
 * @returns maximum depth of the folder tree (needed to calculate the
 *     necessary columns in a table).  Returns 0 if no XML elements added.
 */
protected int getFolderTree(Folder folder, Element xml_parent, boolean subscribed_only, boolean doCount) {
    int generatedDepth = 0;
    int folderType;
    Element xml_folder;

    try {
        folderType = folder.getType();
    } catch (MessagingException ex) {
        log.error("Can't get enough info from server to even make Gui node", ex);
        xml_parent.setAttribute("error", "For child '" + folder.getName() + ":  " + ex.getMessage());
        return 0;
    }
    boolean holds_folders = (folderType & Folder.HOLDS_FOLDERS) != 0;
    boolean holds_messages = (folderType & Folder.HOLDS_MESSAGES) != 0;
    // Sanity check:
    if ((!holds_folders) && !holds_messages) {
        log.fatal("Folder can hold neither folders nor messages: " + folder.getFullName());
        throw new RuntimeException("Folder can hold neither folders nor messages: " + folder.getFullName());
    }
    if (subscribed_only && holds_messages && !folder.isSubscribed())
        return generatedDepth; // Return right away and save a LOT OF WORK
    // N.b. we honor folder.isSubscribed() only for holds_message
    // folders.  That means all Maildir server folders, and all
    // mbox server folders except for mbox directories.  In this
    // last case, we must recurse to determine whether to show folder.
    String id = generateFolderHash(folder);
    xml_folder = model.createFolder(id, folder.getName(), holds_folders, holds_messages);
    // XMLUserModel.createFolder() declares no throws.  If any Exceptions
    // are expected from it, move the statement above into the try block.
    // The xml_folder Element here will be orphaned and GC'd if we don't
    // appendChild (in which case we return 0).

    if (doCount && holds_messages)
        try {
            // this folder will definitely be added!
            /* This folder can contain messages */
            Element messagelist = model.createMessageList();

            int total_messages = folder.getMessageCount();
            int new_messages = folder.getNewMessageCount();

            if (total_messages == -1 || new_messages == -1 || !folder.isOpen()) {
                folder.open(Folder.READ_ONLY);
                total_messages = folder.getMessageCount();
                new_messages = folder.getNewMessageCount();
            }
            if (folder.isOpen())
                folder.close(false);

            messagelist.setAttribute("total", total_messages + "");
            messagelist.setAttribute("new", new_messages + "");
            log.debug("Counted " + new_messages + '/' + total_messages + " for folder " + folder.getFullName());
            xml_folder.appendChild(messagelist);
        } catch (MessagingException ex) {
            log.warn("Failed to count messages in folder '" + folder.getFullName() + "'", ex);
            xml_folder.setAttribute("error", ex.getMessage());
        }

    int descendantDepth = 0;
    if (holds_folders)
        try {
            Set<String> fullNameSet = new HashSet<String>();

            /* Recursively add subfolders to the XML model */
            // DO NOT USE listSubscribed(), because with !HOLDS_MESSAGE
            // folders, that skips non-Message Folders which may contain
            // subscribed descendants!
            for (Folder f : folder.list()) {
                if (!fullNameSet.add(f.getFullName())) {
                    log.warn("Skipping duplicate subfolder returned by mail" + " server:  " + f.getFullName());
                    continue;
                }
                if (subscribed_only && (f.getType() & Folder.HOLDS_MESSAGES) != 0 && !f.isSubscribed())
                    continue;
                /* If we recursed here, the getFolderTree() would
                 * just return 0 and no harm done.
                 * Just helping performance by preventing a recursion
                 * here.
                 * For comment on the logic here, see the same test
                 * towards the top of this method (before recursion).
                 */
                int depth = getFolderTree(f, xml_folder, subscribed_only, doCount);
                if (depth > descendantDepth)
                    descendantDepth = depth;
            }
            generatedDepth += descendantDepth;
        } catch (MessagingException ex) {
            xml_folder.setAttribute("error", ex.getMessage());
        }

    // We've already validated that if subscribed_only and holds_message
    //  then folder is subcribed.  Also verified either holds_m or holds_f.
    //  Only have to check the !holds_message case.
    if (subscribed_only && (!holds_messages) && descendantDepth < 1) {
        xml_folder = null;
        // Unnecessary, but may encourage GC
        return generatedDepth;
    }

    /* We ALWAYS return only subscribed folders except for these two
     * distinct cases: */
    xml_folder.setAttribute("subscribed",
            ((holds_messages && !folder.isSubscribed()) || ((!holds_messages) && descendantDepth < 1)) ? "false"
                    : "true");
    // N.b. our Element's "subscribed" element does not correspond 1:1
    // to Folder.isSubscribed(), since non-message-holding Folders have
    // no "subscribed" attribute.
    folders.put(id, folder);

    xml_parent.appendChild(xml_folder);
    generatedDepth++; // Add the count for xml_folder
    return generatedDepth;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Refresh Information about folders.//  ww  w.ja v  a  2s . co  m
 * Tries to connect folders that are not yet connected.
 *
 * @doCount display message counts for user
 */
public void refreshFolderInformation(boolean subscribed_only, boolean doCount) {
    /* Right now, doCount corresponds exactly to subscribed_only.
     * When we add a user preference setting or one-time action,
     * to present messages from all folders, we will have
     * subscribed_only false and doCount true. */

    //log.fatal("Invoking refreshFolderInformation(boolean, boolean)",
    //new Throwable("Thread Dump"));  FOR DEBUGGING
    setEnv();
    if (folders == null)
        folders = new Hashtable<String, Folder>();
    Folder rootFolder = null;
    String cur_mh_id = "";
    Enumeration mailhosts = user.mailHosts();
    int max_depth = 0;
    int folderType;

    while (mailhosts.hasMoreElements()) {
        cur_mh_id = (String) mailhosts.nextElement();

        MailHostData mhd = user.getMailHost(cur_mh_id);

        URLName url = new URLName(mhd.getHostURL());

        Element mailhost = model.createMailhost(mhd.getName(), mhd.getID(), url.toString());

        int depth = 0;

        try {
            rootFolder = getRootFolder(cur_mh_id);

            try {
                rootFolder.setSubscribed(true);
            } catch (MessagingException ex) {
                // Only IMAP supports subscription
                log.warn("Folder.setSubscribed failed.  " + "Probably a non-supporting mail service: " + ex);
            }
        } catch (MessagingException ex) {
            mailhost.setAttribute("error", ex.getMessage());
            log.warn("Failed to connect and get Root folder from (" + url + ')', ex);
            return;
        }

        try {
            depth = getFolderTree(rootFolder.getFolder("INBOX"), mailhost, subscribed_only, doCount);
            log.debug("Loaded INBOX folders below Root to a depth of " + depth);
            String extraFolderPath = ((imapBasedir == null) ? "~" : imapBasedir) + mhd.getLogin();
            //String extraFolderPath = "/home/" + mhd.getLogin();
            Folder nonInboxBase = rootFolder.getFolder(extraFolderPath);
            log.debug("Trying extra base dir " + nonInboxBase.getFullName());
            if (nonInboxBase.exists()) {
                folderType = nonInboxBase.getType();
                if ((folderType & Folder.HOLDS_MESSAGES) != 0) {
                    // Can only Subscribe to Folders which may hold Msgs.
                    nonInboxBase.setSubscribed(true);
                    if (!nonInboxBase.isSubscribed())
                        log.error("A bug in JavaMail or in the server is " + "preventing subscription to '"
                                + nonInboxBase.getFullName() + "' on '" + url
                                + "'.  Folders will not be visible.");
                }
                int extraDepth = extraDepth = getFolderTree(nonInboxBase, mailhost, subscribed_only, doCount);
                if (extraDepth > depth)
                    depth = extraDepth;
                log.debug("Loaded additional folders from below " + nonInboxBase.getFullName()
                        + " with max depth of " + extraDepth);
            }
        } catch (Exception ex) {
            if (!url.getProtocol().startsWith("pop"))
                mailhost.setAttribute("error", ex.getMessage());
            log.warn("Failed to fetch child folders from (" + url + ')', ex);
        }
        if (depth > max_depth)
            max_depth = depth;
        model.addMailhost(mailhost);
    }
    model.setStateVar("max folder depth", (1 + max_depth) + "");
}