Java 类org.apache.commons.lang3.LocaleUtils 实例源码

项目:InComb    文件:LocaleUtil.java   
/**
 * Converts the given locale {@link String} to a {@link Locale}.
 * The case of the {@link String} is irrelevant unlike {@link LocaleUtils#toLocale(String)}.
 *
 * @param locale the {@link String} to convert.
 * @return the converted {@link Locale}.
 */
public static Locale toLocale(String locale) {
    final String[] parts = locale.split("_");
    for(int i = 0; i < parts.length; i++) {
        switch (i) {
            case 0:
                locale = parts[0].toLowerCase();
                break;
            case 1:
                locale += "_" + parts[1].toUpperCase();
                break;
            case 2:
                locale += "_" + parts[2];
        }
    }

    return LocaleUtils.toLocale(locale);
}
项目:yadaframework    文件:YadaConfiguration.java   
/**
 * Returns the default locale when getting a string that doesn't have a value for the requested locale.
 * If the default locale is not set, the string will have an empty value and no attempt on another locale will be made.
 * @return the default locale, or null if no default is set
 */
public Locale getDefaultLocale() {
    if (!defaultLocaleChecked) {
        defaultLocaleChecked = true;
        String localeString = configuration.getString("config/i18n/locale[@default='true']", null);
        if (localeString!=null) {
            try {
                defaultLocale = LocaleUtils.toLocale(localeString);
            } catch (IllegalArgumentException e) {
                throw new YadaConfigurationException("Locale {} is invalid", localeString);
            }
        } else {
            log.warn("No default locale has been set with <locale default=\"true\">: set a default locale if you don't want empty strings returned for missing localized values in the database");
        }
    }
    return defaultLocale;
}
项目:imf-conversion    文件:LocaleValidator.java   
public static void validateLocale(String str) throws LocaleValidationException {
    if (StringUtils.isBlank(str)) {
        throw new LocaleValidationException("Locale must be set.");
    }

    try {
        Locale locale = LocaleHelper.fromITunesLocale(str);

        if (!LocaleUtils.availableLocaleList().contains(locale)) {
            throw new LocaleValidationException(String.format(
                    "Locale %s is unavailable.", str));
        }
    } catch (IllegalArgumentException e) {
        throw new LocaleValidationException("Locale validation failed.", e);
    }
}
项目:opencucina    文件:MessageConverter.java   
/**
 * JAVADOC Method Level Comments
 *
 * @param message JAVADOC.
 *
 * @return JAVADOC.
 */
@Override
public Collection<MessageDto> convert(Message message) {
    Collection<MessageDto> result = new LinkedList<MessageDto>();
    Collection<MutableI18nMessage> i18nMessages = message.getInternationalisedMessages();

    for (MutableI18nMessage mutableI18nMessage : i18nMessages) {
        MessageDto mdto = new MessageDto();

        mdto.setId(message.getId());
        mdto.setApplication(message.getBaseName());
        mdto.setCode(message.getMessageCd());
        mdto.setLocale(LocaleUtils.toLocale(mutableI18nMessage.getLocaleCd()));
        mdto.setText(mutableI18nMessage.getMessageTx());
        result.add(mdto);
    }

    return result;
}
项目:template-compiler    文件:LegacyMoneyFormatter.java   
@Override
public void validateArgs(Arguments args) throws ArgumentsException {
  args.atMost(1);

  String localeStr = getLocaleArg(args);
  if (localeStr != null) {
    Locale locale;
    try {
      // LocaleUtils uses an underscore format (e.g. en_US), but the new Java standard
      // is a hyphenated format (e.g. en-US). This allows us to use LocaleUtils' validation.
      locale = LocaleUtils.toLocale(localeStr.replace('-', '_'));
    } catch (IllegalArgumentException e) {
      throw new ArgumentsException("Invalid locale: " + localeStr);
    }

    args.setOpaque(locale);
  } else {
    args.setOpaque(DEFAULT_LOCALE);
  }
}
项目:github-job-keywords    文件:SearchUtils.java   
public static Locale lookupLocaleByCountry(String country) {
    List<Locale> localeList = LocaleUtils.languagesByCountry(country);
    if (localeList == null || localeList.size() == 0) {
        throw new IllegalArgumentException("Invalid country code: " + country);
    }
    Locale locale = localeList.get(0);

    // if English isn't the language of the first Locale, then try to find English.
    if (!locale.getLanguage().equals("en")) {
        for (Locale option : localeList) {
            if (option.getLanguage().equals("en")) {
                return option;
            }
        }
    }
    return locale;
}
项目:SPFBL    文件:ServerHTTP.java   
private Language(String language) {
    language = language.replace('-', '_');
    int index = language.indexOf(';');
    if (index == -1) {
        locale = LocaleUtils.toLocale(language);
        q = 1.0f;
    } else {
        String value = language.substring(0,index).trim();
        locale = LocaleUtils.toLocale(value);
        float qFloat;
        try {
            index = language.lastIndexOf('=') + 1;
            value = language.substring(index).trim();
            qFloat = Float.parseFloat(value);
        } catch (NumberFormatException ex) {
            qFloat = 0.0f;
        }
        q = qFloat;
    }
}
项目:SPFBL    文件:User.java   
/**
 * Change locale of user.
 * @param token locale pattern.
 * @return true if value was changed.LocaleUtils.toLocale(language);
 */
public boolean setLocale(String token) {
    if (token == null) {
        return false;
    } else {
        Locale newLocale = LocaleUtils.toLocale(token);
        if (newLocale == null) {
            return false;
        } else if (newLocale.equals(this.locale)) {
            return false;
        } else {
            this.locale = newLocale;
            return CHANGED = true;
        }
    }
}
项目:i18n-editor    文件:Editor.java   
public void showAddLocaleDialog() {
    String localeString = "";
    Path path = project.getPath();
    ResourceType type = project.getResourceType();
    while (localeString != null && localeString.isEmpty()) {
        localeString = Dialogs.showInputDialog(this,
                MessageBundle.get("dialogs.locale.add.title", type),
                MessageBundle.get("dialogs.locale.add.text"),
                JOptionPane.QUESTION_MESSAGE);
        if (localeString != null) {
            localeString = localeString.trim();
            if (localeString.isEmpty()) {
                showError(MessageBundle.get("dialogs.locale.add.error.invalid"));
            } else {
                try {
                    Locale locale = LocaleUtils.toLocale(localeString);
                    Resource resource = Resources.create(path, type, Optional.of(locale), project.getResourceName());
                    addResource(resource);
                } catch (IOException e) {
                    log.error("Error creating new locale", e);
                    showError(MessageBundle.get("dialogs.locale.add.error.create"));
                }
            }
        }
    }
}
项目:url-lang-id    文件:LanguageTagsMapping.java   
/**
 * Instantiates a new Language tags mapping.
 */
public LanguageTagsMapping() {
    super(NAME);
    this.withCaseSensitive(false);

    // Build reverse map.  Use a tree map to offer case insensitiveness while preserving keys case (useful for extending)
    TreeMap<String, Locale> map = new TreeMap<String, Locale>(this.getCaseSensitive() ? null : String.CASE_INSENSITIVE_ORDER);
    for (Locale loc : LocaleUtils.availableLocaleList()) {
        String isoCode = loc.getLanguage();
        if (isoCode.length() > 0) {
            String displayValue = loc.toLanguageTag();
            if (!map.containsKey(displayValue)) {
                // Also add variant with underscores
                map.put(displayValue, loc);
                map.put(displayValue.replace('-', '_'), loc);
            }
        }
    }
    this.withMapping(map);
}
项目:url-lang-id    文件:DisplayNamesMapping.java   
/**
 * Instantiates a new Display names mapping.
 *
 * @param name the name
 * @param displayLocale the display locale
 */
public DisplayNamesMapping(String name, Locale displayLocale) {
    super(name);
    this.displayLocale = displayLocale;

    // Build reverse map
    HashMap<String, Locale> map = new HashMap<String, Locale>();
    for (String isoCode : Locale.getISOLanguages()) {
        Locale loc = LocaleUtils.toLocale(isoCode);
        String displayName = loc.getDisplayName(displayLocale).toLowerCase();
        if (isoCode.length() > 0 && !map.containsKey(displayName)) {
            map.put(displayName, loc);
        }
    }

    this.withMapping(map).withCaseSensitive(false);
}
项目:url-lang-id    文件:ISO639Alpha3Mapping.java   
/**
 * Instantiates a new ISO 639 alpha 3 mapping.
 */
public ISO639Alpha3Mapping() {
    super(NAME);

    // Build reverse map
    HashMap<String, Locale> map = new HashMap<String, Locale>();
    for (Locale loc : LocaleUtils.availableLocaleList()) {
        String isoCode = loc.getLanguage();
        if (isoCode.length() > 0) {
            String displayValue = loc.getISO3Language().toLowerCase();
            if (!map.containsKey(displayValue)) {
                map.put(displayValue, LocaleUtils.toLocale(isoCode));
            }
        }
    }
    this.withMapping(map).withCaseSensitive(false);
}
项目:url-lang-id    文件:ISO639Alpha2Mapping.java   
/**
 * Instantiates a new ISO 639 alpha 2 mapping.
 */
public ISO639Alpha2Mapping() {
    super(NAME);

    // Build reverse map
    HashMap<String, Locale> map = new HashMap<String, Locale>();
    for (String isoCode : Locale.getISOLanguages()) {
        if (isoCode.length() > 0) {
            String displayValue = isoCode.toLowerCase();
            if (!map.containsKey(displayValue)) {
                map.put(displayValue, LocaleUtils.toLocale(isoCode));
            }
        }
    }
    this.withMapping(map).withCaseSensitive(false);
}
项目:url-lang-id    文件:MappingsFactoryTest.java   
@Test
public void testDefaultMappings() throws Exception {
    MappingsFactory f = new MappingsFactory(Collections.emptyList());

    assertEquals(f.getMappings().size(), 4);

    assertTrue(f.getMappings().containsKey("ISO-639-ALPHA-2"));
    assertEquals(f.getMappings().get("ISO-639-ALPHA-2").getMapping().get("en"), LocaleUtils.toLocale("en"));

    assertTrue(f.getMappings().containsKey("ISO-639-ALPHA-3"));
    assertEquals(f.getMappings().get("ISO-639-ALPHA-3").getMapping().get("eng"), LocaleUtils.toLocale("en"));

    assertTrue(f.getMappings().containsKey("LANGUAGE_TAGS"));
    assertEquals(f.getMappings().get("LANGUAGE_TAGS").getMapping().get("en-US"), LocaleUtils.toLocale("en_US"));

    assertTrue(f.getMappings().containsKey("ENGLISH_NAMES"));
    assertEquals(f.getMappings().get("ENGLISH_NAMES").getMapping().get("french"), LocaleUtils.toLocale("fr"));
}
项目:url-lang-id    文件:MappingsFactoryTest.java   
@Test
public void testCreateMappingFilterAndOverride() throws Exception {
    MappingConfig config = new MappingConfig();
    config.name = "test";
    config.extend = ImmutableList.of("ISO-639-ALPHA-3");
    config.filter = "en,fr";
    config.override = ImmutableMap.of("fr", "french,francais");
    MappingsFactory f = new MappingsFactory(Collections.singletonList(config));
    assertTrue(f.getMappings().containsKey("test"));

    Mapping mapping = f.getMappings().get("test");
    assertEquals(mapping.getMapping().size(), 3);
    assertEquals(mapping.getMapping().get("eng"), LocaleUtils.toLocale("en")); // Kept by filter
    assertFalse(mapping.getMapping().containsKey("fra")); // Kept by filter but overriden
    assertFalse(mapping.getMapping().containsKey("ita")); // Removed by filter
    assertEquals(mapping.getMapping().get("french"), LocaleUtils.toLocale("fr"));
    assertEquals(mapping.getMapping().get("francais"), LocaleUtils.toLocale("fr"));
}
项目:tinyMediaManager    文件:MovieSubtitleChooserDialog.java   
@Override
public Void doInBackground() {
  startProgressBar(BUNDLE.getString("chooser.searchingfor") + " " + searchTerm); //$NON-NLS-1$
  for (MediaScraper scraper : scrapers) {
    try {
      IMediaSubtitleProvider subtitleProvider = (IMediaSubtitleProvider) scraper.getMediaProvider();
      SubtitleSearchOptions options = new SubtitleSearchOptions(file, searchTerm);
      options.setImdbId(imdbId);
      options.setLanguage(LocaleUtils.toLocale(language.name()));
      searchResults.addAll(subtitleProvider.search(options));
    }
    catch (Exception e) {
    }
  }

  Collections.sort(searchResults);
  Collections.reverse(searchResults);

  return null;
}
项目:tinyMediaManager    文件:TvShowSubtitleChooserDialog.java   
@Override
public Void doInBackground() {
  startProgressBar(BUNDLE.getString("chooser.searchingfor") + " " + episodeToScrape.getTitle()); //$NON-NLS-1$
  for (MediaScraper scraper : scrapers) {
    try {
      IMediaSubtitleProvider subtitleProvider = (IMediaSubtitleProvider) scraper.getMediaProvider();
      SubtitleSearchOptions options = new SubtitleSearchOptions(file);
      options.setImdbId(imdbId);
      options.setLanguage(LocaleUtils.toLocale(language.name()));
      options.setSeason(season);
      options.setEpisode(episode);
      searchResults.addAll(subtitleProvider.search(options));
    }
    catch (Exception ignored) {
    }
  }

  Collections.sort(searchResults);
  Collections.reverse(searchResults);

  return null;
}
项目:tinyMediaManager    文件:TvShowScrapeTask.java   
/**
 * Gets the artwork.
 * 
 * @param metadata
 *          the metadata
 * @return the artwork
 */
public List<MediaArtwork> getArtwork(TvShow tvShow, MediaMetadata metadata, List<MediaScraper> artworkScrapers) {
  List<MediaArtwork> artwork = new ArrayList<>();

  MediaScrapeOptions options = new MediaScrapeOptions(MediaType.TV_SHOW);
  options.setArtworkType(MediaArtworkType.ALL);
  options.setMetadata(metadata);
  options.setLanguage(LocaleUtils.toLocale(TvShowModuleManager.SETTINGS.getScraperLanguage().name()));
  options.setCountry(TvShowModuleManager.SETTINGS.getCertificationCountry());
  for (Entry<String, Object> entry : tvShow.getIds().entrySet()) {
    options.setId(entry.getKey(), entry.getValue().toString());
  }

  // scrape providers till one artwork has been found
  for (MediaScraper artworkScraper : artworkScrapers) {
    ITvShowArtworkProvider artworkProvider = (ITvShowArtworkProvider) artworkScraper.getMediaProvider();
    try {
      artwork.addAll(artworkProvider.getArtwork(options));
    }
    catch (Exception e) {
      LOGGER.error("getArtwork", e);
      MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, tvShow, "message.scrape.tvshowartworkfailed"));
    }
  }
  return artwork;
}
项目:data-prep    文件:Localization.java   
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                    BeanDefinitionRegistry registry) {
    if (registry instanceof BeanFactory) {
        final Environment environment = ((BeanFactory) registry).getBean(Environment.class);

        final String defaultLocale = environment.getProperty("dataprep.locale", "en-US");
        Locale locale = new Locale.Builder().setLanguageTag(defaultLocale).build();
        if (LocaleUtils.isAvailableLocale(locale)) {
            LOGGER.debug("Setting default JVM locale to configured {}", locale);
        } else {
            LOGGER.debug("Configured JVM Locale {} is not available. Defaulting to {}", locale, Locale.US);
            locale = Locale.US;
        }
        Locale.setDefault(locale);
        LOGGER.info("JVM Default locale set to: '{}'", locale);
    } else {
        LOGGER.warn("Unable to set default locale (unexpected bean registry of type '{}')",
                registry.getClass().getName());
    }
}
项目:data-prep    文件:DataprepLocaleContextResolver.java   
private Locale resolveApplicationLocale(String configuredLocale) {
    Locale locale;
    if (StringUtils.isNotBlank(configuredLocale)) {
        try {
            locale = new Locale.Builder().setLanguageTag(configuredLocale).build();
            if (LocaleUtils.isAvailableLocale(locale)) {
                LOGGER.debug("Setting application locale to configured {}", locale);
            } else {
                locale = getDefaultLocale();
                LOGGER.debug("Locale {} is not available. Defaulting to {}", configuredLocale, getDefaultLocale());
            }
        } catch (IllformedLocaleException e) {
            locale = getDefaultLocale();
            LOGGER.warn(
                    "Error parsing configured application locale: {}. Defaulting to {}. Locale must be in the form \"en-US\" or \"fr-FR\"",
                    configuredLocale, getDefaultLocale());
        }
    } else {
        locale = getDefaultLocale();
        LOGGER.debug("Setting application locale to default value {}", getDefaultLocale());
    }
    LOGGER.info("Application locale set to: '{}'", locale);
    return locale;
}
项目:gwt-commons-lang3    文件:FastDateParserTest.java   
@Test
public void testJpLocales() {

    final Calendar cal= Calendar.getInstance(GMT);
    cal.clear();
    cal.set(2003, Calendar.FEBRUARY, 10);
    cal.set(Calendar.ERA, GregorianCalendar.BC);

    final Locale locale = LocaleUtils.toLocale("zh"); {
        // ja_JP_JP cannot handle dates before 1868 properly

        final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale);
        final DateParser fdf = getInstance(LONG_FORMAT, locale);

        try {
            checkParse(locale, cal, sdf, fdf);
        } catch(final ParseException ex) {
            fail("Locale "+locale+ " failed with "+LONG_FORMAT+"\n" + trimMessage(ex.toString()));
        }
    }
}
项目:gwt-commons-lang3    文件:SystemDefaultsSwitch.java   
private Statement applyLocale(final SystemDefaults defaults, final Statement stmt) {
    if (defaults.locale().isEmpty()) {
        return stmt;
    }

    final Locale newLocale = LocaleUtils.toLocale(defaults.locale());

    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            final Locale save = Locale.getDefault();
            try {
                Locale.setDefault(newLocale);
                stmt.evaluate();
            } finally {
                Locale.setDefault(save);
            }
        }
    };
}
项目:logging-log4j2    文件:FastDateParserTest.java   
@Test
public void testJpLocales() {

    final Calendar cal= Calendar.getInstance(GMT);
    cal.clear();
    cal.set(2003, Calendar.FEBRUARY, 10);
    cal.set(Calendar.ERA, GregorianCalendar.BC);

    final Locale locale = LocaleUtils.toLocale("zh"); {
        // ja_JP_JP cannot handle dates before 1868 properly

        final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale);
        final DateParser fdf = getInstance(LONG_FORMAT, locale);

        try {
            checkParse(locale, cal, sdf, fdf);
        } catch(final ParseException ex) {
            Assert.fail("Locale "+locale+ " failed with "+LONG_FORMAT+"\n" + trimMessage(ex.toString()));
        }
    }
}
项目:SkyDocs    文件:DocsPage.java   
/**
 * Gets the last modification time formatted with the specified locale.
 * 
 * @param locale The locale (will be parsed).
 * 
 * @return The last modification time formatted with the specified locale.
 */

public final String getLastModificationTimeForLocale(final String locale) {
    Locale currentLocale = null;
    try {
        currentLocale = LocaleUtils.toLocale(locale);
    }
    catch(final Exception ex) {}
    return getLastModificationTimeForLocale(currentLocale);
}
项目:SkyDocs    文件:DocsPage.java   
/**
 * Gets the last modification time formatted with the specified locale.
 * 
 * @param locale The locale.
 * 
 * @return The last modification time formatted with the specified locale.
 */

public final String getLastModificationTimeForLocale(Locale locale) {
    if(locale == null || !LocaleUtils.isAvailableLocale(locale)) {
        locale = Locale.getDefault();
    }
    final Date date = new Date(getRawLastModificationTime());
    return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale).format(date);
}
项目:yadaframework    文件:YadaConfiguration.java   
/**
 * Get a list of iso2 locales that the webapp can handle
 * @return
 */
public List<String> getLocaleStrings() {
    if (locales==null) {
        locales = Arrays.asList(configuration.getStringArray("config/i18n/locale"));
        for (String locale : locales) {
            try {
                LocaleUtils.toLocale(locale); // Validity check
            } catch (IllegalArgumentException e) {
                throw new YadaConfigurationException("Locale {} is invalid", locale);
            }           
        }
    }
    return locales;
}
项目:opencucina    文件:I18nServiceImpl.java   
/**
 * Set default Locale. Validates locale String is valid before setting
 * locale
 *
 * @param locale
 */
public void setDefaultLocaleString(String locale) {
    try {
        defaultLocale = LocaleUtils.toLocale(locale);
    } catch (IllegalArgumentException e) {
        LOG.warn("Invalid locale has been set up [" + locale + "]");
        throw e;
    }
}
项目:i18n-editor    文件:Resources.java   
/**
 * Gets all resources from the given {@code rootDir} directory path.
 * 
 * <p>The {@code baseName} is the base of the filename of the resource files to look for.<br>
 * The base name is without extension and without any locale information.<br>
 * When a resource type is given, only resources of that type will returned.</p>
 * 
 * <p>This function will not load the contents of the file, only its description.<br>
 * If you want to load the contents, use {@link #load(Resource)} afterwards.</p>
 * 
 * @param   rootDir the root directory of the resources
 * @param   baseName the base name of the resource files to look for
 * @param   type the type of the resource files to look for
 * @return  list of found resources
 * @throws  IOException if an I/O error occurs reading the directory.
 */
public static List<Resource> get(Path rootDir, String baseName, Optional<ResourceType> type) throws IOException {
    List<Resource> result = Lists.newLinkedList();
    List<Path> files = Files.walk(rootDir, 1).collect(Collectors.toList());
    for (Path p : files) {
        ResourceType resourceType = null;
        for (ResourceType t : ResourceType.values()) {
            if (isResourceType(type, t) && isResource(rootDir, p, t, baseName)) {
                resourceType = t;
                break;
            }
        }
        if (resourceType != null) {
            String fileName = p.getFileName().toString();
            String extension = resourceType.getExtension();
            Locale locale = null;
            Path path = null;
            if (resourceType.isEmbedLocale()) {
                String pattern = "^" + baseName + "_(" + LOCALE_REGEX + ")" + extension + "$";
                Matcher match = Pattern.compile(pattern).matcher(fileName);
                if (match.find()) {
                    locale = LocaleUtils.toLocale(match.group(1));
                }
                path = Paths.get(rootDir.toString(), baseName + (locale == null ? "" : "_" + locale.toString()) + extension);               
            } else {
                locale = LocaleUtils.toLocale(fileName);
                path = Paths.get(rootDir.toString(), locale.toString(), baseName + extension);          
            }
            result.add(new Resource(resourceType, path, locale));
        }
    };
    return result;
}
项目:url-lang-id    文件:MappingsFactoryTest.java   
@Test
public void testCreateMappingAdd() throws Exception {
    MappingConfig config = new MappingConfig();
    config.name = "test";
    config.add = ImmutableMap.of("en_US", "english,anglais", "fr", "french, francais");
    MappingsFactory f = new MappingsFactory(Collections.singletonList(config));
    assertTrue(f.getMappings().containsKey("test"));

    Mapping mapping = f.getMappings().get("test");
    assertEquals(mapping.getMapping().get("english"), LocaleUtils.toLocale("en_US"));
    assertEquals(mapping.getMapping().get("anglais"), LocaleUtils.toLocale("en_US"));
    assertEquals(mapping.getMapping().get("french"), LocaleUtils.toLocale("fr"));
    assertEquals(mapping.getMapping().get("francais"), LocaleUtils.toLocale("fr"));
}
项目:tinyMediaManager    文件:MovieSetEditorDialog.java   
@Override
public void actionPerformed(ActionEvent e) {
  // search for a tmdbId
  try {
    List<MediaScraper> sets = MediaScraper.getMediaScrapers(ScraperType.MOVIE_SET);
    if (sets != null && sets.size() > 0) {
      MediaScraper first = sets.get(0); // just get first
      IMovieSetMetadataProvider mp = (IMovieSetMetadataProvider) first.getMediaProvider();

      for (Movie movie : moviesInSet) {
        MediaScrapeOptions options = new MediaScrapeOptions(MediaType.MOVIE);
        if (Utils.isValidImdbId(movie.getImdbId()) || movie.getTmdbId() > 0) {
          options.setTmdbId(movie.getTmdbId());
          options.setImdbId(movie.getImdbId());
          options.setLanguage(LocaleUtils.toLocale(MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage().name()));
          options.setCountry(MovieModuleManager.MOVIE_SETTINGS.getCertificationCountry());
          MediaMetadata md = mp.getMetadata(options);
          if ((int) md.getId(MediaMetadata.TMDB_SET) > 0) {
            tfTmdbId.setText(String.valueOf(md.getId(MediaMetadata.TMDB_SET)));
            break;
          }
        }
      }
    }
  }
  catch (Exception e1) {
    JOptionPane.showMessageDialog(null, BUNDLE.getString("movieset.tmdb.error")); //$NON-NLS-1$
  }

}
项目:tinyMediaManager    文件:MovieSetChooserDialog.java   
@Override
public Void doInBackground() {
  startProgressBar(BUNDLE.getString("chooser.searchingfor") + " " + searchTerm); //$NON-NLS-1$
  try {
    List<MediaScraper> sets = MediaScraper.getMediaScrapers(ScraperType.MOVIE_SET);
    if (sets != null && sets.size() > 0) {
      MediaScraper first = sets.get(0); // just get first
      IMovieSetMetadataProvider mp = (IMovieSetMetadataProvider) first.getMediaProvider();

      MediaSearchOptions options = new MediaSearchOptions(MediaType.MOVIE_SET, searchTerm);
      options.setLanguage(LocaleUtils.toLocale(MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage().name()));
      List<MediaSearchResult> movieSets = mp.search(options);
      movieSetsFound.clear();
      if (movieSets.size() == 0) {
        movieSetsFound.add(MovieSetChooserModel.emptyResult);
      }
      else {
        for (MediaSearchResult collection : movieSets) {
          MovieSetChooserModel model = new MovieSetChooserModel(collection);
          movieSetsFound.add(model);
        }
      }
    }
  }
  catch (Exception e1) {
    LOGGER.warn("SearchTask", e1);
  }

  return null;
}
项目:tinyMediaManager    文件:MovieChooserModel.java   
/**
 * Scrape meta data.
 */
public void scrapeMetaData() {
  try {
    // poster for preview
    setPosterUrl(result.getPosterUrl());

    MediaScrapeOptions options = new MediaScrapeOptions(MediaType.MOVIE);
    options.setResult(result);
    options.setLanguage(LocaleUtils.toLocale(language.name()));
    options.setCountry(MovieModuleManager.MOVIE_SETTINGS.getCertificationCountry());
    LOGGER.info("=====================================================");
    LOGGER.info("Scraper metadata with scraper: " + metadataProvider.getMediaProvider().getProviderInfo().getId() + ", "
        + metadataProvider.getMediaProvider().getProviderInfo().getVersion());
    LOGGER.info(options.toString());
    LOGGER.info("=====================================================");
    metadata = ((IMovieMetadataProvider) metadataProvider.getMediaProvider()).getMetadata(options);
    setOverview(metadata.getPlot());
    setTagline(metadata.getTagline());

    if (StringUtils.isBlank(posterUrl) && !metadata.getMediaArt(MediaArtworkType.POSTER).isEmpty()) {
      setPosterUrl(metadata.getMediaArt(MediaArtworkType.POSTER).get(0).getPreviewUrl());
    }

    scraped = true;
  }
  catch (Exception e) {
    LOGGER.error("scrapeMedia", e);
    MessageManager.instance.pushMessage(
        new Message(MessageLevel.ERROR, "MovieChooser", "message.scrape.threadcrashed", new String[] { ":", e.getLocalizedMessage() }));
  }
}
项目:tinyMediaManager    文件:TvShowChooserModel.java   
/**
 * Scrape meta data.
 */
public void scrapeMetaData() {
  try {
    // poster for preview
    setPosterUrl(result.getPosterUrl());

    MediaScrapeOptions options = new MediaScrapeOptions(MediaType.TV_SHOW);
    options.setResult(result);
    options.setLanguage(LocaleUtils.toLocale(language.name()));
    options.setCountry(TvShowModuleManager.SETTINGS.getCertificationCountry());
    LOGGER.info("=====================================================");
    LOGGER.info("Scraper metadata with scraper: " + mediaScraper.getMediaProvider().getProviderInfo().getId());
    LOGGER.info(options.toString());
    LOGGER.info("=====================================================");
    metadata = ((ITvShowMetadataProvider) mediaScraper.getMediaProvider()).getMetadata(options);
    setOverview(metadata.getPlot());
    setTagline(metadata.getTagline());

    if (StringUtils.isBlank(posterUrl) && !metadata.getMediaArt(MediaArtworkType.POSTER).isEmpty()) {
      setPosterUrl(metadata.getMediaArt(MediaArtworkType.POSTER).get(0).getPreviewUrl());
    }

    scraped = true;

  }
  catch (Exception e) {
    LOGGER.error("scrapeMedia", e);
    MessageManager.instance.pushMessage(
        new Message(MessageLevel.ERROR, "TvShowChooser", "message.scrape.threadcrashed", new String[] { ":", e.getLocalizedMessage() }));
  }
}
项目:tinyMediaManager    文件:TvShowChooserModel.java   
@Override
protected void doInBackground() {
  if (!scraped) {
    return;
  }

  List<MediaArtwork> artwork = new ArrayList<>();

  MediaScrapeOptions options = new MediaScrapeOptions(MediaType.TV_SHOW);
  options.setArtworkType(MediaArtworkType.ALL);
  options.setMetadata(metadata);
  for (Entry<String, Object> entry : tvShowToScrape.getIds().entrySet()) {
    options.setId(entry.getKey(), entry.getValue().toString());
  }

  options.setLanguage(LocaleUtils.toLocale(language.name()));
  options.setCountry(TvShowModuleManager.SETTINGS.getCertificationCountry());

  // scrape providers till one artwork has been found
  for (MediaScraper artworkScraper : artworkScrapers) {
    ITvShowArtworkProvider artworkProvider = (ITvShowArtworkProvider) artworkScraper.getMediaProvider();
    try {
      artwork.addAll(artworkProvider.getArtwork(options));
    }
    catch (Exception e) {
      LOGGER.warn("could not get artwork from " + artworkProvider.getProviderInfo().getName() + ": " + e.getMessage());
    }
  }

  // at last take the poster from the result
  if (StringUtils.isNotBlank(getPosterUrl())) {
    MediaArtwork ma = new MediaArtwork(result.getProviderId(), MediaArtworkType.POSTER);
    ma.setDefaultUrl(getPosterUrl());
    ma.setPreviewUrl(getPosterUrl());
    artwork.add(ma);
  }

  tvShowToScrape.setArtwork(artwork, config);
}
项目:tinyMediaManager    文件:MovieScrapeTask.java   
private List<MediaArtwork> getArtwork(Movie movie, MediaMetadata metadata, List<MediaScraper> artworkScrapers) {
  List<MediaArtwork> artwork = new ArrayList<>();

  MediaScrapeOptions options = new MediaScrapeOptions(MediaType.MOVIE);
  options.setArtworkType(MediaArtworkType.ALL);
  options.setMetadata(metadata);
  options.setImdbId(movie.getImdbId());
  options.setTmdbId(movie.getTmdbId());
  options.setLanguage(LocaleUtils.toLocale(MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage().name()));
  options.setCountry(MovieModuleManager.MOVIE_SETTINGS.getCertificationCountry());
  options.setFanartSize(MovieModuleManager.MOVIE_SETTINGS.getImageFanartSize());
  options.setPosterSize(MovieModuleManager.MOVIE_SETTINGS.getImagePosterSize());

  // scrape providers till one artwork has been found
  for (MediaScraper scraper : artworkScrapers) {
    IMovieArtworkProvider artworkProvider = (IMovieArtworkProvider) scraper.getMediaProvider();
    try {
      artwork.addAll(artworkProvider.getArtwork(options));
    }
    catch (Exception e) {
      LOGGER.error("getArtwork", e);
      MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, movie, "message.scrape.movieartworkfailed"));
    }
  }

  return artwork;
}
项目:tinyMediaManager    文件:MovieScrapeTask.java   
private List<MovieTrailer> getTrailers(Movie movie, MediaMetadata metadata, List<MediaScraper> trailerScrapers) {
  List<MovieTrailer> trailers = new ArrayList<>();

  // add local trailers!
  for (MediaFile mf : movie.getMediaFiles(MediaFileType.TRAILER)) {
    LOGGER.debug("adding local trailer " + mf.getFilename());
    MovieTrailer mt = new MovieTrailer();
    mt.setName(mf.getFilename());
    mt.setProvider("downloaded");
    mt.setQuality(mf.getVideoFormat());
    mt.setInNfo(false);
    mt.setUrl(mf.getFile().toURI().toString());
    trailers.add(mt);
  }

  MediaScrapeOptions options = new MediaScrapeOptions(MediaType.MOVIE);
  options.setMetadata(metadata);
  options.setImdbId(movie.getImdbId());
  options.setTmdbId(movie.getTmdbId());
  options.setLanguage(LocaleUtils.toLocale(MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage().name()));
  options.setCountry(MovieModuleManager.MOVIE_SETTINGS.getCertificationCountry());

  // scrape trailers
  for (MediaScraper trailerScraper : trailerScrapers) {
    try {
      IMovieTrailerProvider trailerProvider = (IMovieTrailerProvider) trailerScraper.getMediaProvider();
      List<MediaTrailer> foundTrailers = trailerProvider.getTrailers(options);
      for (MediaTrailer mediaTrailer : foundTrailers) {
        MovieTrailer movieTrailer = new MovieTrailer(mediaTrailer);
        trailers.add(movieTrailer);
      }
    }
    catch (Exception e) {
      LOGGER.error("getTrailers", e);
      MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, movie, "message.scrape.movietrailerfailed"));
    }
  }

  return trailers;
}
项目:tinyMediaManager    文件:TvShowMissingArtworkDownloadTask.java   
@Override
public void run() {
  try {
    // set up scrapers
    List<MediaArtwork> artwork = new ArrayList<>();
    MediaScrapeOptions options = new MediaScrapeOptions(MediaType.TV_EPISODE);
    options.setArtworkType(MediaArtwork.MediaArtworkType.ALL);
    options.setLanguage(LocaleUtils.toLocale(TvShowModuleManager.SETTINGS.getScraperLanguage().name()));
    options.setCountry(TvShowModuleManager.SETTINGS.getCertificationCountry());
    for (Map.Entry<String, Object> entry : episode.getTvShow().getIds().entrySet()) {
      options.setId(entry.getKey(), entry.getValue().toString());
    }
    if (episode.isDvdOrder()) {
      options.setId(MediaMetadata.SEASON_NR_DVD, String.valueOf(episode.getDvdSeason()));
      options.setId(MediaMetadata.EPISODE_NR_DVD, String.valueOf(episode.getDvdEpisode()));
    }
    else {
      options.setId(MediaMetadata.SEASON_NR, String.valueOf(episode.getAiredSeason()));
      options.setId(MediaMetadata.EPISODE_NR, String.valueOf(episode.getAiredEpisode()));
    }
    options.setArtworkType(MediaArtwork.MediaArtworkType.THUMB);

    // episode artwork is only provided by the meta data provider (not artwork provider)
    MediaMetadata metadata = ((ITvShowMetadataProvider) tvShowList.getDefaultMediaScraper().getMediaProvider()).getMetadata(options);
    for (MediaArtwork ma : metadata.getMediaArt(MediaArtwork.MediaArtworkType.THUMB)) {
      episode.setArtworkUrl(ma.getDefaultUrl(), MediaFileType.THUMB);
      episode.writeThumbImage();
      break;
    }
  }
  catch (Exception e) {
    LOGGER.error("Thread crashed", e);
    MessageManager.instance.pushMessage(new Message(Message.MessageLevel.ERROR, "TvShowMissingArtwork", "message.scrape.threadcrashed",
        new String[] { ":", e.getLocalizedMessage() }));
  }
}
项目:tinyMediaManager    文件:Utils.java   
/**
 * Gets a correct Locale (language + country) from given language.
 * 
 * @param language
 *          as 2char
 * @return Locale
 */
public static Locale getLocaleFromLanguage(String language) {
  if (StringUtils.isBlank(language)) {
    return Locale.getDefault();
  }
  // do we have a newer locale settings style?
  if (language.length() > 2) {
    return LocaleUtils.toLocale(language);
  }
  if (language.equalsIgnoreCase("en")) {
    return new Locale("en", "US"); // don't mess around; at least fixtate this
  }
  Locale l = null;
  List<Locale> countries = LocaleUtils.countriesByLanguage(language.toLowerCase(Locale.ROOT));
  for (Locale locale : countries) {
    if (locale.getCountry().equalsIgnoreCase(language)) {
      // map to main countries; de->de_DE (and not de_CH)
      l = locale;
    }
  }
  if (l == null && countries.size() > 0) {
    // well, take the first one
    l = countries.get(0);
  }

  return l;
}
项目:ft-components    文件:SLCLocaleUtils.java   
/**
 * Lookup to find the country and return corresponding locale.
 * 
 * @param country
 * @return
 */
private static Locale getLocale(String country) {
    for (Entry<String, String> localeByCountry : LOCALE_TO_COUNTRY_MAP.entrySet()) {
        if (localeByCountry.getValue().equalsIgnoreCase(country)) {
            return LocaleUtils.toLocale(localeByCountry.getKey());
        }
    }
    return null;
}
项目:ft-components    文件:LocaleBean.java   
/**
 * Check that the locale the client is attempting to use is supported.
 * @param locale - the locale the client would like to use
 * @return the locale that most closely matches the requested locale.
 */
protected Locale determineLocaleSupported(Locale locale) {
    if (getSupportedLocales().containsKey(locale.toString())) {
        return locale;
    }
    return LocaleUtils.toLocale(DEFAULT_LOCALE);
}