コード例 #1
1
 private void loadUser(DocearUser user) {
   String token = properties.getProperty(DOCEAR_CONNECTION_TOKEN_PROPERTY);
   if (token == null) {
     token =
         DocearController.getPropertiesController().getProperty(DOCEAR_CONNECTION_TOKEN_PROPERTY);
   }
   user.setAccessToken(token);
   String strRetrieval = properties.getProperty(DOCEAR_INFORMATION_RETRIEVAL);
   if (strRetrieval == null) {
     strRetrieval =
         DocearController.getPropertiesController().getProperty(DOCEAR_INFORMATION_RETRIEVAL);
   }
   if (strRetrieval != null) {
     int ir = Integer.parseInt(strRetrieval);
     user.setRecommendationsEnabled((DocearUser.RECOMMENDATIONS & ir) > 0);
     user.setCollaborationEnabled(((DocearUser.COLLABORATION & ir) > 0));
     user.setBackupEnabled(((DocearUser.BACKUP & ir) > 0));
     user.setSynchronizationEnabled(((DocearUser.SYNCHRONIZATION & ir) > 0));
   }
   if (DocearController.getPropertiesController().getProperty(DOCEAR_SAVE_BACKUP) != null) {
     user.setBackupEnabled(
         Boolean.parseBoolean(
             DocearController.getPropertiesController().getProperty(DOCEAR_SAVE_BACKUP)));
   }
   //		WorkspaceController.load();
 }
コード例 #2
1
ファイル: File.java プロジェクト: KhunAke/StockExchange
  private File() {
    Properties properties = System.getProperties();

    line = properties.getProperty("line.separator");
    encoding = properties.getProperty("file.encoding");
    separator = properties.getProperty("file.separator");
  }
コード例 #3
1
  /**
   * Constructor. Creates a datagram send socket and connects it to the Ganglia hypertable extension
   * listen port. Initializes mPrefix to "ht." + <code>component</code> + ".".
   *
   * @param component Hypertable component ("fsbroker", "hyperspace, "master", "rangeserver", or
   *     "thriftbroker")
   * @param props Configuration properties
   */
  public MetricsCollectorGanglia(String component, Properties props) {
    mPrefix = "ht." + component + ".";

    String str = props.getProperty("Hypertable.Metrics.Ganglia.Port", "15860");
    mPort = Integer.parseInt(str);

    str = props.getProperty("Hypertable.Metrics.Ganglia.Disabled");
    if (str != null && str.equalsIgnoreCase("true")) mDisabled = true;

    try {
      mAddr = InetAddress.getByName("localhost");
    } catch (UnknownHostException e) {
      System.out.println("UnknownHostException : 'localhost'");
      e.printStackTrace();
      System.exit(-1);
    }

    try {
      mSocket = new DatagramSocket();
    } catch (SocketException e) {
      e.printStackTrace();
      System.exit(-1);
    }

    mSocket.connect(mAddr, mPort);
    mConnected = true;
  }
コード例 #4
0
 public ArrayList<ServiceInfo> getServices(Properties properties) throws ApiException {
   ArrayList<ServiceInfo> services = new ArrayList<ServiceInfo>();
   try {
     String defaultLangCode = this.getLangManager().getDefaultLang().getCode();
     String langCode = properties.getProperty(SystemConstants.API_LANG_CODE_PARAMETER);
     String tagParamValue = properties.getProperty("tag");
     String myentandoParamValue = properties.getProperty("myentando");
     Boolean myentando =
         (null != myentandoParamValue && myentandoParamValue.trim().length() > 0)
             ? Boolean.valueOf(myentandoParamValue)
             : null;
     langCode =
         (null != langCode && null != this.getLangManager().getLang(langCode))
             ? langCode
             : defaultLangCode;
     Map<String, ApiService> masterServices =
         this.getApiCatalogManager().getServices(tagParamValue, myentando);
     Iterator<ApiService> iter = masterServices.values().iterator();
     while (iter.hasNext()) {
       ApiService service = (ApiService) iter.next();
       if (service.isActive()
           && !service.isHidden()
           && this.checkServiceAuthorization(service, properties, false)) {
         ServiceInfo smallService = this.createServiceInfo(service, langCode, defaultLangCode);
         services.add(smallService);
       }
     }
     BeanComparator comparator = new BeanComparator("description");
     Collections.sort(services, comparator);
   } catch (Throwable t) {
     ApsSystemUtils.logThrowable(t, this, "getServices", "Error extracting services");
     throw new ApiException(IApiErrorCodes.SERVER_ERROR, "Internal error");
   }
   return services;
 }
コード例 #5
0
  private void setJasperResourceNames(ToolBoxDTO toolBoxDTO, String barDir)
      throws BAMToolboxDeploymentException {
    String jasperDirectory =
        barDir
            + File.separator
            + BAMToolBoxDeployerConstants.DASHBOARD_DIR
            + File.separator
            + BAMToolBoxDeployerConstants.JASPER_DIR;
    if (new File(jasperDirectory).exists()) {
      toolBoxDTO.setJasperParentDirectory(
          barDir
              + File.separator
              + BAMToolBoxDeployerConstants.DASHBOARD_DIR
              + File.separator
              + BAMToolBoxDeployerConstants.JASPER_DIR);
      Properties properties = new Properties();
      try {
        properties.load(
            new FileInputStream(
                barDir
                    + File.separator
                    + BAMToolBoxDeployerConstants.DASHBOARD_DIR
                    + File.separator
                    + BAMToolBoxDeployerConstants.JASPER_META_FILE));

        setJasperTabAndJrxmlNames(toolBoxDTO, properties);

        toolBoxDTO.setDataSource(properties.getProperty(BAMToolBoxDeployerConstants.DATASOURCE));
        toolBoxDTO.setDataSourceConfiguration(
            barDir
                + File.separator
                + BAMToolBoxDeployerConstants.DASHBOARD_DIR
                + File.separator
                + properties.getProperty(BAMToolBoxDeployerConstants.DATASOURCE_CONFIGURATION));
      } catch (FileNotFoundException e) {
        log.error(
            "No "
                + BAMToolBoxDeployerConstants.JASPER_META_FILE
                + " found in dir:"
                + barDir
                + File.separator
                + BAMToolBoxDeployerConstants.DASHBOARD_DIR,
            e);
        throw new BAMToolboxDeploymentException(
            "No "
                + BAMToolBoxDeployerConstants.JASPER_META_FILE
                + " found in dir:"
                + barDir
                + File.separator
                + BAMToolBoxDeployerConstants.DASHBOARD_DIR,
            e);
      } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new BAMToolboxDeploymentException(e.getMessage(), e);
      }
    } else {
      toolBoxDTO.setJasperParentDirectory(null);
      toolBoxDTO.setJasperTabs(new ArrayList<JasperTabDTO>());
    }
  }
コード例 #6
0
 public EmailChannel(String configuration) {
   Properties props = new Properties();
   try {
     props.load(new StringReader(configuration));
   } catch (IOException e) {
     // really shouldn't happen
     throw new IllegalStateException(
         "Bug: can't load email properties " + "for the channel instance", e);
   }
   String smtpUser = props.getProperty(CFG_USER);
   String smtpPassword = props.getProperty(CFG_PASSWD);
   Authenticator smtpAuthn =
       (smtpUser != null && smtpPassword != null)
           ? new SimpleAuthenticator(smtpUser, smtpPassword)
           : null;
   String trustAll = props.getProperty(CFG_TRUST_ALL);
   if (trustAll != null && "true".equalsIgnoreCase(trustAll)) {
     MailSSLSocketFactory trustAllSF;
     try {
       trustAllSF = new MailSSLSocketFactory();
     } catch (GeneralSecurityException e) {
       // really shouldn't happen
       throw new IllegalStateException("Can't init trust-all SSL socket factory", e);
     }
     trustAllSF.setTrustAllHosts(true);
     props.put("mail.smtp.ssl.socketFactory", trustAllSF);
   } else {
     X509CertChainValidator validator = pkiManagement.getMainAuthnAndTrust().getValidator();
     SSLSocketFactory factory = SocketFactoryCreator.getSocketFactory(null, validator);
     props.put("mail.smtp.ssl.socketFactory", factory);
   }
   session = Session.getInstance(props, smtpAuthn);
 }
コード例 #7
0
  private void setConfigDefaults() {
    try {
      Properties config = Util.getConfig(null);

      for (Comboitem item : portBaudRate.getItems()) {
        if (config.getProperty(Constants.SERIAL_PORT_BAUD).equals(item.getValue())) {
          portBaudRate.setSelectedItem(item);
        }
      }
      portsToScan.setValue(config.getProperty(Constants.SERIAL_PORTS));
      cfgWindOffset.setValue(config.getProperty(Constants.WIND_ZERO_OFFSET));
      String useChoice = config.getProperty(Constants.DNS_USE_CHOICE);
      if (Constants.DNS_USE_BOAT.equals(useChoice)) {
        useHomeGroup.setSelectedItem(useBoatRadio);
      } else {
        useHomeGroup.setSelectedItem(useHomeRadio);
      }
      if (new Boolean(config.getProperty(Constants.PREFER_RMC))) {
        useRmcGroup.setSelectedItem(useRmcRadio);
      } else {
        useRmcGroup.setSelectedItem(useHdgRadio);
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      Messagebox.show("There has been a problem with loading the configuration:" + e.getMessage());
    }
  }
コード例 #8
0
  static {
    if (sqlSessionFactory == null) {
      logger.info("create new Sql Session");
      Properties props = new Properties();
      String resource = "com/errclipse/orm/connector/mybatis-conf.xml";
      try {
        FileInputStream propertyFileInput = new FileInputStream(getMybatisProp());
        props.load(propertyFileInput);
        InputStream inputStream = Resources.getResourceAsStream(resource);

        logger.info(String.format("Driver Info : %s ", props.getProperty("errclipse.db.driver")));
        logger.info(String.format("JDBC Url Info : %s ", props.getProperty("errclipse.db.url")));
        logger.info(String.format("User Info : %s ", props.getProperty("errclipse.db.username")));
        /* dangerous, must change hash method md5 */
        logger.info(
            String.format(
                "Passwd Info : %s ",
                props.getProperty("errclipse.db.username").toString().hashCode()));

        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, props);
        propertyFileInput.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
コード例 #9
0
ファイル: SearchQuery.java プロジェクト: Wotanacran/Exam3B
  public SearchQuery() {

    Properties props = new Properties(); // MWC
    InputStream instr = getClass().getResourceAsStream("dbConn.properties");
    try {
      props.load(instr);
    } catch (IOException ex) {
      Logger.getLogger(SearchQuery.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
      instr.close();
    } catch (IOException ex) {
      Logger.getLogger(SearchQuery.class.getName()).log(Level.SEVERE, null, ex);
    }

    String driver = props.getProperty("driver.name");
    String url = props.getProperty("server.name");
    String username = props.getProperty("user.name");
    String passwd = props.getProperty("user.password");
    try {
      Class.forName(driver);
    } catch (ClassNotFoundException ex) {
      Logger.getLogger(SearchQuery.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
      conn = DriverManager.getConnection(url, username, passwd);
    } catch (SQLException ex) {
      Logger.getLogger(SearchQuery.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
コード例 #10
0
  /**
   * Normally called to initialize CoherenceCache. To be able to test the method without having
   * <code>com.tangosol.net.CacheFactory</code> implementation, it can also be called with a test
   * implementations classname.
   *
   * @param implementation Cache implementation classname to initialize.
   * @param params Parameters to initialize the cache (e.g. name, capacity).
   * @throws CacheAcquireException If cache can not be initialized.
   */
  @SuppressWarnings("unchecked")
  public void initialize(final String implementation, final Properties params)
      throws CacheAcquireException {
    super.initialize(params);

    String cacheURL = params.getProperty("cacheURL", DEFAULT_CACHE_URL);
    String cacheProperties = params.getProperty("cacheProperties", DEFAULT_CACHE_PROPERTIES);

    StringBuffer clusterURL = new StringBuffer();
    clusterURL.append(cacheURL);
    clusterURL.append(getName());
    clusterURL.append("?");
    clusterURL.append(cacheProperties);

    if (LOG.isDebugEnabled()) {
      LOG.debug(clusterURL.toString());
    }

    try {
      ClassLoader ldr = this.getClass().getClassLoader();
      Class<?> cls = ldr.loadClass(implementation);
      setCache(
          (Map)
              invokeStaticMethod(
                  cls, "find", TYPES_FIND_CACHE, new Object[] {clusterURL.toString()}));
    } catch (Exception e) {
      LOG.error("Problem!", e);
      String msg = "Error creating Gigaspaces cache: " + e.getMessage();
      LOG.error(msg, e);
      throw new CacheAcquireException(msg, e);
    }
  }
コード例 #11
0
  public static void main(String[] args) throws Exception {

    String axisClientRepo = null;
    if (args != null && args.length > 0) axisClientRepo = args[0];

    if (axisClientRepo != null && !"".equals(axisClientRepo)) {
      AXIS2_CLIENT_PATH = axisClientRepo;
      SANDESHA2_HOME = "";
    }

    InputStream in =
        Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("sandesha2_interop.properties");

    Properties properties = new Properties();
    if (in != null) {
      properties.load(in);

      toEPR = properties.getProperty("to");
      transportToEPR = properties.getProperty("transportTo");
    }

    //		new Scenario_1_4().run();
    new Scenario_1_4().runStubBased();
  }
コード例 #12
0
 @Test
 public void testSplitArrayElementsIntoProperties() {
   String[] input = new String[] {"key1=value1 ", "key2 =\"value2\""};
   Properties result = StringUtils.splitArrayElementsIntoProperties(input, "=");
   assertEquals("value1", result.getProperty("key1"));
   assertEquals("\"value2\"", result.getProperty("key2"));
 }
コード例 #13
0
  private LogisticRegressionModel instantiateSparkModel() {
    Configuration conf = new Configuration();
    conf.set("fs.defaultFS", topologyConfig.getProperty("hdfs.url"));

    double[] sparkModelInfo = null;

    try {
      sparkModelInfo =
          getSparkModelInfoFromHDFS(
              new Path(topologyConfig.getProperty("hdfs.url") + "/tmp/sparkML_weights"), conf);
    } catch (Exception e) {
      LOG.error("Couldn't instantiate Spark model in prediction bolt: " + e.getMessage());
      e.printStackTrace();

      throw new RuntimeException(e);
    }

    // all numbers besides the last value are the weights
    double[] weights = Arrays.copyOfRange(sparkModelInfo, 0, sparkModelInfo.length - 1);

    // the last number in the array is the intercept
    double intercept = sparkModelInfo[sparkModelInfo.length - 1];

    org.apache.spark.mllib.linalg.Vector weightsV = (Vectors.dense(weights));
    return new LogisticRegressionModel(weightsV, intercept);
  }
コード例 #14
0
  private static void loadPropertiesFile() throws Exception {
    InputStream input = new FileInputStream(DATABASE_PROPERTIES);
    //
    //		InputStream in = ConnectionManager.class
    //				.getResourceAsStream(DATABASE_PROPERTIES);
    //		if (in == null)
    //			System.out.println("Null");

    Properties p = new Properties();
    p.load(input);

    driver = p.getProperty("mysql.driver");
    host = p.getProperty("mysql.host");
    port = p.getProperty("mysql.port");
    datebaseName = p.getProperty("mysql.importDatabaseName");
    userName = p.getProperty("mysql.username");
    password = p.getProperty("mysql.password");
    url =
        "jdbc:mysql://"
            + host
            + ":"
            + port
            + "/"
            + datebaseName
            + "?useUnicode=true&characterEncoding=utf-8";
  }
コード例 #15
0
ファイル: Version.java プロジェクト: metairie/AutosuggestFX
  protected Version() {
    Properties properties = new Properties();
    InputStream input = null;
    try {

      input =
          Version.class
              .getClassLoader()
              .getResourceAsStream("org/fxpart/version/version.properties");
      if (input == null) {
        System.out.println("Sorry, unable to find version.properties");
        return;
      }
      properties.load(input);
      version = properties.getProperty("version");
      build = properties.getProperty("build.date");
      System.out.println("AutosuggestFX version : " + version);
      System.out.println("AutosuggestFX build : " + build);
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) {
        try {
          input.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #16
0
  /**
   * Creates an instance of {@code AccessedObjectsListener}.
   *
   * @param properties the {@code Properties} for this listener
   * @param owner the {@code Identity} to use for all tasks run by this listener
   * @param registry the {@code ComponentRegistry} containing the available system components
   * @throws IllegalArgumentException if either of the backlog or count properties is provided but
   *     invalid
   */
  public AccessedObjectsListener(
      Properties properties, Identity owner, ComponentRegistry registry) {
    if (properties == null) throw new NullPointerException("Properties cannot be null");

    String backlogProp = properties.getProperty(BACKLOG_PROPERTY);
    if (backlogProp != null) {
      try {
        int size = Integer.parseInt(backlogProp);
        if (size != 0) {
          backlogMap = new BoundedLinkedHashMap<TransactionId, AccessedObjectsDetail>(size);
        } else {
          backlogMap = null;
        }
      } catch (NumberFormatException nfe) {
        throw new IllegalArgumentException("Backlog size must be a " + "number: " + backlogProp);
      }
    } else {
      backlogMap = null;
    }

    String countProp = properties.getProperty(ACCESS_COUNT_PROPERTY);
    if (countProp != null) {
      try {
        accessesToShow = Integer.parseInt(countProp);
        if (accessesToShow < 0)
          throw new IllegalArgumentException(
              "Access count must be " + "non-negative: " + accessesToShow);
      } catch (NumberFormatException nfe) {
        throw new IllegalArgumentException("Access count moust be a " + "number: " + countProp);
      }
    } else {
      accessesToShow = DEFAULT_ACCESS_COUNT;
    }
  }
コード例 #17
0
  /**
   * see LKC-2436 and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6322825
   *
   * @return true if the workaround should be applied
   */
  static boolean solaris10Workaround(Properties props) {
    String vendor = props.getProperty("java.vendor", "");
    String osName = props.getProperty("os.name", "");
    String osVersion = props.getProperty("os.version", "");
    String javaVersion = props.getProperty("java.version", "");

    if (vendor.toLowerCase().startsWith("sun")
        && "SunOS".equals(osName)
        && "5.10".equals(osVersion)) {
      if (javaVersion.matches("^1\\.[12345]\\..*")) { // bug is fixed in 1.6+ (supposedly)
        // Bug is fixed in 1.5.0_08+ (again, supposedly)
        Pattern p = Pattern.compile("^1\\.5\\.0_(\\d\\d)$");
        Matcher m = p.matcher(javaVersion);
        if (m.matches()) {
          String minorRev = m.group(1);
          int ver = Integer.parseInt(minorRev);
          if (ver >= 8) {
            return false;
          }
        }

        return true;
      }
    }
    return false;
  }
コード例 #18
0
  /**
   * @param config The Properties holding a username, password etc.
   * @param properties Properties holding server settings and configuration
   */
  public ComposeMailScreen(Properties config) {
    this.username = config.getProperty("username");
    Authenticator authenticator =
        new Authenticator() {
          @Override
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
          }
        };

    this.keyWords = new ArrayList<String>();
    this.session = Session.getInstance(config, authenticator);
    // The password which will be decrypted
    String passwordDec = config.getProperty("password");
    try {
      passwordDec = ProtectedPassword.decrypt(passwordDec);
    } catch (GeneralSecurityException ex) {
      JOptionPane.showMessageDialog(
          rootPane, ex.toString(), "GeneralSecurityException", JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {
      JOptionPane.showMessageDialog(
          rootPane, ex.toString(), "GeneralSecurityException", JOptionPane.ERROR_MESSAGE);
    }

    this.password = passwordDec;
    initComponents();
    this.setLocationRelativeTo(null);
  }
コード例 #19
0
ファイル: MassiveRPG.java プロジェクト: CinisterOne/MRPG
 public void loadBlockConfiguration(String dataWorld) {
   Properties props = new Properties();
   try {
     // Create the file if it doesn't exist.
     File configFile =
         this.getFile(this.getDataWorldFile(dataWorld) + "/blockData/", "MassiveBlockEXP.ini");
     if (!configFile.exists()) {
       configFile.createNewFile();
       props.load(new FileReader(configFile));
       props.setProperty("blocks_num", "96");
       for (int i = 0; i < 96; i++) {
         props.setProperty(Material.getMaterial(i).name(), "0");
       }
       props.store(new FileWriter(configFile), "Block Configuration for world " + dataWorld);
     } else {
       props.load(new FileReader(configFile));
     }
     // Load the configuration.
     numBlock = Integer.parseInt(props.getProperty("blocks_num", "96"));
     for (int i = 0; i < numBlock; i++) {
       GeneralData.blockEXP.add(Integer.parseInt(props.getProperty(Integer.toString(i), "0")));
     }
   } catch (Exception ex) {
     log.log(Level.WARNING, "Unable to load MassiveBlockEXP.ini");
   }
 }
コード例 #20
0
ファイル: MainGui.java プロジェクト: Velector/Custom-Desktop
  public static void loadProgramIcons() {
    Properties prop = new Properties();
    try {

      File IconFile = new File(SystemInfo.getProgramPath() + "/StartData/ProgramIcons.txt");
      System.out.println("Program path: " + IconFile.getAbsolutePath());
      prop.load(new FileInputStream(IconFile));
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    int numberOfIcons = Integer.parseInt(prop.getProperty("numberOfIcons"));
    ProgramIcons = new ProgramIcon[numberOfIcons];

    for (int i = 0; i < numberOfIcons; i++) {
      ProgramIcons[i] = new ProgramIcon();
      ProgramIcons[i].Name = prop.getProperty("icon" + (i + 1) + "name");
      ProgramIcons[i].ProgramPath = prop.getProperty("icon" + (i + 1) + "Path");
      ProgramIcons[i].IconPath = prop.getProperty("icon" + (i + 1) + "Icon");
      ProgramIcons[i].HighLightedIconPath = prop.getProperty("icon" + (i + 1) + "HighLightedIcon");
      ProgramIcons[i].LoadIcons();
      RightPanel.add(ProgramIcons[i]);
    }
  }
コード例 #21
0
 /**
  * Generates a Config object containing the properties defined in a relative path-based properties
  * file, required to initialize the FenixFramework.
  *
  * @param relativePathFileName The relative path name where the property file defining the config
  *     properties exists.
  * @return The respective Config object to initialize the FenixFramework.
  */
 public static Config loadFromProperties(String relativePathFileName) {
   final Properties props = new Properties();
   try {
     props.load(new FileInputStream(relativePathFileName));
   } catch (IOException ioe) {
     System.out.println("Problems while trying to read property file at " + relativePathFileName);
   }
   try {
     return new Config() {
       {
         domainModelPath = props.getProperty("persistence.domain.model.path");
         dbAlias = props.getProperty("persistence.db.alias");
         dbUsername = props.getProperty("persistence.db.username");
         dbPassword = props.getProperty("persistence.db.password");
         repositoryType = RepositoryType.BERKELEYDB;
         rootClass = Class.forName(props.getProperty("persistence.root.class"));
         updateRepositoryStructureIfNeeded = true;
       }
     };
   } catch (ClassNotFoundException cnfe) {
     if (props.getProperty("persistence.root.class").equals("")) {
       System.out.println("The persistence.root.class property was not defined");
     }
     System.out.println(
         "The class " + props.getProperty("persistence.root.class") + " was not found.");
   }
   return null;
 }
コード例 #22
0
  @BeforeClass
  public static void beforeClass() throws Exception {
    Properties p = new Properties();
    p.load(OAuthApiTest.class.getResourceAsStream("/response/auth/secret.properties"));

    String filename = p.getProperty("path.to.oauth.token");
    assertNotNull(filename);

    File file = new File(filename);
    assertTrue(file.exists());

    OAuthAccessToken oAuthAccessToken = new OAuthAccessToken();
    oAuthAccessToken.load(new FileInputStream(file));

    assertNotNull(oAuthAccessToken);

    groupsDiscussRepliesApi =
        new GroupsDiscussRepliesApi(
            new Jinx(
                p.getProperty("flickr.key"), p.getProperty("flickr.secret"), oAuthAccessToken));
    groupsDiscussTopicsApi =
        new GroupsDiscussTopicsApi(
            new Jinx(
                p.getProperty("flickr.key"), p.getProperty("flickr.secret"), oAuthAccessToken));
  }
コード例 #23
0
ファイル: Eml.java プロジェクト: evanleonard/ilarkesto
  public static void sendSmtpMessage(Session session, Message message, Address[] recipients)
      throws MessagingException {

    // message = cloneMimeMessage(message);
    message.setSentDate(new Date());
    setHeaderFieldValue(message, HEADER_X_MAILER, X_MAILER);
    message.saveChanges();

    LOG.info(
        "Sending message '"
            + message.getSubject()
            + "' from '"
            + Str.format(message.getFrom())
            + "' to '"
            + Str.format(recipients)
            + "'.");

    Transport trans = session.getTransport("smtp");
    Properties properties = session.getProperties();
    trans.connect(
        properties.getProperty("mail.smtp.host"),
        properties.getProperty("mail.smtp.auth.user"),
        properties.getProperty("mail.smtp.auth.password"));
    trans.sendMessage(message, recipients);
    trans.close();
  }
コード例 #24
0
ファイル: DAOFactory.java プロジェクト: rsilvestre/tweetr
  public static DAOFactory getInstance() throws DAOConfigurationException {
    Properties properties = new Properties();

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream propertiesFile = classLoader.getResourceAsStream(PROPERTIES_FILE);

    if (propertiesFile == null) {
      throw new DAOConfigurationException(
          "The properties file" + PROPERTIES_FILE + " is not found.");
    }

    try {
      properties.load(propertiesFile);
    } catch (IOException e) {
      throw new DAOConfigurationException(
          "Unable to load the properties file" + PROPERTIES_FILE, e);
    }

    try {
      Class.forName(properties.getProperty(PROPERTY_DRIVER));
    } catch (ClassNotFoundException e) {
      throw new DAOConfigurationException("Le driver est introuvable dans le classpath.", e);
    }

    return new DAOFactory(properties.getProperty(PROPERTY_URL), properties);
  }
コード例 #25
0
ファイル: AerospikeClient.java プロジェクト: phanimv/ycsb
  public void init() throws DBException {
    Properties props = getProperties();
    int port;

    // retrieve port
    String portString = props.getProperty("port");
    if (portString != null) {
      port = Integer.parseInt(portString);
    } else {
      port = 3000;
    }

    // retrieve host
    String host = props.getProperty("host");
    if (host == null) {
      host = "localhost";
    }

    // retrieve namespace
    String ns = props.getProperty("ns");
    if (ns != null) {
      NAMESPACE = ns;
    }

    // retrieve set
    String st = props.getProperty("set");
    if (st != null) {
      SET = st;
    }
    try {
      as = new com.aerospike.client.AerospikeClient(host, port);
    } catch (AerospikeException e) {
      throw new DBException(String.format("Failed to add %s:%d to cluster.", host, port));
    }
  }
コード例 #26
0
 public static void loadProp() {
   FileInputStream attestationPropertyFile = null;
   try {
     String configPath = "/etc/oat-appraiser/";
     attestationPropertyFile = new FileInputStream(configPath + PROPERTIES_NAME);
     attestationProperties.load(attestationPropertyFile);
     timeout = Long.parseLong(attestationProperties.getProperty("default_attest_timeout"));
     checkAttestInterval =
         Long.parseLong(attestationProperties.getProperty("check_attest_interval", "1000"));
     portalAddress = attestationProperties.getProperty("portal_address");
     defaultExpirationTime =
         Long.parseLong(attestationProperties.getProperty("default_expiration_time", "7"));
     if (portalAddress == null) {
       try {
         portalAddress = java.net.InetAddress.getLocalHost().getHostName();
       } catch (java.net.UnknownHostException e) {
         portalAddress = "localhost";
       }
     }
     attestationPropertyFile.close();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (attestationPropertyFile != null) attestationPropertyFile.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
コード例 #27
0
  public void initEJB() {
    try {
      InputStream inputStream =
          this.getClass()
              .getClassLoader()
              .getResourceAsStream("hu/neuron/java/sales/services/Settings.properties");

      Properties properties = new Properties();

      try {
        properties.load(inputStream);
      } catch (IOException e) {
        e.printStackTrace();
      }

      Hashtable<String, String> env = new Hashtable<String, String>();
      env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
      env.put(Context.SECURITY_PRINCIPAL, properties.getProperty("SECURITY_PRINCIPAL"));
      env.put(Context.SECURITY_CREDENTIALS, properties.getProperty("SECURITY_CREDENTIALS"));
      env.put(Context.PROVIDER_URL, properties.getProperty("PROVIDER_URL"));
      Context ctx;

      ctx = new InitialContext(env);
      System.out.println("ctx  = " + ctx);
      offerService =
          (OfferServiceRemote)
              ctx.lookup("OfferService#hu.neuron.java.sales.service.OfferServiceRemote");
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
コード例 #28
0
  public static @NonNull LinkedList<ThemeInfo> enumerateThemes(@NonNull Context context) {
    LinkedList<ThemeInfo> themes = new LinkedList<>();
    AssetManager manager = context.getAssets();

    // load themes from assets
    try {
      String[] builtin_themes = manager.list("");
      for (String theme : builtin_themes) {
        if (!theme.toLowerCase().endsWith("theme.properties")) continue;
        Properties p = loadColorScheme(theme, manager);
        if (p != null) themes.add(new ThemeInfo(p.getProperty("NAME", theme), theme));
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    // load themes from disk
    File dir = new File(SEARCH_DIR);
    if (dir.exists()) {
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          if (!file.getName().toLowerCase().endsWith("theme.properties")) continue;
          Properties p = loadColorScheme(file.getAbsolutePath(), null);
          if (p != null)
            themes.add(
                new ThemeInfo(p.getProperty("NAME", file.getName()), file.getAbsolutePath()));
        }
      }
    }
    return themes;
  }
コード例 #29
0
 /**
  * effectue la connexion pour l'utilisateur
  *
  * @return l'oid de l'objet utilisateur
  * @throws ExceptionUtilisateur
  */
 public static Utilisateur Identification()
     throws ExceptionConnexion, ExceptionUtilisateur, IOException {
   Utilisateur user = null;
   String login;
   String passwd;
   // lecture des parametres de connexion dans connection.conf
   Properties p = new Properties();
   InputStream is = null;
   is = new FileInputStream(utils.Constantes.Config);
   p.load(is);
   login = p.getProperty("user");
   passwd = p.getProperty("mdp");
   if (login == null || login.equals("MYUSERNAME")) {
     UserNamePasswordDialog login_dialog = new UserNamePasswordDialog(new Frame(""));
     login_dialog.setVisible(true);
     login = login_dialog.getUid();
     passwd = login_dialog.getPwd();
   }
   /* test de la connexion */
   Connection conn = BDConnexion.getConnexion(login, passwd);
   if (conn != null) {
     IO.afficherln("Connexion reussie...");
     BDConnexion.FermerTout(conn, null, null);
     user = new Utilisateur(login, passwd);
   } else {
     throw new ExceptionConnexion("Connexion impossible\n");
   }
   return user;
 }
コード例 #30
0
  public static Connection getOracleConnection() {

    Connection con = null;

    try {

      Properties prop = new Properties();

      FileInputStream inStream = new FileInputStream(new File("DbConnection.properties"));

      prop.load(inStream);

      Class.forName(prop.getProperty("db.className"));
      con =
          DriverManager.getConnection(
              prop.getProperty("db.url"),
              prop.getProperty("db.userName"),
              prop.getProperty("db.passWord"));

    } catch (Exception e) {

    }

    return con;
  }