Java Code Examples for java.util.ResourceBundle

The following are top voted examples for showing how to use java.util.ResourceBundle. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Java-9-Programming-Blueprints   File: CloudNoticeManagerController.java   Source Code and License 6 votes vote down vote up
@Override
public void initialize(URL url, ResourceBundle rb) {
    recips.setAll(dao.getRecipients());
    topics.setAll(sns.getTopics());

    type.setItems(types);
    recipList.setItems(recips);
    topicCombo.setItems(topics);

    recipList.setCellFactory(p -> new ListCell<Recipient>() {
        @Override
        public void updateItem(Recipient recip, boolean empty) {
            super.updateItem(recip, empty);
            if (!empty) {
                setText(String.format("%s - %s", recip.getType(), recip.getAddress()));
            } else {
                setText(null);
            }
        }
    });
    recipList.getSelectionModel().selectedItemProperty().addListener((obs, oldRecipient, newRecipient) -> {
        type.valueProperty().setValue(newRecipient != null ? newRecipient.getType() : "");
        address.setText(newRecipient != null ? newRecipient.getAddress() : "");
    });
}
 
Example 2
Project: openjdk-jdk10   File: BaseLoggerBridgeTest.java   Source Code and License 6 votes vote down vote up
public static LogEvent of(long sequenceNumber,
        boolean isLoggable, String name,
        Level level, ResourceBundle bundle,
        String key, Supplier<String> supplier,
        Throwable thrown, Object... params) {
    LogEvent evt = new LogEvent(sequenceNumber);
    evt.loggerName = name;
    evt.level = level;
    evt.args = params;
    evt.bundle = bundle;
    evt.thrown = thrown;
    evt.supplier = supplier;
    evt.msg = key;
    evt.isLoggable = isLoggable;
    return evt;
}
 
Example 3
Project: Logisim   File: LocaleManager.java   Source Code and License 6 votes vote down vote up
public String get(String key) {
	String ret;
	try {
		ret = locale.getString(key);
	} catch (MissingResourceException e) {
		ResourceBundle backup = dflt_locale;
		if (backup == null) {
			Locale backup_loc = Locale.US;
			backup = ResourceBundle.getBundle(dir_name + "/en/" + file_start, backup_loc);
			dflt_locale = backup;
		}
		try {
			ret = backup.getString(key);
		} catch (MissingResourceException e2) {
			ret = key;
		}
	}
	HashMap<Character, String> repl = LocaleManager.repl;
	if (repl != null)
		ret = replaceAccents(ret, repl);
	return ret;
}
 
Example 4
Project: NotifyTools   File: Messages.java   Source Code and License 6 votes vote down vote up
/**
     * Changes the locale of the messages.
     * 
     * @param locale
     *            Locale the locale to change to.
     */
    static public ResourceBundle setLocale(final Locale locale,
            final String resource) {
//        try {
//            final ClassLoader loader = VM.bootCallerClassLoader();
//            return (ResourceBundle) AccessController
//                    .doPrivileged(new PrivilegedAction<Object>() {
//                        public Object run() {
//                            return ResourceBundle.getBundle(resource, locale,
//                                    loader != null ? loader : ClassLoader.getSystemClassLoader());
//                        }
//                    });
//        } catch (MissingResourceException e) {
//        }
        return null;
    }
 
Example 5
Project: lazycat   File: ResourceBundleELResolver.java   Source Code and License 6 votes vote down vote up
@Override
public Object getValue(ELContext context, Object base, Object property)
		throws NullPointerException, PropertyNotFoundException, ELException {

	if (context == null) {
		throw new NullPointerException();
	}

	if (base instanceof ResourceBundle) {
		context.setPropertyResolved(true);

		if (property != null) {
			try {
				return ((ResourceBundle) base).getObject(property.toString());
			} catch (MissingResourceException mre) {
				return "???" + property.toString() + "???";
			}
		}
	}

	return null;
}
 
Example 6
Project: openjdk-jdk10   File: LocaleResources.java   Source Code and License 6 votes vote down vote up
int getCalendarData(String key) {
    Integer caldata;
    String cacheKey = CALENDAR_DATA  + key;

    removeEmptyReferences();

    ResourceReference data = cache.get(cacheKey);
    if (data == null || ((caldata = (Integer) data.get()) == null)) {
        ResourceBundle rb = localeData.getCalendarData(locale);
        if (rb.containsKey(key)) {
            caldata = Integer.parseInt(rb.getString(key));
        } else {
            caldata = 0;
        }

        cache.put(cacheKey,
                  new ResourceReference(cacheKey, (Object) caldata, referenceQueue));
    }

    return caldata;
}
 
Example 7
Project: validator-web   File: PlatformResourceBundleLocator.java   Source Code and License 6 votes vote down vote up
/**
 * Search current thread classloader for the resource bundle. If not found,
 * search validator (this) classloader.
 *
 * @param locale The locale of the bundle to load.
 * @return the resource bundle or <code>null</code> if none is found.
 */
@Override
public ResourceBundle getResourceBundle(Locale locale) {
    ResourceBundle rb = null;
    ClassLoader classLoader = GetClassLoader.fromContext();
    if (classLoader != null) {
        rb = loadBundle(
                classLoader, locale, bundleName
                        + " not found by thread local classloader"
        );
    }
    if (rb == null) {
        classLoader = GetClassLoader.fromClass(PlatformResourceBundleLocator.class);
        rb = loadBundle(
                classLoader, locale, bundleName
                        + " not found by validator classloader"
        );
    }
    if (rb != null) {
        log.debug(bundleName + " found.");
    } else {
        log.debug(bundleName + " not found.");
    }
    return rb;
}
 
Example 8
Project: vars-annotation   File: Initializer.java   Source Code and License 6 votes vote down vote up
public static UIToolBox getToolBox() {
    if (toolBox == null) {
        Services services = getInjector().getInstance(Services.class);
        ResourceBundle bundle = ResourceBundle.getBundle("i18n",
                Locale.getDefault());

        // We're using less!! Load it using our custom loader
        LessCSSLoader lessLoader = new LessCSSLoader();
        String stylesheet = lessLoader.loadLess(Initializer.class.getResource("/less/annotation.less"))
                .toExternalForm();
        toolBox = new UIToolBox(new Data(),
                services,
                new EventBus(),
                bundle,
                getConfig(),
                Arrays.asList(stylesheet));
    }
    return toolBox;
}
 
Example 9
Project: code-tracker   File: MainController.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void initialize(URL location, ResourceBundle resources) {
    // Initializes test base, tester and test map to access and modify the algorithm base
    testBase = TestBase.INSTANCE;   // Gets a reference to the test base
    tester = new Tester();          //
    testMap = tester.getTestMap();

    // Binds the list view with a list of algorithms (list items)
    listItems = FXCollections.observableList(new ArrayList<>(testMap.keySet()));
    list.itemsProperty().bindBidirectional(new SimpleListProperty<>(listItems));
    list.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
    list.getSelectionModel().selectedItemProperty().addListener((((observable, oldValue, newValue) -> {
        if(newValue != null) {
            textArea.setText(testMap.get(newValue).getContent());
        } else {
            textArea.clear();
        }
    })));
    list.getSelectionModel().select(0);

    // Initializes the trie that stores all algorithm names
    algorithmNameTrie = new Trie();
    for(String algorithmName : testMap.keySet()) {
        algorithmNameTrie.addWord(algorithmName);
    }

    // Binds search field with the list view (displays search result)
    searchField.textProperty().addListener((observable, oldValue, newValue) -> {
        listItems.setAll(algorithmNameTrie.getWords(newValue.toLowerCase()));
        if(!listItems.isEmpty()) {
            list.getSelectionModel().select(0);
        }
    });

    // For unknown reasons, this style does not work on css, so I put it in here
    textArea.setStyle("-fx-focus-color: transparent; -fx-text-box-border: transparent;");
    textArea.setFocusTraversable(false);
}
 
Example 10
Project: openjdk-jdk10   File: MessageCatalog.java   Source Code and License 6 votes vote down vote up
/**
 * Get a message localized to the specified locale, using the message ID
 * and package name if no message is available.  The locale is normally
 * that of the client of a service, chosen with knowledge that both the
 * client and this server support that locale.  There are two error
 * cases:  first, when the specified locale is unsupported or null, the
 * default locale is used if possible; second, when no bundle supports
 * that locale, the message ID and package name are used.
 *
 * @param locale    The locale of the message to use.  If this is null,
 *                  the default locale will be used.
 * @param messageId The ID of the message to use.
 * @return The message, localized as described above.
 */
public String getMessage(Locale locale,
                         String messageId) {
    ResourceBundle bundle;

    // cope with unsupported locale...
    if (locale == null)
        locale = Locale.getDefault();

    try {
        bundle = ResourceBundle.getBundle(bundleName, locale);
    } catch (MissingResourceException e) {
        bundle = ResourceBundle.getBundle(bundleName, Locale.ENGLISH);
    }
    return bundle.getString(messageId);
}
 
Example 11
Project: ChatRoom-JavaFX   File: ChatController.java   Source Code and License 6 votes vote down vote up
@Override
public void initialize(URL location, ResourceBundle resources) {
	// TODO Auto-generated method stub
	/* Drag and Drop */
       borderPane.setOnMousePressed(event -> {
           xOffset = getLocalStage().getX() - event.getScreenX();
           yOffset = getLocalStage().getY() - event.getScreenY();
           borderPane.setCursor(Cursor.CLOSED_HAND);
       });
       borderPane.setOnMouseDragged(event -> {
       	getLocalStage().setX(event.getScreenX() + xOffset);
       	getLocalStage().setY(event.getScreenY() + yOffset);
       });
       borderPane.setOnMouseReleased(event -> {
           borderPane.setCursor(Cursor.DEFAULT);
       });
       //设置图标
       setIcon("images/icon_chatroom.png");
}
 
Example 12
Project: openjdk-jdk10   File: BootstrapLogger.java   Source Code and License 6 votes vote down vote up
private LogEvent(BootstrapLogger bootstrap,
        PlatformLogger.Level platformLevel,
        String sourceClass, String sourceMethod,
        ResourceBundle bundle, String msg,
        Throwable thrown, Object[] params) {
    this.acc = AccessController.getContext();
    this.timeMillis = System.currentTimeMillis();
    this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis);
    this.level = null;
    this.platformLevel = platformLevel;
    this.bundle = bundle;
    this.msg = msg;
    this.msgSupplier = null;
    this.thrown = thrown;
    this.params = params;
    this.sourceClass = sourceClass;
    this.sourceMethod = sourceMethod;
    this.bootstrap = bootstrap;
}
 
Example 13
Project: AWGW   File: Unit.java   Source Code and License 6 votes vote down vote up
/**
 * loads the daily fuel cost for this unit from a resourcebundle
 * for use in constructor for setDailyCost()
 *
 * @return maximum mobility value for the unit
 */
private int loadDailyCost() {
    if (this instanceof HiddenUnit) {
        HiddenUnit me = (HiddenUnit) this;
        Unit cont = (me).getContainedUnit();
        return (cont.loadDailyCost());
    }
    ResourceBundle b = ResourceBundle.getBundle("unit_daily_fuel");
    try {
        double ans = Double.parseDouble(b.getString(getType()));
        return (int) (this.owner.CO.passive(ans, COFlag.DAILY_COST, getUnitType()));
    } catch (NumberFormatException e) {
        System.out.println(e.getStackTrace());
        System.out.println("Method: Unit.loadDailyCost()");
        throw new RuntimeException("Corrupt File");
    }
}
 
Example 14
Project: NetCompile   File: TestSceneController.java   Source Code and License 6 votes vote down vote up
@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
    test.setVisible(false);
    date.setVisible(false);
    time.setVisible(false);
    code_output.setVisible(false);
    btnRun.setVisible(false);
    time.setText("test time");
    problem_tabs.setVisible(false);
    
    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("MMM d, ''yy");
    String sd=sdf.format(d);
    date.setText(sd);
    //startTimer();
    //problemView.getEngine().loadContent("<h1>HELLO WORLD<h1>");
}
 
Example 15
Project: oscm   File: RichLazyDataModel.java   Source Code and License 6 votes vote down vote up
protected void applyFilters(List<FilterField> filterFields,
        Pagination pagination) {
    Set<Filter> filters = new HashSet<>();
    FacesContext facesContext = FacesContext.getCurrentInstance();
    for (FilterField filterField : filterFields) {
        String propertyName = (String) filterField.getFilterExpression()
                .getValue(facesContext.getELContext());
        Object filterValue = filterField.getFilterValue();

        if (filterValue == null || filterValue.equals("")) {
            continue;
        }
        Filter filter = new Filter(columnNamesMapping.get(propertyName),
                filterValue.toString());
        filters.add(filter);
    }
    ResourceBundle bundle = facesContext.getApplication()
            .getResourceBundle(facesContext, Constants.BUNDLE_NAME);
    pagination.setDateFormat(bundle
            .getString(ApplicationBean.DatePatternEnum.DATE_INPUT_PATTERN
                    .getMessageKey()));
    pagination.setFilterSet(filters);
}
 
Example 16
Project: apache-tomcat-7.0.73-with-comment   File: Util.java   Source Code and License 6 votes vote down vote up
static String message(ELContext context, String name, Object... props) {
    Locale locale = null;
    if (context != null) {
        locale = context.getLocale();
    }
    if (locale == null) {
        locale = Locale.getDefault();
        if (locale == null) {
            return "";
        }
    }
    ResourceBundle bundle = ResourceBundle.getBundle(
            "javax.el.LocalStrings", locale);
    try {
        String template = bundle.getString(name);
        if (props != null) {
            template = MessageFormat.format(template, props);
        }
        return template;
    } catch (MissingResourceException e) {
        return "Missing Resource: '" + name + "' for Locale "
                + locale.getDisplayName();
    }
}
 
Example 17
Project: logistimo-web-service   File: InvntryWithBatchInfoExportHandler.java   Source Code and License 6 votes vote down vote up
private String getMCRUnits(Locale locale) {
  ResourceBundle messages = Resources.get().getBundle("Messages", locale);
  ResourceBundle jsMessages = Resources.get().getBundle("JSMessages", locale);
  Long domainId = invntryWithBatchInfo.getDomainId();
  DomainConfig dc = DomainConfig.getInstance(domainId);
  InventoryConfig ic = dc.getInventoryConfig();

  boolean allowManualConsumptionRates = (ic != null && ic.getManualCRFreq() != null);
  String
      manualCrUnits =
      (allowManualConsumptionRates ? InventoryConfig
          .getFrequencyDisplay(ic.getManualCRFreq(), false, locale) : null);
  if (manualCrUnits == null || manualCrUnits.isEmpty() || manualCrUnits
      .equalsIgnoreCase(messages.getString("days"))) {
    manualCrUnits =
        jsMessages.getString("daysofstock"); // Default the manual consumption rate units to Days.
  } else if (manualCrUnits.equalsIgnoreCase(messages.getString("weeks"))) {
    manualCrUnits = jsMessages.getString("weeksofstock");
  } else if (manualCrUnits.equalsIgnoreCase(messages.getString("months"))) {
    manualCrUnits = jsMessages.getString("monthsofstock");
  }
  return manualCrUnits;
}
 
Example 18
Project: openjdk-jdk10   File: LoggerFinderLoaderTest.java   Source Code and License 6 votes vote down vote up
public static void test(LoggerFinder provider, boolean hasRequiredPermissions) {

        ResourceBundle loggerBundle = ResourceBundle.getBundle(MyLoggerBundle.class.getName());
        final Map<Logger, String> loggerDescMap = new HashMap<>();

        System.Logger sysLogger = accessSystemLogger.getLogger("foo");
        loggerDescMap.put(sysLogger, "accessSystemLogger.getLogger(\"foo\")");
        System.Logger localizedSysLogger = accessSystemLogger.getLogger("fox", loggerBundle);
        loggerDescMap.put(localizedSysLogger, "accessSystemLogger.getLogger(\"fox\", loggerBundle)");
        System.Logger appLogger = System.getLogger("bar");
        loggerDescMap.put(appLogger,"System.getLogger(\"bar\")");
        System.Logger localizedAppLogger = System.getLogger("baz", loggerBundle);
        loggerDescMap.put(localizedAppLogger,"System.getLogger(\"baz\", loggerBundle)");

        testLogger(provider, loggerDescMap, "foo", null, sysLogger);
        testLogger(provider, loggerDescMap, "foo", loggerBundle, localizedSysLogger);
        testLogger(provider, loggerDescMap, "foo", null, appLogger);
        testLogger(provider, loggerDescMap, "foo", loggerBundle, localizedAppLogger);
    }
 
Example 19
Project: Clipcon-Client   File: SettingScene.java   Source Code and License 6 votes vote down vote up
@Override
public void initialize(URL location, ResourceBundle resources) {
	if(clipboardMonitorNotiFlag)
		clipboardMonitorNotiCB.setSelected(false);
	else
		clipboardMonitorNotiCB.setSelected(true);
	
	if(uploadNotiFlag)
		uploadNotiCB.setSelected(false);
	else
		uploadNotiCB.setSelected(true);
	
	// X button event handling
	XBtn.setOnAction(new EventHandler<ActionEvent>() {
		@Override
		public void handle(ActionEvent event) {
			ui.getMainScene().closeSettingStage();
		}
	});
	
}
 
Example 20
Project: logistimo-web-service   File: DashboardController.java   Source Code and License 6 votes vote down vote up
@RequestMapping(value = "/", method = RequestMethod.POST)
public
@ResponseBody
String create(@RequestBody DashboardModel model, HttpServletRequest request) {
  SecureUserDetails sUser = SecurityUtils.getUserDetails(request);
  Locale locale = sUser.getLocale();
  ResourceBundle backendMessages = Resources.get().getBundle("BackendMessages", locale);
  long domainId = SessionMgr.getCurrentDomain(request.getSession(), sUser.getUsername());
  try {
    IDashboard db = builder.buildDashboard(model, domainId, sUser.getUsername());
    IDashboardService ds = Services.getService(DashboardService.class);
    ds.createDashboard(db);
  } catch (ServiceException e) {
    xLogger.severe("Error creating Dashboard for domain ", domainId);
    throw new InvalidServiceException("Error creating Dashboard for " + domainId);
  }
  return "Dashboard " + MsgUtil.bold(model.nm) + " " + backendMessages
      .getString("created.success");
}
 
Example 21
Project: tomcat7   File: TestResourceBundleELResolver.java   Source Code and License 6 votes vote down vote up
/**
 * Tests that a valid property is resolved.
 */
@Test
public void testGetValue03() {
    ResourceBundleELResolver resolver = new ResourceBundleELResolver();
    ELContext context = new ELContextImpl();

    ResourceBundle resourceBundle = new TesterResourceBundle();
    Object result = resolver.getValue(context, resourceBundle, "key1");

    Assert.assertEquals("value1", result);
    Assert.assertTrue(context.isPropertyResolved());

    result = resolver.getValue(context, resourceBundle, "unknown-key");

    Assert.assertEquals("???unknown-key???", result);
    Assert.assertTrue(context.isPropertyResolved());

    result = resolver.getValue(context, resourceBundle, null);

    Assert.assertNull(result);
    Assert.assertTrue(context.isPropertyResolved());
}
 
Example 22
Project: gchisto   File: GCParserDriver.java   Source Code and License 5 votes vote down vote up
public void describe_metrics(PrintStream s)
{
	ResourceBundle b = ResourceBundle.getBundle("GCMetricHelp");

	if (b.containsKey("intro")) s.println(b.getString("intro"));
	for (GCMetric metric:  GCMetric.values())
	{
		String name = metric.name();
		s.println(name + '\t' + b.getString(name));
	}
	if (b.containsKey("closing")) s.println(b.getString("closing"));
}
 
Example 23
Project: jdk8u-jdk   File: TestSetResourceBundle.java   Source Code and License 5 votes vote down vote up
/**
 * Test the LoggingPermission("control") is required.
 * @param loggerName The logger to use.
 */
public static void testPermission(String loggerName) {
    if (System.getSecurityManager() != null) {
        throw new Error("Security manager is already set");
    }
    Policy.setPolicy(new SimplePolicy(TestCase.PERMISSION));
    System.setSecurityManager(new SecurityManager());
    final ResourceBundle bundle = ResourceBundle.getBundle(LIST_BUNDLE_NAME);
    Logger foobar = Logger.getLogger(loggerName);
    try {
        foobar.setResourceBundle(bundle);
        throw new RuntimeException("Permission not checked!");
    } catch (AccessControlException x) {
        if (x.getPermission() instanceof LoggingPermission) {
            if ("control".equals(x.getPermission().getName())) {
                System.out.println("Got expected exception: " + x);
                return;
            }
        }
        throw new RuntimeException("Unexpected exception: "+x, x);
    }

}
 
Example 24
Project: logistimo-web-service   File: DomainConfigController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/customreports", method = RequestMethod.POST)
public
@ResponseBody
CustomReportsConfig.Config getConfig(@RequestParam String templateName, @RequestParam String edit,
                                     @RequestParam String templateKey,
                                     HttpServletRequest request) {
  SecureUserDetails sUser = getUserDetails();
  Locale locale = sUser.getLocale();
  ResourceBundle backendMessages = Resources.get().getBundle("BackendMessages", locale);
  Long domainId = SecurityUtils.getCurrentDomainId();
  if (StringUtils.isEmpty(templateName)) {
    xLogger.severe("Error in fetching configuration");
    throw new BadRequestException(backendMessages.getString("config.fetch.error"));
  }
  try {
    if (edit.equalsIgnoreCase("true")) {
      crBuilder.removeUploadedObject(templateKey);
    }
    IUploaded
        uploaded =
        crBuilder.updateUploadedObject(request, sUser, domainId,
            AppFactory.get().getBlobstoreService(), templateName);
    CustomReportsConfig.Config config = new CustomReportsConfig.Config();
    if (uploaded != null) {
      config.fileName = uploaded.getFileName();
      config.templateKey = uploaded.getId();
    }
    return config;
  } catch (ServiceException e) {
    xLogger.severe("Error in fetching configuration", e);
    throw new InvalidServiceException(backendMessages.getString("config.fetch.error"));
  }
}
 
Example 25
Project: openrouteservice   File: JSONObject.java   Source Code and License 5 votes vote down vote up
/**
     * Construct a JSONObject from a ResourceBundle.
     *
     * @param baseName
     *            The ResourceBundle base name.
     * @param locale
     *            The Locale to load the ResourceBundle for.
     * @throws JSONException
     *             If any JSONExceptions are detected.
     */
    public JSONObject(String baseName, Locale locale) throws JSONException {
        this();
        ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
                Thread.currentThread().getContextClassLoader());

// Iterate through the keys in the bundle.

        Enumeration<String> keys = bundle.getKeys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            if (key != null) {

// Go through the path, ensuring that there is a nested JSONObject for each
// segment except the last. Add the value using the last segment's name into
// the deepest nested JSONObject.

                String[] path = ((String) key).split("\\.");
                int last = path.length - 1;
                JSONObject target = this;
                for (int i = 0; i < last; i += 1) {
                    String segment = path[i];
                    JSONObject nextTarget = target.optJSONObject(segment);
                    if (nextTarget == null) {
                        nextTarget = new JSONObject();
                        target.put(segment, nextTarget);
                    }
                    target = nextTarget;
                }
                target.put(path[last], bundle.getString((String) key));
            }
        }
    }
 
Example 26
Project: logistimo-web-service   File: HandlingUnitController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/update", method = RequestMethod.POST)
public
@ResponseBody
String updateHandlingUnit(@RequestBody HUModel huModel, HttpServletRequest request) {
  SecureUserDetails sUser = SecurityUtils.getUserDetails(request);
  Locale locale = sUser.getLocale();
  ResourceBundle backendMessages = Resources.get().getBundle("BackendMessages", locale);
  if (!GenericAuthoriser.authoriseAdmin(request)) {
    throw new UnauthorizedException(backendMessages.getString("permission.denied"));
  }
  IHandlingUnit hu = builder.buildHandlingUnit(huModel);
  hu.setUpdatedBy(sUser.getUsername());
  Long domainId = SessionMgr.getCurrentDomain(request.getSession(), sUser.getUsername());
  try {
    HandlingUnitServiceImpl
        handlingUnitService =
        Services.getService(HandlingUnitServiceImpl.class, locale);
    if (hu.getName() != null) {
      handlingUnitService.updateHandlingUnit(hu, domainId);
      xLogger.info("AUDITLOG\t{0}\t{1}\tHANDLING UNIT\t UPDATE\t{2}\t{3}", domainId,
          sUser.getUsername(), hu.getId(), hu.getName());
    } else {
      throw new InvalidDataException("No handling unit name");
    }
  } catch (Exception e) {
    xLogger.warn("Error updating handling unit {0}", hu.getId(), e);
    throw new InvalidServiceException(
        "Error updating handling unit " + MsgUtil.bold(hu.getName()) +
            MsgUtil.addErrorMsg(e.getMessage()));
  }
  return "Handling unit " + MsgUtil.bold(huModel.name) + " " + backendMessages
      .getString("updated.successfully.lowercase");
}
 
Example 27
Project: TreasureHunting   File: QaController.java   Source Code and License 5 votes vote down vote up
public String update() {
    try {
        getFacade().edit(current);
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("QaUpdated"));
        return "View";
    } catch (Exception e) {
        JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        return null;
    }
}
 
Example 28
Project: openjdk-jdk10   File: BasicTest.java   Source Code and License 5 votes vote down vote up
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 29
Project: FEFEditor   File: Dispo.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize(URL url, ResourceBundle rb) {
    GuiData.getInstance().getStage().setOnCloseRequest(we -> close());
    file = new FatesDispo(FileData.getInstance().getWorkingFile());
    setupDispoGrid();
    populateTree();

    factionTree.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) ->
            updateSelection(newValue));
    dispoScrollPane.widthProperty().addListener((observable, oldValue, newValue) ->
            dispoPane.setPrefWidth(newValue.doubleValue()));
    dispoScrollPane.heightProperty().addListener((observable, oldValue, newValue) ->
            dispoPane.setPrefHeight(newValue.doubleValue()));
    populateForm();
}
 
Example 30
Project: logistimo-web-service   File: TransactionUtil.java   Source Code and License 5 votes vote down vote up
public static String getDisplayName(String transType, String transNaming, Locale locale) {
  String name = "";
  // Get the resource bundle
  ResourceBundle messages = Resources.get().getBundle("Messages", locale);
  if (messages == null) {
    return "";
  }
  if (ITransaction.TYPE_ISSUE.equals(transType)) {
    name =
        DomainConfig.TRANSNAMING_ISSUESRECEIPTS.equals(transNaming) ? messages
            .getString("transactions.issue") : messages.getString("transactions.sale");
  } else if (ITransaction.TYPE_RECEIPT.equals(transType)) {
    name =
        DomainConfig.TRANSNAMING_ISSUESRECEIPTS.equals(transNaming) ? messages
            .getString("transactions.receipt") : messages.getString("transactions.purchase");
  } else if (ITransaction.TYPE_PHYSICALCOUNT.equals(transType)) {
    name = messages.getString("transactions.stockcount");
  } else if (ITransaction.TYPE_ORDER.equals(transType)) {
    name = messages.getString("transactions.order");
  } else if (ITransaction.TYPE_REORDER.equals(transType)) {
    name = messages.getString("transactions.reorder");
  } else if (ITransaction.TYPE_WASTAGE.equals(transType)) {
    name = messages.getString("transactions.wastage");
  } else if (ITransaction.TYPE_RETURN.equals(transType)) {
    name = messages.getString("transactions.return");
  } else if (ITransaction.TYPE_TRANSFER.equals(transType)) {
    name = messages.getString("transactions.transfer");
  }
  return name;
}
 
Example 31
Project: logistimo-web-service   File: UsersController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/", method = RequestMethod.POST)
public
@ResponseBody
String create(@RequestBody UserModel userModel, HttpServletRequest request) {
  SecureUserDetails sUser = SecurityUtils.getUserDetails(request);
  Locale locale = sUser.getLocale();
  ResourceBundle backendMessages = Resources.get().getBundle("BackendMessages", locale);
  IUserAccount ua = builder.buildUserAccount(userModel);
  ua.setRegisteredBy(sUser.getUsername());
  ua.setUpdatedBy(sUser.getUsername());
  try {
    UsersService as = Services.getService(UsersServiceImpl.class, locale);
    if (ua.getUserId() != null) {
      long domainId = SecurityUtils.getCurrentDomainId();
      ua = as.addAccount(domainId, ua);
      xLogger.info("AUDITLOG \t {0} \t {1} \t USER \t " +
              "CREATE \t {2} \t {3}", domainId, sUser.getUsername(), ua.getUserId(),
          ua.getFullName());
    } else {
      throw new InvalidDataException(backendMessages.getString("user.id.none"));
    }
  } catch (ServiceException e) {
    xLogger.warn("Error creating User for " + ua.getDomainId(), e);
    throw new InvalidServiceException(
        backendMessages.getString("user.create.error") + " " + ua.getDomainId());
  }
  return backendMessages.getString("user.uppercase") + " " + MsgUtil.bold(ua.getFullName()) + " "
      + backendMessages.getString("created.success");
}
 
Example 32
Project: openjdk-jdk10   File: DefaultLoggerTest.java   Source Code and License 5 votes vote down vote up
@Override
public void log(Level level, ResourceBundle rb, String string, Throwable thrwbl) {
    try {
        invoke(System.Logger.class.getMethod(
                "log", Level.class, ResourceBundle.class, String.class, Throwable.class),
                level, rb, string, thrwbl);
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 33
Project: logistimo-web-service   File: UsersController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/userstate/", method = RequestMethod.GET)
public
@ResponseBody
String enableDisableUser(@RequestParam String userId, @RequestParam String action,
                         HttpServletRequest request) {
  SecureUserDetails sUser = SecurityUtils.getUserDetails(request);
  Long domainId = SessionMgr.getCurrentDomain(request.getSession(), sUser.getUsername());
  Locale locale = sUser.getLocale();
  ResourceBundle backendMessages = Resources.get().getBundle("BackendMessages", locale);
  try {
    UsersService as = Services.getService(UsersServiceImpl.class, locale);
    AuthenticationService aus = Services.getService(AuthenticationServiceImpl.class);
    IUserAccount ua = as.getUserAccount(userId);
    if (GenericAuthoriser.authoriseUser(request, userId)) {
      if ("e".equals(action)) {
        as.enableAccount(userId);
        xLogger.info("AUDITLOG \t {0} \t {1} \t USER \t " +
            "ENABLE \t {2} \t {3}", domainId, sUser.getUsername(), userId, ua.getFullName());
        return backendMessages.getString("user.account.enabled") + " " + MsgUtil.bold(userId);
      } else {
        as.disableAccount(userId);
        aus.updateUserSession(userId, null);
        xLogger.info("AUDITLOG \t {0} \t {1} \t USER \t " +
            "DISABLE \t {2} \t {3}", domainId, sUser.getUsername(), userId, ua.getFullName());
        return backendMessages.getString("user.account.disabled") + " " + MsgUtil.bold(userId);
      }
    } else {
      throw new UnauthorizedException(backendMessages.getString("permission.denied"));
    }
  } catch (ServiceException | ObjectNotFoundException se) {
    xLogger.warn("Error Updating User password for " + userId, se);
    throw new InvalidServiceException(
        backendMessages.getString("user.password.update.error") + " " + userId);
  }
}
 
Example 34
Project: logistimo-web-service   File: ExportServlet.java   Source Code and License 5 votes vote down vote up
@Override
protected void processGet(HttpServletRequest request, HttpServletResponse response,
                          ResourceBundle backendMessages, ResourceBundle messages)
    throws ServletException, IOException, ServiceException {
  xLogger.fine("Entered doGet");
  String action = request.getParameter("action");
  if (action == null || action.isEmpty()) {
    String type = request.getParameter("type");
    if (BulkExportMgr.TYPE_ORDERS.equals(type)) {
      exportOrders(request, response);
    } else {
      xLogger.warn("Unknown type: {0}", type);
    }
  } else if (ACTION_DOWNLOAD.equals(action)) {
    serveFile(request, response);
  } else if (ACTION_SCHEDULEBATCHEXPORT.equals(action)) {
    scheduleBatchExport(request, response, backendMessages, messages);
  } else if (ACTION_BATCHEXPORT.equals(action)) {
    batchExport(request, response, backendMessages, messages);
  } else if (ACTION_BULKUPLOADFORMATEXPORT.equals(action)) {
    exportBulkUploadFormat(request, response, messages);
  } else if (ACTION_SCHEDULEREPORTEXPORT.equals(action)) {
    scheduleReportExport(request, response, backendMessages, messages);
  } else if (ACTION_FINALIZEEXPORT.equals(action)) {
    finalizeExport(request, response, backendMessages, messages);
  } else {
    xLogger.severe("Unknown action: " + action);
  }
  xLogger.fine("Exiting doGet");
}
 
Example 35
Project: javaide   File: KeyStoreTest.java   Source Code and License 5 votes vote down vote up
public void testReadResource() {
    ResourceBundle resourceBundle = ResourceBundle.getBundle("sun.security.util.Resources");
    Enumeration<String> keys = resourceBundle.getKeys();
    while (keys.hasMoreElements()) {
        String s = keys.nextElement();
        System.out.println(s + " - " + resourceBundle.getString(s));
    }
}
 
Example 36
Project: powertext   File: AutoCompleteDescWindow.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the localized message for the specified key.
 *
 * @param key The key.
 * @return The localized message.
 */
private String getString(String key) {
	if (bundle==null) {
		bundle = ResourceBundle.getBundle(MSG);
	}
	return bundle.getString(key);
}
 
Example 37
Project: openjdk-jdk10   File: MyResourcesEU.java   Source Code and License 5 votes vote down vote up
@Override
public ResourceBundle getBundle(String baseName, Locale locale) {
    if (euLocales.contains(locale)) {
        return super.getBundle(baseName, locale);
    }
    return null;
}
 
Example 38
Project: ABC-List   File: ExercisePresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize(URL location, ResourceBundle resources) {
    LoggerFacade.getDefault().info(this.getClass(), "Initialize ExercisePresenter"); // NOI18N
    
    this.initializeBindings();
    this.initializeComboBoxTimeChooser();
    this.initializeExerciseTimer();
    this.initializeFlowPaneTerms();
    this.initializeTextFieldUserInput();
    
    this.onActionPrepareExerciseFor(EState.PREPARE_STATE_FOR__INITIALIZE);
}
 
Example 39
Project: logistimo-web-service   File: DashboardServlet.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void getMonthlyUsageStatsForDomain(HttpServletRequest request,
                                                  HttpServletResponse response,
                                                  ResourceBundle backendMessages,
                                                  ResourceBundle messages) throws IOException {
  xLogger.fine("Entered getMonthlyUsageStatsForDomain");
  // Get the domain ID
  String domainIdStr = request.getParameter("domainid");
  String offsetStr = request.getParameter("offset");
  String sizeStr = request.getParameter("size");
  String startDateStr = request.getParameter("startdate");
  if (sizeStr == null || sizeStr.isEmpty() || startDateStr == null || startDateStr.isEmpty()
      || domainIdStr == null || domainIdStr.isEmpty()) {
    xLogger.severe(
        "One or more manadatory parameters or null or empty. offsetStr: {0}, sizeStr: {1}, startDateStr: {2}, domainIdStr: {3}",
        offsetStr, sizeStr, startDateStr, domainIdStr);
    response.setStatus(500);
    return;
  }
  Long domainId = null;
  Date startDate = null;
  int offset = 0;
  try {
    domainId = Long.parseLong(domainIdStr);
    SimpleDateFormat df = new SimpleDateFormat(Constants.DATE_FORMAT);
    startDate = df.parse(startDateStr);
    int size = Integer.parseInt(sizeStr);
    if (offsetStr != null) {
      offset = Integer.parseInt(offsetStr);
    }

    // Proceed only if the mandatory attributes are present.
    ReportsService rs = Services.getService("reports");
    PageParams pageParams = new PageParams(null, offset, size);
    Results results = rs.getMonthlyUsageStatsForDomain(domainId, startDate, pageParams);
    List<IMonthSlice> resultsList = results.getResults();
    if (resultsList != null && !resultsList.isEmpty()) {
      // From the List<MonthSlice> get UsageStats object
      UsageStats usageStats = new UsageStats(results);
      xLogger.info("usageStats: " + usageStats.toJSONString());
      // Convert the usageStats object to JSON and return it.
      writeText(response, usageStats.toJSONString());
    } else {
      xLogger.info("No results: {0}", resultsList);
      writeText(response, "{\"msg\": \"No results\" }");
    }
  } catch (Exception e) {
    xLogger.severe("{0} when trying to get monthly usage stats for domain {1}. Message: {2}",
        e.getClass().getName(), domainId, e.getMessage());
    response.setStatus(500);
  }
  xLogger.fine("Exiting getMonthlyUsageStatsForDomain");
}
 
Example 40
Project: logistimo-web-service   File: DiscrepancyBuilder.java   Source Code and License 5 votes vote down vote up
private String getFdRsnsDisplay(List<String> fdRsns, Locale locale) {
  ResourceBundle jsMessages = Resources.get().getBundle("JSMessages", locale);
  if (jsMessages == null) {
    return "unknown";
  }
  if (fdRsns == null || fdRsns.isEmpty()) {
    return null;
  }
  boolean isBatch = fdRsns.get(0).substring(fdRsns.get(0).indexOf("||") + 2).contains("||");
  StringBuilder fdRsnsStr = new StringBuilder();
  fdRsnsStr.append("<table><tr>")
      .append("<th>").append(jsMessages.getString("shipment")).append("</th>");
  if (isBatch) {
    fdRsnsStr.append("<th>").append("Batch").append("</th>");
  }
  fdRsnsStr.append("<th>").append(jsMessages.getString("reasons")).append("</th></tr>");
  for (String fdRsn : fdRsns) {
    int index = fdRsn.indexOf("||");
    String sid = fdRsn.substring(0, index);
    String bid = null;
    if (isBatch) {
      int lastIndex = fdRsn.lastIndexOf("||");
      bid = fdRsn.substring(index + 2, lastIndex);
      index = lastIndex;
    }
    String rsn = fdRsn.substring(index + 2);
    fdRsnsStr.append("<tr><td><p align=\"left\">").append(sid).append("</p></td>");
    if (isBatch) {
      fdRsnsStr.append("<td><p align=\"left\" class=\"pr5\">").append(bid).append("</p></td>");
    }
    fdRsnsStr.append("<td><p align=\"left\">").append(rsn).append("</p></td></tr>");
  }
  fdRsnsStr.append("</table>");
  return fdRsnsStr.toString();
}
 
Example 41
Project: jdk8u-jdk   File: OpenListResourceBundle.java   Source Code and License 5 votes vote down vote up
/**
 * Implementation of ResourceBundle.getKeys.
 */
@Override
public Enumeration<String> getKeys() {
    ResourceBundle parentBundle = this.parent;
    return new ResourceBundleEnumeration(handleKeySet(),
            (parentBundle != null) ? parentBundle.getKeys() : null);
 }
 
Example 42
Project: ABC-List   File: TestdataTermPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize(URL location, ResourceBundle resources) {
    LoggerFacade.getDefault().info(this.getClass(), "Initialize TestdataTermPresenter"); // NOI18N
    
    assert (cbQuantityEntities != null)             : "fx:id=\"cbQuantityEntities\" was not injected: check your FXML file 'testdataterm.fxml'."; // NOI18N
    assert (cbQuantityTimePeriod != null)           : "fx:id=\"cbQuantityTimePeriod\" was not injected: check your FXML file 'testdataterm.fxml'."; // NOI18N
    assert (lProgressBarInformation != null)        : "fx:id=\"lProgressBarInformation\" was not injected: check your FXML file 'testdataterm.fxml'."; // NOI18N
    assert (lProgressBarPercentInformation != null) : "fx:id=\"lProgressBarPercentInformation\" was not injected: check your FXML file 'testdataterm.fxml'."; // NOI18N
    assert (pbEntity != null)                       : "fx:id=\"pbEntity\" was not injected: check your FXML file 'testdataterm.fxml'."; // NOI18N

    this.initializeComboBoxes();
}
 
Example 43
Project: BecomeJavaHero   File: App3.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	ResourceBundle rb = ResourceBundle.getBundle("pl.edu.bogdan.training.properties.Example3");
	System.out.println(rb.getString("key1"));
	
	rb = ResourceBundle.getBundle("pl.edu.bogdan.training.properties.Example3", Locale.US);
	System.out.println(rb.getString("key1"));
}
 
Example 44
Project: openjdk-jdk10   File: GenerateKeyList.java   Source Code and License 5 votes vote down vote up
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 45
Project: goobi-viewer-connector   File: MessageResourceBundle.java   Source Code and License 5 votes vote down vote up
public static synchronized void loadResourceBundle(Locale inLocale) {
    Locale locale;
    if (inLocale != null) {
        locale = inLocale;
    } else {
        locale = Locale.ENGLISH;
    }
    if (bundle == null || !bundle.getLocale().equals(locale)) {
        bundle = ResourceBundle.getBundle("de.intranda.digiverso.m2m.messages.messages", locale);
    }
    if (localBundle == null || !localBundle.getLocale().equals(locale)) {
        logger.trace("Reloading local resource bundle for '{}'...", locale.getLanguage());
        localBundle = loadLocalResourceBundle(locale);
    }
}
 
Example 46
Project: javaee8-applications   File: CustomerController.java   Source Code and License 5 votes vote down vote up
public void destroy() {
    persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("CustomerDeleted"));
    if (!JsfUtil.isValidationFailed()) {
        selected = null; // Remove selection
        customers = null;    // Invalidate list of items to trigger re-query.
    }
}
 
Example 47
Project: rapidminer   File: I18N.java   Source Code and License 5 votes vote down vote up
/** registers the properties of the given bundle on the global error bundle */
public static void registerErrorBundle(ResourceBundle bundle, boolean overwrite) {
	if (!overwrite) {
		ERROR_BUNDLE.addResourceBundle(bundle);
	} else {
		ERROR_BUNDLE.addResourceBundleAndOverwrite(bundle);
	}
}
 
Example 48
Project: apache-tomcat-7.0.73-with-comment   File: HelloWorldExample.java   Source Code and License 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws IOException, ServletException
{
    ResourceBundle rb =
        ResourceBundle.getBundle("LocalStrings",request.getLocale());
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");

    String title = rb.getString("helloworld.title");

    out.println("<title>" + title + "</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");

    // note that all links are created to be relative. this
    // ensures that we can move the web application that this
    // servlet belongs to to a different place in the url
    // tree and not have any harmful side effects.

    // XXX
    // making these absolute till we work out the
    // addition of a PathInfo issue

    out.println("<a href=\"../helloworld.html\">");
    out.println("<img src=\"../images/code.gif\" height=24 " +
                "width=24 align=right border=0 alt=\"view code\"></a>");
    out.println("<a href=\"../index.html\">");
    out.println("<img src=\"../images/return.gif\" height=24 " +
                "width=24 align=right border=0 alt=\"return\"></a>");
    out.println("<h1>" + title + "</h1>");
    out.println("</body>");
    out.println("</html>");
}
 
Example 49
Project: sbc-qsystem   File: FSpecScheduleDialog.java   Source Code and License 5 votes vote down vote up
public static QSpecSchedule changeQSpecSchedule(Frame parent, boolean modal,
    QSpecSchedule sps) {
    QLog.l().logger().info(java.text.MessageFormat.format(java.util.ResourceBundle
        .getBundle("ru/apertum/qsystem/client/forms/resources/FSpecScheduleDialog")
        .getString("edit_spec"), new Object[]{(sps == null ? "NEW" : sps.getName())}));
    if (dialog == null) {
        dialog = new FSpecScheduleDialog(parent, modal);
        Uses.setLocation(dialog);
    }
    res = false;

    dialog.cbSchedule
        .setModel(new DefaultComboBoxModel(QScheduleList.getInstance().getItems().toArray()));

    if (sps != null) {
        dialog.dcFrom.setDate(sps.getFrom());
        dialog.dcTo.setDate(sps.getTo());
        dialog.cbSchedule.setSelectedItem(sps.getSchedule());
    } else {
        dialog.dcFrom.setDate(new Date());
        dialog.dcTo.setDate(new Date());
        dialog.cbSchedule.setSelectedItem(null);
    }
    dialog.setVisible(true);

    if (res) {
        if (sps == null) {
            sps = new QSpecSchedule();
        }
        sps.setFrom(dialog.dcFrom.getDate());
        sps.setTo(dialog.dcTo.getDate());
        sps.setSchedule((QSchedule) dialog.cbSchedule.getSelectedItem());
        return sps;
    }
    return null;
}
 
Example 50
Project: oscm   File: BaseBean.java   Source Code and License 5 votes vote down vote up
/**
 * Reset all resource bundles
 */
public void resetBundles() {
    FacesContext fc = FacesContext.getCurrentInstance();
    Iterator<Locale> it = fc.getApplication().getSupportedLocales();
    while (it.hasNext()) {
        Locale locale = it.next();
        ResourceBundle bundle = getResourceBundle(locale);
        if (bundle instanceof DbMessages) {
            ((DbMessages) bundle).resetProperties();
        }
    }
}
 
Example 51
Project: jdk8u-jdk   File: WeekFields.java   Source Code and License 5 votes vote down vote up
@Override
public String getDisplayName(Locale locale) {
    Objects.requireNonNull(locale, "locale");
    if (rangeUnit == YEARS) {  // only have values for week-of-year
        LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased()
                .getLocaleResources(locale);
        ResourceBundle rb = lr.getJavaTimeFormatData();
        return rb.containsKey("field.week") ? rb.getString("field.week") : name;
    }
    return name;
}
 
Example 52
Project: alfresco-repository   File: MessageServiceImpl.java   Source Code and License 5 votes vote down vote up
public ResourceBundle getRepoResourceBundle(
        final StoreRef storeRef,
        final String path,
        final Locale locale) throws IOException
{   
    // TODO - need to replace basic strategy with a more complete
    // search & instantiation strategy similar to ResourceBundle.getBundle()
    // Consider search query with basename* and then apply strategy ...
    
    // Avoid permission exceptions
    RunAsWork<ResourceBundle> getBundleWork = new RunAsWork<ResourceBundle>()
    {
        @Override
        public ResourceBundle doWork() throws Exception
        {
            NodeRef rootNode = nodeService.getRootNode(storeRef);

            // first attempt - with locale        
            NodeRef nodeRef = getNode(rootNode, path+"_"+locale+PROPERTIES_FILE_SUFFIX);
            
            if (nodeRef == null)
            {
                // second attempt - basename 
                nodeRef = getNode(rootNode, path+PROPERTIES_FILE_SUFFIX);
            }
            
            if (nodeRef == null)
            {
                logger.debug("Could not find message resource bundle " + storeRef + "/" + path);
                return null;
            }
            
            ContentReader cr = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
            ResourceBundle resBundle = new MessagePropertyResourceBundle(
                    new InputStreamReader(cr.getContentInputStream(), cr.getEncoding()));
            return resBundle;
        }
    };
    return AuthenticationUtil.runAs(getBundleWork, AuthenticationUtil.getSystemUserName());
}
 
Example 53
Project: logistimo-web-service   File: DomainConfigController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/approvals", method = RequestMethod.POST)
public
@ResponseBody
String updateApprovalsConfig(@RequestBody ApprovalsConfigModel model,
                             HttpServletRequest request)
    throws ServiceException, ConfigurationException {
  SecureUserDetails sUser = getUserDetails();
  Locale locale = sUser.getLocale();
  ResourceBundle backendMessages = Resources.get().getBundle("BackendMessages", locale);
  if (!GenericAuthoriser.authoriseAdmin(request)) {
    throw new UnauthorizedException(backendMessages.getString("permission.denied"));
  }
  String userId = sUser.getUsername();
  Long domainId = SecurityUtils.getCurrentDomainId();
  ConfigContainer cc = getDomainConfig(domainId, userId, sUser.getLocale());
  ApprovalsConfig.OrderConfig orderConfig = builder.buildApprovalsOrderConfig(model);
  ApprovalsConfig approvalsConfig = new ApprovalsConfig();
  approvalsConfig.setOrderConfig(orderConfig);
  cc.dc.setApprovalsConfig(approvalsConfig);
  cc.dc.addDomainData(ConfigConstants.APPROVALS, generateUpdateList(userId));
  saveDomainConfig(sUser.getLocale(), domainId, cc, backendMessages);
  xLogger.info("AUDITLOG \t {0} \t {1} \t CONFIGURATION \t " +
      "UPDATE APPROVALS", domainId, sUser.getUsername());
  xLogger.info(cc.dc.toJSONSring());

  return backendMessages.getString("approvals.config.update.success");
}
 
Example 54
Project: Hive_Game   File: NetworkScreenController.java   Source Code and License 5 votes vote down vote up
/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
           UnaryOperator<TextFormatter.Change> filter = c -> {
               String proposedText = c.getControlNewText();
                if (proposedText.matches(".{0,15}")) {
                   return c ;
               } else {
                   return null ;
               }
           };
           playerName.setTextFormatter(new TextFormatter<String>(filter));   
}
 
Example 55
Project: sentry   File: I18nMessages.java   Source Code and License 4 votes vote down vote up
public static void setCurrentLocale(Locale currentLocale) {
    I18nMessages.currentLocale = currentLocale;
    I18nMessages.messages = ResourceBundle.getBundle(BUNDLE, currentLocale, new UTF8Control());
}
 
Example 56
Project: OpenJSharp   File: CommonResourceBundle.java   Source Code and License 4 votes vote down vote up
protected CommonResourceBundle(Locale locale) {
    // Load the resource bundle of specified locale
    bundle = ResourceBundle.getBundle(BASE_NAME, locale);
}
 
Example 57
Project: Equella   File: CurrentLocale.java   Source Code and License 4 votes vote down vote up
public static ResourceBundle getResourceBundle()
{
	return getImpl().getResourceBundle();
}
 
Example 58
Project: ExtremeGuiMakeover   File: MasterDetailViewController.java   Source Code and License 4 votes vote down vote up
@Override
public void initialize(URL location, ResourceBundle resources) {
    backgroundImageView.setMouseTransparent(true);

    movieList.setCellFactory(c -> new MovieListCell());
    movieList.setItems(model.getMovies());
    movieList.setCacheHint(CacheHint.SPEED);

    model.selectedMovieProperty().bind(movieList.getSelectionModel().selectedItemProperty());
    model.selectedMovieProperty().addListener((obs, oldVal, newVal) -> updateDetailArea());
    detailView.visibleProperty().bind(model.selectedMovieProperty().isNotNull());

    maximizeAppIconView.setOnMouseClicked(e -> ((Stage) rootPane.getScene().getWindow()).setFullScreen(!((Stage) rootPane.getScene().getWindow()).isFullScreen()));
    closeAppIconView.setOnMouseClicked(e -> rootPane.getScene().getWindow().hide());

    moviePosterWrapper.setRotationAxis(new Point3D(0, 1, 0));
    moviePosterWrapper.setCache(true);
    moviePosterWrapper.setCacheShape(true);
    moviePosterWrapper.setCacheHint(CacheHint.SPEED);
    posterImageView.setCache(true);
    posterImageView.setCacheHint(CacheHint.SPEED);

    Util.installWindowDragListener(rootPane);

    final ChangeListener backgroundImageResizeListener = (obs, oldVal, newVal) -> {
        final Image image = backgroundImageView.getImage();
        if (backgroundImageView.getImage() != null) {
            Dimension2D backgroundDimension = shouldFitIn(image.getWidth(), image.getHeight(), rootPane.getWidth(), rootPane.getHeight());
            backgroundImageView.setFitWidth(backgroundDimension.getWidth());
            backgroundImageView.setFitHeight(backgroundDimension.getHeight());
        }
    };
    rootPane.widthProperty().addListener(backgroundImageResizeListener);
    rootPane.heightProperty().addListener(backgroundImageResizeListener);
    backgroundImageView.imageProperty().addListener(backgroundImageResizeListener);

    addFeatureSupport();

    updateDetailArea();


    watchTrailerButton.setOnAction(e -> playTrailer());
    mediaView.fitWidthProperty().bind(rootPane.widthProperty().subtract(64.0));

    mediaStateIcon = new AnimatedIcon();
    mediaStateIcon.setOpacity(0.6);
    mediaStateIcon.setScaleX(4.0);
    mediaStateIcon.setScaleY(4.0);
    mediaStateIcon.setMouseTransparent(true);
    mediaStateIcon.toPause();

    Circle circle = new Circle();
    circle.setMouseTransparent(true);
    circle.setRadius(76);
    circle.setStroke(Color.ORANGE);
    circle.setStrokeWidth(8);
    circle.setOpacity(0.6);

    StackPane mediaControl = new StackPane(circle, mediaStateIcon);
    mediaControl.setMouseTransparent(true);
    mediaControl.setMinWidth(USE_PREF_SIZE);
    mediaControl.setMinHeight(USE_PREF_SIZE);
    mediaControl.setMaxWidth(USE_PREF_SIZE);
    mediaControl.setMaxHeight(USE_PREF_SIZE);
    mediaControl.setVisible(false);

    mediaPane.getChildren().addAll(mediaControl);

    //TODO: Animation
    mediaView.setOnMouseEntered(e -> mediaControl.setVisible(true));
    mediaView.setOnMouseExited(e -> mediaControl.setVisible(false));

    movieList.getSelectionModel().select(0);

    rootPane.setOnKeyPressed(evt -> {
        if (evt.getCode().equals(KeyCode.ESCAPE)) {
            stopTrailer();
        }
    });
}
 
Example 59
Project: incubator-netbeans   File: FileSelector.java   Source Code and License 4 votes vote down vote up
/**
     * @param title is a title of the dialog
     * @param rootLabel label for the root node
     * @param root the base object to start browsing from
     * @param acceptor decides whether we have valid selection or not
     * @param top is a <code>Component</code> we just place on the top of the dialog
     * it can be <code>null</code>
     */
    public FileSelector ( String rootLabel, Node root, final NodeAcceptor acceptor, Component top) {
        super ();

        this.acceptor = acceptor;
        
        ResourceBundle bundle = NbBundle.getBundle(FileSelector.class);


        okButton = new JButton(bundle.getString("CTL_FileSelectorOkButton"));
        cancelButton = new JButton(bundle.getString("CTL_FileSelectorCancelButton"));
        okButton.getAccessibleContext().setAccessibleDescription(bundle.getString ("ACSD_FileSelectorOkButton"));
        cancelButton.getAccessibleContext().setAccessibleDescription(bundle.getString ("ACSD_FileSelectorCancelButton"));
        buttons = new JButton[] { okButton, cancelButton };
        

        manager.setRootContext (root);//s[0]);
        
        // Center
        tree = new BeanTreeView () {
            {
                tree.setCellEditor(null);
                tree.setEditable(false);
            }
        };
        tree.setPopupAllowed (false);
        tree.setDefaultActionAllowed (false);
        // install proper border for tree
        tree.setBorder((Border)UIManager.get("Nb.ScrollPane.border")); // NOI18N
        tree.getAccessibleContext().setAccessibleName(NbBundle.getBundle(FileSelector.class).getString("ACSN_FileSelectorTreeView"));
        tree.getAccessibleContext().setAccessibleDescription(NbBundle.getBundle(FileSelector.class).getString("ACSD_FileSelectorTreeView"));
        this.getAccessibleContext().setAccessibleDescription(NbBundle.getBundle(FileSelector.class).getString("ACSD_FileSelectorDialog"));
        setLayout(new BorderLayout());
        add(tree, BorderLayout.CENTER);

        // component to place at the top
        try {
                manager.setSelectedNodes (new Node[] { root });
                JLabel label = new JLabel();
                Mnemonics.setLocalizedText(label, rootLabel);
                label.setLabelFor(tree.getViewport().getView());
                add(label, BorderLayout.NORTH);
        } catch(PropertyVetoException pve) {
            throw new IllegalStateException(pve.getMessage());
        }



        // South
        if (top != null) {
            add(top, BorderLayout.SOUTH);
        }

        manager.addPropertyChangeListener (this);

//        if (top != null) top.requestFocus ();

        if (acceptor.acceptNodes (manager.getSelectedNodes())) {
            enableButton ();
        } else {
            disableButton ();
        }

    }
 
Example 60
Project: logistimo-web-service   File: CreateEntityServlet.java   Source Code and License 4 votes vote down vote up
private void resetRelatedEntitiesOrdering(HttpServletRequest req, HttpServletResponse resp,
                                          EntitiesService as, ResourceBundle backendMessages,
                                          ResourceBundle messages) throws IOException {
  xLogger.fine("Entering resetRelatedEntitiesOrdering");
  String kioskId = req.getParameter(KIOSKID);
  String linkType = req.getParameter("linktype");
  if (kioskId == null || kioskId.isEmpty()) {
    xLogger.severe("Invalid, null or empty kioskId. {0}", kioskId);
    return;
  }
  if (linkType == null || linkType.isEmpty()) {
    xLogger.severe("Invalid, null or empty linkType. {0}", linkType);
    return;
  }
  // Get the map parameter
  String map = req.getParameter("map");
  boolean
      mapView =
      (map != null) ? true
          : false; // If map parameter is present, it means the reset was clicked in the map view

  String message = null;
  xLogger.fine("kioskId = {0}", kioskId);

  try {
    as.resetRelatedEntitiesOrdering(Long.valueOf(kioskId), linkType);
    // The default redirect url has table view of related entities
    String
        redirectUrl =
        "/s/setup/setup.jsp?subview=kiosks&form=kiosklinks&kioskid=" + kioskId + "&linktype="
            + linkType;
    if (mapView) // If mapView is true, then add the map parameter so that redirection happens to map view of managed entities
    {
      redirectUrl += "&map";
    }
    writeToSetupScreen(req, resp,
        backendMessages.getString("resetordering.linkedkiosks.success") + ". &nbsp; [<a href=\""
            + redirectUrl + "\">" + backendMessages.getString("relationships.view") + "</a>]",
        Constants.VIEW_KIOSKS);
  } catch (ServiceException e) {
    xLogger.severe("Exception when resetting related entities ordering for kioskId {0}", kioskId);
    message = backendMessages.getString("error") + ": " + e.getMessage();
    // Write a response text
    writeText(resp, message);
  }
  xLogger.fine("Exiting resetRelatedEntitiesOrdering");
}