Java Code Examples for java.util.ResourceBundle#getBundle()

The following examples show how to use java.util.ResourceBundle#getBundle() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void testAllPropertiesCorrespondToKeys() {
    final String path = LocalizedFormats.class.getName().replaceAll("\\.", "/");
    for (final String language : new String[] { "fr" } ) {
        ResourceBundle bundle =
            ResourceBundle.getBundle("assets/" + path, new Locale(language));
        for (final Enumeration<String> keys = bundle.getKeys(); keys.hasMoreElements();) {
            final String propertyKey = keys.nextElement();
            try {
                Assert.assertNotNull(LocalizedFormats.valueOf(propertyKey));
            } catch (IllegalArgumentException iae) {
                Assert.fail("unknown key \"" + propertyKey + "\" in language " + language);
            }
        }
        Assert.assertEquals(language, bundle.getLocale().getLanguage());
    }

}
 
Example 2
@Override
public String getLocalized() {
  String templateToUse = template;
  if (bundle != null) {
    Locale locale = LocaleInContext.get();
    if (locale != null) {
      try {
        ResourceBundle rb = ResourceBundle.getBundle(bundle, locale, classLoader);
        if (rb.containsKey(id)) {
          templateToUse = rb.getString(id);
        } else if (!MISSING_KEY_WARNS.contains(bundle + " " + id)) {
          MISSING_KEY_WARNS.add(bundle + " " + id);
          LOG.warn("ResourceBundle '{}' does not have key '{}' via ClassLoader '{}'", bundle, id, classLoader);
        }
      } catch (MissingResourceException ex) {
        if (!MISSING_BUNDLE_WARNS.contains(bundle)) {
          MISSING_BUNDLE_WARNS.add(bundle);
          LOG.debug("ResourceBundle '{}' not found via ClassLoader '{}'", bundle, classLoader);
        }
      }
    }
  }
  return Utils.format(templateToUse, args);
}
 
Example 3
private String localize( String key ) {
    ResourceBundle rb;

    if(locale==null)
        rb = ResourceBundle.getBundle(NameGetter.class.getName());
    else
        rb = ResourceBundle.getBundle(NameGetter.class.getName(),locale);

    return rb.getString(key);
}
 
Example 4
Source Project: tn5250j   File: LangTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void init(String initMsgFile) {
   if (labels != null)
      return;

   try {
      labels = ResourceBundle.getBundle(initMsgFile,locale);
   }
   catch (MissingResourceException mre) {
      System.out.println(mre.getLocalizedMessage());
   }
}
 
Example 5
public static void doOutputFor(String packageName,
        String resourceBundleName, PrintStream out)
                throws Exception {
    Locale[] availableLocales = Locale.getAvailableLocales();

    ResourceBundle bundle = ResourceBundle.getBundle(packageName +
                    resourceBundleName, new Locale("", "", ""));
    dumpResourceBundle(resourceBundleName + "/", bundle, out);
    for (int i = 0; i < availableLocales.length; i++) {
        bundle = ResourceBundle.getBundle(packageName + resourceBundleName,
                        availableLocales[i]);
        dumpResourceBundle(resourceBundleName + "/" + availableLocales[i].toString(),
                        bundle, out);
    }
}
 
Example 6
Source Project: zap-extensions   File: CMSSTopMenu.java    License: Apache License 2.0 5 votes vote down vote up
/** */
public CMSSTopMenu() {
    super("ExtensionTopMenu");
    // Load extension specific language files - these are held in the extension jar
    messages =
            ResourceBundle.getBundle(
                    this.getClass().getPackage().getName() + ".resources.Messages",
                    Constant.getLocale());
}
 
Example 7
Source Project: SIMVA-SoS   File: ResourceBundleWrapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds and returns the specified resource bundle.
 *
 * @param baseName  the base name.
 * @param locale  the locale.
 *
 * @return The resource bundle.
 */
public static ResourceBundle getBundle(String baseName, Locale locale) {

    // the noCodeBaseClassLoader is configured by a call to the
    // removeCodeBase() method, typically in the init() method of an
    // applet...
    if (noCodeBaseClassLoader != null) {
        return ResourceBundle.getBundle(baseName, locale,
                noCodeBaseClassLoader);
    }
    else {
        // standard ResourceBundle behaviour
        return ResourceBundle.getBundle(baseName, locale);
    }
}
 
Example 8
Source Project: xJavaFxTool-spring   File: PluginLoader.java    License: Apache License 2.0 5 votes vote down vote up
public static void loadPluginAsTab(PluginJarInfo plugin, TabPane tabPane) {
    try {
        FXMLLoader generatingCodeFXMLLoader = new FXMLLoader(PluginLoader.class.getResource(plugin.getFxmlPath()));

        if (StringUtils.isNotEmpty(plugin.getBundleName())) {
            ResourceBundle resourceBundle = ResourceBundle.getBundle(plugin.getBundleName(), Config.defaultLocale);
            generatingCodeFXMLLoader.setResources(resourceBundle);
        }

        Tab tab = new Tab(plugin.getTitle());

        if (StringUtils.isNotEmpty(plugin.getIconPath())) {
            ImageView imageView = new ImageView(new Image(plugin.getIconPath()));
            imageView.setFitHeight(18);
            imageView.setFitWidth(18);
            tab.setGraphic(imageView);
        }

        tab.setContent(generatingCodeFXMLLoader.load());
        tabPane.getTabs().add(tab);
        tabPane.getSelectionModel().select(tab);

        tab.setOnCloseRequest(
            event -> JavaFxViewUtil.setControllerOnCloseRequest(generatingCodeFXMLLoader.getController(), event)
        );
    } catch (Exception e) {
        log.error("加载插件失败", e);
    }
}
 
Example 9
public Font run() {
    try {
        ResourceBundle rb = ResourceBundle.getBundle("sun.awt.windows.awtLocalization");
        return Font.decode(rb.getString("menuFont"));
    } catch (MissingResourceException e) {
        if (log.isLoggable(PlatformLogger.Level.FINE)) {
            log.fine("WMenuItemPeer: " + e.getMessage()+". Using default MenuItem font.", e);
        }
        return new Font("SanSerif", Font.PLAIN, 11);
    }
}
 
Example 10
/**
 * Gets the label.
 *
 * @param key the key
 * @return the label
 */
public static String getLabel(String key) {
    if (bundle == null) {
        bundle = ResourceBundle.getBundle("label", Locale.getDefault());
        LOG.info("Loading resource bundle for locale " + bundle.getLocale());
    }
    return bundle.getString(key);
}
 
Example 11
static void TestBundle() {
    System.out.println("  TestBundle {");

    // This will fall back to the default locale's bundle or root bundle
    ResourceBundle rb = ResourceBundle.getBundle("TestBundle",
                                                    new Locale("et", ""));
    if (rb.getLocale().getLanguage().equals(new Locale("iw").getLanguage())) {
        assertEquals(rb, ComponentOrientation.RIGHT_TO_LEFT, "et == RIGHT_TO_LEFT" );
    } else if (rb.getLocale().getLanguage() == "es") {
        assertEquals(rb, ComponentOrientation.LEFT_TO_RIGHT, "et == LEFT_TO_RIGHT" );
    } else {
        assertEquals(rb, ComponentOrientation.UNKNOWN, "et == UNKNOWN" );
    }

    // We have actual bundles for "es" and "iw", so it should just fetch
    // the orientation object out of them
    rb = ResourceBundle.getBundle("TestBundle",new Locale("es", ""));
    assertEquals(rb, ComponentOrientation.LEFT_TO_RIGHT, "es == LEFT_TO_RIGHT" );

    rb = ResourceBundle.getBundle("TestBundle", new Locale("iw", "IL"));
    assertEquals(rb, ComponentOrientation.RIGHT_TO_LEFT, "iw == RIGHT_TO_LEFT" );

    // This bundle has no orientation setting at all, so we should get
    // the system's default orientation for Arabic
    rb = ResourceBundle.getBundle("TestBundle1", new Locale("ar", ""));
    assertEquals(rb, ComponentOrientation.RIGHT_TO_LEFT, "ar == RIGHT_TO_LEFT" );

    System.out.println("  } Pass");
}
 
Example 12
private void createUIComponents() {
	bundle = ResourceBundle.getBundle("com.kaylerrenslow.armaplugin.ProjectSettingsBundle");

	tfWithBrowseReferenceDirectory = new TextFieldWithBrowseButton(new JTextField(40));

	treeAddonsRoots_rootNode = new RootTreeNode();
	treeAddonsRoots = new Tree(treeAddonsRoots_rootNode);
	treeAddonsRoots.setCellRenderer(new MyColoredTreeCellRenderer());
	treeAddonsRoots.setHoldSize(true);
	treeAddonsRoots.addTreeSelectionListener(e -> {
		System.out.println("ArmaAddonsSettingsForm.createUIComponents e=" + e);
	});
}
 
Example 13
BuilderGenerator(final PluginContext pluginContext, final Map<String, BuilderOutline> builderOutlines, final BuilderOutline builderOutline, final BuilderGeneratorSettings settings) {
	this.pluginContext = pluginContext;
	this.settings = settings;
	this.builderOutlines = builderOutlines;
	this.typeOutline = (DefinedTypeOutline)builderOutline.getClassOutline();
	this.definedClass = this.typeOutline.getImplClass();
	this.builderClass = new GenerifiedClass(builderOutline.getDefinedBuilderClass(), BuilderGenerator.PARENT_BUILDER_TYPE_PARAMETER_NAME);
	this.resources = ResourceBundle.getBundle(BuilderGenerator.class.getName());
	this.implement = !this.builderClass.raw.isInterface();
	if (builderOutline.getClassOutline().getSuperClass() == null) {
		final JMethod endMethod = this.builderClass.raw.method(JMod.PUBLIC, this.builderClass.typeParam, this.settings.getEndMethodName());
		if (this.implement) {
			this.parentBuilderField = this.builderClass.raw.field(JMod.PROTECTED | JMod.FINAL, this.builderClass.typeParam, BuilderGenerator.PARENT_BUILDER_PARAM_NAME);
			endMethod.body()._return(JExpr._this().ref(this.parentBuilderField));
			this.storedValueField = this.settings.isCopyAlways() ? null : this.builderClass.raw.field(JMod.PROTECTED | JMod.FINAL, this.definedClass, BuilderGenerator.STORED_VALUE_PARAM_NAME);
		} else {
			this.parentBuilderField = null;
			this.storedValueField = null;
		}
	} else {
		this.parentBuilderField = null;
		this.storedValueField = this.implement ? JExpr.ref(BuilderGenerator.STORED_VALUE_PARAM_NAME) : null;
	}
	if (this.implement) {
		generateCopyConstructor(false);
		if (this.settings.isGeneratingPartialCopy()) {
			generateCopyConstructor(true);
		}
	}
}
 
Example 14
public Bug4257318() {
  passed = false;
  res = ResourceBundle.getBundle("Bug4257318Res", new java.util.Locale("","",""));
}
 
Example 15
/**
 * Generates the Budget Report and returns pdf.
 */
public ActionForward performReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    OrganizationReportSelectionForm organizationReportSelectionForm = (OrganizationReportSelectionForm) form;
    String principalId = GlobalVariables.getUserSession().getPerson().getPrincipalId();

    BudgetConstructionReportMode reportMode = BudgetConstructionReportMode.getBudgetConstructionReportModeByName(organizationReportSelectionForm.getReportMode());
    if (!storeCodeSelections(organizationReportSelectionForm, reportMode, principalId)) {
        return mapping.findForward(KFSConstants.MAPPING_BASIC);
    }
    
    // validate threshold settings if needed
    if (reportMode == BudgetConstructionReportMode.REASON_STATISTICS_REPORT || reportMode == BudgetConstructionReportMode.REASON_SUMMARY_REPORT || reportMode == BudgetConstructionReportMode.SALARY_SUMMARY_REPORT){
        if (!this.validThresholdSettings(organizationReportSelectionForm.getBudgetConstructionReportThresholdSettings())){
            return mapping.findForward(KFSConstants.MAPPING_BASIC);
        }
    }

    // for report exports foward to export action to display formatting screen
    if (reportMode.export) {
        String exportUrl = this.buildReportExportForwardURL(organizationReportSelectionForm, mapping);
        return new ActionForward(exportUrl, true);
    }

    // build report data and populate report objects for rendering
    Collection reportSet = buildReportData(reportMode, organizationReportSelectionForm.getUniversityFiscalYear(), principalId, organizationReportSelectionForm.isReportConsolidation(), organizationReportSelectionForm.getBudgetConstructionReportThresholdSettings());

    // build pdf and stream back
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // output the report or a message if empty
    if (reportSet.isEmpty()) {
        List<String> messageList = new ArrayList<String>();
        messageList.add(BCConstants.Report.MSG_REPORT_NO_DATA);
        SpringContext.getBean(BudgetConstructionReportsServiceHelper.class).generatePdf(messageList, baos);
        WebUtils.saveMimeOutputStreamAsFile(response, ReportGeneration.PDF_MIME_TYPE, baos, reportMode.jasperFileName + ReportGeneration.PDF_FILE_EXTENSION);
    }
    else {
        ResourceBundle resourceBundle = ResourceBundle.getBundle(BCConstants.Report.REPORT_MESSAGES_CLASSPATH, Locale.getDefault());
        Map<String, Object> reportData = new HashMap<String, Object>();
        reportData.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle);

        SpringContext.getBean(ReportGenerationService.class).generateReportToOutputStream(reportData, reportSet, BCConstants.Report.REPORT_TEMPLATE_CLASSPATH + reportMode.jasperFileName, baos);
        WebUtils.saveMimeOutputStreamAsFile(response, ReportGeneration.PDF_MIME_TYPE, baos, reportMode.jasperFileName + ReportGeneration.PDF_FILE_EXTENSION);
    }
    return null;
}
 
Example 16
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Logger anonymous = Logger.getAnonymousLogger();

    final TestHandler handler = new TestHandler();
    final TestFilter filter = new TestFilter();
    final ResourceBundle bundle = ResourceBundle.getBundle(TestBundle.class.getName());
    anonymous.setLevel(Level.FINEST);
    anonymous.addHandler(handler);
    anonymous.setFilter(filter);
    anonymous.setUseParentHandlers(true);
    anonymous.setResourceBundle(bundle);

    if (anonymous.getLevel() != Level.FINEST) {
        throw new RuntimeException("Unexpected level: " + anonymous.getLevel());
    } else {
        System.out.println("Got expected level: " + anonymous.getLevel());
    }
    if (!Arrays.asList(anonymous.getHandlers()).contains(handler)) {
        throw new RuntimeException("Expected handler not found in: "
                + Arrays.asList(anonymous.getHandlers()));
    } else {
        System.out.println("Got expected handler in: " + Arrays.asList(anonymous.getHandlers()));
    }
    if (anonymous.getFilter() != filter) {
        throw new RuntimeException("Unexpected filter: " + anonymous.getFilter());
    } else {
        System.out.println("Got expected filter: " + anonymous.getFilter());
    }
    if (!anonymous.getUseParentHandlers()) {
        throw new RuntimeException("Unexpected flag: " + anonymous.getUseParentHandlers());
    } else {
        System.out.println("Got expected flag: " + anonymous.getUseParentHandlers());
    }
    if (anonymous.getResourceBundle() != bundle) {
        throw new RuntimeException("Unexpected bundle: " + anonymous.getResourceBundle());
    } else {
        System.out.println("Got expected bundle: " + anonymous.getResourceBundle());
    }
    try {
        anonymous.setParent(Logger.getLogger("foo.bar"));
        throw new RuntimeException("Expected SecurityException not raised!");
    } catch (SecurityException x) {
        System.out.println("Got expected exception: " + x);
    }
    if (anonymous.getParent() != Logger.getLogger("")) {
        throw new RuntimeException("Unexpected parent: " + anonymous.getParent());
    } else {
        System.out.println("Got expected parent: " + anonymous.getParent());
    }
}
 
Example 17
protected CommonResourceBundle() {
    // Load the resource bundle of default locale
    bundle = ResourceBundle.getBundle(BASE_NAME);
}
 
Example 18
Source Project: Pixelitor   File: Texts.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static void setCurrentLang(Language lang) {
    currentLang = lang;
    Locale newLocale = new Locale(currentLang.getCode());
    Locale.setDefault(newLocale);
    resources = ResourceBundle.getBundle("texts", newLocale);
}
 
Example 19
Source Project: p4ic4idea   File: PerforceMessages.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Instantiates a new perforce messages.
 * 
 * @param locale
 *            the locale
 */
public PerforceMessages(Locale locale) {
	this.locale = locale;
	this.messages = ResourceBundle.getBundle(MESSAGE_BUNDLE, locale);
}
 
Example 20
/**
 * Maps directly to <code>ResourceBundle.getBundle(baseName, locale,
 * loader)</code>.
 *
 * @param baseName  the base name.
 * @param locale  the locale.
 * @param loader  the class loader.
 *
 * @return The resource bundle.
 */
public static ResourceBundle getBundle(String baseName, Locale locale,
        ClassLoader loader) {
    return ResourceBundle.getBundle(baseName, locale, loader);
}