Example usage for java.util Locale Locale

List of usage examples for java.util Locale Locale

Introduction

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

Prototype

public Locale(String language) 

Source Link

Document

Construct a locale from a language code.

Usage

From source file:me.philnate.textmanager.utils.PDFCreator.java

@SuppressWarnings("deprecation")
private void preparePDF() {
    try {/*from  w w  w . ja va  2  s.com*/
        File path = new File(SystemUtils.getUserDir(), "template");
        File template = new File(path, Setting.find("template").getValue());

        Velocity.setProperty("file.resource.loader.path", path.getAbsolutePath());
        Velocity.init();
        VelocityContext ctx = new VelocityContext();

        // User data/Settings
        for (Setting setting : ds.find(Setting.class).asList()) {
            ctx.put(setting.getKey(), setting.getValue());
        }

        NumberFormat format = NumberFormat.getNumberInstance(new Locale(Setting.find("locale").getValue()));
        // #60 always show 2 digits for fraction no matter if right most(s)
        // are zero
        format.setMinimumFractionDigits(2);
        format.setMaximumFractionDigits(2);
        ctx.put("number", format);
        // TODO update schema to have separate first and lastname
        // Customer data
        ctx.put("customer", customer);

        // General data
        ctx.put("month", new DateFormatSymbols().getMonths()[month]);
        ctx.put("math", new MathTool());
        // Billing data
        ctx.put("allItems", BillingItem.find(customer.getId(), year, month));
        ctx.put("billNo", bill.getBillNo());

        StringWriter writer = new StringWriter();
        Velocity.mergeTemplate(template.getName(), ctx, writer);
        File filledTemplate = new File(path, bill.getBillNo() + ".tex");
        FileUtils.writeStringToFile(filledTemplate, writer.toString(), "ISO-8859-1");

        ProcessBuilder pdfLatex = new ProcessBuilder(Setting.find("pdfLatex").getValue(),
                "-interaction nonstopmode", "-output-format pdf", filledTemplate.toString());

        // Saving template file (just in case it may be needed later
        GridFSFile texFile = tex.createFile(filledTemplate);
        texFile.put("month", month);
        texFile.put("year", year);
        texFile.put("customerId", customer.getId());
        texFile.save();

        pdfLatex.directory(path);
        String pdfPath = filledTemplate.toString().replaceAll("tex$", "pdf");
        if (0 == printOutputStream(pdfLatex)) {
            // display Bill in DocumentViewer
            new ProcessBuilder(Setting.find("pdfViewer").getValue(), pdfPath).start().waitFor();
            GridFSFile pdfFile = pdf.createFile(new File(pdfPath));
            pdfFile.put("month", month);
            pdfFile.put("year", year);
            pdfFile.put("customerId", customer.getId());
            pdf.remove(QueryBuilder.start("month").is(month).and("year").is(year).and("customerId")
                    .is(customer.getId()).get());
            pdfFile.save();
            File[] files = path.listFiles((FileFilter) new WildcardFileFilter(bill.getBillNo() + ".*"));
            for (File file : files) {
                FileUtils.forceDelete(file);
            }
        } else {
            new JOptionPane(
                    "Bei der Erstellung der Rechnung ist ein Fehler aufgetreten. Es wurde keine Rechnung erstellt.\n Bitte Schauen sie in die Logdatei fr nhere Fehlerinformationen.",
                    JOptionPane.ERROR_MESSAGE).setVisible(true);
        }
    } catch (IOException e) {
        Throwables.propagate(e);
    } catch (InterruptedException e) {
        Throwables.propagate(e);
    }
}

From source file:be.fedict.eid.dss.document.zip.ZIPDSSDocumentService.java

public DocumentVisualization visualizeDocument(byte[] document, String language, List<MimeType> mimeTypes,
        String documentViewerServlet) throws Exception {

    // get i18n//from  w  w  w.j av a 2 s  . co m
    ResourceBundle zipResourceBundle = ResourceBundle.getBundle("ZIPMessages", new Locale(language));

    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("<html>");
    stringBuilder.append("<head>");
    stringBuilder.append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
    stringBuilder.append("<title>ZIP package</title>");
    stringBuilder.append("</head>");
    stringBuilder.append("<body>");
    stringBuilder.append(String.format("<h2>%s</h2>", zipResourceBundle.getObject("zipTitle")));
    stringBuilder.append("<table>");
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            continue;
        }
        String zipEntryName = zipEntry.getName();

        boolean browserViewable = MimeTypeMapper.browserViewable(mimeTypes, zipEntryName);
        String image = browserViewable ? "view.png" : "download.png";

        stringBuilder.append("<tr>");
        stringBuilder.append("<td>");
        stringBuilder.append(String.format("<a href=\"%s\" target=_blank>",
                documentViewerServlet + getResourceId(zipEntry)));
        stringBuilder.append(
                "<img src=\"./images/" + image + "\" style=\" width: 25px; vertical-align: bottom;\" />");
        stringBuilder.append(zipEntryName);
        stringBuilder.append("</a>");

        stringBuilder.append("</td>");
        stringBuilder.append("</tr>");
    }
    stringBuilder.append("</table>");
    stringBuilder.append("</body></html>");

    return new DocumentVisualization("text/html;charset=utf-8", stringBuilder.toString().getBytes());
}

From source file:de.cosmocode.commons.converter.LocaleLanguageIsoConverter.java

@Override
public String toTwoLetter(String iso6392) {
    // sanity check on arguments
    Preconditions.checkNotNull(iso6392, "iso6392 must not be null");
    if (Patterns.ISO_639_1.matcher(iso6392).matches()) {
        // already ISO 639-1 (two letter)
        return iso6392;
    } else if (StringUtils.isBlank(iso6392)) {
        // this is here for convenience, to allow empty languages
        return TrimMode.EMPTY.apply(iso6392);
    }/*from w  w  w . j  a v a2 s . c  o m*/
    Preconditions.checkArgument(Patterns.ISO_639_2.matcher(iso6392).matches(),
            "Language Code %s not in ISO 639-2", iso6392);

    // try to get two letter code from cache
    final String fromCache = cache.get(iso6392);
    if (fromCache != null) {
        return fromCache;
    }

    // search for three letter code in the known language codes of Locale
    for (final String iso6391 : Locale.getISOLanguages()) {
        final String threeLetter = new Locale(iso6391).getISO3Language();
        if (iso6392.equals(threeLetter)) {
            LOG.trace("Found ISO 639-1 language code: {} for ISO 639-2 language code: {}", iso6391, iso6392);
            cache.put(iso6392, iso6391);
            return iso6391;
        }
    }

    // if we arrive here then the Locale class could not find the iso3 code
    throw new IsoConversionException("No known ISO 639-1 language code for " + iso6392);
}

From source file:at.alladin.rmbt.mapServer.MarkerResource.java

@Post("json")
public String request(final String entity) {
    addAllowOrigin();/*from   ww w  .j  a  v a  2  s .co  m*/

    final MapServerOptions mso = MapServerOptions.getInstance();
    final Classification classification = Classification.getInstance();

    JSONObject request = null;

    final JSONObject answer = new JSONObject();

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            String lang = request.optString("language");

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang))
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

            //                System.out.println(request.toString(4));

            final JSONObject coords = request.getJSONObject("coords");

            final int zoom;
            double geo_x = 0;
            double geo_y = 0;
            int size = 0;

            boolean useXY = false;
            boolean useLatLon = false;

            if (coords.has("x") && coords.has("y"))
                useXY = true;
            else if (coords.has("lat") && coords.has("lon"))
                useLatLon = true;

            if (coords.has("z") && (useXY || useLatLon)) {
                zoom = coords.optInt("z");
                if (useXY) {
                    geo_x = coords.optDouble("x");
                    geo_y = coords.optDouble("y");
                } else if (useLatLon) {
                    final double tmpLat = coords.optDouble("lat");
                    final double tmpLon = coords.optDouble("lon");
                    geo_x = GeoCalc.lonToMeters(tmpLon);
                    geo_y = GeoCalc.latToMeters(tmpLat);
                    //                        System.out.println(String.format("using %f/%f", geo_x, geo_y));
                }

                if (coords.has("size"))
                    size = coords.getInt("size");

                if (zoom != 0 && geo_x != 0 && geo_y != 0) {
                    double radius = 0;
                    if (size > 0)
                        radius = size * GeoCalc.getResFromZoom(256, zoom); // TODO use real tile size
                    else
                        radius = CLICK_RADIUS * GeoCalc.getResFromZoom(256, zoom); // TODO use real tile size
                    final double geo_x_min = geo_x - radius;
                    final double geo_x_max = geo_x + radius;
                    final double geo_y_min = geo_y - radius;
                    final double geo_y_max = geo_y + radius;

                    String hightlightUUIDString = null;
                    UUID highlightUUID = null;

                    final JSONObject mapOptionsObj = request.getJSONObject("options");
                    String optionStr = mapOptionsObj.optString("map_options");
                    if (optionStr == null || optionStr.length() == 0) // set
                                                                      // default
                        optionStr = "mobile/download";

                    final MapOption mo = mso.getMapOptionMap().get(optionStr);

                    final List<SQLFilter> filters = new ArrayList<>(mso.getDefaultMapFilters());
                    filters.add(mso.getAccuracyMapFilter());

                    final JSONObject mapFilterObj = request.getJSONObject("filter");

                    final Iterator<?> keys = mapFilterObj.keys();

                    while (keys.hasNext()) {
                        final String key = (String) keys.next();
                        if (mapFilterObj.get(key) instanceof Object)
                            if (key.equals("highlight"))
                                hightlightUUIDString = mapFilterObj.getString(key);
                            else {
                                final MapFilter mapFilter = mso.getMapFilterMap().get(key);
                                if (mapFilter != null)
                                    filters.add(mapFilter.getFilter(mapFilterObj.getString(key)));
                            }
                    }

                    if (hightlightUUIDString != null)
                        try {
                            highlightUUID = UUID.fromString(hightlightUUIDString);
                        } catch (final Exception e) {
                            highlightUUID = null;
                        }

                    if (conn != null) {
                        PreparedStatement ps = null;
                        ResultSet rs = null;

                        final StringBuilder whereSQL = new StringBuilder(mo.sqlFilter);
                        for (final SQLFilter sf : filters)
                            whereSQL.append(" AND ").append(sf.where);

                        final String sql = String.format("SELECT"
                                + (useLatLon ? " geo_lat lat, geo_long lon"
                                        : " ST_X(t.location) x, ST_Y(t.location) y")
                                + ", t.time, t.timezone, t.speed_download, t.speed_upload, t.ping_median, t.network_type,"
                                + " t.signal_strength, t.lte_rsrp, t.wifi_ssid, t.network_operator_name, t.network_operator,"
                                + " t.network_sim_operator, t.roaming_type, t.public_ip_as_name, " //TODO: sim_operator obsoled by sim_name
                                + " pMob.shortname mobile_provider_name," // TODO: obsoleted by mobile_network_name
                                + " prov.shortname provider_text, t.open_test_uuid,"
                                + " COALESCE(mnwk.shortname,mnwk.name) mobile_network_name,"
                                + " COALESCE(msim.shortname,msim.name) mobile_sim_name"
                                + (highlightUUID == null ? "" : " , c.uid, c.uuid") + " FROM v_test t"
                                + " LEFT JOIN mccmnc2name mnwk ON t.mobile_network_id=mnwk.uid"
                                + " LEFT JOIN mccmnc2name msim ON t.mobile_sim_id=msim.uid"
                                + " LEFT JOIN provider prov" + " ON t.provider_id=prov.uid"
                                + " LEFT JOIN provider pMob" + " ON t.mobile_provider_id=pMob.uid"
                                + (highlightUUID == null ? ""
                                        : " LEFT JOIN client c ON (t.client_id=c.uid AND c.uuid=?)")
                                + " WHERE" + " %s"
                                + " AND location && ST_SetSRID(ST_MakeBox2D(ST_Point(?,?), ST_Point(?,?)), 900913)"
                                + " ORDER BY" + (highlightUUID == null ? "" : " c.uid ASC,") + " t.uid DESC"
                                + " LIMIT 5", whereSQL);

                        //                            System.out.println("SQL: " + sql);
                        ps = conn.prepareStatement(sql);

                        int i = 1;

                        if (highlightUUID != null)
                            ps.setObject(i++, highlightUUID);

                        for (final SQLFilter sf : filters)
                            i = sf.fillParams(i, ps);
                        ps.setDouble(i++, geo_x_min);
                        ps.setDouble(i++, geo_y_min);
                        ps.setDouble(i++, geo_x_max);
                        ps.setDouble(i++, geo_y_max);

                        //                            System.out.println("SQL: " + ps.toString());
                        if (ps.execute()) {

                            final Locale locale = new Locale(lang);
                            final Format format = new SignificantFormat(2, locale);

                            final JSONArray resultList = new JSONArray();

                            rs = ps.getResultSet();

                            while (rs.next()) {
                                final JSONObject jsonItem = new JSONObject();

                                JSONArray jsonItemList = new JSONArray();

                                // RMBTClient Info
                                if (highlightUUID != null && rs.getString("uuid") != null)
                                    jsonItem.put("highlight", true);

                                final double res_x = rs.getDouble(1);
                                final double res_y = rs.getDouble(2);
                                final String openTestUUID = rs.getObject("open_test_uuid").toString();

                                jsonItem.put("lat", res_x);
                                jsonItem.put("lon", res_y);
                                jsonItem.put("open_test_uuid", "O" + openTestUUID);
                                // marker.put("uid", uid);

                                final Date date = rs.getTimestamp("time");
                                final String tzString = rs.getString("timezone");
                                final TimeZone tz = TimeZone.getTimeZone(tzString);
                                final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                                        DateFormat.MEDIUM, locale);
                                dateFormat.setTimeZone(tz);
                                jsonItem.put("time_string", dateFormat.format(date));

                                final int fieldDown = rs.getInt("speed_download");
                                JSONObject singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_DOWNLOAD"));
                                final String downloadString = String.format("%s %s",
                                        format.format(fieldDown / 1000d),
                                        labels.getString("RESULT_DOWNLOAD_UNIT"));
                                singleItem.put("value", downloadString);
                                singleItem.put("classification",
                                        Classification.classify(classification.THRESHOLD_DOWNLOAD, fieldDown));
                                // singleItem.put("help", "www.rtr.at");

                                jsonItemList.put(singleItem);

                                final int fieldUp = rs.getInt("speed_upload");
                                singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_UPLOAD"));
                                final String uploadString = String.format("%s %s",
                                        format.format(fieldUp / 1000d), labels.getString("RESULT_UPLOAD_UNIT"));
                                singleItem.put("value", uploadString);
                                singleItem.put("classification",
                                        Classification.classify(classification.THRESHOLD_UPLOAD, fieldUp));
                                // singleItem.put("help", "www.rtr.at");

                                jsonItemList.put(singleItem);

                                final long fieldPing = rs.getLong("ping_median");
                                final int pingValue = (int) Math.round(rs.getDouble("ping_median") / 1000000d);
                                singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_PING"));
                                final String pingString = String.format("%s %s", format.format(pingValue),
                                        labels.getString("RESULT_PING_UNIT"));
                                singleItem.put("value", pingString);
                                singleItem.put("classification",
                                        Classification.classify(classification.THRESHOLD_PING, fieldPing));
                                // singleItem.put("help", "www.rtr.at");

                                jsonItemList.put(singleItem);

                                final int networkType = rs.getInt("network_type");

                                final String signalField = rs.getString("signal_strength");
                                if (signalField != null && signalField.length() != 0) {
                                    final int signalValue = rs.getInt("signal_strength");
                                    final int[] threshold = networkType == 99 || networkType == 0
                                            ? classification.THRESHOLD_SIGNAL_WIFI
                                            : classification.THRESHOLD_SIGNAL_MOBILE;
                                    singleItem = new JSONObject();
                                    singleItem.put("title", labels.getString("RESULT_SIGNAL"));
                                    singleItem.put("value",
                                            signalValue + " " + labels.getString("RESULT_SIGNAL_UNIT"));
                                    singleItem.put("classification",
                                            Classification.classify(threshold, signalValue));
                                    jsonItemList.put(singleItem);
                                }

                                final String lteRsrpField = rs.getString("lte_rsrp");
                                if (lteRsrpField != null && lteRsrpField.length() != 0) {
                                    final int lteRsrpValue = rs.getInt("lte_rsrp");
                                    final int[] threshold = classification.THRESHOLD_SIGNAL_RSRP;
                                    singleItem = new JSONObject();
                                    singleItem.put("title", labels.getString("RESULT_LTE_RSRP"));
                                    singleItem.put("value",
                                            lteRsrpValue + " " + labels.getString("RESULT_LTE_RSRP_UNIT"));
                                    singleItem.put("classification",
                                            Classification.classify(threshold, lteRsrpValue));
                                    jsonItemList.put(singleItem);
                                }

                                jsonItem.put("measurement", jsonItemList);

                                jsonItemList = new JSONArray();

                                singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_NETWORK_TYPE"));
                                singleItem.put("value", Helperfunctions.getNetworkTypeName(networkType));

                                jsonItemList.put(singleItem);

                                if (networkType == 98 || networkType == 99) // mobile wifi or browser
                                {
                                    String providerText = MoreObjects.firstNonNull(
                                            rs.getString("provider_text"), rs.getString("public_ip_as_name"));
                                    if (!Strings.isNullOrEmpty(providerText)) {
                                        if (providerText.length() > (MAX_PROVIDER_LENGTH + 3)) {
                                            providerText = providerText.substring(0, MAX_PROVIDER_LENGTH)
                                                    + "...";
                                        }

                                        singleItem = new JSONObject();
                                        singleItem.put("title", labels.getString("RESULT_PROVIDER"));
                                        singleItem.put("value", providerText);
                                        jsonItemList.put(singleItem);
                                    }
                                    if (networkType == 99) // mobile wifi
                                    {
                                        if (highlightUUID != null && rs.getString("uuid") != null) // own test
                                        {
                                            final String ssid = rs.getString("wifi_ssid");
                                            if (ssid != null && ssid.length() != 0) {
                                                singleItem = new JSONObject();
                                                singleItem.put("title", labels.getString("RESULT_WIFI_SSID"));
                                                singleItem.put("value", ssid.toString());
                                                jsonItemList.put(singleItem);
                                            }
                                        }
                                    }
                                } else // mobile
                                {
                                    String networkOperator = rs.getString("network_operator");
                                    String mobileNetworkName = rs.getString("mobile_network_name");
                                    String simOperator = rs.getString("network_sim_operator");
                                    String mobileSimName = rs.getString("mobile_sim_name");
                                    final int roamingType = rs.getInt("roaming_type");
                                    //network
                                    if (!Strings.isNullOrEmpty(networkOperator)) {
                                        final String mobileNetworkString;
                                        if (roamingType != 2) { //not international roaming - display name of home network
                                            if (Strings.isNullOrEmpty(mobileSimName))
                                                mobileNetworkString = networkOperator;
                                            else
                                                mobileNetworkString = String.format("%s (%s)", mobileSimName,
                                                        networkOperator);
                                        } else { //international roaming - display name of network
                                            if (Strings.isNullOrEmpty(mobileSimName))
                                                mobileNetworkString = networkOperator;
                                            else
                                                mobileNetworkString = String.format("%s (%s)",
                                                        mobileNetworkName, networkOperator);
                                        }

                                        singleItem = new JSONObject();
                                        singleItem.put("title", labels.getString("RESULT_MOBILE_NETWORK"));
                                        singleItem.put("value", mobileNetworkString);
                                        jsonItemList.put(singleItem);
                                    }
                                    //home network (sim)
                                    else if (!Strings.isNullOrEmpty(simOperator)) {
                                        final String mobileNetworkString;

                                        if (Strings.isNullOrEmpty(mobileSimName))
                                            mobileNetworkString = simOperator;
                                        else
                                            mobileNetworkString = String.format("%s (%s)", mobileSimName,
                                                    simOperator);

                                        /*
                                        if (!Strings.isNullOrEmpty(mobileProviderName)) {
                                           mobileNetworkString = mobileProviderName;
                                        } else {
                                           mobileNetworkString = simOperator;
                                        }
                                        */

                                        singleItem = new JSONObject();
                                        singleItem.put("title", labels.getString("RESULT_HOME_NETWORK"));
                                        singleItem.put("value", mobileNetworkString);
                                        jsonItemList.put(singleItem);
                                    }

                                    if (roamingType > 0) {
                                        singleItem = new JSONObject();
                                        singleItem.put("title", labels.getString("RESULT_ROAMING"));
                                        singleItem.put("value",
                                                Helperfunctions.getRoamingType(labels, roamingType));
                                        jsonItemList.put(singleItem);
                                    }
                                }

                                jsonItem.put("net", jsonItemList);

                                resultList.put(jsonItem);

                                if (resultList.length() == 0)
                                    System.out.println("Error getting Results.");
                                // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"),
                                // new Object[] {uuid}));

                            }

                            answer.put("measurements", resultList);
                        } else
                            System.out.println("Error executing SQL.");
                    } else
                        System.out.println("No Database Connection.");
                }
            } else
                System.out.println("Expected request is missing.");

        } catch (final JSONException e) {
            System.out.println("Error parsing JSDON Data " + e.toString());
        } catch (final SQLException e) {
            e.printStackTrace();
        }
    else
        System.out.println("No Request.");

    return answer.toString();

}

From source file:jp.terasoluna.fw.beans.jxpath.DynamicPointerExTest.java

/**
 * testDynamicPointerExNodePointer01() <br>
 * <br>/*from w  w w  .  j ava  2  s.  co m*/
 * () <br>
 * A <br>
 * <br>
 * () parent:not null<br>
 * () name:not null<br>
 * () bean:new Object()<br>
 * () handler:not null<br>
 * () this.handler:null<br>
 * <br>
 * () this.handler:???<br>
 * <br>
 * ?? <br>
 * @throws Exception ?????
 */
@Test
public void testDynamicPointerExNodePointer01() throws Exception {
    // ??
    QName qName = new QName("name");
    Object bean = new Object();
    DynamicPropertyHandler handler = new MapDynamicPropertyHandler();
    Locale locale = new Locale("ja");
    NodePointer nodePointer = NodePointer.newNodePointer(qName, bean, locale);

    // 
    DynamicPointerEx result = new DynamicPointerEx(nodePointer, qName, bean, handler);

    // 
    Field field = DynamicPointerEx.class.getDeclaredField("handler");
    field.setAccessible(true);
    Object resultHandler = field.get(result);
    assertSame(handler, resultHandler);
}

From source file:jp.terasoluna.fw.beans.jxpath.DynamicPropertyPointerExTest.java

/**
 * testGetLength02()/*from  w  w w.jav a  2  s.c  o m*/
 * <br><br>
 * 
 * ()
 * <br>
 * A
 * <br><br>
 * () getBaseValue():not null<br>
 *         () ValueUtils.getLength(value):?????<br>
 *         
 * <br>
 * () -:ValueUtils.getLength(value)??<br>
 *         
 * <br>
 * ??null??????ValueUtils.getLength()?
 * <br>
 * 
 * @throws Exception ?????
 */
@Test
@SuppressWarnings("unchecked")
public void testGetLength02() throws Exception {
    // ??
    QName qName = new QName("name");
    @SuppressWarnings("rawtypes")
    Map map = new HashMap();
    map.put("key", new String[] { "a", "b", "c" });
    DynamicPropertyHandler handler = new MapDynamicPropertyHandler();
    Locale locale = new Locale("ja");
    NodePointer nodePointer = NodePointer.newNodePointer(qName, map, locale);
    DynamicPropertyPointerEx pointer = new DynamicPropertyPointerEx(nodePointer, handler);
    pointer.setPropertyName("key");

    // 
    assertEquals(3, pointer.getLength());
}

From source file:org.openmrs.module.emrapi.concept.HibernateEmrConceptDAO.java

@Override
@Transactional(readOnly = true)/*from   ww  w  .  j av  a 2  s .c om*/
public List<ConceptSearchResult> conceptSearch(String query, Locale locale, Collection<ConceptClass> classes,
        Collection<Concept> inSets, Collection<ConceptSource> sources, Integer limit) {
    List<String> uniqueWords = getUniqueWords(query, locale);
    if (uniqueWords.size() == 0) {
        return Collections.emptyList();
    }

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

    // find matches based on name
    {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptName.class, "cn");
        criteria.add(Restrictions.eq("voided", false));
        if (StringUtils.isNotBlank(locale.getCountry()) || StringUtils.isNotBlank(locale.getVariant())) {
            Locale[] locales = new Locale[] { locale, new Locale(locale.getLanguage()) };
            criteria.add(Restrictions.in("locale", locales));
        } else {
            criteria.add(Restrictions.eq("locale", locale));
        }
        criteria.setMaxResults(limit);

        Criteria conceptCriteria = criteria.createCriteria("concept");
        conceptCriteria.add(Restrictions.eq("retired", false));
        if (classes != null) {
            conceptCriteria.add(Restrictions.in("conceptClass", classes));
        }
        if (inSets != null) {
            DetachedCriteria allowedSetMembers = DetachedCriteria.forClass(ConceptSet.class);
            allowedSetMembers.add(Restrictions.in("conceptSet", inSets));
            allowedSetMembers.setProjection(Projections.property("concept"));
            criteria.add(Subqueries.propertyIn("concept", allowedSetMembers));
        }

        for (String word : uniqueWords) {
            criteria.add(Restrictions.ilike("name", word, MatchMode.ANYWHERE));
        }

        Set<Concept> conceptsMatchedByPreferredName = new HashSet<Concept>();
        for (ConceptName matchedName : (List<ConceptName>) criteria.list()) {
            results.add(new ConceptSearchResult(null, matchedName.getConcept(), matchedName,
                    calculateMatchScore(query, uniqueWords, matchedName)));
            if (matchedName.isLocalePreferred()) {
                conceptsMatchedByPreferredName.add(matchedName.getConcept());
            }
        }

        // don't display synonym matches if the preferred name matches too
        for (Iterator<ConceptSearchResult> i = results.iterator(); i.hasNext();) {
            ConceptSearchResult candidate = i.next();
            if (!candidate.getConceptName().isLocalePreferred()
                    && conceptsMatchedByPreferredName.contains(candidate.getConcept())) {
                i.remove();
            }
        }
    }

    // find matches based on mapping
    if (sources != null) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptMap.class);
        criteria.setMaxResults(limit);

        Criteria conceptCriteria = criteria.createCriteria("concept");
        conceptCriteria.add(Restrictions.eq("retired", false));
        if (classes != null) {
            conceptCriteria.add(Restrictions.in("conceptClass", classes));
        }

        Criteria mappedTerm = criteria.createCriteria("conceptReferenceTerm");
        mappedTerm.add(Restrictions.eq("retired", false));
        mappedTerm.add(Restrictions.in("conceptSource", sources));
        mappedTerm.add(Restrictions.ilike("code", query, MatchMode.EXACT));

        for (ConceptMap mapping : (List<ConceptMap>) criteria.list()) {
            results.add(new ConceptSearchResult(null, mapping.getConcept(), null,
                    calculateMatchScore(query, mapping)));
        }
    }

    Collections.sort(results, new Comparator<ConceptSearchResult>() {
        @Override
        public int compare(ConceptSearchResult left, ConceptSearchResult right) {
            return right.getTransientWeight().compareTo(left.getTransientWeight());
        }
    });

    if (results.size() > limit) {
        results = results.subList(0, limit);
    }
    return results;
}

From source file:de.ingrid.iplug.sns.gssoil.GsSoilGazetteer4TestLocal.java

public void testGazetteerDirectly() throws Exception {
    SpringUtil springUtil = new SpringUtil("spring/external-services.xml");
    final Class<GazetteerService> _gazetteerService = null;
    GazetteerService gazetteer = springUtil.getBean("gazetteerService", _gazetteerService);

    // getLocationsFromText
    // --------------------
    // NOTICE: Locations are now checked in passed language !  

    // pass correct language OF TEXT ! returns Lisbon !
    Location[] locations = gazetteer.getLocationsFromText("Lisbon", 100, false, new Locale("en"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idLisbonDistrict));
    assertTrue(locations[0].getName().equals("Lisbon"));

    // pass wrong language of text
    locations = gazetteer.getLocationsFromText("Lisbon", 100, false, new Locale("de"));
    assertTrue(locations.length == 0);//from w  ww .j ava2  s.co  m

    // pass wrong language of text
    locations = gazetteer.getLocationsFromText("Lisboa", 100, false, new Locale("de"));
    assertTrue(locations.length == 0);

    locations = gazetteer.getLocationsFromText("Lisboa", 100, false, new Locale("pt"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idLisbonDistrict));
    assertTrue(locations[0].getName().equals("Lisboa"));

    locations = gazetteer.getLocationsFromText("Berlin", 100, false, new Locale("de"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idBerlinLand));
    assertTrue(locations[0].getName().startsWith("Berlin"));

    // case sensitive ! NOTICE: can be set now in sns.properties for controller
    locations = gazetteer.getLocationsFromText("berlin", 100, false, new Locale("de"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idBerlinLand));
    assertTrue(locations[0].getName().startsWith("Berlin"));

    // case insensitive ! NOTICE: can be set now in sns.properties for controller
    locations = gazetteer.getLocationsFromText("berlin", 100, true, new Locale("de"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idBerlinLand));
    assertTrue(locations[0].getName().startsWith("Berlin"));

    locations = gazetteer.getLocationsFromText("ruhlsdorf", 100, false, new Locale("de"));
    //        assertTrue(locations.length > 0);
    assertTrue(locations.length == 0);

    locations = gazetteer.getLocationsFromText("Brief Porto nach Berlin, Deutschland", 100, false,
            new Locale("de"));
    assertTrue(locations.length > 1);

    // invalid text
    locations = gazetteer.getLocationsFromText("yyy xxx zzz", 100, false, new Locale("en"));
    // we find lot's of stuff !?
    assertTrue(locations.length > 0);

    // findLocationsFromQueryTerm
    // --------------------
    // NOTICE: Passed Name of location and language must match, e.g. "Lisbon"<->"en" or "Lisboa"<->"pt" ... 

    locations = gazetteer.findLocationsFromQueryTerm("lisbon", QueryType.ALL_LOCATIONS, MatchingType.EXACT,
            new Locale("en"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idLisbonDistrict));
    assertTrue(locations[0].getName().equals("Lisbon"));

    locations = gazetteer.findLocationsFromQueryTerm("Lissabon", QueryType.ALL_LOCATIONS, MatchingType.EXACT,
            new Locale("de"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idLisbonDistrict));
    assertTrue(locations[0].getName().equals("Lissabon"));

    locations = gazetteer.findLocationsFromQueryTerm("Berlin", QueryType.ALL_LOCATIONS, MatchingType.CONTAINS,
            new Locale("de"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getName().contains("Berlin"));

    locations = gazetteer.findLocationsFromQueryTerm("Lisboa", QueryType.ALL_LOCATIONS,
            MatchingType.BEGINS_WITH, new Locale("pt"));
    assertTrue(locations.length > 0);
    //        assertTrue(locations[0].getId().equals(idLisbonMuncipality));
    assertTrue(locations[0].getName().contains("Lisboa"));

    locations = gazetteer.findLocationsFromQueryTerm("ruhlsdorf", QueryType.ALL_LOCATIONS,
            MatchingType.CONTAINS, new Locale("de"));
    assertTrue(locations.length > 0);

    // getLocation
    // --------------------
    // NOTICE: returns location name in passed language !

    Location location = gazetteer.getLocation(idLisbonDistrict, new Locale("en"));
    assertTrue(location != null);
    assertTrue(location.getId().equals(idLisbonDistrict));
    assertTrue(location.getName().equals("Lisbon"));

    location = gazetteer.getLocation(idBerlinStadt, new Locale("de"));
    assertTrue(location != null);
    assertTrue(location.getId().equals(idBerlinStadt));
    assertTrue(location.getName().startsWith("Berlin"));

    location = gazetteer.getLocation(idBerlinLand, new Locale("de"));
    assertTrue(location != null);
    assertTrue(location.getId().equals(idBerlinLand));
    assertTrue(location.getName().contains("Berlin"));

    location = gazetteer.getLocation(idDeutschland, new Locale("de"));
    assertTrue(location != null);
    assertTrue(location.getId().equals(idDeutschland));
    assertTrue(location.getName().contains("Deutschland"));

    location = gazetteer.getLocation(idPortugal, new Locale("pt"));
    assertTrue(location != null);
    assertTrue(location.getId().equals(idPortugal));
    assertTrue(location.getName().contains("Portuguesa"));

    location = gazetteer.getLocation(idPorto, new Locale("en"));
    assertTrue(location != null);
    assertTrue(location.getId().equals(idPorto));
    assertTrue(location.getName().startsWith("Porto"));

    // getRelatedLocationsFromLocation
    // --------------------
    // NOTICE: returns locations in passed language !

    // include location with passed id !
    locations = gazetteer.getRelatedLocationsFromLocation(idLisbonDistrict, true, new Locale("en"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idLisbonDistrict));
    // do NOT include location with passed id !
    locations = gazetteer.getRelatedLocationsFromLocation(idLisbonDistrict, false, new Locale("de"));
    assertTrue(locations != null);
    if (locations.length > 0) {
        assertFalse(locations[0].getId().equals(idLisbonDistrict));
    }

    // include location with passed id !
    locations = gazetteer.getRelatedLocationsFromLocation(idPortugal, true, new Locale("en"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idPortugal));
    // do NOT include location with passed id !
    locations = gazetteer.getRelatedLocationsFromLocation(idPortugal, false, new Locale("en"));
    assertTrue(locations != null);
    if (locations.length > 0) {
        assertFalse(locations[0].getId().equals(idPortugal));
    }
}

From source file:it.av.youeat.web.security.FacebookAuthenticationProvider.java

/**
 * @param authClient/*w w  w  .  j  av  a2 s .  com*/
 * @param facebookUserId
 * @param eater
 * @throws FacebookException
 */
protected void checkAndCreateUser(FacebookJaxbRestClient authClient, long facebookUserId, Eater eater)
        throws FacebookException {
    if (eater == null) {
        ArrayList<Long> ids = new ArrayList<Long>();
        ids.add(facebookUserId);
        ArrayList<ProfileField> fields = new ArrayList<ProfileField>();
        fields.add(ProfileField.FIRST_NAME);
        fields.add(ProfileField.LAST_NAME);
        fields.add(ProfileField.LOCALE);
        fields.add(ProfileField.PIC);

        UsersGetInfoResponse users = authClient.users_getInfo(ids, fields);
        User user = users.getUser().get(0);
        eater = new Eater();
        eater.setFirstname(user.getFirstName());
        eater.setLastname(user.getLastName());
        eater.setSocialUID(Long.toString(facebookUserId));
        byte[] avatar = getTheAvatar(user.getPic());
        if (avatar != null) {
            eater.setAvatar(avatar);
        }
        eater.setCountry(countryService.getByIso2(user.getLocale().substring(3, 5)));
        eater.setLanguage(languageService.getSupportedLanguage(new Locale(user.getLocale())));
        eaterService.addFacebookUser(eater);
    }
}

From source file:mx.edu.um.eventosum.config.WebConfig.java

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(new Locale("en_US"));
    return localeResolver;
}