コード例 #1
0
 @SuppressWarnings("rawtypes")
 public String getVersionInformation(Class clazz) {
   // The following two lines read from the MANIFEST.MF
   String implTitle = clazz.getPackage().getImplementationTitle();
   String implVersion = clazz.getPackage().getImplementationVersion();
   if (implVersion != null) {
     // If we're in a .jar file, then we can return the version information
     // from the .jar file.
     return implTitle + " " + implVersion; // $NON-NLS-1$
   } else {
     // We're not in a .jar file - try to find the version file and
     // read the version information from that.
     try {
       ResourceBundle bundle = ResourceBundle.getBundle("version"); // $NON-NLS-1$
       StringBuffer buff = new StringBuffer();
       buff.append(bundle.getString("impl.title"))
           .append(' ')
           .append(bundle.getString("release.major.number"))
           .append('.')
           .append(
               bundle.getString(
                   "release.minor.number")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
       buff.append('.')
           .append(bundle.getString("release.milestone.number"))
           .append('.')
           .append(bundle.getString("release.build.number"))
           .append(" (class)"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
       return buff.toString();
     } catch (Exception ex) {
       return "Pentaho BI Platform - No Version Information Available"; //$NON-NLS-1$
     }
   }
 }
コード例 #2
0
  static ModelNode getSubsystemDescription(final Locale locale) {
    final ResourceBundle bundle = getResourceBundle(locale);

    final ModelNode node = new ModelNode();

    node.get(DESCRIPTION).set(bundle.getString("web"));
    node.get(HEAD_COMMENT_ALLOWED).set(true);
    node.get(TAIL_COMMENT_ALLOWED).set(true);
    node.get(NAMESPACE).set(Namespace.WEB_1_0.getUriString());

    node.get(ATTRIBUTES, Constants.DEFAULT_VIRTUAL_SERVER, TYPE).set(ModelType.STRING);
    node.get(ATTRIBUTES, Constants.DEFAULT_VIRTUAL_SERVER, DESCRIPTION)
        .set(bundle.getString("web.default-virtual-server"));
    node.get(ATTRIBUTES, Constants.DEFAULT_VIRTUAL_SERVER, REQUIRED).set(false);
    node.get(ATTRIBUTES, Constants.DEFAULT_VIRTUAL_SERVER, DEFAULT).set("localhost");

    node.get(ATTRIBUTES, Constants.NATIVE, TYPE).set(ModelType.BOOLEAN);
    node.get(ATTRIBUTES, Constants.NATIVE, DESCRIPTION).set(bundle.getString("web.native"));
    node.get(ATTRIBUTES, Constants.NATIVE, REQUIRED).set(false);
    node.get(ATTRIBUTES, Constants.NATIVE, DEFAULT).set(true);

    getConfigurationCommonDescription(
        node.get(ATTRIBUTES, Constants.CONTAINER_CONFIG), ATTRIBUTES, bundle);
    getConnectorCommonDescription(node.get(CHILDREN, Constants.CONNECTOR), ATTRIBUTES, bundle);
    getVirtualServerCommonDescription(
        node.get(CHILDREN, Constants.VIRTUAL_SERVER), ATTRIBUTES, bundle);

    return node;
  }
コード例 #3
0
  public void run() {
    String ipdest = "";
    try {

      ipdest = system.in.read(messages.getString("ipdest"));
      int count = 0;
      byte[] data = String.valueOf(count).getBytes();

      simulip.net.DatagramSocket d = new simulip.net.DatagramSocket(this);
      simulip.net.DatagramPacket p = new simulip.net.DatagramPacket(data, 5, ipdest, 54);
      while (true) {
        d.send(p);
        d.receive(p);
        system.out.println(
            MessageFormat.format(messages.getString("ackOf"), new String(p.getData())));
        p.setAddress(p.getAddress());
        p.setPort(p.getPort());
        count++;
        data = String.valueOf(count).getBytes();
        p.setData(data);
      }
    } catch (NetworkAddressFormatException nafe) {
      system.out.println(MessageFormat.format(messages.getString("badlyFormedAddress"), ipdest));
    } catch (Exception e) {
      system.out.println(e.getMessage());
      Logger.getLogger("").log(Level.SEVERE, "UdpEchoSend error", e);
    }
  }
コード例 #4
0
 @SuppressWarnings("unchecked")
 @Override
 public ActionResult execute(WebContext webContext) {
   ResourceBundle messagesBundle = webContext.getMessagesBundle();
   CategoryService categoryService = new CategoryService();
   ActionResult backToPreviousPage = new ActionResult(webContext.getPreviousURI(), true);
   String name = webContext.getParameter(CATEGORY);
   if (name == null || name.isEmpty()) {
     webContext.setAttribute(
         "errorMessage",
         messagesBundle.getString("add-category.message.categoryIsEmpty"),
         Scope.FLASH);
     return backToPreviousPage;
   }
   Category createdCategory = categoryService.createCategory(name);
   // add new category to the list in app context
   if (createdCategory != null) {
     List<Category> categories =
         (List<Category>)
             webContext.getAttribute(ContextListener.CATEGORIES_LIST, Scope.APPLICATION);
     categories.add(createdCategory);
     webContext.setAttribute(
         "successMessage", messagesBundle.getString("add-category.message.success"), Scope.FLASH);
   } else {
     webContext.setAttribute(
         "errorMessage", messagesBundle.getString("add-category.message.exist"), Scope.FLASH);
   }
   return backToPreviousPage;
 }
コード例 #5
0
  /**
   * Formats a message with the specified arguments using the given locale information.
   *
   * @param locale The locale of the message.
   * @param key The message key.
   * @param arguments The message replacement text arguments. The order of the arguments must match
   *     that of the placeholders in the actual message.
   * @return Returns the formatted message.
   * @throws MissingResourceException Thrown if the message with the specified key cannot be found.
   */
  public String formatMessage(Locale locale, String key, Object[] arguments)
      throws MissingResourceException {

    if (fResourceBundle == null || locale != fLocale) {
      if (locale != null) {
        fResourceBundle =
            PropertyResourceBundle.getBundle("org.apache.xerces.impl.msg.XIncludeMessages", locale);
        // memorize the most-recent locale
        fLocale = locale;
      }
      if (fResourceBundle == null)
        fResourceBundle =
            PropertyResourceBundle.getBundle("org.apache.xerces.impl.msg.XIncludeMessages");
    }

    String msg = fResourceBundle.getString(key);
    if (arguments != null) {
      try {
        msg = java.text.MessageFormat.format(msg, arguments);
      } catch (Exception e) {
        msg = fResourceBundle.getString("FormatFailed");
        msg += " " + fResourceBundle.getString(key);
      }
    }

    if (msg == null) {
      msg = fResourceBundle.getString("BadMessageKey");
      throw new MissingResourceException(msg, "org.apache.xerces.impl.msg.XIncludeMessages", key);
    }

    return msg;
  }
コード例 #6
0
ファイル: NewFileThree.java プロジェクト: peteclarkez/jgnash
  private void initComponents() {
    addButton = new JButton(rb.getString("Button.Add"));
    addButton.setIcon(IconUtils.getIcon("/jgnash/resource/list-add.png"));
    addButton.setHorizontalTextPosition(SwingConstants.LEADING);

    removeButton = new JButton(rb.getString("Button.Remove"));
    removeButton.setIcon(IconUtils.getIcon("/jgnash/resource/list-remove.png"));

    aJList = new JList<>();
    cJList = new JList<>();

    helpPane = new JEditorPane();
    helpPane.setEditable(false);
    helpPane.setEditorKit(new StyledEditorKit());
    helpPane.setBackground(getBackground());
    helpPane.setText(TextResource.getString("NewFileThree.txt"));

    addComponentListener(
        new ComponentAdapter() {

          @Override
          public void componentHidden(ComponentEvent evt) {
            isPageValid();
          }
        });

    addButton.addActionListener(this);
    removeButton.addActionListener(this);
  }
コード例 #7
0
  @Override
  public void validate(FacesContext context, UIComponent component, Object value)
      throws ValidatorException {
    String password = (String) value;
    ResourceBundle bundle = ResourceBundle.getBundle("languages.lang");
    if (password.length() < 8) {
      FacesMessage fm = new FacesMessage(bundle.getString("erreurHuitCaract"));
      throw new ValidatorException(fm);
    } else {
      if (!password.matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[^\\s]{8,}$")) {
        String erreur = "";
        /* Contient au moins 1 chiffre */
        if (!password.matches("^(?=.*\\d)[^\\s]{8,}$")) {
          erreur += bundle.getString("erreurUnChiffre");
        }

        /* Contient au moins 1 minuscule */
        if (!password.matches("^(?=.*[a-z])[^\\s]{8,}$")) {
          erreur += ((erreur.length() > 0) ? ", " : "") + bundle.getString("erreurUneMinuscule");
        }

        /* Contient au moins 1 majuscule */
        if (!password.matches("^(?=.*[A-Z])[^\\s]{8,}$")) {
          erreur += ((erreur.length() > 0) ? ", " : "") + bundle.getString("erreurUneMajuscule");
        }

        FacesMessage fm = new FacesMessage(erreur);
        throw new ValidatorException(fm);
      }
    }
  }
コード例 #8
0
  public String twitterLogin() {
    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true)
        .setOAuthConsumerKey(BUNDLE.getString("twt.client_id"))
        .setOAuthConsumerSecret(BUNDLE.getString("twt.secret"))
        .setOAuthRequestTokenURL("https://api.twitter.com/oauth/request_token")
        .setOAuthAuthorizationURL(("https://api.twitter.com/oauth/authorize"))
        .setOAuthAccessTokenURL(("https://api.twitter.com/oauth/access_token"));
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    HttpServletRequest request =
        (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    HttpServletResponse response =
        (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    request.getSession().setAttribute("twitter", twitter);
    try {
      RequestToken requestToken =
          twitter.getOAuthRequestToken(BUNDLE.getString("twt.redirect_uri"));
      request.getSession().setAttribute("requestToken", requestToken);
      LOGGER.info("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL());
      try {
        response.sendRedirect(requestToken.getAuthenticationURL());
      } catch (IOException e) {
        e.printStackTrace();
      }

    } catch (TwitterException e) {
      e.printStackTrace();
    }
    return "";
  }
コード例 #9
0
  public String requestBearerToken() throws IOException {
    HttpsURLConnection connection = null;
    String encodedCredentials =
        encodeKeys(BUNDLE.getString("twt.client_id"), BUNDLE.getString("twt.secret"));
    String endPointUrl = "https://api.twitter.com/oauth2/token";
    try {
      HttpServletResponse response =
          (HttpServletResponse)
              FacesContext.getCurrentInstance().getExternalContext().getResponse();
      response.setHeader("Host", "api.twitter.com");
      response.setHeader("User-Agent", "Iclub");
      response.setHeader("Authorization", "Basic " + encodedCredentials);
      response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
      response.setHeader("Content-Length", "29");
      ServletOutputStream fdsaf = response.getOutputStream();
      fdsaf.write("grant_type=client_credentials".getBytes());
      fdsaf.close();
      response.sendRedirect(endPointUrl);

      return new String();
    } catch (MalformedURLException e) {
      throw new IOException("Invalid endpoint URL specified.", e);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
コード例 #10
0
  public String askStringQuestion(OutputLevel level, String question, String defaultAnswer) {
    if (defaultAnswer != null) {
      String tmp =
          wrapString(question + " [" + _labels.getString("S4") + defaultAnswer + "] ", level);
      print(level, tmp);
    } else {
      String tmp = wrapString(question + " ", level);
      print(level, tmp);
    }

    String answer = "";
    try {
      answer = readStdInLine();

      if (isYes(answer) || "".equals(answer)) {
        return defaultAnswer == null ? answer : defaultAnswer;
      }

      if (isNo(answer)) {
        if (defaultAnswer != null) {
          print(level, _labels.getString("S5"));
          answer = readStdInLine();
          return answer;
        } else {
          return answer;
        }
      }

      return answer;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
コード例 #11
0
  @Override
  public int doStartTag() throws JspException {
    String language = (String) pageContext.getSession().getAttribute("param.language");

    Locale locale;
    if (language != null) {
      locale = new Locale(language, language.toUpperCase());
    } else {
      locale = pageContext.getRequest().getLocale();
    }

    ResourceBundle resource =
        ResourceBundle.getBundle("by.gstu.Testing.resource.pagestext", locale);
    JspWriter writer = pageContext.getOut();
    try {
      try {
        writer.print(new String(resource.getString(key).getBytes("ISO-8859-1"), "UTF-8"));
      } catch (MissingResourceException ex) {
        logger.debug(ex);
        writer.print(resource.getString("resource.not.found"));
      }
    } catch (IOException ex) {

    }
    return SKIP_BODY;
  }
コード例 #12
0
  /**
   * Default implementation for storing the static contents of the serial port implementation
   *
   * @param object Object to store, of type PositionableLabel
   * @return Element containing the complete info
   */
  public Element store(Object object) {
    getInstance(object);
    Element e = new Element("connection");

    // many of the following are required by the DTD; failing to include
    // them makes the XML file unreadable, but at least the next
    // invocation of the program can then continue.
    storeCommon(e, adapter);

    if (adapter.getCurrentPortName() != null) {
      e.setAttribute("port", adapter.getCurrentPortName());
    } else {
      e.setAttribute("port", rb.getString("noneSelected"));
    }

    if (adapter.getCurrentBaudRate() != null) {
      e.setAttribute("speed", adapter.getCurrentBaudRate());
    } else {
      e.setAttribute("speed", rb.getString("noneSelected"));
    }

    e.setAttribute("class", this.getClass().getName());

    extendElement(e);

    return e;
  }
コード例 #13
0
  /**
   * Gets the string for the given key from one of the doclet's resource bundles.
   *
   * <p>The more specific bundle is checked first; if it is not there, the common bundle is then
   * checked.
   *
   * @param key the key for the desired string
   * @return the string for the given key
   * @throws MissingResourceException if the key is not found in either bundle.
   */
  public String getText(String key) throws MissingResourceException {
    initBundles();

    if (docletBundle.containsKey(key)) return docletBundle.getString(key);

    return commonBundle.getString(key);
  }
コード例 #14
0
  /**
   * Extracts the version information data from the <code>version.properties</code> file found in
   * the source directory.
   *
   * @return the version information from the <code>version.properties</code> file
   */
  protected static VersionInfo createVersionInfo() {
    // We're not in a .jar file - try to find the build-res/version file and
    // read the version information from that.
    final VersionInfo versionInfo = new VersionInfo();
    try {
      final ResourceBundle bundle = ResourceBundle.getBundle("version"); // $NON-NLS-1$
      versionInfo.setFromManifest(false);
      versionInfo.setProductID(bundle.getString("impl.productID")); // $NON-NLS-1$
      versionInfo.setTitle(bundle.getString("impl.title")); // $NON-NLS-1$
      versionInfo.setVersionMajor(bundle.getString("release.major.number")); // $NON-NLS-1$
      versionInfo.setVersionMinor(bundle.getString("release.minor.number")); // $NON-NLS-1$
      versionInfo.setVersionBuild(bundle.getString("release.build.number")); // $NON-NLS-1$

      // The release milestone number has both the release number and the milestone number
      final String releaseMilestoneNumber =
          bundle.getString("release.milestone.number"); // $NON-NLS-1$
      if (releaseMilestoneNumber != null) {
        String[] parts = releaseMilestoneNumber.replace('-', '.').split("\\."); // $NON-NLS-1$
        if (parts.length > 0) {
          versionInfo.setVersionRelease(parts[0]);
          if (parts.length > 1) {
            versionInfo.setVersionMilestone(parts[1]);
          }
        }
      }
    } catch (Exception e) {
      // TODO:log
      versionInfo.setVersion("No Version Information Available"); // $NON-NLS-1$
    }
    return versionInfo;
  }
コード例 #15
0
  /**
   * Generates the returnToUrl parameter that is passed to the OP. The User Agent (i.e., the
   * browser) will be directed to this page following authentication.
   *
   * @param representedPage The RegistrationPage object whose cover is to be cracked open to get at
   *     the raw HttpServlet goodies inside.
   * @return String - the returnToUrl to be used for the authentication request.
   */
  public static String getReturnToUrl() {
    ResourceBundle properties = ResourceBundle.getBundle("icardea");
    boolean isSalkUsage = Boolean.parseBoolean(properties.getString("salk.usage"));
    String server = "";
    String port = "";
    String url = "";
    if (isSalkUsage) {
      server = properties.getString("salk.server");
      port = properties.getString("secure.port");
      url = server + ":" + port + "/ppm_v2/";
    } else { // (isSalkUSage) NoSalkUsage, we assume localhost testing
      log.info("Localhost testing. salk.usage was not 'true'");
      server = "http://127.0.0.1";
      port = "10101";
      url = server + ":" + port + "/";
    }
    url = url + "view?startup=de.offis.health.icardea.ppm.viewapp";

    /*try {
        InetAddress addr = InetAddress.getLocalHost();

        // Get IP Address
        byte[] ipAddr = addr.getAddress();
        String ipadd = ipAddr.toString();
        // Get hostname
        String hostname = addr.getHostAddress();
        url = "https://"+ hostname + ":"+securePort+"/icardea_careplaneditor/servlet/loginServlet?";
    } catch (UnknownHostException e) {
    }*/
    return url;
  }
コード例 #16
0
  public String doIclubLogin() {
    LOGGER.info("Class :: " + this.getClass() + " :: Method :: doIclubLogin");
    if (!validateLogin()) {
      try {
        WebClient client =
            IclubWebHelper.createCustomClient(
                BASE_URL
                    + "person/login/"
                    + bean.getLName()
                    + "/"
                    + Base64.encodeBase64URLSafeString(DigestUtils.md5(bean.getLPasswd())));
        ResponseModel response = client.accept(MediaType.APPLICATION_JSON).get(ResponseModel.class);
        client.close();
        if (response.getStatusCode() == 0) {
          setTheme();
          IclubWebHelper.addMessage("Person Logged-In successfully", FacesMessage.SEVERITY_INFO);
          WebClient loginClient =
              IclubWebHelper.createCustomClient(BASE_URL + "person/" + bean.getLName());
          IclubLoginModel model =
              loginClient.accept(MediaType.APPLICATION_JSON).get(IclubLoginModel.class);
          loginClient.close();
          if (model != null && model.getLId() != null) {
            IclubWebHelper.addObjectIntoSession(
                BUNDLE.getString("logged.in.user.id"), model.getIclubPersonBByLPersonId());
            IclubWebHelper.addObjectIntoSession(
                BUNDLE.getString("logged.in.user.scname"), bean.getLName());
            WebClient personClient =
                IclubWebHelper.createCustomClient(
                    U_BASE_URL + "get/" + model.getIclubPersonBByLPersonId());
            IclubPersonModel personModel =
                personClient.accept(MediaType.APPLICATION_JSON).get(IclubPersonModel.class);
            personClient.close();
            IclubWebHelper.addObjectIntoSession(
                BUNDLE.getString("logged.in.user.name"),
                personModel.getPFName()
                    + (personModel.getPLName() == null ? "" : personModel.getPLName() + " "));
            IclubWebHelper.addObjectIntoSession(
                BUNDLE.getString("logged.in.role.id"), model.getIclubRoleType());

            return "/pages/dashboard/user/main.xhtml?faces-redirect=true";

          } else {
            IclubWebHelper.addMessage(
                "Person Profile Fetch Error - Contact Admin", FacesMessage.SEVERITY_ERROR);
            return "";
          }
        } else {
          IclubWebHelper.addMessage(
              "Login error :: " + response.getStatusDesc(), FacesMessage.SEVERITY_ERROR);
          return "";
        }
      } catch (Exception e) {
        LOGGER.error(e, e);
        IclubWebHelper.addMessage("Login error :: " + e.getMessage(), FacesMessage.SEVERITY_ERROR);
        return "";
      }
    } else {
      return "";
    }
  }
コード例 #17
0
 public static String[] getValidTwoDigits(String currencyCode) throws InterruptOperationException {
   while (true) {
     writeMessage(res.getString("choose.denomination.and.count.format"));
     String twoNumbers = readString();
     String[] numbers;
     if (twoNumbers != null) {
       numbers = twoNumbers.split(" ");
     } else {
       writeMessage(res.getString("invalid.data"));
       continue;
     }
     if (numbers.length != 2) {
       writeMessage(res.getString("invalid.data"));
       continue;
     }
     if (isInteger(numbers[0])
         && isInteger(numbers[1])
         && Integer.parseInt(numbers[0]) > 0
         && Integer.parseInt(numbers[1]) > 0) {
       return numbers;
     } else {
       writeMessage(res.getString("invalid.data"));
     }
   }
 }
コード例 #18
0
  /** @see javax.faces.context.ExceptionHandlerWrapper#handle() */
  @Override
  public void handle() throws FacesException {
    Iterator<ExceptionQueuedEvent> it = getUnhandledExceptionQueuedEvents().iterator();
    while (it.hasNext()) {
      ExceptionQueuedEvent event = it.next();
      ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

      FacesContext facesContext = FacesContext.getCurrentInstance();

      ResourceBundle bundle = facesContext.getApplication().getResourceBundle(facesContext, "msg");

      Throwable t = context.getException();

      String title = bundle.getString("error.unhandled.title");
      String message = bundle.getString("error.unhandled.message") + t;

      if (logger.isErrorEnabled()) {
        logger.error(title, t);
      }

      facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, title, message));

      it.remove();
    }

    getWrapped().handle();
  }
コード例 #19
0
  private boolean checkPassword() {
    Password firstPassword;

    if (jpfFirst instanceof JPasswordQualityField) {
      char[] firstPasswordChars = ((JPasswordQualityField) jpfFirst).getPassword();

      if (firstPasswordChars == null) {
        JOptionPane.showMessageDialog(
            this,
            res.getString("MinimumPasswordQualityNotMet.message"),
            getTitle(),
            JOptionPane.WARNING_MESSAGE);
        return false;
      }

      firstPassword = new Password(firstPasswordChars);
    } else {
      firstPassword = new Password(((JPasswordField) jpfFirst).getPassword());
    }

    Password confirmPassword = new Password(jpfConfirm.getPassword());

    if (firstPassword.equals(confirmPassword)) {
      password = firstPassword;
      return true;
    }

    JOptionPane.showMessageDialog(
        this, res.getString("PasswordsNoMatch.message"), getTitle(), JOptionPane.WARNING_MESSAGE);

    return false;
  }
コード例 #20
0
ファイル: SAFMain.java プロジェクト: jmorenor1986/SAFTWS
  /**
   * Funcion que permite publicar la url del servicio Web
   *
   * @param arg
   */
  public static void main(String arg[]) {
    String ip = "";
    String puerto = "";

    try {
      ResourceBundle rb = ResourceBundle.getBundle("co.com.codesoftware.properties.baseProperties");
      String valida = rb.getString("IP_DINAMICA");

      if ("SI".equalsIgnoreCase(valida)) {
        ip = rb.getString("IP_FIJA");
      } else {
        ip = InetAddress.getLocalHost().getHostAddress();
      }
      puerto = rb.getString("PUERTO");
    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.out.println("Este es la ip: " + ip);
    Endpoint.publish("http://" + ip + ":" + puerto + "/WS/server", new SAFWS());
    System.out.println(
        "Servicos desplegados en la siguiente direccion: \n\n\n"
            + "http://"
            + ip
            + ":"
            + puerto
            + "/WS/server/SAFWS?wsdl");
  }
コード例 #21
0
  public static String[] getValidTwoDigits(String currencyCode) throws InterruptOperationException {
    String[] array;
    writeMessage(
        String.format(res.getString("choose.denomination.and.count.format"), currencyCode));

    while (true) {
      String s = readString();
      array = s.split(" ");
      int k;
      int l;
      try {
        k = Integer.parseInt(array[0]);
        l = Integer.parseInt(array[1]);
      } catch (Exception e) {
        writeMessage(res.getString("invalid.data"));
        continue;
      }
      if (k <= 0 || l <= 0 || array.length > 2) {
        writeMessage(res.getString("invalid.data"));
        continue;
      }
      break;
    }
    return array;
  }
コード例 #22
0
ファイル: I18n.java プロジェクト: gravypod/PersonalWorlds
  /**
   * Get a message from out I18n data file.
   *
   * @param message - message title. Such as 'noPlayer'
   * @return - What the set message really is
   */
  public String getColoredMessage(final String message) {

    if (messageCache.containsKey(message)) {
      return messageCache.get(message);
    }

    try {

      try {

        final String translatedMessage =
            ChatColor.translateAlternateColorCodes(colorCode, customMessages.getString(message));

        messageCache.put(message, translatedMessage);

        return translatedMessage;

      } catch (final MissingResourceException ex) {

        final String translatedMessage =
            ChatColor.translateAlternateColorCodes(colorCode, messages.getString(message));

        messageCache.put(message, translatedMessage);

        return translatedMessage;
      }

    } catch (final MissingResourceException ex) {
      return defaultBundle.getString(message);
    }
  }
コード例 #23
0
  public static final class OutputLevelEditor extends java.beans.PropertyEditorSupport {
    /** Display Names for alignment. */
    private static final String[] names = {
      formBundle.getString("VALUE_OutputLevel_Minimum"),
      formBundle.getString("VALUE_OutputLevel_Normal"),
      formBundle.getString("VALUE_OutputLevel_Maximum"),
    };

    /** @return names of the possible directions */
    public String[] getTags() {
      return names;
    }

    /** @return text for the current value */
    public String getAsText() {
      int value = ((Integer) getValue()).intValue();
      if ((value < 0) || (value > 2)) return null;
      return names[value];
    }

    /**
     * Setter.
     *
     * @param str string equal to one value from directions array
     */
    public void setAsText(String str) {
      for (int i = 0; i <= 2; i++) {
        if (names[i].equals(str)) {
          setValue(new Integer(i));
          return;
        }
      }
    }
  }
コード例 #24
0
 private void updateGUILabels() {
   lMonitor.setText(rb.getString("lbl_folder"));
   lClearFolder.setText(rb.getString("lbl_clear_folder"));
   buttonPanel.setBorder(new TitledBorder(new EtchedBorder(), rb.getString("brd_monitor_button")));
   SwingUtilities.updateComponentTreeUI(this);
   this.pack();
 }
コード例 #25
0
  protected void spendXP() {
    String skillName = (String) choiceSkill.getSelectedItem();
    if (choiceNoSkill.equals(skillName)) {
      // This shouldn't happen, but guard against it anyway.
      return;
    }
    int rows = personnelTable.getRowCount();
    int improvedPersonnelCount = rows;
    while (rows > 0) {
      for (int i = 0; i < rows; ++i) {
        Person p = personnelModel.getPerson(personnelTable.convertRowIndexToModel(i));
        int cost = 0;
        if (p.hasSkill(skillName)) {
          cost = p.getCostToImprove(skillName);
        } else {
          cost = SkillType.getType(skillName).getCost(0);
        }
        int experience = p.getExperienceLevel(false);

        // Improve the skill and deduce the cost
        p.improveSkill(skillName);
        campaign.personUpdated(p);
        p.setXp(p.getXp() - cost);

        // The next part is bollocks and doesn't belong here, but as long as we hardcode AtB ...
        if (campaign.getCampaignOptions().getUseAtB()) {
          if ((p.getPrimaryRole() > Person.T_NONE)
              && (p.getPrimaryRole() <= Person.T_CONV_PILOT)
              && (p.getExperienceLevel(false) > experience)
              && (experience >= SkillType.EXP_REGULAR)) {
            String spa = campaign.rollSPA(p.getPrimaryRole(), p);
            if (null == spa) {
              if (campaign.getCampaignOptions().useEdge()) {
                p.acquireAbility(
                    PilotOptions.EDGE_ADVANTAGES, "edge", p.getEdge() + 1); // $NON-NLS-1$
                p.addLogEntry(
                    campaign.getDate(),
                    String.format(resourceMap.getString("gainedEdge.text"))); // $NON-NLS-1$
              }
            } else {
              p.addLogEntry(
                  campaign.getDate(),
                  String.format(resourceMap.getString("gained.format"), spa)); // $NON-NLS-1$
            }
          }
        }
      }
      // Refresh the filter and continue if we still have anyone available
      updatePersonnelTable();
      rows = personnelTable.getRowCount();
      dataChanged = true;
    }
    if (improvedPersonnelCount > 0) {
      campaign.addReport(
          String.format(
              resourceMap.getString("improvedSkills.format"),
              skillName,
              improvedPersonnelCount)); //$NON-NLS-1$
    }
  }
コード例 #26
0
  // ***** *****
  public MethodDescriptor[] getMethodDescriptors() {
    try {
      MethodDescriptor md1 =
          new MethodDescriptor(
              getMethod(
                  com.ibm.HostPublisher.IntegrationObject.HPubCommon.class, "processRequest"));
      String procReqDesc = res.getString("procReqDesc");
      md1.setShortDescription(procReqDesc);

      MethodDescriptor md2 =
          new MethodDescriptor(
              getMethod(
                  com.ibm.HostPublisher.IntegrationObject.HPubCommon.class, "doHPTransaction"));
      String doHPTransDesc = res.getString("doHPTransDesc");
      md2.setShortDescription(doHPTransDesc);

      // method for receiving event
      MethodDescriptor md3 =
          new MethodDescriptor(
              getMethod(
                  com.ibm.HostPublisher.IntegrationObject.HPubCommon.class, "hPubStartPerformed"));
      String hPubStartPerfDesc = res.getString("hPubStartPerfDesc");
      md3.setShortDescription(hPubStartPerfDesc);

      MethodDescriptor[] arrayOfMDs = {md1, md2, md3};
      return arrayOfMDs;

    } catch (IntrospectionException e) {
      e.printStackTrace();
    }
    return null;
  }
コード例 #27
0
  public static String loadMessage(final String code, final Object[] parameters) {
    // default message
    String errorMessage = "";
    try {
      // get access to the error messages bundle
      final ResourceBundle messagesBundle =
          ResourceBundle.getBundle(ERRORS_BUNDLE, Locale.getDefault());
      // construct the error message
      errorMessage = code + " - " + messagesBundle.getString(MESSAGE_PREFIX + code);

      // get access to the error message parameters bundle
      final ResourceBundle parametersBundle =
          ResourceBundle.getBundle(PARAMETERS_BUNDLE, Locale.getDefault());
      // loop for all parameters
      for (int i = 0; i < parameters.length; i++) {
        // get parameter value
        final String parameterValue =
            parametersBundle.getString(PARAMETER_PREFIX + (String) parameters[i]);
        // replace parameter placeholder in the error message string
        errorMessage = errorMessage.replaceAll("\\{" + (i + 1) + "}", parameterValue);
      }
    } catch (Exception e) {
      // log the exception
      LOGGER.warning(e);
    }

    return errorMessage;
  }
コード例 #28
0
 /**
  * Iterate over the validation result to check for any validation failure. For the very first
  * validation failure, it reads the oneinc-resource.properties encapsulated in member variable
  * apps and set the user friendly message along with the IRC and throws the
  * OneIncValidationException.
  *
  * @param bean - Bean to be validated
  * @param results - contains the validation result
  * @param resources2 - ValidatorResources object prepared for validation-rules.xml
  * @param form - contains the mapping for field and their validation rule.
  * @throws CWValidationException - if validation gets fail.
  */
 @SuppressWarnings({"unchecked", "deprecation"})
 private void checkResults(
     Serializable bean, ValidatorResults results, ValidatorResources resources2, Form form)
     throws CWValidationException {
   Iterator propertyNames = results.getPropertyNames().iterator();
   while (propertyNames.hasNext()) {
     String propertyName = (String) propertyNames.next();
     ValidatorResult result = results.getValidatorResult(propertyName);
     Map actionMap = result.getActionMap();
     Iterator keys = actionMap.keySet().iterator();
     Field field = form.getField(propertyName);
     String prettyFieldName = apps.getString(field.getArg(0).getKey());
     while (keys.hasNext()) {
       String actName = (String) keys.next();
       ValidatorAction action = resources.getValidatorAction(actName);
       if (!result.isValid(actName)) {
         String message = apps.getString(action.getMsg());
         Object[] args = {prettyFieldName};
         String formatMsg = MessageFormat.format(message, args);
         int colonIndex = formatMsg.indexOf(',');
         String imfResponseCode = null;
         String msg = null;
         if (colonIndex > 0) {
           imfResponseCode = formatMsg.substring(0, colonIndex);
           msg = formatMsg.substring(colonIndex);
         }
         throw new CWValidationException(msg, imfResponseCode);
       }
     }
   }
 }
コード例 #29
0
 public TvShowSettingsContainerPanel() {
   setLayout(new BorderLayout(0, 0));
   {
     JTabbedPane tabbedPanePages = new JTabbedPane(JTabbedPane.TOP);
     add(tabbedPanePages, BorderLayout.CENTER);
     {
       JScrollPane scrollPane = new JScrollPane();
       scrollPane.setViewportView(new TvShowSettingsPanel());
       tabbedPanePages.addTab(
           BUNDLE.getString("Settings.general"), null, scrollPane, null); // $NON-NLS-1$
     }
     {
       JScrollPane scrollPane = new JScrollPane();
       scrollPane.setViewportView(new TvShowScraperSettingsPanel());
       tabbedPanePages.addTab(
           BUNDLE.getString("Settings.scraper"), null, scrollPane, null); // $NON-NLS-1$
     }
     {
       JScrollPane scrollPane = new JScrollPane();
       scrollPane.setViewportView(new TvShowRenamerSettingsPanel());
       tabbedPanePages.addTab(
           BUNDLE.getString("Settings.renamer"), null, scrollPane, null); // $NON-NLS-1$
     }
   }
 }
コード例 #30
0
  @SuppressWarnings("UnusedDeclaration")
  public void beforeBeanDiscovery(@Observes final BeforeBeanDiscovery bbd) {
    log.info("starting errai cdi ...");
    final ResourceBundle erraiServiceConfig;
    try {
      erraiServiceConfig = getBundle("ErraiService");
    } catch (MissingResourceException e) {
      // ErraiService is optional!
      return;
    }

    if (erraiServiceConfig.containsKey(ERRAI_CDI_STANDALONE)) {
      final boolean standalone =
          "true".equals(erraiServiceConfig.getString(ERRAI_CDI_STANDALONE).trim());

      if (standalone) {
        log.info("errai cdi running in standalone mode.");
      } else {
        log.info("errai cdi running as regular extension.");
      }
    }

    final String dispatchImplKey = "errai.dispatcher_implementation";
    if (erraiServiceConfig.containsKey(dispatchImplKey)) {
      if (AsyncDispatcher.class.getName().equals(erraiServiceConfig.getString(dispatchImplKey))) {
        throw new ErraiBootstrapFailure(
            "Cannot start Errai CDI. You have have configured the service to use the "
                + AsyncDispatcher.class.getName()
                + " dispatcher implementation. Due to limitations of Weld, you must use the "
                + SimpleDispatcher.class.getName()
                + " in order to use this module.");
      }
    }
  }