Beispiel #1
0
  public static boolean checkRequiredProperties(Properties props) {
    if (props.getProperty(WORKLOAD_PROPERTY) == null) {
      System.out.println("Missing property: " + WORKLOAD_PROPERTY);
      return false;
    }

    if (props.getProperty(ZIPFIAN_CONSTANT_PROPERTY) != null) {
      Double zipfian_constant = 0.0;
      try {
        zipfian_constant = Double.parseDouble(props.getProperty(ZIPFIAN_CONSTANT_PROPERTY));
      } catch (Exception ex) {
        System.out.println(
            "Invalid ZIPFIAN CONSTANT property format: " + ZIPFIAN_CONSTANT_PROPERTY);
        return false;
      }
      if (zipfian_constant <= 0.0) {
        System.out.println("Invalid ZIPFIAN CONSTANT property value: " + ZIPFIAN_CONSTANT_PROPERTY);
        return false;
      }
      // update the the default contant value
      com.yahoo.ycsb.generator.ZipfianGenerator.ZIPFIAN_CONSTANT = zipfian_constant;

      System.out.println("Reading zipfian constant prameter as: " + zipfian_constant);
    }

    return true;
  }
 public static String getNSSLibDir() throws Exception {
   Properties props = System.getProperties();
   String osName = props.getProperty("os.name");
   if (osName.startsWith("Win")) {
     osName = "Windows";
     NSPR_PREFIX = "lib";
   }
   String osid =
       osName
           + "-"
           + props.getProperty("os.arch")
           + "-"
           + props.getProperty("sun.arch.data.model");
   String ostype = osMap.get(osid);
   if (ostype == null) {
     System.out.println("Unsupported OS, skipping: " + osid);
     return null;
     //          throw new Exception("Unsupported OS " + osid);
   }
   if (ostype.length() == 0) {
     System.out.println("NSS not supported on this platform, skipping test");
     return null;
   }
   String libdir = NSS_BASE + SEP + "lib" + SEP + ostype + SEP;
   System.setProperty("pkcs11test.nss.libdir", libdir);
   return libdir;
 }
Beispiel #3
0
  /**
   * Loads the declarations of the script engines declared in a property set
   *
   * @param props property set containing the configuration
   * @throws ConfigurationException if the scripting languages cannot be loaded
   */
  private void loadScriptingLanguages(Properties props) throws ConfigurationException {
    String strEngineList = loadProperty(props, SCRIPT_ENGINE_LIST_P);

    for (StringTokenizer engineTokenizer = new StringTokenizer(strEngineList);
        engineTokenizer.hasMoreTokens(); ) {
      String engineBaseItem = engineTokenizer.nextToken();
      String engineName = props.getProperty(engineBaseItem + ".name"); // $NON-NLS-1$
      String engineClass = props.getProperty(engineBaseItem + ".class"); // $NON-NLS-1$
      String engineExtProps = props.getProperty(engineBaseItem + ".extensions"); // $NON-NLS-1$
      String[] extArray = null;
      if (engineExtProps != null) {
        List<String> extList = new ArrayList<String>();
        for (StringTokenizer extTokenizer = new StringTokenizer(engineExtProps);
            extTokenizer.hasMoreTokens(); ) {
          String extension = extTokenizer.nextToken();
          ext = extension;
          extList.add(extension);
        }
        extArray = extList.toArray(new String[0]);
      }
      BSFManager.registerScriptingEngine(engineName, engineClass, extArray);
      System.out.println("Script " + engineName + " loaded"); // $NON-NLS-1$ //$NON-NLS-2$
    }

    defaultEngineName = loadProperty(props, DFLT_SCRIPT_ENGINE_P);
  }
Beispiel #4
0
 public boolean onPartAll(String sender, String reason) {
   int d = channels.size();
   d--;
   for (int i = 0; i <= channels.size(); i++) {
     boolean f = inChannel(channels.get(d));
     if (!f) {
       return true;
     } else {
       try {
         if (reason == null) {
           this.partChannel(
               channels.get(i),
               config.getProperty("disconnect-message") + "  (Requested by " + sender + ")");
         } else {
           this.partChannel(
               channels.get(i),
               config.getProperty("disconnect-message")
                   + " (Reason: "
                   + reason
                   + "  (Requested by "
                   + sender
                   + "))");
         }
       } catch (Exception ex) {
         return true;
       }
     }
   }
   return false;
 }
Beispiel #5
0
  /** Sends Emails to Customers who have not submitted their Bears */
  public static void BearEmailSendMessage(String msgsubject, String msgText, String msgTo) {
    try {
      BearFrom = props.getProperty("BEARFROM");
      // To = props.getProperty("TO");
      SMTPHost = props.getProperty("SMTPHOST");
      Properties mailprops = new Properties();
      mailprops.put("mail.smtp.host", SMTPHost);

      // create some properties and get the default Session
      Session session = Session.getDefaultInstance(mailprops, null);

      // create a message
      Message msg = new MimeMessage(session);

      // set the from
      InternetAddress from = new InternetAddress(BearFrom);
      msg.setFrom(from);
      InternetAddress[] address = InternetAddress.parse(msgTo);
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject(msgsubject);
      msg.setContent(msgText, "text/plain");
      Transport.send(msg);
    } // end try
    catch (MessagingException mex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    } catch (Exception ex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    }
  } // end BearEmailSendMessage
Beispiel #6
0
 /**
  * Get TdbTitle name from properties alone.
  *
  * @param props a group of properties
  * @return
  */
 private String getTdbTitleName(Properties props) {
   // from auName and one of several properties
   String titleName = props.getProperty("journalTitle");
   if (titleName == null) {
     titleName = props.getProperty("journal.title"); // proposed to replace journalTitle
   }
   return titleName;
 }
Beispiel #7
0
  protected static void initSystemProperties(MoquiStart cl, boolean useProperties)
      throws IOException {
    Properties moquiInitProperties = new Properties();
    URL initProps = cl.getResource("MoquiInit.properties");
    if (initProps != null) {
      InputStream is = initProps.openStream();
      moquiInitProperties.load(is);
      is.close();
    }

    // before doing anything else make sure the moqui.runtime system property exists (needed for
    // config of various things)
    String runtimePath = System.getProperty("moqui.runtime");
    if (runtimePath != null && runtimePath.length() > 0)
      System.out.println("Determined runtime from system property: " + runtimePath);
    if (useProperties && (runtimePath == null || runtimePath.length() == 0)) {
      runtimePath = moquiInitProperties.getProperty("moqui.runtime");
      if (runtimePath != null && runtimePath.length() > 0)
        System.out.println("Determined runtime from MoquiInit.properties file: " + runtimePath);
    }
    if (runtimePath == null || runtimePath.length() == 0) {
      // see if runtime directory under the current directory exists, if not default to the current
      // directory
      File testFile = new File("runtime");
      if (testFile.exists()) runtimePath = "runtime";
      if (runtimePath != null && runtimePath.length() > 0)
        System.out.println("Determined runtime from existing runtime directory: " + runtimePath);
    }
    if (runtimePath == null || runtimePath.length() == 0) {
      runtimePath = ".";
      System.out.println("Determined runtime by defaulting to current directory: " + runtimePath);
    }
    File runtimeFile = new File(runtimePath);
    runtimePath = runtimeFile.getCanonicalPath();
    System.out.println("Canonicalized runtimePath: " + runtimePath);
    if (runtimePath.endsWith("/")) runtimePath = runtimePath.substring(0, runtimePath.length() - 1);
    System.setProperty("moqui.runtime", runtimePath);

    /* Don't do this here... loads as lower-level that WEB-INF/lib jars and so can't have dependencies on those,
        and dependencies on those are necessary
    // add runtime/lib jar files to the class loader
    File runtimeLibFile = new File(runtimePath + "/lib");
    for (File jarFile: runtimeLibFile.listFiles()) {
        if (jarFile.getName().endsWith(".jar")) cl.jarFileList.add(new JarFile(jarFile));
    }
    */

    // moqui.conf=conf/development/MoquiDevConf.xml
    String confPath = System.getProperty("moqui.conf");
    if (confPath == null || confPath.length() == 0) {
      confPath = moquiInitProperties.getProperty("moqui.conf");
    }
    if (confPath == null || confPath.length() == 0) {
      File testFile = new File(runtimePath + "/" + defaultConf);
      if (testFile.exists()) confPath = defaultConf;
    }
    if (confPath != null) System.setProperty("moqui.conf", confPath);
  }
  /**
   * Returns true iff all the files listed in this tracker's dependency list exist and are at the
   * same version as when they were recorded.
   *
   * @return a boolean
   */
  boolean isUpToDate(Properties properties) {
    Iterator e;

    // fixes bug 962
    {
      if (mProperties.size() != properties.size()) {
        mLogger.debug(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="my size " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                DependencyTracker.class.getName(),
                "051018-181",
                new Object[] {new Integer(mProperties.size())}));
        mLogger.debug(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="new size " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                DependencyTracker.class.getName(),
                "051018-189",
                new Object[] {new Integer(properties.size())}));
        return false;
      }

      for (e = mProperties.keySet().iterator(); e.hasNext(); ) {
        String key = (String) e.next();
        String val0 = mProperties.getProperty(key);
        String val1 = properties.getProperty(key);

        // val0 can't be null; properties don't allow that
        if (val1 == null || !val0.equals(val1)) {
          mLogger.debug(
              /* (non-Javadoc)
               * @i18n.test
               * @org-mes="Missing or changed property: " + p[0]
               */
              org.openlaszlo.i18n.LaszloMessages.getMessage(
                  DependencyTracker.class.getName(), "051018-207", new Object[] {val0}));
          return false;
        }
      }
    }

    for (e = mDependencies.iterator(); e.hasNext(); ) {
      FileInfo saved = (FileInfo) e.next();
      FileInfo current = new FileInfo(saved.mPathname);
      if (!saved.isUpToDate(current)) {
        mLogger.debug(saved.mPathname + " has changed");
        mLogger.debug("was " + saved.mLastMod);
        mLogger.debug(" is " + current.mLastMod);
        return false;
      }
    }
    return true;
  }
 public void initParam(String paramFile) throws Exception {
   // 使用Properties类来加载属性文件
   Properties props = new Properties();
   props.load(new FileInputStream(paramFile));
   driver = props.getProperty("driver");
   url = props.getProperty("url");
   user = props.getProperty("user");
   pass = props.getProperty("pass");
 }
 private String getValueFor(String property) {
   if (property == null) return null;
   String result = TestActivator.getContext().getProperty(property);
   if (result == null && archiveAndRepositoryProperties == null) return null;
   if (result == null) archiveAndRepositoryProperties.getProperty(property);
   if (result == null)
     result = archiveAndRepositoryProperties.getProperty(property + '.' + Platform.getOS());
   return result;
 }
  /**
   * Loads test configuration.
   *
   * @throws Exception if configuration is unawailable or broken.
   */
  private void loadTestConfiguration() throws Exception {
    assert TEST_CONFIGURATION_FILE.isFile();

    InputStream in = null;

    Properties p = new Properties();

    try {
      in = new FileInputStream(TEST_CONFIGURATION_FILE);

      p.load(in);
    } finally {
      U.closeQuiet(in);
    }

    clientNodes = Integer.parseInt(p.getProperty("client.nodes.count"));
    srvNodes = Integer.parseInt(p.getProperty("server.nodes.count"));
    threadsPerClient = Integer.parseInt(p.getProperty("threads.per.client"));
    cancelRate = Integer.parseInt(p.getProperty("cancel.rate"));
    submitDelay = Long.parseLong(p.getProperty("submit.delay"));

    taskParams =
        new GridJobLoadTestParams(
            Integer.parseInt(p.getProperty("jobs.count")),
            Integer.parseInt(p.getProperty("jobs.test.duration")),
            Integer.parseInt(p.getProperty("jobs.test.completion.delay")),
            Double.parseDouble(p.getProperty("jobs.failure.probability")));
  }
Beispiel #12
0
 public Configuration() {
   final Properties properties = new Properties();
   try {
     properties.load(new FileReader(getConfigurationFilePath()));
     username = properties.getProperty("username");
     password = properties.getProperty("password");
     from = LocalDate.parse(properties.getProperty("from"));
   } catch (IOException e) {
     System.out.println("No configuration file found.");
   }
 }
Beispiel #13
0
  Competition getDataFromDatabase(String arg, Properties properties) {
    Competition competition = new Competition();

    String getAthleteDataQuery =
        "SELECT athletes.name, athletes.dob, athletes.country_code, "
            + "results.race_100m, results.long_jump, results.shot_put, results.high_jump, results.race_400m, "
            + "results.hurdles_110m, results.discus_throw, results.pole_vault, results.javelin_throw, results.race_1500m "
            + "FROM athletes, results, competitions "
            + "WHERE athletes.id = results.athlete_id "
            + "AND results.competition_id = competitions.id "
            + "AND (competitions.id = ? OR competitions.name = ?)";

    Connection conn = null;

    try {
      String url = properties.getProperty("db.url");
      String username = properties.getProperty("db.username");
      String password = properties.getProperty("db.password");

      conn = DriverManager.getConnection(url, username, password);
      PreparedStatement athleteDataQuery = conn.prepareStatement(getAthleteDataQuery);
      athleteDataQuery.setString(1, arg);
      athleteDataQuery.setString(2, arg);
      ResultSet resultSet = athleteDataQuery.executeQuery();

      while (resultSet.next()) {
        Athlete athlete = parseAthlete(resultSet);
        if (athlete == null) {
          System.out.println(Error.ERROR_DB_ATHLETE_PARSING_FAILED.getErrorText());
          continue;
        }

        DecathlonEvents decathlonEvents = parseDecathlonEvents(resultSet);
        if (decathlonEvents == null) {
          System.out.println(Error.ERROR_DB_ATHLETE_RESULTS_PARSING_FAILED.getErrorText());
          continue;
        }
        athlete.setDecathlonEvent(decathlonEvents);

        competition.addAthlete(athlete);
      }
    } catch (SQLException e) {
      System.out.println(Error.ERROR_DB_CONNECTION.getErrorText());
    } finally {
      if (conn != null)
        try {
          conn.close();
        } catch (SQLException e) {
          System.out.println(Error.ERROR_DB_CLOSE.getErrorText());
        }
    }
    return competition;
  }
Beispiel #14
0
  public Response serve(
      String uri, String method, Properties header, Properties parms, Properties files) {

    if (parms.getProperty("cmd").equals("Play_Status")) {
      return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, connect.Play_Status);
    }
    if (parms.getProperty("cmd").equals("FinalScore")) {
      return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, String.valueOf(multiactivity.FinalScore));
    }

    return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, "A");
  }
  private void setupHomeDir(String homeString) {
    if (homeString == null) {
      homeString = sysProps.getProperty("swingri.home");
    }

    if (homeString != null) {
      dataDir = new File(homeString);
    } else {
      userHome = new File(sysProps.getProperty("user.home"));
      String dataDirStr = props.getString("application.datadir", DEFAULT_HOME_DIR);
      dataDir = new File(userHome, dataDirStr);
    }

    if (!dataDir.isDirectory()) {
      String path = dataDir.getAbsolutePath();
      boolean create;
      if (props.hasUserRejectedCreatingLocalDataDir()) {
        create = false;
      } else if (getBoolean("application.showLocalStorageDialogs", true)) {
        create =
            Resources.showConfirmDialog(
                null,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.createNewDirectory",
                path);
        if (!create) props.setUserRejectedCreatingLocalDataDir();
      } else {
        // Always create local-storage directory if show user prompt dialog setting is false.
        create = true;
      }

      if (!create) {
        dataDir = null;
      } else {
        dataDir.mkdirs();
        if (!dataDir.isDirectory()) {
          // check to make sure that dialog should be shown on the error.
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.failedCreation",
                dataDir.getAbsolutePath());
          }
          dataDir = null;
        }
      }
    }
  }
  public static void main(String[] args)
      throws IOException, ConfigurationException, CompressorException {
    long start = System.currentTimeMillis();
    SSEResidualKnowledgeBaseBuilder kbb = new SSEResidualKnowledgeBaseBuilder();

    Properties config = new Properties();
    String confFile = args[0];
    config.load(new FileInputStream(new File(confFile)));
    // add this properties to indexing.properties
    String sseResidualKBPath = config.getProperty("sse.residualkb", "").trim();
    String wikilinksFilePath = config.getProperty("sse.wikilinks", "").trim();

    // older implmentation of IndexWriter
    // kbb.writer = new IndexWriter(residualKBPath, new StandardAnalyzer(), true);

    StandardAnalyzer sa = new StandardAnalyzer(Version.LUCENE_36);
    Directory directory = FSDirectory.open(new File(sseResidualKBPath));
    kbb.writer = new IndexWriter(directory, sa, true, new IndexWriter.MaxFieldLength(25000));

    int numLines = kbb.countLines(wikilinksFilePath);
    BufferedReader bufferedReader = getBufferedReaderForBZ2File(wikilinksFilePath);
    String line = bufferedReader.readLine();
    LOG.info("Ignore the first line: " + line);
    line = bufferedReader.readLine();
    String uriPresent = line.split(" ")[0];
    String uriPast = uriPresent;
    ArrayList<String> wikilinks = new ArrayList<String>();
    for (int i = 1; i < numLines; i++) {
      if (i != numLines - 1) {
        if ((uriPresent.equals(uriPast))) {
          wikilinks.add(line.split(" ")[2]);
        } else {
          String mergedWikilist = kbb.filterWikiList(wikilinks);
          kbb.addADocument(kbb.cleanUri(uriPast), mergedWikilist);
          wikilinks = new ArrayList<String>();
          wikilinks.add(line.split(" ")[2]);
        }
        line = bufferedReader.readLine();
        uriPast = uriPresent;
        uriPresent = line.split(" ")[0];
      } else {
        wikilinks.add(line.split(" ")[2]);
        String mergedWikilist = kbb.filterWikiList(wikilinks);
        kbb.addADocument(kbb.cleanUri(uriPast), mergedWikilist);
      }
    }
    bufferedReader.close();
    kbb.writer.close();
    long stop = System.currentTimeMillis();
    long time = (stop - start) / (60 * 1000);
    System.out.println("Time elapsed: " + time + " minutes.");
  }
  public static void main(String[] args) {
    final Properties options = StringUtils.argsToProperties(args, argOptionDefs());
    if (args.length < 1 || options.containsKey("help")) {
      System.err.println(usage());
      return;
    }

    final Pattern posPattern =
        options.containsKey("searchPos") ? Pattern.compile(options.getProperty("searchPos")) : null;
    final Pattern wordPattern =
        options.containsKey("searchWord")
            ? Pattern.compile(options.getProperty("searchWord"))
            : null;
    final boolean plainPrint = PropertiesUtils.getBool(options, "plain", false);
    final boolean ner = PropertiesUtils.getBool(options, "ner", false);
    final boolean detailedAnnotations =
        PropertiesUtils.getBool(options, "detailedAnnotations", false);

    String[] remainingArgs = options.getProperty("").split(" ");
    List<File> fileList = new ArrayList<>();
    for (int i = 0; i < remainingArgs.length; i++) fileList.add(new File(remainingArgs[i]));

    final SpanishXMLTreeReaderFactory trf =
        new SpanishXMLTreeReaderFactory(true, true, ner, detailedAnnotations);
    ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    for (final File file : fileList) {
      pool.execute(
          new Runnable() {
            public void run() {
              try {
                Reader in =
                    new BufferedReader(
                        new InputStreamReader(new FileInputStream(file), "ISO-8859-1"));
                TreeReader tr = trf.newTreeReader(file.getPath(), in);
                process(file, tr, posPattern, wordPattern, plainPrint);
                tr.close();
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          });
    }

    pool.shutdown();
    try {
      pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Beispiel #18
0
  /** 利用属性文件中的信息连接数据库 * */
  public static Connection getConnection() throws SQLException, IOException {
    Properties props = new Properties();
    String fileName = "QueryDB.properties";
    FileInputStream in = new FileInputStream(fileName);
    props.load(in);

    String drivers = props.getProperty("jdbc.drivers");
    if (drivers != null) System.setProperty("jdbc.drivers", drivers);
    String url = props.getProperty("jdbc.url");
    String username = props.getProperty("jdbc.username");
    String password = props.getProperty("jdbc.password");

    return DriverManager.getConnection(url, username, password);
  }
  /**
   * Parse and validate the cli arguments
   *
   * @param ln parsed command line
   * @return parsed cli parameters wrapped in the CliParams
   * @throws InvalidArgumentException in case of nonexistent or incorrect cli args
   */
  protected CliParams parse(CommandLine ln, Properties defaults) throws InvalidArgumentException {
    l.debug("Parsing cli " + ln);
    CliParams cp = new CliParams();

    for (Option o : mandatoryOptions) {
      String name = o.getLongOpt();
      if (ln.hasOption(name)) cp.put(name, ln.getOptionValue(name));
      else if (defaults.getProperty(name) != null) {
        cp.put(name, defaults.getProperty(name));
      } else {
        throw new InvalidArgumentException("Missing the '" + name + "' commandline parameter.");
      }
    }

    for (Option o : optionalOptions) {
      String name = o.getLongOpt();
      if (ln.hasOption(name)) {
        cp.put(name, ln.getOptionValue(name));
      } else if (defaults.getProperty(name) != null) {
        cp.put(name, defaults.getProperty(name));
      }
    }

    if (cp.containsKey(CLI_PARAM_VERSION[0])) {
      l.info(
          "GoodData Notification Tool version 1.2.45"
              + ((BUILD_NUMBER.length() > 0) ? ", build " + BUILD_NUMBER : "."));
      System.exit(0);
    }

    // use default host if there is no host in the CLI params
    if (!cp.containsKey(CLI_PARAM_GDC_HOST[0])) {
      cp.put(CLI_PARAM_GDC_HOST[0], Defaults.DEFAULT_HOST);
    }

    l.debug("Using host " + cp.get(CLI_PARAM_GDC_HOST[0]));

    if (ln.getArgs().length == 0) {
      throw new InvalidArgumentException("No config file has been given, quitting.");
    }

    String configs = "";
    for (final String arg : ln.getArgs()) {
      if (configs.length() > 0) configs += "," + arg;
      else configs += arg;
    }
    cp.put(CLI_PARAM_CONFIG, configs);

    return cp;
  }
Beispiel #20
0
  public void loadProperty() {

    try {

      File file = new File(confFileName);

      log.debug("file=" + file.getAbsolutePath());

      confProperties = new Properties();
      confProperties.loadFromXML(new FileInputStream(file));

      bonitaApiHost = confProperties.getProperty("bonita.api.host");
      bonitaApiUsername = confProperties.getProperty("bonita.api.username");
      bonitaApiPassword = confProperties.getProperty("bonita.api.password");
      bonitaApiHttpUsername = confProperties.getProperty("bonita.api.http.username");
      bonitaApiHttpPassword = confProperties.getProperty("bonita.api.http.password");
      bonitaApiPath = confProperties.getProperty("bonita.api.path");

      rallyApiHost = confProperties.getProperty("rally.api.host");
      rallyApiHttpUsername = confProperties.getProperty("rally.api.http.username");
      rallyApiHttpPassword = confProperties.getProperty("rally.api.http.password");
      rallyProjectIds = confProperties.getProperty("rally.project.ids");

      // bonitaProcessId=properties.getProperty("bonita.process.xp_code.id");

      workflowServiceUrl = confProperties.getProperty("service.url");

    } catch (Exception e) {
      log.error("", e);
    }
  }
Beispiel #21
0
  /**
   * Gets a connection from the properties specified in the file database.properties
   *
   * @return the database connection
   */
  public static Connection getConnection() throws SQLException, IOException {
    Properties props = new Properties();
    try (InputStream in = Files.newInputStream(Paths.get("database.properties"))) {
      props.load(in);
    }

    String drivers = props.getProperty("jdbc.drivers");
    if (drivers != null) System.setProperty("jdbc.drivers", drivers);

    String url = props.getProperty("jdbc.url");
    String username = props.getProperty("jdbc.username");
    String password = props.getProperty("jdbc.password");

    return DriverManager.getConnection(url, username, password);
  }
Beispiel #22
0
 private String getProperty(String key, String defaultValue) {
   String property = properties.getProperty(key, defaultValue);
   if (property != null) {
     return substitute(property);
   }
   return property;
 }
Beispiel #23
0
 private void loadLanguageMappings(Properties props) {
   Enumeration<?> en = props.propertyNames();
   while (en.hasMoreElements()) {
     String propName = (String) en.nextElement();
     String propVal = props.getProperty(propName);
     if (propName.startsWith(".")) {
       // This is an extension mapping
       if (propName.equals(".")) {
         // The default mapping
         defaultLanguageImplName = propVal;
       } else {
         propName = propName.substring(1);
         extensionMappings.put(propName, propVal);
       }
     } else {
       // value is made up of an optional module name followed by colon followed by the
       // FQCN of the factory
       int colonIndex = propVal.lastIndexOf(COLON);
       String moduleName;
       String factoryName;
       if (colonIndex != -1) {
         moduleName = propVal.substring(0, colonIndex);
         factoryName = propVal.substring(colonIndex + 1);
       } else {
         throw new IllegalArgumentException(
             "Language mapping: " + propVal + " does not specify an implementing module");
       }
       LanguageImplInfo langImpl = new LanguageImplInfo(moduleName, factoryName);
       languageImpls.put(propName, langImpl);
       extensionMappings.put(propName, propName); // automatically register the name as a mapping
     }
   }
 }
  public void load() {
    datasources.clear();
    try {
      if (repoURL != null) {
        File[] files = new File(repoURL.getFile()).listFiles();

        for (File file : files) {
          if (!file.isHidden()) {
            Properties props = new Properties();
            props.load(new FileInputStream(file));
            String name = props.getProperty("name");
            String type = props.getProperty("type");
            if (name != null && type != null) {
              Type t = SaikuDatasource.Type.valueOf(type.toUpperCase());
              SaikuDatasource ds = new SaikuDatasource(name, t, props);
              datasources.put(name, ds);
            }
          }
        }
      } else {
        throw new Exception("repo URL is null");
      }
    } catch (Exception e) {
      throw new SaikuServiceException(e.getMessage(), e);
    }
  }
Beispiel #25
0
  /**
   * Get publisher name from properties and TdbAu. Creates a name based on title name if not
   * specified.
   *
   * @param props the properties
   * @param au the TdbAu
   * @return the publisher name
   */
  private String getTdbPublisherName(Properties props, TdbAu au) {
    // use "publisher" attribute if specified, or synthesize from titleName.
    // proposed to replace with publisher.name property
    String publisherName = props.getProperty("attributes.publisher");
    if (publisherName == null) {
      publisherName = props.getProperty("publisher.name"); // proposed new property
    }

    if (publisherName == null) {
      // create publisher name from title name if not specified
      String titleName = getTdbTitleName(props, au);
      publisherName = UNKNOWN_PUBLISHER_PREFIX + "[" + titleName + "]";
    }

    return publisherName;
  }
 private Map<String, Plugin> loadPluginsFromClasspath(Settings settings) {
   Map<String, Plugin> plugins = newHashMap();
   Enumeration<URL> pluginUrls = null;
   try {
     pluginUrls = settings.getClassLoader().getResources("es-plugin.properties");
   } catch (IOException e) {
     logger.warn("Failed to find plugins from classpath", e);
   }
   while (pluginUrls.hasMoreElements()) {
     URL pluginUrl = pluginUrls.nextElement();
     Properties pluginProps = new Properties();
     InputStream is = null;
     try {
       is = pluginUrl.openStream();
       pluginProps.load(is);
       String sPluginClass = pluginProps.getProperty("plugin");
       Class<?> pluginClass = settings.getClassLoader().loadClass(sPluginClass);
       Plugin plugin = (Plugin) pluginClass.newInstance();
       plugins.put(plugin.name(), plugin);
     } catch (Exception e) {
       logger.warn("Failed to load plugin from [" + pluginUrl + "]", e);
     } finally {
       if (is != null) {
         try {
           is.close();
         } catch (IOException e) {
           // ignore
         }
       }
     }
   }
   return plugins;
 }
 /** Sets Tesseract's internal parameters. */
 private void setTessVariables() {
   Enumeration<?> em = prop.propertyNames();
   while (em.hasMoreElements()) {
     String key = (String) em.nextElement();
     api.TessBaseAPISetVariable(handle, key, prop.getProperty(key));
   }
 }
Beispiel #28
0
 /**
  * Add set of properties to this object. This method will replace the value of any properties that
  * already existed.
  */
 public void setProperties(Properties props) {
   Enumeration names = props.propertyNames();
   while (names.hasMoreElements()) {
     String name = (String) names.nextElement();
     setProperty(name, props.getProperty(name));
   }
 }
    /**
     * 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;
    }
  static String getPropertyName(int propertyId, boolean bNamed) {
    if (bFirstTime) {
      bFirstTime = false;
      propertyNames = new Properties();
      try {
        InputStream propertyStream = PSTFile.class.getResourceAsStream("/PropertyNames.txt");
        if (propertyStream != null) {
          propertyNames.load(propertyStream);
        } else {
          propertyNames = null;
        }
      } catch (FileNotFoundException e) {
        propertyNames = null;
        e.printStackTrace();
      } catch (IOException e) {
        propertyNames = null;
        e.printStackTrace();
      }
    }

    if (propertyNames != null) {
      String key = String.format((bNamed ? "%08X" : "%04X"), propertyId);
      return propertyNames.getProperty(key);
    }

    return null;
  }