Example usage for java.util Locale toString

List of usage examples for java.util Locale toString

Introduction

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

Prototype

@Override
public final String toString() 

Source Link

Document

Returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions as below:
language + "_" + country + "_" + (variant + "_#" | "#") + script + "_" + extensions
Language is always lower case, country is always upper case, script is always title case, and extensions are always lower case.

Usage

From source file:com.playhaven.android.req.PlayHavenRequest.java

@SuppressWarnings("deprecation")
protected UriComponentsBuilder createUrl(Context context) throws PlayHavenException {
    try {//from ww  w  .  jav  a 2s.  co  m
        SharedPreferences pref = PlayHaven.getPreferences(context);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(getString(pref, APIServer));
        builder.path(context.getResources().getString(getApiPath(context)));
        builder.queryParam("app", getString(pref, AppPkg));
        builder.queryParam("opt_out", getString(pref, OptOut, "0"));
        builder.queryParam("app_version", getString(pref, AppVersion));
        builder.queryParam("os", getInt(pref, OSVersion, 0));
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        builder.queryParam("orientation", display.getRotation());
        builder.queryParam("hardware", getString(pref, DeviceModel));
        PlayHaven.ConnectionType connectionType = getConnectionType(context);
        builder.queryParam("connection", connectionType.ordinal());
        builder.queryParam("idiom",
                context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK);

        /**
         * For height/width we will use getSize(Point) not getRealSize(Point) as this will allow us to automatically
         * account for rotation and screen decorations like the status bar. We only want to know available space.
         *
         * @playhaven.apihack for SDK_INT < 13, have to use getHeight and getWidth!
         */
        Point size = new Point();
        if (Build.VERSION.SDK_INT >= 13) {
            display.getSize(size);
        } else {
            size.x = display.getWidth();
            size.y = display.getHeight();
        }
        builder.queryParam("width", size.x);
        builder.queryParam("height", size.y);

        /**
         * SDK Version needs to be reported as a dotted numeric value
         * So, if it is a -SNAPSHOT build, we will replace -SNAPSHOT with the date of the build
         * IE: 2.0.0.20130201
         * as opposed to an actual released build, which would be like 2.0.0
         */
        String sdkVersion = getString(pref, SDKVersion);
        String[] date = Version.PLUGIN_BUILD_TIME.split("[\\s]");
        sdkVersion = sdkVersion.replace("-SNAPSHOT", "." + date[0].replaceAll("-", ""));
        builder.queryParam("sdk_version", sdkVersion);

        builder.queryParam("plugin", getString(pref, PluginIdentifer));

        Locale locale = context.getResources().getConfiguration().locale;
        builder.queryParam("languages", String.format("%s,%s", locale.toString(), locale.getLanguage()));
        builder.queryParam("token", getString(pref, Token));

        builder.queryParam("device", getString(pref, DeviceId));
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        builder.queryParam("dpi", metrics.densityDpi);

        String uuid = UUID.randomUUID().toString();
        String nonce = base64Digest(uuid);
        builder.queryParam("nonce", nonce);

        ktsid = KontagentUtil.getSenderId(context);
        if (ktsid != null)
            builder.queryParam("sid", ktsid);

        addSignature(builder, pref, nonce);

        // Setup for signature verification
        String secret = getString(pref, Secret);
        SecretKeySpec key = new SecretKeySpec(secret.getBytes(UTF8), HMAC);
        sigMac = Mac.getInstance(HMAC);
        sigMac.init(key);
        sigMac.update(nonce.getBytes(UTF8));

        return builder;
    } catch (Exception e) {
        throw new PlayHavenException(e);
    }
}

From source file:org.enerj.apache.commons.beanutils.locale.LocaleConvertUtilsBean.java

/**
 * Convert an array of specified values to an array of objects of the
 * specified class (if possible) using the convertion pattern.
 *
 * @param values Value to be converted (may be null)
 * @param clazz Java array or element class to be converted to
 * @param locale The locale/*from   w  w w  .  j  a  v  a 2  s. c o m*/
 * @param pattern The convertion pattern
 *
 * @exception ConversionException if thrown by an underlying Converter
 */
public Object convert(String values[], Class clazz, Locale locale, String pattern) {

    Class type = clazz;
    if (clazz.isArray()) {
        type = clazz.getComponentType();
    }
    if (log.isDebugEnabled()) {
        log.debug("Convert String[" + values.length + "] to class " + type.getName() + "[] using "
                + locale.toString() + " locale and " + pattern + " pattern");
    }

    Object array = Array.newInstance(type, values.length);
    for (int i = 0; i < values.length; i++) {
        Array.set(array, i, convert(values[i], type, locale, pattern));
    }

    return (array);
}

From source file:com.amazonaws.mobileconnectors.pinpoint.analytics.AnalyticsEvent.java

@Override
public JSONObject toJSONObject() {
    final Locale locale = this.deviceDetails.locale();
    final String localeString = locale != null ? locale.toString() : "UNKNOWN";

    final JSONBuilder builder = new JSONBuilder(this);

    // ****************************************************
    // ==================System Attributes=================
    // ****************************************************
    builder.withAttribute("event_id", getEventId());
    builder.withAttribute("event_type", getEventType());
    builder.withAttribute("unique_id", getUniqueId());
    builder.withAttribute("timestamp", getEventTimestamp());

    // ****************************************************
    // ==============Device Details Attributes=============
    // ****************************************************
    builder.withAttribute("platform", this.deviceDetails.platform());
    builder.withAttribute("platform_version", this.deviceDetails.platformVersion());
    builder.withAttribute("make", this.deviceDetails.manufacturer());
    builder.withAttribute("model", this.deviceDetails.model());
    builder.withAttribute("locale", localeString);
    builder.withAttribute("carrier", this.deviceDetails.carrier());

    // ****************************************************
    // ==============Session Attributes=============
    // ****************************************************
    final JSONObject sessionObject = new JSONObject();
    try {/*from  www . jav  a 2  s.c  o  m*/
        sessionObject.put("id", session.getSessionId());
        if (session.getSessionStart() != null) {
            sessionObject.put("startTimestamp", session.getSessionStart());
        }
        if (session.getSessionStop() != null) {
            sessionObject.put("stopTimestamp", session.getSessionStop());
        }
        if (session.getSessionDuration() != null) {
            sessionObject.put("duration", session.getSessionDuration().longValue());
        }
    } catch (final JSONException e) {
        log.error("Error serializing session information", e);
    }
    builder.withAttribute("session", sessionObject);

    // ****************************************************
    // ====SDK Details Attributes -- Prefix with 'sdk_'====
    // ****************************************************
    builder.withAttribute("sdk_version", this.sdkVersion);
    builder.withAttribute("sdk_name", this.sdkName);

    // ****************************************************
    // Application Details Attributes -- Prefix with 'app_'
    // ****************************************************
    builder.withAttribute("app_version_name", this.appDetails.versionName());
    builder.withAttribute("app_version_code", this.appDetails.versionCode());
    builder.withAttribute("app_package_name", this.appDetails.packageName());
    builder.withAttribute("app_title", this.appDetails.getAppTitle());
    builder.withAttribute(ClientContext.APP_ID_KEY, this.appDetails.getAppId());

    final JSONObject attributesJson = new JSONObject();
    for (final Entry<String, String> entry : getAllAttributes().entrySet()) {
        try {
            attributesJson.put(entry.getKey(), entry.getValue());
        } catch (final JSONException e) {
            // Do not log e due to potentially sensitive information
            log.error("Error serializing attribute for eventType: " + eventType);
        }
    }

    final JSONObject metricsJson = new JSONObject();
    for (final Entry<String, Double> entry : getAllMetrics().entrySet()) {
        try {
            metricsJson.put(entry.getKey(), entry.getValue());
        } catch (final JSONException e) {
            // Do not log e due to potentially sensitive information
            log.error("Error serializing metric for eventType: " + eventType);
        }
    }

    // If there are any attributes put then add the attributes to the
    // structure
    if (attributesJson.length() > 0) {
        builder.withAttribute("attributes", attributesJson);
    }

    // If there are any metrics put then add the attributes to the structure
    if (metricsJson.length() > 0) {
        builder.withAttribute("metrics", metricsJson);
    }
    return builder.toJSONObject();
}

From source file:org.eclipse.jubula.autagent.commands.StartRcpAutServerCommand.java

/**
 * {@inheritDoc}//from  ww w. j a  va 2s  . co m
 */
protected String[] createCmdArray(String baseCmd, Map<String, String> parameters) {

    List<String> cmds;

    if (!isRunningFromExecutable(parameters)) {
        // Start using java
        cmds = createDirectAutJavaCall(parameters);
        cmds.add(0, baseCmd);

        createDirectAutJavaCallParameter(PATH_SEPARATOR, cmds, parameters);
        addLocale(cmds, LocaleUtils.toLocale(parameters.get(AutConfigConstants.AUT_LOCALE)));
    } else {
        // Start using executable file
        cmds = new Vector<String>();

        cmds.add(0, baseCmd);

        createDirectAutExeCallParameter(cmds, parameters);
        // add locale
        // Note: This overrides the -nl defined in the <app>.ini file, if
        // any. It will not override a -nl from the command line.
        if (!cmds.contains(NL)) {
            Locale locale = LocaleUtils.toLocale(parameters.get(AutConfigConstants.AUT_LOCALE));
            if (locale != null) {
                if ((locale.getCountry() != null && locale.getCountry().length() > 0)
                        || (locale.getLanguage() != null && locale.getLanguage().length() > 0)) {

                    // Add -nl argument if country and/or language is
                    // available.
                    cmds.add(1, NL);
                    cmds.add(2, locale.toString());
                }
            }
        }
        addDebugParams(cmds, true);
    }

    String[] cmdArray = cmds.toArray(new String[cmds.size()]);
    return cmdArray;
}

From source file:com.erudika.scoold.utils.ScooldUtils.java

public Map<String, String> getLang(Locale currentLocale) {
    Map<String, String> lang = langutils.readLanguage(currentLocale.toString());
    if (lang == null || lang.isEmpty()) {
        lang = langutils.getDefaultLanguage();
    }//from  w  w w .ja  va 2s  .c o  m
    return lang;
}

From source file:com.bluexml.side.Framework.alfresco.notification.NotificationHelper.java

/**
 * This method loads the 'notification_<language>.properties' file from the Dictionary path of Alfresco repository and then overwrite the properties 
 * whith the properties files successively contains in resourceCustomPaths[i]+"/cm:"+propertyFileName.basename+<language>+propertyFileName.extension
 * @param language the language to load; if not null the propertyFileName is modified in propertyFileName.basename+<language>+propertyFileName.extension; if null the propertyFileName is not modified
 * @param propertyFileName the property file name to load
 * @param resourceCustomPaths a list of folder where the propertyFileName may be loaded (with the embedded language if not null)
 * @return the set of properties for this language
 * @throws Exception/*from   www  .ja  v  a 2 s  .  c  om*/
 */
public Properties getPropertiesFor(String language, String propertyFileName,
        ArrayList<String> resourceCustomPaths) throws Exception {
    if (props == null) {
        props = new HashMap<String, Properties>();
    }
    if (language == null) {
        Locale loc = I18NUtil.getLocale();
        if (loc == null || loc.toString() == null) {
            language = "fr_FR";
        } else {
            language = loc.toString();
        }
    }
    logger.trace("language :" + language);
    Properties langueExist = props.get(language);
    if (langueExist == null || dynamicLoading) {
        // load properties
        Properties prop = getProperties(language, propertyFileName, resourceCustomPaths);
        props.put(language, prop);
    }
    // not dynamic so return cached object
    return props.get(language);
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHttpResponse.java

/**
 * Sets the locale of the response, setting the headers (including the
 * Content-Type's charset) as appropriate.  This method should be called
 * before a call to {@link #getWriter}.  By default, the response locale
 * is the default locale for the server.
 * /* ww  w  . j  a va  2 s .co  m*/
 * @see   #getLocale
 * @param locale the Locale of the response
 */
public void setLocale(Locale locale) {
    if (locale == null || isCommitted())
        return;

    _locale = locale;
    setHeader(HttpFields.__ContentLanguage, locale.toString().replace('_', '-'));

    if (this._outputState == 0) {
        /* get current MIME type from Content-Type header */
        String type = _httpResponse.getField(HttpFields.__ContentType);
        if (type == null) {
            // servlet did not set Content-Type yet
            // so lets assume default one
            type = "application/octet-stream";
        }

        HttpContext httpContext = _servletHttpRequest.getServletHandler().getHttpContext();
        if (httpContext instanceof ServletHttpContext) {
            String charset = ((ServletHttpContext) httpContext).getLocaleEncoding(locale);
            if (charset != null && charset.length() > 0) {
                int semi = type.indexOf(';');
                if (semi < 0)
                    type += "; charset=" + charset;
                else if (!_charEncodingSetInContentType)
                    type = type.substring(0, semi) + "; charset=" + charset;

                setHeader(HttpFields.__ContentType, type);
            }

        }
    }
}

From source file:no.abmu.abmstatistikk.web.AbstractReportController.java

protected ModelAndView createMAVForOrganisationUnit(HttpServletRequest request, String view,
        SchemaTypeNameAndVersion schemaTypeNameAndVersion) {

    Assert.checkRequiredArgument("request", request);
    Assert.checkRequiredArgument("view", view);
    Assert.checkRequiredArgument("schemaTypeAndName", schemaTypeNameAndVersion);

    StopWatch stopWatch = new StopWatch();
    stopWatch.start("private_createMAVForOrganisationUnit");

    if (noLoggedOnStatusInfo(request)) {
        logger.error("No loggedOnStatus exists, logout.");
        return new ModelAndView(ViewNameConst.LOGOFF_VIEW);
    }/*w  ww .  j av a  2  s  .  com*/

    Long workingSchemaOrgUnitId = changeWorkingSchemaOrgUnitIdOrGetCurrent(request);
    if (workingSchemaOrgUnitId == null) {
        logger.error("No workingSchemaOrgUnitId or LoggedOnOrgUnitId exists, log off");
        return new ModelAndView(ViewNameConst.LOGOFF_VIEW);

    }

    //        String schemaVersion = Integer.toString(reportPeriod);
    OrgUnitFinderSpecificationBean finderBean = new OrgUnitFinderSpecificationBean();
    finderBean.setOrganisationUnitId(workingSchemaOrgUnitId);

    SchemaList jasperReportDataSource = reportService.createFullReportData(finderBean,
            schemaTypeNameAndVersion);

    if (schemaTypeNameAndVersion.getYear() >= 2009
            && schemaTypeNameAndVersion.getSchemaName().equals(SchemaName.KUD_CULTURAL_ACTIVITY_REPORT)) {
        int reportPeriod = schemaTypeNameAndVersion.getYear();

        int oneYearBack = reportPeriod - 1;
        String prefixOneYearBack = "LastYear";
        SchemaTypeNameAndVersion kudActivitySchemaAndVersionOneYearBack = SchemaTypeNameAndVersion
                .newInstance(SchemaName.KUD_CULTURAL_ACTIVITY_REPORT, oneYearBack);

        reportService.getReportDataForOrganisationUnits(jasperReportDataSource,
                kudActivitySchemaAndVersionOneYearBack, prefixOneYearBack);

        int twoYearBack = reportPeriod - 2;
        String prefixTwoYearBack = "YearBeforeLastYear";
        SchemaTypeNameAndVersion kudActivitySchemaAndVersionTwoYearBack = SchemaTypeNameAndVersion
                .newInstance(SchemaName.KUD_CULTURAL_ACTIVITY_REPORT, twoYearBack);
        reportService.getReportDataForOrganisationUnits(jasperReportDataSource,
                kudActivitySchemaAndVersionTwoYearBack, prefixTwoYearBack);

    }

    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();

    SchemaPdfLogo pdfLogo = SchemaPdfLogo.newInstance(schemaTypeNameAndVersion);

    Locale locale = sessionLocaleResolver.resolveLocale(request);
    logger.info("We are using locale=[" + locale.toString() + "]");

    int reportPeriod = schemaTypeNameAndVersion.getYear();
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("logourl", pdfLogo.getLogoUrl());
    model.put("logoheight", pdfLogo.getLogoHeight());
    model.put("logowidth", pdfLogo.getLogoWidth());
    model.put("reportData", jasperReportDataSource);
    model.put("abmstatistikk.reportPeriod", Integer.toString(reportPeriod));
    model.put("abmstatistikk.budgetYear", Integer.toString(reportPeriod + 1));
    model.put(JRParameter.REPORT_LOCALE, locale);

    ModelAndView mav = new ModelAndView(view, model);

    stopWatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("[private:createMAVForOrganisationUnit] tok[" + stopWatch.getTotalTimeMillis() + "] ms");
    }

    return mav;
}

From source file:fr.mailjet.rest.impl.MessageRESTServiceImpl.java

@Override
public String tplModels(EnumReturnType parType, Integer parCategory, Boolean parCustom, Locale parLocale)
        throws UniformInterfaceException {
    MultivaluedMap<String, String> locParameters = this.createHTTPProperties(parType);
    if (parCategory != null) {
        locParameters.putSingle(_categoryTplModel, parCategory.toString());
    }/*from   w  ww  .  j  av a  2  s. c  om*/
    if (parCustom != null) {
        locParameters.putSingle(_customTplModel, parCustom.toString());
    }
    if (parLocale != null) {
        locParameters.putSingle(_localeTplModel, parLocale.toString());
    }
    return this.createGETRequest("messageTplcategories", locParameters);
}

From source file:com.vmware.identity.SsoController.java

/**
 * Handle request sent with a wrong binding
 *///from  w ww.  ja va  2 s.c o m
@RequestMapping(value = "/SAML2/SSO/{tenant:.*}")
public void ssoBindingError(Locale locale, @PathVariable(value = "tenant") String tenant,
        HttpServletResponse response) throws IOException {
    logger.info("SSO binding error! The client locale is " + locale.toString() + ", tenant is " + tenant);

    ssoDefaultTenantBindingError(locale, response);
}