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   Source Code and License 7 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: kafka-streams-on-heroku   File: TextProcessorConfig.java   Source Code and License 5 votes vote down vote up
private Properties buildDefaults() throws CertificateException, NoSuchAlgorithmException,
    KeyStoreException, IOException, URISyntaxException {
  Properties defaultProperties = new Properties();
  Properties herokuKafkaConfigVarProperties = buildHerokuKafkaConfigVars();
  Properties kafkaStreamsProperties = buildKafkaStreamsDefaults();

  defaultProperties.putAll(herokuKafkaConfigVarProperties);
  defaultProperties.putAll(kafkaStreamsProperties);


  return defaultProperties;
}
 
Example 42
Project: parabuild-ci   File: PromotionPolicyStepListTable.java   Source Code and License 5 votes vote down vote up
void setStep(final PromotionPolicyStep step) {
  // Up
  final Properties upProps = createProperties(step);
  upProps.setProperty(Pages.PARAM_PROMOTION_STEP_OPERATION_CODE, Pages.PARAM_PROMOTION_STEP_OPERATION_UP);
  lnkUp.setParameters(upProps);
  // Down
  final Properties downProps = createProperties(step);
  downProps.setProperty(Pages.PARAM_PROMOTION_STEP_OPERATION_CODE, Pages.PARAM_PROMOTION_STEP_OPERATION_DOWN);
  lnkDown.setParameters(downProps);
}
 
Example 43
Project: bootstrap   File: SequenceIdentifierGeneratorStrategyProvider.java   Source Code and License 5 votes vote down vote up
@Override
protected QualifiedName determineSequenceName(final Properties params, final Dialect dialect, final JdbcEnvironment jdbcEnv) {
	// Make sure sequence are lower case and corresponds to table name
	params.put(SEQUENCE_PARAM, StringHelper.unquote(params.getProperty("identity_tables"))
			+ ConfigurationHelper.getString(CONFIG_SEQUENCE_PER_ENTITY_SUFFIX, params, DEF_SEQUENCE_SUFFIX));
	return super.determineSequenceName(params, dialect, jdbcEnv);
}
 
Example 44
Project: rmq4note   File: AdminBrokerProcessor.java   Source Code and License 5 votes vote down vote up
private RemotingCommand updateBrokerConfig(ChannelHandlerContext ctx, RemotingCommand request) {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);

    log.info("updateBrokerConfig called by {}", RemotingHelper.parseChannelRemoteAddr(ctx.channel()));

    byte[] body = request.getBody();
    if (body != null) {
        try {
            String bodyStr = new String(body, MixAll.DEFAULT_CHARSET);
            Properties properties = MixAll.string2Properties(bodyStr);
            if (properties != null) {
                log.info("updateBrokerConfig, new config: [{}] client: {} ", properties, ctx.channel().remoteAddress());
                this.brokerController.getConfiguration().update(properties);
                if (properties.containsKey("brokerPermission")) {
                    this.brokerController.registerBrokerAll(false, false);
                    this.brokerController.getTopicConfigManager().getDataVersion().nextVersion();
                }
            } else {
                log.error("string2Properties error");
                response.setCode(ResponseCode.SYSTEM_ERROR);
                response.setRemark("string2Properties error");
                return response;
            }
        } catch (UnsupportedEncodingException e) {
            log.error("", e);
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("UnsupportedEncodingException " + e);
            return response;
        }
    }

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example 45
Project: Reer   File: InProcessGradleExecuter.java   Source Code and License 5 votes vote down vote up
private BuildResult doRun(StandardOutputListener outputListener, StandardOutputListener errorListener, BuildListenerImpl listener) {
    // Capture the current state of things that we will change during execution
    InputStream originalStdIn = System.in;
    Properties originalSysProperties = new Properties();
    originalSysProperties.putAll(System.getProperties());
    File originalUserDir = new File(originalSysProperties.getProperty("user.dir")).getAbsoluteFile();
    Map<String, String> originalEnv = new HashMap<String, String>(System.getenv());

    GradleInvocation invocation = buildInvocation();
    Set<String> changedEnvVars = new HashSet<String>(invocation.environmentVars.keySet());

    try {
        return executeBuild(invocation, outputListener, errorListener, listener);
    } finally {
        // Restore the environment
        System.setProperties(originalSysProperties);
        resetTempDirLocation();
        processEnvironment.maybeSetProcessDir(originalUserDir);
        for (String envVar : changedEnvVars) {
            String oldValue = originalEnv.get(envVar);
            if (oldValue != null) {
                processEnvironment.maybeSetEnvironmentVariable(envVar, oldValue);
            } else {
                processEnvironment.maybeRemoveEnvironmentVariable(envVar);
            }
        }
        System.setProperty("user.dir", originalSysProperties.getProperty("user.dir"));
        System.setIn(originalStdIn);
    }
}
 
Example 46
Project: openjdk-jdk10   File: CompatibilityTest.java   Source Code and License 5 votes vote down vote up
static void loadPropertyFile(String filename) {
    try (InputStream in = new FileInputStream(filename)) {
        Properties prop = new Properties();
        prop.loadFromXML(in);
        verifyProperites(prop);
    } catch (IOException ex) {
        fail(ex.getMessage());
    }
}
 
Example 47
Project: monarch   File: ClusterConfigBaseTest.java   Source Code and License 5 votes vote down vote up
@Before
public void before() throws Exception {
  clusterConfigZipPath = buildClusterZipFile();
  locatorProps = new Properties();
  serverProps = new Properties();

  // the following are default values, we don't need to set them. We do it for clarity purpose
  locatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
  serverProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
}
 
Example 48
Project: ProyectoPacientes   File: ConnectionImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a connection instance -- We need to provide factory-style methods
 * so we can support both JDBC3 (and older) and JDBC4 runtimes, otherwise
 * the class verifier complains when it tries to load JDBC4-only interface
 * classes that are present in JDBC4 method signatures.
 */

protected static Connection getInstance(String hostToConnectTo, int portToConnectTo, Properties info, String databaseToConnectTo, String url)
        throws SQLException {
    if (!Util.isJdbc4()) {
        return new ConnectionImpl(hostToConnectTo, portToConnectTo, info, databaseToConnectTo, url);
    }

    return (Connection) Util.handleNewInstance(JDBC_4_CONNECTION_CTOR,
            new Object[] { hostToConnectTo, Integer.valueOf(portToConnectTo), info, databaseToConnectTo, url }, null);
}
 
Example 49
Project: alfresco-repository   File: MultiTAdminServiceImpl.java   Source Code and License 5 votes vote down vote up
private void importBootstrapVersionTenantStore(String tenantDomain, File directorySource)
{
    // Import Bootstrap (restore) Tenant-Specific Version Store
    Properties bootstrapView = new Properties();
    bootstrapView.put("path", "/");
    bootstrapView.put("location", directorySource.getPath()+"/"+tenantDomain+"_versions2.acp");
    
    List<Properties> bootstrapViews = new ArrayList<Properties>(1);
    bootstrapViews.add(bootstrapView);
    
    ImporterBootstrap versionImporterBootstrap = (ImporterBootstrap)ctx.getBean("versionBootstrap");
    versionImporterBootstrap.setBootstrapViews(bootstrapViews);
    
    bootstrapVersionTenantStore(versionImporterBootstrap, tenantDomain);
}
 
Example 50
Project: oscm   File: PropertyImportControllerTest.java   Source Code and License 5 votes vote down vote up
@Ignore
@Test
public void execute_ProxySettings() {
    // given
    Properties p = givenAppProperties(ControllerId.WITH_VALUE);
    doReturn(p).when(propImportProxy)
            .loadProperties(any(InputStream.class));

    // when
    propImportProxy.execute();

    // then
    assertEquals(CONTROLLER_ID_PROXY, propImportProxy.getControllerId());
}
 
Example 51
Project: SigPloit   File: SriSMLowLevelServer.java   Source Code and License 5 votes vote down vote up
public void init() {
    try {


        InputStream inStreamLog4j = SriSMLowLevelServer.class.getResourceAsStream("log4j.properties");

        System.out.println("Input Stream = " + inStreamLog4j);

        Properties propertiesLog4j = new Properties();
        try {
            propertiesLog4j.load(inStreamLog4j);
            PropertyConfigurator.configure(propertiesLog4j);
        } catch (IOException e) {
            e.printStackTrace();
            BasicConfigurator.configure();
        }

        logger.debug("log4j configured");

        String lf = System.getProperties().getProperty(LOG_FILE_NAME);
        if (lf != null) {
            logFileName = lf;
        }

        // If already created a print writer then just use it.
        try {
            logger.addAppender(new FileAppender(new SimpleLayout(), logFileName));
        } catch (FileNotFoundException fnfe) {

        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }

}
 
Example 52
Project: light-4-j-plugin-wrapper   File: PluginServiceImpl.java   Source Code and License 5 votes vote down vote up
private void initCache(Properties props){
	String apiKeysCSV = props.getProperty(API_KEYS);
	String methodsCSV = props.getProperty(METHODS);
	String[] apiKeys = apiKeysCSV.split(",");
	String[] methods = methodsCSV.split(",");
	
	System.out.println("Start Now is "+new java.util.Date()+", size is " + authorizations.size());
	for (String apiKey: apiKeys){
		for(String method: methods){
			putToAuthMap(apiKey+method, true);
		}
	}
	System.out.println("End Now is "+new java.util.Date()+", size is " + authorizations.size());

}
 
Example 53
Project: CentauriCloud   File: DirectoryInstaller.java   Source Code and License 5 votes vote down vote up
public void start(Scanner scanner, Properties config) {
	boolean change = false;

	Cloud.getLogger().info("Do you want change the modules dir? Type: true or false");
	change = Boolean.valueOf(scanner.nextLine());
	if (change) {
		Cloud.getLogger().info("Type the relative path. Default: modules/");
		config.setProperty("modulesDir", scanner.nextLine());
	}

	Cloud.getLogger().info("Do you want change the libraries dir? Type: true or false");
	change = Boolean.valueOf(scanner.nextLine());
	if (change) {
		Cloud.getLogger().info("Type the relative path. Default: libs/");
		config.setProperty("libDir", scanner.nextLine());
	}

	Cloud.getLogger().info("Do you want change the templates dir? Type: true or false");
	change = Boolean.valueOf(scanner.nextLine());
	if (change) {
		Cloud.getLogger().info("Type the relative path. Default: templates/");
		config.setProperty("templatesDir", scanner.nextLine());
	}

	Cloud.getLogger().info("Do you want change the shared dir? Type: true or false");
	change = Boolean.valueOf(scanner.nextLine());
	if (change) {
		Cloud.getLogger().info("Type the relative path. Default: shared/");
		config.setProperty("sharedDir", scanner.nextLine());
	}

	Cloud.getLogger().info("Do you want change the temporary dir? Type: true or false");
	change = Boolean.valueOf(scanner.nextLine());
	if (change) {
		Cloud.getLogger().info("Type the relative path. Default: tmp/");
		config.setProperty("tmpDir", scanner.nextLine());
	}

}
 
Example 54
Project: monarch   File: Configuration.java   Source Code and License 5 votes vote down vote up
public Configuration(String configName) {
  this.configName = configName;
  this.cacheXmlFileName = configName + ".xml";
  this.propertiesFileName = configName + ".properties";
  this.gemfireProperties = new Properties();
  this.jarNames = new HashSet<String>();
}
 
Example 55
Project: monarch   File: CacheServerTestUtil.java   Source Code and License 4 votes vote down vote up
private static Properties getClientProperties(boolean durable) {
  Properties props = new Properties();
  props.setProperty(MCAST_PORT, "0");
  props.setProperty(LOCATORS, "");
  return props;
}
 
Example 56
Project: the-vigilantes   File: ResultSetRegressionTest.java   Source Code and License 4 votes vote down vote up
/**
 * Tests fix for BUG#10485, SQLException thrown when retrieving YEAR(2) with
 * ResultSet.getString().
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug10485() throws Exception {

    if (versionMeetsMinimum(5, 7, 5)) {
        // Nothing to test, YEAR(2) is removed starting from 5.7.5
        return;
    }

    String tableName = "testBug10485";

    Calendar nydCal = null;

    if (((com.mysql.jdbc.Connection) this.conn).getUseGmtMillisForDatetimes()) {
        nydCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    } else {
        nydCal = Calendar.getInstance();
    }

    nydCal.set(2005, 0, 1, 0, 0, 0);

    Date newYears2005 = new Date(nydCal.getTime().getTime());

    createTable(tableName, "(field1 YEAR(2))");
    this.stmt.executeUpdate("INSERT INTO " + tableName + " VALUES ('05')");

    this.rs = this.stmt.executeQuery("SELECT field1 FROM " + tableName);
    assertTrue(this.rs.next());

    assertEquals(newYears2005.toString(), this.rs.getString(1));

    this.rs = this.conn.prepareStatement("SELECT field1 FROM " + tableName).executeQuery();
    assertTrue(this.rs.next());
    assertEquals(newYears2005.toString(), this.rs.getString(1));

    Properties props = new Properties();
    props.setProperty("yearIsDateType", "false");

    Connection yearShortConn = getConnectionWithProps(props);
    this.rs = yearShortConn.createStatement().executeQuery("SELECT field1 FROM " + tableName);
    assertTrue(this.rs.next());

    String expectedShort = versionMeetsMinimum(5, 6, 6) ? "2005" : "05";

    assertEquals(expectedShort, this.rs.getString(1));

    this.rs = yearShortConn.prepareStatement("SELECT field1 FROM " + tableName).executeQuery();
    assertTrue(this.rs.next());
    assertEquals(expectedShort, this.rs.getString(1));

    if (versionMeetsMinimum(5, 0)) {

        createProcedure("testBug10485", "()\nBEGIN\nSELECT field1 FROM " + tableName + ";\nEND");

        this.rs = this.conn.prepareCall("{CALL testBug10485()}").executeQuery();
        assertTrue(this.rs.next());
        assertEquals(newYears2005.toString(), this.rs.getString(1));

        this.rs = yearShortConn.prepareCall("{CALL testBug10485()}").executeQuery();
        assertTrue(this.rs.next());
        assertEquals(expectedShort, this.rs.getString(1));

    }
}
 
Example 57
Project: monarch   File: QuarterPartitionResolver.java   Source Code and License 4 votes vote down vote up
public Properties getConfig() {
  return this.resolveProps;
}
 
Example 58
Project: learn-kafka   File: TransactionalProducerApp.java   Source Code and License 4 votes vote down vote up
private static Properties getProducerProperties(String clientId, String transactionalId) {

        Properties properties = new Properties();

        /**
         * A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client will
         * make use of all servers irrespective of which servers are specified here for bootstrapping—this list only
         * impacts the initial hosts used to discover the full set of servers. This list should be in the form
         * host1:port1,host2:port2,.... Since these servers are just used for the initial connection to discover the full
         * cluster membership (which may change dynamically), this list need not contain the full set of servers (you
         * may want more than one, though, in case a server is down).
         */
        properties.put(KafkaConfig.Producer.BOOTSTRAP_SERVERS, String.join(", ", Setup.KafkaServers));

        /**
         * Serializer class for key that implements the Serializer interface.
         */
        properties.put(KafkaConfig.Producer.KEY_SERIALIZER, StringSerializer.class.getName());

        /**
         * Serializer class for value that implements the Serializer interface.
         */
        properties.put(KafkaConfig.Producer.VALUE_SERIALIZER, MessageJsonSerializer.class.getName());

        /**
         * An id string to pass to the server when making requests. The purpose of this is to be able to track the source
         * of requests beyond just ip/port by allowing a logical application name to be included in server-side request
         * logging.
         */
        properties.put(KafkaConfig.Producer.CLIENT_ID, clientId);

        /**
         * The TransactionalId to use for transactional delivery. This enables reliability semantics which span multiple
         * producer sessions since it allows the client to guarantee that transactions using the same TransactionalId
         * have been completed prior to starting any new transactions. If no TransactionalId is provided, then the
         * producer is limited to idempotent delivery. Note that enable.idempotence must be enabled if a TransactionalId
         * is configured. The default is empty, which means transactions cannot be used.
         */
        properties.put(KafkaConfig.Producer.TRANSACTIONAL_ID, transactionalId);

        return properties;
    }
 
Example 59
Project: proteus-consumer-couchbase   File: ProteusFlatnessTask.java   Source Code and License 4 votes vote down vote up
@Override
public void setup(Properties runnerProperties) {
	logger.info("Task: < " + this.getClass().getName() + "  > launched over topic "
			+ ConsumerUtils.getTopicName(runnerProperties.getProperty("eu.proteus.kafkaTopic")));
}
 
Example 60
Project: dacapobench   File: ClinitInstrument.java   Source Code and License 4 votes vote down vote up
public static ClassVisitor make(ClassVisitor cv, TreeMap<String,Integer> methodToLargestLocal, 
		Properties options, Properties state) {
	if (options.containsKey(CLASSES_INITIALIZATION))
		cv = new ClinitInstrument(cv, methodToLargestLocal, options, state, options.getProperty(CLASSES_INITIALIZATION)); 
	return cv;
}