java.util.Locale Java Examples
The following examples show how to use
java.util.Locale.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MathRuntimeException.java From tomee with Apache License 2.0 | 6 votes |
/** * Constructs a new <code>NullPointerException</code> with specified formatted detail message. * Message formatting is delegated to {@link MessageFormat}. * * @param pattern format specifier * @param arguments format arguments * @return built exception */ public static NullPointerException createNullPointerException(final String pattern, final Object... arguments) { return new NullPointerException() { /** Serializable version identifier. */ private static final long serialVersionUID = -3075660477939965216L; /** {@inheritDoc} */ @Override public String getMessage() { return buildMessage(Locale.US, pattern, arguments); } /** {@inheritDoc} */ @Override public String getLocalizedMessage() { return buildMessage(Locale.getDefault(), pattern, arguments); } }; }
Example #2
Source File: Time.java From OpenDA with GNU Lesser General Public License v3.0 | 6 votes |
/** * Represent the time object as string * * @return string representation of time * @param time Time to be presented as string */ public static String asDateString(ITime time) { String result; if (time.isStamp()) { result = timeStampToDate(time.getMJD()).toString(); } else { if ((time.getEndTime().getMJD() - time.getBeginTime().getMJD()) < getTimePrecision()) { result = timeStampToDate(0.5 * (time.getBeginTime().getMJD() + time.getEndTime().getMJD())).toString(); } else { Locale locale = new Locale("EN"); String stepFormat = "%6.6f"; result = timeStampToDate(time.getBeginTime().getMJD()).toString() + " - step=" + String.format(locale, stepFormat, time.getStepMJD()) + " - " + timeStampToDate(time.getEndTime().getMJD()); } } return result; }
Example #3
Source File: EastAsianST.java From Time4A with Apache License 2.0 | 6 votes |
@Override public String getDisplayName(Locale locale) { String lang = locale.getLanguage(); if (lang.equals("zh")) { return locale.getCountry().equals("TW") ? "節氣" : "节气"; } else if (lang.equals("ko")) { return "절기"; } else if (lang.equals("vi")) { return "tiết khí"; } else if (lang.equals("ja")) { return "節気"; } else if (lang.isEmpty()) { return "jieqi"; } else { return "jiéqì"; // pinyin } }
Example #4
Source File: RichDiagnosticFormatter.java From lua-for-android with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public String visitMethodSymbol(MethodSymbol s, Locale locale) { String ownerName = visit(s.owner, locale); if (s.isStaticOrInstanceInit()) { return ownerName; } else { String ms = (s.name == s.name.table.names.init) ? ownerName : s.name.toString(); if (s.type != null) { if (s.type.hasTag(FORALL)) { ms = "<" + visitTypes(s.type.getTypeArguments(), locale) + ">" + ms; } ms += "(" + printMethodArgs( s.type.getParameterTypes(), (s.flags() & VARARGS) != 0, locale) + ")"; } return ms; } }
Example #5
Source File: JsetsLogoutFilter.java From jsets-shiro-spring-boot-starter with Apache License 2.0 | 6 votes |
@Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); // Check if POST only logout is enabled if (isPostOnlyLogout()) { // check if the current request's method is a POST, if not redirect if (!WebUtils.toHttp(request).getMethod().toUpperCase(Locale.ENGLISH).equals("POST")) { return onLogoutRequestNotAPost(request, response); } } String redirectUrl = getRedirectUrl(request, response, subject); //try/catch added for SHIRO-298: try { String account = (String) subject.getPrincipal(); subject.logout(); this.authListenerManager.onLogout(request, account); } catch (SessionException ise) { LOGGER.debug("Encountered session exception during logout. This can generally safely be ignored.", ise); } issueRedirect(request, response, redirectUrl); return false; }
Example #6
Source File: FileNameExtensionFilter.java From Java8CN with Apache License 2.0 | 6 votes |
/** * Creates a {@code FileNameExtensionFilter} with the specified * description and file name extensions. The returned {@code * FileNameExtensionFilter} will accept all directories and any * file with a file name extension contained in {@code extensions}. * * @param description textual description for the filter, may be * {@code null} * @param extensions the accepted file name extensions * @throws IllegalArgumentException if extensions is {@code null}, empty, * contains {@code null}, or contains an empty string * @see #accept */ public FileNameExtensionFilter(String description, String... extensions) { if (extensions == null || extensions.length == 0) { throw new IllegalArgumentException( "Extensions must be non-null and not empty"); } this.description = description; this.extensions = new String[extensions.length]; this.lowerCaseExtensions = new String[extensions.length]; for (int i = 0; i < extensions.length; i++) { if (extensions[i] == null || extensions[i].length() == 0) { throw new IllegalArgumentException( "Each extension must be non-null and not empty"); } this.extensions[i] = extensions[i]; lowerCaseExtensions[i] = extensions[i].toLowerCase(Locale.ENGLISH); } }
Example #7
Source File: Test6524757.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) { Locale reservedLocale = Locale.getDefault(); try { // it affects Swing because it is not initialized Locale.setDefault(Locale.KOREAN); validate(KOREAN, create()); // it does not affect Swing because it is initialized Locale.setDefault(Locale.CANADA); validate(KOREAN, create()); // it definitely should affect Swing JComponent.setDefaultLocale(Locale.FRENCH); validate(FRENCH, create()); } finally { // restore the reserved locale Locale.setDefault(reservedLocale); } }
Example #8
Source File: SyslogAuditLogProtocolResourceDefinition.java From wildfly-core with GNU Lesser General Public License v2.1 | 6 votes |
public static void createServerAddOperations(final List<ModelNode> addOps, final PathAddress protocolAddress, final ModelNode protocol) { addOps.add(createProtocolAddOperation(protocolAddress, protocol)); final SyslogAuditLogHandler.Transport transport = SyslogAuditLogHandler.Transport.valueOf(protocolAddress.getLastElement().getValue().toUpperCase(Locale.ENGLISH)); if (transport == SyslogAuditLogHandler.Transport.TLS){ if (protocol.hasDefined(AUTHENTICATION)){ final ModelNode auth = protocol.get(AUTHENTICATION); if (auth.hasDefined(TRUSTSTORE)){ addOps.add(createKeystoreAddOperation(protocolAddress.append(AUTHENTICATION, TRUSTSTORE), protocol.get(AUTHENTICATION, TRUSTSTORE))); } if (auth.hasDefined(CLIENT_CERT_STORE)){ addOps.add(createKeystoreAddOperation(protocolAddress.append(AUTHENTICATION, CLIENT_CERT_STORE), protocol.get(AUTHENTICATION, CLIENT_CERT_STORE))); } } } }
Example #9
Source File: ZoneName.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
public static String toZid(String zid, Locale locale) { String mzone = zidToMzone.get(zid); if (mzone == null && aliases.containsKey(zid)) { zid = aliases.get(zid); mzone = zidToMzone.get(zid); } if (mzone != null) { Map<String, String> map = mzoneToZidL.get(mzone); if (map != null && map.containsKey(locale.getCountry())) { zid = map.get(locale.getCountry()); } else { zid = mzoneToZid.get(mzone); } } return toZid(zid); }
Example #10
Source File: RestAnomalyDetectorJobAction.java From anomaly-detection with Apache License 2.0 | 6 votes |
@Override public List<Route> routes() { return ImmutableList .of( // start AD job new Route( RestRequest.Method.POST, String.format(Locale.ROOT, "%s/{%s}/%s", AnomalyDetectorPlugin.AD_BASE_DETECTORS_URI, DETECTOR_ID, START_JOB) ), // stop AD job new Route( RestRequest.Method.POST, String.format(Locale.ROOT, "%s/{%s}/%s", AnomalyDetectorPlugin.AD_BASE_DETECTORS_URI, DETECTOR_ID, STOP_JOB) ) ); }
Example #11
Source File: TimeZoneNameUtility.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
private static String examineAliases(TimeZoneNameProvider tznp, Locale locale, String requestID, String tzid, int style, Map<String, String> aliases) { if (aliases.containsValue(tzid)) { for (Map.Entry<String, String> entry : aliases.entrySet()) { if (entry.getValue().equals(tzid)) { String alias = entry.getKey(); String name = getName(tznp, locale, requestID, style, alias); if (name != null) { return name; } name = examineAliases(tznp, locale, requestID, alias, style, aliases); if (name != null) { return name; } } } } return null; }
Example #12
Source File: LocaleUtils.java From AOSP-Kayboard-7.1.2 with Apache License 2.0 | 6 votes |
/** * Execute {@link #job(Resources)} method in specified system locale exclusively. * * @param res the resources to use. Pass current resources. * @param newLocale the locale to change to * @return the value returned from {@link #job(Resources)}. */ public T runInLocale(final Resources res, final Locale newLocale) { synchronized (sLockForRunInLocale) { final Configuration conf = res.getConfiguration(); final Locale oldLocale = conf.locale; try { if (newLocale != null && !newLocale.equals(oldLocale)) { conf.locale = newLocale; res.updateConfiguration(conf, null); } return job(res); } finally { if (newLocale != null && !newLocale.equals(oldLocale)) { conf.locale = oldLocale; res.updateConfiguration(conf, null); } } } }
Example #13
Source File: LanguageString.java From mollyim-android with GNU General Public License v3.0 | 5 votes |
private static boolean isValid(@NonNull Locale locale) { try { return locale.getISO3Language() != null && locale.getISO3Country() != null; } catch (Exception ex) { return false; } }
Example #14
Source File: MediaActionTypeProvider.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
/** * This method creates one option for every sink that is found in the system. * * @return a list of parameter options representing the audio sinks */ private List<ParameterOption> getSinkOptions(@Nullable Locale locale) { List<ParameterOption> options = new ArrayList<>(); for (AudioSink sink : audioManager.getAllSinks()) { options.add(new ParameterOption(sink.getId(), sink.getLabel(locale))); } return options; }
Example #15
Source File: ChannelTypeI18nLocalizationService.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
public List<CommandOption> createLocalizedCommandOptions(final Bundle bundle, List<CommandOption> commandOptions, final ChannelTypeUID channelTypeUID, final @Nullable Locale locale) { List<CommandOption> localizedOptions = new ArrayList<>(); for (final CommandOption commandOption : commandOptions) { String optionLabel = commandOption.getLabel(); if (optionLabel != null) { optionLabel = thingTypeI18nUtil.getChannelCommandOption(bundle, channelTypeUID, commandOption.getCommand(), optionLabel, locale); } localizedOptions.add(new CommandOption(commandOption.getCommand(), optionLabel)); } return localizedOptions; }
Example #16
Source File: UserManagement.java From opencps-v2 with GNU Affero General Public License v3.0 | 5 votes |
@GET @Path("/{id}/sites") @Consumes({ MediaType.APPLICATION_FORM_URLENCODED }) @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response getSites(@Context HttpServletRequest request, @Context HttpHeaders header, @Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext, @PathParam("id") long id);
Example #17
Source File: AngularCookieLocaleResolver.java From angularjs-springboot-bookstore with MIT License | 5 votes |
private void parseLocaleCookieIfNecessary(HttpServletRequest request) { if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) { // Retrieve and parse cookie value. Cookie cookie = WebUtils.getCookie(request, getCookieName()); Locale locale = null; TimeZone timeZone = null; if (cookie != null) { String value = cookie.getValue(); // Remove the double quote value = StringUtils.replace(value, "%22", ""); String localePart = value; String timeZonePart = null; int spaceIndex = localePart.indexOf(' '); if (spaceIndex != -1) { localePart = value.substring(0, spaceIndex); timeZonePart = value.substring(spaceIndex + 1); } locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null); if (timeZonePart != null) { timeZone = StringUtils.parseTimeZoneString(timeZonePart); } if (logger.isTraceEnabled()) { logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale + "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : "")); } } request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME, (locale != null ? locale: determineDefaultLocale(request))); request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, (timeZone != null ? timeZone : determineDefaultTimeZone(request))); } }
Example #18
Source File: Configurations.java From Chisel-2 with GNU General Public License v2.0 | 5 votes |
/** * Makes the old camelCase names from the new CONSTANT_CASE names */ public static String featureName(Features feature) { String[] words = feature.name().toLowerCase(Locale.ENGLISH).split("_"); if (words.length == 1) { return words[0]; } String ret = words[0]; for (int i = 1; i < words.length; i++) { ret += StringUtils.capitalize(words[i]); } return ret; }
Example #19
Source File: Lang_50_FastDateFormat_t.java From coming with MIT License | 5 votes |
/** * <p>Gets a date formatter instance using the specified style, time * zone and locale.</p> * * @param style date style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined */ public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) { Object key = new Integer(style); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale == null) { locale = Locale.getDefault(); } key = new Pair(key, locale); FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key); if (format == null) { try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cDateInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date pattern for locale: " + locale); } } return format; }
Example #20
Source File: HTMLdtd.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Returns true if the specified attribute is a boolean and should be * printed without the value. This applies to attributes that are true * if they exist, such as selected (OPTION/INPUT). * * @param tagName The element's tag name * @param attrName The attribute's name */ public static boolean isBoolean( String tagName, String attrName ) { String[] attrNames; attrNames = _boolAttrs.get( tagName.toUpperCase(Locale.ENGLISH) ); if ( attrNames == null ) return false; for ( int i = 0 ; i < attrNames.length ; ++i ) if ( attrNames[ i ].equalsIgnoreCase( attrName ) ) return true; return false; }
Example #21
Source File: HttpApiUtil.java From centraldogma with Apache License 2.0 | 5 votes |
/** * Returns a newly created {@link HttpResponse} with the specified {@link HttpStatus} and the formatted * message. */ public static HttpResponse newResponse(RequestContext ctx, HttpStatus status, String format, Object... args) { requireNonNull(ctx, "ctx"); requireNonNull(status, "status"); requireNonNull(format, "format"); requireNonNull(args, "args"); return newResponse(ctx, status, String.format(Locale.ENGLISH, format, args)); }
Example #22
Source File: SimpleFolder.java From rapidminer-studio with GNU Affero General Public License v3.0 | 5 votes |
@Override public Folder createFolder(String name) throws RepositoryException { if (RepositoryTools.isInSpecialConnectionsFolder(this)) { throw new RepositoryStoreOtherInConnectionsFolderException(MESSAGE_CONNECTION_FOLDER); } // check for possible invalid name if (!RepositoryLocation.isNameValid(name)) { throw new RepositoryException( I18N.getMessage(I18N.getErrorBundle(), "repository.illegal_entry_name", name, getLocation())); } SimpleFolder newFolder = new SimpleFolder(name, this, getRepository()); acquireWriteLock(); try { ensureLoaded(); for (Folder folder : folders) { // folder with the same name (no matter if they have different capitalization) // must // not // be // created if (folder.getName().toLowerCase(Locale.ENGLISH).equals(name.toLowerCase(Locale.ENGLISH))) { throw new RepositoryException( I18N.getMessage(I18N.getErrorBundle(), "repository.repository_folder_already_exists", name)); } } newFolder.mkdir(); folders.add(newFolder); } finally { releaseWriteLock(); } getRepository().fireEntryAdded(newFolder, this); return newFolder; }
Example #23
Source File: DrawerLayoutAdapter.java From TelePlus-Android with GNU General Public License v2.0 | 5 votes |
public void swapAccountPosition(int currentAdapterPosition, int targetAdapterPosition) { int currentIndex = currentAdapterPosition - 2; int targetIndex = targetAdapterPosition - 2; int currentElement = accountNumbers.get(currentIndex); int targetElement = accountNumbers.get(targetIndex); accountNumbers.set(targetIndex, currentElement); accountNumbers.set(currentIndex, targetElement); MessagesController.getGlobalMainSettings().edit(). putLong(String.format(Locale.US, "account_pos_%d", currentElement), targetIndex). putLong(String.format(Locale.US, "account_pos_%d", targetElement), currentIndex) .apply(); notifyItemMoved(currentAdapterPosition, targetAdapterPosition); }
Example #24
Source File: HostActivity.java From blog-nested-fragments-backstack with Apache License 2.0 | 5 votes |
@Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); case 1: return getString(R.string.title_section2).toUpperCase(l); case 2: return getString(R.string.title_section3).toUpperCase(l); } return null; }
Example #25
Source File: DateTimeFormatterBuilder.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * Gets the formatting pattern for date and time styles for a locale and chronology. * The locale and chronology are used to lookup the locale specific format * for the requested dateStyle and/or timeStyle. * * @param dateStyle the FormatStyle for the date * @param timeStyle the FormatStyle for the time * @param chrono the Chronology, non-null * @param locale the locale, non-null * @return the locale and Chronology specific formatting pattern * @throws IllegalArgumentException if both dateStyle and timeStyle are null */ public static String getLocalizedDateTimePattern(FormatStyle dateStyle, FormatStyle timeStyle, Chronology chrono, Locale locale) { Objects.requireNonNull(locale, "locale"); Objects.requireNonNull(chrono, "chrono"); if (dateStyle == null && timeStyle == null) { throw new IllegalArgumentException("Either dateStyle or timeStyle must be non-null"); } LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased().getLocaleResources(locale); String pattern = lr.getJavaTimeDateTimePattern( convertStyle(timeStyle), convertStyle(dateStyle), chrono.getCalendarType()); return pattern; }
Example #26
Source File: TestISOChronology.java From astor with GNU General Public License v2.0 | 5 votes |
protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; }
Example #27
Source File: RichDiagnosticFormatter.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
@Override public String visitCapturedType(CapturedType t, Locale locale) { if (getConfiguration().isEnabled(RichFormatterFeature.WHERE_CLAUSES)) { return localize(locale, "compiler.misc.captured.type", indexOf(t, WhereClauseKind.CAPTURED)); } else return super.visitCapturedType(t, locale); }
Example #28
Source File: Strings.java From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
static String millisToString(long millis, boolean text) { boolean negative = millis < 0; millis = java.lang.Math.abs(millis); millis /= 1000; int sec = (int) (millis % 60); millis /= 60; int min = (int) (millis % 60); millis /= 60; int hours = (int) millis; String time; DecimalFormat format = (DecimalFormat)NumberFormat.getInstance(Locale.US); format.applyPattern("00"); if (text) { if (millis > 0) time = (negative ? "-" : "") + hours + "h" + format.format(min) + "min"; else if (min > 0) time = (negative ? "-" : "") + min + "min"; else time = (negative ? "-" : "") + sec + "s"; } else { if (millis > 0) time = (negative ? "-" : "") + hours + ":" + format.format(min) + ":" + format.format(sec); else time = (negative ? "-" : "") + min + ":" + format.format(sec); } return time; }
Example #29
Source File: ResultHandler.java From analyzer-of-android-for-Apache-Weex with Apache License 2.0 | 5 votes |
private static int doToContractType(String typeString, String[] types, int[] values) { if (typeString == null) { return NO_TYPE; } for (int i = 0; i < types.length; i++) { String type = types[i]; if (typeString.startsWith(type) || typeString.startsWith(type.toUpperCase(Locale.ENGLISH))) { return values[i]; } } return NO_TYPE; }
Example #30
Source File: MainUI.java From Vaadin4Spring-MVP-Sample-SpringSecurity with Apache License 2.0 | 5 votes |
@Override protected void init(VaadinRequest request) { setLocale(new Locale.Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build()); SecuredNavigator securedNavigator = new SecuredNavigator(MainUI.this, mainLayout, springViewProvider, security, eventBus); securedNavigator.addViewChangeListener(mainLayout); setContent(mainLayout); setErrorHandler(new SpringSecurityErrorHandler()); /* * Handling redirections */ // RequestAttributes attrs = RequestContextHolder.getRequestAttributes(); // if (sessionStrategy.getAttribute(attrs, VaadinRedirectObject.REDIRECT_OBJECT_SESSION_ATTRIBUTE) != null) { // VaadinRedirectObject redirectObject = (VaadinRedirectObject) sessionStrategy.getAttribute(attrs, VaadinRedirectObject.REDIRECT_OBJECT_SESSION_ATTRIBUTE); // sessionStrategy.removeAttribute(attrs, VaadinRedirectObject.REDIRECT_OBJECT_SESSION_ATTRIBUTE); // // navigator.navigateTo(redirectObject.getRedirectViewToken()); // // if (redirectObject.getErrorMessage() != null) { // Notification.show("Error", redirectObject.getErrorMessage(), Type.ERROR_MESSAGE); // } // // } }