Example usage for java.util Locale getDisplayCountry

List of usage examples for java.util Locale getDisplayCountry

Introduction

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

Prototype

public final String getDisplayCountry() 

Source Link

Document

Returns a name for the locale's country that is appropriate for display to the user.

Usage

From source file:eu.seaclouds.platform.discoverer.crawler.CloudTypes.java

private String expandCountryCode(String cc) {
    Locale l = new Locale("", cc);
    return l.getDisplayCountry();
}

From source file:de.hybris.platform.acceleratorservices.web.payment.controllers.HostedOrderPageMockController.java

@ModelAttribute("billingCountries")
public List<SelectOption> getBillingCountries() {
    final List<SelectOption> countries = new ArrayList<SelectOption>();
    final Locale[] locales = Locale.getAvailableLocales();
    final Map<String, String> countryMap = new HashMap<String, String>();

    for (final Locale locale : locales) {
        final String code = locale.getCountry();
        final String name = locale.getDisplayCountry();

        // putting in a map to remove duplicates
        if (StringUtils.isNotBlank(code) && StringUtils.isNotBlank(name)) {
            countryMap.put(code, name);//from   ww w .j  ava2 s. c  o  m
        }
    }

    for (final String key : countryMap.keySet()) {
        countries.add(new SelectOption(key, countryMap.get(key)));
    }

    Collections.sort(countries, CountryComparator.INSTANCE);

    return countries;
}

From source file:info.magnolia.templating.elements.InitElement.java

@Override
public void begin(Appendable out) throws IOException, RenderException {
    if (!isAdmin()) {
        return;//from  w  w  w .  ja  v a 2 s  .  com
    }

    Node content = getPassedContent();
    if (content == null) {
        content = currentContent();
    }

    TemplateDefinition templateDefinition = getRequiredTemplateDefinition();

    dialog = resolveDialog(templateDefinition);

    Sources src = new Sources(MgnlContext.getContextPath());
    MarkupHelper helper = new MarkupHelper(out);
    helper.append("<!-- begin js and css added by @cms.init -->\n");
    helper.append("<meta name=\"gwt:property\" content=\"locale=" + i18nContentSupport.getLocale() + "\"/>\n");
    helper.append(src.getHtmlCss());
    helper.append(src.getHtmlJs());
    //TODO see SCRUM-1239, we will probably get rid of the init tag in 5.0
    //helper.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PAGE_EDITOR_CSS + "\"></link>\n");
    //helper.append("<script type=\"text/javascript\" src=\"" + PAGE_EDITOR_JS_SOURCE + "\"></script>\n");

    helper.openComment(CMS_PAGE_TAG);
    if (content != null) {
        helper.attribute(AreaDirective.CONTENT_ATTRIBUTE, getNodePath(content));
    }
    helper.attribute("dialog", dialog);
    helper.attribute("preview", String.valueOf(MgnlContext.getAggregationState().isPreviewMode()));

    //here we provide the page editor with the available locales and their respective URI for the current page
    if (i18nAuthoringSupport.isEnabled() && i18nContentSupport.isEnabled()
            && i18nContentSupport.getLocales().size() > 1) {

        Content currentPage = MgnlContext.getAggregationState().getMainContent();
        String currentUri = createURI(currentPage, i18nContentSupport.getLocale());
        helper.attribute("currentURI", currentUri);

        List<String> availableLocales = new ArrayList<String>();

        for (Locale locale : i18nContentSupport.getLocales()) {
            String uri = createURI(currentPage, locale);
            String label = StringUtils.capitalize(locale.getDisplayLanguage(locale));
            if (StringUtils.isNotEmpty(locale.getCountry())) {
                label += " (" + StringUtils.capitalize(locale.getDisplayCountry()) + ")";
            }
            availableLocales.add(label + ":" + uri);
        }

        helper.attribute("availableLocales", StringUtils.join(availableLocales, ","));
    }

    helper.append(" -->\n");
    helper.closeComment(CMS_PAGE_TAG);

}

From source file:edu.cornell.mannlib.vitro.webapp.filters.WebappDaoFactorySparqlPrep.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if (request.getAttribute("WebappDaoFactorySDBPrep.setup") != null) {
        // don't run multiple times
        filterChain.doFilter(request, response);
        return;//from ww  w .  java 2  s .co  m
    }

    for (Pattern skipPattern : skipPatterns) {
        Matcher match = skipPattern.matcher(((HttpServletRequest) request).getRequestURI());
        if (match.matches()) {
            log.debug("request matched a skipPattern, skipping VitroRequestPrep");
            filterChain.doFilter(request, response);
            return;
        }
    }

    javax.sql.DataSource ds = JenaDataSourceSetupBase.getApplicationDataSource(_ctx);
    StoreDesc storeDesc = (StoreDesc) _ctx.getAttribute("storeDesc");
    OntModelSelector oms = (OntModelSelector) _ctx.getAttribute("unionOntModelSelector");
    String defaultNamespace = (String) _ctx.getAttribute("defaultNamespace");
    Connection sqlConn = null;
    SDBConnection conn = null;
    Store store = null;
    Dataset dataset = null;
    WebappDaoFactory wadf = null;

    try {
        if (ds == null || storeDesc == null || oms == null) {
            throw new RuntimeException("SDB store not property set up");
        }

        try {
            sqlConn = ds.getConnection();
            conn = new SDBConnection(sqlConn);
        } catch (SQLException sqe) {
            throw new RuntimeException("Unable to connect to database", sqe);
        }
        if (conn != null) {
            store = SDBFactory.connectStore(conn, storeDesc);
            dataset = SDBFactory.connectDataset(store);
            VitroRequest vreq = new VitroRequest((HttpServletRequest) request);

            log.info("---------");

            Enumeration<String> headStrs = vreq.getHeaderNames();
            while (headStrs.hasMoreElements()) {
                String head = headStrs.nextElement();
                log.info(head + " : " + vreq.getHeader(head));
            }

            List<String> langs = new ArrayList<String>();

            log.info("Accept-Language: " + vreq.getHeader("Accept-Language"));
            Enumeration<Locale> locs = vreq.getLocales();
            while (locs.hasMoreElements()) {
                Locale locale = locs.nextElement();
                langs.add(locale.toString().replace("_", "-"));
                log.info(locale.toString() + " / " + locale.getLanguage() + " + " + locale.getCountry() + " : "
                        + locale.getDisplayCountry() + " | " + locale.getLanguage() + " : "
                        + locale.getDisplayLanguage());
            }
            WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
            config.setDefaultNamespace(defaultNamespace);
            config.setPreferredLanguages(langs);

            //okay let's make a graph-backed model
            String endpointURI = ConfigurationProperties.getBean(request)
                    .getProperty("VitroConnection.DataSource.endpointURI");

            Graph g = new SparqlGraphMultilingual(endpointURI, langs);
            //Graph g = new SparqlGraph(endpointURI);

            Model m = ModelFactory.createModelForGraph(g);
            OntModel om = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, m);
            oms = new SingleContentOntModelSelector(om, oms.getDisplayModel(), oms.getUserAccountsModel());

            dataset = DatasetFactory.create(new SparqlDatasetGraph(endpointURI));

            //DataSource datasource = DatasetFactory.create();
            //datasource.addNamedModel("fake:fake", m);
            //dataset = datasource;         

            vreq.setAssertionsWebappDaoFactory(wadf);

            wadf = new WebappDaoFactoryJena(oms, config);
            //wadf = new WebappDaoFactorySDB(oms, dataset, config);
            vreq.setWebappDaoFactory(wadf);
            vreq.setFullWebappDaoFactory(wadf);
            vreq.setUnfilteredWebappDaoFactory(wadf);
            vreq.setWebappDaoFactory(wadf);
            vreq.setDataset(dataset);
            vreq.setJenaOntModel(om);
            vreq.setOntModelSelector(oms);
        }
    } catch (Throwable t) {
        log.error("Unable to filter request to set up SDB connection", t);
    }

    request.setAttribute("WebappDaoFactorySDBPrep.setup", 1);

    try {
        filterChain.doFilter(request, response);
        return;
    } finally {
        if (conn != null) {
            conn.close();
        }
        if (dataset != null) {
            dataset.close();
        }
        if (store != null) {
            store.close();
        }
        if (wadf != null) {
            wadf.close();
        }
    }

}

From source file:no.abmu.common.locale.LocaleUtil.java

/**
 * Method for logging of locale. Used under test and development.
 * /*from   ww w .ja  v a 2  s.  c  om*/
 * @param request current HTTP request
 */

public void logLocale(HttpServletRequest request) {
    HttpSession session = request.getSession(false);

    String parameterSiteLocale = request.getParameter("siteLocale");
    String parameterStartLocale = request.getParameter("startLocale");
    String rcSiteLocale = (String) request.getAttribute("siteLocale");
    //        String seSiteLocale = (String) session.getAttribute("siteLocale");

    Locale locale = RequestContextUtils.getLocale(request);

    logger.info("request siteLocale: " + rcSiteLocale);
    logger.info("request parameter siteLocale: " + parameterSiteLocale);
    logger.info("request parameter startLocale: " + parameterStartLocale);
    //        logger.info("session siteLocale: " + seSiteLocale);

    logger.info("Locale getDisplayCountry: " + locale.getDisplayCountry());
    logger.info("Locale getDisplayLanguage: " + locale.getDisplayLanguage());
    logger.info("Locale getDisplayVariant: " + locale.getDisplayVariant());
    logger.info("Locale getDisplayName: " + locale.getDisplayName());
    logger.info("Locale getISO3Country: " + locale.getISO3Country());
    logger.info("Locale getLanguage: " + locale.getLanguage());
    logger.info("Locale getVariant: " + locale.getVariant());
    logger.info("Locale toString: " + locale.toString());

}

From source file:edu.uchicago.duo.web.DuoEnrollController.java

/**
 * *********************************************************************
 * Below are ALL FOR creating the International Dial Code Drop Down list
 *
 * Used in: DuoEnrollStep3.jsp//from  ww  w. j  a  va2s  . c o m
 * *********************************************************************
 */
@ModelAttribute("countryDialList")
public Map<String, String> populatecountryDialList() {

    List<DuoEnrollController.Country> countries = new ArrayList<>();
    Map<String, String> dialCodes = new LinkedHashMap<>();
    Map<String, String> sortedDialCodes = new LinkedHashMap<>();

    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();

    //
    // Get ISO countries, create Country object and
    // store in the collection.
    //
    String[] isoCountries = Locale.getISOCountries();
    for (String country : isoCountries) {
        Locale locale = new Locale("en", country);
        String code = locale.getCountry();
        String name = locale.getDisplayCountry();

        if (!"".equals(code) && !"".equals(name)) {
            try {
                int dialCode = phoneUtil.parse("1112223333", code).getCountryCode();
                countries.add(new DuoEnrollController.Country(code, name, dialCode));
            } catch (Exception e) {
            }
        }
    }

    Collections.sort(countries, new DuoEnrollController.CountryComparator());

    for (DuoEnrollController.Country country : countries) {
        dialCodes.put("+" + String.valueOf(country.dialCode), country.name);
        //dialCodes.put("+"+String.valueOf(country.code), country.name);
    }

    sortedDialCodes = sortByValue(dialCodes);

    return sortedDialCodes;
}

From source file:eu.eubrazilcc.lvl.core.NCBIXmlBindingTest.java

@Test
public void test() {
    System.out.println("NCBIXmlBindingTest.test()");
    try {/*from  w  w  w.ja  va2 s  .  c  o m*/
        // test parsing GenInfo identifier
        final String[] ids = { "gb|JQ790522.1|", "gi|384562886", "gi|", "gi|JQ790522", "gi" };
        final Integer[] gis = { null, 384562886, null, null, null };
        final GBSeq gbSeq = GBSEQ_XML_FACTORY.createGBSeq();
        gbSeq.setGBSeqOtherSeqids(GBSEQ_XML_FACTORY.createGBSeqOtherSeqids());
        gbSeq.getGBSeqOtherSeqids().getGBSeqid().add(GBSEQ_XML_FACTORY.createGBSeqid());
        for (int i = 0; i < ids.length; i++) {
            gbSeq.getGBSeqOtherSeqids().getGBSeqid().get(0).setvalue(ids[i]);
            final Integer gi = getGenInfoIdentifier(gbSeq);
            assertThat("gi coincides with expected", gi, equalTo(gis[i]));
        }

        // test inferring location from the country feature stored in GenBank records
        final String[] features = { "Italy", "Spain:Almeria", "Sudan: Sirougia, Khartoum State" };
        final Locale[] countries = { getLocale("Italy"), getLocale("Spain"), getLocale("Sudan") };
        gbSeq.setGBSeqFeatureTable(GBSEQ_XML_FACTORY.createGBSeqFeatureTable());
        gbSeq.getGBSeqFeatureTable().getGBFeature().add(GBSEQ_XML_FACTORY.createGBFeature());
        gbSeq.getGBSeqFeatureTable().getGBFeature().get(0)
                .setGBFeatureQuals(GBSEQ_XML_FACTORY.createGBFeatureQuals());
        gbSeq.getGBSeqFeatureTable().getGBFeature().get(0).getGBFeatureQuals().getGBQualifier()
                .add(GBSEQ_XML_FACTORY.createGBQualifier());
        gbSeq.getGBSeqFeatureTable().getGBFeature().get(0).getGBFeatureQuals().getGBQualifier().get(0)
                .setGBQualifierName("country");
        for (int i = 0; i < features.length; i++) {
            gbSeq.getGBSeqFeatureTable().getGBFeature().get(0).getGBFeatureQuals().getGBQualifier().get(0)
                    .setGBQualifierValue(features[i]);
            final ImmutableMultimap<String, Locale> countries2 = inferCountry(gbSeq);
            assertThat("inferred countries is not null", countries2, notNullValue());
            assertThat("inferred countries is not empty", !countries2.isEmpty());
            for (final String key : countries2.keySet()) {
                for (final Locale locale : countries2.get(key)) {
                    assertThat("inferred country coincides with expected", locale, equalTo(countries[i]));
                    /* uncomment to display additional output */
                    System.out.println(
                            "Inferred country: field=" + key + ", country=" + locale.getDisplayCountry());
                }
            }
        }

        // test parsing GenBank XML records
        Collection<File> files = getGBSeqXMLSetFiles();
        for (final File file : files) {
            System.out.println(" >> GenBank sequence set XML file: " + file.getCanonicalPath());
            final GBSet gbSet = GBSEQ_XMLB.typeFromFile(file);
            assertThat("GenBank XML set is not null", gbSet, notNullValue());
            assertThat("GenBank XML sequences is not null", gbSet.getGBSeq(), notNullValue());
            assertThat("GenBank XML sequences is not empty", !gbSet.getGBSeq().isEmpty());
            for (final GBSeq seq : gbSet.getGBSeq()) {
                assertThat("GenBank XML sequence accession is not empty",
                        isNotBlank(seq.getGBSeqPrimaryAccession()));
                assertThat("GenBank XML sequence definition is not empty",
                        isNotBlank(seq.getGBSeqDefinition()));
                assertThat("GenBank XML sequence version is not empty",
                        isNotBlank(seq.getGBSeqAccessionVersion()));
                assertThat("GenBank XML sequence organism is not empty", isNotBlank(seq.getGBSeqOrganism()));
                /* Uncomment for additional output */
                System.out.println(" >> Accession  : " + seq.getGBSeqPrimaryAccession());
                System.out.println(" >> Definition : " + seq.getGBSeqDefinition());
                System.out.println(" >> Version    : " + seq.getGBSeqAccessionVersion());
                System.out.println(" >> Organism   : " + seq.getGBSeqOrganism());
                System.out.println(" >> Length     : " + seq.getGBSeqLength());

                final Set<String> gene = getGeneNames(seq);
                if (gene != null) {
                    /* Uncomment for additional output */
                    System.out.println(" >> Gene names : " + gene);
                }

                final List<Reference> references = getPubMedReferences(seq);
                assertThat("References is not null", references, notNullValue());
                assertThat("References is not empty", references.isEmpty(), equalTo(false));
                /* Uncomment for additional output */
                System.out.println(" >> References : " + references);

                final Set<String> pmids = getPubMedIds(seq);
                assertThat("References PMIDS are not null", pmids, notNullValue());
                assertThat("References PMIDS are not empty", pmids.isEmpty(), equalTo(false));
                /* Uncomment for additional output */
                System.out.println(" >> Reference PMIDS : " + pmids);

                final Sequence sequence = parseSequence(seq, Sandfly.builder());
                assertThat("Sequence is not null", sequence, notNullValue());
                assertThat("Sequence data source is not empty", isNotBlank(sequence.getDataSource()));
                assertThat("Sequence accession is not empty", isNotBlank(sequence.getAccession()));
                assertThat("Sequence definition is not empty", isNotBlank(sequence.getDefinition()));
                assertThat("Sequence version is not empty", isNotBlank(sequence.getVersion()));
                assertThat("Sequence organism is not empty", isNotBlank(sequence.getOrganism()));
                /* Uncomment for additional output */
                System.out.println(" >> Sequence  : " + sequence.toString());
            }
        }

        // test parsing GenBank isolated sequences
        files = getGBSeqXMLFiles();
        for (final File file : files) {
            System.out.println(" >> GenBank sequence XML file: " + file.getCanonicalPath());
            final GBSeq seq = GBSEQ_XMLB.typeFromFile(file);
            assertThat("GenBank XML sequence is not null", seq, notNullValue());
            assertThat("GenBank XML sequence accession is not empty",
                    isNotBlank(seq.getGBSeqPrimaryAccession()));
            assertThat("GenBank XML sequence definition is not empty", isNotBlank(seq.getGBSeqDefinition()));
            assertThat("GenBank XML sequence version is not empty", isNotBlank(seq.getGBSeqAccessionVersion()));
            assertThat("GenBank XML sequence organism is not empty", isNotBlank(seq.getGBSeqOrganism()));
            /* Uncomment for additional output */
            System.out.println(" >> Accession  : " + seq.getGBSeqPrimaryAccession());
            System.out.println(" >> Definition : " + seq.getGBSeqDefinition());
            System.out.println(" >> Version    : " + seq.getGBSeqAccessionVersion());
            System.out.println(" >> Organism   : " + seq.getGBSeqOrganism());
            System.out.println(" >> Length     : " + seq.getGBSeqLength());

            final Set<String> gene = getGeneNames(seq);
            if (gene != null) {
                /* Uncomment for additional output */
                System.out.println(" >> Gene names : " + gene);
            }

            final List<Reference> references = getPubMedReferences(seq);
            assertThat("References is not null", references, notNullValue());
            assertThat("References is not empty", references.isEmpty(), equalTo(false));
            /* Uncomment for additional output */
            System.out.println(" >> References : " + references);

            final Set<String> pmids = getPubMedIds(seq);
            assertThat("References PMIDS are not null", pmids, notNullValue());
            assertThat("References PMIDS are not empty", pmids.isEmpty(), equalTo(false));
            /* Uncomment for additional output */
            System.out.println(" >> Reference PMIDS : " + pmids);

            final Sequence sequence = parseSequence(seq, Sandfly.builder());
            assertThat("Sequence is not null", sequence, notNullValue());
            assertThat("Sequence data source is not empty", isNotBlank(sequence.getDataSource()));
            assertThat("Sequence accession is not empty", isNotBlank(sequence.getAccession()));
            assertThat("Sequence definition is not empty", isNotBlank(sequence.getDefinition()));
            assertThat("Sequence version is not empty", isNotBlank(sequence.getVersion()));
            assertThat("Sequence organism is not empty", isNotBlank(sequence.getOrganism()));
            /* Uncomment for additional output */
            System.out.println(" >> Sequence  : " + sequence.toString());
        }

        // test parsing PubMed XML records
        files = getPubMedXMLSetFiles();
        for (final File file : files) {
            System.out.println(" >> PubMed article set XML file: " + file.getCanonicalPath());
            final PubmedArticleSet articleSet = PUBMED_XMLB.typeFromFile(file);
            assertThat("PubMed XML set is not null", articleSet, notNullValue());
            assertThat("PubMed XML articles is not null", articleSet.getPubmedArticle(), notNullValue());
            assertThat("PubMed XML articles is not empty", !articleSet.getPubmedArticle().isEmpty());
            for (final PubmedArticle article : articleSet.getPubmedArticle()) {
                assertThat("PubMed XML article MEDLINE citation is not null", article.getMedlineCitation(),
                        notNullValue());
                assertThat("PubMed XML article is not null", article.getMedlineCitation().getArticle(),
                        notNullValue());
                assertThat("PubMed XML article title is not empty",
                        isNotBlank(article.getMedlineCitation().getArticle().getArticleTitle()));
                assertThat("PubMed XML article PMID is not null", article.getMedlineCitation().getPMID(),
                        notNullValue());
                assertThat("PubMed XML article PMID is not empty",
                        isNotBlank(article.getMedlineCitation().getPMID().getvalue()));
                assertThat("PubMed XML article journal is not null",
                        article.getMedlineCitation().getArticle().getJournal(), notNullValue());
                assertThat("PubMed XML article journal issue is not null",
                        article.getMedlineCitation().getArticle().getJournal().getJournalIssue(),
                        notNullValue());
                assertThat("PubMed XML article journal publication date is not null",
                        article.getMedlineCitation().getArticle().getJournal().getJournalIssue().getPubDate(),
                        notNullValue());
                assertThat("PubMed XML article journal publication year is not null",
                        article.getMedlineCitation().getArticle().getJournal().getJournalIssue().getPubDate()
                                .getYearOrMonthOrDayOrSeasonOrMedlineDate(),
                        notNullValue());
                assertThat("PubMed XML article journal publication year is not empty",
                        article.getMedlineCitation().getArticle().getJournal().getJournalIssue().getPubDate()
                                .getYearOrMonthOrDayOrSeasonOrMedlineDate().isEmpty(),
                        equalTo(false));
                /* Uncomment for additional output */
                System.out
                        .println(" >> Title : " + article.getMedlineCitation().getArticle().getArticleTitle());
                System.out.println(" >> PMID  : " + article.getMedlineCitation().getPMID().getvalue());

                final Reference reference = parseArticle(article);
                assertThat("Reference is not null", reference, notNullValue());
                assertThat("Reference title is not empty", isNotBlank(reference.getTitle()));
                assertThat("Reference PMID is not empty", isNotBlank(reference.getPubmedId()));
                assertThat("Reference publication year coincides with expected",
                        reference.getPublicationYear() > 1900, equalTo(true));
                /* Uncomment for additional output */
                System.out.println(" >> Reference  : " + reference.toString());
            }
        }

        // test parsing GenBank isolated articles
        files = getPubMedXMLFiles();
        for (final File file : files) {
            System.out.println(" >> PubMed article XML file: " + file.getCanonicalPath());
            final PubmedArticle article = PUBMED_XMLB.typeFromFile(file);
            assertThat("PubMed XML article MEDLINE citation is not null", article.getMedlineCitation(),
                    notNullValue());
            assertThat("PubMed XML article is not null", article.getMedlineCitation().getArticle(),
                    notNullValue());
            assertThat("PubMed XML article title is not empty",
                    isNotBlank(article.getMedlineCitation().getArticle().getArticleTitle()));
            assertThat("PubMed XML article PMID is not null", article.getMedlineCitation().getPMID(),
                    notNullValue());
            assertThat("PubMed XML article PMID is not empty",
                    isNotBlank(article.getMedlineCitation().getPMID().getvalue()));
            assertThat("PubMed XML article journal is not null",
                    article.getMedlineCitation().getArticle().getJournal(), notNullValue());
            assertThat("PubMed XML article journal issue is not null",
                    article.getMedlineCitation().getArticle().getJournal().getJournalIssue(), notNullValue());
            assertThat("PubMed XML article journal publication date is not null",
                    article.getMedlineCitation().getArticle().getJournal().getJournalIssue().getPubDate(),
                    notNullValue());
            assertThat("PubMed XML article journal publication year is not null",
                    article.getMedlineCitation().getArticle().getJournal().getJournalIssue().getPubDate()
                            .getYearOrMonthOrDayOrSeasonOrMedlineDate(),
                    notNullValue());
            assertThat("PubMed XML article journal publication year is not empty",
                    article.getMedlineCitation().getArticle().getJournal().getJournalIssue().getPubDate()
                            .getYearOrMonthOrDayOrSeasonOrMedlineDate().isEmpty(),
                    equalTo(false));
            /* Uncomment for additional output */
            System.out.println(" >> Title : " + article.getMedlineCitation().getArticle().getArticleTitle());
            System.out.println(" >> PMID  : " + article.getMedlineCitation().getPMID().getvalue());

            final Reference reference = parseArticle(article);
            assertThat("Reference is not null", reference, notNullValue());
            assertThat("Reference title is not empty", isNotBlank(reference.getTitle()));
            assertThat("Reference PMID is not empty", isNotBlank(reference.getPubmedId()));
            assertThat("Reference publication year coincides with expected",
                    reference.getPublicationYear() > 1900, equalTo(true));
            /* Uncomment for additional output */
            System.out.println(" >> Reference  : " + reference.toString());
        }

        // test parsing Taxonomy XML records
        files = getTaxonomyXMLSetFiles();
        for (final File file : files) {
            System.out.println(" >> Taxonomy set XML file: " + file.getCanonicalPath());
            final TaxaSet taxaSet = TAXONOMY_XMLB.typeFromFile(file);
            assertThat("Taxonomy XML set is not null", taxaSet, notNullValue());
            assertThat("Taxonomy XML taxons is not null", taxaSet.getTaxon(), notNullValue());
            assertThat("Taxonomy XML taxons is not empty", !taxaSet.getTaxon().isEmpty());
            // TODO : complete
        }

    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("NCBIXmlBindingTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("NCBIXmlBindingTest.test() has finished");
    }
}

From source file:org.tdl.vireo.search.impl.LuceneAbstractJobImpl.java

/**
 * Write a the provided submission and all associated action logs to the
 * index writer. This method expects that the submission and action logs
 * have been removed from the index, either through a specific delete,
 * or a delete all in the case of rebuilding the index.
 * // w  w  w  .j  av  a 2  s . c o  m
 * This method is used to share code between the various index job
 * implementations so that submissions are written the same no matter
 * who indexes them first.
 * 
 * @param writer
 *            The index writer.
 * @param sub
 *            The submission to index.
 */
public void indexSubmission(IndexWriter writer, Submission sub) throws CorruptIndexException, IOException {

    StringBuilder searchText = new StringBuilder();

    long subId = sub.getId();

    String state = sub.getState().getDisplayName();
    searchText.append(state).append(" ");

    long searchAssigned = 0;
    String sortAssigned = "";
    if (sub.getAssignee() != null) {
        searchAssigned = sub.getAssignee().getId();
        sortAssigned = sub.getAssignee().getFormattedName(NameFormat.LAST_FIRST_MIDDLE_BIRTH);
        searchText.append(sortAssigned).append(" ");
    }

    Date graduationSemester = null;
    if (sub.getGraduationYear() != null) {
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, sub.getGraduationYear());
        if (sub.getGraduationMonth() != null)
            cal.set(Calendar.MONTH, sub.getGraduationMonth());

        graduationSemester = cal.getTime();
    }

    Date defenseDate = sub.getDefenseDate();

    String department = sub.getDepartment();
    String program = sub.getProgram();
    String college = sub.getCollege();
    String major = sub.getMajor();
    searchText.append(department).append(" ").append(program).append(" ").append(college).append(" ")
            .append(major).append(" ");

    String embargo = null;
    if (sub.getEmbargoType() != null) {
        embargo = sub.getEmbargoType().getName();
        searchText.append(embargo).append(" ");
    }

    String degree = sub.getDegree();
    String documentType = sub.getDocumentType();
    searchText.append(degree).append(" ").append(documentType).append(" ");

    Date submissionDate = sub.getSubmissionDate();

    String studentName = "";
    if (sub.getStudentLastName() != null)
        studentName += sub.getStudentLastName() + " ";
    if (sub.getStudentFirstName() != null)
        studentName += sub.getStudentFirstName() + " ";
    if (sub.getStudentMiddleName() != null)
        studentName += sub.getStudentMiddleName() + " ";
    searchText.append(studentName).append(" ");

    searchText.append(sub.getStudentFormattedName(NameFormat.LAST_FIRST_BIRTH)).append(" ");
    searchText.append(sub.getStudentFormattedName(NameFormat.FIRST_LAST_BIRTH)).append(" ");

    String studentEmail = sub.getSubmitter().getEmail();
    searchText.append(studentEmail).append(" ");

    String institutionalIdentifier = sub.getSubmitter().getInstitutionalIdentifier();
    searchText.append(institutionalIdentifier).append(" ");

    String documentTitle = sub.getDocumentTitle();
    String documentAbstract = sub.getDocumentAbstract();
    String documentKeywords = sub.getDocumentKeywords();
    searchText.append(documentTitle).append(" ").append(documentAbstract).append(" ").append(documentKeywords)
            .append(" ");

    String documentSubjects = "";
    for (String subject : sub.getDocumentSubjects()) {
        documentSubjects += subject + " ";
    }
    searchText.append(documentSubjects).append(" ");

    String documentLanguage = null;
    if (sub.getDocumentLanguageLocale() != null) {
        Locale locale = sub.getDocumentLanguageLocale();
        searchText.append(locale.getDisplayName()).append(" ");
        searchText.append(locale.getDisplayLanguage()).append(" ");
        searchText.append(locale.getDisplayCountry()).append(" ");
        searchText.append(locale.getDisplayVariant()).append(" ");

        documentLanguage = locale.getDisplayName();
    }

    String publishedMaterial = sub.getPublishedMaterial();
    searchText.append(publishedMaterial).append(" ");

    String primaryDocument = null;
    if (sub.getPrimaryDocument() != null) {
        primaryDocument = sub.getPrimaryDocument().getName();
        searchText.append(primaryDocument).append(" ");
    }

    Date licenseAgreementDate = sub.getLicenseAgreementDate();
    Date approvalDate = sub.getApprovalDate();
    Date committeeApprovalDate = sub.getCommitteeApprovalDate();
    Date committeeEmbargoApprovalDate = sub.getCommitteeEmbargoApprovalDate();

    String committeeMembers = "";
    for (CommitteeMember member : sub.getCommitteeMembers()) {
        // TODO: sort by display order?
        committeeMembers += member.getFormattedName(NameFormat.LAST_FIRST) + " " + member.getFormattedRoles();
    }
    searchText.append(committeeMembers).append(" ");

    String committeeContactEmail = sub.getCommitteeContactEmail();
    searchText.append(committeeContactEmail).append(" ");

    String umiRelease;
    if (sub.getUMIRelease() == null) {
        umiRelease = "";
    } else if (sub.getUMIRelease()) {
        umiRelease = "yes";
    } else {
        umiRelease = "no";
    }

    int customActions = 0;
    for (CustomActionValue action : sub.getCustomActions()) {
        if (action.getValue())
            customActions++;
    }

    String degreeLevel = null;
    if (sub.getDegreeLevel() != null)
        degreeLevel = sub.getDegreeLevel().name();
    searchText.append(degreeLevel).append(" ");

    String depositId = sub.getDepositId();
    searchText.append(depositId).append(" ");

    String reviewerNotes = sub.getReviewerNotes();
    searchText.append(reviewerNotes).append(" ");

    String lastEventEntry = null;
    Date lastEventTime = null;

    List<ActionLog> logs = indexer.subRepo.findActionLog(sub);
    if (logs.size() > 0) {
        lastEventEntry = logs.get(0).getEntry();
        lastEventTime = logs.get(0).getActionDate();
        searchText.append(lastEventEntry);
    }

    Document doc = new Document();

    doc.add(new NumericField("subId", Field.Store.YES, true).setLongValue(subId));
    doc.add(new Field("type", "submission", Field.Store.YES, Index.NOT_ANALYZED));
    doc.add(new Field("searchText", searchText.toString(), Field.Store.NO, Index.ANALYZED_NO_NORMS));
    if (state != null)
        doc.add(new Field("state", state, Field.Store.NO, Index.NOT_ANALYZED));

    doc.add(new NumericField("searchAssigned", Field.Store.NO, true).setLongValue(searchAssigned));

    if (sortAssigned != null)
        doc.add(new Field("sortAssigned", sortAssigned, Field.Store.NO, Index.NOT_ANALYZED));

    if (graduationSemester != null)
        doc.add(new NumericField("graduationSemester", Field.Store.NO, true)
                .setLongValue(graduationSemester.getTime()));

    if (defenseDate != null)
        doc.add(new NumericField("defenseDate", Field.Store.NO, true).setLongValue(defenseDate.getTime()));

    if (department != null)
        doc.add(new Field("department", department, Field.Store.NO, Index.NOT_ANALYZED));

    if (program != null)
        doc.add(new Field("program", program, Field.Store.NO, Index.NOT_ANALYZED));

    if (college != null)
        doc.add(new Field("college", college, Field.Store.NO, Index.NOT_ANALYZED));

    if (major != null)
        doc.add(new Field("major", major, Field.Store.NO, Index.NOT_ANALYZED));

    if (embargo != null)
        doc.add(new Field("embargo", embargo, Field.Store.NO, Index.NOT_ANALYZED));

    if (degree != null)
        doc.add(new Field("degree", degree, Field.Store.NO, Index.NOT_ANALYZED));

    if (documentType != null)
        doc.add(new Field("documentType", documentType, Field.Store.NO, Index.NOT_ANALYZED));

    if (submissionDate != null)
        doc.add(new NumericField("submissionDate", Field.Store.NO, true)
                .setLongValue(submissionDate.getTime()));

    if (studentName != null)
        doc.add(new Field("studentName", studentName, Field.Store.NO, Index.NOT_ANALYZED));

    if (studentEmail != null)
        doc.add(new Field("studentEmail", studentEmail, Field.Store.NO, Index.NOT_ANALYZED));

    if (institutionalIdentifier != null)
        doc.add(new Field("institutionalIdentifier", institutionalIdentifier, Field.Store.NO,
                Index.NOT_ANALYZED));

    if (documentTitle != null)
        doc.add(new Field("documentTitle", documentTitle, Field.Store.NO, Index.NOT_ANALYZED));

    if (documentAbstract != null)
        doc.add(new Field("documentAbstract", documentAbstract, Field.Store.NO, Index.NOT_ANALYZED));

    if (documentKeywords != null)
        doc.add(new Field("documentKeywords", documentKeywords, Field.Store.NO, Index.NOT_ANALYZED));

    if (documentSubjects != null)
        doc.add(new Field("documentSubjects", documentSubjects, Field.Store.NO, Index.NOT_ANALYZED));

    if (documentLanguage != null)
        doc.add(new Field("documentLanguage", documentLanguage, Field.Store.NO, Index.NOT_ANALYZED));

    if (publishedMaterial != null)
        doc.add(new Field("publishedMaterial", publishedMaterial, Field.Store.NO, Index.NOT_ANALYZED));

    if (primaryDocument != null)
        doc.add(new Field("primaryDocument", primaryDocument, Field.Store.NO, Index.NOT_ANALYZED));

    if (licenseAgreementDate != null)
        doc.add(new NumericField("licenseAgreementDate", Field.Store.NO, true)
                .setLongValue(licenseAgreementDate.getTime()));

    if (approvalDate != null)
        doc.add(new NumericField("approvalDate", Field.Store.NO, true).setLongValue(approvalDate.getTime()));

    if (committeeApprovalDate != null)
        doc.add(new NumericField("committeeApprovalDate", Field.Store.NO, true)
                .setLongValue(committeeApprovalDate.getTime()));

    if (committeeEmbargoApprovalDate != null)
        doc.add(new NumericField("committeeEmbargoApprovalDate", Field.Store.NO, true)
                .setLongValue(committeeEmbargoApprovalDate.getTime()));

    if (committeeMembers != null)
        doc.add(new Field("committeeMembers", committeeMembers, Field.Store.NO, Index.NOT_ANALYZED));

    if (committeeContactEmail != null)
        doc.add(new Field("committeeContactEmail", committeeContactEmail, Field.Store.NO, Index.NOT_ANALYZED));

    if (umiRelease != null)
        doc.add(new Field("umiRelease", umiRelease, Field.Store.NO, Index.NOT_ANALYZED));

    doc.add(new NumericField("customActions", Field.Store.NO, true).setIntValue(customActions));

    if (degreeLevel != null)
        doc.add(new Field("degreeLevel", degreeLevel, Field.Store.NO, Index.NOT_ANALYZED));

    if (depositId != null)
        doc.add(new Field("depositId", depositId, Field.Store.NO, Index.NOT_ANALYZED));

    if (reviewerNotes != null)
        doc.add(new Field("reviewerNotes", reviewerNotes, Field.Store.NO, Index.NOT_ANALYZED));

    if (lastEventEntry != null)
        doc.add(new Field("lastEventEntry", lastEventEntry, Field.Store.NO, Index.NOT_ANALYZED));

    if (lastEventTime != null)
        doc.add(new NumericField("lastEventTime", Field.Store.NO, true).setLongValue(lastEventTime.getTime()));

    writer.addDocument(doc);

    for (ActionLog log : logs) {

        Long logId = log.getId();
        String logEntry = log.getEntry();
        String logState = log.getSubmissionState().getDisplayName();
        long logSearchAssigned = 0;
        String logSortAssigned = null;
        if (log.getPerson() != null) {
            logSearchAssigned = log.getPerson().getId();
            logSortAssigned = log.getPerson().getFormattedName(NameFormat.FIRST_LAST);
        }
        Date logTime = log.getActionDate();

        // The new special things for action logs.
        doc = new Document();
        doc.add(new NumericField("subId", Field.Store.YES, true).setLongValue(subId));
        doc.add(new NumericField("logId", Field.Store.YES, true).setLongValue(logId));
        doc.add(new Field("type", "actionlog", Field.Store.YES, Index.NOT_ANALYZED));

        if (logEntry != null)
            doc.add(new Field("searchText", logEntry, Field.Store.NO, Index.ANALYZED_NO_NORMS));

        if (logState != null)
            doc.add(new Field("state", logState, Field.Store.NO, Index.NOT_ANALYZED));

        doc.add(new NumericField("searchAssigned", Field.Store.NO, true).setLongValue(logSearchAssigned));

        if (logSortAssigned != null)
            doc.add(new Field("sortAssigned", logSortAssigned, Field.Store.NO, Index.NOT_ANALYZED));

        if (logEntry != null)
            doc.add(new Field("lastEventEntry", logEntry, Field.Store.NO, Index.NOT_ANALYZED));

        if (logTime != null)
            doc.add(new NumericField("lastEventTime", Field.Store.NO, true).setLongValue(logTime.getTime()));

        // Stuff that is the same as the submission.
        if (graduationSemester != null)
            doc.add(new NumericField("graduationSemester", Field.Store.NO, true)
                    .setLongValue(graduationSemester.getTime()));

        if (defenseDate != null)
            doc.add(new NumericField("defenseDate", Field.Store.NO, true).setLongValue(defenseDate.getTime()));

        if (department != null)
            doc.add(new Field("department", department, Field.Store.NO, Index.NOT_ANALYZED));

        if (program != null)
            doc.add(new Field("program", program, Field.Store.NO, Index.NOT_ANALYZED));

        if (college != null)
            doc.add(new Field("college", college, Field.Store.NO, Index.NOT_ANALYZED));

        if (major != null)
            doc.add(new Field("major", major, Field.Store.NO, Index.NOT_ANALYZED));

        if (embargo != null)
            doc.add(new Field("embargo", embargo, Field.Store.NO, Index.NOT_ANALYZED));

        if (degree != null)
            doc.add(new Field("degree", degree, Field.Store.NO, Index.NOT_ANALYZED));

        if (documentType != null)
            doc.add(new Field("documentType", documentType, Field.Store.NO, Index.NOT_ANALYZED));

        if (submissionDate != null)
            doc.add(new NumericField("submissionDate", Field.Store.NO, true)
                    .setLongValue(submissionDate.getTime()));

        if (studentName != null)
            doc.add(new Field("studentName", studentName, Field.Store.NO, Index.NOT_ANALYZED));

        if (studentEmail != null)
            doc.add(new Field("studentEmail", studentEmail, Field.Store.NO, Index.NOT_ANALYZED));

        if (institutionalIdentifier != null)
            doc.add(new Field("institutionalIdentifier", institutionalIdentifier, Field.Store.NO,
                    Index.NOT_ANALYZED));

        if (documentAbstract != null)
            doc.add(new Field("documentAbstract", documentAbstract, Field.Store.NO, Index.NOT_ANALYZED));

        if (documentKeywords != null)
            doc.add(new Field("documentKeywords", documentKeywords, Field.Store.NO, Index.NOT_ANALYZED));

        if (documentSubjects != null)
            doc.add(new Field("documentSubjects", documentSubjects, Field.Store.NO, Index.NOT_ANALYZED));

        if (documentLanguage != null)
            doc.add(new Field("documentLanguage", documentLanguage, Field.Store.NO, Index.NOT_ANALYZED));

        if (publishedMaterial != null)
            doc.add(new Field("publishedMaterial", publishedMaterial, Field.Store.NO, Index.NOT_ANALYZED));

        if (primaryDocument != null)
            doc.add(new Field("primaryDocument", primaryDocument, Field.Store.NO, Index.NOT_ANALYZED));

        if (licenseAgreementDate != null)
            doc.add(new NumericField("licenseAgreementDate", Field.Store.NO, true)
                    .setLongValue(licenseAgreementDate.getTime()));

        if (approvalDate != null)
            doc.add(new NumericField("approvalDate", Field.Store.NO, true)
                    .setLongValue(approvalDate.getTime()));

        if (committeeApprovalDate != null)
            doc.add(new NumericField("committeeApprovalDate", Field.Store.NO, true)
                    .setLongValue(committeeApprovalDate.getTime()));

        if (committeeEmbargoApprovalDate != null)
            doc.add(new NumericField("committeeEmbargoApprovalDate", Field.Store.NO, true)
                    .setLongValue(committeeEmbargoApprovalDate.getTime()));

        if (committeeMembers != null)
            doc.add(new Field("committeeMembers", committeeMembers, Field.Store.NO, Index.NOT_ANALYZED));

        if (committeeContactEmail != null)
            doc.add(new Field("committeeContactEmail", committeeContactEmail, Field.Store.NO,
                    Index.NOT_ANALYZED));

        if (umiRelease != null)
            doc.add(new Field("umiRelease", umiRelease, Field.Store.NO, Index.NOT_ANALYZED));

        doc.add(new NumericField("customActions", Field.Store.NO, true).setIntValue(customActions));

        if (degreeLevel != null)
            doc.add(new Field("degreeLevel", degreeLevel, Field.Store.NO, Index.NOT_ANALYZED));

        if (depositId != null)
            doc.add(new Field("depositId", depositId, Field.Store.NO, Index.NOT_ANALYZED));

        if (reviewerNotes != null)
            doc.add(new Field("reviewerNotes", reviewerNotes, Field.Store.NO, Index.NOT_ANALYZED));

        writer.addDocument(doc);

        // Detach the log so it dosn't keep stacking up in memory.
        log.detach();
    } // for logs
}

From source file:com.contact.ContactData.java

public ContactData(String id, String contextPath) {
    java.sql.Connection con = null;
    java.sql.PreparedStatement stmt = null;
    java.sql.ResultSet rs = null;
    try {//from   www  .j  av a2  s.c  o  m
        con = ControlPanelPool.getInstance().getConnection();
        stmt = con.prepareStatement("SELECT * FROM leadContact WHERE Id = ?");
        stmt.setString(1, id);
        rs = stmt.executeQuery();
        while (rs.next()) {
            name = rs.getString("Name");
            email = rs.getString("Email");
            website = rs.getString("WebSite");
            remoteAddress = rs.getString("RemoteAddress");
            address = rs.getString("Address");
            phone = rs.getString("Phone");
            businessName = rs.getString("BusinessName");
            source = rs.getString("Source");
        }
        stmt = con.prepareStatement(
                "SELECT * FROM leadContact WHERE (BusinessName = ? AND BusinessName != '' AND BusinessName != 'NA' AND BusinessName != 'N/A' AND BusinessName != '-' AND Id != ? AND Email != ?) OR (WebSite = ? AND WebSite != '' AND WebSite != '-' AND WebSite != 'NA' AND WebSite != 'N/A' AND Id != ? AND Email != ?)");
        stmt.setString(1, businessName);
        stmt.setString(2, id);
        stmt.setString(3, email);
        stmt.setString(4, website);
        stmt.setString(5, id);
        stmt.setString(6, email);
        rs = stmt.executeQuery();
        businessCollegues = "";
        while (rs.next()) {
            businessCollegues += "<a href=\"" + contextPath + "/contact?id=" + rs.getString("Id")
                    + "\" class=\"list-group-item\">" + rs.getString("Name") + "</a>\n";
        }
        businessNameHeader = "";
        if (businessName != null && !businessName.isEmpty()) {
            businessNameHeader = businessName + " Employees";
        }
        relatedIp = new ArrayList<>();
        if (email != null && !email.isEmpty()) {
            stmt = con.prepareStatement(
                    "SELECT RemoteAddress FROM LeadContact WHERE Id IN (SELECT Id FROM LeadContact WHERE Email = ?)");
            stmt.setString(1, email);
            rs = stmt.executeQuery();
            while (rs.next()) {
                relatedIp.add(rs.getString("RemoteAddress"));
            }
        }
        pageViews = new HashMap<>();
        totalPagesVisited = "0";
        totalClicks = "0";
        String relatedIps = "";
        if (relatedIp != null && !relatedIp.isEmpty()) {
            for (int i = 0; i < relatedIp.size(); i++) {
                stmt = con.prepareStatement(
                        "SELECT DISTINCT TOP 15 leadSession.pageTitle, leadSession.location, COUNT(*) as pageViews FROM leadSession WHERE remoteAddress = ? GROUP BY leadSession.pageTitle, leadSession.location ORDER BY COUNT(*) DESC");
                stmt.setString(1, relatedIp.get(i));
                rs = stmt.executeQuery();
                while (rs.next()) {
                    if (pageViews.containsKey(rs.getString("pageTitle"))) {
                        pageViews.get(rs.getString(
                                "pageTitle")).visitCount = (pageViews.get(rs.getString("pageTitle")).visitCount
                                        + rs.getInt("pageViews"));
                    } else {
                        pageViews.put(rs.getString("pageTitle"), new PageNamePair(rs.getString("pageTitle"),
                                rs.getString("location"), rs.getInt("pageViews")));
                    }
                }
                relatedIps += relatedIp.get(i) + "','";
            }
        }
        if (relatedIps != null && !relatedIps.isEmpty()) {
            stmt = con.prepareStatement(
                    "SELECT COUNT(*) AS pCount, COUNT(DISTINCT pageTitle) as dpCount FROM leadSession WHERE remoteAddress IN ('"
                            + relatedIps + "')");
            rs = stmt.executeQuery();
            while (rs.next()) {
                totalPagesVisited = rs.getString("dpCount");
                totalClicks = rs.getString("pCount");
            }
        }
        stmt = con.prepareStatement(
                "SELECT LeadOrganization.Id, LeadOrganization.Name, LeadOrganization.Address, LeadOrganization.City, LeadOrganization.StateProv, LeadOrganization.PostalCode, LeadOrganization.Country FROM LeadRemoteAddress, LeadOrganization WHERE ip = ? AND prefered = 1 AND LeadRemoteAddress.LeadOrganization_uid = LeadOrganization.Id");
        stmt.setString(1, remoteAddress);
        rs = stmt.executeQuery();
        networkOwner = "";
        geoLocation = "";
        while (rs.next()) {
            networkOwner = rs.getString("Name");
            Locale l = new Locale("", rs.getString("Country"));
            networkOwnerId = rs.getString("Id");
            geoLocation = rs.getString("Address") == null || rs.getString("Address").isEmpty() ? ""
                    : rs.getString("Address") + ", ";
            geoLocation += rs.getString("City") == null || rs.getString("City").isEmpty() ? ""
                    : rs.getString("City") + ", ";
            geoLocation += rs.getString("City") == null || rs.getString("StateProv").isEmpty() ? ""
                    : rs.getString("StateProv") + " ";
            geoLocation += rs.getString("City") == null || rs.getString("PostalCode").isEmpty() ? ""
                    : rs.getString("PostalCode") + ", ";
            geoLocation += l.getDisplayCountry();
        }
        detailedPageViews = "";
        stmt = con.prepareStatement("SELECT location, timeIn FROM leadSession WHERE remoteAddress IN ('"
                + relatedIps + "') ORDER BY Id DESC");
        rs = stmt.executeQuery();
        while (rs.next()) {
            detailedPageViews += "<a target=\"_blank\" href=\"" + rs.getString("location")
                    + "\" class=\"list-group-item\">\n"
                    + "                                        <i class=\"fa fa-link fa-fw\"></i> "
                    + rs.getString("location") + "\n"
                    + "                                        <span class=\"pull-right text-muted small\"><em>"
                    + rs.getString("timeIn") + "</em>\n" + "                                        </span>\n"
                    + "                                    </a>";
        }
        con.close();
    } catch (SQLException | PropertyVetoException | IOException ex) {
        Logger.getLogger(ContactData.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DbUtils.closeQuietly(con, stmt, rs);
    }
}

From source file:org.torproject.android.OrbotMainActivity.java

private void doLayout() {
    setContentView(R.layout.layout_main);

    setTitle(R.string.app_name);/*from  w w w.j  a  va 2 s  .co m*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, android.R.string.ok,
            android.R.string.cancel);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawer.setDrawerListener(mDrawerToggle);
    mDrawerToggle.syncState();

    mTxtOrbotLog = (TextView) findViewById(R.id.orbotLog);

    lblStatus = (TextView) findViewById(R.id.lblStatus);
    lblStatus.setOnLongClickListener(this);
    imgStatus = (ImageProgressView) findViewById(R.id.imgStatus);
    imgStatus.setOnLongClickListener(this);
    imgStatus.setOnTouchListener(this);

    downloadText = (TextView) findViewById(R.id.trafficDown);
    uploadText = (TextView) findViewById(R.id.trafficUp);

    downloadText.setText(formatCount(0) + " / " + formatTotal(0));
    uploadText.setText(formatCount(0) + " / " + formatTotal(0));

    // Gesture detection
    mGestureDetector = new GestureDetector(this, new MyGestureDetector());

    mBtnBrowser = (Button) findViewById(R.id.btnBrowser);
    mBtnBrowser.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            doTorCheck();

        }

    });

    mBtnBrowser.setEnabled(false);

    mBtnVPN = (ToggleButton) findViewById(R.id.btnVPN);

    boolean useVPN = Prefs.useVpn();
    mBtnVPN.setChecked(useVPN);

    //auto start VPN if VPN is enabled
    if (useVPN) {
        startActivity(new Intent(OrbotMainActivity.this, VPNEnableActivity.class));
    }

    mBtnVPN.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (mBtnVPN.isChecked())
                startActivity(new Intent(OrbotMainActivity.this, VPNEnableActivity.class));
            else
                stopVpnService();

        }

    });

    mBtnBridges = (ToggleButton) findViewById(R.id.btnBridges);
    mBtnBridges.setChecked(Prefs.bridgesEnabled());
    mBtnBridges.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (Build.CPU_ABI.contains("arm")) {
                promptSetupBridges(); //if ARM processor, show all bridge options

            } else {
                Toast.makeText(OrbotMainActivity.this,
                        R.string.note_only_standard_tor_bridges_work_on_intel_x86_atom_devices,
                        Toast.LENGTH_LONG).show();
                showGetBridgePrompt(""); //if other chip ar, only stock bridges are supported
            }
        }

    });

    String currentExit = Prefs.getExitNodes();
    int selIdx = -1;

    ArrayList<String> cList = new ArrayList<String>();
    cList.add(0, getString(R.string.vpn_default_world));

    for (int i = 0; i < TorServiceConstants.COUNTRY_CODES.length; i++) {
        Locale locale = new Locale("", TorServiceConstants.COUNTRY_CODES[i]);
        cList.add(locale.getDisplayCountry());

        if (currentExit.contains(TorServiceConstants.COUNTRY_CODES[i]))
            selIdx = i + 1;
    }

    spnCountries = (Spinner) findViewById(R.id.spinnerCountry);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cList);
    spnCountries.setAdapter(adapter);

    if (selIdx != -1)
        spnCountries.setSelection(selIdx);

    spnCountries.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            // your code here

            String country = null;

            if (position == 0)
                country = "";
            else
                country = '{' + TorServiceConstants.COUNTRY_CODES[position - 1] + '}';

            Intent torService = new Intent(OrbotMainActivity.this, TorService.class);
            torService.setAction(TorServiceConstants.CMD_SET_EXIT);
            torService.putExtra("exit", country);
            startService(torService);

        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });
}