Example usage for java.util Properties Properties

List of usage examples for java.util Properties Properties

Introduction

In this page you can find the example usage for java.util Properties Properties.

Prototype

public Properties() 

Source Link

Document

Creates an empty property list with no default values.

Usage

From source file:de.uzk.hki.da.main.SIPBuilder.java

public static void main(String[] args) {

    TTCCLayout layout = new TTCCLayout();
    layout.setDateFormat("yyyy'-'MM'-'dd' 'HH':'mm':'ss");
    layout.setThreadPrinting(false);/*from   www  . ja va 2 s  .  c om*/
    ConsoleAppender consoleAppender = new ConsoleAppender(layout);
    logger.addAppender(consoleAppender);
    logger.setLevel(Level.DEBUG);

    properties = new Properties();
    try {
        properties.load(new InputStreamReader(
                (ClassLoader.getSystemResourceAsStream("configuration/config.properties"))));
    } catch (FileNotFoundException e1) {
        System.exit(Feedback.GUI_ERROR.toInt());
    } catch (IOException e2) {
        System.exit(Feedback.GUI_ERROR.toInt());
    }

    try {
        if (SystemUtils.IS_OS_WINDOWS)
            System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out), true, "CP850"));
        else
            System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out), true, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return;
    }

    String mainFolderPath = SIPBuilder.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    String confFolderPath, dataFolderPath;
    try {
        mainFolderPath = URLDecoder.decode(mainFolderPath, "UTF-8");
        confFolderPath = new File(mainFolderPath).getParent() + File.separator + "conf";
        dataFolderPath = new File(mainFolderPath).getParent() + File.separator + "data";
    } catch (UnsupportedEncodingException e) {
        confFolderPath = "conf";
        dataFolderPath = "data";
    }
    System.out.println("ConfFolderPath:" + confFolderPath);
    if (args.length == 0)
        startGUIMode(confFolderPath, dataFolderPath);
    else
        startCLIMode(confFolderPath, dataFolderPath, args);
}

From source file:com.widen.valet.importer.ImportZone.java

public static void main(String[] args) throws IOException {
    Properties properties = new Properties();

    InputStream stream = ImportZone.class.getResourceAsStream("importdns.properties");

    if (stream == null) {
        throw new RuntimeException("File importdns.properties not found!");
    }/*from   w w  w.  j  av  a 2s  . co  m*/

    properties.load(stream);

    new ImportZone(properties).run();
}

From source file:azkaban.jobtype.HadoopSecureHiveWrapper.java

public static void main(final String[] args) throws Exception {

    String propsFile = System.getenv(ProcessJob.JOB_PROP_ENV);
    Properties prop = new Properties();
    prop.load(new BufferedReader(new FileReader(propsFile)));

    hiveScript = prop.getProperty("hive.script");

    final Configuration conf = new Configuration();

    UserGroupInformation.setConfiguration(conf);
    securityEnabled = UserGroupInformation.isSecurityEnabled();

    if (shouldProxy(prop)) {
        UserGroupInformation proxyUser = null;
        String userToProxy = prop.getProperty("user.to.proxy");
        if (securityEnabled) {
            String filelocation = System.getenv(UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION);
            if (filelocation == null) {
                throw new RuntimeException("hadoop token information not set.");
            }/*from w  w w  .  ja va 2s .  c  o m*/
            if (!new File(filelocation).exists()) {
                throw new RuntimeException("hadoop token file doesn't exist.");
            }

            logger.info("Found token file " + filelocation);

            logger.info("Setting " + HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY + " to "
                    + filelocation);
            System.setProperty(HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY, filelocation);

            UserGroupInformation loginUser = null;

            loginUser = UserGroupInformation.getLoginUser();
            logger.info("Current logged in user is " + loginUser.getUserName());

            logger.info("Creating proxy user.");
            proxyUser = UserGroupInformation.createProxyUser(userToProxy, loginUser);

            for (Token<?> token : loginUser.getTokens()) {
                proxyUser.addToken(token);
            }
        } else {
            proxyUser = UserGroupInformation.createRemoteUser(userToProxy);
        }

        logger.info("Proxied as user " + userToProxy);

        proxyUser.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                runHive(args);
                return null;
            }
        });

    } else {
        logger.info("Not proxying. ");
        runHive(args);
    }
}

From source file:com.bluexml.tools.miscellaneous.PrepareSIDEModulesMigration.java

/**
 * @param args//from w w  w .j  a v a  2 s  .com
 */
public static void main(String[] args) {
    boolean inplace = false;

    String workspace = "/Users/davidabad/workspaces/SIDE-Modules/";
    String frameworkmodulesPath = "/Volumes/Data/SVN/side/HEAD/S-IDE/FrameworksModules/trunk/";
    String classifier_base = "enterprise";
    String version_base = "3.4.6";
    String classifier_target = "enterprise";
    String version_target = "3.4.11";
    String frameworkmodulesInplace = "/Volumes/Data/SVN/projects/Ifremer/IfremerV5/src/modules/mavenProjects";

    Properties props = new Properties();
    try {
        InputStream resourceAsStream = PrepareSIDEModulesMigration.class
                .getResourceAsStream("config.properties");
        if (resourceAsStream != null) {
            props.load(resourceAsStream);

            inplace = Boolean.parseBoolean(props.getProperty("inplace", Boolean.toString(inplace)));
            workspace = props.getProperty("workspace", workspace);
            frameworkmodulesPath = props.getProperty("frameworkmodulesPath", frameworkmodulesPath);
            classifier_base = props.getProperty("classifier_base", classifier_base);
            version_base = props.getProperty("version_base", version_base);
            classifier_target = props.getProperty("classifier_target", classifier_target);
            version_target = props.getProperty("version_target", version_target);
            frameworkmodulesInplace = props.getProperty("frameworkmodulesInplace", frameworkmodulesInplace);
        } else {
            System.out.println("no configuration founded in classpath config.properties");
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    System.out.println("properties :");
    Enumeration<?> propertyNames = props.propertyNames();
    while (propertyNames.hasMoreElements()) {
        String nextElement = propertyNames.nextElement().toString();
        System.out.println("\t " + nextElement + " : " + props.getProperty(nextElement));
    }

    File workspaceFile = new File(workspace);

    File targetHome = new File(workspaceFile, MIGRATION_FOLDER);
    if (targetHome.exists()) {
        try {
            FileUtils.deleteDirectory(targetHome);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    final String versionInProjectName = getVersionInProjectName(classifier_base, version_base);
    String versionInProjectName2 = getVersionInProjectName(classifier_target, version_target);

    if (frameworkmodulesPath.contains(",")) {
        // this is a list of paths
        String[] split = frameworkmodulesPath.split(",");
        for (String string : split) {
            if (StringUtils.trimToNull(string) != null) {
                executeInpath(inplace, string, classifier_base, version_base, classifier_target, version_target,
                        frameworkmodulesInplace, workspaceFile, versionInProjectName, versionInProjectName2);
            }
        }
    } else {
        executeInpath(inplace, frameworkmodulesPath, classifier_base, version_base, classifier_target,
                version_target, frameworkmodulesInplace, workspaceFile, versionInProjectName,
                versionInProjectName2);
    }

    System.out.println("Job's done !");
    System.out.println("Please check " + MIGRATION_FOLDER);
    System.out.println(
            "If all is ok you can use commit.sh in a terminal do : cd " + MIGRATION_FOLDER + "; sh commit.sh");
    System.out.println(
            "This script will create new svn projet and commit resources, add 'target' to svn:ignore ...");

}

From source file:edu.usc.goffish.gopher.impl.Main.java

public static void main(String[] args) {

    Properties properties = new Properties();
    try {/*from  ww w. j ava2  s  .  com*/
        properties.load(new FileInputStream(CONFIG_FILE));
    } catch (IOException e) {
        String message = "Error while loading Container Configuration from " + CONFIG_FILE + " Cause -"
                + e.getCause();
        log.warning(message);
    }

    if (args.length == 4) {

        PropertiesConfiguration propertiesConfiguration;
        String url = null;

        URI uri = URI.create(args[3]);

        String dataDir = uri.getPath();

        String currentHost = uri.getHost();
        try {

            propertiesConfiguration = new PropertiesConfiguration(dataDir + "/gofs.config");
            propertiesConfiguration.load();
            url = (String) propertiesConfiguration.getString(DataNode.DATANODE_NAMENODE_LOCATION_KEY);

        } catch (ConfigurationException e) {

            String message = " Error while reading gofs-config cause -" + e.getCause();
            handleException(message);
        }

        URI nameNodeUri = URI.create(url);

        INameNode nameNode = new RemoteNameNode(nameNodeUri);
        int partition = -1;
        try {
            for (URI u : nameNode.getDataNodes()) {
                if (URIHelper.isLocalURI(u)) {
                    IDataNode dataNode = DataNode.create(u);
                    IntCollection partitions = dataNode.getLocalPartitions(args[2]);
                    partition = partitions.iterator().nextInt();
                    break;
                }
            }

            if (partition == -1) {
                String message = "Partition not loaded from uri : " + nameNodeUri;
                handleException(message);
            }

            properties.setProperty(GopherInfraHandler.PARTITION, String.valueOf(partition));

        } catch (Exception e) {
            String message = "Error while loading Partitions from " + nameNodeUri + " Cause -" + e.getMessage();
            e.printStackTrace();
            handleException(message);
        }

        properties.setProperty(Constants.STATIC_PELLET_COUNT, String.valueOf(1));
        FloeRuntimeEnvironment environment = FloeRuntimeEnvironment.getEnvironment();
        environment.setSystemConfig(properties);
        properties.setProperty(Constants.CURRET_HOST, currentHost);
        String managerHost = args[0];
        int managerPort = Integer.parseInt(args[1]);

        Container container = environment.getContainer();
        container.setManager(managerHost, managerPort);

        DefaultClientConfig config = new DefaultClientConfig();
        config.getProperties().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);
        config.getFeatures().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);

        Client c = Client.create(config);

        if (managerHost == null || managerPort == 0) {
            handleException("Manager Host / Port have to be configured in " + args[0]);
        }

        WebResource r = c.resource("http://" + managerHost + ":" + managerPort
                + "/Manager/addContainerInfo/Container=" + container.getContainerInfo().getContainerId()
                + "/Host=" + container.getContainerInfo().getContainerHost());
        c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
        r.post();
        log.log(Level.INFO, "Container started  ");

    } else {

        String message = "Invalid arguments , arg[0]=Manager host, "
                + "arg[1] = mamanger port,arg[2]=graph id,arg[3]=partition uri";

        message += "\n Current Arguments...." + args.length + "\n";
        for (int i = 0; i < args.length; i++) {
            message += "arg " + i + " : " + args[i] + "\n";
        }

        handleException(message);

    }

}

From source file:com.dataartisans.Consumer.java

public static void main(String[] args) throws Exception {
    // set up the execution environment
    final StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment();
    final ParameterTool pt = ParameterTool.fromArgs(args);

    Properties props = new Properties();
    props.setProperty(KinesisConfigConstants.CONFIG_AWS_CREDENTIALS_PROVIDER_BASIC_ACCESSKEYID,
            pt.get("accesskey"));
    props.setProperty(KinesisConfigConstants.CONFIG_AWS_CREDENTIALS_PROVIDER_BASIC_SECRETKEY,
            pt.get("secretkey"));
    props.setProperty(KinesisConfigConstants.CONFIG_AWS_REGION, "eu-central-1");
    props.setProperty(KinesisConfigConstants.CONFIG_STREAM_INIT_POSITION_TYPE, pt.get("start", "TRIM_HORIZON"));

    FlinkKinesisConsumer<String> consumer = new FlinkKinesisConsumer<>(pt.getRequired("stream"),
            new SimpleStringSchema(), props);
    DataStream<String> jsonStream = see.addSource(consumer);

    jsonStream.flatMap(new ThroughputLogger(5_000L)).setParallelism(1);
    jsonStream.flatMap(new LatencyStat());
    //jsonStream.print();

    // execute program
    see.execute("Kinesis data consumer");
}

From source file:registry.java

public static void main(String[] args) {
    Properties props = new Properties();

    // set smtp and imap to be our default 
    // transport and store protocols, respectively
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.store.protocol", "imap");

    // //from  w  ww  .j a  v a  2 s . c  om
    props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
    props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");

    Session session = Session.getInstance(props, null);
    //session.setDebug(true);

    // Retrieve all configured providers from the Session
    System.out.println("\n------ getProviders()----------");
    Provider[] providers = session.getProviders();
    for (int i = 0; i < providers.length; i++) {
        System.out.println("** " + providers[i]);

        // let's remember some providers so that we can use them later
        // (I'm explicitly showing multiple ways of testing Providers)
        // BTW, no Provider "ACME Corp" will be found in the default
        // setup b/c its not in any javamail.providers resource files
        String s = null;
        if (((s = providers[i].getVendor()) != null) && s.startsWith("ACME Corp")) {
            _aProvider = providers[i];
        }

        // this Provider won't be found by default either
        if (providers[i].getClassName().endsWith("application.smtp"))
            _bProvider = providers[i];

        // this Provider will be found since com.sun.mail.imap.IMAPStore
        // is configured in javamail.default.providers
        if (providers[i].getClassName().equals("com.sun.mail.imap.IMAPStore")) {
            _sunIMAP = providers[i];
        }

        // this Provider will be found as well since there is an
        // Oracle SMTP transport configured by 
        // default in javamail.default.providers
        if (((s = providers[i].getVendor()) != null) && s.startsWith("Oracle")
                && providers[i].getType() == Provider.Type.TRANSPORT
                && providers[i].getProtocol().equalsIgnoreCase("smtp")) {
            _sunSMTP = providers[i];
        }
    }

    System.out.println("\n------ initial protocol defaults -------");
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
        // the NNTP provider will fail since we don't have one configured
        System.out.println("nntp: " + session.getProvider("nntp"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> This exception is OK since there is no NNTP Provider configured by default");
        mex.printStackTrace();
    }

    System.out.println("\n------ set new protocol defaults ------");
    // set some new defaults
    try {
        // since _aProvider isn't configured, this will fail
        session.setProvider(_aProvider); // will fail
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: _aProvider is null");
        mex.printStackTrace();
    }
    try {
        // _sunIMAP provider should've configured correctly; should work
        session.setProvider(_sunIMAP);
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    System.out.println("\n\n----- get some stores ---------");
    // multiple ways to retrieve stores. these will print out the
    // string "imap:" since its the URLName for the store
    try {
        System.out.println("getStore(): " + session.getStore());
        System.out.println("getStore(Provider): " + session.getStore(_sunIMAP));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    try {
        System.out.println("getStore(imap): " + session.getStore("imap"));
        // pop3 will fail since it doesn't exist
        System.out.println("getStore(pop3): " + session.getStore("pop3"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: no pop3 provider");
        mex.printStackTrace();
    }

    System.out.println("\n\n----- now for transports/addresses ---------");
    // retrieve transports; these will print out "smtp:" (like stores did)
    try {
        System.out.println("getTransport(): " + session.getTransport());
        System.out.println("getTransport(Provider): " + session.getTransport(_sunSMTP));
        System.out.println("getTransport(smtp): " + session.getTransport("smtp"));
        System.out.println(
                "getTransport(Address): " + session.getTransport(new InternetAddress("mspivak@apilon")));
        // News will fail since there's no news provider configured
        System.out.println("getTransport(News): " + session.getTransport(new NewsAddress("rec.humor")));
    } catch (MessagingException mex) {
        System.out.println(">> Exception expected: no news provider configured");
        mex.printStackTrace();
    }
}

From source file:com.marklogic.client.example.util.Bootstrapper.java

/**
 * Command-line invocation./*from  www.  j ava2s.  co  m*/
 * @param args   command-line arguments specifying the configuration and REST server
 */
public static void main(String[] args) throws ClientProtocolException, IOException, FactoryConfigurationError {
    Properties properties = new Properties();
    for (int i = 0; i < args.length; i++) {
        String name = args[i];
        if (name.startsWith("-") && name.length() > 1 && ++i < args.length) {
            name = name.substring(1);
            if ("properties".equals(name)) {
                InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name);
                if (propsStream == null)
                    throw new IOException("Could not read bootstrapper properties");
                Properties props = new Properties();
                props.load(propsStream);
                props.putAll(properties);
                properties = props;
            } else {
                properties.put(name, args[i]);
            }
        } else {
            System.err.println("invalid argument: " + name);
            System.err.println(getUsage());
            System.exit(1);
        }
    }

    String invalid = joinList(listInvalidKeys(properties));
    if (invalid != null && invalid.length() > 0) {
        System.err.println("invalid arguments: " + invalid);
        System.err.println(getUsage());
        System.exit(1);
    }

    // TODO: catch invalid argument exceptions and provide feedback
    new Bootstrapper().makeServer(properties);

    System.out.println("Created " + properties.getProperty("restserver") + " server on "
            + properties.getProperty("restport") + " port for " + properties.getProperty("restdb")
            + " database");
}

From source file:com.datis.kafka.stream.PageViewUntypedDemo.java

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-pageview-untyped");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(StreamsConfig.TIMESTAMP_EXTRACTOR_CLASS_CONFIG, JsonTimestampExtractor.class);

    // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    KStreamBuilder builder = new KStreamBuilder();

    final Serializer<JsonNode> jsonSerializer = new JsonSerializer();
    final Deserializer<JsonNode> jsonDeserializer = new JsonDeserializer();
    final Serde<JsonNode> jsonSerde = Serdes.serdeFrom(jsonSerializer, jsonDeserializer);

    KStream<String, JsonNode> views = builder.stream(Serdes.String(), jsonSerde, "streams-pageview-input");

    KTable<String, JsonNode> users = builder.table(Serdes.String(), jsonSerde, "streams-userprofile-input");

    KTable<String, String> userRegions = users.mapValues(new ValueMapper<JsonNode, String>() {
        @Override/*from  w w  w . j  a  v  a  2s . c o  m*/
        public String apply(JsonNode record) {
            return record.get("region").textValue();
        }
    });

    KStream<JsonNode, JsonNode> regionCount = views
            .leftJoin(userRegions, new ValueJoiner<JsonNode, String, JsonNode>() {
                @Override
                public JsonNode apply(JsonNode view, String region) {
                    ObjectNode jNode = JsonNodeFactory.instance.objectNode();

                    return jNode.put("user", view.get("user").textValue())
                            .put("page", view.get("page").textValue())
                            .put("region", region == null ? "UNKNOWN" : region);
                }
            }).map(new KeyValueMapper<String, JsonNode, KeyValue<String, JsonNode>>() {
                @Override
                public KeyValue<String, JsonNode> apply(String user, JsonNode viewRegion) {
                    return new KeyValue<>(viewRegion.get("region").textValue(), viewRegion);
                }
            })
            .countByKey(TimeWindows.of("GeoPageViewsWindow", 7 * 24 * 60 * 60 * 1000L).advanceBy(1000),
                    Serdes.String())
            // TODO: we can merge ths toStream().map(...) with a single toStream(...)
            .toStream().map(new KeyValueMapper<Windowed<String>, Long, KeyValue<JsonNode, JsonNode>>() {
                @Override
                public KeyValue<JsonNode, JsonNode> apply(Windowed<String> key, Long value) {
                    ObjectNode keyNode = JsonNodeFactory.instance.objectNode();
                    keyNode.put("window-start", key.window().start()).put("region", key.key());

                    ObjectNode valueNode = JsonNodeFactory.instance.objectNode();
                    valueNode.put("count", value);

                    return new KeyValue<>((JsonNode) keyNode, (JsonNode) valueNode);
                }
            });

    // write to the result topic
    regionCount.to(jsonSerde, jsonSerde, "streams-pageviewstats-untyped-output");

    KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();

    // usually the stream application would be running forever,
    // in this example we just let it run for some time and stop since the input data is finite.
    Thread.sleep(5000L);

    streams.close();
}

From source file:com.netflix.suro.SuroServer.java

public static void main(String[] args) throws IOException {
    final AtomicReference<Injector> injector = new AtomicReference<Injector>();

    try {/*from w w  w. j  av  a  2  s  . co m*/
        // Parse the command line
        Options options = createOptions();
        final CommandLine line = new BasicParser().parse(options, args);

        // Load the properties file
        final Properties properties = new Properties();
        if (line.hasOption('p')) {
            properties.load(new FileInputStream(line.getOptionValue('p')));
        }

        // Bind all command line options to the properties with prefix "SuroServer."
        for (Option opt : line.getOptions()) {
            String name = opt.getOpt();
            String value = line.getOptionValue(name);
            String propName = PROP_PREFIX + opt.getArgName();
            if (propName.equals(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY)) {
                properties.setProperty(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertySinkConfigurator.SINK_PROPERTY)) {
                properties.setProperty(DynamicPropertySinkConfigurator.SINK_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY)) {
                properties.setProperty(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else {
                properties.setProperty(propName, value);
            }
        }

        create(injector, properties);
        injector.get().getInstance(LifecycleManager.class).start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
                } catch (IOException e) {
                    // do nothing because Closeables.close will swallow IOException
                }
            }
        });

        waitForShutdown(getControlPort(properties));
    } catch (Throwable e) {
        System.err.println("SuroServer startup failed: " + e.getMessage());
        System.exit(-1);
    } finally {
        Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
    }
}