Example usage for org.jdom2 Document Document

List of usage examples for org.jdom2 Document Document

Introduction

In this page you can find the example usage for org.jdom2 Document Document.

Prototype

public Document() 

Source Link

Document

Creates a new empty document.

Usage

From source file:de.knewcleus.openradar.gui.flightplan.FlightPlanExchangeManager.java

License:Open Source License

private String buildXml(FlightPlanData fpd) {
    Document doc = new Document();
    Element root = new Element("flightplanList");
    doc.addContent(root);/*from ww  w . java 2 s  .c o  m*/

    try {
        root.setAttribute("version", "1.0");
        Element elementFp = FpXml_1_0.createXml(fpd);
        if (elementFp != null) {
            root.addContent(elementFp);
        }
    } catch (Exception ex) {
        log.error("Problem to create flightplan...", ex);
    }
    StringWriter sw = new StringWriter();
    try {
        // XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat());
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        sw = new StringWriter();
        outputter.output(doc, sw);
    } catch (Exception e) {
        log.error("Problem to create XML output...", e);
    }

    return sw.toString();
}

From source file:de.sixtyfourktec.mirrorhub.modules.NationalRailModule.java

License:Open Source License

private NationalRailModule() {
    /* Create the soap envelope document */
    Document doc = new Document();
    Namespace soap = Namespace.getNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
    Namespace ldb = Namespace.getNamespace("ldb", "http://thalesgroup.com/RTTI/2014-02-20/ldb/");
    Namespace typ = Namespace.getNamespace("typ", "http://thalesgroup.com/RTTI/2010-11-01/ldb/commontypes");
    Element env = new Element("Envelope", soap);
    /* Header */// w  ww  .  j av  a 2 s . com
    env.addContent(new Element("Header", soap).addContent(new Element("AccessToken", typ)
            .addContent(new Element("TokenValue", typ).addContent(BuildConfig.NATIONALRAIL_API_KEY))));
    /* Body */
    Element dep_request = new Element("GetDepartureBoardRequest", ldb)
            .addContent(new Element("crs", ldb).addContent(BuildConfig.NATIONALRAIL_CRS))
            .addContent(new Element("numRows", ldb).addContent("5"));
    if (!BuildConfig.NATIONALRAIL_FILTER_CRS.isEmpty()) {
        dep_request.addContent(new Element("filterCrs", ldb).addContent(BuildConfig.NATIONALRAIL_FILTER_CRS))
                .addContent(new Element("filterType", ldb).addContent(BuildConfig.NATIONALRAIL_FILTER_TYPE));
    }
    env.addContent(new Element("Body", soap).addContent(dep_request));
    doc.setContent(env);
    String xml = new XMLOutputter(Format.getPrettyFormat()).outputString(doc);
    if (showXml) {
        Log.i(TAG, xml);
    }

    /* Create a static request object we can reuse */
    RequestBody body = RequestBody.create(MediaType.parse("text/xml; charset=utf-8"), xml);
    request = new Request.Builder().url("https://lite.realtime.nationalrail.co.uk/OpenLDBWS/ldb6.asmx")
            .post(body).build();
}

From source file:de.sub.goobi.helper.tasks.ProcessSwapInTask.java

License:Open Source License

/**
 * Aufruf als Thread ================================================================
 *//*www  .  j  av  a2  s  .  c  o m*/
@SuppressWarnings("deprecation")
@Override
public void run() {
    setStatusProgress(5);
    String swapPath = null;
    //      ProzessDAO dao = new ProzessDAO();
    String processDirectory = "";

    if (ConfigurationHelper.getInstance().isUseSwapping()) {
        swapPath = ConfigurationHelper.getInstance().getSwapPath();
    } else {
        setStatusMessage("swapping not activated");
        setStatusProgress(-1);
        return;
    }
    if (swapPath == null || swapPath.length() == 0) {
        setStatusMessage("no swappingPath defined");
        setStatusProgress(-1);
        return;
    }
    Path swapFile = Paths.get(swapPath);
    if (!StorageProvider.getInstance().isFileExists(swapFile)) {
        setStatusMessage("Swap folder does not exist or is not mounted");
        setStatusProgress(-1);
        return;
    }
    try {
        processDirectory = getProzess().getProcessDataDirectoryIgnoreSwapping();
        // TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage(
                "Error while getting process data folder: " + e.getClass().getName() + " - " + e.getMessage());
        setStatusProgress(-1);
        return;
    }

    Path fileIn = Paths.get(processDirectory);
    Path fileOut = Paths.get(swapPath + getProzess().getId() + FileSystems.getDefault().getSeparator());

    if (!StorageProvider.getInstance().isFileExists(fileOut)) {
        setStatusMessage(getProzess().getTitel() + ": swappingOutTarget does not exist");
        setStatusProgress(-1);
        return;
    }
    if (!StorageProvider.getInstance().isFileExists(fileIn)) {
        setStatusMessage(getProzess().getTitel() + ": process data folder does not exist");
        setStatusProgress(-1);
        return;
    }

    SAXBuilder builder = new SAXBuilder();
    Document docOld;
    try {
        Path swapLogFile = Paths.get(processDirectory, "swapped.xml");
        docOld = builder.build(swapLogFile.toFile());
        // TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage("Error while reading swapped.xml in process data folder: " + e.getClass().getName()
                + " - " + e.getMessage());
        setStatusProgress(-1);
        return;
    }

    /*
     * --------------------- alte Checksummen in HashMap schreiben -------------------
     */
    setStatusMessage("reading checksums");
    Element rootOld = docOld.getRootElement();

    HashMap<String, String> crcMap = new HashMap<String, String>();

    // TODO: Don't use Iterators
    for (Iterator<Element> it = rootOld.getChildren("file").iterator(); it.hasNext();) {
        Element el = it.next();
        crcMap.put(el.getAttribute("path").getValue(), el.getAttribute("crc32").getValue());
    }
    StorageProvider.getInstance().deleteDataInDir(fileIn);

    /*
     * --------------------- Dateien kopieren und Checksummen ermitteln -------------------
     */
    Document doc = new Document();
    Element root = new Element("goobiArchive");
    doc.setRootElement(root);

    /*
     * --------------------- Verzeichnisse und Dateien kopieren und anschliessend den Ordner leeren -------------------
     */
    setStatusProgress(50);
    try {
        setStatusMessage("copying process files");
        Helper.copyDirectoryWithCrc32Check(fileOut, fileIn, swapPath.length(), root);
    } catch (IOException e) {
        logger.warn("IOException:", e);
        setStatusMessage("IOException in copyDirectory: " + e.getMessage());
        setStatusProgress(-1);
        return;
    }
    setStatusProgress(80);

    /*
     * --------------------- Checksummen vergleichen -------------------
     */
    setStatusMessage("checking checksums");
    // TODO: Don't use Iterators
    for (Iterator<Element> it = root.getChildren("file").iterator(); it.hasNext();) {
        Element el = it.next();
        String newPath = el.getAttribute("path").getValue();
        String newCrc = el.getAttribute("crc32").getValue();
        if (crcMap.containsKey(newPath)) {
            if (!crcMap.get(newPath).equals(newCrc)) {
                setLongMessage(getLongMessage() + "File " + newPath + " has different checksum<br/>");
            }
            crcMap.remove(newPath);
        }
    }

    setStatusProgress(85);
    /*
     * --------------------- prfen, ob noch Dateien fehlen -------------------
     */
    setStatusMessage("checking missing files");
    if (crcMap.size() > 0) {
        for (String myFile : crcMap.keySet()) {
            setLongMessage(getLongMessage() + "File " + myFile + " is missing<br/>");
        }
    }

    setStatusProgress(90);

    /* in Prozess speichern */
    StorageProvider.getInstance().deleteDir(fileOut);
    try {
        setStatusMessage("saving process");
        Process myProzess = ProcessManager.getProcessById(getProzess().getId());
        myProzess.setSwappedOutGui(false);
        ProcessManager.saveProcess(myProzess);
    } catch (DAOException e) {
        setStatusMessage("DAOException while saving process: " + e.getMessage());
        logger.warn("DAOException:", e);
        setStatusProgress(-1);
        return;
    }
    setStatusMessage("done");

    setStatusProgress(100);
}

From source file:de.sub.goobi.helper.tasks.ProcessSwapOutTask.java

License:Open Source License

/**
 * Aufruf als Thread ================================================================
 *//*from  w  ww  .  ja va 2 s  .co m*/
@SuppressWarnings("deprecation")
@Override
public void run() {
    setStatusProgress(5);
    Helper help = new Helper();
    String swapPath = null;
    //      ProzessDAO dao = new ProzessDAO();
    String processDirectory = "";

    if (ConfigurationHelper.getInstance().isUseSwapping()) {
        swapPath = ConfigurationHelper.getInstance().getSwapPath();
    } else {
        setStatusMessage("swapping not activated");
        setStatusProgress(-1);
        return;
    }
    if (swapPath == null || swapPath.length() == 0) {
        setStatusMessage("no swappingPath defined");
        setStatusProgress(-1);
        return;
    }
    Path swapFile = Paths.get(swapPath);
    if (!StorageProvider.getInstance().isFileExists(swapFile)) {
        setStatusMessage("Swap folder does not exist or is not mounted");
        setStatusProgress(-1);
        return;
    }
    try {
        processDirectory = getProzess().getProcessDataDirectoryIgnoreSwapping();
        //TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage(
                "Error while getting process data folder: " + e.getClass().getName() + " - " + e.getMessage());
        setStatusProgress(-1);
        return;
    }

    Path fileIn = Paths.get(processDirectory);
    Path fileOut = Paths.get(swapPath + getProzess().getId() + FileSystems.getDefault().getSeparator());
    if (StorageProvider.getInstance().isFileExists(fileOut)) {
        setStatusMessage(getProzess().getTitel() + ": swappingOutTarget already exists");
        setStatusProgress(-1);
        return;
    }
    try {
        StorageProvider.getInstance().createDirectories(fileOut);
    } catch (IOException e1) {
        logger.error(e1);
    }

    /* ---------------------
     * Xml-Datei vorbereiten
    * -------------------*/
    Document doc = new Document();
    Element root = new Element("goobiArchive");
    doc.setRootElement(root);
    Element source = new Element("source").setText(fileIn.toString());
    Element target = new Element("target").setText(fileOut.toString());
    Element title = new Element("title").setText(getProzess().getTitel());
    Element mydate = new Element("date").setText(new Date().toString());
    root.addContent(source);
    root.addContent(target);
    root.addContent(title);
    root.addContent(mydate);

    /* ---------------------
     * Verzeichnisse und Dateien kopieren und anschliessend den Ordner leeren
    * -------------------*/
    setStatusProgress(50);
    try {
        setStatusMessage("copying process folder");
        Helper.copyDirectoryWithCrc32Check(fileIn, fileOut, help.getGoobiDataDirectory().length(), root);
    } catch (IOException e) {
        logger.warn("IOException:", e);
        setStatusMessage("IOException in copyDirectory: " + e.getMessage());
        setStatusProgress(-1);
        return;
    }
    setStatusProgress(80);
    StorageProvider.getInstance().deleteDataInDir(fileIn);

    /* ---------------------
     * xml-Datei schreiben
    * -------------------*/
    Format format = Format.getPrettyFormat();
    format.setEncoding("UTF-8");
    try {
        setStatusMessage("writing swapped.xml");
        XMLOutputter xmlOut = new XMLOutputter(format);
        FileOutputStream fos = new FileOutputStream(
                processDirectory + FileSystems.getDefault().getSeparator() + "swapped.xml");
        xmlOut.output(doc, fos);
        fos.close();
        //TODO: Don't catch Exception (the super class)
    } catch (Exception e) {
        logger.warn("Exception:", e);
        setStatusMessage(e.getClass().getName() + " in xmlOut.output: " + e.getMessage());
        setStatusProgress(-1);
        return;
    }
    setStatusProgress(90);

    /* in Prozess speichern */
    try {
        setStatusMessage("saving process");
        Process myProzess = ProcessManager.getProcessById(getProzess().getId());
        myProzess.setSwappedOutGui(true);
        ProcessManager.saveProcess(myProzess);
    } catch (DAOException e) {
        setStatusMessage("DAOException while saving process: " + e.getMessage());
        logger.warn("DAOException:", e);
        setStatusProgress(-1);
        return;
    }
    setStatusMessage("done");
    setStatusProgress(100);
}

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

License:Open Source License

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

    String ips = request.getHeader("X-Forwarded-For");

    boolean isTUintern = false;
    boolean isUBintern = false;
    boolean is52bIBA = false;

    try {/*from  w w w  . ja v a  2  s. co  m*/
        if (ips != null) {

            String[] ranges = config.getProperty("service.iprange.tu").split("\\|");
            for (String range : ranges) {

                if (ips.matches(range)) {

                    isTUintern = true;
                    break;
                }
            }

            String[] exceptions = config.getProperty("service.iprange.tu.exceptions").split("\\|");
            if (isTUintern) {

                for (String exception : exceptions) {

                    if (ips.matches(exception)) {

                        isTUintern = false;
                        break;
                    }
                }
            }

            ranges = config.getProperty("service.iprange.ub").split("\\|");
            for (String range : ranges) {

                if (ips.matches(range)) {

                    isUBintern = true;
                    break;
                }
            }
            exceptions = config.getProperty("service.iprange.ub.exceptions").split("\\|");
            if (isUBintern) {

                for (String exception : exceptions) {

                    if (ips.matches(exception)) {

                        isUBintern = false;
                        break;
                    }
                }
            }

            ranges = config.getProperty("service.iprange.ub.52bIBAs").split("\\|");
            exceptions = config.getProperty("service.iprange.ub.52bIBAs.exceptions").split("\\|");
            String tmp[] = ips.split(", ");

            for (int i = 1; i < 3; i++) {

                try {
                    String ip = tmp[tmp.length - i];

                    for (String range : ranges) {

                        if (ip.matches(range)) {

                            is52bIBA = true;
                            break;
                        }
                    }

                    if (exceptions.length > 0) {

                        if (is52bIBA) {

                            for (String exception : exceptions) {

                                if (ip.matches(exception)) {

                                    is52bIBA = false;
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception e) {

                }
            }
        }
    } catch (Exception e) {

        this.logger.error(e.getMessage(), e.getCause());
    }
    this.logger.info("[" + this.config.getProperty("service.name") + "] " + "Where is it from? "
            + request.getHeader("X-Forwarded-For") + ", " + isTUintern + ", " + isUBintern + ", " + is52bIBA);

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

    try {
        String format = "html";

        if (request.getParameter("format") != null && !request.getParameter("format").equals("")) {

            format = request.getParameter("format");
        } else {

            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerNameKey = headerNames.nextElement();

                if (headerNameKey.equals("Accept")) {

                    this.logger.debug("headerNameKey = " + request.getHeader(headerNameKey));

                    if (request.getHeader(headerNameKey).contains("text/html")) {
                        format = "html";
                    } else if (request.getHeader(headerNameKey).contains("application/xml")) {
                        format = "xml";
                    } else if (request.getHeader(headerNameKey).contains("application/json")) {
                        format = "json";
                    }
                }
            }
        }

        if (format.equals("")) {

            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No valid {FORMAT} requested.");
        } else if (request.getParameter("id") == null || request.getParameter("id").equals("")) {

            this.logger.debug("Query: " + request.getQueryString());

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

                response.sendRedirect(this.config.getProperty("service.doc"));
            } else {

                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Usage: http://api.ub-tu-dortmund.de.de/daia/?id={ID}&format={FORMAT}.");
            }
        } else {

            if (request.getParameter("id").contains(":")) {

                String[] tmp = request.getParameter("id").split(":");
                this.logger.debug("id = " + request.getParameter("id") + "' - " + new Date());
                String idtype = tmp[0];
                String localpart = "";
                if (tmp.length > 1) {
                    for (int i = 1; i < tmp.length; i++) {
                        localpart += tmp[i];

                        if (i < tmp.length - 1) {
                            localpart += ":";
                        }
                    }
                }

                if (!(idtype.equals("ilsid") || idtype.equals("isbn") || idtype.equals("issn")
                        || idtype.equals("verbundid") || idtype.equals("eki") || idtype.equals("zdbid"))) {

                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No valid {IDTYPE} requested.");
                } else {

                    try {

                        // Wenn via META-INF/services eine Implementierung zum interface "IntegratedLibrarySystem" erfolgt ist, dann frage das System ab.
                        if (Lookup.lookupAll(IntegratedLibrarySystem.class).size() > 0) {

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

                            ArrayList<de.tu_dortmund.ub.api.daia.ils.model.Document> documents = null;
                            documents = integratedLibrarySystem.items(idtype, localpart);

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

                                ArrayList<de.tu_dortmund.ub.api.daia.model.Document> daiaDocuments = new ArrayList<de.tu_dortmund.ub.api.daia.model.Document>();

                                ArrayList<Integer> indexToRemove = new ArrayList<Integer>();

                                for (de.tu_dortmund.ub.api.daia.ils.model.Document document : documents) {

                                    if (document == null) {

                                        // Wie kann das sein?
                                        this.logger.error(
                                                "document = null for '" + idtype + ":" + localpart + "'");
                                    } else {

                                        if (document.getItem() == null
                                                || (document.getItem() != null
                                                        && document.getItem().size() == 0)
                                                || (document.getErschform() != null
                                                        && document.getErschform().equals("p")
                                                        && document.getVeroefart() != null
                                                        && !document.getVeroefart().equals("da"))
                                                || (document.getErschform() != null
                                                        && document.getErschform().equals("z"))) {

                                            // TODO 2015-03-06: HttpClient-Aufruf an den OpenURL-DaiaService
                                            if (Lookup.lookupAll(JournalOnlinePrintService.class).size() > 0) {

                                                String issn = null;
                                                if (document.getIssnprint() != null) {
                                                    issn = document.getIssnprint().replaceAll("ISSN ", "");
                                                } else if (document.getIssn() != null) {
                                                    issn = document.getIssn();
                                                } else if (document.getIssnwww() != null) {
                                                    issn = document.getIssnwww().replaceAll("ISSN ", "");
                                                }

                                                this.logger.debug("JOP mit ISSN = " + issn);
                                                this.logger.debug("JOP mit ZDB-ID = " + document.getZdbid());

                                                if (issn != null) {
                                                    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("issn", issn);

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

                                                        de.tu_dortmund.ub.api.daia.model.Document daiaDocument = new de.tu_dortmund.ub.api.daia.model.Document();

                                                        if (idtype.equals("verbundid")) {

                                                            //daiaDocument.setId(this.config.getProperty("daia.document.baseurl") + localpart);
                                                            //daiaDocument.setHref(this.config.getProperty("daia.document.baseurl") + localpart);
                                                            daiaDocument.setId(document.getId());
                                                            daiaDocument.setHref(document.getHref());
                                                        } else if (idtype.equals("issn")) {

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

                                                            if (jopDocuments.get(0).getHref() != null) {
                                                                daiaDocument
                                                                        .setId(jopDocuments.get(0).getHref());
                                                            }
                                                        } else {

                                                            if (jopDocuments.get(0).getId() != null) {
                                                                daiaDocument.setId(jopDocuments.get(0).getId());
                                                            } else {
                                                                daiaDocument.setId(this.config.getProperty(
                                                                        "daia.document.baseurl") + localpart);
                                                            }

                                                            if (jopDocuments.get(0).getHref() != null) {
                                                                daiaDocument
                                                                        .setId(jopDocuments.get(0).getHref());
                                                            } else {
                                                                daiaDocument.setHref(this.config.getProperty(
                                                                        "daia.document.baseurl") + localpart);
                                                            }
                                                        }

                                                        // 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) {

                                                            String openurl = "";

                                                            if (document.getMediatype() != null
                                                                    && document.getMediatype().equals("g")) {

                                                                this.logger.debug(
                                                                        "document.getMediatype().equals(\"g\")");

                                                                openurl += "&rft.genre=journal&rft.eissn="
                                                                        + issn;

                                                                if (document.getIssnprint() != null) {
                                                                    if (document.getIssnprint()
                                                                            .startsWith("ISSN ")) {
                                                                        openurl += "&rft.issn=" + document
                                                                                .getIssnprint()
                                                                                .replaceAll("ISSN ", "");
                                                                    } else {

                                                                        openurl += "&rft.issn="
                                                                                + document.getIssnprint();
                                                                    }
                                                                }
                                                            } else {

                                                                if (document.getIssnprint() != null) {
                                                                    if (document.getIssnprint()
                                                                            .startsWith("ISSN ")) {
                                                                        openurl += "&rft.genre=journal&rft.issn="
                                                                                + document.getIssnprint()
                                                                                        .replaceAll("ISSN ",
                                                                                                "");
                                                                    } else {

                                                                        openurl += "&rft.genre=journal&rft.issn="
                                                                                + document.getIssnprint();
                                                                    }

                                                                    openurl += "&rft.eissn="
                                                                            + document.getIssn();
                                                                } else if (document.getIssnwww() != null) {
                                                                    if (document.getIssnwww()
                                                                            .startsWith("ISSN ")) {
                                                                        openurl += "&rft.genre=journal&rft.eissn="
                                                                                + document.getIssnwww()
                                                                                        .replaceAll("ISSN ",
                                                                                                "");
                                                                    } else {
                                                                        openurl += "&rft.genre=journal&rft.eissn="
                                                                                + document.getIssnwww();
                                                                    }
                                                                    openurl += "&rft.issn="
                                                                            + document.getIssn();
                                                                } else {
                                                                    openurl += "&rft.genre=journal&&rft.issn="
                                                                            + document.getIssn();
                                                                }

                                                                // TODO reicht das aus?
                                                                //openurl += "&rft.genre=journal&&rft.issn=" + issn;
                                                            }

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

                                                            // get items
                                                            ArrayList<de.tu_dortmund.ub.api.daia.model.Document> linkresolverDocument = linkResolver
                                                                    .items("openurl", openurl);

                                                            if (linkresolverDocument != null
                                                                    && linkresolverDocument.size() > 0) {
                                                                this.logger.debug(linkresolverDocument.get(0)
                                                                        .getItem().size() + ", "
                                                                        + jopDocuments.get(0)
                                                                                .getCountDigitlItems());
                                                            }

                                                            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 {

                                                                this.logger.debug("Ja, der Fall ist das!");
                                                                openurl = "";

                                                                if (document.getIssnprint() != null) {
                                                                    if (document.getIssnprint()
                                                                            .startsWith("ISSN ")) {
                                                                        openurl += "&rft.genre=journal&&rft.issn="
                                                                                + document.getIssnprint()
                                                                                        .replaceAll("ISSN ",
                                                                                                "");
                                                                    }
                                                                } else if (document.getIssnwww() != null) {
                                                                    if (document.getIssnwww()
                                                                            .startsWith("ISSN ")) {
                                                                        openurl += "&rft.genre=journal&&rft.issn="
                                                                                + document.getIssnwww()
                                                                                        .replaceAll("ISSN ",
                                                                                                "");
                                                                    }
                                                                }

                                                                if (!openurl.equals("")) {
                                                                    // get items
                                                                    linkresolverDocument = linkResolver
                                                                            .items("openurl", openurl);

                                                                    if (linkresolverDocument != null
                                                                            && linkresolverDocument
                                                                                    .size() > 0) {
                                                                        this.logger.debug(linkresolverDocument
                                                                                .get(0).getItem().size() + ", "
                                                                                + jopDocuments.get(0)
                                                                                        .getCountDigitlItems());
                                                                    }

                                                                    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 {
                                                                                        daiaDocument.getItem()
                                                                                                .addAll(jopDocuments
                                                                                                        .get(0)
                                                                                                        .getItem());
                                                                                    }

                                                                                }
                                                                            } else {

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

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

                                                                    //daiaDocument = null;

                                                                    /* TODO tue nix? */
                                                                    if (daiaDocument.getItem() == null
                                                                            || daiaDocument.getItem()
                                                                                    .size() == 0) {

                                                                        if (daiaDocument.getItem() == null) {
                                                                            daiaDocument.setItem(
                                                                                    new ArrayList<Item>());
                                                                        }
                                                                        daiaDocument
                                                                                .setItem(linkresolverDocument
                                                                                        .get(0).getItem());
                                                                    } else {
                                                                        daiaDocument.getItem()
                                                                                .addAll(linkresolverDocument
                                                                                        .get(0).getItem());
                                                                    }

                                                                }

                                                            }
                                                        }

                                                        if (daiaDocument != null) {

                                                            daiaDocuments.add(daiaDocument);
                                                        }
                                                    }
                                                } else if (document.getZdbid() != null) {

                                                    this.logger.info("Bin drin!");

                                                    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("zdbid", document.getZdbid());

                                                    if (jopDocuments != null) {

                                                        this.logger.info(
                                                                "jopDocuments.size()=" + jopDocuments.size());
                                                    }

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

                                                        de.tu_dortmund.ub.api.daia.model.Document daiaDocument = new de.tu_dortmund.ub.api.daia.model.Document();

                                                        if (jopDocuments.get(0).getId() != null) {
                                                            daiaDocument.setId(jopDocuments.get(0).getId());
                                                        } else {
                                                            daiaDocument.setId(this.config
                                                                    .getProperty("daia.document.baseurl")
                                                                    + document.getZdbid());
                                                        }

                                                        if (jopDocuments.get(0).getHref() != null) {
                                                            daiaDocument.setHref(jopDocuments.get(0).getHref());
                                                        } else {
                                                            daiaDocument.setHref(this.config
                                                                    .getProperty("daia.document.baseurl")
                                                                    + document.getZdbid());
                                                        }

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

                                                        // digital - nicht mglich, da ISSN fehlt
                                                        this.logger.info(
                                                                "jopDocuments.get(0).isExistsDigitalItems()="
                                                                        + jopDocuments.get(0)
                                                                                .isExistsDigitalItems());

                                                        if (jopDocuments.get(0).isExistsDigitalItems()) {

                                                            jopDocuments = journalOnlinePrintService
                                                                    .eonly("zdbid", document.getZdbid());

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

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

                                                        daiaDocuments.add(daiaDocument);
                                                    }
                                                } else {
                                                    // evtl. Serienaufnahme
                                                    indexToRemove.add(documents.indexOf(document));
                                                }
                                            }
                                        } else {
                                            de.tu_dortmund.ub.api.daia.model.Document daiaDocument = new de.tu_dortmund.ub.api.daia.model.Document();
                                            daiaDocument.setId(document.getId());
                                            daiaDocument.setHref(document.getHref());

                                            if (document.getErschform() != null
                                                    && document.getErschform().equals("p")
                                                    && document.getVeroefart() != null
                                                    && document.getVeroefart().equals("da")) {

                                                // TODO inhaltlich falsch
                                                if (document.getLokaleurl() != null
                                                        && !document.getLokaleurl().equals("")) {

                                                    //this.logger.info(document.getItem().size() + " Items");
                                                    document.getItem().get(0)
                                                            .setHref(document.getLokaleurl().get(0));
                                                } else if (document.getUrl() != null
                                                        && !document.getUrl().equals("")) {
                                                    document.getItem().get(0).setHref(document.getUrl().get(0));
                                                }
                                            }

                                            daiaDocument.setItem(document.getItem());

                                            String editionStatement = "";
                                            if (document.getAusgabe() != null
                                                    && !document.getAusgabe().equals("")) {
                                                editionStatement += document.getAusgabe() + ". ";
                                            }
                                            if (document.getErschjahr() != null
                                                    && !document.getErschjahr().equals("")) {
                                                editionStatement += document.getErschjahr();
                                            }
                                            if (document.getUmfang() != null
                                                    && !document.getUmfang().equals("")) {
                                                editionStatement += ". - " + document.getUmfang();
                                            }
                                            daiaDocument.setEdition(editionStatement);
                                            daiaDocuments.add(daiaDocument);
                                        }
                                    }
                                }

                                if (indexToRemove.size() > 0) {

                                    for (Integer i : indexToRemove) {

                                        documents.remove(Integer.valueOf(i));
                                    }

                                }

                                if (daiaDocuments.size() > 0) {

                                    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 java.util.Date().getTime());
                                    try {
                                        DatatypeFactory df = DatatypeFactory.newInstance();

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

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

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

                                            Document doc = new SAXBuilder()
                                                    .build(new StringReader(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));

                                            this.logger.debug("idtype = " + idtype);
                                            parameters.put("id", idtype + ":" + localpart);

                                            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.");
                                        }
                                    }

                                    // 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 {

                                    // Document not found
                                    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
                                            Document doc = new 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", idtype + ":" + localpart);

                                            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 {

                                // Document not found
                                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
                                        Document doc = new 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", idtype + ":" + localpart);

                                        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 {
                            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                                    "Service unavailable (ILS): No ILS configured!");
                        }
                    } catch (ILSException e) {
                        e.printStackTrace();
                        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                                "Service unavailable (ILS).");
                    } catch (LinkResolverException e) {
                        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                                "Service unavailable (LinkResolver).");
                    } catch (JOPException e) {
                        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                                "Service unavailable (JOP).");
                    }
                }
            }
        }
    } catch (Exception e) {

        e.printStackTrace();

        this.logger.error(new Date() + "[DAIA] 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 {

            String referer = "'none'";
            if (request.getHeader("referer") != null) {

                referer = request.getHeader("referer");
            }
            mailer.postMail(
                    "[DAIA] Exception: " + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable.",
                    e.getMessage() + "\n" + request.getRequestURL() + "\n" + ips + "\n" + referer + "\n" + "\n"
                            + e.getCause().toString());

        } catch (MessagingException e1) {

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

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

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

License:Open Source License

/**
 * PAIAauth services: Prfe jeweils die scopes und liefere die Daten
 *//*from   w w  w  . j a  v a 2s . 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:de.unirostock.sems.cbarchive.web.dataholder.MetaObjectDataholder.java

License:Open Source License

/**
 * Generates a temporarily id for the meta entry
 *//*from   www. j a  va2 s  .  com*/
@JsonIgnore
public void generateId() {

    Element xmlElement = metaObject.getXmlDescription();
    String xmlString = null;
    try {
        Document doc = new Document();
        doc.setRootElement(xmlElement.clone());
        xmlString = Utils.prettyPrintDocument(doc);
    } catch (IOException | TransformerException e) {
        LOGGER.error(e, "Can't generate xml from meta object to generate meta id");
        return;
    }

    id = Tools.generateHashId(xmlString);
    //      LOGGER.debug("generated ID: ", id);
}

From source file:de.unirostock.sems.cbarchive.web.dataholder.XmlTreeMetaObjectDataholder.java

License:Open Source License

public String getXmlString() {
    try {/*from   w  ww . j av  a2s.c o  m*/
        Document doc = new Document().setRootElement(xmlTree.clone());
        return Utils.prettyPrintDocument(doc);
    } catch (IOException | TransformerException e) {
        LOGGER.error(e, "Cannot transform Xml Element to String.");
        return "";
    }
}

From source file:delfos.configfile.rs.single.DatasetConfigurationFileParser.java

License:Open Source License

/**
 * Almacena la configuracin completa del dataset en el fichero indicado.
 *
 * @param configFile Nombre del fichero en que se almacena la configuracin.
 * @param datasetLoader Objeto para recuperar los datos de entrada.
 * @throws java.io.IOException//from w  w  w  .  j a  va2  s .c o m
 */
public static void saveConfigFile(File configFile, DatasetLoader datasetLoader) throws IOException {

    Document doc = new Document();
    Element root = new Element("config");

    //Creo el objeto Jdom del datasetLoader
    root.addContent(DatasetLoaderXML.getElement(datasetLoader));

    doc.addContent(root);
    XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat());

    if (!configFile.getAbsolutePath().endsWith("." + CONFIGURATION_EXTENSION)) {
        configFile = new File(configFile.getAbsolutePath() + "." + CONFIGURATION_EXTENSION);
    }

    try (FileWriter fileWriter = new FileWriter(configFile)) {
        outputter.output(doc, fileWriter);
    }
}

From source file:delfos.configfile.rs.single.RecommenderSystemConfigurationFileParser.java

License:Open Source License

/**
 * Almacena la configuracin completa del sistema en el fichero indicado.
 *
 * @param fileName Fichero en el que se almacena la configuracin.
 * @param recommenderSystem Sistema de recomendacin que utiliza.
 * @param datasetLoader Objeto para recuperar los datos de entrada.
 * @param relevanceCriteria Criterio de relevancia utilizado.
 * @param persistenceMethod//w ww . j  a va2  s  .  c  om
 * @param recommendationCandidatesSelector
 * @param recommdendationsOutputMethod
 */
public static void saveConfigFile(String fileName, GenericRecommenderSystem recommenderSystem,
        DatasetLoader<? extends Rating> datasetLoader, RelevanceCriteria relevanceCriteria,
        PersistenceMethod persistenceMethod, RecommendationCandidatesSelector recommendationCandidatesSelector,
        RecommendationsOutputMethod recommdendationsOutputMethod) {

    Document doc = new Document();
    Element root = new Element("config");

    //Creo el objeto Jdom del sistema de recomendacin
    root.addContent(RecommenderSystemXML.getElement(recommenderSystem));

    //Creo el objeto Jdom del datasetLoader
    root.addContent(DatasetLoaderXML.getElement(datasetLoader));

    //Umbral de relevancia
    root.addContent(RelevanceCriteriaXML.getElement(relevanceCriteria));

    //Persistence Method
    root.addContent(PersistenceMethodXML.getElement(persistenceMethod));

    root.addContent(RecommendationCandidatesSelectorXML.getElement(recommendationCandidatesSelector));

    root.addContent(RecommdendationsOutputMethodXML.getElement(recommdendationsOutputMethod));

    doc.addContent(root);

    XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat());

    try {
        if (!fileName.endsWith("." + CONFIGURATION_EXTENSION)) {
            fileName += "." + CONFIGURATION_EXTENSION;
        }
        try (FileWriter fileWriter = new FileWriter(fileName)) {
            outputter.output(doc, fileWriter);
        }
    } catch (IOException ex) {
        ERROR_CODES.CANNOT_WRITE_FILE.exit(ex);
    }
}