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:com.sos.jitl.jasperreports.JobSchedulerJasperReportJob.java

/**
 * process report/*w  w w  .  ja v a 2 s.  c  o m*/
 */
public boolean spooler_process() {

    //Order order = null;
    //Variable_set orderData = null;
    order = null;
    orderData = null;

    File settingsFile = null;
    File reportFile = null;
    File queryFile = null;
    File currQueryFile = null;
    File queryStatementFile = null;
    File outputFile = null;
    File parameterQueryFile = null;
    String stateText = "";
    String tmpOutputFileWithoutExtension = ""; //hilfsvariable
    SOSConnectionFileProcessor queryProcessor = null;

    try {
        spooler_log.debug3("******************spooler_process*****************************");
        this.prepareParams();

        listOfOutputFilename = new ArrayList();
        this.setSettingsFilename("");
        this.setReportFilename("");
        this.setQueryFilename("");
        this.setOutputType("pdf");
        this.setOutputFilename("");
        this.setQueryStatement("");

        //         get job parameters from job configuration (scheduler.xml)
        this.getJobParameters();
        //         to fetch parameters from orders that have precedence to job parameters
        this.getOrderParameters();
        //         to check report parameters
        checkParams();

        try { // to process report

            reportFile = new File(this.getReportFilename());
            if (!reportFile.exists())
                throw new Exception("report file does not exist: " + reportFile.getCanonicalPath());

            filledReportFile = File.createTempFile("sos", ".tmp");
            filledReportFile.deleteOnExit();

            queryFile = new File(this.getQueryFilename());

            outputFile = null;
            if (this.getOutputFilename() != null && this.getOutputFilename().length() > 0) {
                String outputFile_ = maskFilename(this.getOutputFilename());
                outputFile = new File(outputFile_);
            } else {
                outputFile = File.createTempFile("sos", ".tmp");
                outputFile.deleteOnExit();
            }

            //eventuell vorhandene alte Berichte lschen
            if (this.isDeleteOldFilename()) {
                if (outputFile.exists()) {
                    spooler_log.debug3("..deleting old File " + outputFile.getCanonicalPath());
                    if (!outputFile.delete()) {
                        spooler_log.warn("..could not delete old File " + outputFile.getCanonicalPath());
                    } else {
                        spooler_log.debug3("..successfully delete old File " + outputFile.getCanonicalPath());
                    }
                }
            }

            if (this.getSettingsFilename() != null && this.getSettingsFilename().length() > 0) {
                settingsFile = new File(this.getSettingsFilename());
                if (!settingsFile.exists())
                    throw new Exception("settings file does not exist: " + settingsFile.getCanonicalPath());
                queryProcessor = new SOSConnectionFileProcessor(settingsFile.getCanonicalPath(),
                        new sos.util.SOSSchedulerLogger(spooler_log));
            } else {
                if (this.getConnection() == null)
                    throw new Exception("job scheduler runs without database");
                queryProcessor = new SOSConnectionFileProcessor(this.getConnection(),
                        new sos.util.SOSSchedulerLogger(spooler_log));
            }

            //alle Jobparametern werden den jasperreport bergeben
            Map parameters = new HashMap();
            Variable_set params = spooler_task.params();

            if (orderData != null) {
                spooler_log.debug6(".......orderDatanames: " + orderData.names());
                java.util.StringTokenizer tokenizero = new java.util.StringTokenizer(orderData.names(), ";");
                while (tokenizero.hasMoreTokens()) {
                    String name = tokenizero.nextToken();
                    parameters.put(name, orderData.var(name));
                    spooler_log.debug6(".......orderData: " + name + "=" + orderData.var(name));
                }
            }

            spooler_log.debug6(".......paramsnames: " + params.names());
            java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(params.names(), ";");
            while (tokenizer.hasMoreTokens()) {
                String name = tokenizer.nextToken();
                parameters.put(name, params.var(name));
                spooler_log.debug6(".......jobparameter: " + name + "=" + params.var(name));
            }

            //Ausfhren der sql-script und das Ergebnis den Jasperreport als Parameter bergeben
            if (sosString.parseToString(parameterQueryFilename).length() > 0) {
                parameterQueryFile = new File(this.parameterQueryFilename);
                if (parameterQueryFile.exists()) {
                    queryProcessor.process(parameterQueryFile);
                    try {
                        parameters.putAll(queryProcessor.getConnection().get());
                    } catch (Exception e) {
                        spooler_log.warn(
                                "..error while get Resultset from query Processor Connection: " + e.toString());
                    }
                } else {
                    spooler_log.warn(".." + parameterQueryFilename + " not exists");
                }
            }

            if (sosString.parseToString(parameters.get("report_locale")).length() > 0) {
                parameters.put(JRParameter.REPORT_LOCALE,
                        new Locale(sosString.parseToString(parameters.get("report_locale"))));
            } else {
                parameters.put(JRParameter.REPORT_LOCALE, Locale.GERMAN);
            }

            //Ausgaben aller Parametern, die den JasperReport bergeben werden
            Object[] param = parameters.entrySet().toArray();
            for (int i = 0; i < param.length; i++) {
                spooler_log.debug3("..report parameter " + param[i].toString());
            }

            //java.util.ResourceBundle.getBundle("com.sos.jitl.jasperreports.dod").toString();   
            //parameters.put(JRParameter.REPORT_RESOURCE_BUNDLE, java.util.ResourceBundle.getBundle("com.sos.jitl.jasperreports.dod").toString());

            if (sosString.parseToString(queryStatement).length() > 0) {
                queryStatementFile = this.decodeBase64(this.queryStatement);
                this.spooler_log.debug3("queryStatementFile: " + queryStatementFile);
                if (queryStatementFile.exists()) {
                    queryProcessor.process(queryStatementFile);
                }
            }

            //existiert ein queryfile, dann wird das Ergebnis der Queryfile ohne Connection den jasperreport bergeben
            //Vorher werden alle Platzhalter in der query_filname ersetzt mit Parameter
            if (queryFile.exists()) {
                //queryProcessor.process(queryFile);
                //               Paltzhalter in der query_filename parsieren
                SOSPlainTextProcessor processor_ = new SOSPlainTextProcessor();
                //File currQueryFile = File.createTempFile("temp", ".sql", queryFile.getParentFile());
                currQueryFile = processor_.process(queryFile, (HashMap) parameters);
                currQueryFile.deleteOnExit();
                queryProcessor.process(currQueryFile);

                this.spooler_log.debug5("query " + processor_.getDocumentContent());
            }

            if (queryFile.exists() || (queryStatementFile != null && queryStatementFile.exists())) {
                JasperFillManager.fillReportToFile(reportFile.getCanonicalPath(),
                        filledReportFile.getCanonicalPath(), parameters,
                        new JRResultSetDataSource(queryProcessor.getConnection().getResultSet()));
            } else {
                JasperFillManager.fillReportToFile(reportFile.getCanonicalPath(),
                        filledReportFile.getCanonicalPath(), parameters,
                        queryProcessor.getConnection().getConnection());
            }

            tmpOutputFileWithoutExtension = outputFile.getCanonicalPath().substring(0,
                    outputFile.getCanonicalPath().lastIndexOf(".")) + ".";

            if (getOutputType().indexOf("pdf") > -1) {
                outputFile = new File(tmpOutputFileWithoutExtension + "pdf");
                JasperExportManager.exportReportToPdfFile(filledReportFile.getCanonicalPath(),
                        outputFile.getCanonicalPath());
                listOfOutputFilename.add(outputFile);
            }

            if (getOutputType().indexOf("htm") > -1 || getOutputType().indexOf("html") > -1) {
                if (getOutputType().indexOf("html") > -1)
                    outputFile = new File(tmpOutputFileWithoutExtension + "html");
                else
                    outputFile = new File(tmpOutputFileWithoutExtension + "htm");
                // JasperExportManager.exportReportToHtmlFile(filledReportFile.getCanonicalPath(), outputFile.getCanonicalPath());
                JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(filledReportFile);
                JRHtmlExporter exporter = new JRHtmlExporter();
                exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
                exporter.setParameter(JRHtmlExporterParameter.OUTPUT_FILE_NAME, outputFile.getCanonicalPath());
                exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
                exporter.exportReport();
                listOfOutputFilename.add(outputFile);
            }

            if (this.getOutputType().indexOf("xml") > -1) {
                outputFile = new File(tmpOutputFileWithoutExtension + "xml");
                JasperExportManager.exportReportToXmlFile(filledReportFile.getCanonicalPath(),
                        outputFile.getCanonicalPath(), true);
                listOfOutputFilename.add(outputFile);
            }

            if (this.getOutputType().indexOf("xls") > -1) {
                outputFile = new File(tmpOutputFileWithoutExtension + "xls");
                JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(filledReportFile);
                JRXlsExporter exporter = new JRXlsExporter();
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outputFile.getCanonicalPath());
                exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
                exporter.exportReport();
                listOfOutputFilename.add(outputFile);
            }

            if (this.getOutputType().indexOf("rtf") > -1) {
                outputFile = new File(tmpOutputFileWithoutExtension + "rtf");
                JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(filledReportFile);
                JRRtfExporter exporter = new JRRtfExporter();
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outputFile.getCanonicalPath());
                exporter.exportReport();
                listOfOutputFilename.add(outputFile);
            }

            stateText = printDocument();

            stateText = stateText + "..report generated in output file: " + tmpOutputFileWithoutExtension + "["
                    + getOutputType() + "] " + stateText;

            stateText = sendEmail(stateText);

            spooler_log.info(stateText);

            spooler_job.set_state_text(stateText);

        } catch (Exception e) {
            throw new Exception("error occurred processing report: " + e);
        }

        try { // to fetch parameters from orders that have precedence to job parameters
            if (spooler_task.job().order_queue() != null) {
                order = spooler_task.order();

                // create response for web service request
                if (order.web_service_operation_or_null() != null) {
                    Web_service_response response = order.web_service_operation().response();

                    if (this.getOutputFilename() != null && this.getOutputFilename().length() > 0) {
                        // return SOAP response
                        // should the response be previously transformed ...
                        if (order.web_service().params().var("response_stylesheet") != null
                                && order.web_service().params().var("response_stylesheet").length() > 0) {
                            Xslt_stylesheet stylesheet = spooler.create_xslt_stylesheet();
                            stylesheet.load_file(order.web_service().params().var("response_stylesheet"));
                            String xml_document = stylesheet.apply_xml(order.xml());
                            spooler_log.debug3("content of response transformation:/n" + xml_document);
                            response.set_string_content(xml_document);
                        } else {
                            response.set_string_content(order.xml());
                        }
                    } else {
                        // return binary content
                        BufferedInputStream in = new BufferedInputStream(new FileInputStream(outputFile));
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        byte buffer[] = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                        order.web_service_operation().response().set_binary_content(out.toByteArray());
                    }

                    response.send();
                    spooler_log.debug3(
                            "web service response successfully processed for order \"" + order.id() + "\"");
                }
            }
        } catch (Exception e) {
            throw new Exception("error occurred processing web service response: " + e.getMessage());
        }

        if (filledReportFile != null && filledReportFile.exists())
            spooler_log.debug5(
                    "..delete " + filledReportFile.getCanonicalPath() + ": " + filledReportFile.delete());

        if (currQueryFile != null && currQueryFile.exists())
            spooler_log.debug5("delete " + currQueryFile.getCanonicalPath() + ": " + currQueryFile.delete());

        // return value for classic and order driven processing
        return (spooler_task.job().order_queue() != null);

    } catch (Exception e) {
        spooler_job.set_state_text(e.getMessage());
        try {
            if (filledReportFile != null && filledReportFile.exists())
                spooler_log.debug("could delete " + filledReportFile.getCanonicalPath() + ": "
                        + filledReportFile.delete());
        } catch (Exception se) {
        }
        spooler_log.warn(e.getMessage());
        return false;
    } finally {

    }
}

From source file:de.bogutzky.psychophysiocollector.app.MainActivity.java

private void createRootDirectory() {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.GERMAN);
    SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("HH-mm-ss", Locale.GERMAN);
    String dateString = simpleDateFormat.format(this.startTimestamp);
    String timeString = simpleTimeFormat.format(this.startTimestamp);
    if (activityName.equals(""))
        activityName = getString(R.string.settings_undefined);
    if (participantLastName.equals(""))
        participantLastName = getString(R.string.settings_undefined);
    if (participantFirstName.equals(""))
        participantFirstName = getString(R.string.settings_undefined);
    this.directoryName = "PsychoPhysioCollector/" + activityName.toLowerCase() + "/"
            + participantLastName.toLowerCase() + "-" + participantFirstName.toLowerCase() + "/" + dateString
            + "--" + timeString;
    this.root = getStorageDirectory(this.directoryName);
}

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

protected DetailledItem parse_result(Document doc) {
    DetailledItem item = new DetailledItem();

    // Title and Subtitle
    item.setTitle(doc.select("span[id$=LblShortDescriptionValue]").text());
    String subtitle = doc.select("span[id$=LblSubTitleValue]").text();
    if (!subtitle.equals("")) {
        item.addDetail(new Detail(stringProvider.getString(StringProvider.SUBTITLE), subtitle));
    }/* w  ww .  ja v a 2  s.  c  o  m*/

    // Cover
    if (doc.select("input[id$=mediumImage]").size() > 0) {
        item.setCover(doc.select("input[id$=mediumImage]").attr("src"));
    } else if (doc.select("img[id$=CoverView_Image]").size() > 0) {
        item.setCover(getCoverUrl(doc.select("img[id$=CoverView_Image]").first()));
    }

    // ID
    item.setId(doc.select("input[id$=regionmednr]").val());

    // Description
    if (doc.select("span[id$=ucCatalogueContent_LblAnnotation]").size() > 0) {
        String name = doc.select("span[id$=lblCatalogueContent]").text();
        String value = doc.select("span[id$=ucCatalogueContent_LblAnnotation]").text();
        item.addDetail(new Detail(name, value));
    }
    // Details
    for (Element detail : doc.select("div[id$=CatalogueDetailView] .spacingBottomSmall:has(span+span)")) {
        String name = detail.select("span").get(0).text().replace(": ", "");
        String value = detail.select("span").get(1).text();
        item.addDetail(new Detail(name, value));
    }

    // Copies
    Element table = doc.select("table[id$=grdViewMediumCopies]").first();
    Elements trs = table.select("tr");
    List<String> columnmap = new ArrayList<>();
    for (Element th : trs.first().select("th")) {
        columnmap.add(getCopyColumnKey(th.text()));
    }

    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN);
    for (int i = 1; i < trs.size(); i++) {
        Elements tds = trs.get(i).select("td");
        Copy copy = new Copy();
        for (int j = 0; j < tds.size(); j++) {
            if (columnmap.get(j) == null)
                continue;
            String text = tds.get(j).text().replace("\u00a0", "");
            if (text.equals(""))
                continue;
            copy.set(columnmap.get(j), text, fmt);
        }
        item.addCopy(copy);
    }

    return item;
}

From source file:org.yccheok.jstock.gui.PortfolioManagementJPanel.java

public boolean openAsStatements(Statements statements, File file) {
    assert (statements != null);

    if (statements.getType() == Statement.Type.PortfolioManagementBuy
            || statements.getType() == Statement.Type.PortfolioManagementSell
            || statements.getType() == Statement.Type.PortfolioManagementDeposit
            || statements.getType() == Statement.Type.PortfolioManagementDividend) {
        final GUIBundleWrapper guiBundleWrapper = statements.getGUIBundleWrapper();
        // We will use a fixed date format (Locale.English), so that it will be
        // easier for Android to process.
        ////w  w  w.jav  a2s. co m
        // "Sep 5, 2011"    -   Locale.ENGLISH
        // "2011-9-5"       -   Locale.SIMPLIFIED_CHINESE
        // "2011/9/5"       -   Locale.TRADITIONAL_CHINESE
        // 05.09.2011       -   Locale.GERMAN
        //
        // However, for backward compatible purpose (Able to read old CSV),
        // we perform a for loop to determine the best date format.
        DateFormat dateFormat = null;
        final int size = statements.size();
        switch (statements.getType()) {
        case PortfolioManagementBuy: {
            final List<Transaction> transactions = new ArrayList<Transaction>();

            for (int i = 0; i < size; i++) {
                final Statement statement = statements.get(i);
                final String _code = statement.getValueAsString(guiBundleWrapper.getString("MainFrame_Code"));
                final String _symbol = statement
                        .getValueAsString(guiBundleWrapper.getString("MainFrame_Symbol"));
                final String _date = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Date"));
                final Double units = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Units"));
                final Double purchasePrice = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchasePrice"));
                final Double broker = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Broker"));
                final Double clearingFee = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_ClearingFee"));
                final Double stampDuty = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_StampDuty"));
                final String _comment = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Comment"));

                Stock stock = null;
                if (_code.length() > 0 && _symbol.length() > 0) {
                    stock = org.yccheok.jstock.engine.Utils.getEmptyStock(Code.newInstance(_code),
                            Symbol.newInstance(_symbol));
                } else {
                    log.error("Unexpected empty stock. Ignore");
                    // stock is null.
                    continue;
                }
                Date date = null;

                if (dateFormat == null) {
                    // However, for backward compatible purpose (Able to read old CSV),
                    // we perform a for loop to determine the best date format.
                    // For the latest CSV, it should be Locale.ENGLISH.
                    Locale[] locales = { Locale.ENGLISH, Locale.SIMPLIFIED_CHINESE, Locale.GERMAN,
                            Locale.TRADITIONAL_CHINESE, Locale.ITALIAN };
                    for (Locale locale : locales) {
                        dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
                        try {
                            date = dateFormat.parse((String) _date);
                        } catch (ParseException exp) {
                            log.error(null, exp);
                            date = null;
                            dateFormat = null;
                            continue;
                        }
                        // We had found our best dateFormat. Early break.
                        break;
                    }
                } else {
                    // We already determine our best dateFormat.
                    try {
                        date = dateFormat.parse((String) _date);
                    } catch (ParseException exp) {
                        log.error(null, exp);
                    }
                }

                if (date == null) {
                    log.error("Unexpected wrong date. Ignore");
                    continue;
                }

                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (units == null) {
                    log.error("Unexpected wrong units. Ignore");
                    continue;
                }
                if (purchasePrice == null || broker == null || clearingFee == null || stampDuty == null) {
                    log.error("Unexpected wrong purchasePrice/broker/clearingFee/stampDuty. Ignore");
                    continue;
                }

                final SimpleDate simpleDate = new SimpleDate(date);
                final Contract.Type type = Contract.Type.Buy;
                final Contract.ContractBuilder builder = new Contract.ContractBuilder(stock, simpleDate);
                final Contract contract = builder.type(type).quantity(units).price(purchasePrice).build();
                final Transaction t = new Transaction(contract, broker, stampDuty, clearingFee);
                t.setComment(org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(_comment));
                transactions.add(t);
            }

            // We allow empty portfolio.
            //if (transactions.size() <= 0) {
            //    return false;
            //}

            // Is there any exsiting displayed data?
            if (this.getBuyTransactionSize() > 0) {
                final String output = MessageFormat.format(
                        MessagesBundle.getString("question_message_load_file_for_buy_portfolio_template"),
                        file.getName());
                final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                        MessagesBundle.getString("question_title_load_file_for_buy_portfolio"),
                        javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result != javax.swing.JOptionPane.YES_OPTION) {
                    // Assume success.
                    return true;
                }
            }

            this.buyTreeTable.setTreeTableModel(new BuyPortfolioTreeTableModelEx());
            final BuyPortfolioTreeTableModelEx buyPortfolioTreeTableModel = (BuyPortfolioTreeTableModelEx) buyTreeTable
                    .getTreeTableModel();
            buyPortfolioTreeTableModel.bind(this.portfolioRealTimeInfo);
            buyPortfolioTreeTableModel.bind(this);

            Map<String, String> metadatas = statements.getMetadatas();
            for (Transaction transaction : transactions) {
                final Code code = transaction.getStock().code;
                TransactionSummary transactionSummary = this.addBuyTransaction(transaction);
                if (transactionSummary != null) {
                    String comment = metadatas.get(code.toString());
                    if (comment != null) {
                        transactionSummary.setComment(
                                org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(comment));
                    }
                }
            }

            // Only shows necessary columns.
            initGUIOptions();

            expandTreeTable(buyTreeTable);

            updateRealTimeStockMonitorAccordingToPortfolioTreeTableModels();
            updateExchangeRateMonitorAccordingToPortfolioTreeTableModels();

            // updateWealthHeader will be called at end of switch.

            refreshStatusBarExchangeRateVisibility();
        }
            break;

        case PortfolioManagementSell: {
            final List<Transaction> transactions = new ArrayList<Transaction>();

            for (int i = 0; i < size; i++) {
                final Statement statement = statements.get(i);
                final String _code = statement.getValueAsString(guiBundleWrapper.getString("MainFrame_Code"));
                final String _symbol = statement
                        .getValueAsString(guiBundleWrapper.getString("MainFrame_Symbol"));
                final String _referenceDate = statement.getValueAsString(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_ReferenceDate"));

                // Legacy file handling. PortfolioManagementJPanel_PurchaseBroker, PortfolioManagementJPanel_PurchaseClearingFee,
                // and PortfolioManagementJPanel_PurchaseStampDuty are introduced starting from 1.0.6x
                Double purchaseBroker = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchaseBroker"));
                if (purchaseBroker == null) {
                    // Legacy file handling. PortfolioManagementJPanel_PurchaseFee is introduced starting from 1.0.6s
                    purchaseBroker = statement.getValueAsDouble(
                            guiBundleWrapper.getString("PortfolioManagementJPanel_PurchaseFee"));
                    if (purchaseBroker == null) {
                        purchaseBroker = new Double(0.0);
                    }
                }
                Double purchaseClearingFee = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchaseClearingFee"));
                if (purchaseClearingFee == null) {
                    purchaseClearingFee = new Double(0.0);
                }
                Double purchaseStampDuty = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchaseStampDuty"));
                if (purchaseStampDuty == null) {
                    purchaseStampDuty = new Double(0.0);

                }
                final String _date = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Date"));
                final Double units = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Units"));
                final Double sellingPrice = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_SellingPrice"));
                final Double purchasePrice = statement.getValueAsDouble(
                        guiBundleWrapper.getString("PortfolioManagementJPanel_PurchasePrice"));
                final Double broker = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Broker"));
                final Double clearingFee = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_ClearingFee"));
                final Double stampDuty = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_StampDuty"));
                final String _comment = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Comment"));

                Stock stock = null;
                if (_code.length() > 0 && _symbol.length() > 0) {
                    stock = org.yccheok.jstock.engine.Utils.getEmptyStock(Code.newInstance(_code),
                            Symbol.newInstance(_symbol));
                } else {
                    log.error("Unexpected empty stock. Ignore");
                    // stock is null.
                    continue;
                }

                Date date = null;
                Date referenceDate = null;

                if (dateFormat == null) {
                    // However, for backward compatible purpose (Able to read old CSV),
                    // we perform a for loop to determine the best date format.
                    // For the latest CSV, it should be Locale.ENGLISH.
                    Locale[] locales = { Locale.ENGLISH, Locale.SIMPLIFIED_CHINESE, Locale.GERMAN,
                            Locale.TRADITIONAL_CHINESE, Locale.ITALIAN };
                    for (Locale locale : locales) {
                        dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
                        try {
                            date = dateFormat.parse((String) _date);
                            referenceDate = dateFormat.parse((String) _referenceDate);
                        } catch (ParseException exp) {
                            log.error(null, exp);
                            date = null;
                            referenceDate = null;
                            dateFormat = null;
                            continue;
                        }
                        // We had found our best dateFormat. Early break.
                        break;
                    }
                } else {
                    // We already determine our best dateFormat.
                    try {
                        date = dateFormat.parse((String) _date);
                        referenceDate = dateFormat.parse((String) _referenceDate);
                    } catch (ParseException exp) {
                        log.error(null, exp);
                    }
                }

                if (date == null || referenceDate == null) {
                    log.error("Unexpected wrong date/referenceDate. Ignore");
                    continue;
                }
                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (units == null) {
                    log.error("Unexpected wrong units. Ignore");
                    continue;
                }
                if (purchasePrice == null || broker == null || clearingFee == null || stampDuty == null
                        || sellingPrice == null) {
                    log.error(
                            "Unexpected wrong purchasePrice/broker/clearingFee/stampDuty/sellingPrice. Ignore");
                    continue;
                }

                final SimpleDate simpleDate = new SimpleDate(date);
                final SimpleDate simpleReferenceDate = new SimpleDate(referenceDate);
                final Contract.Type type = Contract.Type.Sell;
                final Contract.ContractBuilder builder = new Contract.ContractBuilder(stock, simpleDate);
                final Contract contract = builder.type(type).quantity(units).price(sellingPrice)
                        .referencePrice(purchasePrice).referenceDate(simpleReferenceDate)
                        .referenceBroker(purchaseBroker).referenceClearingFee(purchaseClearingFee)
                        .referenceStampDuty(purchaseStampDuty).build();
                final Transaction t = new Transaction(contract, broker, stampDuty, clearingFee);
                t.setComment(org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(_comment));
                transactions.add(t);
            } // for

            // We allow empty portfolio.
            //if (transactions.size() <= 0) {
            //    return false;
            //}

            // Is there any exsiting displayed data?
            if (this.getSellTransactionSize() > 0) {
                final String output = MessageFormat.format(
                        MessagesBundle.getString("question_message_load_file_for_sell_portfolio_template"),
                        file.getName());
                final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                        MessagesBundle.getString("question_title_load_file_for_sell_portfolio"),
                        javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result != javax.swing.JOptionPane.YES_OPTION) {
                    // Assume success.
                    return true;
                }
            }

            this.sellTreeTable.setTreeTableModel(new SellPortfolioTreeTableModelEx());
            final SellPortfolioTreeTableModelEx sellPortfolioTreeTableModel = (SellPortfolioTreeTableModelEx) sellTreeTable
                    .getTreeTableModel();
            sellPortfolioTreeTableModel.bind(this.portfolioRealTimeInfo);
            sellPortfolioTreeTableModel.bind(this);

            Map<String, String> metadatas = statements.getMetadatas();

            for (Transaction transaction : transactions) {
                final Code code = transaction.getStock().code;
                TransactionSummary transactionSummary = this.addSellTransaction(transaction);
                if (transactionSummary != null) {
                    String comment = metadatas.get(code.toString());
                    if (comment != null) {
                        transactionSummary.setComment(
                                org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(comment));
                    }
                }
            }

            // Only shows necessary columns.
            initGUIOptions();

            expandTreeTable(this.sellTreeTable);

            updateExchangeRateMonitorAccordingToPortfolioTreeTableModels();

            // updateWealthHeader will be called at end of switch.

            refreshStatusBarExchangeRateVisibility();
        }
            break;

        case PortfolioManagementDeposit: {
            final List<Deposit> deposits = new ArrayList<Deposit>();

            for (int i = 0; i < size; i++) {
                Date date = null;
                final Statement statement = statements.get(i);
                final String object0 = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Date"));
                assert (object0 != null);

                if (dateFormat == null) {
                    // However, for backward compatible purpose (Able to read old CSV),
                    // we will perform a for loop to determine the best date format.
                    // For the latest CSV, it should be Locale.ENGLISH.
                    Locale[] locales = { Locale.ENGLISH, Locale.SIMPLIFIED_CHINESE, Locale.GERMAN,
                            Locale.TRADITIONAL_CHINESE, Locale.ITALIAN };
                    for (Locale locale : locales) {
                        dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
                        try {
                            date = dateFormat.parse(object0);
                        } catch (ParseException exp) {
                            log.error(null, exp);
                            date = null;
                            dateFormat = null;
                            continue;
                        }
                        // We had found our best dateFormat. Early break.
                        break;
                    }
                } else {
                    // We already determine our best dateFormat.
                    try {
                        date = dateFormat.parse(object0);
                    } catch (ParseException exp) {
                        log.error(null, exp);
                    }
                }

                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (date == null) {
                    log.error("Unexpected wrong date. Ignore");
                    continue;
                }
                final Double cash = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Cash"));
                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (cash == null) {
                    log.error("Unexpected wrong cash. Ignore");
                    continue;
                }
                final Deposit deposit = new Deposit(cash, new SimpleDate(date));

                final String comment = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Comment"));
                if (comment != null) {
                    // Possible to be null. As in version <=1.0.6p, comment
                    // is not being saved to CSV.
                    deposit.setComment(
                            org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(comment));
                }

                deposits.add(deposit);
            }

            // We allow empty portfolio.
            //if (deposits.size() <= 0) {
            //    return false;
            //}

            // Is there any exsiting displayed data?
            if (this.depositSummary.size() > 0) {
                final String output = MessageFormat.format(
                        MessagesBundle.getString("question_message_load_file_for_cash_deposit_template"),
                        file.getName());
                final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                        MessagesBundle.getString("question_title_load_file_for_cash_deposit"),
                        javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result != javax.swing.JOptionPane.YES_OPTION) {
                    // Assume success.
                    return true;
                }
            }

            this.depositSummary = new DepositSummary();

            for (Deposit deposit : deposits) {
                depositSummary.add(deposit);
            }
        }
            break;

        case PortfolioManagementDividend: {
            final List<Dividend> dividends = new ArrayList<Dividend>();

            for (int i = 0; i < size; i++) {
                Date date = null;
                StockInfo stockInfo = null;
                final Statement statement = statements.get(i);
                final String object0 = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Date"));
                assert (object0 != null);

                if (dateFormat == null) {
                    // However, for backward compatible purpose (Able to read old CSV),
                    // we will perform a for loop to determine the best date format.
                    // For the latest CSV, it should be Locale.ENGLISH.
                    Locale[] locales = { Locale.ENGLISH, Locale.SIMPLIFIED_CHINESE, Locale.GERMAN,
                            Locale.TRADITIONAL_CHINESE, Locale.ITALIAN };
                    for (Locale locale : locales) {
                        dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
                        try {
                            date = dateFormat.parse(object0);
                        } catch (ParseException exp) {
                            log.error(null, exp);
                            date = null;
                            dateFormat = null;
                            continue;
                        }
                        // We had found our best dateFormat. Early break.
                        break;
                    }
                } else {
                    // We already determine our best dateFormat.
                    try {
                        date = dateFormat.parse(object0);
                    } catch (ParseException exp) {
                        log.error(null, exp);
                    }
                }

                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (date == null) {
                    log.error("Unexpected wrong date. Ignore");
                    continue;
                }
                final Double dividend = statement
                        .getValueAsDouble(guiBundleWrapper.getString("PortfolioManagementJPanel_Dividend"));
                // Shall we continue to ignore, or shall we just return false to
                // flag an error?
                if (dividend == null) {
                    log.error("Unexpected wrong dividend. Ignore");
                    continue;
                }
                final String codeStr = statement.getValueAsString(guiBundleWrapper.getString("MainFrame_Code"));
                final String symbolStr = statement
                        .getValueAsString(guiBundleWrapper.getString("MainFrame_Symbol"));
                if (codeStr.isEmpty() == false && symbolStr.isEmpty() == false) {
                    stockInfo = StockInfo.newInstance(Code.newInstance(codeStr), Symbol.newInstance(symbolStr));
                } else {
                    log.error("Unexpected wrong stock. Ignore");
                    // stock is null.
                    continue;
                }

                assert (stockInfo != null);
                assert (dividend != null);
                assert (date != null);

                final Dividend d = new Dividend(stockInfo, dividend, new SimpleDate(date));

                final String comment = statement
                        .getValueAsString(guiBundleWrapper.getString("PortfolioManagementJPanel_Comment"));
                if (comment != null) {
                    // Possible to be null. As in version <=1.0.6p, comment
                    // is not being saved to CSV.
                    d.setComment(
                            org.yccheok.jstock.portfolio.Utils.replaceCSVLineFeedToSystemLineFeed(comment));
                }

                dividends.add(d);
            }

            // We allow empty portfolio.
            //if (dividends.size() <= 0) {
            //    return false;
            //}                    

            if (this.dividendSummary.size() > 0) {
                final String output = MessageFormat.format(
                        MessagesBundle.getString("question_message_load_file_for_dividend_template"),
                        file.getName());
                final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                        MessagesBundle.getString("question_title_load_file_for_dividend"),
                        javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result != javax.swing.JOptionPane.YES_OPTION) {
                    // Assume success.
                    return true;
                }
            }

            this.dividendSummary = new DividendSummary();

            for (Dividend dividend : dividends) {
                dividendSummary.add(dividend);
            }
        }
            break;

        default:
            assert (false);
        } // End of switch

        this.updateWealthHeader();
    } else if (statements.getType() == Statement.Type.RealtimeInfo) {
        /* Open using other tabs. */
        return JStock.instance().openAsStatements(statements, file);
    } else {
        return false;
    }
    return true;
}

From source file:com.aurel.track.dbase.UpgradeDatabase.java

public static void upgrade370To380() throws SQLException, TorqueException {
    TSiteBean siteBean = siteDAO.load1();
    if (!isNewDbVersion(siteBean, 380)) {
        return; // upgrade should not be necessary
    }/*  www  .  ja  v  a 2  s . c  om*/
    LOGGER.info("Performing upgrade step 370 to 380.");
    ApplicationStarter.getInstance().actualizePercentComplete(ApplicationStarter.DB_DATA_UPGRADE_STEP,
            ApplicationStarter.DATA_UPGRADE_TO_TEXT + "3.8");
    addNewReportTemplatesBy380();
    Connection con = Torque.getConnection(BaseTProjectTypePeer.DATABASE_NAME);
    int maxid = 0;
    String sqlStmt = "SELECT MAX(OBJECTID) FROM TLINKTYPE";
    ResultSet rs = executeSelect(sqlStmt, con);
    if (rs != null) {
        maxid = rs.getInt(1) + 1;
    }
    if (maxid < 101) {
        maxid = 101;
        sqlStmt = "UPDATE ID_TABLE SET NEXT_ID = " + String.valueOf(maxid) + " WHERE TABLE_NAME = 'TLINKTYPE'";
        insertData(sqlStmt);
    }
    Integer linkTypeID = addLinkType("close depends on", "conditioning the close", LINK_DIRECTION.RIGHT_TO_LEFT,
            CloseDependsOnLinkType.class.getName());
    LocalizeBL.saveLocalizedResource("linkType.name.1.", linkTypeID, "close depends on", Locale.ENGLISH);
    LocalizeBL.saveLocalizedResource("linkType.filterSuperset.1.", linkTypeID, "conditioning the close",
            Locale.ENGLISH);
    LocalizeBL.saveLocalizedResource("linkType.name.1.", linkTypeID, "Schlieen hngt ab von", Locale.GERMAN);
    LocalizeBL.saveLocalizedResource("linkType.filterSuperset.1.", linkTypeID, "zuerst geschlossen sein mssen",
            Locale.GERMAN);

    addUnscheduledReleaseState();
    siteBean.setDbVersion("380");
    siteDAO.save(siteBean);
    Torque.closeConnection(con);
}

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

@Override
public AccountData account(Account account) throws IOException, JSONException, OpacErrorException {
    login(account);/*from www.ja v  a  2 s  .  com*/
    String html;
    Document doc;
    AccountData adata = new AccountData(account.getId());
    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN);

    html = httpGet(opac_url + "/konto.cgi?sess=" + sessid, getDefaultEncoding());
    doc = Jsoup.parse(html);
    doc.setBaseUri(opac_url + "/");

    for (Element td : doc.select("table.konto td")) {
        if (td.text().contains("Offene")) {
            String text = td.text().trim().replaceAll(
                    "Offene[^0-9]+Geb.+hren:[^0-9]+([0-9.," + "]+)[^0-9A-Z]*(|EUR|CHF|Fr.)", "$1 $2");
            adata.setPendingFees(text);
        }
    }

    List<LentItem> lent = new ArrayList<>();
    for (Element tr : doc.select("table.kontopos tr")) {
        LentItem item = new LentItem();
        Element desc = tr.child(1).select("label").first();
        String dates = tr.child(2).text().trim();
        if (tr.child(1).select("a").size() > 0) {
            String kk = getQueryParamsFirst(tr.child(1).select("a").first().absUrl("href")).get("katkey");
            item.setId(kk);
        }

        int i = 0;
        for (Node node : desc.childNodes()) {
            if (node instanceof TextNode) {
                String text = ((TextNode) node).text().trim();
                if (i == 0) {
                    item.setAuthor(text);
                } else if (i == 1) {
                    item.setTitle(text);
                } else if (text.contains("Mediennummer")) {
                    item.setBarcode(text.replace("Mediennummer: ", ""));
                }
                i++;
            }
        }

        if (tr.child(0).select("input").size() == 1) {
            item.setProlongData(tr.child(0).select("input").first().val());
            item.setRenewable(true);
        } else {
            item.setProlongData("" + tr.child(0).select("span").first().attr("class"));
            item.setRenewable(false);
        }

        String todate = dates;
        if (todate.contains("-")) {
            String[] datesplit = todate.split("-");
            todate = datesplit[1].trim();
        }
        try {
            item.setDeadline(fmt.parseLocalDate(todate.substring(0, 10)));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        lent.add(item);
    }
    adata.setLent(lent);

    List<ReservedItem> reservations = new ArrayList<>();
    html = httpGet(opac_url + "/konto.cgi?konto=v&sess=" + sessid, getDefaultEncoding());
    reservations.addAll(parse_reservations(html));
    html = httpGet(opac_url + "/konto.cgi?konto=b&sess=" + sessid, getDefaultEncoding());
    reservations.addAll(parse_reservations(html));

    adata.setReservations(reservations);

    return adata;
}

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

@Override
public AccountData account(Account acc)
        throws IOException, NotReachableException, JSONException, SocketException, OpacErrorException {
    Document login = login(acc);/*from  w ww  . j  a  va2s. co m*/
    if (login == null)
        return null;

    AccountData res = new AccountData(acc.getId());

    String lent_link = null;
    String res_link = null;
    int lent_cnt = -1;
    int res_cnt = -1;
    for (Element td : login.select(
            ".AccountSummaryCounterNameCell, .AccountSummaryCounterNameCellStripe, .CAccountDetailFieldNameCellStripe, .CAccountDetailFieldNameCell")) {
        String section = td.text().trim();
        if (section.contains("Entliehene Medien")) {
            lent_link = td.select("a").attr("href");
            lent_cnt = Integer.parseInt(td.nextElementSibling().text().trim());
        } else if (section.contains("Vormerkungen")) {
            res_link = td.select("a").attr("href");
            res_cnt = Integer.parseInt(td.nextElementSibling().text().trim());
        } else if (section.contains("Kontostand")) {
            res.setPendingFees(td.nextElementSibling().text().trim());
        } else if (section.matches("Ausweis g.ltig bis")) {
            res.setValidUntil(td.nextElementSibling().text().trim());
        }
    }
    assert (lent_cnt >= 0);
    assert (res_cnt >= 0);
    if (lent_link == null)
        return null;

    String lent_html = httpGet(opac_url + "/" + lent_link.replace("utf-8?Method", "utf-8&Method"),
            getDefaultEncoding());
    Document lent_doc = Jsoup.parse(lent_html);
    List<Map<String, String>> lent = new ArrayList<Map<String, String>>();

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.GERMAN);
    Pattern id_pat = Pattern.compile("javascript:renewItem\\('[0-9]+','(.*)'\\)");

    for (Element table : lent_doc
            .select(".LoansBrowseItemDetailsCellStripe table, .LoansBrowseItemDetailsCell table")) {
        Map<String, String> item = new HashMap<String, String>();

        for (Element tr : table.select("tr")) {
            String desc = tr.select(".LoanBrowseFieldNameCell").text().trim();
            String value = tr.select(".LoanBrowseFieldDataCell").text().trim();
            if (desc.equals("Titel"))
                item.put(AccountData.KEY_LENT_TITLE, value);
            if (desc.equals("Verfasser"))
                item.put(AccountData.KEY_LENT_AUTHOR, value);
            if (desc.equals("Mediennummer"))
                item.put(AccountData.KEY_LENT_BARCODE, value);
            if (desc.equals("ausgeliehen in"))
                item.put(AccountData.KEY_LENT_BRANCH, value);
            if (desc.matches("F.+lligkeits.*datum")) {
                value = value.split(" ")[0];
                item.put(AccountData.KEY_LENT_DEADLINE, value);
                try {
                    item.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP,
                            String.valueOf(sdf.parse(value).getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        if (table.select(".button[Title~=Zum]").size() == 1) {
            Matcher matcher1 = id_pat.matcher(table.select(".button[Title~=Zum]").attr("href"));
            if (matcher1.matches()) {
                item.put(AccountData.KEY_LENT_LINK, matcher1.group(1));
            }
        }
        lent.add(item);
    }
    res.setLent(lent);
    assert (lent_cnt <= lent.size());

    List<Map<String, String>> reservations = new ArrayList<Map<String, String>>();
    String res_html = httpGet(opac_url + "/" + res_link, getDefaultEncoding());
    Document res_doc = Jsoup.parse(res_html);

    for (Element table : res_doc
            .select(".MessageBrowseItemDetailsCell table, .MessageBrowseItemDetailsCellStripe table")) {
        Map<String, String> item = new HashMap<String, String>();

        for (Element tr : table.select("tr")) {
            String desc = tr.select(".MessageBrowseFieldNameCell").text().trim();
            String value = tr.select(".MessageBrowseFieldDataCell").text().trim();
            if (desc.equals("Titel"))
                item.put(AccountData.KEY_RESERVATION_TITLE, value);
            if (desc.equals("Publikationsform"))
                item.put(AccountData.KEY_RESERVATION_FORMAT, value);
            if (desc.equals("Liefern an"))
                item.put(AccountData.KEY_RESERVATION_BRANCH, value);
            if (desc.equals("Status"))
                item.put(AccountData.KEY_RESERVATION_READY, value);
        }
        if ("Gelscht".equals(item.get(AccountData.KEY_RESERVATION_READY))) {
            continue;
        }
        reservations.add(item);
    }
    res.setReservations(reservations);
    assert (reservations.size() >= res_cnt);

    return res;
}

From source file:com.aurel.track.dbase.UpgradeDatabase.java

private static void addUnscheduledReleaseState() {
    TSystemStateBean systemStateBean = new TSystemStateBean();
    systemStateBean.setLabel("unscheduled");
    systemStateBean.setStateflag(TSystemStateBean.STATEFLAGS.NOT_PLANNED);
    systemStateBean.setEntityflag(TSystemStateBean.ENTITYFLAGS.RELEASESTATE);
    systemStateBean.setSortorder(Integer.valueOf(10));
    Integer systemStateID = systemStateDAO.save(systemStateBean);
    String fieldName = LocalizationKeyPrefixes.SYSTEM_STATUS_KEY_PREFIX
            + TSystemStateBean.ENTITYFLAGS.RELEASESTATE;
    LocalizeBL.saveLocalizedResource(fieldName, systemStateID, "unscheduled", Locale.ENGLISH);
    LocalizeBL.saveLocalizedResource(fieldName, systemStateID, "nicht geplannt", Locale.GERMAN);
}

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

static void parseMediaList(List<LentItem> media, Document doc, JSONObject data) {
    if (doc.select("a[name=AUS]").size() == 0)
        return;//w ww . j  a  v a2s . c  o m

    Elements copytrs = doc.select("a[name=AUS] ~ table, a[name=AUS] ~ form table").first().select("tr");
    doc.setBaseUri(data.optString("baseurl"));

    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN);

    int trs = copytrs.size();
    if (trs < 2) {
        return;
    }
    assert (trs > 0);

    JSONObject copymap = new JSONObject();
    try {
        if (data.has("accounttable")) {
            copymap = data.getJSONObject("accounttable");
        }
    } catch (JSONException e) {
    }

    Pattern datePattern = Pattern.compile("\\d{2}\\.\\d{2}\\.\\d{4}");
    for (int i = 1; i < trs; i++) {
        Element tr = copytrs.get(i);
        LentItem item = new LentItem();

        if (copymap.optInt("title", 0) >= 0) {
            item.setTitle(tr.child(copymap.optInt("title", 0)).text().trim().replace("\u00a0", ""));
        }
        if (copymap.optInt("author", 1) >= 0) {
            item.setAuthor(tr.child(copymap.optInt("author", 1)).text().trim().replace("\u00a0", ""));
        }
        if (copymap.optInt("format", 2) >= 0) {
            item.setFormat(tr.child(copymap.optInt("format", 2)).text().trim().replace("\u00a0", ""));
        }
        int prolongCount = 0;
        if (copymap.optInt("prolongcount", 3) >= 0) {
            prolongCount = Integer
                    .parseInt(tr.child(copymap.optInt("prolongcount", 3)).text().trim().replace("\u00a0", ""));
            item.setStatus(String.valueOf(prolongCount) + "x verl.");
        }
        if (data.optInt("maxprolongcount", -1) != -1) {
            item.setRenewable(prolongCount < data.optInt("maxprolongcount", -1));
        }
        if (copymap.optInt("returndate", 4) >= 0) {
            String value = tr.child(copymap.optInt("returndate", 4)).text().trim().replace("\u00a0", "");
            Matcher matcher = datePattern.matcher(value);
            if (matcher.find()) {
                try {
                    item.setDeadline(fmt.parseLocalDate(matcher.group()));
                } catch (IllegalArgumentException e1) {
                    e1.printStackTrace();
                }
            }
        }
        if (copymap.optInt("prolongurl", 5) >= 0) {
            if (tr.children().size() > copymap.optInt("prolongurl", 5)) {
                Element cell = tr.child(copymap.optInt("prolongurl", 5));
                if (cell.select("input[name=MedNrVerlAll]").size() > 0) {
                    // new iOPAC Version 1.45 - checkboxes to prolong multiple items
                    // internal convention: We add "NEW" to the media ID to show that we have
                    // the new iOPAC version
                    Element input = cell.select("input[name=MedNrVerlAll]").first();
                    String value = input.val();
                    item.setProlongData("NEW" + value);
                    item.setId(value.split(";")[0]);
                    if (input.hasAttr("disabled"))
                        item.setRenewable(false);
                } else {
                    // previous versions - link for prolonging on every medium
                    String link = cell.select("a").attr("href");
                    item.setProlongData(link);
                    // find media number with regex
                    Pattern pattern = Pattern.compile("mednr=([^&]*)&");
                    Matcher matcher = pattern.matcher(link);
                    if (matcher.find() && matcher.group() != null)
                        item.setId(matcher.group(1));
                }
            }
        }

        media.add(item);
    }
    assert (media.size() == trs - 1);

}

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

protected List<ReservedItem> parse_reservations(String html) {
    Document doc = Jsoup.parse(html);
    List<ReservedItem> reservations = new ArrayList<>();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN);

    for (Element tr : doc.select("table.kontopos tr")) {
        ReservedItem item = new ReservedItem();
        Element desc = tr.child(1).select("label").first();
        Element pos = tr.child(3);
        if (tr.child(1).select("a").size() > 0) {
            String kk = getQueryParamsFirst(tr.child(1).select("a").first().absUrl("href")).get("katkey");
            item.setId(kk);//from ww w .  j a v a 2  s. c o  m
        }
        if (tr.child(0).select("input").size() > 0) {
            item.setCancelData(tr.child(0).select("input").first().val());
        }

        int i = 0;
        for (Node node : desc.childNodes()) {
            if (node instanceof TextNode) {
                String text = ((TextNode) node).text().trim();
                if (i == 0) {
                    item.setAuthor(text);
                } else if (i == 1) {
                    item.setTitle(text);
                }
                i++;
            }
        }
        i = 0;
        for (Node node : pos.childNodes()) {
            if (node instanceof TextNode) {
                String text = ((TextNode) node).text().trim();
                if (i == 0 && text.contains("")) {
                    try {
                        item.setReadyDate(fmt.parseLocalDate(text));
                    } catch (IllegalArgumentException e) {
                        item.setStatus(text);
                    }
                } else if (i == 1) {
                    item.setBranch(text);
                }
                i++;
            }
        }
        reservations.add(item);
    }
    return reservations;
}