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:de.iteratec.iteraplan.presentation.EnforceLocaleResolver.java

/**
 * A locale attribute in the user's session in case a custom setting is used
 * More precisely, English is a custom setting for the chosen language
 * useful setting for Date validation in English
 *//*from ww  w.j a  v a  2s  .c o  m*/
public void setEnforcedLocaleString(String enforcedLocaleString) {
    if (!StringUtils.isEmpty(enforcedLocaleString)) {
        this.enforcedLocale = new Locale(enforcedLocaleString);
    }
}

From source file:autoupdater.FileDAO.java

/**
 * Adds a shortcut to the desktop. At the moment for Windows only.
 *
 * @param mavenJarFile the {@code MavenJarFile} to create the shortcut for
 * @param iconName the name of the icon in the resource folder of the
 * {@code MavenJarFile} to link to/*www  .j a  v  a  2 s  . c om*/
 * @return true if the shortcut was created otherwise false
 * @throws NullPointerException
 * @throws RuntimeException
 */
public boolean addShortcutAtDeskTop(MavenJarFile mavenJarFile, String iconName)
        throws NullPointerException, RuntimeException {
    String os = System.getProperty("os.name").toLowerCase(new Locale("en"));
    if (os.contains("win")) {

        JShellLink link = new JShellLink();
        link.setFolder(JShellLink.getDirectory("desktop"));
        link.setName(new StringBuilder().append(mavenJarFile.getArtifactId()).append("-")
                .append(mavenJarFile.getVersionNumber()).toString());
        if (iconName != null) {
            link.setIconLocation(new StringBuilder()
                    .append(new File(mavenJarFile.getAbsoluteFilePath()).getParentFile().getAbsolutePath())
                    .append("/resources/").append(iconName).toString());
        }
        link.setPath(mavenJarFile.getAbsoluteFilePath());
        link.save();
    } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
        /**
         * To manually create a desktop shortcut for a particular program or command, you can create a .desktop file using any text editor, and place it in either /usr/share/applications or ~/.local/share/applications. A typical .desktop file looks like the following.
                
         [Desktop Entry]
         Encoding=UTF-8
         Version=1.0                                     # version of an app.
         Name[en_US]=yEd                                 # name of an app.
         GenericName=GUI Port Scanner                    # longer name of an app.
         Exec=java -jar /opt/yed-3.11.1/yed.jar          # command used to launch an app.
         Terminal=false                                  # whether an app requires to be run in a terminal.
         Icon[en_US]=/opt/yed-3.11.1/icons/yicon32.png   # location of icon file.
         Type=Application                                # type.
         Categories=Application;Network;Security;        # categories in which this app should be listed.
         Comment[en_US]=yEd Graph Editor                 # comment which appears as a tooltip.
                
         */
    }

    return true;
}

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

/**
 * /*  www.j a v  a  2s  .  co  m*/
 * @param entity
 * @return
 */
@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();

    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_SETTINGS_REQUEST"), 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);
                int typeId = 0;

                if (request.optString("type").length() > 0) {
                    typeId = client.getTypeId(request.getString("type"));
                    if (client.hasError())
                        errorList.addError(client.getError());
                }

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

                final JSONArray settingsList = new JSONArray();
                final JSONObject jsonItem = new JSONObject();

                if (clientNames.contains(request.optString("name")) && typeId > 0) {

                    // String clientName = request.getString("name");
                    // String clientVersionCode =
                    // request.getString("version_name");
                    // String clientVersionName =
                    // request.optString("version_code", "");

                    UUID uuid = null;
                    long clientUid = 0;

                    final String uuidString = request.optString("uuid", "");
                    try {
                        if (!Strings.isNullOrEmpty(uuidString))
                            uuid = UUID.fromString(uuidString);
                    } catch (IllegalArgumentException e) // not a valid uuid
                    {
                    }

                    if (uuid != null && errorList.getLength() == 0) {
                        clientUid = client.getClientByUuid(uuid);
                        if (client.hasError())
                            errorList.addError(client.getError());
                    }

                    boolean tcAccepted = request.optInt("terms_and_conditions_accepted_version", 0) > 0; // accept any version for now
                    if (!tcAccepted) // allow old non-version parameter
                        tcAccepted = request.optBoolean("terms_and_conditions_accepted", false);
                    {
                        if (tcAccepted && (uuid == null || clientUid == 0)) {

                            final Timestamp tstamp = java.sql.Timestamp
                                    .valueOf(new Timestamp(System.currentTimeMillis()).toString());

                            final Calendar timeWithZone = Helperfunctions
                                    .getTimeWithTimeZone(Helperfunctions.getTimezoneId());

                            client.setTimeZone(timeWithZone);
                            client.setTime(tstamp);
                            client.setClient_type_id(typeId);
                            client.setTcAccepted(tcAccepted);

                            uuid = client.storeClient();

                            if (client.hasError())
                                errorList.addError(client.getError());
                            else
                                jsonItem.put("uuid", uuid.toString());
                        }

                        if (client.getUid() > 0) {
                            /* map server */

                            final Series<Parameter> ctxParams = getContext().getParameters();
                            final String host = ctxParams.getFirstValue("RMBT_MAP_HOST");
                            final String sslStr = ctxParams.getFirstValue("RMBT_MAP_SSL");
                            final String portStr = ctxParams.getFirstValue("RMBT_MAP_PORT");
                            if (host != null && sslStr != null && portStr != null) {
                                JSONObject mapServer = new JSONObject();
                                mapServer.put("host", host);
                                mapServer.put("port", Integer.parseInt(portStr));
                                mapServer.put("ssl", Boolean.parseBoolean(sslStr));
                                jsonItem.put("map_server", mapServer);
                            }

                            // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            // HISTORY / FILTER

                            final JSONObject subItem = new JSONObject();

                            final JSONArray netList = new JSONArray();

                            try {

                                // deviceList:

                                subItem.put("devices", getSyncGroupDeviceList(errorList, client));

                                // network_type:

                                final PreparedStatement st = conn.prepareStatement("SELECT DISTINCT group_name"
                                        + " FROM test t" + " JOIN network_type nt ON t.network_type=nt.uid"
                                        + " WHERE t.deleted = false AND t.status = 'FINISHED' "
                                        + " AND (t.client_id IN (SELECT ? UNION SELECT uid FROM client WHERE sync_group_id = ? ))"
                                        + " AND group_name IS NOT NULL ORDER BY group_name;");

                                st.setLong(1, client.getUid());
                                st.setInt(2, client.getSync_group_id());

                                final ResultSet rs = st.executeQuery();

                                if (rs != null)
                                    while (rs.next())
                                        // netList.put(Helperfunctions.getNetworkTypeName(rs.getInt("network_type")));
                                        netList.put(rs.getString("group_name"));
                                else
                                    errorList.addError("ERROR_DB_GET_SETTING_HISTORY_NETWORKS_SQL");

                                rs.close();
                                st.close();

                                subItem.put("networks", netList);

                            } catch (final SQLException e) {
                                e.printStackTrace();
                                errorList.addError("ERROR_DB_GET_SETTING_HISTORY_SQL");
                                // errorList.addError("ERROR_DB_GET_CLIENT_SQL");
                            }

                            if (errorList.getLength() == 0)
                                jsonItem.put("history", subItem);

                        } else
                            errorList.addError("ERROR_CLIENT_UUID");
                    }

                    //also put there: basis-urls for all services
                    final JSONObject jsonItemURLs = new JSONObject();
                    jsonItemURLs.put("open_data_prefix", getSetting("url_open_data_prefix", lang));
                    jsonItemURLs.put("statistics", getSetting("url_statistics", lang));
                    jsonItemURLs.put("control_ipv4_only", getSetting("control_ipv4_only", lang));
                    jsonItemURLs.put("control_ipv6_only", getSetting("control_ipv6_only", lang));
                    jsonItemURLs.put("url_ipv4_check", getSetting("url_ipv4_check", lang));
                    jsonItemURLs.put("url_ipv6_check", getSetting("url_ipv6_check", lang));

                    jsonItem.put("urls", jsonItemURLs);

                    final JSONObject jsonControlServerVersion = new JSONObject();
                    jsonControlServerVersion.put("control_server_version", RevisionHelper.getVerboseRevision());
                    jsonItem.put("versions", jsonControlServerVersion);

                    try {
                        final Locale locale = new Locale(lang);
                        final QoSTestTypeDescDao testTypeDao = new QoSTestTypeDescDao(conn, locale);
                        final JSONArray testTypeDescArray = new JSONArray();
                        for (QoSTestTypeDesc desc : testTypeDao.getAll()) {
                            JSONObject json = new JSONObject();
                            json.put("test_type", desc.getTestType().name());
                            json.put("name", desc.getName());
                            testTypeDescArray.put(json);
                        }
                        jsonItem.put("qostesttype_desc", testTypeDescArray);
                    } catch (SQLException e) {
                        errorList.addError("ERROR_DB_CONNECTION");
                    }

                    settingsList.put(jsonItem);
                    answer.put("settings", settingsList);

                    //debug: print settings response (JSON)
                    //System.out.println(settingsList);

                } else
                    errorList.addError("ERROR_CLIENT_VERSION");

            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    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();

    //        try
    //        {
    //            System.out.println(answer.toString(4));
    //        }
    //        catch (final JSONException e)
    //        {
    //            e.printStackTrace();
    //        }

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

    return answerString;
}

From source file:it.tidalwave.northernwind.core.model.spi.ParameterLanguageOverrideRequestProcessor.java

/*******************************************************************************************************************
 *
 * {@inheritDoc}/*from w ww .j  a  v  a2  s .co  m*/
 *
 ******************************************************************************************************************/
@Override
@Nonnull
public Status process(final @Nonnull Request request) {
    try {
        final String parameterValue = request.getParameter(parameterName);
        parameterValueHolder.set(parameterValue);
        requestLocaleManager.setRequestLocale(new Locale(parameterValue));
    } catch (NotFoundException e) {
        // ok, no override
    }

    return CONTINUE;
}

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

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();//from   w  w  w .ja  v a 2 s . com

    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_TESTRESULT"), 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);
                final Test test = new Test(conn);

                final String testUuid = request.optString("test_uuid");
                if (testUuid != null && test.getTestByUuid(UUID.fromString(testUuid)) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())
                        && "FINISHED".equals(test.getField("status").toString())) {

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

                    final JSONArray resultList = new JSONArray();

                    final JSONObject jsonItem = new JSONObject();

                    JSONArray jsonItemList = new JSONArray();

                    // RMBTClient Info
                    //also send open-uuid (starts with 'P')
                    final String openUUID = "P" + ((UUIDField) test.getField("open_uuid")).toString();
                    jsonItem.put("open_uuid", openUUID);

                    //and open test-uuid (starts with 'O')
                    final String openTestUUID = "O" + ((UUIDField) test.getField("open_test_uuid")).toString();
                    jsonItem.put("open_test_uuid", openTestUUID);

                    final Date date = ((TimestampField) test.getField("time")).getDate();
                    final long time = date.getTime();
                    final String tzString = test.getField("timezone").toString();
                    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);
                    final String timeString = dateFormat.format(date);
                    jsonItem.put("time_string", timeString);

                    final Field fieldDown = test.getField("speed_download");
                    JSONObject singleItem = new JSONObject();
                    singleItem.put("title", labels.getString("RESULT_DOWNLOAD"));
                    final String downloadString = String.format("%s %s",
                            format.format(fieldDown.doubleValue() / 1000d),
                            labels.getString("RESULT_DOWNLOAD_UNIT"));
                    singleItem.put("value", downloadString);
                    singleItem.put("classification",
                            Classification.classify(classification.THRESHOLD_DOWNLOAD, fieldDown.intValue()));

                    jsonItemList.put(singleItem);

                    final Field fieldUp = test.getField("speed_upload");
                    singleItem = new JSONObject();
                    singleItem.put("title", labels.getString("RESULT_UPLOAD"));
                    final String uploadString = String.format("%s %s",
                            format.format(fieldUp.doubleValue() / 1000d),
                            labels.getString("RESULT_UPLOAD_UNIT"));
                    singleItem.put("value", uploadString);
                    singleItem.put("classification",
                            Classification.classify(classification.THRESHOLD_UPLOAD, fieldUp.intValue()));

                    jsonItemList.put(singleItem);

                    final Field fieldPing = test.getField("ping_median");
                    String pingString = "";
                    if (!fieldPing.isNull()) {
                        final double pingValue = fieldPing.doubleValue() / 1000000d;
                        singleItem = new JSONObject();
                        singleItem.put("title", labels.getString("RESULT_PING"));
                        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.longValue()));

                        jsonItemList.put(singleItem);
                    }

                    final int networkType = test.getField("network_type").intValue();

                    final Field signalField = test.getField("signal_strength"); // signal strength as RSSI (GSM, UMTS, Wifi, sometimes LTE)
                    final Field lteRsrpField = test.getField("lte_rsrp"); // signal strength as RSRP, used in LTE
                    String signalString = null;
                    if (!signalField.isNull() || !lteRsrpField.isNull()) {
                        if (lteRsrpField.isNull()) { // only RSSI value, output RSSI to JSON  
                            final int signalValue = signalField.intValue();
                            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"));
                            signalString = signalValue + " " + labels.getString("RESULT_SIGNAL_UNIT");
                            singleItem.put("value", signalString);
                            singleItem.put("classification", Classification.classify(threshold, signalValue));
                        } else { // use RSRP value else (RSRP value has priority if both are available (e.g. 3G/4G-test))
                            final int signalValue = lteRsrpField.intValue();
                            final int[] threshold = classification.THRESHOLD_SIGNAL_RSRP;
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_SIGNAL_RSRP"));
                            signalString = signalValue + " " + labels.getString("RESULT_SIGNAL_UNIT");
                            singleItem.put("value", signalString);
                            singleItem.put("classification", Classification.classify(threshold, signalValue));

                        }
                        jsonItemList.put(singleItem);
                    }

                    jsonItem.put("measurement", jsonItemList);

                    jsonItemList = new JSONArray();

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

                    jsonItemList.put(singleItem);

                    if (networkType == 98 || networkType == 99) // mobile wifi or browser
                    {
                        final Field providerNameField = test.getField("provider_id_name");
                        if (!providerNameField.isNull()) {
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_OPERATOR_NAME"));
                            singleItem.put("value", providerNameField.toString());
                            jsonItemList.put(singleItem);
                        }
                        if (networkType == 99) // mobile wifi
                        {
                            final Field ssid = test.getField("wifi_ssid");
                            if (!ssid.isNull()) {
                                singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_WIFI_SSID"));
                                singleItem.put("value", ssid.toString());
                                jsonItemList.put(singleItem);
                            }

                        }
                    } else // mobile
                    {
                        final Field operatorNameField = test.getField("network_operator_name");
                        if (!operatorNameField.isNull()) {
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_OPERATOR_NAME"));
                            singleItem.put("value", operatorNameField.toString());
                            jsonItemList.put(singleItem);
                        }

                        final Field roamingTypeField = test.getField("roaming_type");
                        if (!roamingTypeField.isNull() && roamingTypeField.intValue() > 0) {
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_ROAMING"));
                            singleItem.put("value",
                                    Helperfunctions.getRoamingType(labels, roamingTypeField.intValue()));
                            jsonItemList.put(singleItem);
                        }
                    }

                    jsonItem.put("net", jsonItemList);

                    final Field latField = test.getField("geo_lat");
                    final Field longField = test.getField("geo_long");
                    boolean includeLocation = false;
                    final Field accuracyField = test.getField("geo_accuracy");
                    if (!(latField.isNull() || longField.isNull() || accuracyField.isNull())) {
                        final double accuracy = accuracyField.doubleValue();
                        if (accuracy < Double.parseDouble(getSetting("rmbt_geo_accuracy_button_limit", lang))) {
                            includeLocation = true;
                            jsonItem.put("geo_lat", latField.doubleValue());
                            jsonItem.put("geo_long", longField.doubleValue());
                        }
                    }

                    //geo location
                    JSONObject locationJson = TestResultDetailResource.getGeoLocation(this, test, settings,
                            conn, labels);
                    if (locationJson != null) {
                        if (locationJson.has("location")) {
                            jsonItem.put("location", locationJson.getString("location"));
                        }
                        if (locationJson.has("motion")) {
                            jsonItem.put("motion", locationJson.getString("motion"));
                        }
                    }

                    resultList.put(jsonItem);

                    final Field zip_code = test.getField("zip_code");
                    if (!zip_code.isNull())
                        jsonItem.put("zip_code", zip_code.intValue());

                    final Field zip_code_geo = test.getField("zip_code_geo");
                    if (!zip_code_geo.isNull())
                        jsonItem.put("zip_code_geo", zip_code_geo.intValue());

                    String providerString = test.getField("provider_id_name").toString();
                    if (providerString == null)
                        providerString = "";
                    String platformString = test.getField("plattform").toString();
                    if (platformString == null)
                        platformString = "";
                    String modelString = test.getField("model_fullname").toString();
                    if (modelString == null)
                        modelString = "";

                    String mobileNetworkString = null;
                    final Field networkOperatorField = test.getField("network_operator");
                    final Field mobileProviderNameField = test.getField("mobile_provider_name");
                    if (!networkOperatorField.isNull()) {
                        if (mobileProviderNameField.isNull())
                            mobileNetworkString = networkOperatorField.toString();
                        else
                            mobileNetworkString = String.format("%s (%s)", mobileProviderNameField,
                                    networkOperatorField);
                    }

                    /*
                    RESULT_SHARE_TEXT = My Result:\nDate/time: {0}\nDownload: {1}\nUpload: {2}\nPing: {3}\n{4}Network type: {5}\n{6}{7}Platform: {8}\nModel: {9}\n{10}\n\n
                    RESULT_SHARE_TEXT_SIGNAL_ADD = Signal strength: {0}\n
                    RESULT_SHARE_TEXT_RSRP_ADD = Signal strength (RSRP): {0}\n
                    RESULT_SHARE_TEXT_MOBILE_ADD = Mobile network: {0}\n
                    RESULT_SHARE_TEXT_PROVIDER_ADD = Operator: {0}\n
                            
                    */
                    String shareTextField4 = "";
                    if (signalString != null) //info on signal strength, field 4
                        if (lteRsrpField.isNull()) { //add RSSI if RSRP is not available
                            shareTextField4 = MessageFormat
                                    .format(labels.getString("RESULT_SHARE_TEXT_SIGNAL_ADD"), signalString);
                        } else { //add RSRP
                            shareTextField4 = MessageFormat
                                    .format(labels.getString("RESULT_SHARE_TEXT_RSRP_ADD"), signalString);
                        }
                    String shareLocation = "";
                    if (includeLocation && locationJson != null) {

                        shareLocation = MessageFormat.format(labels.getString("RESULT_SHARE_TEXT_LOCATION_ADD"),
                                locationJson.getString("location"));
                    }

                    final String shareText = MessageFormat.format(labels.getString("RESULT_SHARE_TEXT"),
                            timeString, //field 0
                            downloadString, //field 1
                            uploadString, //field 2
                            pingString, //field 3
                            shareTextField4, //contains field 4
                            networkTypeString, //field 5
                            providerString.isEmpty() ? ""
                                    : MessageFormat.format(labels.getString("RESULT_SHARE_TEXT_PROVIDER_ADD"),
                                            providerString), //field 6
                            mobileNetworkString == null ? ""
                                    : MessageFormat.format(labels.getString("RESULT_SHARE_TEXT_MOBILE_ADD"),
                                            mobileNetworkString), //field 7
                            platformString, //field 8
                            modelString, //field 9
                            //dz add location
                            shareLocation, //field 10
                            getSetting("url_open_data_prefix", lang) + openTestUUID); //field 11
                    jsonItem.put("share_text", shareText);

                    final String shareSubject = MessageFormat.format(labels.getString("RESULT_SHARE_SUBJECT"),
                            timeString //field 0
                    );
                    jsonItem.put("share_subject", shareSubject);

                    jsonItem.put("network_type", networkType);

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

                    answer.put("testresult", resultList);
                } 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());
        }
    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_TESTRESULT_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:com.che.software.testato.util.jsf.faces.LocaleController.java

/**
 * Set a new language and consequently, a new locale.
 * //from www  .j  av a 2  s  .  co m
 * @param language the new language to set.
 */
public void setLanguage(String language) {
    LOGGER.debug("setLanguage(" + language + ").");
    locale = new Locale(language);
    FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
}

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

/**
 * testGetLength02()//from  w  w w .  j  a v  a  2s. com
 * <br><br>
 * 
 * ()
 * <br>
 * A
 * <br><br>
 * () super.getLength():0<br>
 *         () getBaseValue():null<br>
 *         
 * <br>
 * () -:1<br>
 *         
 * <br>
 * ?????null???
 * <br>
 * 
 * @throws Exception ?????
 */
@Test
public void testGetLength02() throws Exception {
    // ??
    QName qName = new QName("property");
    BeanPropertyPointerEx_JavaBeanStub01 bean = new BeanPropertyPointerEx_JavaBeanStub01();
    bean.setListProperty(null);
    Locale locale = new Locale("ja");
    NodePointer nodePointer = NodePointer.newNodePointer(qName, bean, locale);

    JXPathBasicBeanInfo beanInfo = new JXPathBasicBeanInfo(bean.getClass());
    BeanPropertyPointerEx pointer = new BeanPropertyPointerEx(nodePointer, beanInfo);
    pointer.setPropertyName("listProperty");

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

From source file:de.ingrid.iplug.sns.gssoil.GsSoilGazetteer3TestLocal.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(idLisbon));
    assertTrue(locations[0].getName().equals("Lisbon"));

    // pass wrong language of text -> still a result!
    locations = gazetteer.getLocationsFromText("Lisbon", 100, false, new Locale("de"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idLisbon));
    assertTrue(locations[0].getName().equals("Lisbon"));

    // pass wrong language of text -> still a result!
    locations = gazetteer.getLocationsFromText("Lisboa", 100, false, new Locale("de"));
    assertTrue(locations.length > 0);
    assertTrue(locations[0].getId().equals(idLisboa));
    assertTrue(locations[0].getName().equals("Lisboa"));

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

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

    // 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);/*from  w  w  w.  j  a va 2s  .c o  m*/

    // 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(idBerlinStadt));
    assertTrue(locations[0].getName().equals("Berlin, Stadt"));

    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"));
    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(idLisbon));
    assertTrue(locations[0].getName().equals("Lisbon"));

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

    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(idLisboa));
    assertTrue(locations[0].getName().equals("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(idLisbon, new Locale("en"));
    assertTrue(location != null);
    assertTrue(location.getId().equals(idLisbon));
    assertTrue(location.getName().equals("Lisbon"));

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

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

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

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

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

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

    // 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:jp.terasoluna.fw.beans.jxpath.BeanPointerExTest.java

/**
 * testBeanPointerExNodePointer01() <br>
 * <br>//  w ww . ja v a  2s  .  co m
 * () <br>
 * A <br>
 * <br>
 * () parent:not null<br>
 * () name:not null<br>
 * () bean:new Object()<br>
 * () beanInfo:not null<br>
 * () this.beanInfo:null<br>
 * <br>
 * () this.beanInfo:???<br>
 * <br>
 * ?? <br>
 * @throws Exception ?????
 */
@Test
public void testBeanPointerExNodePointer01() throws Exception {
    // ??
    QName qName = new QName("name");
    Object bean = new Object();
    JXPathBeanInfo beanInfo = new JXPathBasicBeanInfo(bean.getClass());
    Locale locale = new Locale("ja");
    NodePointer nodePointer = NodePointer.newNodePointer(qName, bean, locale);

    // 
    BeanPointerEx result = new BeanPointerEx(nodePointer, qName, bean, beanInfo);

    // 
    assertEquals(beanInfo, ReflectionTestUtils.getField(result, "beanInfo"));
}

From source file:es.pode.visualizador.presentacion.conexionFlash.conexionFlashControllerImpl.java

/**
 * @see es.pode.visualizador.presentacion.conexionFlash.conexionFlashController#construirXML(org.apache.struts.action.ActionMapping, es.pode.visualizador.presentacion.conexionFlash.ConstruirXMLForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   w w w . j  a  v a2s .c  om
public final void construirXML(ActionMapping mapping,
        es.pode.visualizador.presentacion.conexionFlash.ConstruirXMLForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    //Recogemos de la request las palabras con la que hacemos la busqueda y el idioma
    String palabras = request.getParameter("palabras");
    String idioma = request.getParameter("idioma");

    //construimos un locale con el idioma que nos viene como paramatro
    Locale locale = new Locale(idioma);

    //recogemos la url por defecto de soporte
    String urlImagenDefecto = AgregaPropertiesImpl.getInstance()
            .getProperty(AgregaProperties.URL_IMAGEN_DEFECTO_GRANDE);
    String urlLogoAgrega = AgregaPropertiesImpl.getInstance().getProperty(AgregaProperties.URL_LOGO_AGREGA);

    //declaramos ficheroRecursos para poder acceder al fichero de las etiquetas y recoger la url de la ficha
    ficheroRecursos = ResourceBundle.getBundle("application-resources", locale);
    String urlFicha = ficheroRecursos.getString("agregaSlider.url.ficha");

    //recogemos el nodo correspodiente desde soporte
    String nodo = AgregaPropertiesImpl.getInstance().getProperty(AgregaProperties.HOST);

    //declaramos los VOs de recogida y envio para la llamada al buscar
    ParametrosBusquedaAvanzadaVO parametros = new ParametrosBusquedaAvanzadaVO();
    ResultadoBusquedaVO resultado = new ResultadoBusquedaVO();
    ValoresBusquedaVO[] valoresBusqueda;

    //rellenamos el VO que tenemos que pasarle al buscar para realizar la busqueda de imagenes
    log("Rellenamos el VO para pasarlo al buscar");
    parametros.setPalabrasClave(palabras);
    parametros.setIdiomaBusqueda(idioma);
    parametros.setIdiomaNavegacion(idioma);
    parametros.setBusquedaSimpleAvanzada("Busqueda AgregaSlider");
    parametros.setNumeroResultados(new Integer(20));
    parametros.setOrigenPagina(new Integer(1));
    parametros.setResultadosPorPagina(new Integer(20));
    parametros.setComunidadPeticion(nodo);

    //rellenamos la primera linea del xml
    String xml = "<?xml version='1.0' encoding='utf-8'?> <GALERIA>";

    //rellenamos la primera posicion con los datos de la portada de la aplicacion para asociarla al logo agrega
    xml += "<IMAGEN " + "TITULO='portada' " + "URL_FICHA='http://" + nodo
            + AgregaPropertiesImpl.getInstance().getProperty("admin.ws.subdominio")
            + "/visualizadorcontenidos/Portada/Portada.do' " + "URL_IMAGEN='http://" + nodo
            + AgregaPropertiesImpl.getInstance().getProperty("admin.ws.subdominio") + "/" + urlLogoAgrega
            + "' />";

    try {

        //llamamos al servicio buscar
        resultado = this.getSrvBuscarService().buscarAvanzado(parametros);
        valoresBusqueda = resultado.getResultadoBusqueda();
        log("valores de  busqueda : " + valoresBusqueda.length);

        if (valoresBusqueda.length != 0) {

            //recorremos el array de imagenes para construir la url de la imagen correstamente y si no tuviera asignarle una por defecto
            String url = new String();
            for (int i = 0; i < valoresBusqueda.length; i++) {
                if (valoresBusqueda[i].getUrlImagen() == null
                        || valoresBusqueda[i].getUrlImagen().equalsIgnoreCase("")) {
                    valoresBusqueda[i].setUrlImagen(urlImagenDefecto);
                    log("no hay imagen en" + valoresBusqueda[i].getTitulo());

                } else {
                    //Contruimos la url de la imagen
                    url = valoresBusqueda[i].getUrlImagen();
                    String urls[] = url.split("\\.");
                    url = urls[0] + "_captured.jpg";
                    valoresBusqueda[i].setUrlImagen(url);

                    //filtramos para que en el titulo no aparezcan comillas
                    String cadena = valoresBusqueda[i].getTitulo();
                    valoresBusqueda[i].setTitulo(StringEscapeUtils.escapeXml(cadena));
                }
            }

            //se rellena el xml con los datos devueltos del busca

            log("se han encontrado" + valoresBusqueda.length + "elementos");
            for (int i = 0; i < valoresBusqueda.length; i++) {
                log("valoresBusqueda[i].getUrlImagen() " + i + ":" + valoresBusqueda[i].getUrlImagen());
                xml += "<IMAGEN " + "TITULO='" + valoresBusqueda[i].getTitulo() + "' " + "URL_FICHA='http://"
                        + nodo + AgregaPropertiesImpl.getInstance().getProperty("admin.ws.subdominio") + "/"
                        + urlFicha + "/" + idioma + "/" + valoresBusqueda[i].getId() + "' "
                        + "URL_IMAGEN='http://" + nodo
                        + AgregaPropertiesImpl.getInstance().getProperty("admin.ws.subdominio") + "/"
                        + valoresBusqueda[i].getUrlImagen() + "' />";
            }
            xml += "</GALERIA>";
        } else {
            log("No se ha encontrado nada en el buscar y se rellena manualmente");
            log("urlImagenDefecto " + urlImagenDefecto);
            //Se rellena el xml con una imagen por defecto porque no se ha encontrado ninguna
            xml += "<IMAGEN TITULO='Imagen Agrega' URL_FICHA='#' " + "URL_IMAGEN='http://" + nodo
                    + AgregaPropertiesImpl.getInstance().getProperty("admin.ws.subdominio") + "/"
                    + urlImagenDefecto + "'/>" + "</GALERIA>";
        }

    } catch (Exception e) {
        log.error("exception en concexion flash " + e);
        //Se rellena el xml con una imagen por defecto porque no se ha encontrado ninguna
        xml += "<IMAGEN TITULO='Imagen Agrega' URL_FICHA='#' " + "URL_IMAGEN='http://" + nodo
                + AgregaPropertiesImpl.getInstance().getProperty("admin.ws.subdominio") + "/" + urlImagenDefecto
                + "'/>" + "</GALERIA>";
    }

    log(xml);
    //Mandamos el xml a flash como un array de bytes
    log("Mandamos el xml a flash como un array de bytes");

    response.setContentType("text/xml");

    OutputStream out = (OutputStream) response.getOutputStream();
    out.write(xml.getBytes());

    out.flush();
    out.close();

    log("Se ha mandado a flash el xml");
}