Java Code Examples for java.util.Properties

The following are top voted examples for showing how to use java.util.Properties. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: parabuild-ci   File: WebuiUtils.java   View source code 6 votes vote down vote up
public static String makeURLParameters(final Properties params) {
  final StringBuffer result = new StringBuffer(100);
  if (!params.isEmpty()) {
    boolean first = true;
    final Set set = params.entrySet();
    for (final Iterator i = set.iterator(); i.hasNext(); ) {
      final Map.Entry entry = (Map.Entry) i.next();
      if (first) {
        result.append('?');
        first = false;
      } else {
        result.append('&');
      }
      result.append((String) entry.getKey());
      result.append('=');
      result.append((String) entry.getValue());
    }
  }
  return result.toString();
}
 
Example 2
Project: BecomeJavaHero   File: Database.java   View source code 6 votes vote down vote up
public Database() throws FileNotFoundException, IOException {
	Properties properties = new Properties();
	properties.load(new FileInputStream("src/main/resources/database.properties"));
	username = properties.getProperty("username");
	password = properties.getProperty("password");
	hostname = properties.getProperty("url");
	database = properties.getProperty("name");
	port = properties.getProperty("port");
}
 
Example 3
Project: cruise-control   File: ExcludedTopicsTest.java   View source code 6 votes vote down vote up
private static Goal goal(Class<? extends Goal> goalClass) throws Exception {
  Properties props = CruiseControlUnitTestUtils.getCruiseControlProperties();
  props.setProperty(KafkaCruiseControlConfig.MAX_REPLICAS_PER_BROKER_CONFIG, Long.toString(1L));
  BalancingConstraint balancingConstraint = new BalancingConstraint(new KafkaCruiseControlConfig(props));
  balancingConstraint.setBalancePercentage(TestConstants.LOW_BALANCE_PERCENTAGE);
  balancingConstraint.setCapacityThreshold(TestConstants.MEDIUM_CAPACITY_THRESHOLD);
  
  try {
    Constructor<? extends Goal> constructor = goalClass.getDeclaredConstructor(BalancingConstraint.class);
    constructor.setAccessible(true);
    return constructor.newInstance(balancingConstraint);
  } catch (NoSuchMethodException badConstructor) {
    //Try default constructor
    return goalClass.newInstance();
  }
}
 
Example 4
Project: the-vigilantes   File: StatementRegressionTest.java   View source code 6 votes vote down vote up
/**
 * Tests fix for BUG#10630, Statement.getWarnings() fails with NPE if
 * statement has been closed.
 */
public void testBug10630() throws Exception {
    Connection conn2 = null;
    Statement stmt2 = null;

    try {
        conn2 = getConnectionWithProps((Properties) null);
        stmt2 = conn2.createStatement();

        conn2.close();
        stmt2.getWarnings();
        fail("Should've caught an exception here");
    } catch (SQLException sqlEx) {
        assertEquals(SQLError.SQL_STATE_ILLEGAL_ARGUMENT, sqlEx.getSQLState());
    } finally {
        if (stmt2 != null) {
            stmt2.close();
        }

        if (conn2 != null) {
            conn2.close();
        }
    }
}
 
Example 5
Project: PrincessEdit   File: Loader.java   View source code 6 votes vote down vote up
private LoaderData getLoaderData(Path rootPath) {
    String os = getOS();

    try {
        Path inputPath = rootPath.resolve("manifest.properties");
        Properties prop = new Properties();
        prop.load(Files.newInputStream(inputPath));

        String mainClass = prop.getProperty("main");
        String classPath = prop.getProperty(os);

        if(classPath == null)
            throw error("Your system configuration ("+os+") is not supported in this build.", null);

        return new LoaderData(mainClass, classPath.split(":"));
    } catch (Exception e) {
        throw error("Could not load library manifest.", e);
    }
}
 
Example 6
Project: monarch   File: CacheServerTestUtil.java   View source code 6 votes vote down vote up
public static void createPool(PoolAttributes poolAttr) throws Exception {
  Properties props = new Properties();
  props.setProperty(MCAST_PORT, "0");
  props.setProperty(LOCATORS, "");

  DistributedSystem ds = new CacheServerTestUtil().getSystem(props);;

  PoolFactoryImpl pf = (PoolFactoryImpl) PoolManager.createFactory();
  pf.init(poolAttr);
  PoolImpl p = (PoolImpl) pf.create("CacheServerTestUtil");
  AttributesFactory factory = new AttributesFactory();
  factory.setScope(Scope.LOCAL);
  factory.setPoolName(p.getName());

  RegionAttributes attrs = factory.create();
  pool = p;
}
 
Example 7
Project: oscm   File: UserNotificationIT.java   View source code 6 votes vote down vote up
/**
 * Execute send mail without a valid server.
 */
@Test(expected = MailOperationException.class)
public void testSendMail_invServer() throws Exception {
    List<UserData> userData = new ArrayList<UserData>();
    UserData ud = new UserData();
    ud.email = testMailAddress;
    ud.userid = "newid";
    ud.olduserid = "oldid";
    userData.add(ud);

    Properties unProperties = getProperties(
            getProperiesForComputerName(unPropertiesFilePath));

    unProperties.setProperty(HandlerUtils.MAIL_SERVER, "invalidServer");
    userNotification.sendMail(userData, unProperties);
}
 
Example 8
Project: NGB-master   File: CommandManager.java   View source code 6 votes vote down vote up
private ServerParameters loadServerParameters(Properties serverProperties) {
    ServerParameters parameters = new ServerParameters();
    parameters.setServerUrl(serverProperties.getProperty(SERVER_URL_PROPERTY));
    parameters.setAuthPayload(serverProperties.getProperty(AUTHENTICATION_PROPERTY));
    parameters.setAuthenticationUrl(serverProperties.getProperty(AUTHENTICATION_URL_PROPERTY));
    parameters.setSearchUrl(serverProperties.getProperty(SEARCH_URL_PROPERTY));
    parameters.setRegistrationUrl(serverProperties.getProperty(REGISTRATION_URL_PROPERTY));
    parameters.setProjectLoadUrl(serverProperties.getProperty(PROJECT_URL_PROPERTY));
    parameters.setProjectLoadByIdUrl(serverProperties.getProperty(PROJECT_URL_BY_ID_PROPERTY));
    parameters.setFileFindUrl(serverProperties.getProperty(FIND_FILE_URL_PROPERTY));
    parameters.setVersionUrl(serverProperties.getProperty(VERSION_URL_PROPERTY));
    parameters.setMinSupportedServerVersion(
            Integer.parseInt(serverProperties.getProperty(SERVER_VERSION_PROPERTY)));
    parameters.setProjectTreeUrl(serverProperties.getProperty(PROJECT_TREE_URL_PROPERTY));
    return parameters;
}
 
Example 9
Project: rainbow   File: TestWorkloadEvaluation.java   View source code 6 votes vote down vote up
@Test
public void test()
{
    ConfigFactory.Instance().LoadProperties("/home/hank/Desktop/rainbow/rainbow-evaluate/rainbow.properties");
    Properties params = new Properties();
    params.setProperty("method", "PRESTO");
    params.setProperty("format", "ORC");
    params.setProperty("table.dir", "/rainbow2/orc");
    params.setProperty("table.name", "orc");
    params.setProperty("workload.file", "/home/hank/Desktop/rainbow/rainbow-evaluate/workload.txt");
    params.setProperty("log.dir", "/home/hank/Desktop/rainbow/rainbow-evaluate/workload_eva/");
    params.setProperty("drop.cache", "false");

    Invoker invoker = new InvokerWorkloadEvaluation();
    try
    {
        invoker.executeCommands(params);
    } catch (InvokerException e)
    {
        e.printStackTrace();
    }
}
 
Example 10
Project: incubator-netbeans   File: ProfilerWindow.java   View source code 6 votes vote down vote up
private boolean configureAttachSettings(boolean partially) {
    AttachSettings settings = AttachWizard.getDefault().configure(attachSettings, partially);
    if (settings == null) return false; // cancelled by the user
    
    attachSettings = settings;
    final AttachSettings as = new AttachSettings();
    attachSettings.copyInto(as);
    final Lookup.Provider lp = session.getProject();
    RequestProcessor.getDefault().post(new Runnable() {
        public void run() {
            Properties p = new Properties();
            as.store(p);
            try {
                ProfilerStorage.saveProjectProperties(p, lp, "attach"); // NOI18N
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
        
    return true;
}
 
Example 11
Project: syndesis   File: SqlCommon.java   View source code 6 votes vote down vote up
public Connection setupConnection(Connection connection, Properties properties) throws Exception {

        InputStream is = SqlCommon.class.getClassLoader().getResourceAsStream("application.properties");
        properties.load(is);
        String user     = String.valueOf(properties.get("sql-connector.user"));
        String password = String.valueOf(properties.get("sql-connector.password"));
        String url      = String.valueOf(properties.get("sql-connector.url"));

        System.out.println("Connecting to the database for unit tests");
        try {
            connection = DriverManager.getConnection(url,user,password);
        } catch (Exception ex) {
            fail("Exception during database startup.");
        }
        return connection;
    }
 
Example 12
Project: ServerBrowser   File: SettingsController.java   View source code 6 votes vote down vote up
private void configureLegacyPropertyComponents() {
	final Properties legacyProperties = LegacySettingsController.getLegacyProperties().orElse(new Properties());
	initLegacySettings(legacyProperties);

	fpsLimitSpinner.valueProperty().addListener(__ -> changeLegacyIntegerSetting(LegacySettingsController.FPS_LIMIT, fpsLimitSpinner.getValue()));
	pageSizeSpinner.valueProperty().addListener(__ -> changeLegacyIntegerSetting(LegacySettingsController.PAGE_SIZE, pageSizeSpinner.getValue()));

	multicoreCheckbox.setOnAction(__ -> changeLegacyBooleanSetting(LegacySettingsController.MULTICORE, multicoreCheckbox.isSelected()));
	audioMsgCheckBox.setOnAction(__ -> changeLegacyBooleanSetting(LegacySettingsController.AUDIO_MESSAGE_OFF, !audioMsgCheckBox.isSelected()));
	audioproxyCheckBox.setOnAction(__ -> changeLegacyBooleanSetting(LegacySettingsController.AUDIO_PROXY_OFF, !audioproxyCheckBox.isSelected()));
	timestampsCheckBox.setOnAction(__ -> changeLegacyBooleanSetting(LegacySettingsController.TIMESTAMP, timestampsCheckBox.isSelected()));
	headMoveCheckBox.setOnAction(__ -> changeLegacyBooleanSetting(LegacySettingsController.HEAD_MOVE, !headMoveCheckBox.isSelected()));
	imeCheckBox.setOnAction(__ -> changeLegacyBooleanSetting(LegacySettingsController.IME, imeCheckBox.isSelected()));
	directModeCheckBox.setOnAction(__ -> changeLegacyBooleanSetting(LegacySettingsController.DIRECT_MODE, directModeCheckBox.isSelected()));
	nameTagStatusCheckBox.setOnAction(__ -> changeLegacyBooleanSetting(LegacySettingsController.NO_NAME_TAG_STATUS, !nameTagStatusCheckBox.isSelected()));
}
 
Example 13
Project: ProyectoPacientes   File: StatementRegressionTest.java   View source code 6 votes vote down vote up
/**
 * Tests fix for BUG#10630, Statement.getWarnings() fails with NPE if
 * statement has been closed.
 */
public void testBug10630() throws Exception {
    Connection conn2 = null;
    Statement stmt2 = null;

    try {
        conn2 = getConnectionWithProps((Properties) null);
        stmt2 = conn2.createStatement();

        conn2.close();
        stmt2.getWarnings();
        fail("Should've caught an exception here");
    } catch (SQLException sqlEx) {
        assertEquals(SQLError.SQL_STATE_ILLEGAL_ARGUMENT, sqlEx.getSQLState());
    } finally {
        if (stmt2 != null) {
            stmt2.close();
        }

        if (conn2 != null) {
            conn2.close();
        }
    }
}
 
Example 14
Project: OSWf-OSWorkflow-fork   File: XMLTest.java   View source code 6 votes vote down vote up
public void testSaveWithWriter() throws IOException, ParserConfigurationException {
    propertySet.setBoolean("testBoolean", true);
    propertySet.setData("testData", "value1".getBytes());
    propertySet.setDate("testDate", new Date());
    propertySet.setDouble("testDouble", 10.245D);
    propertySet.setInt("testInt", 7);
    propertySet.setLong("testLong", 100000);
    propertySet.setObject("testObject", new TestObject(1));

    Properties props = new Properties();
    props.setProperty("prop1", "value1");
    propertySet.setProperties("testProperties", props);
    propertySet.setString("testString", "value1");
    propertySet.setText("testText", TEXT_VALUE);

    StringWriter writer = new StringWriter();
    ((XMLPropertySet) propertySet).save(writer);
    assertNotNull(writer.toString());
}
 
Example 15
Project: WebtoonDownloadManager   File: Main.java   View source code 6 votes vote down vote up
@Override
public void start(Stage primaryStage) throws IOException {

	/* 앱 버전 */
	Properties prop = new Properties();
	FileInputStream fis = new FileInputStream(Constants.SystemMessage.PROPERTY_PATH);
	prop.load(new java.io.BufferedInputStream(fis));
	String current = prop.getProperty(Constants.SystemMessage.PROPERTY_APP_KEY);

	/* 업데이트 앱 버전 체크 */
	ApplicationAPI api = new ApplicationAPI();
	Map<String, String> result = api.appCheck();
	String now = result.get("new_version");

	if (current != null && now != null) {
		if (!current.equals(now)) {
			AlertSupport alert = new AlertSupport(Constants.AlertInfoMessage.VERSION_UPDATE_MESSAGE);
			int c = alert.alertConfirm();
			if (c == 1) {
				Runtime runTime = Runtime.getRuntime();
				try {
					primaryStage.close();
					runTime.exec(Constants.SystemMessage.UPDATE_APP_PATH);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				// 업데이트를 하지 않을 때
				run(primaryStage, current);
			}
		} else {
			// 최신버전일때
			run(primaryStage, current);
		}
	}
}
 
Example 16
Project: lemon   File: PropertiesUtils.java   View source code 6 votes vote down vote up
public static void bindProperties(Object object, Properties properties,
        String prefix) {
    if (properties == null) {
        throw new IllegalArgumentException(
                "there is no properties setting.");
    }

    logger.debug("prefix : {}", prefix);

    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();

        if (!key.startsWith(prefix)) {
            continue;
        }

        String propertyName = key.substring(prefix.length());

        tryToSetProperty(object, propertyName, value);
    }
}
 
Example 17
Project: apollo-custom   File: ConfigIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void testGetConfigWithLocalFileAndWithRemoteConfig() throws Exception {
  String someKey = "someKey";
  String someValue = "someValue";
  String anotherValue = "anotherValue";
  Properties properties = new Properties();
  properties.put(someKey, someValue);
  createLocalCachePropertyFile(properties);

  ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, anotherValue));
  ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
  startServerWithHandlers(handler);

  Config config = ConfigService.getAppConfig();

  assertEquals(anotherValue, config.getProperty(someKey, null));
}
 
Example 18
Project: apollo-custom   File: JsonConfigFileTest.java   View source code 6 votes vote down vote up
@Test
public void testWhenHasContent() throws Exception {
  Properties someProperties = new Properties();
  String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
  String someValue = "someValue";
  someProperties.setProperty(key, someValue);

  when(configRepository.getConfig()).thenReturn(someProperties);

  JsonConfigFile configFile = new JsonConfigFile(someNamespace, configRepository);

  assertEquals(ConfigFileFormat.JSON, configFile.getConfigFileFormat());
  assertEquals(someNamespace, configFile.getNamespace());
  assertTrue(configFile.hasContent());
  assertEquals(someValue, configFile.getContent());
}
 
Example 19
Project: monarch   File: ClusterConfigurationService.java   View source code 6 votes vote down vote up
private void persistSecuritySettings(final Region<String, Configuration> configRegion) {
  Properties securityProps = cache.getDistributedSystem().getSecurityProperties();

  Configuration clusterPropertiesConfig =
      configRegion.get(ClusterConfigurationService.CLUSTER_CONFIG);
  if (clusterPropertiesConfig == null) {
    clusterPropertiesConfig = new Configuration(ClusterConfigurationService.CLUSTER_CONFIG);
    configRegion.put(ClusterConfigurationService.CLUSTER_CONFIG, clusterPropertiesConfig);
  }
  // put security-manager and security-post-processor in the cluster config
  Properties clusterProperties = clusterPropertiesConfig.getGemfireProperties();

  if (securityProps.containsKey(SECURITY_MANAGER)) {
    clusterProperties.setProperty(SECURITY_MANAGER, securityProps.getProperty(SECURITY_MANAGER));
  }
  if (securityProps.containsKey(SECURITY_POST_PROCESSOR)) {
    clusterProperties.setProperty(SECURITY_POST_PROCESSOR,
        securityProps.getProperty(SECURITY_POST_PROCESSOR));
  }
}
 
Example 20
Project: incubator-netbeans   File: WindowsNativeUtils.java   View source code 6 votes vote down vote up
private void rollbackDefaultApplication(SystemApplicationKey app, FileExtensionKey fe, Properties props) throws NativeException {
    String property;
    if(app.isUseByDefault() == null || app.isUseByDefault().booleanValue() == true) {
        String name = fe.getDotName();
        String extKey = fe.getKey();            
        property = getExtProperty(props, name, EXT_HKCRSHELL_OPEN_COMMAND_PROPERTY);
        if(property!=null) {
            String s = SHELL_OPEN_COMMAND;
            registry.deleteKey(clSection, clKey +  extKey + s);  //  delete command
            s = s.substring(0,s.lastIndexOf(SEP));
            registry.deleteKey(clSection, clKey +  extKey + s);  //  delete open
            s = s.substring(0,s.lastIndexOf(SEP)); //
            registry.deleteKey(clSection, clKey +  extKey + s);  //  delete shell
        }
        property = getExtProperty(props, name, DOT + EXT_HKCU_DEFAULTAPP_PROPERTY);
        
        if(registry.keyExists(HKCU, CURRENT_USER_FILE_EXT_KEY + SEP + name)) {
            if(property!=null) {
                registry.setStringValue(HKCU, CURRENT_USER_FILE_EXT_KEY + SEP + name, APPLICATION_VALUE_NAME, property);
            } else if(app.isUseByDefault()!=null) {
                registry.deleteValue(HKCU, CURRENT_USER_FILE_EXT_KEY + SEP + name, APPLICATION_VALUE_NAME);
            }
        }
    }
}
 
Example 21
Project: oscm   File: BrandServiceBeanNoDBTest.java   View source code 6 votes vote down vote up
@Test
public void loadMessagePropertiesFromDB_bug10739_MsgNotExistsInShop()
        throws Exception {
    // given
    doReturn(marketplace).when(ds).getReferenceByBusinessKey(
            any(Marketplace.class));
    Properties properties = prepareProperties("key", "value");
    doReturn(new Properties()).when(localizerService)
            .loadLocalizedPropertiesFromDatabase(anyLong(),
                    eq(LocalizedObjectTypes.SHOP_MESSAGE_PROPERTIES),
                    eq(Locale.ENGLISH.toString()));
    doReturn(properties).when(localizerService)
            .loadLocalizedPropertiesFromDatabase(anyLong(),
                    eq(LocalizedObjectTypes.MESSAGE_PROPERTIES),
                    eq(Locale.ENGLISH.toString()));
    doReturn(new Properties()).when(localizerService)
            .loadLocalizedPropertiesFromDatabase(anyLong(),
                    eq(LocalizedObjectTypes.MAIL_PROPERTIES),
                    eq(Locale.ENGLISH.toString()));
    // when
    Properties result = brandServiceBean.loadMessagePropertiesFromDB(
            "marketplaceId", Locale.ENGLISH.toString());
    // then
    assertEquals(properties.size(), result.size());
}
 
Example 22
Project: osc-core   File: FileUtilTest.java   View source code 6 votes vote down vote up
@Test
public void testLoadProperties_WithUnavailableConfigFile_ThrowsIOException() throws IOException {
    // Arrange.
    File regularFile = new File(this.homeDirectory, this.CONFIG_FILE);
    if(this.regularFile.exists()){
        boolean isDeleted = this.regularFile.delete();
        Assert.assertTrue(isDeleted);
    }

    this.exception.expect(FileNotFoundException.class);

    // Act.
    Properties prop = FileUtil.loadProperties(regularFile.getAbsolutePath());

    // Assert.
    Assert.assertEquals("Different size of loaded properties file", 0, prop.size());
}
 
Example 23
Project: Cognizant-Intelligent-Test-Scripter   File: QCSync.java   View source code 6 votes vote down vote up
@Override
public synchronized boolean updateResults(TestInfo tc, String status,
        List<File> attach) {
    try {
        String tsPath = Control.exe.getExecSettings().getTestMgmgtSettings().getProperty("qcTestsetLocation");
        String tsName = Control.exe.getExecSettings().getTestMgmgtSettings().getProperty("qcTestsetName");
        Properties vMap = tc.getMap();
        vMap.putAll(Control.exe.getProject().getProjectSettings().getUserDefinedSettings());
        tsPath = KeyMap.resolveContextVars(tsPath, vMap);
        tsName = KeyMap.resolveContextVars(tsName, vMap);
        if (qc.QCUpdateTCStatus(qcCon, tsPath, tsName, tc.testScenario,
                tc.testCase, "[1]", tc.testCase + "@" + tc.date + "_"
                + tc.time, status, attach)) {
            System.out.println("Result Updated  in QC-ALM !!!");
            return true;
        } else {
            System.out.println("Error while Updating Result in QC-ALM !!!");
        }
    } catch (Exception ex) {
        System.out.println("Error while Updating Result in QC-ALM !!!");
        LOG.log(Level.SEVERE, null, ex);
    }
    return false;
}
 
Example 24
Project: openjdk-jdk10   File: ValueHandler.java   View source code 6 votes vote down vote up
private static String getProperty(Properties properties,
                                  String prefix, String name) {
    if (prefix == null || prefix.isEmpty()) {
        return properties.getProperty(name);
    }
    int index = prefix.length();
    do {
        String value = properties.getProperty(
                Utils.prependPrefix(prefix.substring(0, index), name));
        if (value != null) {
            return value;
        }
        index = prefix.lastIndexOf('.', index - 1);
    } while (index > 0);
    return  properties.getProperty(name);
}
 
Example 25
Project: RLibrary   File: Root.java   View source code 6 votes vote down vote up
public static String loadProperties(String key) {
    L.d("root before loadProperties key : " + key);
    if (TextUtils.isEmpty(key)) {
        return "";
    }
    String value = null;
    try {
        value = loadProperties(new Function2<Properties, String, Void>() {
            @Override
            public Void invoke(Properties properties, String writer) {
                return null;
            }
        }).getProperty(key);
    } catch (Exception e) {
        e.printStackTrace();
        value = "";
    }
    L.d("root loadProperties key : " + key + " value : " + value);

    if (TextUtils.isEmpty(value)) {
        return "";
    } else {
        return value;
    }
}
 
Example 26
Project: OpenVertretung   File: StandardSocketFactory.java   View source code 5 votes vote down vote up
/**
 * Configures socket properties based on properties from the connection
 * (tcpNoDelay, snd/rcv buf, traffic class, etc).
 * 
 * @param props
 * @throws SocketException
 * @throws IOException
 */
private void configureSocket(Socket sock, Properties props) throws SocketException, IOException {
    sock.setTcpNoDelay(Boolean.valueOf(props.getProperty(TCP_NO_DELAY_PROPERTY_NAME, TCP_NO_DELAY_DEFAULT_VALUE)).booleanValue());

    String keepAlive = props.getProperty(TCP_KEEP_ALIVE_PROPERTY_NAME, TCP_KEEP_ALIVE_DEFAULT_VALUE);

    if (keepAlive != null && keepAlive.length() > 0) {
        sock.setKeepAlive(Boolean.valueOf(keepAlive).booleanValue());
    }

    int receiveBufferSize = Integer.parseInt(props.getProperty(TCP_RCV_BUF_PROPERTY_NAME, TCP_RCV_BUF_DEFAULT_VALUE));

    if (receiveBufferSize > 0) {
        sock.setReceiveBufferSize(receiveBufferSize);
    }

    int sendBufferSize = Integer.parseInt(props.getProperty(TCP_SND_BUF_PROPERTY_NAME, TCP_SND_BUF_DEFAULT_VALUE));

    if (sendBufferSize > 0) {
        sock.setSendBufferSize(sendBufferSize);
    }

    int trafficClass = Integer.parseInt(props.getProperty(TCP_TRAFFIC_CLASS_PROPERTY_NAME, TCP_TRAFFIC_CLASS_DEFAULT_VALUE));

    if (trafficClass > 0) {
        sock.setTrafficClass(trafficClass);
    }
}
 
Example 27
Project: oscm   File: MailReader.java   View source code 5 votes vote down vote up
private void initialize() throws Exception {
    PropertiesReader reader = new PropertiesReader();
    Properties props = reader.load();
    mailProviderType = props.getProperty("mail.servertype");
    mailUser = props.getProperty("mail.username");
    mailPassword = props.getProperty("mail.password");
    mailServer = props.getProperty("mail.server");
    mailAddress = props.getProperty("mail.address");
}
 
Example 28
Project: oscm   File: PSPResponse.java   View source code 5 votes vote down vote up
/**
 * Converts the input given in the request to a properties object.
 * 
 * @param request
 *            The received request.
 * @return The properties contained in the request.
 * @throws IOException
 *             Thrown in case the request information could not be
 *             evaluated.
 */
private boolean determinePSPParams(HttpServletRequest request, Properties p) {
    

    try {
        ServletInputStream inputStream = request.getInputStream();
        if (inputStream == null) {
            return false;
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(
                inputStream, "UTF-8"));
        String line = br.readLine();
        StringBuffer sb = new StringBuffer();
        while (line != null) {
            sb.append(line);
            line = br.readLine();
        }
        String params = sb.toString();
        StringTokenizer st = new StringTokenizer(params, "&");
        while (st.hasMoreTokens()) {
            String nextToken = st.nextToken();
            String[] splitResult = nextToken.split("=");
            String key = splitResult[0];
            String value = "";
            if (splitResult.length > 1) {
                value = URLDecoder.decode(splitResult[1], "UTF-8");
            }
            p.setProperty(key, value);
        }
        return validateResponse(p);
    } catch (IOException e) {
        // if the request information cannot be read, we cannot determine
        // whether the registration worked or not. Hence we assume it
        // failed, log a warning and return the failure-URL to the PSP.
        logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.WARN_HEIDELPAY_INPUT_PROCESS_FAILED);
    }
    
    return false;
}
 
Example 29
Project: sentry   File: SchedulerConfiguration.java   View source code 5 votes vote down vote up
@Bean
public Properties quartzProperties() throws IOException {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocations(new FileSystemResource("quartz.properties"));
    propertiesFactoryBean.afterPropertiesSet();
    return propertiesFactoryBean.getObject();
}
 
Example 30
Project: bluewatcher   File: Transliterator.java   View source code 5 votes vote down vote up
public Transliterator(Context context) {
	AssetManager assets = context.getAssets();
	InputStream stream = null;
	try {
		stream = assets.open(TRANSLITERATION_PROPERTIES);
		transliteration = new Properties();
		transliteration.load(new InputStreamReader(stream, "UTF-8"));
		stream.close();
	}
	catch (IOException e) {
		transliteration = null;
	}
}
 
Example 31
Project: kafka-0.11.0.0-src-with-comment   File: StreamPartitionAssignorTest.java   View source code 5 votes vote down vote up
@Test
public void testAssignWithPartialTopology() throws Exception {
    Properties props = configProps();
    props.put(StreamsConfig.PARTITION_GROUPER_CLASS_CONFIG, SingleGroupPartitionGrouperStub.class);
    StreamsConfig config = new StreamsConfig(props);

    builder.addSource("source1", "topic1");
    builder.addProcessor("processor1", new MockProcessorSupplier(), "source1");
    builder.addStateStore(new MockStateStoreSupplier("store1", false), "processor1");
    builder.addSource("source2", "topic2");
    builder.addProcessor("processor2", new MockProcessorSupplier(), "source2");
    builder.addStateStore(new MockStateStoreSupplier("store2", false), "processor2");
    List<String> topics = Utils.mkList("topic1", "topic2");
    Set<TaskId> allTasks = Utils.mkSet(task0, task1, task2);

    UUID uuid1 = UUID.randomUUID();
    String client1 = "client1";

    StreamThread thread10 = new StreamThread(builder, config, mockClientSupplier, "test", client1, uuid1, new Metrics(), Time.SYSTEM, new StreamsMetadataState(builder, StreamsMetadataState.UNKNOWN_HOST), 0);

    partitionAssignor.configure(config.getConsumerConfigs(thread10, "test", client1));
    partitionAssignor.setInternalTopicManager(new MockInternalTopicManager(thread10.config, mockClientSupplier.restoreConsumer));
    Map<String, PartitionAssignor.Subscription> subscriptions = new HashMap<>();
    subscriptions.put("consumer10",
        new PartitionAssignor.Subscription(topics, new SubscriptionInfo(uuid1, Collections.<TaskId>emptySet(), Collections.<TaskId>emptySet(), userEndPoint).encode()));


    // will throw exception if it fails
    Map<String, PartitionAssignor.Assignment> assignments = partitionAssignor.assign(metadata, subscriptions);

    // check assignment info
    Set<TaskId> allActiveTasks = new HashSet<>();
    AssignmentInfo info10 = checkAssignment(Utils.mkSet("topic1"), assignments.get("consumer10"));
    allActiveTasks.addAll(info10.activeTasks);

    assertEquals(3, allActiveTasks.size());
    assertEquals(allTasks, new HashSet<>(allActiveTasks));
}
 
Example 32
Project: butterfly   File: RemoveLineTest.java   View source code 5 votes vote down vote up
@Test
public void removeLineNumberTest() throws IOException {
    RemoveLine removeLine = new RemoveLine(2).relative("/src/main/resources/application.properties");
    TOExecutionResult executionResult = removeLine.execution(transformedAppFolder, transformationContext);
    Assert.assertEquals(executionResult.getType(), TOExecutionResult.Type.SUCCESS);

    assertChangedFile("/src/main/resources/application.properties");
    assertLineCount("/src/main/resources/application.properties", -1);

    Properties properties = getProperties("/src/main/resources/application.properties");

    Assert.assertEquals(properties.size(), 2);
    Assert.assertEquals(properties.getProperty("foo"), "foov");
    Assert.assertEquals(properties.getProperty("foofoo"), "foofoov");
}
 
Example 33
Project: sunshine   File: ConfigFromFile.java   View source code 5 votes vote down vote up
Properties get() {
    if (props.isEmpty()) {
        try {
            Properties property = new Properties();
            property.load(from);
            props.add(property);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return props.get(0);
}
 
Example 34
Project: CloudNet   File: CloudServerMeta.java   View source code 5 votes vote down vote up
public CloudServerMeta(ServiceId serviceId, int memory, boolean priorityStop, String[] processParameters, Collection<ServerInstallablePlugin> plugins, ServerConfig serverConfig, int port, String templateName, Properties properties, ServerGroupType serverGroupType)
{
    this.serviceId = serviceId;
    this.memory = memory;
    this.priorityStop = priorityStop;
    this.processParameters = processParameters;
    this.plugins = plugins;
    this.serverConfig = serverConfig;
    this.port = port;
    this.templateName = templateName;
    this.serverProperties = properties;
    this.serverGroupType = serverGroupType;
    this.template = new Template(templateName, TemplateResource.MASTER, null, new String[0], new ArrayList<>());
}
 
Example 35
Project: monarch   File: MultiRegionFunctionExecutionDUnitTest.java   View source code 5 votes vote down vote up
public void createCache() {
  try {
    Properties props = new Properties();
    DistributedSystem ds = getSystem(props);
    assertNotNull(ds);
    ds.disconnect();
    ds = getSystem(props);
    cache = CacheFactory.create(ds);
    assertNotNull(cache);
  } catch (Exception e) {
    org.apache.geode.test.dunit.Assert.fail("Failed while creating the cache", e);
  }
}
 
Example 36
Project: ramus   File: FileIEngineImpl.java   View source code 5 votes vote down vote up
private FileMetadata loadFileMetadata() throws IOException {
    ZipEntry entry = new ZipEntry(APPLICATION_METADATA);
    InputStream is = zFile.getInputStream(entry);
    if (is != null) {

        Properties ps = new Properties();
        ps.loadFromXML(is);

        FileMetadata fileMetadata = new FileMetadata(ps);
        is.close();
        return fileMetadata;
    }
    return null;
}
 
Example 37
Project: open-kilda   File: AbstractStormTest.java   View source code 5 votes vote down vote up
protected static Properties kafkaProperties() throws ConfigurationException, CmdLineException {
    Properties properties = new Properties();
    properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, makeUnboundConfig().getKafkaHosts());
    properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test");
    properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
    properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
    properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
    properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
    properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
    properties.put("request.required.acks", "1");
    return properties;
}
 
Example 38
Project: LightSIP   File: MultipleContactsTest.java   View source code 5 votes vote down vote up
public Client() {
    try {
        final Properties defaultProperties = new Properties();
        String host = "127.0.0.1";
        defaultProperties.setProperty("javax.sip.STACK_NAME", "client");
        defaultProperties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "DEBUG");
        defaultProperties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "client_debug.txt");
        defaultProperties.setProperty("gov.nist.javax.sip.SERVER_LOG", "client_log.txt");
        defaultProperties.setProperty("gov.nist.javax.sip.READ_TIMEOUT", "1000");
        defaultProperties.setProperty("gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS","false");
        if(System.getProperty("enableNIO") != null && System.getProperty("enableNIO").equalsIgnoreCase("true")) {
        	defaultProperties.setProperty("gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY", NioMessageProcessorFactory.class.getName());
        }
        this.sipFactory = SipFactory.getInstance();
        this.sipFactory.setPathName("gov.nist");
        this.sipStack = this.sipFactory.createSipStack(defaultProperties);
        this.sipStack.start();
        ListeningPoint lp = this.sipStack.createListeningPoint(host, CLIENT_PORT, testProtocol);
        this.provider = this.sipStack.createSipProvider(lp);
        headerFactory = this.sipFactory.createHeaderFactory();
        messageFactory = this.sipFactory.createMessageFactory();
        addressFactory = this.sipFactory.createAddressFactory();
        this.provider.addSipListener(this);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("unexpected exception ");
    }
}
 
Example 39
Project: jdk8u-jdk   File: LoadAndStoreXMLWithDefaults.java   View source code 5 votes vote down vote up
@Override
public Properties loadFromXML(String xml, Properties defaults)
        throws IOException {
    final ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    Properties p = new Properties(defaults);
    p.loadFromXML(bais);
    return p;
}
 
Example 40
Project: rmq4note   File: DefaultMQAdminExtImpl.java   View source code 5 votes vote down vote up
@Override
public void updateNameServerConfig(final Properties properties, final List<String> nameServers)
    throws InterruptedException, RemotingConnectException,
    UnsupportedEncodingException, RemotingSendRequestException, RemotingTimeoutException,
    MQClientException, MQBrokerException {
    this.mqClientInstance.getMQClientAPIImpl().updateNameServerConfig(properties, nameServers, timeoutMillis);
}