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.efaps.esjp.accounting.util.data.ImportDetails.java

protected List<Document> checkAccounts(final Parameter _parameter, final File _file,
        final Map<String, Instance> _docMap, final DateTime _date, final Boolean _inverse)
        throws IOException, EFapsException {
    final List<Document> ret = new ArrayList<>();
    final CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"));
    final List<String[]> entries = reader.readAll();
    reader.close();//w ww  .j a v a2  s  .com
    entries.remove(0);
    int i = 1;
    final Map<String, Document> map = new HashMap<>();
    for (final String[] row : entries) {
        i++;
        final String docNumber = row[0];
        final String ruc = row[1];
        final String dateStr = row[2];
        final String accountStr = row[5];
        final String accountDesc = row[4];
        final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
        formater.setParseBigDecimal(true);
        final String amountMEStr = row[6];
        final String amountMNStr = row[7];

        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
        queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accountStr.trim());
        final InstanceQuery query = queryBldr.getQuery();
        query.executeWithoutAccessCheck();
        if (query.next()) {
            ImportDetails.LOG.info("Found account: '{}' ", accountStr);
            final String[] docSplit = docNumber.split("-");
            if (docSplit.length != 2 && _docMap != null) {
                ImportDetails.LOG.warn(
                        "Document '{}'  - Line: {} has no '-' to distinguish SerialNumber and No.", docNumber,
                        i);
            } else {
                try {
                    final Formatter criteria = new Formatter();
                    String name = docNumber;
                    if (_docMap != null) {
                        final String serialNo = docSplit[0];
                        final String docNo = docSplit[1];
                        final int serial = Integer.parseInt(serialNo.trim().replaceAll("\\D", ""));
                        final int no = Integer.parseInt(docNo.trim().replaceAll("\\D", ""));
                        criteria.format("%03d-%06d", serial, no);
                        name = criteria.toString();
                    }

                    Document doc;
                    if (map.containsKey(name)) {
                        doc = map.get(name);
                    } else {
                        if (_docMap != null && _docMap.containsKey(name)) {
                            doc = new Document(name, _docMap.get(name), ruc, dateStr, accountDesc);
                        } else {
                            doc = new Document(name, null, ruc, dateStr, accountDesc);
                        }
                    }

                    BigDecimal amountME = (BigDecimal) formater.parse(amountMEStr);
                    BigDecimal amountMN = (BigDecimal) formater.parse(amountMNStr);

                    if (_inverse) {
                        amountME = amountME.negate();
                        amountMN = amountMN.negate();
                    }

                    if (amountMN.compareTo(BigDecimal.ZERO) >= 0) {
                        doc.addAmountMECredit(amountME);
                        doc.addAmountMNCredit(amountMN);
                    } else {
                        doc.addAmountMEDebit(amountME);
                        doc.addAmountMNDebit(amountMN);
                    }

                    final Map<String, Account> accounts = doc.getAccounts();
                    Account acc;
                    if (accounts.containsKey(accountStr)) {
                        acc = accounts.get(accountStr);
                    } else {
                        acc = new Account(accountStr, accountDesc);
                        accounts.put(accountStr, acc);
                    }
                    acc.addAmountME(amountME);
                    acc.addAmountMN(amountMN);
                    acc.setInstance(query.getCurrentValue());

                    map.put(name, doc);

                    criteria.close();
                } catch (final NumberFormatException e) {
                    ImportDetails.LOG.error("wrong format for document '{}'", docNumber);
                } catch (final ParseException e) {
                    ImportDetails.LOG.error("wrong format for amounts '{}' - '{}'", amountMEStr, amountMNStr);
                }
            }
        } else {
            ImportDetails.LOG.error("Not found account: {}", accountStr);
        }
    }

    final Instance periodInst = getPeriodInstance();
    for (final Document doc : map.values()) {
        final BigDecimal amountCreditMN = doc.getAmountMNCredit() != null ? doc.getAmountMNCredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitMN = doc.getAmountMNDebit() != null ? doc.getAmountMNDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountMN = amountCreditMN.add(amountDebitMN);
        final BigDecimal amountCreditME = doc.getAmountMECredit() != null ? doc.getAmountMECredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitME = doc.getAmountMEDebit() != null ? doc.getAmountMEDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountME = amountCreditME.add(amountDebitME);
        if (BigDecimal.ZERO.compareTo(amountMN) == 0 && BigDecimal.ZERO.compareTo(amountME) == 0) {
            ImportDetails.LOG.info(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' and Credit with Debit Amount (MN): '{}' + '{}' are Zero (0)",
                    doc.getName(), amountCreditME, amountDebitME, amountCreditMN, amountDebitMN);
        } else {
            ImportDetails.LOG.error(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' = '{}' and Credit with Debit Amount (MN): '{}' + '{}' = '{}'",
                    doc.getName(), amountCreditME, amountDebitME, amountME, amountCreditMN, amountDebitMN,
                    amountMN);
        }

        final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance);
        insert.add(CIAccounting.TransactionOpeningBalance.Date, _date);
        final StringBuilder descBldr = new StringBuilder()
                .append(doc.getInstance() != null ? doc.getInstance().getType().getLabel() : "Sin Documento")
                .append(": ").append(doc.getName()).append(" - RUC: ").append(doc.getRuc()).append(" - ")
                .append(doc.getDate()).append(" - ").append(doc.getDesc());

        insert.add(CIAccounting.TransactionOpeningBalance.Description, descBldr.toString());
        insert.add(CIAccounting.TransactionOpeningBalance.Status,
                Status.find(CIAccounting.TransactionStatus.Open));
        insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst);
        insert.executeWithoutAccessCheck();

        if (_docMap != null) {
            final Instance instance = insert.getInstance();
            new Create().connectDocs2Transaction(_parameter, instance, doc.getInstance());
        }

        final Map<String, Account> accounts = doc.getAccounts();
        final Instance basCur = Currency.getBaseCurrency();
        for (final Account acc : accounts.values()) {
            final Insert insertpos = new Insert(
                    acc.getAmountMN().compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit
                            : CIAccounting.TransactionPositionDebit);
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }

        if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) <= 0) {
            Insert insertpos = null;
            Account acc = null;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGDEBIT);
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGCREDIT);
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        } else if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) > 0) {
            Insert insertpos = null;
            final Account acc = getRoundingAccount(AccountingSettings.PERIOD_TRANSFERACCOUNT);
            ;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }
    }

    return ret;
}

From source file:de.dekarlab.moneybuilder.view.AnalyticsView.java

/**
 * Create pie chart.//from  ww w  .  java 2  s .  c om
 * 
 * @param dataset
 * @param title
 * @return
 */
protected JFreeChart createLineChart(final CategoryDataset dataset, final String title) {
    final JFreeChart chart = ChartFactory.createLineChart("", // chart title
            App.getGuiProp("report.period.lbl"), // domain axis label
            App.getGuiProp("report.value.lbl"), // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );
    final CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setNoDataMessage(App.getGuiProp("report.nodata.msg"));
    plot.setBackgroundPaint(Color.white);
    plot.setBackgroundPaint(Color.white);
    ((NumberAxis) plot.getRangeAxis()).setAutoRangeIncludesZero(false);
    ((CategoryAxis) plot.getDomainAxis()).setMaximumCategoryLabelLines(10);
    ((CategoryAxis) plot.getDomainAxis()).setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.gray);
    plot.setRangeGridlinePaint(Color.gray);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeZeroBaselinePaint(Color.black);
    plot.setRangeZeroBaselineVisible(true);
    int color = 0;
    CategoryItemRenderer renderer = plot.getRenderer();
    for (int ser = 0; ser < dataset.getColumnCount(); ser++) {
        renderer.setSeriesPaint(ser, COLORS[color]);
        renderer.setSeriesStroke(ser, new BasicStroke(4));
        StandardCategoryItemLabelGenerator gen = new StandardCategoryItemLabelGenerator("{2}",
                NumberFormat.getInstance(Locale.GERMAN)) {
            private static final long serialVersionUID = 1L;

            public String generateLabel(CategoryDataset dataset, int series, int item) {
                if (item % 3 == 0) {
                    return super.generateLabelString(dataset, series, item);
                } else {
                    return null;
                }
            }
        };

        renderer.setSeriesItemLabelGenerator(ser, gen);
        renderer.setSeriesItemLabelsVisible(ser, true);

        color++;
        if (COLORS.length == color) {
            color = 0;
        }
    }
    return chart;
}

From source file:de.geeksfactory.opacclient.objects.Library.java

@Override
public int compareTo(Library arg0) {
    Collator deCollator = Collator.getInstance(Locale.GERMAN);
    deCollator.setStrength(Collator.TERTIARY);

    int g = deCollator.compare(country, arg0.getCountry());
    if (g == 0) {
        g = deCollator.compare(state, arg0.getState());
        if (g == 0) {
            g = deCollator.compare(city, arg0.getCity());
            if (g == 0) {
                g = deCollator.compare(title, arg0.getTitle());
            }//from  ww w  .ja  v  a2 s. com
        }
    }
    return g;
}

From source file:org.xwiki.search.solr.internal.job.DatabaseDocumentIteratorTest.java

@Test
public void iterateOneWiki() throws Exception {
    DocumentReference rootReference = createDocumentReference("gang", Arrays.asList("A", "B"), "C", null);

    Query emptyQuery = mock(Query.class);
    when(emptyQuery.execute()).thenReturn(Collections.emptyList());

    Query query = mock(Query.class);
    when(query.setLimit(anyInt())).thenReturn(query);
    when(query.setWiki(rootReference.getWikiReference().getName())).thenReturn(query);
    when(query.setOffset(0)).thenReturn(query);
    when(query.setOffset(100)).thenReturn(emptyQuery);
    when(query.execute())/*  ww w  .  ja  va 2s.co m*/
            .thenReturn(Collections.<Object>singletonList(new Object[] { "A.B", "C", "de", "3.1" }));

    Map<String, Object> namedParameters = new HashMap<String, Object>();
    namedParameters.put("space", "A.B");
    namedParameters.put("name", "C");
    when(query.getNamedParameters()).thenReturn(namedParameters);

    Query countQuery = mock(Query.class);
    when(countQuery.addFilter(mocker.<QueryFilter>getInstance(QueryFilter.class, "count")))
            .thenReturn(countQuery);

    QueryManager queryManager = mocker.getInstance(QueryManager.class);
    String whereClause = " where doc.space = :space and doc.name = :name";
    when(queryManager.createQuery("select doc.space, doc.name, doc.language, doc.version from XWikiDocument doc"
            + whereClause + " order by doc.space, doc.name, doc.language", Query.HQL)).thenReturn(query);
    when(queryManager.createQuery(whereClause, Query.HQL)).thenReturn(countQuery);

    DocumentIterator<String> iterator = mocker.getComponentUnderTest();
    iterator.setRootReference(rootReference);

    List<Pair<DocumentReference, String>> actualResults = new ArrayList<Pair<DocumentReference, String>>();
    while (iterator.hasNext()) {
        actualResults.add(iterator.next());
    }

    List<Pair<DocumentReference, String>> expectedResults = new ArrayList<Pair<DocumentReference, String>>();
    expectedResults.add(new ImmutablePair<DocumentReference, String>(
            new DocumentReference(rootReference, Locale.GERMAN), "3.1"));

    assertEquals(expectedResults, actualResults);

    verify(query).bindValue("space", "A.B");
    verify(query).bindValue("name", "C");

    verify(countQuery).bindValue("space", "A.B");
    verify(countQuery).bindValue("name", "C");
}

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

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

    if (doc.select("h4").size() > 0) {
        if (doc.select("h4").text().trim().startsWith("0 gefundene Medien")) {
            // nothing found
            return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, 1);
        } else if (!doc.select("h4").text().trim().contains("gefundene Medien")
                && !doc.select("h4").text().trim().contains("Es wurden mehr als")) {
            // error
            throw new OpacErrorException(doc.select("h4").text().trim());
        }/*from w w w  . ja v a  2 s.  c om*/
    } else if (doc.select("h1").size() > 0) {
        if (doc.select("h1").text().trim().contains("RUNTIME ERROR")) {
            // Server Error
            throw new NotReachableException("IOPAC RUNTIME ERROR");
        } else {
            throw new OpacErrorException(stringProvider.getFormattedString(
                    StringProvider.UNKNOWN_ERROR_WITH_DESCRIPTION, doc.select("h1").text().trim()));
        }
    } else {
        return null;
    }

    updateRechnr(doc);

    reusehtml = html;

    results_total = -1;

    if (doc.select("h4").text().trim().contains("Es wurden mehr als")) {
        results_total = 200;
    } else {
        String resultnumstr = doc.select("h4").first().text();
        resultnumstr = resultnumstr.substring(0, resultnumstr.indexOf(" ")).trim();
        results_total = Integer.parseInt(resultnumstr);
    }

    List<SearchResult> results = new ArrayList<>();

    Elements tables = doc.select("table").first().select("tr:has(td)");

    Map<String, Integer> colmap = new HashMap<>();
    Element thead = doc.select("table").first().select("tr:has(th)").first();
    int j = 0;
    for (Element th : thead.select("th")) {
        String text = th.text().trim().toLowerCase(Locale.GERMAN);
        if (text.contains("cover")) {
            colmap.put("cover", j);
        } else if (text.contains("titel")) {
            colmap.put("title", j);
        } else if (text.contains("verfasser")) {
            colmap.put("author", j);
        } else if (text.contains("mtyp")) {
            colmap.put("category", j);
        } else if (text.contains("jahr")) {
            colmap.put("year", j);
        } else if (text.contains("signatur")) {
            colmap.put("shelfmark", j);
        } else if (text.contains("info")) {
            colmap.put("info", j);
        } else if (text.contains("abteilung")) {
            colmap.put("department", j);
        } else if (text.contains("verliehen") || text.contains("verl.")) {
            colmap.put("returndate", j);
        } else if (text.contains("anz.res")) {
            colmap.put("reservations", j);
        }
        j++;
    }
    if (colmap.size() == 0) {
        colmap.put("cover", 0);
        colmap.put("title", 1);
        colmap.put("author", 2);
        colmap.put("publisher", 3);
        colmap.put("year", 4);
        colmap.put("department", 5);
        colmap.put("shelfmark", 6);
        colmap.put("returndate", 7);
        colmap.put("category", 8);
    }

    for (int i = 0; i < tables.size(); i++) {
        Element tr = tables.get(i);
        SearchResult sr = new SearchResult();

        if (tr.select("td").get(colmap.get("cover")).select("img").size() > 0) {
            String imgUrl = tr.select("td").get(colmap.get("cover")).select("img").first().attr("src");
            sr.setCover(imgUrl);
        }

        // Media Type
        if (colmap.get("category") != null) {
            String mType = tr.select("td").get(colmap.get("category")).text().trim().replace("\u00a0", "");
            if (data.has("mediatypes")) {
                try {
                    sr.setType(MediaType.valueOf(
                            data.getJSONObject("mediatypes").getString(mType.toLowerCase(Locale.GERMAN))));
                } catch (JSONException | IllegalArgumentException e) {
                    sr.setType(defaulttypes.get(mType.toLowerCase(Locale.GERMAN)));
                }
            } else {
                sr.setType(defaulttypes.get(mType.toLowerCase(Locale.GERMAN)));
            }
        }

        // Title and additional info
        String title;
        String additionalInfo = "";
        if (colmap.get("info") != null) {
            Element info = tr.select("td").get(colmap.get("info"));
            title = info.select("a[title=Details-Info]").text().trim();
            String authorIn = info.text().substring(0, info.text().indexOf(title));
            if (authorIn.contains(":")) {
                authorIn = authorIn.replaceFirst("^([^:]*):(.*)$", "$1");
                additionalInfo += " - " + authorIn;
            }
        } else {
            title = tr.select("td").get(colmap.get("title")).text().trim().replace("\u00a0", "");
            if (title.contains("(") && title.indexOf("(") > 0) {
                additionalInfo += title.substring(title.indexOf("("));
                title = title.substring(0, title.indexOf("(") - 1).trim();
            }

            // Author
            if (colmap.containsKey("author")) {
                String author = tr.select("td").get(colmap.get("author")).text().trim().replace("\u00a0", "");
                additionalInfo += " - " + author;
            }
        }

        // Publisher
        if (colmap.containsKey("publisher")) {
            String publisher = tr.select("td").get(colmap.get("publisher")).text().trim().replace("\u00a0", "");
            additionalInfo += " (" + publisher;
        }

        // Year
        if (colmap.containsKey("year")) {
            String year = tr.select("td").get(colmap.get("year")).text().trim().replace("\u00a0", "");
            additionalInfo += ", " + year + ")";
        }

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

        // Status
        String status = tr.select("td").get(colmap.get("returndate")).text().trim().replace("\u00a0", "");
        SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
        try {
            df.parse(status);
            // this is a return date
            sr.setStatus(Status.RED);
            sr.setInnerhtml(sr.getInnerhtml() + "<br><i>" + stringProvider.getString(StringProvider.LENT_UNTIL)
                    + " " + status + "</i>");
        } catch (ParseException e) {
            // this is a different status text
            String lc = status.toLowerCase(Locale.GERMAN);
            if ((lc.equals("") || lc.toLowerCase(Locale.GERMAN).contains("onleihe") || lc.contains("verleihbar")
                    || lc.contains("entleihbar") || lc.contains("ausleihbar")) && !lc.contains("nicht")) {
                sr.setStatus(Status.GREEN);
            } else {
                sr.setStatus(Status.YELLOW);
                sr.setInnerhtml(sr.getInnerhtml() + "<br><i>" + status + "</i>");
            }
        }

        // In some libraries (for example search for "atelier" in Preetz)
        // the results are sorted differently than their numbers suggest, so
        // we need to detect the number ("recno") from the link
        String link = tr.select("a[href^=/cgi-bin/di.exe?page=]").attr("href");
        Map<String, String> params = getQueryParamsFirst(link);
        if (params.containsKey("recno")) {
            int recno = Integer.valueOf(params.get("recno"));
            sr.setNr(recno - 1);
        } else {
            // the above should work, but fall back to this if it doesn't
            sr.setNr(10 * (page - 1) + i);
        }

        // In some libraries (for example Preetz) we can detect the media ID
        // here using another link present in the search results
        Elements idLinks = tr.select("a[href^=/cgi-bin/di.exe?cMedNr]");
        if (idLinks.size() > 0) {
            Map<String, String> idParams = getQueryParamsFirst(idLinks.first().attr("href"));
            String id = idParams.get("cMedNr");
            sr.setId(id);
        } else {
            sr.setId(null);
        }

        results.add(sr);
    }
    return new SearchRequestResult(results, results_total, page);
}

From source file:at.flack.MailMainActivity.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    prefs = getActivity().getSharedPreferences("mail", Context.MODE_PRIVATE);
    if (!prefs.getString("mailaddress", "").equals("")) {
        View rootView = inflater.inflate(R.layout.fragment_mail_main, container, false);

        loadmore = new LoadMoreAdapter(inflater.inflate(R.layout.contacts_loadmore, contactList, false));
        contactList = (ListView) rootView.findViewById(R.id.listview);
        TextView padding = new TextView(getActivity());
        padding.setHeight(10);//from w  w w .  j ava 2 s  .c om
        contactList.addHeaderView(padding);
        contactList.setHeaderDividersEnabled(false);
        contactList.addFooterView(loadmore.getView(), null, false);
        contactList.setFooterDividersEnabled(false);
        progressbar = rootView.findViewById(R.id.load_screen);
        FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
        fab.attachToListView(contactList);
        fab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent newMail = new Intent(getActivity(), NewMailActivity.class);
                getActivity().startActivity(newMail);
            }
        });

        progressbar = rootView.findViewById(R.id.load_screen);
        if (MainActivity.getMailcontacts() == null)
            progressbar.setVisibility(View.VISIBLE);
        updateContactList(((MainActivity) this.getActivity()));

        swipe = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (getActivity() instanceof MainActivity) {
                    MainActivity.mailprofile = null;
                    ((MainActivity) getActivity()).emailLogin(1, 0, limit);
                }

            }
        });
        contactList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                int topRowVerticalPosition = (contactList == null || contactList.getChildCount() == 0) ? 0
                        : contactList.getChildAt(0).getTop();
                swipe.setEnabled(topRowVerticalPosition >= 0);
            }
        });

        contactList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (MainActivity.getListItems() == null) {
                    updateContactList((MainActivity) getActivity());
                }
                openMessageActivity(getActivity(), arg2 - 1);
            }

        });

        loadmore.getView().setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                loadmore.setEnabled(false);
                MainActivity.mailprofile = null;
                limit += 12;
                ((MainActivity) getActivity()).emailLogin(1, 0, limit);
            }
        });

        setRetainInstance(true);
        return rootView;
    } else {
        View rootView = inflater.inflate(R.layout.fragment_email_login, container, false);
        final EditText mail = (EditText) rootView.findViewById(R.id.email);
        final EditText password = (EditText) rootView.findViewById(R.id.password);

        final EditText host = (EditText) rootView.findViewById(R.id.host);
        final EditText port = (EditText) rootView.findViewById(R.id.port);
        final EditText smtphost = (EditText) rootView.findViewById(R.id.smtphost);
        final EditText smtpport = (EditText) rootView.findViewById(R.id.smtpport);

        final Button login_button = (Button) rootView.findViewById(R.id.login_button);

        final RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.radioGroup);
        final RadioButton imap = (RadioButton) rootView.findViewById(R.id.radioButtonImap);

        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                host.setVisibility(View.VISIBLE);
                port.setVisibility(View.VISIBLE);
                smtphost.setVisibility(View.VISIBLE);
                smtpport.setVisibility(View.VISIBLE);
            }
        });

        login_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int at = mail.getText().toString().indexOf("@");
                int dot = mail.getText().toString().lastIndexOf(".");
                if (mail.getText().length() <= 0 || at < 0 || dot < 0) {
                    Toast.makeText(MailMainActivity.this.getActivity(),
                            getResources().getString(R.string.facebook_login_please_enter_valid_mail),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password.getText().length() <= 0) {
                    Toast.makeText(MailMainActivity.this.getActivity(),
                            getResources().getString(R.string.facebook_login_please_enter_valid_pw),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                String hostPart = mail.getText().toString().substring(at + 1, dot);

                MailAccounts mailacc = null;
                try {
                    mailacc = MailAccounts.valueOf(hostPart.toUpperCase(Locale.GERMAN));
                } catch (IllegalArgumentException e) {
                }
                if (mailacc == null) {
                    radioGroup.setVisibility(View.VISIBLE);
                    if (host.getText().toString().isEmpty() || port.getText().toString().isEmpty()
                            || smtphost.getText().toString().isEmpty()
                            || smtpport.getText().toString().isEmpty()) {
                        Toast.makeText(MailMainActivity.this.getActivity(),
                                MailMainActivity.this.getActivity().getResources().getString(
                                        R.string.activity_mail_enter_more_information),
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                    prefs.edit().putString("mailsmtp", smtphost.getText().toString()).apply();
                    prefs.edit().putInt("mailsmtpport", Integer.parseInt(smtpport.getText().toString()));
                    prefs.edit().putString("mailimap", host.getText().toString()).apply();
                    prefs.edit().putInt("mailimapport", Integer.parseInt(port.getText().toString())).apply();
                    prefs.edit().putBoolean("mailuseimap", imap.isChecked()).apply();
                }

                login_button.setEnabled(false);
                login_button.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
                prefs.edit().putString("mailaddress", mail.getText().toString()).apply();
                prefs.edit().putString("mailpassword", password.getText().toString()).apply();

                if (mailacc != null) {
                    prefs.edit().putString("mailsmtp", mailacc.getSmtpHost()).apply();
                    prefs.edit().putInt("mailsmtpport", mailacc.getSMTPPort());
                    prefs.edit().putString("mailimap", mailacc.getHost()).apply();
                    prefs.edit().putInt("mailimapport", mailacc.getPort()).apply();
                    prefs.edit().putBoolean("mailuseimap", true).apply();
                }

                prefs.edit().commit();
                ((MainActivity) getActivity()).emailLogin(0);
            }
        });

        setRetainInstance(true);

        return rootView;
    }
}

From source file:com.seajas.search.codex.service.social.SocialProfileServiceTest.java

@Test
public void testSearchFacebookProfile() throws Exception {
    Reference ref1 = new Reference("id");
    Reference ref2 = new Reference("id2");

    FacebookProfile fbp1 = new FacebookProfile("id", "username", "name", "first", "last", "gender",
            Locale.GERMAN);
    FacebookProfile fbp2 = new FacebookProfile("id2", "username", "name", "first", "last", "gender",
            Locale.GERMAN);/*from w  ww. j a v a 2s  . c o m*/

    when(socialFacadeMock.searchFacebookProfiles("testPerson")).thenReturn(Lists.newArrayList(ref1, ref2));
    when(socialFacadeMock.getFacebookProfiles(Lists.newArrayList("id", "id2")))
            .thenReturn(Lists.newArrayList(fbp1, fbp2));

    List<SocialProfileDto> dtos = socialProfileService.searchFacebookProfiles("testPerson", false);

    List profiles = Lists.newArrayList(SocialProfileDto.translate(fbp1), SocialProfileDto.translate(fbp2));
    Assert.assertEquals(profiles, dtos);
    verify(mediaServiceMock, times(2)).storeUrl(anyString(), (String) isNull(), eq("image"));
}

From source file:test.be.fedict.eid.applet.PcscTest.java

@Test
public void pcscOTPSpike() throws Exception {
    this.messages = new Messages(Locale.GERMAN);
    PcscEid pcscEid = new PcscEid(new TestView(), this.messages);
    if (false == pcscEid.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEid.waitForEidPresent();/*ww  w  .  j a  v a 2 s.co m*/
    }
    byte[] challenge1 = "123456".getBytes();
    byte[] challenge2 = "654321".getBytes();
    byte[] signatureValue1;
    byte[] signatureValue2;
    List<X509Certificate> authnCertChain;
    try {
        signatureValue1 = pcscEid.signAuthn(challenge1);
        signatureValue2 = pcscEid.signAuthn(challenge2);
        authnCertChain = pcscEid.getAuthnCertificateChain();
    } finally {
        pcscEid.close();
    }

    byte[] sv1 = Arrays.copyOf(signatureValue1, 13);
    byte[] sv2 = Arrays.copyOf(signatureValue2, 13);
    LOG.debug("same encrypted prefix: " + Arrays.equals(sv1, sv2));

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(authnCertChain.get(0).getPublicKey());
    signature.update(challenge1);
    boolean result = signature.verify(signatureValue1);
    assertTrue(result);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE, authnCertChain.get(0).getPublicKey());
    byte[] signatureDigestInfoValue = cipher.doFinal(signatureValue1);
    LOG.debug("encrypted signature value: " + signatureValue1.length);
    ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue);
    DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject());
    LOG.debug("algo OID: " + signatureDigestInfo.getAlgorithmId().getObjectId().getId());
    LOG.debug("digest size: " + signatureDigestInfo.getDigest().length);
    int digestIndex = findSubArray(signatureDigestInfoValue, signatureDigestInfo.getDigest());
    assertTrue(-1 != digestIndex);
    LOG.debug("digest index: " + digestIndex);

    // inject the encrypted digest of signature1 into signature2
    // padding will look bad now
    System.arraycopy(signatureValue1, 13, signatureValue2, 13, 20);
    cipher = Cipher.getInstance("RSA/ECB/nopadding");
    cipher.init(Cipher.DECRYPT_MODE, authnCertChain.get(0).getPublicKey());
    signatureValue2 = Arrays.copyOf(signatureValue2, 13 + 20);
    byte[] signatureDigestInfoValue2 = cipher.doFinal(signatureValue2);
    LOG.debug("decrypted structure size: " + signatureDigestInfoValue2.length);
    signatureDigestInfoValue2 = Arrays.copyOf(signatureDigestInfoValue2, 13 + 20);
    LOG.debug("decrypted structure size (truncated): " + signatureDigestInfoValue2.length);
    ASN1InputStream aIn2 = new ASN1InputStream(signatureDigestInfoValue2);
    DigestInfo signatureDigestInfo2 = new DigestInfo((ASN1Sequence) aIn2.readObject());
    LOG.debug("digest size: " + signatureDigestInfo2.getDigest().length);
    LOG.debug("digest: " + new String(signatureDigestInfo2.getDigest()));
}

From source file:de.ingrid.portal.scheduler.jobs.IngridMonitorAbstractJob.java

private boolean sendUpdateEmail(String email, IngridComponent component) {
    String from = PortalConfig.getInstance().getString(PortalConfig.COMPONENT_MONITOR_ALERT_EMAIL_SENDER,
            "foo@bar.com");

    String emailSubject = PortalConfig.getInstance().getString(
            PortalConfig.COMPONENT_MONITOR_UPDATE_ALERT_EMAIL_SUBJECT, "ingrid component monitor update alert");
    emailSubject = emailSubject.concat(" [").concat(component.getName()).concat("]");

    URL url = Thread.currentThread().getContextClassLoader()
            .getResource("../templates/administration/monitor_update_alert_email.vm");
    String templatePath = url.getPath();

    HashMap<String, Object> mailData = new HashMap<String, Object>();
    mailData.put("COMPONENT", component);
    ResourceBundle resources = ResourceBundle.getBundle("de.ingrid.portal.resources.AdminPortalResources",
            Locale.GERMAN);
    mailData.put("MESSAGES", new IngridResourceBundle(resources, Locale.GERMAN));

    String text = Utils.mergeTemplate(templatePath, mailData, "map");

    return Utils.sendEmail(from, emailSubject, new String[] { email }, text, null);

}

From source file:de.iteratec.iteraplan.presentation.dialog.GraphicalReporting.Landscape.LandscapeDiagramFrontendServiceTest.java

private void testManageLandscapeDiagramMemoryBean(ManageLandscapeDiagramMemoryBean memBean,
        InformationSystemRelease ipuRel, EnumAT lineType, BusinessUnit bu) {
    DynamicQueryFormData<?> contentForm = memBean.getQueryResult(LandscapeOptionsBean.CONTENT_QUERY)
            .getQueryForms().get(0);/*from   w  w  w  . ja  va2 s.c  o m*/
    assertEquals(InformationSystemReleaseTypeQu.getInstance(), contentForm.getType());

    IQStatusData status = contentForm.getQueryUserInput().getStatusQueryData();
    QTimespanData time = contentForm.getQueryUserInput().getTimespanQueryData();
    QPart part = contentForm.getQueryUserInput().getQueryFirstLevels().get(0).getQuerySecondLevels().get(0);

    assertEquals(DateUtils.formatAsString(new Date(), Locale.GERMAN),
            DateUtils.formatAsString(time.getStartDate(), Locale.GERMAN));
    assertEquals(DateUtils.formatAsString(new Date(new Date().getTime() + 500000000L), Locale.GERMAN),
            DateUtils.formatAsString(time.getEndDate(), Locale.GERMAN));
    assertEquals(4, status.getStatusMap().size());
    assertTrue(status.getStatus("typeOfStatus_current").booleanValue());
    assertFalse(status.getStatus("typeOfStatus_planned").booleanValue());
    assertFalse(status.getStatus("typeOfStatus_target").booleanValue());
    assertFalse(status.getStatus("typeOfStatus_inactive").booleanValue());

    assertEquals("userdefEnum_null_" + lineType.getId(), part.getChosenAttributeStringId());
    assertEquals(Constants.OPERATION_CONTAINSNOT_ID, part.getChosenOperationId());

    LandscapeOptionsBean landscapeOptions = memBean.getGraphicalOptions();

    ColorDimensionOptionsBean colorOptions = landscapeOptions.getColorOptionsBean();
    assertEquals("AFCEA8", colorOptions.getSelectedColors().get(0));
    assertEquals("Gut", colorOptions.getAttributeValues().get(0));
    assertEquals("F6DF95", colorOptions.getSelectedColors().get(1));
    assertEquals("Mittel", colorOptions.getAttributeValues().get(1));
    assertEquals("D79DAD", colorOptions.getSelectedColors().get(2));
    assertEquals("Schlecht", colorOptions.getAttributeValues().get(2));

    LineDimensionOptionsBean lineOptions = landscapeOptions.getLineOptionsBean();
    assertEquals("1", lineOptions.getSelectedLineTypes().get(0));
    assertEquals("Hoch", lineOptions.getAttributeValues().get(0));
    assertEquals("2", lineOptions.getSelectedLineTypes().get(1));
    assertEquals("Mittel", lineOptions.getAttributeValues().get(1));
    assertEquals("3", lineOptions.getSelectedLineTypes().get(2));
    assertEquals("Gering", lineOptions.getAttributeValues().get(2));

    assertEquals("1_1", landscapeOptions.getSelectedLevelRangeColumnAxis());
    assertEquals("1_1", landscapeOptions.getSelectedLevelRangeRowAxis());

    // ID set in selectedResultIds:
    QueryResult contentQuery = memBean.getQueryResult(LandscapeOptionsBean.CONTENT_QUERY);
    assertEquals(1, contentQuery.getSelectedResultIds().length);
    assertEquals(ipuRel.getId(), contentQuery.getSelectedResultIds()[0]);
    assertEquals(Integer.valueOf(12), ipuRel.getId());
    LOGGER.info("Postprocessing: {0}", contentQuery.getSelectedPostProcessingStrategies());

    // No selected result ids
    assertEquals(2, memBean.getQueryResult(LandscapeOptionsBean.COLUMN_QUERY).getSelectedResultIds().length);
    // assertEquals(process.getId(), memBean.getColumnQuery().getSelectedResultIds()[0]);
    // assertEquals(process2.getId(), memBean.getColumnQuery().getSelectedResultIds()[1]);

    // ID set in selectedResultIds:
    // 2 Units where found, but only one is in selected id array.
    QueryResult rowQuery = memBean.getQueryResult(LandscapeOptionsBean.ROW_QUERY);
    assertEquals(1, rowQuery.getSelectedResultIds().length);
    assertEquals(bu.getId(), rowQuery.getSelectedResultIds()[0]);
    assertEquals(Integer.valueOf(15), bu.getId());

    assertFalse(landscapeOptions.isColumnAxisScalesWithContent());

    // If an attribute id in the query doesn't exist anymore in DB, then it has to be substituted by
    // -1 otherwise query can not be loaded; here attribute with id=4 is no longer available,
    // so test checks if it is substituted by blank attribute in order to load query.
    assertEquals("blank_null_-1", rowQuery.getQueryForms().get(0).getQueryUserInput().getQueryFirstLevels()
            .get(0).getQuerySecondLevels().get(0).getChosenAttributeStringId());
}