private List<String> getTopicTweets(HttpServletRequest request) throws ServletException {

    final String topicFile = request.getParameter("topicFile");
    final String fullFilePath = topicFile;
    List<String> listFiles = new ArrayList<String>();

    Properties properties = new Properties();

    try {
      properties.load(new FileInputStream(fullFilePath));
    } catch (FileNotFoundException e) {
      LOGGER.error("missing file for in topic tweets: '" + fullFilePath + "'" + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      LOGGER.error("can't read file for in topic tweets: '" + fullFilePath + "'" + e.getMessage());
      e.printStackTrace();
    }

    for (Entry<Object, Object> propertyEntry : properties.entrySet()) {
      String key = (String) propertyEntry.getKey();
      if (key.startsWith("inTopic")) {
        listFiles.add((String) propertyEntry.getValue());
      }
    }

    List<String> tweets = new ArrayList<String>();
    for (String filtFile : listFiles) {
      tweets.addAll(parseTweetsFromFile(filtFile));
    }
    return tweets;
  }
示例#2
0
 private void resolveVariables(Context ctx, Properties initProps) {
   for (Map.Entry<Object, Object> entry : initProps.entrySet()) {
     if (entry.getValue() != null) {
       entry.setValue(ctx.replaceTokens((String) entry.getValue()));
     }
   }
 }
  private BalanceElementExtractor() {
    InputStream inputStream = null;
    try {
      Properties prop = new Properties();
      String propFileName = "runtimecfg/balance_rules.properties";

      inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

      if (inputStream != null) {
        prop.load(inputStream);
        Set<Map.Entry<Object, Object>> set = prop.entrySet();
        for (Map.Entry<Object, Object> entry : set) {
          String[] values = entry.getValue().toString().split(";");
          for (String v : values) {
            extract(entry.getKey().toString().toUpperCase(), v);
          }
        }
      } else {
        throw new FileNotFoundException(
            "property file '" + propFileName + "' not found in the classpath");
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
示例#4
0
    /**
     * Parse the parameters of a connection into a CoreNLP properties file that can be passed into
     * {@link StanfordCoreNLP}, and used in the I/O stages.
     *
     * @param httpExchange The http exchange; effectively, the request information.
     * @return A {@link Properties} object corresponding to a combination of default and passed
     *     properties.
     * @throws UnsupportedEncodingException Thrown if we could not decode the key/value pairs with
     *     UTF-8.
     */
    private Properties getProperties(HttpExchange httpExchange)
        throws UnsupportedEncodingException {
      // Load the default properties
      Properties props = new Properties();
      defaultProps
          .entrySet()
          .stream()
          .forEach(
              entry -> props.setProperty(entry.getKey().toString(), entry.getValue().toString()));

      // Try to get more properties from query string.
      Map<String, String> urlParams = getURLParams(httpExchange.getRequestURI());
      if (urlParams.containsKey("properties")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      } else if (urlParams.containsKey("props")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      }

      // Make sure the properties compile
      props.setProperty(
          "annotators",
          StanfordCoreNLP.ensurePrerequisiteAnnotators(
              props.getProperty("annotators").split("[, \t]+")));

      return props;
    }
示例#5
0
  @Test
  public void testGetConnection() {

    String url = "jdbc:mysql://10.112.1.110:3306/test_mysql";
    String driver = "com.mysql.jdbc.Driver";
    String user = "******";
    String passwd = "111111";

    try {
      Class.forName(driver);
    } catch (Exception e) {
      System.out.println("Get Connection failed!!!");
    }

    try {
      Connection con = DriverManager.getConnection(url, user, passwd);

      System.out.println("Get Connection Success!!!");

      Properties properties = con.getClientInfo();
      Iterator<Map.Entry<Object, Object>> it = properties.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry<Object, Object> entry = it.next();
        System.out.println(entry.getKey() + "---------------" + entry.getValue());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private List<String> getOutOfTopicTweets(HttpServletRequest request) throws ServletException {

    String topicFile = request.getParameter("topicFile");

    List<String> listFiles = new ArrayList<String>();
    Properties properties = new Properties();
    try {
      properties.load(new FileInputStream(topicFile));
    } catch (FileNotFoundException e) {
      final String emsg =
          "missing file for out of topic tweets: '" + topicFile + "'" + e.getMessage();
      LOGGER.error(emsg);
      throw new ServletException(emsg, e);
    } catch (IOException e) {
      final String emsg =
          "can't read file for out of topic tweets: '" + topicFile + "'" + e.getMessage();
      LOGGER.error(emsg);
      throw new ServletException(emsg);
    }

    for (Entry<Object, Object> propertyEntry : properties.entrySet()) {
      String key = (String) propertyEntry.getKey();

      if (key.startsWith("outOfTopic")) {
        listFiles.add((String) propertyEntry.getValue());
      }
    }

    List<String> tweets = new ArrayList<String>();
    for (String filtFile : listFiles) {
      tweets.addAll(parseTweetsFromFile(filtFile));
    }
    return tweets;
  }
 private static void processSystemArguments(CommandLine allArgs) {
   Properties systemProps = allArgs.getSystemProperties();
   if (systemProps != null) {
     for (Map.Entry<Object, Object> entry : systemProps.entrySet()) {
       System.setProperty(entry.getKey().toString(), entry.getValue().toString());
     }
   }
 }
  public void loadFile(String filename) throws IOException {
    final Properties settings = new Properties();
    settings.load(new FileInputStream(filename));

    for (Iterator it = settings.entrySet().iterator(); it.hasNext(); ) {

      Map.Entry setting = (Map.Entry) it.next();
      putAny((String) setting.getKey(), (String) setting.getValue());
    }
  }
示例#9
0
 public static String expandProperties(String text) {
   if (StringUtil.isEmptyOrSpaces(text)) return text;
   Properties props = MavenServerUtil.collectSystemProperties();
   for (Map.Entry<Object, Object> each : props.entrySet()) {
     Object val = each.getValue();
     text =
         text.replace(
             "${" + each.getKey() + "}",
             val instanceof CharSequence ? (CharSequence) val : val.toString());
   }
   return text;
 }
示例#10
0
  public void buildCalc(InputStreamReader readerCmdList, CStackCalc calc) throws IOException {
    Properties cmdMap = new Properties(); // Перечень комманд калькулятора для создания.

    cmdMap.load(readerCmdList);
    Hashtable<FieldCmdKind, Object> fieldsValue =
        InitValuesFieldForCmd(); // Перечень пар (тип поля, значение для него) (инициализация полей
                                 // команды).

    for (Map.Entry<Object, Object> icmdList : cmdMap.entrySet()) {
      addCmdInCalc(calc, icmdList.getKey().toString(), icmdList.getValue().toString(), fieldsValue);
    }
  }
 private static Map<String, Object> createPropertyTypes(Properties properties) {
   Map<String, Object> propertyTypes = new LinkedHashMap<String, Object>();
   for (Map.Entry entry : properties.entrySet()) {
     String property = (String) entry.getKey();
     String className = (String) entry.getValue();
     Class clazz = resolveClassForTypeName(className);
     if (clazz != null) {
       propertyTypes.put(property, clazz);
     }
   }
   return propertyTypes;
 }
 /**
  * When launching a secondary runtime workbench, all projects already in dev mode must continue in
  * dev mode such that their class files are found.
  *
  * @param properties dev.properties
  */
 public static void weaveDevProperties(Properties properties) {
   if (fgIsDev) {
     Properties devProperties = getDevProperties();
     if (devProperties != null) {
       Set<?> entries = devProperties.entrySet();
       Iterator<?> iterator = entries.iterator();
       while (iterator.hasNext()) {
         Entry<?, ?> entry = (Entry<?, ?>) iterator.next();
         properties.setProperty((String) entry.getKey(), (String) entry.getValue());
       }
     }
   }
 }
示例#13
0
 protected Properties filterResponseProps(Properties props) {
   Properties res = new Properties();
   for (Map.Entry ent : props.entrySet()) {
     String key = (String) ent.getKey();
     if (StringUtil.startsWithIgnoreCase(key, "x-lockss")
         || StringUtil.startsWithIgnoreCase(key, "x_lockss")
         || key.equalsIgnoreCase("org.lockss.version.number")) {
       continue;
     }
     // We've lost the original case - capitalize them the way most people
     // expect
     res.put(StringUtil.titleCase(key, '-'), (String) ent.getValue());
   }
   return res;
 }
示例#14
0
  public static void main(final String[] args) throws IOException {
    Properties properties = new Properties();
    int n = args.length - 1;
    for (int i = 0; i < n - 1; ++i) {
      properties.load(new FileInputStream(args[i]));
    }

    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
      MAPPING.put((String) entry.getKey(), (String) entry.getValue());
    }

    final Set<String> unused = new HashSet<String>(MAPPING.keySet());

    File f = new File(args[n - 1]);
    File d = new File(args[n]);

    optimize(
        f,
        d,
        new SimpleRemapper(MAPPING) {
          @Override
          public String map(String key) {
            String s = super.map(key);
            if (s != null) {
              unused.remove(key);
            }
            return s;
          }
        });

    Iterator<String> i = unused.iterator();
    while (i.hasNext()) {
      String s = i.next();
      if (!s.endsWith("/remove")) {
        System.out.println("INFO: unused mapping " + s);
      }
    }
  }
 /**
  * This method used to extract properties from request context
  *
  * @param requestContext Request Context
  * @return Extracted Properties
  */
 private static Properties copyProperties(RequestContext requestContext) {
   Properties properties = requestContext.getResource().getProperties();
   Properties copiedProperties = new Properties();
   if (properties != null) {
     List<String> linkProperties =
         Arrays.asList(
             RegistryConstants.REGISTRY_LINK,
             RegistryConstants.REGISTRY_USER,
             RegistryConstants.REGISTRY_MOUNT,
             RegistryConstants.REGISTRY_AUTHOR,
             RegistryConstants.REGISTRY_MOUNT_POINT,
             RegistryConstants.REGISTRY_TARGET_POINT,
             RegistryConstants.REGISTRY_ACTUAL_PATH,
             RegistryConstants.REGISTRY_REAL_PATH);
     for (Map.Entry<Object, Object> e : properties.entrySet()) {
       String key = (String) e.getKey();
       if (!linkProperties.contains(key)
           && !(key.startsWith("resource") || key.startsWith("registry"))) {
         copiedProperties.put(key, (List<String>) e.getValue());
       }
     }
   }
   return copiedProperties;
 }
示例#16
0
 @Override
 public Map<String, String> getSystemProperties(CallingContext context, List<String> keys) {
   Map<String, String> ret = new TreeMap<String, String>();
   if (keys.isEmpty()) {
     ret.putAll(System.getenv());
     Properties p = System.getProperties();
     for (Map.Entry<Object, Object> prop : p.entrySet()) {
       ret.put(prop.getKey().toString(), prop.getValue().toString());
     }
   } else {
     for (String k : keys) {
       String val = System.getenv(k);
       if (val != null) {
         ret.put(k, System.getenv(k));
       } else {
         String prop = System.getProperty(k);
         if (prop != null) {
           ret.put(k, prop);
         }
       }
     }
   }
   return ret;
 }
示例#17
0
  @SuppressWarnings("unchecked")
  private static <T> List<T> loadServices(Class<T> clazz) {
    final Map<T, Double> services = new IdentityHashMap<T, Double>();
    Enumeration<URL> resourceList;
    try {
      resourceList =
          clazz
              .getClassLoader()
              .getResources("META-INF/services/" + clazz.getName() + ".properties");
    } catch (IOException e) {
      throw new RegisteredExceptionWrapper("Could not load resources for " + clazz, e);
    }
    while (resourceList.hasMoreElements()) {
      URL resource = resourceList.nextElement();
      Properties properties = new Properties();
      try {
        properties.load(resource.openStream());
      } catch (IOException e) {
        LOG.log(Level.WARNING, "Could not load service list for " + clazz + " from " + resource, e);
      }
      for (Entry<Object, Object> e : properties.entrySet()) {
        T service;
        try {
          service = (T) Class.forName(e.getKey().toString()).newInstance();
        } catch (Exception ex) {
          LOG.log(
              Level.WARNING,
              "Service "
                  + e.getKey()
                  + " defined in "
                  + resource
                  + " could not be loaded and was skipped",
              ex);
          continue;
        }
        Double priority;
        try {
          priority = Double.valueOf(e.getValue().toString());
        } catch (NumberFormatException ex) {
          LOG.warning(
              "Service "
                  + e.getKey()
                  + " defined in "
                  + resource
                  + " has invalid priority "
                  + e.getValue()
                  + ": "
                  + ex.getMessage()
                  + " Default priority used");
          priority = 0.0;
        }
        services.put(service, priority);
      }
    }
    List<T> rc = new ArrayList<T>(services.keySet());
    Collections.sort(
        rc,
        new Comparator<T>() {

          public int compare(T o1, T o2) {
            return services.get(o2).compareTo(services.get(o1));
          }
        });
    return Collections.unmodifiableList(rc);
  }
 /** Sets all the provided settings. */
 public Builder put(Properties properties) {
   for (Map.Entry entry : properties.entrySet()) {
     map.put((String) entry.getKey(), (String) entry.getValue());
   }
   return this;
 }
示例#19
0
  /** Generate the XML report from all the test results */
  protected static void generateReport(
      Writer out, String classname, List<TestCase> results, Reader stdout, Reader stderr)
      throws IOException {
    int num_failures = getFailures(results);
    int num_skips = getSkips(results);
    int num_errors = getErrors(results);
    long total_time = getTotalTime(results);

    try {
      out.write(XML_DEF + "\n");

      out.write(
          "\n<testsuite "
              + "name=\""
              + classname
              + "\" "
              + "tests=\""
              + results.size()
              + "\" "
              + "failures=\""
              + num_failures
              + "\" "
              + "errors=\""
              + num_errors
              + "\" "
              + "skips=\""
              + num_skips
              + "\" "
              + "time=\""
              + (total_time / 1000.0)
              + "\">");

      out.write("\n<properties>");
      Properties props = System.getProperties();

      for (Map.Entry<Object, Object> tmp : props.entrySet()) {
        out.write(
            "\n    <property name=\""
                + tmp.getKey()
                + "\""
                + " value=\""
                + tmp.getValue()
                + "\"/>");
      }
      out.write("\n</properties>\n");

      for (TestCase result : results) {
        if (result == null) continue;

        try {
          writeTestCase(out, result);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      if (stdout != null) writeOutput(1, stdout, out);
      if (stderr != null) writeOutput(2, stderr, out);
    } finally {
      out.write("\n</testsuite>\n");
    }
  }
示例#20
0
  /**
   * Create a new TdbAu instance from the properties.
   *
   * @param props the properties
   * @return a TdbAu instance set built from the properties
   */
  private TdbAu newTdbAu(Properties props) {
    String pluginId = (String) props.get("plugin");
    if (pluginId == null) {
      throw new IllegalArgumentException("TdbAu plugin ID not specified");
    }

    String auName = props.getProperty("title");
    if (auName == null) {
      throw new IllegalArgumentException("TdbAu title not specified");
    }

    // create a new TdbAu and set its elements
    TdbAu au = new TdbAu(auName, pluginId);

    // process attrs, and params
    Map<String, Map<String, String>> paramMap = new HashMap<String, Map<String, String>>();
    for (Map.Entry<Object, Object> entry : props.entrySet()) {
      String key = String.valueOf(entry.getKey());
      String value = String.valueOf(entry.getValue());
      if (key.startsWith("attributes.")) {
        // set attributes directly
        String name = key.substring("attributes.".length());
        try {
          au.setAttr(name, value);
        } catch (TdbException ex) {
          logger.warning(
              "Cannot set attribute \"" + name + "\" with value \"" + value + "\" -- ignoring");
        }

      } else if (key.startsWith("param.")) {
        // skip to param name
        String param = key.substring("param.".length());
        int i;
        if (((i = param.indexOf(".key")) < 0) && ((i = param.indexOf(".value")) < 0)) {
          logger.warning(
              "Ignoring unexpected param key for au \""
                  + auName
                  + "\" key: \""
                  + key
                  + "\" -- ignoring");
        } else {
          // get param map for pname
          String pname = param.substring(0, i);
          Map<String, String> pmap = paramMap.get(pname);
          if (pmap == null) {
            pmap = new HashMap<String, String>();
            paramMap.put(pname, pmap);
          }
          // add name and value to param map for pname
          String name = param.substring(i + 1);
          pmap.put(name, value);
        }

      } else if (!key.equals("title") // TdbAu has "name" property
          && !key.equals("plugin") // TdbAu has "pluginId" property
          && !key.equals("journalTitle") // TdbAu has "title" TdbTitle property
          && !key.startsWith("journal.")) { // TdbAu has "title" TdbTitle property
        // translate all other properties into AU properties
        try {
          au.setPropertyByName(key, value);
        } catch (TdbException ex) {
          logger.warning(
              "Cannot set property \"" + key + "\" with value \"" + value + "\" -- ignoring");
        }
      }
    }

    // set param from accumulated "key", and "value" entries
    for (Map<String, String> pmap : paramMap.values()) {
      String name = pmap.get("key");
      String value = pmap.get("value");
      if (name == null) {
        logger.warning("Ignoring property with null name");
      } else if (value == null) {
        logger.warning("Ignoring property \"" + name + "\" with null value");
      } else {
        try {
          au.setParam(name, value);
        } catch (TdbException ex) {
          logger.warning(
              "Cannot set param \"" + name + "\" with value \"" + value + "\" -- ignoring");
        }
      }
    }

    return au;
  }
  public static void main(String[] args) throws Exception {
    // See : http://patorjk.com/software/taag/#p=display&f=Slant&t=Flamingo%20Collector
    System.out.println(
        "   _  __              ____                  _      _             _                _____                          \n"
            + "  | |/ /__  ____     / __ \\_________ _   __(_)____(_)___  ____  (_)___  ____ _   / ___/___  ______   _____  _____\n"
            + "  |   / _ \\/ __ \\   / /_/ / ___/ __ \\ | / / / ___/ / __ \\/ __ \\/ / __ \\/ __ `/   \\__ \\/ _ \\/ ___/ | / / _ \\/ ___/\n"
            + " /   /  __/ / / /  / ____/ /  / /_/ / |/ / (__  ) / /_/ / / / / / / / / /_/ /   ___/ /  __/ /   | |/ /  __/ /    \n"
            + "/_/|_\\___/_/ /_/  /_/   /_/   \\____/|___/_/____/_/\\____/_/ /_/_/_/ /_/\\__, /   /____/\\___/_/    |___/\\___/_/     \n"
            + "                                                                     /____/                                      \n");

    ////////////////////////////////////////////////////////////////////////////////////

    StringBuilder builder = new StringBuilder();
    printHeader(builder, "Application Information");

    Properties appProps = new Properties();
    Properties systemProperties = System.getProperties();
    appProps.put(
        "Java Version",
        systemProperties.getProperty("java.version", UNKNOWN)
            + " - "
            + systemProperties.getProperty("java.vendor", UNKNOWN));
    appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN));

    print(builder, appProps);

    Properties memPros = new Properties();
    final Runtime rt = Runtime.getRuntime();
    final long maxMemory = rt.maxMemory() / MEGA_BYTES;
    final long totalMemory = rt.totalMemory() / MEGA_BYTES;
    final long freeMemory = rt.freeMemory() / MEGA_BYTES;
    final long usedMemory = totalMemory - freeMemory;

    memPros.put("Maximum Allowable Memory", maxMemory + "MB");
    memPros.put("Total Memory", totalMemory + "MB");
    memPros.put("Free Memory", freeMemory + "MB");
    memPros.put("Used Memory", usedMemory + "MB");

    print(builder, memPros);

    printHeader(builder, "Java System Properties");
    Properties sysProps = new Properties();
    for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) {
      sysProps.put(entry.getKey(), entry.getValue());
    }

    print(builder, sysProps);

    printHeader(builder, "System Environments");
    Map<String, String> getenv = System.getenv();
    Properties envProps = new Properties();
    Set<String> strings = getenv.keySet();
    for (String key : strings) {
      String message = getenv.get(key);
      envProps.put(key, message);
    }

    print(builder, envProps);

    System.out.println(builder.toString());

    ////////////////////////////////////////////////////////////////////////////////////

    NativeLoader.loadSigarNative();

    ////////////////////////////////////////////////////////////////////////////////////

    SpringApplication app = new SpringApplication(Application.class);
    app.setShowBanner(false);
    ApplicationContext ctx = app.run(args);

    try {
      LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
      for (Logger LOGGER : context.getLoggerList()) {
        if (LOGGER instanceof ch.qos.logback.classic.Logger) {
          ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) LOGGER;
          for (Iterator<Appender<ILoggingEvent>> index = logbackLogger.iteratorForAppenders();
              index.hasNext(); ) {
            Appender<ILoggingEvent> appender = index.next();
            if ("FILE".equals(appender.getName())
                && appender instanceof ch.qos.logback.core.rolling.RollingFileAppender) {
              ch.qos.logback.core.rolling.RollingFileAppender logbackAppender =
                  (ch.qos.logback.core.rolling.RollingFileAppender) appender;
              logger.info("Log file is {}", logbackAppender.getFile());
            }
          }
        }
      }
    } catch (Exception ex) {
    }
  }
示例#22
0
  /**
   * Add a TdbAu to a TdbTitle and TdbPubisher, and add links to the TdbTitle specified by the
   * properties.
   *
   * @param props the properties
   * @param au the TdbAu to add
   * @throws TdbException if the AU already exists in this Tdb
   */
  private void addTdbAu(Properties props, TdbAu au) throws TdbException {
    // add au for plugin assuming it is not a duplicate
    if (!addTdbAuForPlugin(au)) {
      // au already registered -- report existing au
      TdbAu existingAu = findExistingTdbAu(au);
      String titleName = getTdbTitleName(props, au);
      if (!titleName.equals(existingAu.getTdbTitle().getName())) {
        throw new TdbException(
            "Cannot add duplicate au entry: \""
                + au.getName()
                + "\" for title \""
                + titleName
                + "\" with same definition as existing au entry: \""
                + existingAu.getName()
                + "\" for title \""
                + existingAu.getTdbTitle().getName()
                + "\" to title database");
      } else if (!existingAu.getName().equals(au.getName())) {
        // error because it could lead to a missing AU -- one probably has a typo
        throw new TdbException(
            "Cannot add duplicate au entry: \""
                + au.getName()
                + "\" with the same definition as \""
                + existingAu.getName()
                + "\" for title \""
                + titleName
                + "\" to title database");
      } else {
        throw new TdbException(
            "Cannot add duplicate au entry: \""
                + au.getName()
                + "\" for title \""
                + titleName
                + "\" to title database");
      }
    }

    // get or create the TdbTitle for this
    TdbTitle title = getTdbTitle(props, au);
    try {
      // add AU to title
      title.addTdbAu(au);
    } catch (TdbException ex) {
      // if we can't add au to title, remove for plugin and re-throw exception
      removeTdbAuForPlugin(au);
      throw ex;
    }

    // process title links
    Map<String, Map<String, String>> linkMap = new HashMap<String, Map<String, String>>();
    for (Map.Entry<Object, Object> entry : props.entrySet()) {
      String key = "" + entry.getKey();
      String value = "" + entry.getValue();
      if (key.startsWith("journal.link.")) {
        // skip to link name
        String param = key.substring("link.".length());
        int i;
        if (((i = param.indexOf(".type")) < 0) && ((i = param.indexOf(".journalId")) < 0)) {
          logger.warning(
              "Ignoring nexpected link key for au \"" + au.getName() + "\" key: \"" + key + "\"");
        } else {
          // get link map for linkName
          String lname = param.substring(0, i);
          Map<String, String> lmap = linkMap.get(lname);
          if (lmap == null) {
            lmap = new HashMap<String, String>();
            linkMap.put(lname, lmap);
          }
          // add name and value to link map for link
          String name = param.substring(i + 1);
          lmap.put(name, value);
        }
      }
    }

    // add links to title from accumulated "type", "journalId" entries
    for (Map<String, String> lmap : linkMap.values()) {
      String name = lmap.get("type");
      String value = lmap.get("journalId");
      if ((name != null) && (value != null)) {
        try {
          TdbTitle.LinkType linkType = TdbTitle.LinkType.valueOf(name);
          title.addLinkToTdbTitleId(linkType, value);
        } catch (IllegalArgumentException ex) {
          logger.warning(
              "Ignoring unknown link type for au \"" + au.getName() + "\" name: \"" + name + "\"");
        }
      }
    }
  }
示例#23
0
  @Override
  public void onApplicationStart() {

    // must check and configure JPA for each DBConfig
    for (DBConfig dbConfig : DB.getDBConfigs()) {
      // check and enable JPA on this config

      // is JPA already configured?
      String configName = dbConfig.getDBConfigName();

      if (JPA.getJPAConfig(configName, true) == null) {
        // must configure it

        // resolve prefix for hibernate config..
        // should be nothing for default, and db_<name> for others
        String propPrefix = "";
        if (!DBConfig.defaultDbConfigName.equalsIgnoreCase(configName)) {
          propPrefix = "db_" + configName + ".";
        }
        List<Class> classes = findEntityClassesForThisConfig(configName, propPrefix);
        if (classes == null) continue;

        // we're ready to configure this instance of JPA
        final String hibernateDataSource =
            Play.configuration.getProperty(propPrefix + "hibernate.connection.datasource");

        if (StringUtils.isEmpty(hibernateDataSource) && dbConfig == null) {
          throw new JPAException(
              "Cannot start a JPA manager without a properly configured database"
                  + getConfigInfoString(configName),
              new NullPointerException("No datasource configured"));
        }

        Ejb3Configuration cfg = new Ejb3Configuration();

        if (dbConfig.getDatasource() != null) {
          cfg.setDataSource(dbConfig.getDatasource());
        }

        if (!Play.configuration
            .getProperty(propPrefix + "jpa.ddl", Play.mode.isDev() ? "update" : "none")
            .equals("none")) {
          cfg.setProperty(
              "hibernate.hbm2ddl.auto",
              Play.configuration.getProperty(propPrefix + "jpa.ddl", "update"));
        }

        String driver = null;
        if (StringUtils.isEmpty(propPrefix)) {
          driver = Play.configuration.getProperty("db.driver");
        } else {
          driver = Play.configuration.getProperty(propPrefix + "driver");
        }
        cfg.setProperty("hibernate.dialect", getDefaultDialect(propPrefix, driver));
        cfg.setProperty("javax.persistence.transaction", "RESOURCE_LOCAL");

        cfg.setInterceptor(new PlayInterceptor());

        // This setting is global for all JPAs - only configure if configuring default JPA
        if (StringUtils.isEmpty(propPrefix)) {
          if (Play.configuration.getProperty(propPrefix + "jpa.debugSQL", "false").equals("true")) {
            org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.ALL);
          } else {
            org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.OFF);
          }
        }
        // inject additional  hibernate.* settings declared in Play! configuration
        Properties additionalProperties =
            (Properties)
                Utils.Maps.filterMap(Play.configuration, "^" + propPrefix + "hibernate\\..*");
        // We must remove prefix from names
        Properties transformedAdditionalProperties = new Properties();
        for (Map.Entry<Object, Object> entry : additionalProperties.entrySet()) {
          Object key = entry.getKey();
          if (!StringUtils.isEmpty(propPrefix)) {
            key = ((String) key).substring(propPrefix.length()); // chop off the prefix
          }
          transformedAdditionalProperties.put(key, entry.getValue());
        }
        cfg.addProperties(transformedAdditionalProperties);

        try {
          // nice hacking :) I like it..
          Field field = cfg.getClass().getDeclaredField("overridenClassLoader");
          field.setAccessible(true);
          field.set(cfg, Play.classloader);
        } catch (Exception e) {
          Logger.error(
              e, "Error trying to override the hibernate classLoader (new hibernate version ???)");
        }

        for (Class<?> clazz : classes) {
          cfg.addAnnotatedClass(clazz);
          if (Logger.isTraceEnabled()) {
            Logger.trace("JPA Model : %s", clazz);
          }
        }
        String[] moreEntities =
            Play.configuration.getProperty(propPrefix + "jpa.entities", "").split(", ");
        for (String entity : moreEntities) {
          if (entity.trim().equals("")) {
            continue;
          }
          try {
            cfg.addAnnotatedClass(Play.classloader.loadClass(entity));
          } catch (Exception e) {
            Logger.warn("JPA -> Entity not found: %s", entity);
          }
        }

        for (ApplicationClass applicationClass : Play.classes.all()) {
          if (applicationClass.isClass() || applicationClass.javaPackage == null) {
            continue;
          }
          Package p = applicationClass.javaPackage;
          Logger.info("JPA -> Adding package: %s", p.getName());
          cfg.addPackage(p.getName());
        }

        String mappingFile = Play.configuration.getProperty(propPrefix + "jpa.mapping-file", "");
        if (mappingFile != null && mappingFile.length() > 0) {
          cfg.addResource(mappingFile);
        }

        if (Logger.isTraceEnabled()) {
          Logger.trace("Initializing JPA" + getConfigInfoString(configName) + " ...");
        }

        try {
          JPA.addConfiguration(configName, cfg);
        } catch (PersistenceException e) {
          throw new JPAException(
              e.getMessage() + getConfigInfoString(configName),
              e.getCause() != null ? e.getCause() : e);
        }
      }
    }

    // must look for Entity-objects referring to none-existing JPAConfig
    List<Class> allEntityClasses = Play.classloader.getAnnotatedClasses(Entity.class);
    for (Class clazz : allEntityClasses) {
      String configName = Entity2JPAConfigResolver.getJPAConfigNameForEntityClass(clazz);
      if (JPA.getJPAConfig(configName, true) == null) {
        throw new JPAException(
            "Found Entity-class ("
                + clazz.getName()
                + ") referring to none-existing JPAConfig"
                + getConfigInfoString(configName)
                + ". "
                + "Is JPA properly configured?");
      }
    }
  }
  public HashMap<String, Properties> generateResourceBundle(String baseName)
      throws GenerationException {
    // be sure to have at least the default URI constant settings
    if (uriGeneration == null) {
      uriGeneration = GenerationSetting.createDefault(caseFormat, "", "");
    }
    Pattern pattern = Pattern.compile(Pattern.quote(getPrefix()) + "(.+)");
    HashMap<String, URI> splitUris = new HashMap<>();
    for (Resource nextSubject : model.subjects()) {
      if (nextSubject instanceof URI) {
        Matcher matcher = pattern.matcher(nextSubject.stringValue());
        if (matcher.find()) {
          String k = matcher.group(1);
          splitUris.put(k, (URI) nextSubject);
        }
      }
    }

    List<String> keys = new ArrayList<>();
    keys.addAll(splitUris.keySet());
    Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);

    HashMap<String, Properties> bundles = new HashMap<>();
    // Default we have for sure
    bundles.put(baseName, new Properties());
    for (String key : keys) {
      final URI resource = splitUris.get(key);
      //
      String nextKey = cleanKey(doCaseFormatting(key, uriGeneration.getCaseFormat()));

      for (URI p : LABEL_PROPERTIES) {
        for (Value v : GraphUtil.getObjects(model, resource, p)) {
          if (v instanceof Literal) {
            final Literal lit = (Literal) v;
            final String lang = lit.getLanguage();
            final Properties bundle;
            if (lang == null) {
              bundle = bundles.get(baseName);
            } else if (bundles.containsKey(baseName + "_" + lang)) {
              bundle = bundles.get(baseName + "_" + lang);
            } else {
              bundle = new Properties();
              bundles.put(baseName + "_" + lang, bundle);
            }

            if (!bundle.containsKey(nextKey + ".label")) {
              bundle.put(nextKey + ".label", lit.getLabel().replaceAll("\\s+", " "));
            }
          }
        }
      }

      for (URI p : COMMENT_PROPERTIES) {
        for (Value v : GraphUtil.getObjects(model, resource, p)) {
          if (v instanceof Literal) {
            final Literal lit = (Literal) v;
            final String lang = lit.getLanguage();
            final Properties bundle;
            if (lang == null) {
              bundle = bundles.get(baseName);
            } else if (bundles.containsKey(baseName + "_" + lang)) {
              bundle = bundles.get(baseName + "_" + lang);
            } else {
              bundle = new Properties();
              bundles.put(baseName + "_" + lang, bundle);
            }

            if (!bundle.containsKey(nextKey + ".comment")) {
              bundle.put(nextKey + ".comment", lit.getLabel().replaceAll("\\s+", " "));
            }
          }
        }
      }
    }

    if (getPreferredLanguage() != null) {
      log.debug("completing default Bundle with preferred language {}", getPreferredLanguage());
      final Properties defaultBundle = bundles.get(baseName);
      final Properties prefBundle = bundles.get(baseName + "_" + getPreferredLanguage());
      if (prefBundle != null) {
        for (Entry<Object, Object> key : prefBundle.entrySet()) {
          String nextKey = (String) key.getKey();
          if (!defaultBundle.containsKey(nextKey)) {
            log.trace("copying {} from {} to default Bundle", nextKey, getPreferredLanguage());
            defaultBundle.setProperty(nextKey, (String) key.getValue());
          }
        }
      } else {
        log.warn("No Bundle data found for preferred language {}", getPreferredLanguage());
      }
    }
    return bundles;
  }