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:module.geography.domain.task.CountryCodesImport.java

private static LocalizedString makeName(String pt, String en) {
    if (pt != null || en != null) {
        LocalizedString name = new LocalizedString();
        if (pt != null) {
            name = name.with(new Locale("pt"), WordUtils.capitalizeFully(pt));
        }/* www  . j a  v  a2 s  . com*/
        if (en != null) {
            name = name.with(Locale.ENGLISH, WordUtils.capitalizeFully(en));
        }
        return name;
    }
    return null;
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.file.File.java

/**
 * Returns the {@code lastModifiedDate} property.
 * @return the {@code lastModifiedDate} property
 *///from w  w  w  . j  ava  2 s.  c  o m
@JsxGetter
public String getLastModifiedDate() {
    final Date date = new Date(getLastModified());
    final BrowserVersion browser = getBrowserVersion();
    final Locale locale = new Locale(browser.getSystemLanguage());

    if (browser.hasFeature(BrowserVersionFeatures.JS_FILE_SHORT_DATE_FORMAT)) {
        final FastDateFormat format = FastDateFormat.getInstance(LAST_MODIFIED_DATE_FORMAT_FF, locale);
        return format.format(date);
    }

    final FastDateFormat format = FastDateFormat.getInstance(LAST_MODIFIED_DATE_FORMAT, locale);
    return format.format(date);
}

From source file:com.salesmanager.core.util.LabelUtil.java

private void getLocale(String lang) {

    if (StringUtils.isBlank(lang)) {
        lang = LanguageUtil.getDefaultLanguage();
    }//w w  w  .j  a va 2 s .com

    if (lang.equals("en")) {
        setLocale(Locale.ENGLISH);
    } else if (lang.equals("fr")) {
        setLocale(Locale.FRENCH);
    } else {
        setLocale(new Locale(lang));
    }
}

From source file:edu.ku.brc.specify.plugins.sgr.SGRResultsDisplay.java

public SGRResultsDisplay(int width, MatchResults results) {
    if (Main.m_settings == null) {
        Main.m_settings = new JSettings(true);
        Main.m_settings.load(//from  ww  w .  j  a  v a  2s .  c o m
                JPathHelper.addSeparator(System.getProperty("user.home")) + JSettings.SETTINGS_FILE, "1.8");

        Main.m_sysLocale = Locale.getDefault();
        if (Main.m_settings.getLocale().length() > 0) {
            Locale.setDefault(new Locale(Main.m_settings.getLocale()));
        }
    }

    SGRColumnOrdering columns = SGRColumnOrdering.getInstance();
    String[] fields = columns.getFields();

    DefaultTableModel resultsTableModel = new DefaultTableModel(columns.getHeadings(), 0);

    final List<List<Color>> rowColors = new LinkedList<List<Color>>();

    for (Match result : results) {
        SGRRecord match = result.match;
        float score = result.score;
        float maxScore = 22.0f; //results.maxScore;

        List<Color> cellColors = new LinkedList<Color>();

        List<String> data = new LinkedList<String>();
        for (String field : fields) {
            if (field.equals("id")) {
                data.add(match.id);
                cellColors.add(SGRColors.colorForScore(score, maxScore));
            } else if (field.equals("score")) {
                data.add(((Float) score).toString());
                cellColors.add(SGRColors.colorForScore(score, maxScore));
            } else {
                data.add(StringUtils.join(match.getFieldValues(field).toArray(), ';'));

                Float fieldContribution = result.fieldScoreContributions().get(field);
                Color color = SGRColors.colorForScore(score, maxScore, fieldContribution);
                cellColors.add(color);
            }
        }
        resultsTableModel.addRow(data.toArray());
        rowColors.add(cellColors);
    }

    JTable table = createTable(resultsTableModel, rowColors);
    Dimension preferredSize = table.getPreferredSize();
    preferredSize.width = Math.min((int) (0.9 * width), preferredSize.width);
    table.setPreferredScrollableViewportSize(preferredSize);
    table.getColumnModel().addColumnModelListener(this);

    add(new JScrollPane(table));
}

From source file:at.alladin.rmbt.controlServer.HistoryResource.java

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();//from  ww w.jav a2  s .c om

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    System.out.println(MessageFormat.format(labels.getString("NEW_HISTORY"), clientIpRaw));

    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)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            } else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

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

            if (conn != null) {
                final Client client = new Client(conn);

                if (request.optString("uuid").length() > 0
                        && client.getClientByUuid(UUID.fromString(request.getString("uuid"))) > 0) {

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

                    String limitRequest = "";
                    if (request.optInt("result_limit", 0) != 0) {
                        final int limit = request.getInt("result_limit");

                        //get offset string if there is one
                        String offsetString = "";
                        if ((request.optInt("result_offset", 0) != 0)
                                && (request.getInt("result_offset") >= 0)) {
                            offsetString = " OFFSET " + request.getInt("result_offset");
                        }

                        limitRequest = " LIMIT " + limit + offsetString;
                    }

                    final ArrayList<String> deviceValues = new ArrayList<>();
                    String deviceRequest = "";
                    if (request.optJSONArray("devices") != null) {
                        final JSONArray devices = request.getJSONArray("devices");

                        boolean checkUnknown = false;
                        final StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < devices.length(); i++) {
                            final String device = devices.getString(i);

                            if (device.equals("Unknown Device"))
                                checkUnknown = true;
                            else {
                                if (sb.length() > 0)
                                    sb.append(',');
                                deviceValues.add(device);
                                sb.append('?');
                            }
                        }

                        if (sb.length() > 0)
                            deviceRequest = " AND (COALESCE(adm.fullname, t.model) IN (" + sb.toString() + ")"
                                    + (checkUnknown ? " OR model IS NULL OR model = ''" : "") + ")";
                        //                            System.out.println(deviceRequest);

                    }

                    final ArrayList<String> filterValues = new ArrayList<>();
                    String networksRequest = "";

                    if (request.optJSONArray("networks") != null) {
                        final JSONArray tmpArray = request.getJSONArray("networks");
                        final StringBuilder tmpString = new StringBuilder();

                        if (tmpArray.length() >= 1) {
                            tmpString.append("AND nt.group_name IN (");
                            boolean first = true;
                            for (int i = 0; i < tmpArray.length(); i++) {
                                if (first)
                                    first = false;
                                else
                                    tmpString.append(',');
                                tmpString.append('?');
                                filterValues.add(tmpArray.getString(i));
                            }
                            tmpString.append(')');
                        }
                        networksRequest = tmpString.toString();
                    }

                    final JSONArray historyList = new JSONArray();

                    final PreparedStatement st;

                    try {
                        if (client.getSync_group_id() == 0) {
                            //use faster request ignoring sync-group as user is not synced (id=0)
                            st = conn.prepareStatement(String.format(

                                    "SELECT DISTINCT"
                                            + " t.uuid, time, timezone, speed_upload, speed_download, ping_median, network_type, nt.group_name network_type_group_name,"
                                            + " COALESCE(adm.fullname, t.model) model" + " FROM test t"
                                            + " LEFT JOIN device_map adm ON adm.codename=t.model"
                                            + " LEFT JOIN network_type nt ON t.network_type=nt.uid"
                                            + " WHERE t.deleted = false AND t.implausible = false AND t.status = 'FINISHED'"
                                            + " AND client_id = ?" + " %s %s" + " ORDER BY time DESC" + " %s",
                                    deviceRequest, networksRequest, limitRequest));
                        } else { //use slower request including sync-group if client is synced
                            st = conn.prepareStatement(String.format("SELECT DISTINCT"
                                    + " t.uuid, time, timezone, speed_upload, speed_download, ping_median, network_type, nt.group_name network_type_group_name,"
                                    + " COALESCE(adm.fullname, t.model) model" + " FROM test t"
                                    + " LEFT JOIN device_map adm ON adm.codename=t.model"
                                    + " LEFT JOIN network_type nt ON t.network_type=nt.uid"
                                    + " WHERE t.deleted = false AND t.implausible = false AND t.status = 'FINISHED'"
                                    + " AND (t.client_id IN (SELECT ? UNION SELECT uid FROM client WHERE sync_group_id = ? ))"
                                    + " %s %s" + " ORDER BY time DESC" + " %s", deviceRequest, networksRequest,
                                    limitRequest));

                        }

                        int i = 1;
                        st.setLong(i++, client.getUid());
                        if (client.getSync_group_id() != 0)
                            st.setInt(i++, client.getSync_group_id());

                        for (final String value : deviceValues)
                            st.setString(i++, value);

                        for (final String filterValue : filterValues)
                            st.setString(i++, filterValue);

                        //System.out.println(st.toString());

                        final ResultSet rs = st.executeQuery();

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

                            jsonItem.put("test_uuid", rs.getString("uuid"));

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

                            jsonItem.put("speed_upload", format.format(rs.getInt("speed_upload") / 1000d));
                            jsonItem.put("speed_download", format.format(rs.getInt("speed_download") / 1000d));

                            final long ping = rs.getLong("ping_median");
                            jsonItem.put("ping", format.format(ping / 1000000d));
                            // backwards compatibility for old clients
                            jsonItem.put("ping_shortest", format.format(ping / 1000000d));
                            jsonItem.put("model", rs.getString("model"));
                            jsonItem.put("network_type", rs.getString("network_type_group_name"));

                            //for appscape-iPhone-Version: also add classification to the response
                            jsonItem.put("speed_upload_classification", Classification
                                    .classify(classification.THRESHOLD_UPLOAD, rs.getInt("speed_upload")));
                            jsonItem.put("speed_download_classification", Classification
                                    .classify(classification.THRESHOLD_DOWNLOAD, rs.getInt("speed_download")));
                            jsonItem.put("ping_classification", Classification
                                    .classify(classification.THRESHOLD_PING, rs.getLong("ping_median")));
                            // backwards compatibility for old clients
                            jsonItem.put("ping_shortest_classification", Classification
                                    .classify(classification.THRESHOLD_PING, rs.getLong("ping_median")));

                            historyList.put(jsonItem);
                        }

                        if (historyList.length() == 0)
                            errorList.addError("ERROR_DB_GET_HISTORY");
                        // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"),
                        // new Object[] {uuid}));

                        rs.close();
                        st.close();
                    } catch (final SQLException e) {
                        e.printStackTrace();
                        errorList.addError("ERROR_DB_GET_HISTORY_SQL");
                        // errorList.addError("ERROR_DB_GET_CLIENT_SQL");
                    }

                    answer.put("history", historyList);
                } else
                    errorList.addError("ERROR_REQUEST_NO_UUID");

            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        } catch (final IllegalArgumentException e) {
            errorList.addError("ERROR_REQUEST_NO_UUID");
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();

    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_HISTORY_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:ar.com.zauber.commons.xmpp.message.XMPPMessageTest.java

/** multiples lenguajes */
@Test//w  w  w  .  j  a  v  a2  s .co m
public final void testXHTML() throws Exception {
    final XMPPMessage c = new XMPPMessage("body", "title");
    final Map<Locale, Resource> msgs = new HashMap<Locale, Resource>();
    msgs.put(new Locale("es"), new StringResource("hola!"));
    msgs.put(Locale.ITALIAN, new StringResource("pronto!"));
    c.setLangBodies(msgs);
    c.setHtmlMessage(new StringResource("<body><strong>html!</strong></body>"));
    org.jivesoftware.smack.packet.Message m = c.getXMPPMessage("juan");
    m.setPacketID("0");

    // sin setear conection no deberia haber mensaje html 
    Assert.assertEquals(getResult("multilang.xml"), m.toXML());
}

From source file:org.osiam.addons.administration.mail.EmailSender.java

public void sendActivateMail(User user) {
    sendActivateMail(user, new Locale(user.getLocale()));
}

From source file:com.opencsv.bean.BeanFieldPrimitiveTypes.java

@Override
protected Object convert(String value) throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
    if (required && StringUtils.isBlank(value)) {
        throw new CsvRequiredFieldEmptyException(
                String.format("Field '%s' is mandatory but no value was provided.", field.getName()));
    }/*w w w.  j a  v a  2s.co  m*/

    Object o = null;

    if (StringUtils.isNotBlank(value)) {
        try {
            if (StringUtils.isEmpty(locale)) {
                ConvertUtilsBean converter = new ConvertUtilsBean();
                converter.register(true, false, 0);
                o = converter.convert(value, field.getType());
            } else {
                LocaleConvertUtilsBean lcub = new LocaleConvertUtilsBean();
                lcub.setDefaultLocale(new Locale(locale));
                o = lcub.convert(value, field.getType());
            }
        } catch (ConversionException e) {
            CsvDataTypeMismatchException csve = new CsvDataTypeMismatchException(value, field.getType(),
                    "Conversion of " + value + " to " + field.getType().getCanonicalName() + " failed.");
            csve.initCause(e);
            throw csve;
        }
    }
    return o;
}

From source file:com.isalnikov.config.MessageTest.java

@Test
public void testHelloParamsConfigurer() {
    System.out.println(messageHelper.getMessage("hello.name", "igor"));
    System.out.println(messageHelper.getMessage(Locale.CANADA, "hello.name", "igor"));
    System.out.println(messageHelper.getMessage(Locale.ENGLISH, "hello.name", "igor"));
    System.out.println(messageHelper.getMessage(Locale.ENGLISH, "hello.name", ""));
    System.out.println(messageHelper.getMessage(new Locale("ru"), "hello.name", ""));
    System.out.println(messageHelper.getMessage(new Locale("ru_RU"), "hello.name", ""));
}

From source file:fi.helsinki.opintoni.web.rest.privateapi.NewsResourceTest.java

@Test
public void thatTeacherNewsAreReturned() throws Exception {
    flammaServer.expectTeacherNews();//from w w  w .ja va  2  s. c  o m

    mockMvc.perform(get("/api/private/v1/news/teacher").with(securityContext(teacherSecurityContext()))
            .characterEncoding("UTF-8").contentType(MediaType.APPLICATION_JSON).locale(new Locale("fi"))
            .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(content().contentType(WebConstants.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$").isArray()).andExpect(jsonPath("$", hasSize(2)))
            .andExpect(jsonPath("$[0].title").value("Reflekta palkittiin parhaana opiskelijakilpailussa"))
            .andExpect(jsonPath("$[0].url").value("https://flamma.helsinki.fi/portal/home/sisalto1"))
            .andExpect(jsonPath("$[0].content").value("Content"))
            .andExpect(jsonPath("$[1].title").value("Tukea yliopisto-opettajille"))
            .andExpect(jsonPath("$[1].url").value("https://flamma.helsinki.fi/portal/home/sisalto2"))
            .andExpect(jsonPath("$[1].content").value("Content"));
}