Example usage for java.util Locale GERMAN

List of usage examples for java.util Locale GERMAN

Introduction

In this page you can find the example usage for java.util Locale GERMAN.

Prototype

Locale GERMAN

To view the source code for java.util Locale GERMAN.

Click Source Link

Document

Useful constant for language.

Usage

From source file:org.ms123.common.git.GitServiceImpl.java

public List getRepositories(@PName("flags") @POptional List<String> flags,
        @PName("all") @PDefaultBool(false) @POptional Boolean all) throws RpcException {
    System.out.println("getRepositories;" + flags + "/" + all);
    try {//from  w  w  w .  ja va  2s . c  o  m
        String gitSpace = System.getProperty("git.repos");
        File dir = new File(gitSpace);
        if (!dir.exists()) {
            throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.gitSpace not exists");
        }
        List<Map> resList = new ArrayList<Map>();
        File[] chld = dir.listFiles();
        FS fs = FS.detect();
        for (int i = 0; i < chld.length; i++) {
            File file = chld[i];
            String fileName = file.getName();
            if (!all && hasStoreCfg(file) == false) {
                continue;
            }
            debug("\n---------------->" + fileName);
            Map map = new HashMap();
            if (flags != null && flags.contains("updateAvailable")) {
                Git gitObject = Git.open(new File(gitSpace, fileName));
                map.put("updateAvailable", updateAvailable(gitObject));
            }
            if (flags != null && flags.contains("isModified")) {
                Git gitObject = Git.open(new File(gitSpace, fileName));
                map.put("isModified", isModified(gitObject));
            }
            debug(fileName);
            FileBasedConfig fbc = new FileBasedConfig(new File(gitSpace + "/" + fileName + "/.git/config"), fs);
            fbc.load();
            debug("FBC:" + fbc);
            debug("FBC:" + fbc.getSections());
            debug("FBC:" + fbc.toText());
            String created = fbc.getString("sw", null, "created");
            SimpleDateFormat sdf = new SimpleDateFormat(m_datePattern, Locale.GERMAN);
            map.put("name", fileName);
            if (created != null) {
                map.put("created", sdf.parse(created).getTime());
            }
            resList.add(map);
        }
        return resList;
    } catch (Exception e) {
        if (e instanceof RpcException)
            throw (RpcException) e;
        throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.getRepositories:", e);
    } finally {
    }
}

From source file:org.gtdfree.GTDFree.java

/**
 * @param args/*from   ww  w  . ja v  a  2s .  co  m*/
 */
@SuppressWarnings("static-access")
public static void main(final String[] args) {

    //ApplicationHelper.changeDefaultFontSize(6, "TextField");
    //ApplicationHelper.changeDefaultFontSize(6, "TextArea");
    //ApplicationHelper.changeDefaultFontSize(6, "Table");
    //ApplicationHelper.changeDefaultFontSize(6, "Tree");

    //ApplicationHelper.changeDefaultFontStyle(Font.BOLD, "Tree");

    final Logger logger = Logger.getLogger(GTDFree.class);
    logger.setLevel(Level.ALL);
    BasicConfigurator.configure();

    Options op = new Options();
    op.addOption("data", true, Messages.getString("GTDFree.Options.data")); //$NON-NLS-1$ //$NON-NLS-2$
    op.addOption("eodb", true, Messages.getString("GTDFree.Options.eodb")); //$NON-NLS-1$ //$NON-NLS-2$
    op.addOption("exml", true, Messages.getString("GTDFree.Options.exml")); //$NON-NLS-1$ //$NON-NLS-2$
    op.addOption("h", "help", false, Messages.getString("GTDFree.Options.help")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    op.addOption("log", true, Messages.getString("GTDFree.Options.log")); //$NON-NLS-1$ //$NON-NLS-2$

    Options op2 = new Options();
    op2.addOption(OptionBuilder.hasArg().isRequired(false)
            .withDescription(new MessageFormat(Messages.getString("GTDFree.Options.lang")) //$NON-NLS-1$
                    .format(new Object[] { "'en'", "'de', 'en'" })) //$NON-NLS-1$ //$NON-NLS-2$
            .withArgName("de|en") //$NON-NLS-1$
            .withLongOpt("Duser.language") //$NON-NLS-1$
            .withValueSeparator('=').create());
    op2.addOption(OptionBuilder.hasArg().isRequired(false)
            .withDescription(new MessageFormat(Messages.getString("GTDFree.Options.laf")).format(new Object[] { //$NON-NLS-1$
                    "'com.jgoodies.looks.plastic.Plastic3DLookAndFeel', 'com.jgoodies.looks.plastic.PlasticLookAndFeel', 'com.jgoodies.looks.plastic.PlasticXPLookAndFeel', 'com.jgoodies.looks.windows.WindowsLookAndFeel' (only on MS Windows), 'com.sun.java.swing.plaf.gtk.GTKLookAndFeel' (only on Linux with GTK), 'com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel', 'javax.swing.plaf.metal.MetalLookAndFeel'" })) //$NON-NLS-1$
            .withLongOpt("Dswing.crossplatformlaf") //$NON-NLS-1$
            .withValueSeparator('=').create());

    CommandLineParser clp = new GnuParser();
    CommandLine cl = null;
    try {
        cl = clp.parse(op, args);
    } catch (ParseException e1) {
        logger.error("Parse error.", e1); //$NON-NLS-1$
    }

    System.out.print("GTD-Free"); //$NON-NLS-1$
    String ver = ""; //$NON-NLS-1$
    try {
        System.out.println(" version " + (ver = ApplicationHelper.getVersion())); //$NON-NLS-1$

    } catch (Exception e) {
        System.out.println();
        // ignore
    }

    if (true) { // || cl.hasOption("help") || cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java [Java options] -jar gtd-free.jar [gtd-free options]" //$NON-NLS-1$
                , "[gtd-free options] - " + Messages.getString("GTDFree.Options.appop") //$NON-NLS-1$ //$NON-NLS-2$
                , op, "[Java options] - " + new MessageFormat(Messages.getString("GTDFree.Options.javaop")) //$NON-NLS-1$//$NON-NLS-2$
                        .format(new Object[] { "'-jar'" }) //$NON-NLS-1$
                , false);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        hf.setLongOptPrefix("-"); //$NON-NLS-1$
        hf.setWidth(88);
        hf.printOptions(pw, hf.getWidth(), op2, hf.getLeftPadding(), hf.getDescPadding());
        String s = sw.getBuffer().toString();
        s = s.replaceAll("\\A {3}", ""); //$NON-NLS-1$ //$NON-NLS-2$
        s = s.replaceAll("\n {3}", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        s = s.replaceAll(" <", "=<"); //$NON-NLS-1$ //$NON-NLS-2$
        System.out.print(s);
    }

    String val = cl.getOptionValue("data"); //$NON-NLS-1$
    if (val != null) {
        System.setProperty(ApplicationHelper.DATA_PROPERTY, val);
        System.setProperty(ApplicationHelper.TITLE_PROPERTY, "1"); //$NON-NLS-1$
    } else {
        System.setProperty(ApplicationHelper.TITLE_PROPERTY, "0"); //$NON-NLS-1$
    }

    val = cl.getOptionValue("log"); //$NON-NLS-1$
    if (val != null) {
        Level l = Level.toLevel(val, Level.ALL);
        logger.setLevel(l);
    }

    if (!ApplicationHelper.tryLock(null)) {
        System.out.println("Instance of GTD-Free already running, pushing it to be visible..."); //$NON-NLS-1$
        remotePushVisible();
        System.out.println("Instance of GTD-Free already running, exiting."); //$NON-NLS-1$
        System.exit(0);
    }

    if (!"OFF".equalsIgnoreCase(val)) { //$NON-NLS-1$
        RollingFileAppender f = null;
        try {
            f = new RollingFileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN),
                    ApplicationHelper.getLogFileName(), true);
            f.setMaxBackupIndex(3);
            BasicConfigurator.configure(f);
            f.rollOver();
        } catch (IOException e2) {
            logger.error("Logging error.", e2); //$NON-NLS-1$
        }
    }
    logger.info("GTD-Free " + ver + " started."); //$NON-NLS-1$ //$NON-NLS-2$
    logger.debug("Args: " + Arrays.toString(args)); //$NON-NLS-1$
    logger.info("Using data in: " + ApplicationHelper.getDataFolder()); //$NON-NLS-1$

    if (cl.getOptionValue("exml") != null || cl.getOptionValue("eodb") != null) { //$NON-NLS-1$ //$NON-NLS-2$

        GTDFreeEngine engine = null;

        try {
            engine = new GTDFreeEngine();
        } catch (Exception e1) {
            logger.fatal("Fatal error, exiting.", e1); //$NON-NLS-1$
        }

        val = cl.getOptionValue("exml"); //$NON-NLS-1$
        if (val != null) {
            File f1 = new File(val);
            if (f1.isDirectory()) {
                f1 = new File(f1, "gtd-free-" + ApplicationHelper.formatLongISO(new Date()) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            try {
                f1.getParentFile().mkdirs();
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
            try {
                engine.getGTDModel().exportXML(f1);
                logger.info("Data successfully exported as XML to " + f1.toString()); //$NON-NLS-1$
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
        }

        val = cl.getOptionValue("eodb"); //$NON-NLS-1$
        if (val != null) {
            File f1 = new File(val);
            if (f1.isDirectory()) {
                f1 = new File(f1, "gtd-free-" + ApplicationHelper.formatLongISO(new Date()) + ".odb-xml"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            try {
                f1.getParentFile().mkdirs();
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
            try {
                GTDData data = engine.getGTDModel().getDataRepository();
                if (data instanceof GTDDataODB) {
                    try {
                        ((GTDDataODB) data).exportODB(f1);
                    } catch (Exception e) {
                        logger.error("Export error.", e); //$NON-NLS-1$
                    }
                    logger.info("Data successfully exported as ODB to " + f1.toString()); //$NON-NLS-1$
                } else {
                    logger.info("Data is not stored in ODB database, nothing is exported."); //$NON-NLS-1$
                }
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
        }

        try {
            engine.close(true, false);
        } catch (Exception e) {
            logger.error("Internal error.", e); //$NON-NLS-1$
        }

        return;
    }

    logger.debug("Using OS '" + System.getProperty("os.name") + "', '" + System.getProperty("os.version") //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
            + "', '" + System.getProperty("os.arch") + "'."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    logger.debug("Using Java '" + System.getProperty("java.runtime.name") + "' version '" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            + System.getProperty("java.runtime.version") + "'."); //$NON-NLS-1$ //$NON-NLS-2$

    Locale[] supported = { Locale.ENGLISH, Locale.GERMAN };

    String def = Locale.getDefault().getLanguage();
    boolean toSet = true;
    for (Locale locale : supported) {
        toSet &= !locale.getLanguage().equals(def);
    }

    if (toSet) {
        logger.debug("System locale '" + def + "' not supported, setting to '" + Locale.ENGLISH.getLanguage() //$NON-NLS-1$//$NON-NLS-2$
                + "'."); //$NON-NLS-1$
        try {
            Locale.setDefault(Locale.ENGLISH);
        } catch (Exception e) {
            logger.warn("Setting default locale failed.", e); //$NON-NLS-1$
        }
    } else {
        logger.debug("Using locale '" + Locale.getDefault().toString() + "'."); //$NON-NLS-1$ //$NON-NLS-2$
    }

    try {
        //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.PlasticLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "javax.swing.plaf.metal.MetalLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        if (System.getProperty("swing.crossplatformlaf") == null) { //$NON-NLS-1$
            String osName = System.getProperty("os.name"); //$NON-NLS-1$
            if (osName != null && osName.toLowerCase().indexOf("windows") != -1) { //$NON-NLS-1$
                UIManager.setLookAndFeel("com.jgoodies.looks.windows.WindowsLookAndFeel"); //$NON-NLS-1$
            } else {
                try {
                    // we prefer to use native L&F, many systems support GTK, even if Java thinks it is not supported
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); //$NON-NLS-1$
                } catch (Throwable e) {
                    logger.debug("GTK L&F not supported.", e); //$NON-NLS-1$
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }
            }
        }
    } catch (Throwable e) {
        logger.warn("Setting L&F failed.", e); //$NON-NLS-1$
    }
    logger.debug("Using L&F '" + UIManager.getLookAndFeel().getName() + "' by " //$NON-NLS-1$//$NON-NLS-2$
            + UIManager.getLookAndFeel().getClass().getName());

    try {
        final GTDFree application = new GTDFree();

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {

                    application.getJFrame();
                    application.restore();
                    //application.getJFrame().setVisible(true);
                    application.pushVisible();

                    ApplicationHelper.executeInBackground(new Runnable() {
                        @Override
                        public void run() {
                            if (SystemTray.isSupported() && application.getEngine().getGlobalProperties()
                                    .getBoolean(GlobalProperties.SHOW_TRAY_ICON, false)) {
                                try {
                                    SystemTray.getSystemTray().add(application.getTrayIcon());
                                } catch (AWTException e) {
                                    logger.error("Failed to activate system tray icon.", e); //$NON-NLS-1$
                                }
                            }
                        }
                    });

                    ApplicationHelper.executeInBackground(new Runnable() {

                        @Override
                        public void run() {
                            application.exportRemote();
                        }
                    });

                    if (application.getEngine().getGlobalProperties()
                            .getBoolean(GlobalProperties.CHECK_FOR_UPDATE_AT_START, true)) {
                        ApplicationHelper.executeInBackground(new Runnable() {

                            @Override
                            public void run() {
                                application.checkForUpdates(false);
                            }
                        });
                    }

                } catch (Throwable t) {
                    t.printStackTrace();
                    logger.fatal("Failed to start application, exiting.", t); //$NON-NLS-1$
                    if (application != null) {
                        application.close(true);
                    }
                    System.exit(0);
                }
            }
        });

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    application.close(true);
                } catch (Exception e) {
                    logger.warn("Failed to stop application.", e); //$NON-NLS-1$
                }
                logger.info("Closed."); //$NON-NLS-1$
                ApplicationHelper.releaseLock();
                LogManager.shutdown();
            }
        });
    } catch (Throwable t) {
        logger.fatal("Initialization failed, exiting.", t); //$NON-NLS-1$
        t.printStackTrace();
        System.exit(0);
    }
}

From source file:de.geeksfactory.opacclient.apis.Heidi.java

@Override
public DetailledItem getResultById(String id, final String homebranch) throws IOException {

    if (sessid == null) {
        start();//from   w  w  w.j a  v  a  2s  .com
    }

    // Homebranch
    if (homebranch != null && !"".equals(homebranch)) {
        cookieStore.addCookie(new BasicClientCookie("zweig", homebranch));
    }

    String html = httpGet(opac_url + "/titel.cgi?katkey=" + id + "&sess=" + sessid, ENCODING, false,
            cookieStore);
    Document doc = Jsoup.parse(html);

    DetailledItem item = new DetailledItem();
    item.setId(id);

    Elements table = doc.select(".titelsatz tr");
    for (Element tr : table) {
        if (tr.select("th").size() == 0 || tr.select("td").size() == 0) {
            continue;
        }
        String d = tr.select("th").first().text();
        String c = tr.select("td").first().text();
        if (d.equals("Titel:")) {
            item.setTitle(c);
        } else if ((d.contains("URL") || d.contains("Link")) && tr.select("td a").size() > 0) {
            item.addDetail(new Detail(d, tr.select("td a").first().attr("href")));
        } else {
            item.addDetail(new Detail(d, c));
        }
    }

    if (doc.select(".ex table tr").size() > 0) {
        table = doc.select(".ex table tr");
        DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN);
        for (Element tr : table) {
            if (tr.hasClass("exueber") || tr.select(".exsig").size() == 0 || tr.select(".exso").size() == 0
                    || tr.select(".exstatus").size() == 0) {
                continue;
            }
            Copy copy = new Copy();
            copy.setShelfmark(tr.select(".exsig").first().text());
            copy.setBranch(tr.select(".exso").first().text());
            String status = tr.select(".exstatus").first().text();
            if (status.contains("entliehen bis")) {
                copy.setReturnDate(fmt.parseLocalDate(status.replaceAll("entliehen bis ([0-9.]+) .*", "$1")));
                copy.setReservations(status.replaceAll(".*\\(.*Vormerkungen: ([0-9]+)\\)", "$1"));
                copy.setStatus("entliehen");
            } else {
                copy.setStatus(status);
            }
            item.addCopy(copy);
        }
    }

    for (Element a : doc.select(".status1 a")) {
        if (a.attr("href").contains("bestellung.cgi")) {
            item.setReservable(true);
            item.setReservation_info(id);
            break;
        }
    }
    for (Element a : doc.select(".titelsatz a")) {
        if (a.text().trim().matches("B.+nde")) {
            Map<String, String> volumesearch = new HashMap<>();
            volumesearch.put("query", getQueryParamsFirst(a.attr("href")).get("query"));
            item.setVolumesearch(volumesearch);
        }
    }

    return item;
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceTest.java

@Override
protected void prepare_getOutputStream_NOK_ResourceIsDirectory(URI href) throws Exception {
    List<DavResource> davResources = Lists.newArrayList(createDavResourceFrom(OwncloudTestResourceImpl.builder()
            .href(href).mediaType(OwncloudUtils.getDirectoryMediaType()).build(), Locale.GERMAN));
    Mockito.when(sardine.list(getResourcePath(href), 0)).thenReturn(davResources);
}

From source file:org.apache.sling.i18n.it.ResourceBundleProviderIT.java

private void assertMessages(final String key, final String deMessage, final String deDeMessage,
        final String frMessage) {
    new Retry(RETRY_TIMEOUT_MSEC) {
        @Override// ww w. ja va  2  s. co m
        protected void exec() {
            {
                final ResourceBundle deDE = resourceBundleProvider.getResourceBundle(Locale.GERMANY); // this is the resource bundle for de_DE
                assertNotNull(deDE);
                assertEquals(deDeMessage, deDE.getString(key));
            }
            {
                final ResourceBundle de = resourceBundleProvider.getResourceBundle(Locale.GERMAN);
                assertNotNull(de);
                assertEquals(deMessage, de.getString(key));
            }
            {
                final ResourceBundle fr = resourceBundleProvider.getResourceBundle(Locale.FRENCH);
                assertNotNull(fr);
                assertEquals(frMessage, fr.getString(key));
            }
        }
    };
}

From source file:de.geeksfactory.opacclient.apis.Bibliotheca.java

protected SearchRequestResult parse_search(String html, int page) {
    Document doc = Jsoup.parse(html);
    doc.setBaseUri(opac_url);/*from  ww  w .  j a  v a2s  . c  o  m*/
    Elements table = doc.select(".resulttab tr.result_trefferX, .resulttab tr.result_treffer");
    List<SearchResult> results = new ArrayList<>();
    for (int i = 0; i < table.size(); i++) {
        Element tr = table.get(i);
        SearchResult sr = new SearchResult();
        int contentindex = 1;
        if (tr.select("td a img").size() > 0) {
            String[] fparts = tr.select("td a img").get(0).attr("src").split("/");
            String fname = fparts[fparts.length - 1];
            if (data.has("mediatypes")) {
                try {
                    sr.setType(MediaType.valueOf(data.getJSONObject("mediatypes").getString(fname)));
                } catch (JSONException | IllegalArgumentException e) {
                    sr.setType(defaulttypes.get(fname.toLowerCase(Locale.GERMAN).replace(".jpg", "")
                            .replace(".gif", "").replace(".png", "")));
                }
            } else {
                sr.setType(defaulttypes.get(fname.toLowerCase(Locale.GERMAN).replace(".jpg", "")
                        .replace(".gif", "").replace(".png", "")));
            }
        } else {
            if (tr.children().size() == 3) {
                contentindex = 2;
            }
        }
        sr.setInnerhtml(tr.child(contentindex).child(0).html());

        sr.setNr(i);
        Element link = tr.child(contentindex).select("a").first();
        try {
            if (link != null && link.attr("href").contains("detmediennr")) {
                Map<String, String> params = getQueryParamsFirst(link.attr("abs:href"));
                String nr = params.get("detmediennr");
                if (Integer.parseInt(nr) > i + 1) {
                    // Seems to be an ID
                    if (params.get("detDB") != null) {
                        sr.setId("&detmediennr=" + nr + "&detDB=" + params.get("detDB"));
                    } else {
                        sr.setId("&detmediennr=" + nr);
                    }
                }
            }
        } catch (Exception e) {
        }
        try {
            if (tr.child(1).childNode(0) instanceof Comment) {
                Comment c = (Comment) tr.child(1).childNode(0);
                String comment = c.getData().trim();
                String id = comment.split(": ")[1];
                sr.setId(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        results.add(sr);
    }
    int results_total = -1;
    if (doc.select(".result_gefunden").size() > 0) {
        try {
            results_total = Integer.parseInt(
                    doc.select(".result_gefunden").text().trim().replaceAll(".*[^0-9]+([0-9]+).*", "$1"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
            results_total = -1;
        }
    }
    return new SearchRequestResult(results, results_total, page);
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

public PrivilegeEnum mapToPrivilege(Attributes attributes, String attributeName) {
    Attribute attributeValue = null;
    PrivilegeEnum privilege = null;//  w  w  w.j a  v  a 2  s  .  c  o  m
    if (attributes != null && (attributeValue = attributes.get(attributeName)) != null) {
        try {
            String attributeString = String.valueOf(attributeValue.get()).toLowerCase(Locale.GERMAN);
            try {
                privilege = PrivilegeEnum.valueOf(attributeString.substring(4).toUpperCase(Locale.GERMAN));
            } catch (IllegalArgumentException iae) {
                LOG.log(Level.WARNING, "Name: {0}={1} - no such privilege",
                        new Object[] { attributeName, attributeString });
            }
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, "Can't convert LDAP Group " + attributeValue + " to DDB Privilege.",
                    ne.getMessage());
        }
    }
    return privilege;
}

From source file:org.opencms.workplace.help.CmsHelpTemplateBean.java

/**
 * Returns the HTML for the body frame of the online help.<p>
 * //from  w w  w . j  a va2s.  c  o m
 * @return the HTML for the body frame of the online help 
 */
public String displayBody() {

    StringBuffer result = new StringBuffer(256);

    // change to online project to allow static export 
    try {
        getJsp().getRequestContext().setCurrentProject(m_onlineProject);
        result.append(buildHtmlHelpStart("onlinehelp.css", true));
        result.append("<body>\n");
        result.append("<a name=\"top\"></a>\n");
        result.append("<table class=\"helpcontent\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n");
        result.append("<tr>\n");
        result.append("\t<td class=\"helpnav\">\n");
        result.append(
                "\t\t<a class=\"navhelphead\" href=\"javascript:top.body.location.href=top.head.homeLink;\">");
        result.append(key(Messages.GUI_HELP_NAVIGATION_HEAD_0));
        result.append("</a>\n");
        result.append(buildHtmlHelpNavigation());
        result.append("</td>\n");
        result.append("\t<td class=\"helpcontent\">\n");
        result.append("\t\t<h1>");
        result.append(getJsp().property(CmsPropertyDefinition.PROPERTY_TITLE, getParamHelpresource(),
                key(Messages.GUI_HELP_FRAMESET_TITLE_0)));
        result.append("</h1>\n");
        // print navigation if property template-elements is set to sitemap
        result.append(getJsp().getContent(getParamHelpresource(), "body", getLocale()));
        try {
            // additionally allow appending content of dynamic pages whose path may be specified 
            // as value of property PROPERTY_TEMPLATE_ELEMENTS (currently sitemap.jsp and search.jsp are used)
            CmsProperty elements = getCms().readPropertyObject(getParamHelpresource(),
                    CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS, false);
            if (!elements.isNullProperty()) {
                try {
                    // trigger an exception here as getContent won't throw anything!
                    getJsp().getCmsObject().readFile(elements.getValue());
                    // Ok, ressource exists: switsch from the online project to turn of static export links. 
                    String elementName = elements.getValue();
                    // check, wether the "dynamic resource" wants to be exported or not:
                    boolean export = false;
                    CmsProperty exportProp = getCms().readPropertyObject(elementName,
                            CmsPropertyDefinition.PROPERTY_EXPORT, true);

                    if (!exportProp.isNullProperty()) {
                        export = Boolean.valueOf(exportProp.getValue(CmsStringUtil.FALSE)).booleanValue();
                    }
                    if (!export) {
                        // switch back from online project to avoid export:
                        getJsp().getRequestContext().setCurrentProject(m_offlineProject);
                    }
                    result.append(getJsp().getContent(elements.getValue()));

                } catch (Throwable t) {
                    CmsVfsResourceNotFoundException e2 = new CmsVfsResourceNotFoundException(Messages.get()
                            .container(Messages.GUI_HELP_ERR_CONTENT_APPEND_2, this.getParamHelpresource(),
                                    elements.getValue(), CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS),
                            t);
                    throw e2;
                }
            }
        } catch (CmsException e1) {

            if (LOG.isErrorEnabled()) {
                LOG.error(e1);
            }
            result.append("<br>\n<div class=\"dialogerror\">");
            // getLocale() does not work in this context!?!
            result.append(e1.getMessageContainer().key(Locale.GERMAN));
            result.append("</div>");
        }
        result.append("\t</td>\n");
        result.append("</tr>\n");
        result.append("</table>\n");
        result.append(buildHtmlHelpEnd());
        return result.toString();
    } finally {
        getJsp().getRequestContext().setCurrentProject(m_offlineProject);
    }
}

From source file:de.geeksfactory.opacclient.apis.TouchPoint.java

protected SearchRequestResult parse_search(String html, int page) throws OpacErrorException, IOException {
    Document doc = Jsoup.parse(html);

    if (doc.select("#RefineHitListForm").size() > 0) {
        // the results are located on a different page loaded via AJAX
        html = httpGet(opac_url + "/speedHitList.do?_=" + String.valueOf(System.currentTimeMillis() / 1000)
                + "&hitlistindex=0&exclusionList=", ENCODING);
        doc = Jsoup.parse(html);// w w  w .  jav  a2s. c om
    }

    if (doc.select(".nodata").size() > 0) {
        return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, 1);
    }

    doc.setBaseUri(opac_url + "/searchfoo");

    int results_total = -1;

    String resultnumstr = doc.select(".box-header h2").first().text();
    if (resultnumstr.contains("(1/1)") || resultnumstr.contains(" 1/1")) {
        reusehtml = html;
        throw new OpacErrorException("is_a_redirect");
    } else if (resultnumstr.contains("(")) {
        results_total = Integer.parseInt(resultnumstr.replaceAll(".*\\(([0-9]+)\\).*", "$1"));
    } else if (resultnumstr.contains(": ")) {
        results_total = Integer.parseInt(resultnumstr.replaceAll(".*: ([0-9]+)$", "$1"));
    }

    Elements table = doc.select("table.data > tbody > tr");
    identifier = null;

    Elements links = doc.select("table.data a");
    boolean haslink = false;
    for (Element node : links) {
        if (node.hasAttr("href") & node.attr("href").contains("singleHit.do") && !haslink) {
            haslink = true;
            try {
                List<NameValuePair> anyurl = URLEncodedUtils
                        .parse(new URI(node.attr("href").replace(" ", "%20").replace("&amp;", "&")), ENCODING);
                for (NameValuePair nv : anyurl) {
                    if (nv.getName().equals("identifier")) {
                        identifier = nv.getValue();
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    List<SearchResult> results = new ArrayList<>();
    for (int i = 0; i < table.size(); i++) {
        Element tr = table.get(i);
        SearchResult sr = new SearchResult();
        if (tr.select(".icn, img[width=32]").size() > 0) {
            String[] fparts = tr.select(".icn, img[width=32]").first().attr("src").split("/");
            String fname = fparts[fparts.length - 1];
            String changedFname = fname.toLowerCase(Locale.GERMAN).replace(".jpg", "").replace(".gif", "")
                    .replace(".png", "");

            // File names can look like this: "20_DVD_Video.gif"
            Pattern pattern = Pattern.compile("(\\d+)_.*");
            Matcher matcher = pattern.matcher(changedFname);
            if (matcher.find()) {
                changedFname = matcher.group(1);
            }

            MediaType defaulttype = defaulttypes.get(changedFname);
            if (data.has("mediatypes")) {
                try {
                    sr.setType(MediaType.valueOf(data.getJSONObject("mediatypes").getString(fname)));
                } catch (JSONException | IllegalArgumentException e) {
                    sr.setType(defaulttype);
                }
            } else {
                sr.setType(defaulttype);
            }
        }
        String title;
        String text;
        if (tr.select(".results table").size() > 0) { // e.g. RWTH Aachen
            title = tr.select(".title a").text();
            text = tr.select(".title div").text();
        } else { // e.g. Schaffhausen, BSB Mnchen
            title = tr.select(".title, .hitlistTitle").text();
            text = tr.select(".results, .hitlistMetadata").first().ownText();
        }

        // we need to do some evil javascript parsing here to get the cover
        // and loan status of the item

        // get cover
        if (tr.select(".cover script").size() > 0) {
            String js = tr.select(".cover script").first().html();
            String isbn = matchJSVariable(js, "isbn");
            String ajaxUrl = matchJSVariable(js, "ajaxUrl");
            if (!"".equals(isbn) && !"".equals(ajaxUrl)) {
                String url = new URL(new URL(opac_url + "/"), ajaxUrl).toString();
                String coverUrl = httpGet(url + "?isbn=" + isbn + "&size=small", ENCODING);
                if (!"".equals(coverUrl)) {
                    sr.setCover(coverUrl.replace("\r\n", "").trim());
                }
            }
        }
        // get loan status and media ID
        if (tr.select("div[id^=loanstatus] + script").size() > 0) {
            String js = tr.select("div[id^=loanstatus] + script").first().html();
            String[] variables = new String[] { "loanstateDBId", "itemIdentifier", "hitlistIdentifier",
                    "hitlistPosition", "duplicateHitlistIdentifier", "itemType", "titleStatus", "typeofHit",
                    "context" };
            String ajaxUrl = matchJSVariable(js, "ajaxUrl");
            if (!"".equals(ajaxUrl)) {
                JSONObject id = new JSONObject();
                List<NameValuePair> map = new ArrayList<>();
                for (String variable : variables) {
                    String value = matchJSVariable(js, variable);
                    if (!"".equals(value)) {
                        map.add(new BasicNameValuePair(variable, value));
                    }
                    try {
                        if (variable.equals("itemIdentifier")) {
                            id.put("id", value);
                        } else if (variable.equals("loanstateDBId")) {
                            id.put("db", value);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                sr.setId(id.toString());
                String url = new URL(new URL(opac_url + "/"), ajaxUrl).toString();
                String loanStatusHtml = httpGet(url + "?" + URLEncodedUtils.format(map, "UTF-8"), ENCODING)
                        .replace("\r\n", "").trim();
                Document loanStatusDoc = Jsoup.parse(loanStatusHtml);
                String loanstatus = loanStatusDoc.text().replace("\u00bb", "").trim();

                if ((loanstatus.startsWith("entliehen") && loanstatus.contains("keine Vormerkung mglich")
                        || loanstatus.contains("Keine Exemplare verfgbar"))) {
                    sr.setStatus(SearchResult.Status.RED);
                } else if (loanstatus.startsWith("entliehen") || loanstatus.contains("andere Zweigstelle")) {
                    sr.setStatus(SearchResult.Status.YELLOW);
                } else if ((loanstatus.startsWith("bestellbar") && !loanstatus.contains("nicht bestellbar"))
                        || (loanstatus.startsWith("vorbestellbar")
                                && !loanstatus.contains("nicht vorbestellbar"))
                        || (loanstatus.startsWith("vorbestellbar")
                                && !loanstatus.contains("nicht vorbestellbar"))
                        || (loanstatus.startsWith("vormerkbar") && !loanstatus.contains("nicht vormerkbar"))
                        || (loanstatus.contains("heute zurckgebucht"))
                        || (loanstatus.contains("ausleihbar") && !loanstatus.contains("nicht ausleihbar"))) {
                    sr.setStatus(SearchResult.Status.GREEN);
                }
                if (sr.getType() != null) {
                    if (sr.getType().equals(MediaType.EBOOK) || sr.getType().equals(MediaType.EVIDEO)
                            || sr.getType().equals(MediaType.MP3))
                    // Especially Onleihe.de ebooks are often marked
                    // green though they are not available.
                    {
                        sr.setStatus(SearchResult.Status.UNKNOWN);
                    }
                }
            }
        }

        sr.setInnerhtml(("<b>" + title + "</b><br/>") + text);

        sr.setNr(10 * (page - 1) + i + 1);
        results.add(sr);
    }
    resultcount = results.size();
    return new SearchRequestResult(results, results_total, page);
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceTest.java

@Override
protected void prepare_getOutputStream_OK_OverwriteFile(URI href, MediaType mediaType, String testFileContent)
        throws Exception {
    List<DavResource> davResources = Lists.newArrayList(createDavResourceFrom(OwncloudTestFileResourceImpl
            .fileBuilder()/*from w  w w. j  a  v  a 2s  .  c o  m*/
            .owncloudResource(OwncloudTestResourceImpl.builder().href(href).mediaType(mediaType).build())
            .testFileContent(testFileContent).build(), Locale.GERMAN));
    Mockito.when(sardine.list(getResourcePath(href))).thenReturn(davResources);
    mockServer.expect(requestToWithPrefix(href)).andExpect(method(HttpMethod.PUT))
            .andExpect(header(HttpHeaders.AUTHORIZATION, getBasicAuthorizationHeader()))
            .andExpect(header(HttpHeaders.CONNECTION, "keep-alive")).andExpect(content().contentType(mediaType))
            .andExpect(content().string(testFileContent)).andRespond(withSuccess());
}