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;
  }
示例#2
0
  public static void main(String[] args) throws MessagingException, IOException {
    Properties props = new Properties();
    try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) {
      props.load(in);
    }
    List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8"));

    String from = lines.get(0);
    String to = lines.get(1);
    String subject = lines.get(2);

    StringBuilder builder = new StringBuilder();
    for (int i = 3; i < lines.size(); i++) {
      builder.append(lines.get(i));
      builder.append("\n");
    }

    Console console = System.console();
    String password = new String(console.readPassword("Password: "));

    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(builder.toString());
    Transport tr = mailSession.getTransport();
    try {
      tr.connect(null, password);
      tr.sendMessage(message, message.getAllRecipients());
    } finally {
      tr.close();
    }
  }
  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);
    }
  }
示例#4
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);
  }
示例#5
0
  public static void main(String[] args) throws IOException {
    PrintWriter out;
    if (args.length > 1) {
      out = new PrintWriter(args[1]);
    } else {
      out = new PrintWriter(System.out);
    }
    PrintWriter xmlOut = null;
    if (args.length > 2) {
      xmlOut = new PrintWriter(args[2]);
    }
    Properties props = new Properties();
    props.put("annotators", "tokenize, ssplit, pos, lemma, ner,parse");
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
    Annotation annotation;
    if (args.length > 0) {
      annotation = new Annotation(IOUtils.slurpFileNoExceptions(args[0]));
    } else {
      annotation =
          new Annotation(
              "Kosgi Santosh sent an email to Stanford University. He didn't get a reply.");
    }

    pipeline.annotate(annotation);
    pipeline.prettyPrint(annotation, out);
  }
    public void write(final BufferedWriter w) {
      RW.writeln(w, "Module:" + myName);

      RW.writeln(w, "SourceProperties:");
      mySource.write(w);

      RW.writeln(w, "TestProperties:");
      myTest.write(w);

      RW.writeln(w, "Excludes:");
      RW.writeln(w, myExcludes, RW.fromString);

      RW.writeln(w, "Libraries:");
      RW.writeln(w, myLibraries);

      RW.writeln(w, "Dependencies:");

      final List<ClasspathItemWrapper> weakened = new ArrayList<ClasspathItemWrapper>();

      for (ClasspathItemWrapper cpiw : dependsOn(false)) {
        weakened.add(weaken(cpiw));
      }

      RW.writeln(w, weakened);

      weakened.clear();

      for (ClasspathItemWrapper cpiw : dependsOn(true)) {
        weakened.add(weaken(cpiw));
      }

      RW.writeln(w, weakened);
    }
    public Set<String> getSources(final boolean tests) {
      if (tests) {
        return myTest.getFiles();
      }

      return mySource.getFiles();
    }
示例#8
0
 private void setProperty(String key, String value) {
   if (value != null) {
     properties.setProperty(key, value);
   } else {
     properties.remove(key);
   }
 }
  public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;
    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imap.host", "imap.googlemail.com");
      SimpleAuthenticator authenticator =
          new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy");
      Session session = Session.getDefaultInstance(props, null);
      // Session session = Session.getDefaultInstance(props, authenticator);

      store = session.getStore("imaps");
      //          store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");
      // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");

      store.connect("*****@*****.**", "hhy8611hhy");
      // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email
      // account
      folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account

      if (!folder.isOpen()) folder.open(Folder.READ_WRITE);
      Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages();
      System.out.println("No of get Messages : " + messages.length);
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println("No of New Messages : " + folder.getNewMessageCount());
      System.out.println(messages.length);
      for (int i = 0; i < messages.length; i++) {

        System.out.println(
            "*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg = messages[i];
        // System.out.println(msg.getMessageNumber());
        // Object String;
        // System.out.println(folder.getUID(msg)

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
        System.out.println("To: " + msg.getAllRecipients()[0]);
        System.out.println("Date: " + msg.getReceivedDate());
        System.out.println("Size: " + msg.getSize());
        System.out.println(msg.getFlags());
        System.out.println("Body: \n" + msg.getContent());
        System.out.println(msg.getContentType());
      }
    } finally {
      if (folder != null && folder.isOpen()) {
        folder.close(true);
      }
      if (store != null) {
        store.close();
      }
    }
  }
示例#10
0
文件: Arisu.java 项目: Carlgo11/Arisu
 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;
 }
  public void setUp() throws Exception {
    super.setUp();
    tempDirPath = getTempDir().getAbsolutePath() + File.separator;

    theDaemon = getMockLockssDaemon();
    theDaemon.getAlertManager();
    theDaemon.getPluginManager().setLoadablePluginsReady(true);
    theDaemon.getHashService();
    MockSystemMetrics metrics = new MyMockSystemMetrics();
    metrics.initService(theDaemon);
    theDaemon.setSystemMetrics(metrics);

    theDaemon.setDaemonInited(true);

    Properties props = new Properties();
    props.setProperty(SystemMetrics.PARAM_HASH_TEST_DURATION, "1000");
    props.setProperty(SystemMetrics.PARAM_HASH_TEST_BYTE_STEP, "1024");
    props.setProperty(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST, tempDirPath);
    ConfigurationUtil.setCurrentConfigFromProps(props);

    pluginMgr = theDaemon.getPluginManager();
    pluginMgr.startService();
    theDaemon.getHashService().startService();
    metrics.startService();
    metrics.setHashSpeed(100);

    simPlugin = PluginTestUtil.findPlugin(SimulatedPlugin.class);
  }
示例#12
0
  public void setUp() throws Exception {
    super.setUp();
    theDaemon = getMockLockssDaemon();
    tempDir = getTempDir();
    String tempDirPath = tempDir.getAbsolutePath();
    System.setProperty("java.io.tmpdir", tempDirPath);

    Properties p = new Properties();
    p.setProperty(IdentityManager.PARAM_IDDB_DIR, tempDirPath + "iddb");
    p.setProperty(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST, tempDirPath);
    p.setProperty(IdentityManager.PARAM_LOCAL_IP, "127.0.0.1");
    p.setProperty(V3LcapMessage.PARAM_REPAIR_DATA_THRESHOLD, "4096");
    ConfigurationUtil.setCurrentConfigFromProps(p);
    IdentityManager idmgr = theDaemon.getIdentityManager();
    idmgr.startService();
    mPollMgr = new MockPollManager();
    theDaemon.setPollManager(mPollMgr);
    try {
      m_testID = idmgr.stringToPeerIdentity("127.0.0.1");
    } catch (IOException ex) {
      fail("can't open test host 127.0.0.1: " + ex);
    }
    m_repairProps = new CIProperties();
    m_repairProps.setProperty("key1", "val1");
    m_repairProps.setProperty("key2", "val2");
    m_repairProps.setProperty("key3", "val3");

    m_testVoteBlocks = V3TestUtils.makeVoteBlockList(10);
    m_testMsg = this.makeTestVoteMessage(m_testVoteBlocks);
  }
 private XmlUIElement getXmlUIElementFor(String typeArg) {
   if (typeToClassMappingProp == null) {
     setUpMappingsHM();
   }
   String clsName = (String) typeToClassMappingProp.get(typeArg);
   if ((clsName != null) && !(clsName.equals("*NOTFOUND*")) && !(clsName.equals("*EXCEPTION*"))) {
     try {
       Class cls = Class.forName(clsName);
       return (XmlUIElement) cls.newInstance();
     } catch (Throwable th) {
       typeToClassMappingProp.put(typeArg, "*EXCEPTION*");
       showErrorMessage(
           MessageFormat.format(
               ProvClientUtils.getString(
                   "{0} occurred when trying to get the XmlUIElement for type : {1}"),
               new Object[] {th.getClass().getName(), typeArg}));
       th.printStackTrace();
       return null;
     }
   } else if (clsName == null) {
     typeToClassMappingProp.put(typeArg, "*NOTFOUND*");
     showErrorMessage(
         MessageFormat.format(
             ProvClientUtils.getString(
                 "The type {0} does not have the corresponding XMLUIElement specified in the TypeToUIElementMapping.txt file"),
             new Object[] {typeArg}));
   }
   return null;
 }
示例#14
0
 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;
 }
示例#15
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));
   }
 }
示例#16
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
示例#17
0
  /** store the given RenderingHints to a Properties object */
  public static void formatRenderingHints(RenderingHints rh, Properties preferences) {

    if (rh.get(RenderingHints.KEY_ANTIALIASING).equals(RenderingHints.VALUE_ANTIALIAS_ON))
      preferences.put("rendering.antialiasing", "on");
    else if (rh.get(RenderingHints.KEY_ANTIALIASING).equals(RenderingHints.VALUE_ANTIALIAS_OFF))
      preferences.put("rendering.antialiasing", "off");

    if (rh.get(RenderingHints.KEY_TEXT_ANTIALIASING).equals(RenderingHints.VALUE_TEXT_ANTIALIAS_ON))
      preferences.put("rendering.text-antialiasing", "on");
    else if (rh.get(RenderingHints.KEY_TEXT_ANTIALIASING)
        .equals(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF))
      preferences.put("rendering.text-antialiasing", "off");

    if (rh.get(RenderingHints.KEY_RENDERING).equals(RenderingHints.VALUE_RENDER_SPEED))
      preferences.put("rendering.render", "speed");
    else if (rh.get(RenderingHints.KEY_RENDERING).equals(RenderingHints.VALUE_RENDER_QUALITY))
      preferences.put("rendering.render", "quality");

    if (rh.get(RenderingHints.KEY_DITHERING).equals(RenderingHints.VALUE_DITHER_ENABLE))
      preferences.put("rendering.dither", "on");
    else if (rh.get(RenderingHints.KEY_DITHERING).equals(RenderingHints.VALUE_DITHER_DISABLE))
      preferences.put("rendering.dither", "off");

    if (rh.get(RenderingHints.KEY_FRACTIONALMETRICS)
        .equals(RenderingHints.VALUE_FRACTIONALMETRICS_ON))
      preferences.put("rendering.fractional-metrics", "on");
    else if (rh.get(RenderingHints.KEY_FRACTIONALMETRICS)
        .equals(RenderingHints.VALUE_FRACTIONALMETRICS_OFF))
      preferences.put("rendering.fractional-metrics", "off");
  }
示例#18
0
  public static void exportWithProperties(String propFile, String outFile) throws IOException {
    Properties props = new Properties();
    try {
      props.load(new FileInputStream(propFile));
    } catch (FileNotFoundException e) {
      System.err.println("Property file not found: " + propFile);
      System.exit(2);
    } catch (IOException e) {
      System.err.println("Unable to read properties: " + propFile);
      System.exit(2);
    }

    OutputStream out = null;

    try {
      out = new BufferedOutputStream(new FileOutputStream(outFile));
      WikiEngine engine = new WikiEngine(props);

      Exporter x = new Exporter(out, true);

      x.export(engine);
    } catch (WikiException e) {
      // TODO Auto-generated catch block
      e.printStackTrace(System.err);
      System.exit(3);
    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.exit(3);
    } finally {
      if (out != null) out.close();

      // Make sure JSPWiki dies too
      System.exit(0);
    }
  }
    public Set<String> getOutdatedFiles(final boolean tests) {
      if (tests) {
        return myTest.outputEmpty() ? getTests() : getOutdatedTests();
      }

      return mySource.outputEmpty() ? getSources() : getOutdatedSources();
    }
示例#20
0
 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;
 }
示例#21
0
 public Properties loadUpdateProperties() {
   File propertiesDirectory;
   Properties updateProperties = new Properties();
   // First we look at local configuration directory
   propertiesDirectory = new File(System.getProperty("user.home"), PROPERTIES_DIRECTORY_NAME);
   if (!propertiesDirectory.exists()) {
     // Second we look at tangara binary path
     propertiesDirectory = getTangaraPath().getParentFile();
   }
   BufferedInputStream input = null;
   try {
     input =
         new BufferedInputStream(
             new FileInputStream(
                 new File(propertiesDirectory, getProperty("checkUpdate.fileName"))));
     updateProperties.load(input);
     input.close();
     return updateProperties;
   } catch (IOException e) {
     LOG.warn("Error trying to load update properties");
   } finally {
     IOUtils.closeQuietly(input);
   }
   return null;
 }
示例#22
0
  protected Properties convertProperties(Map<String, Object> m) {
    Properties res = null;

    {
      if (m != null) {
        res = new Properties();

        Set<String> keys = m.keySet();
        for (String key : keys) {
          String value = null;

          // Set 'value':
          {
            Object o = m.get(key);
            if (o != null) {
              value = o.toString();
            }
          }

          res.setProperty(key, value);
        }
      }
    }

    return res;
  }
示例#23
0
 /** 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));
   }
 }
 public static void init() throws Exception {
   Properties props = new Properties();
   int pid = OSProcess.getId();
   String path = File.createTempFile("dunit-cachejta_", ".xml").getAbsolutePath();
   /** * Return file as string and then modify the string accordingly ** */
   String file_as_str = readFile(TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml"));
   file_as_str = file_as_str.replaceAll("newDB", "newDB_" + pid);
   String modified_file_str = modifyFile(file_as_str);
   FileOutputStream fos = new FileOutputStream(path);
   BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(fos));
   wr.write(modified_file_str);
   wr.flush();
   wr.close();
   props.setProperty("cache-xml-file", path);
   //    String tableName = "";
   //		  props.setProperty("mcast-port", "10339");
   try {
     //			   ds = DistributedSystem.connect(props);
     ds = (new ExceptionsDUnitTest("temp")).getSystem(props);
     cache = CacheFactory.create(ds);
   } catch (Exception e) {
     e.printStackTrace(System.err);
     throw new Exception("" + e);
   }
 }
示例#25
0
  public void mail(String toAddress, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.ssl.enable", true);
    Authenticator authenticator = null;
    if (login) {
      props.put("mail.smtp.auth", true);
      authenticator =
          new Authenticator() {
            private PasswordAuthentication pa = new PasswordAuthentication(username, password);

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
              return pa;
            }
          };
    }

    Session s = Session.getInstance(props, authenticator);
    s.setDebug(debug);
    MimeMessage email = new MimeMessage(s);
    try {
      email.setFrom(new InternetAddress(from));
      email.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
      email.setSubject(subject);
      email.setSentDate(new Date());
      email.setText(body);
      Transport.send(email);
    } catch (MessagingException ex) {
      ex.printStackTrace();
    }
  }
示例#26
0
  public void send() {
    // Your SMTP server address here.
    String smtpHost = "myserver.jeffcorp.com";
    // The sender's email address
    String from = "*****@*****.**";
    // The recepients email address
    String to = "*****@*****.**";

    Properties props = new Properties();
    // The protocol to use is SMTP
    props.put("mail.smtp.host", smtpHost);

    Session session = Session.getDefaultInstance(props, null);

    try {
      InternetAddress[] address = {new InternetAddress(to)};
      MimeMessage message;

      message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));

      message.setRecipients(Message.RecipientType.TO, to);
      message.setSubject("Hello from Jeff");
      message.setSentDate(sendDate);
      message.setText("Hello Jeff, \nHow are things going?");

      Transport.send(message);

      System.out.println("email has been sent.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  public SaikuDatasource addDatasource(SaikuDatasource datasource) {
    try {
      String uri = repoURL.toURI().toString();
      if (uri != null && datasource != null) {
        uri += datasource.getName().replace(" ", "_");
        File dsFile = new File(new URI(uri));
        if (dsFile.exists()) {
          dsFile.delete();
        } else {
          dsFile.createNewFile();
        }
        FileWriter fw = new FileWriter(dsFile);
        Properties props = datasource.getProperties();
        props.store(fw, null);
        fw.close();
        datasources.put(datasource.getName(), datasource);
        return datasource;

      } else {
        throw new SaikuServiceException(
            "Cannot save datasource because uri or datasource is null uri(" + (uri == null) + ")");
      }
    } catch (Exception e) {
      throw new SaikuServiceException("Error saving datasource", e);
    }
  }
示例#28
0
  /**
   * Get the set of properties that match a specified pattern. The match pattern accepts a single
   * '*' char anywhere in the pattern. If the '*' is placed somewhere in the middle of the pattern,
   * then then the subset will contain properties that startWith everything before the '*' and end
   * with everything after the '*'.
   *
   * <p>Sample property patterns:
   *
   * <table>
   * <tr><td>*.bar<td>   returns the subset of properties that end with '.bar'
   * <tr><td>bar.*<td>   returns the subset of properties that begin with 'bar.'
   * <tr><td>foo*bar<td> returns the subset of properties that begin with 'foo' and end with 'bar'
   * </table>
   *
   * @param propPattern a pattern with 0 or 1 '*' chars.
   * @return the subset of properties that match the specified pattern. Note that changing the
   *     properties in the returned subset will not affect this object.
   */
  public Properties getProperties(String propPattern) {
    Properties props = new Properties();
    int index = propPattern.indexOf("*");
    if (index == -1) {
      String value = getProperty(propPattern);
      if (value != null) {
        props.put(propPattern, value);
      }
    } else {
      String startsWith = propPattern.substring(0, index);
      String endsWith;
      if (index == propPattern.length() - 1) {
        endsWith = null;
      } else {
        endsWith = propPattern.substring(index + 1);
      }

      Enumeration names = propertyNames();
      while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        if (name.startsWith(startsWith)) {
          if (endsWith == null) {
            props.put(name, getProperty(name));
          } else if (name.endsWith(endsWith)) {
            props.put(name, getProperty(name));
          }
        }
      }
    }
    return props;
  }
  public static Map<String, String> readProperties(InputStream inputStream) {
    Map<String, String> propertiesMap = null;
    try {
      propertiesMap = new LinkedHashMap<String, String>();

      Properties properties = new Properties();
      properties.load(inputStream);

      Enumeration<?> enumeration = properties.propertyNames();
      while (enumeration.hasMoreElements()) {
        String key = (String) enumeration.nextElement();
        String value = (String) properties.get(key);
        propertiesMap.put(key, value);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return propertiesMap;
  }
示例#30
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;
  }