Beispiel #1
0
 /**
  * Method to get localized String
  *
  * @param p_key - String of the key that identify needed localized String
  * @param p_args - Array of type Object that contains parameters for localized Strings. Numbers
  *     are localized
  * @return Localized SString
  */
 public String getString(String p_key, Object[] p_args) {
   for (int i = 0; i < p_args.length; i++) {
     if (p_args[i] instanceof Date) {
       p_args[i] =
           DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG, bundle.getLocale())
               .format(p_args[i]);
     } else if (p_args[i] instanceof Number) {
       p_args[i] = NumberFormat.getNumberInstance(bundle.getLocale()).format(p_args[i]);
     }
   }
   MessageFormat formatter = new MessageFormat(bundle.getString(p_key), bundle.getLocale());
   return formatter.format(p_args);
 }
 private String debugState(final String prefix) {
   return prefix
       + "Parameter: "
       + parameter
       + "\n"
       + prefix
       + "Options: "
       + FList.mkString(options, "\n" + prefix + "  ", ",\n" + prefix + "  ", "")
       + "\n"
       + prefix
       + "Commands: "
       + FList.mkString(commands, "\n" + prefix + "  ", ",\n" + prefix + "  ", "")
       + "\n"
       + prefix
       + "ResourceBundle: "
       + resourceBundle
       + "\n"
       + prefix
       + "Locale: "
       + (resourceBundle == null ? null : resourceBundle.getLocale())
       + "\n"
       + prefix
       + "CmdOptionHandlers: "
       + FList.mkString(
           handlerRegistry.entrySet(), "\n" + prefix + "  ", "\n" + prefix + "  ", "");
 }
Beispiel #3
0
 public ResultsPanel(ResourceBundle messageResources) {
   super(new BorderLayout());
   this.messageResources = messageResources;
   dateFormat = new SimpleDateFormat("EEE d MMM yyyy", messageResources.getLocale());
   add(createControls(), BorderLayout.NORTH);
   add(createTable(), BorderLayout.CENTER);
 }
 /**
  * Creates a new StringManager for a given package. This is a private method and all access to it
  * is arbitrated by the static getManager method call so that only one StringManager per package
  * will be created.
  *
  * @param packageName Name of package to create StringManager for.
  */
 private StringManager(String packageName, Locale locale) {
   String bundleName = packageName + ".LocalStrings";
   ResourceBundle bnd = null;
   try {
     bnd = ResourceBundle.getBundle(bundleName, locale);
   } catch (MissingResourceException ex) {
     // Try from the current loader (that's the case for trusted apps)
     // Should only be required if using a TC5 style classloader structure
     // where common != shared != server
     ClassLoader cl = Thread.currentThread().getContextClassLoader();
     if (cl != null) {
       try {
         bnd = ResourceBundle.getBundle(bundleName, locale, cl);
       } catch (MissingResourceException ex2) {
         // Ignore
       }
     }
   }
   bundle = bnd;
   // Get the actual locale, which may be different from the requested one
   if (bundle != null) {
     this.locale = bundle.getLocale();
   } else {
     this.locale = null;
   }
 }
  public static String getMessage(ResourceBundle resourceBundle, String key) {
    /*
    try {
       	String bundleName = "Default";
           Field portletInfoField = PortletResourceBundle.class.getDeclaredField("_portletInfo");
           portletInfoField.setAccessible(true);
           PortletInfo portletInfo = (PortletInfo)portletInfoField.get(resourceBundle);
           bundleName = portletInfo.getTitle();
           System.out.println("MessageSourceUtil:getMessage:bundleName: " + bundleName);
       } catch (NoSuchFieldException e) {
           e.printStackTrace();
       } catch (IllegalAccessException e) {
           e.printStackTrace();
       }*/

    try {
      if (key == null || resourceBundle == null) {
        return null;
      }
      Locale locale = null;
      try {
        locale = resourceBundle.getLocale();
      } catch (Exception ignored) {
      }
      if (locale == null) {
        locale = Locale.US;
      }
      return getMessage(locale, key);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
 public String getString(String key, String dv) {
   if (i18n == null || getLocale() != i18n.getLocale()) {
     i18n = ResourceBundle.getBundle("i18n", getLocale());
   }
   String val = i18n.getString(key);
   if (val == null) return dv;
   else return val;
 }
  /**
   * Formats the given record with the head and tail.
   *
   * @param h the Handler or null.
   * @param reset true if the summary statistics and LogRecord should be reset back to initial
   *     values.
   * @return the formatted string.
   * @see #getTail(java.util.logging.Handler)
   */
  private String formatRecord(final Handler h, final boolean reset) {
    final LogRecord record;
    final long c;
    final long t;
    long msl;
    long msh;
    synchronized (this) {
      record = last;
      c = count;
      t = thrown;
      msl = minMillis;
      msh = maxMillis;

      if (reset) { // BUG ID 6351685
        reset();
      }
    }

    if (c == 0L) { // Use the estimated lifespan of this class.
      msl = INIT_TIME;
      msh = System.currentTimeMillis();
    }

    final String head;
    final String msg;
    final String tail;
    final Formatter f = this.formatter;
    if (f != null) {
      synchronized (f) {
        head = f.getHead(h);
        msg = record != null ? f.format(record) : "";
        tail = f.getTail(h);
      }
    } else {
      head = msg = tail = "";
    }

    Locale l = null;
    if (record != null) {
      ResourceBundle rb = record.getResourceBundle();
      l = rb == null ? null : rb.getLocale();
    }

    final MessageFormat mf;
    if (l == null) { // BUG ID 8039165
      mf = new MessageFormat(fmt);
    } else {
      mf = new MessageFormat(fmt, l);
    }

    /** These arguments are described in the getTail documentation. */
    return mf.format(
        new Object[] {finish(head), finish(msg), finish(tail), c, (c - 1), t, (c - t), msl, msh});
  }
Beispiel #8
0
 @Override
 public String getTranslatedString(String key) {
   try {
     key = resourceBundle.getString(key);
   } catch (MissingResourceException missingResourceException) {
     logger.debug(
         String.format(
             "Unable to find translation for key %s in %s_%s.properties",
             key, bundleLocation, resourceBundle.getLocale().getLanguage()));
   }
   return key;
 }
 @Override
 public ModelNode addResourceAttributeDescription(
     ResourceBundle bundle, String prefix, ModelNode resourceDescription) {
   final ModelNode attr = getNoTextDescription(false);
   attr.get(ModelDescriptionConstants.DESCRIPTION)
       .set(getAttributeTextDescription(bundle, prefix));
   final ModelNode result =
       resourceDescription.get(ModelDescriptionConstants.ATTRIBUTES, getName()).set(attr);
   addValueTypeDescription(result, prefix, bundle, false, null, null);
   addAccessConstraints(result, bundle.getLocale());
   return result;
 }
  /*
   * Gets the resource bundle with the given base name and preferred locale.
   *
   * This method calls java.util.ResourceBundle.getBundle(), but ignores
   * its return value unless its locale represents an exact or language match
   * with the given preferred locale.
   *
   * @param basename the resource bundle base name
   * @param pref the preferred locale
   *
   * @return the requested resource bundle, or <tt>null</tt> if no resource
   * bundle with the given base name exists or if there is no exact- or
   * language-match between the preferred locale and the locale of
   * the bundle returned by java.util.ResourceBundle.getBundle().
   */
  private static ResourceBundle findMatch(String basename, Locale pref) {
    ResourceBundle match = null;

    try {
      ResourceBundle bundle =
          ResourceBundle.getBundle(basename, pref, Thread.currentThread().getContextClassLoader());
      Locale avail = bundle.getLocale();
      if (pref.equals(avail)) {
        // Exact match
        match = bundle;
      } else {
        /*
         * We have to make sure that the match we got is for
         * the specified locale. The way ResourceBundle.getBundle()
         * works, if a match is not found with (1) the specified locale,
         * it tries to match with (2) the current default locale as
         * returned by Locale.getDefault() or (3) the root resource
         * bundle (basename).
         * We must ignore any match that could have worked with (2) or (3).
         * So if an exact match is not found, we make the following extra
         * tests:
         *     - avail locale must be equal to preferred locale
         *     - avail country must be empty or equal to preferred country
         *       (the equality match might have failed on the variant)
         */
        if (pref.getLanguage().equals(avail.getLanguage())
            && ("".equals(avail.getCountry()) || pref.getCountry().equals(avail.getCountry()))) {
          /*
           * Language match.
           * By making sure the available locale does not have a
           * country and matches the preferred locale's language, we
           * rule out "matches" based on the container's default
           * locale. For example, if the preferred locale is
           * "en-US", the container's default locale is "en-UK", and
           * there is a resource bundle (with the requested base
           * name) available for "en-UK", ResourceBundle.getBundle()
           * will return it, but even though its language matches
           * that of the preferred locale, we must ignore it,
           * because matches based on the container's default locale
           * are not portable across different containers with
           * different default locales.
           */
          match = bundle;
        }
      }
    } catch (MissingResourceException mre) {
    }

    return match;
  }
Beispiel #11
0
  /** Sets the response locale if changeResponseLocale attribute is true */
  public int doEndTag() throws JspException {
    if (_changeResponseLocale) {
      // set the locale for the response
      Locale bundleLocale = _bundle.getLocale();
      if ((bundleLocale != null) && !("".equals(bundleLocale.getLanguage()))) {
        pageContext.getResponse().setLocale(bundleLocale);
      }
    }

    // cache the bundle for use by message tags within this request

    ResourceHelper.setBundle(pageContext, _bundle, _scope);

    return EVAL_PAGE;
  }
 public void setResourceBundle(
     final String resourceBundleName, final Locale locale, final ClassLoader classloader) {
   try {
     this.resourceBundle = ResourceBundle.getBundle(resourceBundleName, locale, classloader);
     debug(
         "Loaded a ResourceBundle with name \"{0}\" using classloader \"{1}\". Locale: {2}",
         resourceBundleName, classloader, resourceBundle.getLocale());
   } catch (final MissingResourceException e) {
     debug(
         "Could not load a ResourceBundle with name \"{0}\" using classloader \"{1}\" for locale {2}",
         resourceBundleName, classloader, Locale.getDefault());
     // no resource bundle found
     this.resourceBundle = null;
   }
 }
Beispiel #13
0
  @Override
  public String getMessage(Locale locale) {
    if (bundle == null || !bundle.getLocale().equals(locale)) {
      bundle = ResourceBundle.getBundle(MESSAGE_BUNDLE_NAME, locale);
    }
    return element.accept(
        new DefaultMetadataVisitor<String>() {

          @Override
          public String visit(ComplexTypeMetadata complexType) {
            return MessageFormat.format(
                bundle.getString("remove_entity_type"), complexType.getName()); // $NON-NLS-1$
          }

          @Override
          public String visit(ReferenceFieldMetadata referenceField) {
            return MessageFormat.format(
                bundle.getString("remove_reference_field"),
                referenceField.getName()); // $NON-NLS-1$
          }

          @Override
          public String visit(ContainedTypeFieldMetadata containedField) {
            return MessageFormat.format(
                bundle.getString("remove_contained_field"),
                containedField.getName()); // $NON-NLS-1$
          }

          @Override
          public String visit(SimpleTypeFieldMetadata simpleField) {
            return MessageFormat.format(
                bundle.getString("remove_simple_field"), simpleField.getName()); // $NON-NLS-1$
          }

          @Override
          public String visit(EnumerationFieldMetadata enumField) {
            return MessageFormat.format(
                bundle.getString("remove_enum_field"), enumField.getName()); // $NON-NLS-1$
          }
        });
  }
Beispiel #14
0
 private static String formatMessage(ResourceBundle rb, String key, String... messageArguments) {
   return new MessageFormat(rb.getString(key), rb.getLocale()).format(messageArguments);
 }
  private static void notifyGroupOfTask(Context c, WorkflowItem wi, Group mygroup, EPerson[] epa)
      throws SQLException, IOException {
    // check to see if notification is turned off
    // and only do it once - delete key after notification has
    // been suppressed for the first time
    Integer myID = new Integer(wi.getItem().getID());

    if (noEMail.containsKey(myID)) {
      // suppress email, and delete key
      noEMail.remove(myID);
    } else {
      try {
        // Get the item title
        String title = getItemTitle(wi);

        // Get the submitter's name
        String submitter = getSubmitterName(wi);

        // Get the collection
        Collection coll = wi.getCollection();

        String message = "";

        for (int i = 0; i < epa.length; i++) {
          Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]);
          Email email =
              ConfigurationManager.getEmail(
                  I18nUtil.getEmailFilename(supportedLocale, "submit_task"));
          email.addArgument(title);
          email.addArgument(coll.getMetadata("name"));
          email.addArgument(submitter);

          ResourceBundle messages = ResourceBundle.getBundle("Messages", supportedLocale);
          log.info("Locale des Resource Bundles: " + messages.getLocale().getDisplayName());
          switch (wi.getState()) {
            case WFSTATE_STEP1POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step1");

              break;

            case WFSTATE_STEP2POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step2");

              break;

            case WFSTATE_STEP3POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step3");

              break;
          }
          email.addArgument(message);
          email.addArgument(getMyDSpaceLink());
          email.addRecipient(epa[i].getEmail());
          email.send();
        }
      } catch (MessagingException e) {
        log.warn(
            LogManager.getHeader(
                c,
                "notifyGroupofTask",
                "cannot email user"
                    + " group_id"
                    + mygroup.getID()
                    + " workflow_item_id"
                    + wi.getID()));
      }
    }
  }
Beispiel #16
0
  /**
   * Locates and prepares a ResourceBundle for use within this request by message tags. The bundle
   * is located as specified by the given bundle name and the user's browser locale settings. The
   * first preferred locale available that matches at least on basis of language is used. If an
   * exact match is found for both locale and country, it is used.
   *
   * <p>Once a preferred locale has been determined for the given bundle name, the locale is cached
   * in the user's session, so that the above computation can be avoided the next time the user
   * requests a page with this bundle. (The entire bundle could be cached in the session, but large
   * bundles would be problematic in servlet containers that serialize the session to provide
   * clustering.)
   *
   * <p>The bundle is obtained using org.jboss.dashboard.LocaleManager#getBunle method in order to
   * use the custom fallback control for the dashbuilder webapp.
   */
  private void findBundle() throws JspException {
    // the bundle name is required. if not provided, throw an exception
    if (_baseName == null) {
      throw new JspTagException("i18n:bundle tag, a baseName attribute must be specified.");
    }

    // Add a local variable to keep _locale unchanged.
    Locale locale = _locale;

    // if locale not provided, but an attribute was, search for it
    if (locale == null && _localeAttribute != null) {
      locale = (Locale) pageContext.findAttribute(_localeAttribute);
    }

    // if we now have a locale, grab the resource bundle
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (locale != null) {
      _bundle = _localeManager.getBundle(_baseName, locale, cl);
      if (_debug) {
        ServletContext sc = pageContext.getServletContext();
        sc.log("i18n:bundle tag debug: found locale " + locale);
      }
    }

    // attempt to load the bundle and compute the locale by looping through
    // the browser's preferred locales; cache the final locale for future use
    else {
      Enumeration localeEnumerator = pageContext.getRequest().getLocales();
      while (localeEnumerator.hasMoreElements()) {
        locale = (Locale) localeEnumerator.nextElement();

        if (_debug) {
          ServletContext sc = pageContext.getServletContext();
          sc.log("i18n:bundle tag debug: enumerating locale = " + locale);
        }

        // get a bundle and see whether it has a good locale
        ResourceBundle test = _localeManager.getBundle(_baseName, locale, cl);
        String language = test.getLocale().getLanguage();
        String country = test.getLocale().getCountry();

        // if the requested locale isn't available, the above call will
        // return a bundle with a locale for the same language, or will
        // return the default locale, so we need to compare the locale
        // of the bundle we got back with the one we asked for
        if (test.getLocale().equals(locale)) {
          // exactly what we were looking for - stop here and use this
          _bundle = test;
          break;
        } else if (locale.getLanguage().equals(language)) {
          // the language matches; see if the country matches as well
          if (locale.getCountry().equals(country)) {
            // keep looking but this is a good option. it only gets
            // better if the variant matches too!  (note: we will only
            // get to this statement if a variant has been provided)
            _bundle = test;
            continue;
          } else {
            // if we don't already have a candidate, this is a good
            // one otherwise, don't change it because the current
            // candidate might match the country but not the variant
            if (_bundle == null) {
              _bundle = test;
            }
            continue;
          }
        } else if (_debug) {
          ServletContext sc = pageContext.getServletContext();
          sc.log("i18n:bundle tag requested locale not available: " + locale);
        }
      }

      // bundle should never be null at this point - if the last locale on
      // the list wasn't available, the default locale should have kicked
      // in, but I like being safe, hence the code below.
      if (_bundle == null) {
        _bundle = _localeManager.getBundle(_baseName);
      }

      if (_debug) {
        ServletContext sc = pageContext.getServletContext();
        sc.log("i18n:bundle tag debug: bundle (sensed locale) = " + _bundle);
      }

      // if the localeAttribute was provided, but didn't have a value,
      // go ahead and remember the value for next time
      if (_localeAttribute != null) {
        HttpSession session = pageContext.getSession();
        session.setAttribute(_localeAttribute, _bundle.getLocale());
      }
    }
  }
 public final Locale getLocale() {
   return resBundle.getLocale();
 }
Beispiel #18
0
  private static boolean changeLocale(Locale newLocale, boolean force) {
    // set locale for startup (will override immediately it on locale change anyway)
    Locale.setDefault(newLocale);

    if (!isCurrentLocale(newLocale) || force) {
      Locale.setDefault(LOCALE_DEFAULT);
      ResourceBundle newResourceBundle = null;
      String bundleFolder = BUNDLE_NAME.replace('.', '/');
      final String prefix = BUNDLE_NAME.substring(BUNDLE_NAME.lastIndexOf('.') + 1);
      final String extension = ".properties";

      if (newLocale.equals(LOCALE_ENGLISH)) newLocale = LOCALE_DEFAULT;

      try {
        File userBundleFile = new File(SystemProperties.getUserPath());
        File appBundleFile = new File(SystemProperties.getApplicationPath());

        // Get the jarURL
        // XXX Is there a better way to get the JAR name?
        ClassLoader cl = MessageText.class.getClassLoader();
        String sJar = cl.getResource(bundleFolder + extension).toString();
        sJar = sJar.substring(0, sJar.length() - prefix.length() - extension.length());
        URL jarURL = new URL(sJar);

        // User dir overrides app dir which overrides jar file bundles
        URL[] urls = {userBundleFile.toURL(), appBundleFile.toURL(), jarURL};

        /* This is debugging code, use it when things go wrong :) The line number
         * is approximate as the input stream is buffered by the reader...

        {
        	LineNumberInputStream lnis	= null;

            try{
                ClassLoader fff = new URLClassLoader(urls);

                java.io.InputStream stream = fff.getResourceAsStream("MessagesBundle_th_TH.properties");

                lnis = new LineNumberInputStream( stream );

                new java.util.PropertyResourceBundle(lnis);
            }catch( Throwable e ){

            	System.out.println( lnis.getLineNumber());

            	e.printStackTrace();
            }
        }
        */

        newResourceBundle =
            getResourceBundle("MessagesBundle", newLocale, new URLClassLoader(urls));
        // do more searches if getBundle failed, or if the language is not the
        // same and the user wanted a specific country
        if ((!newResourceBundle.getLocale().getLanguage().equals(newLocale.getLanguage())
            && !newLocale.getCountry().equals(""))) {

          Locale foundLocale = newResourceBundle.getLocale();
          System.out.println(
              "changeLocale: "
                  + (foundLocale.toString().equals("")
                      ? "*Default Language*"
                      : foundLocale.getDisplayLanguage())
                  + " != "
                  + newLocale.getDisplayName()
                  + ". Searching without country..");
          // try it without the country
          Locale localeJustLang = new Locale(newLocale.getLanguage());
          newResourceBundle =
              getResourceBundle("MessagesBundle", localeJustLang, new URLClassLoader(urls));

          if (newResourceBundle == null
              || !newResourceBundle
                  .getLocale()
                  .getLanguage()
                  .equals(localeJustLang.getLanguage())) {
            // find first language we have in our list
            System.out.println(
                "changeLocale: Searching for language "
                    + newLocale.getDisplayLanguage()
                    + " in *any* country..");
            Locale[] locales = getLocales();
            for (int i = 0; i < locales.length; i++) {
              if (locales[i].getLanguage() == newLocale.getLanguage()) {
                newResourceBundle =
                    getResourceBundle("MessagesBundle", locales[i], new URLClassLoader(urls));
                break;
              }
            }
          }
        }
      } catch (MissingResourceException e) {
        System.out.println("changeLocale: no resource bundle for " + newLocale);
        Debug.printStackTrace(e);
        return false;
      } catch (Exception e) {
        Debug.printStackTrace(e);
      }

      if (newResourceBundle != null) {
        if (!newLocale.equals(LOCALE_DEFAULT) && !newResourceBundle.getLocale().equals(newLocale)) {
          String sNewLanguage = newResourceBundle.getLocale().getDisplayName();
          if (sNewLanguage == null || sNewLanguage.trim().equals(""))
            sNewLanguage = "English (default)";
          System.out.println(
              "changeLocale: no message properties for Locale '"
                  + newLocale.getDisplayName()
                  + "' ("
                  + newLocale
                  + "), using '"
                  + sNewLanguage
                  + "'");
        }
        newLocale = newResourceBundle.getLocale();
        Locale.setDefault(newLocale.equals(LOCALE_DEFAULT) ? LOCALE_ENGLISH : newLocale);
        LOCALE_CURRENT = newLocale;
        setResourceBundle(new IntegratedResourceBundle(newResourceBundle, pluginLocalizationPaths));
        if (newLocale.equals(LOCALE_DEFAULT)) DEFAULT_BUNDLE = RESOURCE_BUNDLE;
        return true;
      } else return false;
    }
    return false;
  }
  /**
   * Find a resource bundle by looking up using the locales. This is done by loading either the
   * specified locale based resource bundle and, if that fails, by looping through the fallback
   * locales to locate a usable bundle.
   */
  private ResourceBundle findBundle(String baseName) {
    ResourceBundle resourceBundle = null;

    // first try to load the resource bundle with the specified locale
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (null != locale) {
      try {
        resourceBundle = ResourceBundle.getBundle(baseName, locale, cl);
      } catch (Exception e) {
        log.fatal("unable to load a default bundle: " + baseName + "_" + locale);
      }
      // check that the requested main locale matches the resource bundle's,
      // since we get the system fallback locale if no match is found
      if (!resourceBundle.getLocale().equals(locale)) {
        resourceBundle = null;
      }
    }

    // loop through the fall back locales until a bundle is found
    if (null == resourceBundle) {
      if (null != fallback) {
        while (fallback.hasMoreElements()) {
          Locale testLocale = (Locale) fallback.nextElement();
          log.debug("looking up locale " + testLocale);
          ResourceBundle testBundle = ResourceBundle.getBundle(baseName, testLocale, cl);
          String language = testBundle.getLocale().getLanguage();
          String country = testBundle.getLocale().getCountry();

          if (testBundle.getLocale().equals(testLocale)) {
            resourceBundle = testBundle;
            log.debug("found bundle for locale " + baseName + "_" + testBundle.getLocale());
            break;
          } else if (testLocale.getLanguage().equals(language)) {
            if (testLocale.getCountry().equals(country)) {
              // language and country match which is good, keep looking for variant too
              resourceBundle = testBundle;
              log.debug("potential bundle: " + baseName + "_" + testBundle.getLocale());
              continue;
            } else {
              // only accept this if there is no better previous lookup
              if (null == resourceBundle) {
                resourceBundle = testBundle;
                log.debug("potential bundle: " + baseName + "_" + testBundle.getLocale());
              }
              continue;
            }
          }
        }
      }

      // make sure the resource bundle is loaded (should not happen)
      if (null == resourceBundle) {
        resourceBundle = ResourceBundle.getBundle(baseName);
        if (null != resourceBundle) {
          log.debug("system locale bundle taken: " + baseName + "_" + resourceBundle.getLocale());
        }
      }
    }

    return resourceBundle;
  }
Beispiel #20
0
 /**
  * Returns the Code of language used by the ResourceBundle
  *
  * @return Code of language used by the ResourceBundle
  */
 public String getLanguage() {
   return bundle.getLocale().getLanguage();
 }
Beispiel #21
0
  public static String getSystemInfoText() {

    ResourceBundle resb = TranslationBundle.getBundle();

    String netInfo, home, cpu, name, info;

    if (checkForNoSandbox()) {
      home = System.getProperty("java.home");
      cpu = System.getProperty("sun.cpu.isalist");
      name =
          System.getProperty("java.runtime.name")
              + " ("
              + System.getProperty("java.runtime.version")
              + ")";
      info = System.getProperty("java.vm.info");

      // we CAN do this outside the sandbox, but for some reason it promps the webstart
      try {
        netInfo =
            InetAddress.getLocalHost().getHostAddress()
                + " ("
                + InetAddress.getLocalHost().getHostName()
                + ")";
      } catch (UnknownHostException e) {
        netInfo = resb.getString("about.nonetwork");
      }
    } else {
      home = "?";
      cpu = "?";
      info = "?";

      if (applet != null) {
        name = "applet";
      } else if (webstart != null) {
        name = "web start (" + webstart + ")";
      } else {
        name = "?";
      }

      netInfo = "?";
    }

    String displayInfo;
    try {
      Toolkit toolkit = Toolkit.getDefaultToolkit();
      displayInfo =
          toolkit.getScreenSize().width
              + "x"
              + toolkit.getScreenSize().height
              + " ("
              + toolkit.getScreenResolution()
              + "dpi) density="
              + GraphicsUtil.density
              + " scale="
              + GraphicsUtil.scale;
    } catch (HeadlessException ex) {
      displayInfo = ex.getMessage();
      if (displayInfo != null) displayInfo = RiskUtil.replaceAll(displayInfo, "\n", " ");
    }

    return " "
        + RiskUtil.RISK_VERSION
        + " (save: "
        + RiskGame.SAVE_VERSION
        + " network: "
        + RiskGame.NETWORK_VERSION
        + ") \n"
        + " "
        + "system:"
        + java.util.Locale.getDefault()
        + " current:"
        + resb.getLocale()
        + " \n"
        + " "
        + netInfo
        + " \n"
        + " "
        + getOSString()
        + " \n"
        + " "
        + cpu
        + " \n"
        + " "
        + UIManager.getLookAndFeel()
        + " \n"
        + " "
        + displayInfo
        + " \n"
        + " "
        + System.getProperty("java.vendor")
        + " \n"
        + " "
        + System.getProperty("java.vendor.url")
        + " \n"
        + " "
        + name
        + " \n"
        + " "
        + System.getProperty("java.vm.name")
        + " ("
        + System.getProperty("java.vm.version")
        + ", "
        + info
        + ") \n"
        + " "
        + System.getProperty("java.specification.version")
        + " ("
        + System.getProperty("java.version")
        + ") \n"
        + " "
        + home
        + " \n"
        + " "
        + System.getProperty("java.class.version");
  }
Beispiel #22
0
  private static ResourceBundle processGetBundle(
      String baseName,
      Locale targetLocale,
      ClassLoader loader,
      ResourceBundle.Control control,
      boolean expired,
      ResourceBundle result) {
    List<Locale> locales = control.getCandidateLocales(baseName, targetLocale);
    if (null == locales) {
      throw new IllegalArgumentException();
    }
    List<String> formats = control.getFormats(baseName);
    if (Control.FORMAT_CLASS == formats
        || Control.FORMAT_PROPERTIES == formats
        || Control.FORMAT_DEFAULT == formats) {
      throw new IllegalArgumentException();
    }
    ResourceBundle ret = null;
    ResourceBundle currentBundle = null;
    ResourceBundle bundle = null;
    for (Locale locale : locales) {
      for (String format : formats) {
        try {
          if (expired) {
            bundle =
                control.newBundle(
                    baseName,
                    locale,
                    format,
                    loader,
                    control.needsReload(
                        baseName, locale, format, loader, result, System.currentTimeMillis()));

          } else {
            try {
              bundle = control.newBundle(baseName, locale, format, loader, false);
            } catch (IllegalArgumentException e) {
              // do nothing
            }
          }
        } catch (IllegalAccessException e) {
          // do nothing
        } catch (InstantiationException e) {
          // do nothing
        } catch (IOException e) {
          // do nothing
        }
        if (null != bundle) {
          if (null != currentBundle) {
            currentBundle.setParent(bundle);
            currentBundle = bundle;
          } else {
            if (null == ret) {
              ret = bundle;
              currentBundle = ret;
            }
          }
        }
        if (null != bundle) {
          break;
        }
      }
    }

    if ((null == ret)
        || (Locale.ROOT.equals(ret.getLocale())
            && (!(locales.size() == 1 && locales.contains(Locale.ROOT))))) {
      Locale nextLocale = control.getFallbackLocale(baseName, targetLocale);
      if (null != nextLocale) {
        ret = processGetBundle(baseName, nextLocale, loader, control, expired, result);
      }
    }

    return ret;
  }
Beispiel #23
0
 @FXML
 void setEnglish(ActionEvent event) throws IOException {
   resources = ResourceBundle.getBundle("Bundle", new Locale("en", "EN"));
   System.out.println(resources.getLocale());
   this.changeLanguage(resources);
 }
Beispiel #24
0
 public Locale getLocale() {
   return delegate.getLocale();
 }
  /**
   * Creates localized messages of all the constraint violations that has occured.
   *
   * <p>The key &nbsp;"<code>Qi4j_ConstraintViolation_<i><strong>CompositeType</strong></code></i>"
   * will be used to lookup the text formatting pattern from the ResourceBundle, where <strong>
   * <code><i>CompositeType</i></code></strong> is the class name of the Composite where the
   * constraint was violated. If such key does not exist, then the key &nbsp;"<code>
   * Qi4j_ConstraintViolation</code>" will be used, and if that one also doesn't exist, or the
   * resourceBundle argument is null, then the default patterns will be used;
   *
   * <table><tr><th>Type of Composite</th><th>Pattern used</th></tr>
   * <tr><td>Composite</td>
   * <td><code>Constraint Violation in {2}.{3} with constraint {4}, in composite \n{0} of type {1}</code></td>
   * </tr>
   * <tr><td>EntityComposite</td>
   * <td><code>Constraint Violation in {2}.{3} with constraint {4}, in entity {1}[id={0}]</code></td>
   * </tr>
   * <tr><td>ServiceComposite</td>
   * <td><code>Constraint Violation in {2}.{3} with constraint {4}, in service {0}</code></td>
   * </tr>
   * </table>
   *
   * Then format each ConstraintViolation according to such pattern, where the following argument
   * are passed;
   *
   * <table><tr><th>Arg</th><th>Value</th></tr>
   * <tr>
   * <td>{0}</td>
   * <td>Composite instance toString()</td>
   * </tr>
   * <tr>
   * <td>{1}</td>
   * <td>CompositeType class name</td>
   * </tr>
   * <tr>
   * <td>{2}</td>
   * <td>MixinType class name</td>
   * </tr>
   * <tr>
   * <td>{3}</td>
   * <td>MixinType method name</td>
   * </tr>
   * <tr>
   * <td>{4}</td>
   * <td>Annotation toString()</td>
   * </tr>
   * <tr>
   * <td>{5}</td>
   * <td>toString() of value passed as the argument, or "null" text if argument was null.</td>
   * </tr>
   * </table>
   *
   * <p><b>NOTE!!!</b> This class is still under construction and will be modified further.
   *
   * @param bundle The ResourceBundle for Localization, or null if default formatting and locale to
   *     be used.
   * @return An array of localized messages of the violations incurred.
   */
  public String[] localizedMessagesFrom(ResourceBundle bundle) {
    String pattern =
        "Constraint violation in {0}.{1} for method ''{3}'' with constraint \"{4}({6})\", for value ''{5}''";

    ArrayList<String> list = new ArrayList<String>();
    for (ConstraintViolation violation : constraintViolations) {
      Locale locale;
      if (bundle != null) {
        try {
          pattern = bundle.getString("qi4j.constraint." + mixinTypeName + "." + methodName);
        } catch (MissingResourceException e1) {
          try {
            pattern = bundle.getString("qi4j.constraint");
          } catch (MissingResourceException e2) {
            // ignore. The default pattern will be used.
          }
        }
        locale = bundle.getLocale();
      } else {
        locale = Locale.getDefault();
      }
      MessageFormat format = new MessageFormat(pattern, locale);

      Annotation annotation = violation.constraint();
      String name = violation.name();
      Object value = violation.value();
      String classes;
      if (Iterables.count(instanceTypes) == 1) {
        classes = Iterables.first(instanceTypes).getSimpleName();
      } else {
        classes =
            "["
                + Iterables.<Class<?>>toString(
                    instanceTypes,
                    new Function<Class<?>, String>() {
                      @Override
                      public String map(Class<?> from) {
                        return from.getSimpleName();
                      }
                    },
                    ",")
                + "]";
      }
      Object[] args =
          new Object[] {
            instanceToString,
            classes,
            mixinTypeName,
            methodName,
            annotation.toString(),
            "" + value,
            name
          };
      StringBuffer text = new StringBuffer();
      format.format(args, text, null);
      list.add(text.toString());
    }
    String[] result = new String[list.size()];
    list.toArray(result);
    return result;
  }
Beispiel #26
0
 @Override
 public Locale getLocale() {
   return bundle.getLocale();
 }
 /**
  * Constructs an I18N localization context from the given resource bundle.
  *
  * <p>The localization context's locale is taken from the given resource bundle.
  *
  * @param bundle The resource bundle
  */
 public LocalizationContext(ResourceBundle bundle) {
   this.bundle = bundle;
   this.locale = bundle.getLocale();
 }
 @Override
 public Locale getLocale() {
   return null != delegate ? delegate.getLocale() : null;
 }