Java Code Examples for java.util.Locale

The following are top voted examples for showing how to use java.util.Locale. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: yadaframework   File: YadaSecurityEmailService.java   View source code 6 votes vote down vote up
/**
 * Invio la mail per il recupero password
 * @param logoImage e.g. "/res/img/logo-small.jpg"
 * @param yadaRegistrationRequest
 * @param request
 * @param response
 * @param locale
 * @return
 */
public boolean sendPasswordRecovery(YadaRegistrationRequest yadaRegistrationRequest, HttpServletRequest request, Locale locale) {
	final String emailName = "passwordRecovery";
	final String[] toEmail = new String[] {yadaRegistrationRequest.getEmail()};
	final String[] subjectParams = {yadaRegistrationRequest.getEmail()};

	String myServerAddress = yadaWebUtil.getWebappAddress(request);
	String fullLink = myServerAddress + "/passwordReset/" + yadaTokenHandler.makeLink(yadaRegistrationRequest, null);

	final Map<String, Object> templateParams = new HashMap<String, Object>();
	templateParams.put("fullLink", fullLink);
	
	Map<String, String> inlineResources = new HashMap<String, String>();
	inlineResources.put("logosmall", config.getEmailLogoImage());
	return yadaEmailService.sendHtmlEmail(toEmail, emailName, subjectParams, templateParams, inlineResources, locale, true);
}
 
Example 2
Project: GitHub   File: DateUtils.java   View source code 6 votes vote down vote up
private static long[] calculateDifference(long differentMilliSeconds) {
    long secondsInMilli = 1000;//1s==1000ms
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;
    long elapsedDays = differentMilliSeconds / daysInMilli;
    differentMilliSeconds = differentMilliSeconds % daysInMilli;
    long elapsedHours = differentMilliSeconds / hoursInMilli;
    differentMilliSeconds = differentMilliSeconds % hoursInMilli;
    long elapsedMinutes = differentMilliSeconds / minutesInMilli;
    differentMilliSeconds = differentMilliSeconds % minutesInMilli;
    long elapsedSeconds = differentMilliSeconds / secondsInMilli;
    LogUtils.verbose(String.format(Locale.CHINA, "different: %d ms, %d days, %d hours, %d minutes, %d seconds",
            differentMilliSeconds, elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds));
    return new long[]{elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds};
}
 
Example 3
Project: AOSP-Kayboard-7.1.2   File: LatinIME.java   View source code 6 votes vote down vote up
@UsedForTesting
void loadSettings() {
    final Locale locale = mRichImm.getCurrentSubtypeLocale();
    final EditorInfo editorInfo = getCurrentInputEditorInfo();
    final InputAttributes inputAttributes = new InputAttributes(
            editorInfo, isFullscreenMode(), getPackageName());
    mSettings.loadSettings(this, locale, inputAttributes);
    final SettingsValues currentSettingsValues = mSettings.getCurrent();
    AudioAndHapticFeedbackManager.getInstance().onSettingsChanged(currentSettingsValues);
    // This method is called on startup and language switch, before the new layout has
    // been displayed. Opening dictionaries never affects responsivity as dictionaries are
    // asynchronously loaded.
    if (!mHandler.hasPendingReopenDictionaries()) {
        resetDictionaryFacilitator(locale);
    }
    refreshPersonalizationDictionarySession(currentSettingsValues);
    resetDictionaryFacilitatorIfNecessary();
    mStatsUtilsManager.onLoadSettings(this /* context */, currentSettingsValues);
}
 
Example 4
Project: CXJPadProject   File: NormalUtil.java   View source code 6 votes vote down vote up
public static String date2flydate(String date) {
    SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
    Date d = null;
    long l = 0;
    try {
        d = dft.parse(date);
        l = d.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    Date new_date = new Date(l + 1000 * 60 * 15);
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
    String time = f.format(new_date);
    return time;
}
 
Example 5
Project: OpenJSharp   File: P11Cipher.java   View source code 6 votes vote down vote up
private int parseMode(String mode) throws NoSuchAlgorithmException {
    mode = mode.toUpperCase(Locale.ENGLISH);
    int result;
    if (mode.equals("ECB")) {
        result = MODE_ECB;
    } else if (mode.equals("CBC")) {
        if (blockSize == 0) {
            throw new NoSuchAlgorithmException
                    ("CBC mode not supported with stream ciphers");
        }
        result = MODE_CBC;
    } else if (mode.equals("CTR")) {
        result = MODE_CTR;
    } else {
        throw new NoSuchAlgorithmException("Unsupported mode " + mode);
    }
    return result;
}
 
Example 6
Project: openjdk-jdk10   File: CharacterName.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    for (int cp = 0; cp < Character.MAX_CODE_POINT; cp++) {
        if (!Character.isValidCodePoint(cp)) {
            try {
                Character.getName(cp);
            } catch (IllegalArgumentException x) {
                continue;
            }
            throw new RuntimeException("Invalid failed: " + cp);
        } else if (Character.getType(cp) == Character.UNASSIGNED) {
            if (Character.getName(cp) != null)
                throw new RuntimeException("Unsigned failed: " + cp);
        } else {
            String name = Character.getName(cp);
            if (cp != Character.codePointOf(name) ||
                cp != Character.codePointOf(name.toLowerCase(Locale.ENGLISH)))
            throw new RuntimeException("Roundtrip failed: " + cp);
        }
    }
}
 
Example 7
Project: tomcat7   File: Request.java   View source code 6 votes vote down vote up
/**
 * Return the set of preferred Locales that the client will accept
 * content in, based on the values for any <code>Accept-Language</code>
 * headers that were encountered.  If the request did not specify a
 * preferred language, the server's default Locale is returned.
 */
@Override
public Enumeration<Locale> getLocales() {

    if (!localesParsed) {
        parseLocales();
    }

    if (locales.size() > 0) {
        return Collections.enumeration(locales);
    }
    ArrayList<Locale> results = new ArrayList<Locale>();
    results.add(defaultLocale);
    return Collections.enumeration(results);

}
 
Example 8
Project: androidtools   File: CustomDatePicker.java   View source code 6 votes vote down vote up
public CustomDatePicker(Context context, ResultHandler resultHandler, String startDate, String endDate) {
    if (isValidDate(startDate, "yyyy-MM-dd HH:mm") && isValidDate(endDate, "yyyy-MM-dd HH:mm")) {
        canAccess = true;
        this.context = context;
        this.handler = resultHandler;
        selectedCalender = Calendar.getInstance();
        startCalendar = Calendar.getInstance();
        endCalendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        try {
            startCalendar.setTime(sdf.parse(startDate));
            endCalendar.setTime(sdf.parse(endDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        initDialog();
        initView();
    }
}
 
Example 9
Project: uia.syslog.we4j   File: WindowsEvent5156Test.java   View source code 6 votes vote down vote up
@Test
public void testTW() throws Exception {
    String content = "應用程式資訊: " +
            "處理程序識別碼: 1648 " +
            "應用程式名稱: \\device\\harddiskvolume1\\windows\\system32\\dns.exe " +
            "網路資訊: " +
            "方向: Inbound " +
            "來源位址: 10.42.42.223 " +
            "來源連接埠: 53 " +
            "目的地位址: 10.42.42.123 " +
            "目的地連接埠: 153 " +
            "通訊協定:  6 " +
            "篩選器資訊: " +
            "篩選器執行階段識別碼: 65884 " +
            "階層名稱:  Listen " +
            "階層執行階段識別碼: 40 ";

    Assert.assertNotNull(parse2Map("5156", content, Locale.TAIWAN));
}
 
Example 10
Project: mobile-store   File: Utils.java   View source code 6 votes vote down vote up
/**
 * There is a method {@link java.util.Locale#forLanguageTag(String)} which would be useful
 * for this, however it doesn't deal with android-specific language tags, which are a little
 * different. For example, android language tags may have an "r" before the country code,
 * such as "zh-rHK", however {@link java.util.Locale} expects them to be "zr-HK".
 */
public static Locale getLocaleFromAndroidLangTag(String languageTag) {
    if (TextUtils.isEmpty(languageTag)) {
        return null;
    }

    final String[] parts = languageTag.split("-");
    if (parts.length == 1) {
        return new Locale(parts[0]);
    }
    if (parts.length == 2) {
        String country = parts[1];
        // Some languages have an "r" before the country as per the values folders, such
        // as "zh-rCN". As far as the Locale class is concerned, the "r" is
        // not helpful, and this should be "zh-CN". Thus, we will
        // strip the "r" when found.
        if (country.charAt(0) == 'r' && country.length() == 3) {
            country = country.substring(1);
        }
        return new Locale(parts[0], country);
    }
    Log.e(TAG, "Locale could not be parsed from language tag: " + languageTag);
    return new Locale(languageTag);
}
 
Example 11
Project: Elasticsearch   File: SettingsAppliers.java   View source code 6 votes vote down vote up
@Override
public void apply(Settings.Builder settingsBuilder, Object[] parameters, Expression expression) {
    ByteSizeValue byteSizeValue;
    try {
        byteSizeValue = ExpressionToByteSizeValueVisitor.convert(expression, parameters);
    } catch (IllegalArgumentException e) {
        throw invalidException(e);
    }

    if (byteSizeValue == null) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                "'%s' does not support null values", name));
    }

    applyValue(settingsBuilder, byteSizeValue);
}
 
Example 12
Project: jdk8u-jdk   File: ZoneName.java   View source code 6 votes vote down vote up
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 13
Project: NotifyTools   File: BeanContextSupport.java   View source code 6 votes vote down vote up
/**
 * Sets the locale of this context. <code>VetoableChangeListener</code>s
 * and <code>PropertyChangeListener</code>s are notified.
 * 
 * @param newLocale     the new locale to set
 * @throws PropertyVetoException if any <code>VetoableChangeListener</code> vetos this change
 */
public void setLocale(Locale newLocale) throws PropertyVetoException {
    if (newLocale == null || newLocale == locale) {
        return; // ignore null locale
    }

    PropertyChangeEvent event = new PropertyChangeEvent(
            beanContextChildPeer, "locale", locale, newLocale);

    // apply change
    Locale oldLocale = locale;
    locale = newLocale;

    try {
        // notify vetoable listeners
        vcSupport.fireVetoableChange(event);
    } catch (PropertyVetoException e) {
        // rollback change
        locale = oldLocale;
        throw e;
    }
    // Notify BeanContext about this change
    this.pcSupport.firePropertyChange(event);
}
 
Example 14
Project: FreeCol   File: FreeColDirectories.java   View source code 6 votes vote down vote up
/**
 * Gets a list containing the names of all possible message files
 * for a locale.
 *
 * @param prefix The file name prefix.
 * @param suffix The file name suffix.
 * @param locale The {@code Locale} to generate file names for.
 * @return A list of candidate file names.
 */
public static List<String> getLocaleFileNames(String prefix,
                                              String suffix,
                                              Locale locale) {
    String language = locale.getLanguage();
    String country = locale.getCountry();
    String variant = locale.getVariant();

    List<String> result = new ArrayList<>(4);

    if (!language.isEmpty()) language = "_" + language;
    if (!country.isEmpty()) country = "_" + country;
    if (!variant.isEmpty()) variant = "_" + variant;

    result.add(prefix + suffix);
    String filename = prefix + language + suffix;
    if (!result.contains(filename)) result.add(filename);
    filename = prefix + language + country + suffix;
    if (!result.contains(filename)) result.add(filename);
    filename = prefix + language + country + variant + suffix;
    if (!result.contains(filename)) result.add(filename);
    return result;
}
 
Example 15
Project: Equella   File: UserSelectorControlEditor.java   View source code 6 votes vote down vote up
private JComponent createDetailsSection()
{
	final JLabel titleLabel = new JLabel(CurrentLocale.get("wizard.controls.title")); //$NON-NLS-1$
	final JLabel descriptionLabel = new JLabel(CurrentLocale.get("wizard.controls.description")); //$NON-NLS-1$

	final Set<Locale> langs = BundleCache.getLanguages();
	title = new I18nTextField(langs);
	description = new I18nTextField(langs);
	mandatory = new JCheckBox(CurrentLocale.get("wizard.controls.mandatory")); //$NON-NLS-1$
	selectMultiple = new JCheckBox(getString("usersel.selectmultiple")); //$NON-NLS-1$

	final JPanel all = new JPanel(new MigLayout("wrap", "[][grow, fill]"));

	all.add(titleLabel);
	all.add(title);
	all.add(descriptionLabel);
	all.add(description);
	all.add(mandatory, "span 2");
	all.add(selectMultiple, "span 2");

	return all;
}
 
Example 16
Project: coursera-sustainable-apps   File: LoginUtils.java   View source code 5 votes vote down vote up
/**
 * This method returns the postal code at a given latitude / longitude.
 *
 * If you test this method thoroughly, you will see that there are some
 * edge cases it doesn't handle well.
 *
 * @param ctx
 * @param lat
 * @param lng
 * @return
 */
public String getCurrentZipCode(Context ctx, double lat, double lng){
    try {
        Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
        // lat,lng, your current location

        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

        return addresses.get(0).getPostalCode();

    } catch(IOException ex){
        throw new RuntimeException(ex);
    }
}
 
Example 17
Project: letv   File: EnabledEventsStrategy.java   View source code 5 votes vote down vote up
void sendAndCleanUpIfSuccess() {
    FilesSender filesSender = getFilesSender();
    if (filesSender == null) {
        CommonUtils.logControlled(this.context, "skipping files send because we don't yet know the target endpoint");
        return;
    }
    CommonUtils.logControlled(this.context, "Sending all files");
    int filesSent = 0;
    List<File> batch = this.filesManager.getBatchOfFilesToSend();
    while (batch.size() > 0) {
        try {
            CommonUtils.logControlled(this.context, String.format(Locale.US, "attempt to send batch of %d files", new Object[]{Integer.valueOf(batch.size())}));
            boolean cleanup = filesSender.send(batch);
            if (cleanup) {
                filesSent += batch.size();
                this.filesManager.deleteSentFiles(batch);
            }
            if (!cleanup) {
                break;
            }
            batch = this.filesManager.getBatchOfFilesToSend();
        } catch (Exception e) {
            CommonUtils.logControlledError(this.context, "Failed to send batch of analytics files to server: " + e.getMessage(), e);
        }
    }
    if (filesSent == 0) {
        this.filesManager.deleteOldestInRollOverIfOverMax();
    }
}
 
Example 18
Project: boohee_v5.6   File: b.java   View source code 5 votes vote down vote up
public static String a(byte[] bArr) {
    if (bArr == null) {
        return null;
    }
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < bArr.length; i++) {
        stringBuffer.append(String.format("%02X", new Object[]{Byte.valueOf(bArr[i])}));
    }
    return stringBuffer.toString().toLowerCase(Locale.US);
}
 
Example 19
Project: COB   File: CordovaPreferences.java   View source code 5 votes vote down vote up
public String getString(String name, String defaultValue) {
    name = name.toLowerCase(Locale.ENGLISH);
    String value = prefs.get(name);
    if (value != null) {
        return value;
    }
    return defaultValue;
}
 
Example 20
Project: openjdk-jdk10   File: DecimalFormatSymbols.java   View source code 5 votes vote down vote up
/**
 * Initializes the symbols from the FormatData resource bundle.
 */
private void initialize( Locale locale ) {
    this.locale = locale;

    // get resource bundle data
    LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(DecimalFormatSymbolsProvider.class, locale);
    // Avoid potential recursions
    if (!(adapter instanceof ResourceBundleBasedAdapter)) {
        adapter = LocaleProviderAdapter.getResourceBundleBased();
    }
    Object[] data = adapter.getLocaleResources(locale).getDecimalFormatSymbolsData();
    String[] numberElements = (String[]) data[0];

    decimalSeparator = numberElements[0].charAt(0);
    groupingSeparator = numberElements[1].charAt(0);
    patternSeparator = numberElements[2].charAt(0);
    percent = numberElements[3].charAt(0);
    zeroDigit = numberElements[4].charAt(0); //different for Arabic,etc.
    digit = numberElements[5].charAt(0);
    minusSign = numberElements[6].charAt(0);
    exponential = numberElements[7].charAt(0);
    exponentialSeparator = numberElements[7]; //string representation new since 1.6
    perMill = numberElements[8].charAt(0);
    infinity  = numberElements[9];
    NaN = numberElements[10];

    // maybe filled with previously cached values, or null.
    intlCurrencySymbol = (String) data[1];
    currencySymbol = (String) data[2];

    // Currently the monetary decimal separator is the same as the
    // standard decimal separator for all locales that we support.
    // If that changes, add a new entry to NumberElements.
    monetarySeparator = decimalSeparator;
}
 
Example 21
Project: openjdk-jdk10   File: VerifyLintDescriptions.java   View source code 5 votes vote down vote up
public static void main(String... args) {
    ModuleLayer boot = ModuleLayer.boot();
    Module jdk_compiler = boot.findModule("jdk.compiler").get();
    ResourceBundle b = ResourceBundle.getBundle("com.sun.tools.javac.resources.javac",
                                                Locale.US,
                                                jdk_compiler);

    List<String> missing = new ArrayList<>();

    for (LintCategory lc : LintCategory.values()) {
        try {
            b.getString(PrefixKind.JAVAC.key("opt.Xlint.desc." + lc.option));
        } catch (MissingResourceException ex) {
            missing.add(lc.option);
        }
    }

    if (!missing.isEmpty()) {
        throw new UnsupportedOperationException("Lints that are missing description: " + missing);
    }
}
 
Example 22
Project: unitimes   File: ExamPeriod.java   View source code 5 votes vote down vote up
public static Date[] getBounds(Long sessionId, Date examBeginDate, Long examTypeId) {
    Object[] bounds = (Object[])new ExamPeriodDAO().getQuery("select min(ep.dateOffset), min(ep.startSlot - ep.eventStartOffset), max(ep.dateOffset), max(ep.startSlot+ep.length+ep.eventStopOffset) " +
    		"from ExamPeriod ep where ep.session.uniqueId = :sessionId and ep.examType.uniqueId = :examTypeId")
    		.setLong("sessionId", sessionId)
            .setLong("examTypeId", examTypeId)
            .setCacheable(true).uniqueResult();
    if (bounds == null || bounds[0] == null) return null;
    int minDateOffset = ((Number)bounds[0]).intValue();
    int minSlot = ((Number)bounds[1]).intValue();
    int minHour = (Constants.SLOT_LENGTH_MIN*minSlot+Constants.FIRST_SLOT_TIME_MIN) / 60;
    int minMin = (Constants.SLOT_LENGTH_MIN*minSlot+Constants.FIRST_SLOT_TIME_MIN) % 60;
    int maxDateOffset = ((Number)bounds[2]).intValue();
    int maxSlot = ((Number)bounds[3]).intValue();
    int maxHour = (Constants.SLOT_LENGTH_MIN*maxSlot+Constants.FIRST_SLOT_TIME_MIN) / 60;
    int maxMin = (Constants.SLOT_LENGTH_MIN*maxSlot+Constants.FIRST_SLOT_TIME_MIN) % 60;
    Calendar c = Calendar.getInstance(Locale.US);
    c.setTime(examBeginDate);
    c.add(Calendar.DAY_OF_YEAR, minDateOffset);
    c.set(Calendar.HOUR, minHour);
    c.set(Calendar.MINUTE, minMin);
    Date min = c.getTime();
    c.setTime(examBeginDate);
    c.add(Calendar.DAY_OF_YEAR, maxDateOffset);
    c.set(Calendar.HOUR, maxHour);
    c.set(Calendar.MINUTE, maxMin);
    Date max = c.getTime();
    return new Date[] {min, max};
}
 
Example 23
Project: rapidminer   File: XlsDataSourceDataTest.java   View source code 5 votes vote down vote up
@BeforeClass
public static void setup() throws URISyntaxException, IOException {
	testFile = new File(XlsDataSourceDataTest.class.getResource("test.xls").toURI());
	nominalDateTestFile = new File(XlsDataSourceDataTest.class.getResource("nominal_date_1.xls").toURI());
	dateDateTestFile = new File(XlsDataSourceDataTest.class.getResource("date_date_1.xls").toURI());

	// we need to set the local as otherwise test results might differ depending on the system
	// local running the test
	Locale.setDefault(Locale.ENGLISH);
}
 
Example 24
Project: lams   File: UnescapedCharSequence.java   View source code 5 votes vote down vote up
public static CharSequence toLowerCase(CharSequence text, Locale locale) {
  if (text instanceof UnescapedCharSequence) {
    char[] chars = text.toString().toLowerCase(locale).toCharArray();
    boolean[] wasEscaped = ((UnescapedCharSequence)text).wasEscaped;
    return new UnescapedCharSequence(chars, wasEscaped, 0, chars.length);
  } else 
    return new UnescapedCharSequence(text.toString().toLowerCase(locale));
}
 
Example 25
Project: apache-tomcat-7.0.73-with-comment   File: TestCorsFilter.java   View source code 5 votes vote down vote up
@Test
public void testDoFilterPreflightWithCredentials() throws IOException,
        ServletException {
    TesterHttpServletRequest request = new TesterHttpServletRequest();
    request.setHeader(CorsFilter.REQUEST_HEADER_ORIGIN,
            TesterFilterConfigs.HTTPS_WWW_APACHE_ORG);
    request.setHeader(
            CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD, "PUT");
    request.setHeader(
            CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS,
            "Content-Type");
    request.setMethod("OPTIONS");
    TesterHttpServletResponse response = new TesterHttpServletResponse();

    CorsFilter corsFilter = new CorsFilter();
    corsFilter.init(TesterFilterConfigs
            .getSecureFilterConfig());
    corsFilter.doFilter(request, response, filterChain);

    Assert.assertTrue(response.getHeader(
            CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN).equals(
            TesterFilterConfigs.HTTPS_WWW_APACHE_ORG));
    Assert.assertTrue(response.getHeader(
            CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS)
            .equals("true"));
    Assert.assertTrue(((Boolean) request.getAttribute(
            CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST)).booleanValue());
    Assert.assertTrue(request.getAttribute(
            CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN).equals(
            TesterFilterConfigs.HTTPS_WWW_APACHE_ORG));
    Assert.assertTrue(request.getAttribute(
            CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE).equals(
            CorsFilter.CORSRequestType.PRE_FLIGHT.name().toLowerCase(Locale.ENGLISH)));
    Assert.assertTrue(request.getAttribute(
            CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS).equals(
            "Content-Type"));
}
 
Example 26
Project: android-dev-challenge   File: MainActivity.java   View source code 5 votes vote down vote up
private void displayBoardingPassInfo(BoardingPassInfo info) {

        // COMPLETED (6) Use mBinding to set the Text in all the textViews using the data in info
        mBinding.textViewPassengerName.setText(info.passengerName);
        mBinding.textViewOriginAirport.setText(info.originCode);
        mBinding.textViewFlightCode.setText(info.flightCode);
        mBinding.textViewDestinationAirport.setText(info.destCode);

        // COMPLETED (7) Use a SimpleDateFormat formatter to set the formatted value in time text views
        SimpleDateFormat formatter = new SimpleDateFormat(getString(R.string.timeFormat), Locale.getDefault());
        String boardingTime = formatter.format(info.boardingTime);
        String departureTime = formatter.format(info.departureTime);
        String arrivalTime = formatter.format(info.arrivalTime);

        mBinding.textViewBoardingTime.setText(boardingTime);
        mBinding.textViewDepartureTime.setText(departureTime);
        mBinding.textViewArrivalTime.setText(arrivalTime);

        // COMPLETED (8) Use TimeUnit methods to format the total minutes until boarding
        long totalMinutesUntilBoarding = info.getMinutesUntilBoarding();
        long hoursUntilBoarding = TimeUnit.MINUTES.toHours(totalMinutesUntilBoarding);
        long minutesLessHoursUntilBoarding =
                totalMinutesUntilBoarding - TimeUnit.HOURS.toMinutes(hoursUntilBoarding);

        String hoursAndMinutesUntilBoarding = getString(R.string.countDownFormat,
                hoursUntilBoarding,
                minutesLessHoursUntilBoarding);

        mBinding.textViewBoardingInCountdown.setText(hoursAndMinutesUntilBoarding);
        mBinding.textViewTerminal.setText(info.departureTerminal);
        mBinding.textViewGate.setText(info.departureGate);
        mBinding.textViewSeat.setText(info.seatNumber);
    }
 
Example 27
Project: mapbox-assistant-example   File: IntentManager.java   View source code 5 votes vote down vote up
public SpeechletResponse getOfficeAddressResponse(Slot postalAddress, Slot city) {
    String speechText;
    String cardText;
    Image image = null;

    String address = AddressUtils.getAddressFromSlot(postalAddress, city, null);

    try {
        Position proximity = storageManager.getHomeAddress();
        Position position = AddressUtils.getCoordinatesFromAddress(address, proximity);
        storageManager.setOfficeAddress(position);
        cardText = String.format(Locale.US, "Thank you, office address set: %s", address);
        speechText = "Thank you, office address set.";
        image = new Image();
        image.setSmallImageUrl(ImageComponent.getLocationMap(position, true));
        image.setLargeImageUrl(ImageComponent.getLocationMap(position, false));
    } catch (Exception e) {
        cardText = String.format(Locale.US, "Sorry, I couldn't find that address: %s", address);
        speechText = "Sorry, I couldn't find that address.";
    }

    // Create a standard card content
    StandardCard card = new StandardCard();
    card.setTitle(CARD_TITLE);
    card.setText(cardText);

    // Card image
    if (image != null) {
        card.setImage(image);
    }

    // Create the plain text output
    PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
    speech.setText(speechText);

    return SpeechletResponse.newTellResponse(speech, card);
}
 
Example 28
Project: elasticsearch_my   File: QueryRescorerBuilder.java   View source code 5 votes vote down vote up
@Override
public void doXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(NAME);
    builder.field(RESCORE_QUERY_FIELD.getPreferredName(), queryBuilder);
    builder.field(QUERY_WEIGHT_FIELD.getPreferredName(), queryWeight);
    builder.field(RESCORE_QUERY_WEIGHT_FIELD.getPreferredName(), rescoreQueryWeight);
    builder.field(SCORE_MODE_FIELD.getPreferredName(), scoreMode.name().toLowerCase(Locale.ROOT));
    builder.endObject();
}
 
Example 29
Project: flume-release-1.7.0   File: TestDatabaseTypeEnum.java   View source code 5 votes vote down vote up
@Test
public void testDatabaseTypeLookup() {
  for (String key : enumMap.keySet()) {
    DatabaseType type = enumMap.get(key);
    DatabaseType lookupType = DatabaseType.valueOf(key);
    String lookupTypeName = lookupType.getName();

    Assert.assertEquals(lookupTypeName, lookupType.toString());
    Assert.assertSame(type, lookupType);
    Assert.assertEquals(key, lookupTypeName);

    DatabaseType lookupType2 = DatabaseType.getByName(key.toLowerCase(Locale.ENGLISH));
    Assert.assertSame(type, lookupType2);
  }
}
 
Example 30
Project: boohee_v5.6   File: e.java   View source code 5 votes vote down vote up
private e(Context context) {
    this.b = "2.0.3";
    this.L = VERSION.SDK_INT;
    this.M = Build.MODEL;
    this.ab = Build.MANUFACTURER;
    this.bq = Locale.getDefault().getLanguage();
    this.aQ = 0;
    this.aR = null;
    this.aS = null;
    this.cB = null;
    this.cC = null;
    this.cD = null;
    this.cE = null;
    this.cF = null;
    this.cB = context.getApplicationContext();
    this.cA = l.x(this.cB);
    this.a = l.D(this.cB);
    this.br = c.e(this.cB);
    this.bs = l.C(this.cB);
    this.bt = TimeZone.getDefault().getID();
    Context context2 = this.cB;
    this.aQ = l.au();
    this.al = l.H(this.cB);
    this.aR = this.cB.getPackageName();
    if (this.L >= 14) {
        this.cC = l.M(this.cB);
    }
    context2 = this.cB;
    this.cD = l.az().toString();
    this.cE = l.L(this.cB);
    this.cF = l.ax();
    this.aS = l.R(this.cB);
}
 
Example 31
Project: boohee_v5.6   File: c.java   View source code 5 votes vote down vote up
private c(Context context) {
    this.b = StatConstants.VERSION;
    this.d = VERSION.SDK_INT;
    this.e = Build.MODEL;
    this.f = Build.MANUFACTURER;
    this.g = Locale.getDefault().getLanguage();
    this.l = 0;
    this.m = null;
    this.n = null;
    this.o = null;
    this.p = null;
    this.q = null;
    this.r = null;
    this.n = context;
    this.c = k.d(context);
    this.a = k.n(context);
    this.h = StatConfig.getInstallChannel(context);
    this.i = k.m(context);
    this.j = TimeZone.getDefault().getID();
    this.l = k.s(context);
    this.k = k.t(context);
    this.m = context.getPackageName();
    if (this.d >= 14) {
        this.o = k.A(context);
    }
    this.p = k.z(context).toString();
    this.q = k.x(context);
    this.r = k.e();
}
 
Example 32
Project: FCM-for-Mojo   File: GroupWhitelistItemViewHolder.java   View source code 5 votes vote down vote up
@Override
public void onBind() {
    title.setText(getData().first.getName());
    summary.setText(getData().first.getUid() == 0 ? itemView.getContext().getString(R.string.whitelist_group_no_uid) :
            String.format(Locale.ENGLISH, "%d", getData().first.getUid()));
    toggle.setChecked(getData().second);

    mDisposable = Single.just(getData().first.loadIcon(itemView.getContext()))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Drawable>() {
                @Override
                public void accept(Drawable drawable) throws Exception {
                    icon.setImageDrawable(drawable);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    throwable.printStackTrace();

                    Crashlytics.log("load icon");
                    Crashlytics.logException(throwable);
                }
            });

    super.onBind();
}
 
Example 33
Project: simple-keyboard   File: KeyboardTextsSet.java   View source code 5 votes vote down vote up
@UsedForTesting
public void setLocale(final Locale locale, final Resources res,
        final String resourcePackageName) {
    mResources = res;
    // Null means the current system locale.
    mResourceLocale = SubtypeLocaleUtils.NO_LANGUAGE.equals(locale.toString()) ? null : locale;
    mResourcePackageName = resourcePackageName;
    mTextsTable = KeyboardTextsTable.getTextsTable(locale);
}
 
Example 34
Project: SmartMath   File: MFPAdapter.java   View source code 5 votes vote down vote up
public static boolean copyAssetCharts2SD(AssetManager am, String strSrcPath, String strDestPath) {
    String strAssetFiles[] = null;
    boolean bReturnValue = true;
    try {
    	String strScriptExt = MFPFileManagerActivity.STRING_CHART_EXTENSION;
        if (strSrcPath.substring(strSrcPath.length() - strScriptExt.length())
        		.toLowerCase(Locale.US).equals(strScriptExt)
        	&& (strSrcPath.equals(STRING_ASSET_CHARTS_FOLDER
        						+ MFPFileManagerActivity.STRING_PATH_DIV
        						+ STRING_ASSET_CHART_EXAMPLE1_FILE)
        		|| strSrcPath.equals(STRING_ASSET_CHARTS_FOLDER
   						+ MFPFileManagerActivity.STRING_PATH_DIV
   						+ STRING_ASSET_CHART_EXAMPLE2_FILE))) {
        	// this is a chart.
            if (copyAssetFile2SD(am, strSrcPath, strDestPath) == false)	{
				return false;
			}
        } else if (strSrcPath.substring(strSrcPath.length() - STRING_ASSET_CHARTS_FOLDER_EXTENSION.length())
				.toLowerCase(Locale.US).equals(STRING_ASSET_CHARTS_FOLDER_EXTENSION))	{
            File dir = new File(strDestPath);
            if (!dir.exists())	{
                if (!dir.mkdirs())	{
                    return false;	// cannot create destination folder
				}
			}
	        strAssetFiles = am.list(strSrcPath);
            for (int i = 0; i < strAssetFiles.length; ++i) {
            	boolean bThisCpyReturn = copyAssetCharts2SD(am, strSrcPath + MFPFileManagerActivity.STRING_PATH_DIV + strAssetFiles[i],
							strDestPath + MFPFileManagerActivity.STRING_PATH_DIV + strAssetFiles[i]);
            	if (!bThisCpyReturn) {
            		bReturnValue = false;
            	}
            }
        }
    } catch (IOException ex) {
        return false;
    }
	return bReturnValue;
}
 
Example 35
Project: xdman   File: FTPClientConfig.java   View source code 5 votes vote down vote up
/**
 * Looks up the supplied language code in the internally maintained table of
 * language codes.  Returns a DateFormatSymbols object configured with
 * short month names corresponding to the code.  If there is no corresponding
 * entry in the table, the object returned will be that for
 * <code>Locale.US</code>
 * @param languageCode See {@link  #setServerLanguageCode(String)  serverLanguageCode}
 * @return a DateFormatSymbols object configured with short month names
 * corresponding to the supplied code, or with month names for
 * <code>Locale.US</code> if there is no corresponding entry in the internal
 * table.
 */
public static DateFormatSymbols lookupDateFormatSymbols(String languageCode)
{
    Object lang = LANGUAGE_CODE_MAP.get(languageCode);
    if (lang != null) {
        if (lang instanceof Locale) {
            return new DateFormatSymbols((Locale) lang);
        } else if (lang instanceof String){
            return getDateFormatSymbols((String) lang);
        }
    }
    return new DateFormatSymbols(Locale.US);
}
 
Example 36
Project: GameResourceBot   File: OcrTestEnglishIphone.java   View source code 5 votes vote down vote up
@Test
public void en_iphone7_750px_1334px_1710102230a() throws Exception {
	InputStream stream = OcrTestEnglishIphone.class.getClassLoader().getResourceAsStream("en_iphone7_750px_1334px_1710102230a.png");
	Map<String, Long> stocks = OCR.getInstance().convertToStocks(stream, Locale.ENGLISH, Device.IPHONE);
	Assert.assertEquals(9,stocks.keySet().size());
	Assert.assertEquals(Long.valueOf(430), stocks.get(REFINED_OIL));
	Assert.assertEquals(Long.valueOf(2881), stocks.get(MOTHERBOARD));
	Assert.assertEquals(Long.valueOf(14), stocks.get(URANIUM_ROD));
	Assert.assertEquals(Long.valueOf(403), stocks.get(PLASTIC));
	Assert.assertEquals(Long.valueOf(686158), stocks.get(COPPER_NAIL));
	Assert.assertEquals(Long.valueOf(110), stocks.get(OPTIC_FIBER));
	Assert.assertEquals(Long.valueOf(75), stocks.get(SOLAR_PANEL));
	Assert.assertEquals(Long.valueOf(75247), stocks.get(GRAPHITE));
	Assert.assertEquals(Long.valueOf(27493), stocks.get(GREEN_LASER));
}
 
Example 37
Project: civify-app   File: AchievementAdapterImplTest.java   View source code 5 votes vote down vote up
private void setUpAchievement() throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat(ServiceGenerator.RAILS_DATE_FORMAT,
            Locale.getDefault());
    mBadge = new Picture();
    mBadge.setContentType("testContent");
    mAchievement = new Achievement(TITLE, DESCRIPTION, NUMBER, KIND, COINS, XP,
            dateFormat.parse(DATE), TOKEN, true, PROGRESS, false, false, mBadge);
}
 
Example 38
Project: opencps-v2   File: OfficeSiteManagement.java   View source code 5 votes vote down vote up
@PUT
@Path("/{id}/preferences")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response updateOfficeSitePreferences(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") long id, @BeanParam OfficeSiteInputModel input);
 
Example 39
Project: lams   File: NumberUtil.java   View source code 5 votes vote down vote up
/**
    * Format a given float or double to the I18N format specified by the locale, with a fixed number of decimal places. 
    * If numFractionDigits is 2: 4.051 -> 4.05, 4 -> 4.00
    *
    * @param mark
    * @param locale
    * @param numFractionDigits
    * @return
    */
   public static String formatLocalisedNumberForceDecimalPlaces(Number number, Locale locale, int numFractionDigits) {
NumberFormat format = null;
if (locale == null) {
    format = NumberFormat.getInstance(NumberUtil.getServerLocale());
} else {
    format = NumberFormat.getInstance(locale);
}
format.setMinimumFractionDigits(numFractionDigits);
return format.format(number);
   }
 
Example 40
Project: GitHub   File: Utils.java   View source code 5 votes vote down vote up
/**
 * convert long to GMT string
 *
 * @param lastModify long
 * @return String
 */
public static String longToGMT(long lastModify) {
    Date d = new Date(lastModify);
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    sdf.setTimeZone(getTimeZone("GMT"));
    return sdf.format(d);
}