Example #1
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.");
      }
    }
  }
 public String getExceptionMessage(Exception e) {
   if (e instanceof EmpireException) {
     EmpireException ee = (EmpireException) e;
     String key = ee.getErrorType().getKey();
     // get Pattern
     String pattern;
     if (resBundle.containsKey(key)) { // Get Pattern
       pattern = resBundle.getString(key);
     } else { // No error message pattern provided. Using default
       pattern = ee.getErrorType().getMessagePattern();
       log.error("Error resolving error messsage pattern: {}", key);
     }
     // get Params and translate
     String[] params = ee.getErrorParams();
     if (params != null) {
       for (int i = 0; i < params.length; i++) params[i] = resolveText(params[i]);
     }
     // Format message
     return EmpireException.formatErrorMessage(ee.getErrorType(), pattern, params);
   } else { // Other exception try to resolve by class name
     String key = "exception." + e.getClass().getName();
     if (resBundle.containsKey(key)) return resBundle.getString(key);
     // not provided
     return e.getLocalizedMessage();
   }
 }
Example #3
0
  static {
    /** 配置文件变量 */
    ResourceBundle rb = null;
    try {
      rb = ResourceBundle.getBundle("library");
    } catch (Exception e) {
      try {
        File find = FileFinder.find("library.properties");
        if (find != null) {
          rb =
              new PropertyResourceBundle(
                  IOUtil.getReader(find.getAbsolutePath(), System.getProperty("file.encoding")));
          LIBRARYLOG.info(
              "load library not find in classPath ! i find it in "
                  + find.getAbsolutePath()
                  + " make sure it is your config!");
        }
      } catch (Exception e1) {
        LIBRARYLOG.warning(
            "not find library.properties. and err " + e.getMessage() + " i think it is a bug!");
      }
    }

    if (rb == null) {
      LIBRARYLOG.warning("not find library.properties in classpath use it by default !");
    }

    if (rb.containsKey("userLibrary")) userLibrary = rb.getString("userLibrary");
    if (rb.containsKey("ambiguityLibrary")) ambiguityLibrary = rb.getString("ambiguityLibrary");
    if (rb.containsKey("isSkipUserDefine"))
      isSkipUserDefine = Boolean.valueOf(rb.getString("isSkipUserDefine"));
    if (rb.containsKey("isRealName")) isRealName = Boolean.valueOf(rb.getString("isRealName"));
    if (rb.containsKey("crfModel")) crfModel = rb.getString("crfModel");
  }
Example #4
0
  public static String getString(String key) {
    if (!BUNDLE.containsKey(key)) {
      return String.format(DEFAULT_VALUE, key);
    }

    return BUNDLE.getString(key);
  }
Example #5
0
 public static String getPropertyParam(ResourceBundle res, String[] propNames, String parameter) {
   try {
     for (String propName : propNames) {
       if (res.containsKey(propName + '.' + parameter)) {
         try {
           return res.getString(propName + '.' + parameter);
         } catch (MissingResourceException e) {
         }
       }
     }
     // don't need this, just return null
     // if (value == null) {
     //    throw new MissingResourceException("Can't find resource for bundle",
     // res.getClass().getName(), Arrays.asList(propNames) + "." + parameter);
     // }
   } catch (Exception e) {
     Debug.logWarning(
         e,
         "Error getting "
             + parameter
             + " value from cache.properties file for propNames: "
             + propNames,
         module);
   }
   return null;
 }
Example #6
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);
  }
  // retrieve text for localization key (use freq to customize the message for
  // a specific resource type)
  private String localize(
      ResourceBundle labels, String s, int freq, int type, String component, String mode) {
    String fulli18n = s + ".freq" + freq + ".type" + type;
    String notypei18n = s + ".freq" + freq;
    if (component != null) {
      fulli18n += "." + component;
      notypei18n += "." + component;
      if (mode != null) {
        fulli18n += "." + mode;
        notypei18n += "." + mode;
      }
    }

    if (labels.containsKey(fulli18n)) return labels.getString(fulli18n);
    else if (labels.containsKey(notypei18n)) return labels.getString(notypei18n);
    else return labels.getString(s);
  }
Example #8
0
  /**
   * Returns a message if found or <code>null</code> if not.
   *
   * <p>Arguments <b>can</b> be specified which will be used to format the String. In the {@link
   * ResourceBundle} the String '{0}' (without ') will be replaced by the first argument, '{1}' with
   * the second and so on.
   */
  public static String getMessageOrNull(ResourceBundle bundle, String key, Object... arguments) {

    if (bundle.containsKey(key)) {
      return getMessage(bundle, key, arguments);
    } else {
      return null;
    }
  }
Example #9
0
 /**
  * Retrieve a i18n among the Collection of resourceBundle associated with the instance
  *
  * @param key
  * @param resourceBundleList
  * @return
  */
 private String retrieveI18nValue(String key, Collection<ResourceBundle> resourceBundleList) {
   for (ResourceBundle rb : resourceBundleList) {
     if (rb.containsKey(key)) {
       return rb.getString(key);
     }
   }
   return key;
 }
Example #10
0
  private static String getKey(ResourceBundle bundle, String elementName) {

    if (bundle.containsKey("useShortKeys") && "true".equals(bundle.getString("useShortKeys"))) {

      return elementName.substring(0, 1);
    }

    return elementName;
  }
Example #11
0
 @Override
 protected Object handleGetObject(String key) {
   if (bundle.containsKey(key)) {
     return bundle.getObject(key);
   }
   // TODO: Workarounds for https://github.com/kohsuke/args4j/issues/70
   // and https://github.com/kohsuke/args4j/issues/71
   return key;
 }
Example #12
0
 private String getLocaleString(String key) {
   if (!isLocale()) {
     return null;
   }
   String propertyKey = String.format("field.%s.%s", getReference(), key);
   return resourceBundle.containsKey(propertyKey)
       ? resourceBundle.getString(propertyKey)
       : propertyKey;
 }
 /**
  * Efficiently retrieve the String value for the specified key, or return {@code null} if not
  * found.
  *
  * <p>As of 4.2, the default implementation checks {@code containsKey} before it attempts to call
  * {@code getString} (which would require catching {@code MissingResourceException} for key not
  * found).
  *
  * <p>Can be overridden in subclasses.
  *
  * @param bundle the ResourceBundle to perform the lookup in
  * @param key the key to look up
  * @return the associated value, or {@code null} if none
  * @since 4.2
  * @see ResourceBundle#getString(String)
  * @see ResourceBundle#containsKey(String)
  */
 protected String getStringOrNull(ResourceBundle bundle, String key) {
   if (bundle.containsKey(key)) {
     try {
       return bundle.getString(key);
     } catch (MissingResourceException ex) {
       // Assume key not found for some other reason
       // -> do NOT throw the exception to allow for checking parent message source.
     }
   }
   return null;
 }
  public static String getBasePath() {

    ResourceBundle configuration = ResourceBundle.getBundle("applicationConfig");

    if (configuration.containsKey("FILE.PATH.DIR")) {

      return (String) configuration.getObject("FILE.PATH.DIR");
    }

    return null;
  }
Example #15
0
  private String getFormatted(String key, Object... arguments) {
    if (defaultMessages.containsKey(key)) {
      String result = defaultMessages.getString(key);
      if (arguments.length != 0) {
        // If there are arguments use messageformat to replace
        result = MessageFormat.format(result, arguments);
      }

      return result;
    }

    return "";
  }
Example #16
0
  private static String[] meridiems(Locale locale, TextWidth tw, OutputContext oc)
      throws MissingResourceException {

    ResourceBundle rb = getBundle(locale);

    if (rb != null) {
      if (tw == TextWidth.SHORT) {
        tw = TextWidth.ABBREVIATED;
      }

      String amKey = meridiemKey("am", tw, oc);
      String pmKey = meridiemKey("pm", tw, oc);

      if (rb.containsKey(amKey) && rb.containsKey(pmKey)) {
        String[] names = new String[2];
        names[0] = rb.getString(amKey);
        names[1] = rb.getString(pmKey);
        return names;
      }

      // fallback
      if (oc == OutputContext.STANDALONE) {
        if (tw == TextWidth.ABBREVIATED) {
          return meridiems(locale, tw, OutputContext.FORMAT);
        } else {
          return meridiems(locale, TextWidth.ABBREVIATED, oc);
        }
      } else if (tw != TextWidth.ABBREVIATED) {
        return meridiems(locale, TextWidth.ABBREVIATED, oc);
      }
    }

    throw new MissingResourceException(
        "Cannot find ISO-8601-resource for am/pm.",
        IsoTextProviderSPI.class.getName(),
        locale.toString());
  }
Example #17
0
  private static String[] lookupBundle(
      ResourceBundle rb,
      int len,
      String elementName,
      TextWidth tw,
      OutputContext oc,
      int baseIndex) {

    String[] names = new String[len];
    boolean shortKey = (elementName.length() == 1);

    for (int i = 0; i < len; i++) {
      StringBuilder b = new StringBuilder();
      b.append(elementName);
      b.append('(');

      if (shortKey) {
        char c = tw.name().charAt(0);

        if (oc != OutputContext.STANDALONE) {
          c = Character.toLowerCase(c);
        }

        b.append(c);
      } else {
        b.append(tw.name());

        if (oc == OutputContext.STANDALONE) {
          b.append('|');
          b.append(oc.name());
        }
      }

      b.append(')');
      b.append('_');
      b.append(i + baseIndex);
      String key = b.toString();

      if (rb.containsKey(key)) {
        names[i] = rb.getString(key);
      } else {
        return null;
      }
    }

    return names;
  }
Example #18
0
 /**
  * 构建redis集群配置信息
  *
  * @param bundle
  * @return
  */
 private List<JedisShardInfo> createJedisShardInfoList(ResourceBundle bundle) {
   List<JedisShardInfo> list = new LinkedList<JedisShardInfo>();
   String defaultRedisPort = bundle.getString("redis.port");
   for (int i = 0; i < 10; i++) {
     if (!bundle.containsKey("redis" + (i == 0 ? "" : i) + ".ip")) {
       continue;
     }
     String redisIp = bundle.getString("redis" + (i == 0 ? "" : i) + ".ip");
     String redisPort = bundle.getString("redis" + (i == 0 ? "" : i) + ".port");
     if (StringUtils.isEmpty(redisPort)) {
       redisPort = defaultRedisPort;
     }
     if (StringUtils.isNotEmpty(redisIp) && StringUtils.isNotEmpty(redisPort)) {
       JedisShardInfo jedisShardInfo = new JedisShardInfo(redisIp, redisPort);
       logger.info("初始化redis,redis" + (i == 0 ? "" : i) + ".ip:" + redisIp + ",端口:" + redisPort);
       list.add(jedisShardInfo);
     }
   }
   return list;
 }
  @Override
  public String get(HttpServletRequest request, String key, String defaultValue) {

    if ((request == null) || (key == null)) {
      return defaultValue;
    }

    PortletConfig portletConfig =
        (PortletConfig) request.getAttribute(JavaConstants.JAVAX_PORTLET_CONFIG);

    Locale locale = _getLocale(request);

    if (portletConfig == null) {
      return get(locale, key, defaultValue);
    }

    ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale);

    if (resourceBundle.containsKey(key)) {
      return _get(resourceBundle, key);
    }

    return get(locale, key, defaultValue);
  }
Example #20
0
 private String getResourceMessage(Locale locale) {
   ResourceBundle bundle = ResourceBundle.getBundle("DomainError", locale);
   return (bundle.containsKey(code.name()))
       ? bundle.getString(code.name())
       : "Missing message: " + code.name();
 }
Example #21
0
  @GET
  @Path("/installed")
  @Produces({MediaType.APPLICATION_JSON})
  public String getInstalledConnectors() {
    Guest guest = AuthHelper.getGuest();
    // If no guest is logged in, return empty array
    if (guest == null) return "[]";
    ResourceBundle res = ResourceBundle.getBundle("messages/connectors");
    try {
      List<ConnectorInfo> connectors = sysService.getConnectors();
      JSONArray connectorsArray = new JSONArray();
      for (int i = 0; i < connectors.size(); i++) {
        final ConnectorInfo connectorInfo = connectors.get(i);
        final Connector api = connectorInfo.getApi();
        if (api == null) {
          StringBuilder sb =
              new StringBuilder(
                  "module=API component=connectorStore action=getInstalledConnectors ");
          logger.warn("message=\"null connector for " + connectorInfo.getName() + "\"");
          continue;
        }
        if (!guestService.hasApiKey(guest.getId(), api)
            || api.getName().equals("facebook") /*HACK*/) {
          connectors.remove(i--);
        } else {
          ConnectorInfo connector = connectorInfo;
          JSONObject connectorJson = new JSONObject();
          Connector conn = Connector.fromValue(connector.api);
          ApiKey apiKey = guestService.getApiKey(guest.getId(), conn);

          connectorJson.accumulate("prettyName", conn.prettyName());
          List<String> facetTypes = new ArrayList<String>();
          ObjectType[] objTypes = conn.objectTypes();
          if (objTypes != null) {
            for (ObjectType obj : objTypes) {
              facetTypes.add(connector.connectorName + "-" + obj.getName());
            }
          }
          connectorJson.accumulate("facetTypes", facetTypes);
          connectorJson.accumulate(
              "status", apiKey.status != null ? apiKey.status.toString() : "NA");
          connectorJson.accumulate("name", connector.name);
          connectorJson.accumulate("connectUrl", connector.connectUrl);
          connectorJson.accumulate("image", connector.image);
          connectorJson.accumulate("connectorName", connector.connectorName);
          connectorJson.accumulate("enabled", connector.enabled);
          connectorJson.accumulate("manageable", connector.manageable);
          connectorJson.accumulate("text", connector.text);
          connectorJson.accumulate("api", connector.api);
          connectorJson.accumulate("apiKeyId", apiKey.getId());
          connectorJson.accumulate(
              "lastSync", connector.supportsSync ? getLastSync(apiKey) : Long.MAX_VALUE);
          connectorJson.accumulate("latestData", getLatestData(apiKey));
          final String auditTrail = checkForErrors(apiKey);
          connectorJson.accumulate("errors", auditTrail != null);
          connectorJson.accumulate("auditTrail", auditTrail != null ? auditTrail : "");
          connectorJson.accumulate("syncing", checkIfSyncInProgress(guest.getId(), conn));
          connectorJson.accumulate(
              "channels", settingsService.getChannelsForConnector(guest.getId(), conn));
          connectorJson.accumulate("sticky", connector.connectorName.equals("fluxtream_capture"));
          connectorJson.accumulate("supportsRenewToken", connector.supportsRenewTokens);
          connectorJson.accumulate("supportsSync", connector.supportsSync);
          connectorJson.accumulate("supportsFileUpload", connector.supportsFileUpload);
          connectorJson.accumulate("prettyName", conn.prettyName());
          final String uploadMessageKey = conn.getName() + ".upload";
          if (res.containsKey(uploadMessageKey)) {
            final String uploadMessage = res.getString(uploadMessageKey);
            connectorJson.accumulate("uploadMessage", uploadMessage);
          }
          connectorsArray.add(connectorJson);
        }
      }
      StringBuilder sb =
          new StringBuilder("module=API component=connectorStore action=getInstalledConnectors")
              .append(" guestId=")
              .append(guest.getId());
      logger.info(sb.toString());
      return connectorsArray.toString();
    } catch (Exception e) {
      StringBuilder sb =
          new StringBuilder("module=API component=connectorStore action=getInstalledConnectors")
              .append(" guestId=")
              .append(guest.getId())
              .append(" stackTrace=<![CDATA[")
              .append(Utils.stackTrace(e))
              .append("]]>");
      System.out.println(sb.toString());
      logger.warn(sb.toString());
      return gson.toJson(
          new StatusModel(false, "Failed to get installed connectors: " + e.getMessage()));
    }
  }
Example #22
0
 @Override
 public boolean containsKey(String key) {
   return bundle.containsKey(key);
 }