Java 类java.util.ResourceBundle 实例源码

项目:jdk8u-jdk    文件:TestSetResourceBundle.java   
/**
 * 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);
    }

}
项目:Java-9-Programming-Blueprints    文件:CloudNoticeManagerController.java   
@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() : "");
    });
}
项目:openjdk-jdk10    文件:BaseLoggerBridgeTest.java   
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;
}
项目:Logisim    文件:LocaleManager.java   
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;
}
项目:NotifyTools    文件:Messages.java   
/**
     * 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;
    }
项目:lazycat    文件:ResourceBundleELResolver.java   
@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;
}
项目:openjdk-jdk10    文件:LocaleResources.java   
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;
}
项目:validator-web    文件:PlatformResourceBundleLocator.java   
/**
 * 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;
}
项目:vars-annotation    文件:Initializer.java   
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;
}
项目:openjdk-jdk10    文件:MessageCatalog.java   
/**
 * 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);
}
项目:ChatRoom-JavaFX    文件:ChatController.java   
@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");
}
项目:openjdk-jdk10    文件:BootstrapLogger.java   
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;
}
项目:AWGW    文件:Unit.java   
/**
 * 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");
    }
}
项目:NetCompile    文件:TestSceneController.java   
@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>");
}
项目:oscm    文件:RichLazyDataModel.java   
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);
}
项目:apache-tomcat-7.0.73-with-comment    文件:Util.java   
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();
    }
}
项目:logistimo-web-service    文件:InvntryWithBatchInfoExportHandler.java   
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;
}
项目:openjdk-jdk10    文件:LoggerFinderLoaderTest.java   
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);
    }
项目:Clipcon-Client    文件:SettingScene.java   
@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();
        }
    });

}
项目:logistimo-web-service    文件:DashboardController.java   
@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");
}
项目:tomcat7    文件:TestResourceBundleELResolver.java   
/**
 * 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());
}
项目:gchisto    文件:GCParserDriver.java   
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"));
}
项目:logistimo-web-service    文件:DomainConfigController.java   
@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"));
  }
}
项目:openrouteservice    文件:JSONObject.java   
/**
     * 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));
            }
        }
    }
项目:logistimo-web-service    文件:HandlingUnitController.java   
@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");
}
项目:TreasureHunting    文件:QaController.java   
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;
    }
}
项目:openjdk-jdk10    文件:BasicTest.java   
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");
}
项目:FEFEditor    文件:Dispo.java   
@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();
}
项目:logistimo-web-service    文件:TransactionUtil.java   
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;
}
项目:logistimo-web-service    文件:UsersController.java   
@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");
}
项目:openjdk-jdk10    文件:DefaultLoggerTest.java   
@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);
    }
}
项目:logistimo-web-service    文件:UsersController.java   
@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);
  }
}
项目:logistimo-web-service    文件:ExportServlet.java   
@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");
}
项目:javaide    文件:KeyStoreTest.java   
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));
    }
}
项目:code-tracker    文件:MainController.java   
@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);
}
项目:powertext    文件:AutoCompleteDescWindow.java   
/**
 * 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);
}
项目:openjdk-jdk10    文件:MyResourcesEU.java   
@Override
public ResourceBundle getBundle(String baseName, Locale locale) {
    if (euLocales.contains(locale)) {
        return super.getBundle(baseName, locale);
    }
    return null;
}
项目:ABC-List    文件:ExercisePresenter.java   
@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);
}
项目:logistimo-web-service    文件:DashboardServlet.java   
@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");
}
项目:logistimo-web-service    文件:DiscrepancyBuilder.java   
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();
}