Exemple #1
0
  public static Locale localeMatch(List<String> requestedLocales, List<Locale> availableLocales) {
    if (requestedLocales == null || availableLocales == null) {
      return null;
    }

    for (String requestedLocale : requestedLocales) {
      Locale reqInQuestion = LocaleUtils.toLocale(requestedLocale);
      List<Locale> lookupList = LocaleUtils.localeLookupList(reqInQuestion);

      for (Locale localeInQuestion : lookupList) {
        for (Locale availableLocale : availableLocales) {
          if (localeInQuestion.equals(availableLocale)) {
            return availableLocale;
          }
        }
      }

      for (Locale availableLocale : availableLocales) {
        if (reqInQuestion.getLanguage().equals(availableLocale.getLanguage())) {
          return availableLocale;
        }
      }
    }

    return null;
  }
Exemple #2
0
  /**
   * Attempts to parse given String to an instance of a given class. The class may also have a
   * generic type. It will throw {@link java.lang.IllegalStateException} in case this method was not
   * able to parse the value.
   *
   * @param str String to parse
   * @param toClass a class to turn value into
   * @param generic generic class
   * @return parsed value, an instance of the given class
   */
  public static Object parseString(String str, Class<?> toClass, Class<?> generic) {
    if (isBlank(str, toClass)) {
      return (String.class.isAssignableFrom(toClass)) ? "" : null;
    }

    if (isDateOrPeriod(toClass)) {
      return parseDateOrPeriod(toClass, str);
    }

    try {
      if (toClass.isEnum()) {
        Class<? extends Enum> enumClass = (Class<? extends Enum>) toClass;
        return Enum.valueOf(enumClass, str);
      }

      if (Collection.class.isAssignableFrom(toClass)) {
        return parseStringToCollection(str, toClass, generic);
      } else if (Map.class.isAssignableFrom(toClass)) {
        return parseStringToMap(str);
      } else if (Locale.class.isAssignableFrom(toClass)) {
        return LocaleUtils.toLocale(str);
      } else if (Byte[].class.isAssignableFrom(toClass)) {
        return ArrayUtils.toObject(str.getBytes());
      } else {
        return MethodUtils.invokeStaticMethod(toClass, "valueOf", str);
      }
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
      throw new IllegalStateException("Unable to parse value " + str + " to " + toClass, e);
    }
  }
 protected Locale getLocale() {
   String locale = (String) getProperties().get("locale");
   if (!StringUtils.isBlank(locale)) {
     return LocaleUtils.toLocale(locale);
   }
   return Locale.getDefault();
 }
 @Override
 public String generatePageHtml(ITestPage test) {
   TemplateResolver templateResolver = new ClassLoaderTemplateResolver();
   templateResolver.setTemplateMode("HTML5");
   templateResolver.setCharacterEncoding("UTF-8");
   TemplateEngine templateEngine = new TemplateEngine();
   templateEngine.setTemplateResolver(templateResolver);
   Locale locale = LocaleUtils.toLocale("fr");
   final Context ctx = new Context(locale);
   ctx.setVariable("test", test);
   String htmlOutput = templateEngine.process("new_test_report_template.html", ctx);
   return htmlOutput;
 }
  /** Tests the case where we don't use a mapping file and just map records by name. */
  @Test
  public void testDefaultConversion() throws Exception {
    // We will convert s1 from string to long (or leave it null), ignore s2,
    // convert s3 to from string to double, convert l1 from long to string,
    // and leave l2 the same.
    Schema input =
        SchemaBuilder.record("Input")
            .namespace("com.cloudera.edh")
            .fields()
            .nullableString("s1", "")
            .requiredString("s2")
            .requiredString("s3")
            .optionalLong("l1")
            .requiredLong("l2")
            .endRecord();
    Schema output =
        SchemaBuilder.record("Output")
            .namespace("com.cloudera.edh")
            .fields()
            .optionalLong("s1")
            .optionalString("l1")
            .requiredLong("l2")
            .requiredDouble("s3")
            .endRecord();

    AvroRecordConverter converter =
        new AvroRecordConverter(input, output, EMPTY_MAPPING, LocaleUtils.toLocale("en_US"));

    Record inputRecord = new Record(input);
    inputRecord.put("s1", null);
    inputRecord.put("s2", "blah");
    inputRecord.put("s3", "5.5");
    inputRecord.put("l1", null);
    inputRecord.put("l2", 5L);
    Record outputRecord = converter.convert(inputRecord);
    assertNull(outputRecord.get("s1"));
    assertNull(outputRecord.get("l1"));
    assertEquals(5L, outputRecord.get("l2"));
    assertEquals(5.5, outputRecord.get("s3"));

    inputRecord.put("s1", "500");
    inputRecord.put("s2", "blah");
    inputRecord.put("s3", "5.5e-5");
    inputRecord.put("l1", 100L);
    inputRecord.put("l2", 2L);
    outputRecord = converter.convert(inputRecord);
    assertEquals(500L, outputRecord.get("s1"));
    assertEquals("100", outputRecord.get("l1"));
    assertEquals(2L, outputRecord.get("l2"));
    assertEquals(5.5e-5, outputRecord.get("s3"));
  }
 public Locale getLocale() {
   Locale locale = null;
   try {
     String stringLocale = "";
     if (StringUtils.isNotEmpty(country) && !country.equalsIgnoreCase(language)) {
       stringLocale = language + "_" + country;
     } else {
       stringLocale = language;
     }
     locale = LocaleUtils.toLocale(stringLocale);
   } catch (Exception e) {
     // NO LOG - EXCEPTION IS CAUSE BY LocaleUtils AND A NON ISO CODE LIKE SIMPLY ZH
   }
   return locale;
 }
 @Override
 public Locale getLocale(CoreSession repo) throws ClientException {
   UserProfileService userProfileService = Framework.getLocalService(UserProfileService.class);
   DocumentModel userProfileDoc = userProfileService.getUserProfileDocument(repo);
   String locale =
       (String) userProfileDoc.getPropertyValue(UserProfileConstants.USER_PROFILE_LOCALE);
   if (locale == null || locale.trim().length() == 0) {
     // undefined if not set
     return null;
   }
   try {
     return LocaleUtils.toLocale(locale);
   } catch (Exception e) {
     log.error("Locale parse exception:  \"" + locale + "\"", e);
   }
   return null;
 }
  public void processEmailTemplates(List<String> templatePaths) {

    final String ADMIN = "admin";

    Persister persister = new Persister();
    for (String templatePath : templatePaths) {

      log.debug("Processing template: " + templatePath);

      InputStream in = getClass().getClassLoader().getResourceAsStream(templatePath);

      if (in == null) {
        log.warn("Could not load resource from '" + templatePath + "'. Skipping ...");
        continue;
      }

      EmailTemplate template = null;
      try {
        template = persister.read(EmailTemplate.class, in);
      } catch (Exception e) {
        log.warn(
            "Error processing template: '"
                + templatePath
                + "', "
                + e.getClass()
                + ":"
                + e.getMessage()
                + ". Skipping ...");
        continue;
      }

      // check if we have an existing template of this key and locale
      // its possible the template has no locale set
      // The locale could also be the Default
      Locale loc = null;
      if (template.getLocale() != null
          && !"".equals(template.getLocale())
          && !EmailTemplate.DEFAULT_LOCALE.equals(template.getLocale())) {
        loc = LocaleUtils.toLocale(template.getLocale());
      }

      EmailTemplate existingTemplate = getEmailTemplateNoDefault(template.getKey(), loc);
      if (existingTemplate == null) {
        // no existing, save this one
        Session sakaiSession = sessionManager.getCurrentSession();
        sakaiSession.setUserId(ADMIN);
        sakaiSession.setUserEid(ADMIN);
        saveTemplate(template);
        sakaiSession.setUserId(null);
        sakaiSession.setUserId(null);
        log.info(
            "Saved email template: " + template.getKey() + " with locale: " + template.getLocale());
        continue; // skip to next
      }

      // check version, if local one newer than persisted, update it - SAK-17679
      // also update the locale - SAK-20987
      int existingTemplateVersion =
          existingTemplate.getVersion() != null ? existingTemplate.getVersion().intValue() : 0;
      if (template.getVersion() > existingTemplateVersion) {
        existingTemplate.setSubject(template.getSubject());
        existingTemplate.setMessage(template.getMessage());
        existingTemplate.setHtmlMessage(template.getHtmlMessage());
        existingTemplate.setVersion(template.getVersion());
        existingTemplate.setOwner(template.getOwner());
        existingTemplate.setLocale(template.getLocale());

        Session sakaiSession = sessionManager.getCurrentSession();
        sakaiSession.setUserId(ADMIN);
        sakaiSession.setUserEid(ADMIN);
        updateTemplate(existingTemplate);
        sakaiSession.setUserId(null);
        sakaiSession.setUserId(null);
        log.info(
            "Updated email template: "
                + template.getKey()
                + " with locale: "
                + template.getLocale());
      }
    }
  }