Example usage for java.util Properties load

List of usage examples for java.util Properties load

Introduction

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

Prototype

public synchronized void load(InputStream inStream) throws IOException 

Source Link

Document

Reads a property list (key and element pairs) from the input byte stream.

Usage

From source file:PropView.java

public static void main(String args[]) throws Exception {
    Properties properties = System.getProperties();
    properties.list(System.out);/*from  ww w .j av  a  2 s  .  c o  m*/

    FileInputStream in = null;

    in = new FileInputStream(args[0]);
    properties.load(in);

    System.getProperties().list(System.out);
    System.out.println("\nValue of local.animal.defined is " + Boolean.getBoolean("local.animal.defined"));
    System.out.println("\nValue of local.animal.legcount is " + Integer.getInteger("local.animal.legcount"));
}

From source file:com.ibm.watson.developer_cloud.conversation_tone_analyzer_integration.v1.ToneConversationIntegrationV1.java

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

    // load the properties file
    Properties props = new Properties();
    props.load(FileUtils.openInputStream(new File("tone_conversation_integration.properties")));

    // instantiate the conversation service
    ConversationService conversationService = new ConversationService(
            ConversationService.VERSION_DATE_2016_07_11);
    conversationService.setUsernameAndPassword(
            props.getProperty("CONVERSATION_USERNAME", "<conversation_username>"),
            props.getProperty("CONVERSATION_PASSWORD", "<conversation_password>"));

    // instantiate the tone analyzer service
    ToneAnalyzer toneService = new ToneAnalyzer(ToneAnalyzer.VERSION_DATE_2016_05_19);
    toneService.setUsernameAndPassword(props.getProperty("TONE_ANALYZER_USERNAME", "<tone_analyzer_username>"),
            props.getProperty("TONE_ANALYZER_PASSWORD", "<tone_analyzer_password>"));

    // workspace id
    final String workspaceId = props.getProperty("WORKSPACE_ID", "<workspace_id>");

    // maintain history in the context variable - will add a history variable to
    // each of the emotion, social and language tones
    final Boolean maintainHistory = false;

    /**//from   www  . j av a2 s  .  c o m
     * Input for the conversation service: input (String): an input string (the user's conversation turn) and context
     * (Map<String,Object>: any context that needs to be maintained - either added by the client app or passed in the
     * response from the conversation service on the previous conversation turn.
     */
    final String input = "I am happy";
    final Map<String, Object> context = new HashMap<String, Object>();

    // UPDATE CONTEXT HERE IF CONTINUING AN ONGOING CONVERSATION
    // set local context variable to the context from the last response from the
    // Conversation Service
    // (see the getContext() method of the MessageResponse class in
    // com.ibm.watson.developer_cloud.conversation.v1.model)

    // async call to Tone Analyzer
    toneService.getTone(input, null).enqueue(new ServiceCallback<ToneAnalysis>() {
        @Override
        public void onResponse(ToneAnalysis toneResponsePayload) {

            // update context with the tone data returned by the Tone Analyzer
            ToneDetection.updateUserTone(context, toneResponsePayload, maintainHistory);

            // call Conversation Service with the input and tone-aware context
            MessageRequest newMessage = new MessageRequest.Builder().inputText(input).context(context).build();
            conversationService.message(workspaceId, newMessage)
                    .enqueue(new ServiceCallback<MessageResponse>() {
                        @Override
                        public void onResponse(MessageResponse response) {
                            System.out.println(response);
                        }

                        @Override
                        public void onFailure(Exception e) {
                        }
                    });
        }

        @Override
        public void onFailure(Exception e) {
        }
    });
}

From source file:TypeMapDemo.java

public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {

    Properties p = new Properties();
    p.load(new FileInputStream("db.properties"));
    Class c = Class.forName(p.getProperty("db.driver"));
    System.out.println("Loaded driverClass " + c.getName());

    Connection con = DriverManager.getConnection(p.getProperty("db.url"), "student", "student");
    System.out.println("Got Connection " + con);

    Statement s = con.createStatement();
    int ret;//w w  w  . ja  va  2  s . c o m
    try {
        s.executeUpdate("drop table MR");
        s.executeUpdate("drop type MUSICRECORDING");
    } catch (SQLException andDoNothingWithIt) {
        // Should use "if defined" but not sure it works for UDTs...
    }
    ret = s.executeUpdate("create type MUSICRECORDING as object (" + "   id integer," + "   title varchar(20), "
            + "   artist varchar(20) " + ")");
    System.out.println("Created TYPE! Ret=" + ret);

    ret = s.executeUpdate("create table MR of MUSICRECORDING");
    System.out.println("Created TABLE! Ret=" + ret);

    int nRows = s.executeUpdate("insert into MR values(123, 'Greatest Hits', 'Ian')");
    System.out.println("inserted " + nRows + " rows");

    // Put the data class into the connection's Type Map
    // If the data class were not an inner class,
    // this would likely be done with Class.forName(...);
    Map map = con.getTypeMap();
    map.put("MUSICRECORDING", MusicRecording.class);
    con.setTypeMap(map);

    ResultSet rs = s.executeQuery("select * from MR where id = 123");
    //"select musicrecording(id,artist,title) from mr");
    rs.next();
    for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
        Object o = rs.getObject(i);
        System.out.print(o + "(Type " + o.getClass().getName() + ")\t");
    }
    System.out.println();
}

From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    HelpFormatter formatter = new HelpFormatter();
    options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert")
            .longOpt("source").hasArg(true).build());
    options.addOption(Option.builder("t").argName("target").desc("the target file to store in")
            .longOpt("target").hasArg(true).build());
    options.addOption(Option.builder("h").desc("print help").build());

    try {/*from   w  w  w .  j av a  2  s . c om*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            formatter.printHelp("converter", options);
        }
        File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir")));
        String name = source.getName();
        if (source.isDirectory()) {
            PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter();
            String[] ext = { "properties" };
            Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true);
            while (fileIterator.hasNext()) {
                File next = fileIterator.next();
                System.out.println(next);
                String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath());
                System.out.println(s);
                String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0];
                System.out.println("key = " + f);
                Properties p = new Properties();
                try {
                    p.load(new FileReader(next));
                    yamlConverter.addProperties(f, p);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            yamlConverter.writeYaml(fileWriter);
            fileWriter.close();
        } else {
            Properties p = new Properties();
            p.load(new FileReader(source));
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter);
            fileWriter.close();
        }
    } catch (ParseException e) {
        e.printStackTrace();
        formatter.printHelp("converter", options);
    }
}

From source file:com.wso2.rfid.Main.java

public static void main(String[] args) throws IOException {
    Properties configs = new Properties();
    configs.load(
            new FileInputStream(System.getProperty("rpi.agent.home") + File.separator + "config.properties"));

    Server server = new Server(InetSocketAddress.createUnresolved("127.0.0.1", 8084));
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);/* w  ww . java  2  s  .c  o  m*/
    handler.addServletWithMapping(RFIDReaderServlet.class, "/rfid");
    String controlCenterURL = configs.getProperty("control.center.url");
    System.out.println("Using RPi Control Center: " + controlCenterURL);
    String tokenEndpoint = configs.getProperty("token.endpoint");
    System.out.println("Using token endpoint: " + tokenEndpoint);
    APICall.setTokenEndpoint(tokenEndpoint);
    String primaryNwInterface = configs.getProperty("primary.nw.interface");
    String userRegEndpoint = configs.getProperty("user.registration.endpoint");
    System.out.println("Using user registration endpoint: " + userRegEndpoint);
    APICall.setUserRegistrationEndpoint(userRegEndpoint);
    scheduler.scheduleWithFixedDelay(new MonitoringTask(controlCenterURL, primaryNwInterface), 0, 10,
            TimeUnit.SECONDS);

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.atomserver.utils.jetty.StandAloneAtomServer.java

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

    // the System Property "atomserver.home" defines the home directory for the standalone app
    String atomserverHome = System.getProperty("atomserver.home");
    if (StringUtils.isEmpty(atomserverHome)) {
        log.error("The variable \"atomserver.home\" must be defined");
        System.exit(-1);/*from   w ww. ja  v a 2 s.  c  om*/
    }
    File atomserverHomeDir = new File(atomserverHome);
    if (!atomserverHomeDir.exists() && !atomserverHomeDir.isDirectory()) {
        log.error("The variable \"atomserver.home\" (" + atomserverHome
                + ") must point to a directory that exists");
    }

    // instantiate the Jetty Server
    Server server = new Server();

    // create a new connector on the declared port, and set it onto the server
    log.debug("atomserver.port = " + System.getProperty("atomserver.port"));
    Connector connector = new SelectChannelConnector();
    connector.setPort(Integer.getInteger("atomserver.port", DEFAULT_PORT));
    server.setConnectors(new Connector[] { connector });

    // create a ClassLoader that points at the conf directories
    log.debug("atomserver.conf.dir = " + System.getProperty("atomserver.conf.dir"));
    log.debug("atomserver.ops.conf.dir = " + System.getProperty("atomserver.ops.conf.dir"));
    ClassLoader classLoader = new ConfigurationAwareClassLoader(StandAloneAtomServer.class.getClassLoader());

    // load the version from the version.properties file
    Properties versionProps = new Properties();
    versionProps.load(classLoader.getResourceAsStream(DEFAULT_VERSIONS_FILE));
    String version = versionProps.getProperty("atomserver.version");

    // create a new webapp, rooted at webapps/atomserver-${version}, with the configured
    // context name
    String servletContextName = System.getProperty("atomserver.servlet.context");
    log.debug("atomserver.servlet.context = " + servletContextName);
    WebAppContext webapp = new WebAppContext(atomserverHome + "/webapps/atomserver-" + version,
            "/" + servletContextName);

    // set the webapp's ClassLoader to be the one that loaded THIS class.  the REASON that
    // this needs to be set is so that when we extract the web application context below we can
    // cast it to WebApplicationContext here
    webapp.setClassLoader(StandAloneAtomServer.class.getClassLoader());

    // set the Jetty server's webapp and start it
    server.setHandler(webapp);
    server.start();

    // if the seed system property was set, use the DBSeeder to populate the server
    String seedDB = System.getProperty("seed.database.with.pets");
    log.debug("seed.database.with.pets = " + seedDB);
    if (!StringUtils.isEmpty(seedDB)) {
        if (Boolean.valueOf(seedDB)) {
            Thread.sleep(2000);

            WebApplicationContext webappContext = WebApplicationContextUtils
                    .getWebApplicationContext(webapp.getServletContext());

            DBSeeder.getInstance(webappContext).seedPets();
        }
    }

    server.join();
}

From source file:com.machinelinking.cli.loader.java

public static void main(String[] args) {
    if (args.length != 2) {
        System.err.println("Usage: $0 <config-file> <dump>");
        System.exit(1);//from  www.j a v  a 2s.  c  o m
    }

    try {
        final File configFile = check(args[0]);
        final File dumpFile = check(args[1]);
        final Properties properties = new Properties();
        properties.load(FileUtils.openInputStream(configFile));

        final Flag[] flags = WikiPipelineFactory.getInstance().toFlags(getPropertyOrFail(properties,
                LOADER_FLAGS_PROP,
                "valid flags: " + Arrays.toString(WikiPipelineFactory.getInstance().getDefinedFlags())));
        final JSONStorageFactory jsonStorageFactory = MultiJSONStorageFactory
                .loadJSONStorageFactory(getPropertyOrFail(properties, LOADER_STORAGE_FACTORY_PROP, null));
        final String jsonStorageConfig = getPropertyOrFail(properties, LOADER_STORAGE_CONFIG_PROP, null);
        final URL prefixURL = readURL(getPropertyOrFail(properties, LOADER_PREFIX_URL_PROP,
                "expected a valid URL prefix like: http://en.wikipedia.org/"), LOADER_PREFIX_URL_PROP);

        final DefaultJSONStorageLoader[] loader = new DefaultJSONStorageLoader[1];
        final boolean[] finalReportProduced = new boolean[] { false };
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                if (!finalReportProduced[0] && loader[0] != null) {
                    System.err.println(
                            "Process interrupted. Partial loading report: " + loader[0].createReport());
                }
                System.err.println("Shutting down.");
            }
        }));

        final JSONStorageConfiguration storageConfig = jsonStorageFactory
                .createConfiguration(jsonStorageConfig);
        try (final JSONStorage storage = jsonStorageFactory.createStorage(storageConfig)) {
            loader[0] = new DefaultJSONStorageLoader(WikiPipelineFactory.getInstance(), flags, storage);

            final StorageLoaderReport report = loader[0].load(prefixURL,
                    FileUtil.openDecompressedInputStream(dumpFile));
            System.err.println("Loading report: " + report);
            finalReportProduced[0] = true;
        }
        System.exit(0);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:ImageStringToBlob.java

public static void main(String[] args) {
    Connection conn = null;/*w w w .j  a v a2 s  . c o  m*/

    if (args.length != 1) {
        System.out.println("Missing argument: full path to <oscar.properties>");
        return;
    }

    try {

        FileInputStream fin = new FileInputStream(args[0]);
        Properties prop = new Properties();
        prop.load(fin);

        String driver = prop.getProperty("db_driver");
        String uri = prop.getProperty("db_uri");
        String db = prop.getProperty("db_name");
        String username = prop.getProperty("db_username");
        String password = prop.getProperty("db_password");

        Class.forName(driver);
        conn = DriverManager.getConnection(uri + db, username, password);
        conn.setAutoCommit(true); // no transactions

        /*
         * select all records ids with image_data not null and contents is null
         * for each id fetch record
         * migrate data from image_data to contents
         */
        String sql = "select image_id from client_image where image_data is not null and contents is null";
        PreparedStatement pst = conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();
        List<Long> ids = new ArrayList<Long>();

        while (rs.next()) {
            ids.add(rs.getLong("image_id"));
        }

        rs.close();

        sql = "select image_data from client_image where image_id = ?";
        pst = conn.prepareStatement(sql);

        System.out.println("Migrating image data for " + ids.size() + " images...");
        for (Long id : ids) {
            pst.setLong(1, id);
            ResultSet imagesRS = pst.executeQuery();
            while (imagesRS.next()) {
                String dataString = imagesRS.getString("image_data");
                Blob dataBlob = fromStringToBlob(dataString);
                if (writeBlobToDb(conn, id, dataBlob) == 1) {
                    System.out.println("Image data migrated for image_id: " + id);
                }
            }
            imagesRS.close();
        }
        System.out.println("Migration completed.");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.joliciel.talismane.TalismaneMain.java

public static void main(String[] args) throws Exception {
    Map<String, String> argsMap = StringUtils.convertArgs(args);
    OtherCommand otherCommand = null;/*  w  w  w.  j  av a 2 s .  c o  m*/
    if (argsMap.containsKey("command")) {
        try {
            otherCommand = OtherCommand.valueOf(argsMap.get("command"));
            argsMap.remove("command");
        } catch (IllegalArgumentException e) {
            // not anotherCommand
        }
    }

    String sessionId = "";
    TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId);
    TalismaneService talismaneService = locator.getTalismaneService();
    TalismaneSession talismaneSession = talismaneService.getTalismaneSession();

    if (otherCommand == null) {
        // regular command
        TalismaneConfig config = talismaneService.getTalismaneConfig(argsMap, sessionId);
        if (config.getCommand() == null)
            return;

        Talismane talismane = config.getTalismane();

        talismane.process();
    } else {
        // other command
        String logConfigPath = argsMap.get("logConfigFile");
        if (logConfigPath != null) {
            argsMap.remove("logConfigFile");
            Properties props = new Properties();
            props.load(new FileInputStream(logConfigPath));
            PropertyConfigurator.configure(props);
        }

        switch (otherCommand) {
        case serializeLexicon: {
            LexiconSerializer serializer = new LexiconSerializer();
            serializer.serializeLexicons(argsMap);
            break;
        }
        case testLexicon: {
            String lexiconFilePath = null;
            String[] wordList = null;
            for (String argName : argsMap.keySet()) {
                String argValue = argsMap.get(argName);
                if (argName.equals("lexicon")) {
                    lexiconFilePath = argValue;
                } else if (argName.equals("words")) {
                    wordList = argValue.split(",");
                } else {
                    throw new TalismaneException("Unknown argument: " + argName);
                }
            }
            File lexiconFile = new File(lexiconFilePath);
            LexiconDeserializer lexiconDeserializer = new LexiconDeserializer(talismaneSession);
            List<PosTaggerLexicon> lexicons = lexiconDeserializer.deserializeLexicons(lexiconFile);
            for (PosTaggerLexicon lexicon : lexicons)
                talismaneSession.addLexicon(lexicon);
            PosTaggerLexicon mergedLexicon = talismaneSession.getMergedLexicon();
            for (String word : wordList) {
                LOG.info("################");
                LOG.info("Word: " + word);
                List<LexicalEntry> entries = mergedLexicon.getEntries(word);
                for (LexicalEntry entry : entries) {
                    LOG.info(entry + ", Full morph: " + entry.getMorphologyForCoNLL());
                }
            }
            break;
        }
        }
    }
}

From source file:PersistentEcho.java

public static void main(String[] args) {
    String argString = "";
    boolean notProperty = true;

    // Are there arguments? 
    // If so retrieve them.
    if (args.length > 0) {
        for (String arg : args) {
            argString += arg + " ";
        }//from  w  ww  . ja v a  2  s  .  co  m
        argString = argString.trim();
    }
    // No arguments, is there
    // an environment variable?
    // If so, //retrieve it.
    else if ((argString = System.getenv("PERSISTENTECHO")) != null) {
    }
    // No environment variable
    // either. Retrieve property value.
    else {
        notProperty = false;
        // Set argString to null.
        // If it's still null after
        // we exit the try block,
        // we've failed to retrieve
        // the property value.
        argString = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("PersistentEcho.txt");
            Properties inProperties = new Properties();
            inProperties.load(fileInputStream);
            argString = inProperties.getProperty("argString");
        } catch (IOException e) {
            System.err.println("Can't read property file.");
            System.exit(1);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
                ;
            }
        }
    }
    if (argString == null) {
        System.err.println("Couldn't find argString property");
        System.exit(1);
    }

    // Somehow, we got the
    // value. Echo it already!
    System.out.println(argString);

    // If we didn't retrieve the
    // value from the property,
    // save it //in the property.
    if (notProperty) {
        Properties outProperties = new Properties();
        outProperties.setProperty("argString", argString);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("PersistentEcho.txt");
            outProperties.store(fileOutputStream, "PersistentEcho properties");
        } catch (IOException e) {
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                }
                ;
            }
        }
    }
}