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:kr.ac.kaist.wala.hybridroid.shell.Shell.java

/**
 * HybriDroid main function. Now, There is CFG-building option only in
 * HybriDroid./*from  w  ww. ja  va  2  s.c o m*/
 * 
 * @param args
 * @throws IOException
 * @throws IllegalArgumentException
 * @throws CancelException
 * @throws ParseException
 * @throws WalaException 
 */
public static void main(String[] args)
        throws IOException, IllegalArgumentException, CancelException, ParseException, WalaException {
    Shell.args = new CommandArguments(args);
    // Load wala property. Now, 'PROP_ARG' is essential option, so else
    // branch cannot be reached.
    if (Shell.args.has(CommandArguments.PROP_ARG)) {
        String propertyfile = Shell.args.get(CommandArguments.PROP_ARG);
        File propFile = new File(propertyfile);
        walaProperties = new Properties();
        walaProperties.load(new FileInputStream(propFile));
    } else {
        try {
            walaProperties = WalaProperties.loadProperties();
        } catch (WalaException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // Load target file for analysis.
    String targetPath = Shell.args.get(CommandArguments.TARGET_ARG);
    long startTime = System.currentTimeMillis();
    START = startTime;
    /**
     * Below is the switch case for HybriDroid functions. One function of
     * the CommandLineOptionGroup must be one case in below.
     */
    // Build Control-flow Graph.
    if (Shell.args.has(CommandArguments.CFG_ARG)) {
        if (Shell.args.has(CommandArguments.ONLY_JS_ARG)) {
            //            File analysisfile = new File(targetPath);
            //                   URL url = analysisfile.toURI().toURL();
            //                   // Setting WALA analyzer
            //                   CAstRhinoTranslatorFactory translatorFactory = new CAstRhinoTranslatorFactory();
            //                   JSCallGraphUtil.setTranslatorFactory(translatorFactory);
            //                   // make actual file name and directory
            //                   JSCFABuilder b = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url);
            //                   CallGraph callGraph = b.makeCallGraph(b.getOptions());
            //                   PointerAnalysis<InstanceKey> pa = b.getPointerAnalysis();
            //                   WalaCGVisualizer vis = new WalaCGVisualizer();
            //                   vis.visualize(callGraph, "cfg.dot");
            //                   vis.printLabel("jslabel.txt");
        } else {

            //            Shell.START = System.currentTimeMillis();
            HybridCFGAnalysis cfgAnalysis = new HybridCFGAnalysis();
            Pair<CallGraph, PointerAnalysis<InstanceKey>> p = cfgAnalysis.main(targetPath,
                    LocalFileReader.androidJar(Shell.walaProperties).getPath());
            CallGraph cg = p.fst;
            PointerAnalysis<InstanceKey> pa = p.snd;

            //            PointerAnalysis<InstanceKey> pa = p.snd;
            //            Shell.END = System.currentTimeMillis();
            //            System.err.println("#time: " + (((double)(Shell.END - Shell.START))/1000d) + "s");

            //            System.err.println("Graph Modeling for taint...");
            //            ModeledCallGraphForTaint mcg = new ModeledCallGraphForTaint(p.fst);
            //            System.err.println("Taint analysis...");
            //            PrivateLeakageDetector pld = new PrivateLeakageDetector(p.fst, p.snd);
            //            pld.analyze();
            //            Shell.END = System.currentTimeMillis();
            //            System.err.println("#time: " + (((double)(Shell.END - Shell.START))/1000d) + "s");
            //             for(PrivateLeakageDetector.LeakWarning w : pld.getWarnings()){
            //                System.out.println("=========");
            //                System.out.println(w);
            //                System.out.println("=========");
            // //               w.printPathFlow("leak.dot");
            //             }
        }
    } else {
        // TODO: support several functions
    }
    long endTime = System.currentTimeMillis();
    System.out.println("#Time: " + (endTime - startTime));
}

From source file:dashboard.ImportCDN.java

public static void main(String[] args)

{
    int n = 0;//from w w  w.  ja v  a2s.  c o m
    String propertiesFileName = "";

    // First argument - number of events to import
    if (args.length > 0) {
        try {
            n = Integer.parseInt(args[0]);
        } catch (NumberFormatException e) {
            System.err.println("First argument must be an integer");
            System.exit(1);
        }
    } else {
        System.err.println("Please specify number of events to import.");
        System.exit(1);
    }

    // Second argument - properties file name
    if (args.length > 1)
        propertiesFileName = args[1];
    else
        propertiesFileName = "gigaDashboard.properties";

    // Read Properties file
    Properties prop = new Properties();

    try {
        //load a properties file
        prop.load(new FileInputStream(propertiesFileName));

        // Another option - load default properties from the Jar
        //prop.load(ImportCDN.class.getResourceAsStream("/gigaDashboard.properties"));

        //get the property values
        TOKEN = prop.getProperty("MIXPANEL_GIGA_PROJECT_TOKEN");
        API_KEY = prop.getProperty("MIXPANEL_GIGA_API_KEY");
        bucketName = prop.getProperty("S3_BUCKET_NAME");
        AWS_USER = prop.getProperty("AWS_USER");
        AWS_PASS = prop.getProperty("AWS_PASS");
        DELETE_PROCESSED_LOGS = prop.getProperty("DELETE_PROCESSED_LOGS");

        //System.out.println("MIXPANEL PROJECT TOKEN = " + TOKEN);
        //System.out.println("MIXPANEL API KEY = " + API_KEY);
        System.out.println("DELETE_PROCESSED_LOGS = " + DELETE_PROCESSED_LOGS);
        System.out.println("S3_BUCKET_NAME = " + prop.getProperty("S3_BUCKET_NAME"));
        //System.out.println("AWS_USER = " + prop.getProperty("AWS_USER"));
        //System.out.println("AWS_PASS = " + prop.getProperty("AWS_PASS"));

        System.out.println("===================");
    } catch (IOException ex) {
        //ex.printStackTrace();
        System.err.println("Can't find Propertie file - " + propertiesFileName);
        System.err.println("Second argument must be properties file name");
        System.exit(1);
    }

    try {
        System.out.println("\n>>> Starting to import " + n + " events... \n");
        readAmazonLogs(n);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.image32.demo.simpleapi.SimpleApiDemo.java

final public static void main(String[] args) {
    me = new SimpleApiDemo();
    me.contentHandlers = new ContentHandler();

    //load configurations
    try {//from  w w w  .java 2s .co m
        Properties prop = new Properties();
        InputStream input = SimpleApiDemo.class.getResourceAsStream("/demoConfig.properties");

        // load a properties file
        prop.load(input);
        image32ApiClientId = prop.getProperty("image32ApiClientId");
        image32ApiSecrect = prop.getProperty("image32ApiSecrect");
        image32ApiAuthUrl = prop.getProperty("image32ApiAuthUrl");
        image32ApiGetStudiesUrl = prop.getProperty("image32ApiGetStudiesUrl");
        demoDataFile = prop.getProperty("demoDataFile");
        input.close();
    } catch (Exception ex) {
        logger.info("No configuration found.");
        System.exit(1);
    }

    // test port availability
    while (!checkPortAvailablity(port)) {
        if (port > 8090) {
            logger.info("Port is not available. Exiting...");
            System.exit(1);
        }
        port++;
    }
    ;

    // run server
    server = new Server(port);
    HashSessionIdManager hashSessionIdManager = new HashSessionIdManager();
    server.setSessionIdManager(hashSessionIdManager);

    WebAppContext homecontext = new WebAppContext();
    homecontext.setContextPath("/home");
    ResourceCollection resources = new ResourceCollection(new String[] { "site" });
    homecontext.setBaseResource(resources);

    HashSessionManager manager = new HashSessionManager();
    manager.setSecureCookies(true);
    SessionHandler sessionHandler = new SessionHandler(manager);

    sessionHandler.setHandler(me.contentHandlers);

    ContextHandler context = new ContextHandler();
    context.setContextPath("/app");
    context.setResourceBase(".");
    context.setClassLoader(Thread.currentThread().getContextClassLoader());
    context.setHandler(sessionHandler);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { homecontext, context });

    server.setHandler(handlers);

    try {
        server.start();
        logger.info("Server started on port " + port);
        logger.info("Please access this demo from browser with this url: http://localhost:" + port);

        if (Desktop.isDesktopSupported())
            Desktop.getDesktop().browse(new URI("http://localhost:" + port + "/home"));

        server.join();
    } catch (Exception exception) {
        logger.error(exception.getMessage());
    }
    System.exit(1);
}

From source file:io.hops.examples.spark.kafka.StreamingLogs.java

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

    SparkConf sparkConf = new SparkConf().setAppName(Hops.getJobName());
    JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, Durations.seconds(2));

    //Use applicationId for sink folder
    final String appId = jssc.sparkContext().getConf().getAppId();
    SparkSession sparkSession = SparkSession.builder().config(sparkConf).getOrCreate();
    //Get consumer groups
    Properties props = new Properties();
    props.put("value.deserializer", StringDeserializer.class.getName());
    props.put("client.id", Hops.getJobName());
    SparkConsumer consumer = Hops.getSparkConsumer(jssc, props);
    //Store processed offsets

    // Create direct kafka stream with topics
    JavaInputDStream<ConsumerRecord<String, String>> messages = consumer.createDirectStream();

    //Convert line to JSON
    JavaDStream<NamenodeLogEntry> logEntries = messages
            .map(new Function<ConsumerRecord<String, String>, JSONObject>() {
                @Override/*from w  ww  . ja v  a  2 s.  c  o  m*/
                public JSONObject call(ConsumerRecord<String, String> record)
                        throws SchemaNotFoundException, MalformedURLException, ProtocolException {
                    LOG.log(Level.INFO, "record:{0}", record);
                    return parser(record.value(), appId);
                }
            }).map(new Function<JSONObject, NamenodeLogEntry>() {
                @Override
                public NamenodeLogEntry call(JSONObject json)
                        throws SchemaNotFoundException, MalformedURLException, ProtocolException, IOException {
                    NamenodeLogEntry logEntry = new NamenodeLogEntry(
                            json.getString("message").replace("\n\t", "\n").replace("\n", "---"),
                            json.getString("priority"), json.getString("logger_name"),
                            json.getString("timestamp"), json.getString("file"));
                    LOG.log(Level.INFO, "NamenodeLogEntry:{0}", logEntry);
                    return logEntry;
                }
            });

    //logEntries.print();
    logEntries.foreachRDD(new VoidFunction2<JavaRDD<NamenodeLogEntry>, Time>() {
        @Override
        public void call(JavaRDD<NamenodeLogEntry> rdd, Time time) throws Exception {
            Dataset<Row> row = sparkSession.createDataFrame(rdd, NamenodeLogEntry.class);
            if (!rdd.isEmpty()) {
                row.write().mode(SaveMode.Append)
                        .parquet("/Projects/" + Hops.getProjectName() + "/Resources/LogAnalysis");
            }
        }
    });
    /*
     * Enable this to get all the streaming outputs. It creates a folder for
     * every microbatch slot.
     * ///////////////////////////////////////////////////////////////////////
     * wordCounts.saveAsHadoopFiles(args[1], "txt", String.class,
     * String.class, (Class) TextOutputFormat.class);
     * ///////////////////////////////////////////////////////////////////////
     */
    // Start the computation
    jssc.start();
    Hops.shutdownGracefully(jssc);
}

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  .  j a  va 2s .c  o 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) {
                }
                ;
            }
        }
    }
}

From source file:dpfmanager.shell.core.util.VersionUtil.java

public static void main(String[] args) {
    String version = args[0];//w ww .j  a v a 2 s  .c  o  m
    String baseDir = args[1];

    String issPath = baseDir + "/package/windows/DPF Manager.iss";
    String rpmPath = baseDir + "/package/linux/DPFManager.old.spec";
    String propOutput = baseDir + "/target/classes/version.properties";

    try {
        // Windows iss
        File issFile = new File(issPath);
        String issContent = FileUtils.readFileToString(issFile);
        String newIssContent = replaceLine(StringUtils.split(issContent, '\n'), "AppVersion=", version);
        if (!newIssContent.isEmpty()) {
            FileUtils.writeStringToFile(issFile, newIssContent);
            System.out.println("New version information updated! (iss)");
        }

        // RPM spec
        File rpmFile = new File(rpmPath);
        String rpmContent = FileUtils.readFileToString(rpmFile);
        String newRpmContent = replaceLine(StringUtils.split(rpmContent, '\n'), "Version: ", version);
        if (!newRpmContent.isEmpty()) {
            FileUtils.writeStringToFile(rpmFile, newRpmContent);
            System.out.println("New version information updated! (spec)");
        }

        // Java properties file
        OutputStream output = new FileOutputStream(propOutput);
        Properties prop = new Properties();
        prop.setProperty("version", version);
        prop.store(output, "Version autoupdated");
        output.close();
        System.out.println("New version information updated! (properties)");

    } catch (Exception e) {
        System.out.println("Exception ocurred, no version changed.");
        e.printStackTrace();
    }

}

From source file:com.joliciel.talismane.terminology.TalismaneTermExtractorMain.java

public static void main(String[] args) throws Exception {
    String termFilePath = null;//from w w  w.ja  va2 s .co m
    String outFilePath = null;
    Command command = Command.extract;
    int depth = -1;
    String databasePropertiesPath = null;
    String projectCode = null;
    String terminologyPropertiesPath = null;

    Map<String, String> argMap = StringUtils.convertArgs(args);

    String logConfigPath = argMap.get("logConfigFile");
    if (logConfigPath != null) {
        argMap.remove("logConfigFile");
        Properties props = new Properties();
        props.load(new FileInputStream(logConfigPath));
        PropertyConfigurator.configure(props);
    }

    Map<String, String> innerArgs = new HashMap<String, String>();
    for (Entry<String, String> argEntry : argMap.entrySet()) {
        String argName = argEntry.getKey();
        String argValue = argEntry.getValue();

        if (argName.equals("command"))
            command = Command.valueOf(argValue);
        else if (argName.equals("termFile"))
            termFilePath = argValue;
        else if (argName.equals("outFile"))
            outFilePath = argValue;
        else if (argName.equals("depth"))
            depth = Integer.parseInt(argValue);
        else if (argName.equals("databaseProperties"))
            databasePropertiesPath = argValue;
        else if (argName.equals("terminologyProperties"))
            terminologyPropertiesPath = argValue;
        else if (argName.equals("projectCode"))
            projectCode = argValue;
        else
            innerArgs.put(argName, argValue);
    }
    if (termFilePath == null && databasePropertiesPath == null)
        throw new TalismaneException("Required argument: termFile or databasePropertiesPath");

    if (termFilePath != null) {
        String currentDirPath = System.getProperty("user.dir");
        File termFileDir = new File(currentDirPath);
        if (termFilePath.lastIndexOf("/") >= 0) {
            String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/"));
            termFileDir = new File(termFileDirPath);
            termFileDir.mkdirs();
        }
    }

    long startTime = new Date().getTime();
    try {
        if (command.equals(Command.analyse)) {
            innerArgs.put("command", "analyse");
        } else {
            innerArgs.put("command", "process");
        }

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

        TalismaneConfig config = talismaneService.getTalismaneConfig(innerArgs, sessionId);

        TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance(locator);
        TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService();
        TerminologyBase terminologyBase = null;

        if (projectCode == null)
            throw new TalismaneException("Required argument: projectCode");

        File file = new File(databasePropertiesPath);
        FileInputStream fis = new FileInputStream(file);
        Properties dataSourceProperties = new Properties();
        dataSourceProperties.load(fis);
        terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties);

        TalismaneSession talismaneSession = talismaneService.getTalismaneSession();

        if (command.equals(Command.analyse) || command.equals(Command.extract)) {
            Locale locale = talismaneSession.getLocale();
            Map<TerminologyProperty, String> terminologyProperties = new HashMap<TerminologyProperty, String>();
            if (terminologyPropertiesPath != null) {
                Map<String, String> terminologyPropertiesStr = StringUtils.getArgMap(terminologyPropertiesPath);
                for (String key : terminologyPropertiesStr.keySet()) {
                    try {
                        TerminologyProperty property = TerminologyProperty.valueOf(key);
                        terminologyProperties.put(property, terminologyPropertiesStr.get(key));
                    } catch (IllegalArgumentException e) {
                        throw new TalismaneException("Unknown terminology property: " + key);
                    }
                }
            } else {
                terminologyProperties = getDefaultTerminologyProperties(locale);
            }
            if (depth <= 0 && !terminologyProperties.containsKey(TerminologyProperty.maxDepth))
                throw new TalismaneException("Required argument: depth");

            InputStream regexInputStream = getInputStreamFromResource(
                    "parser_conll_with_location_input_regex.txt");
            Scanner regexScanner = new Scanner(regexInputStream, "UTF-8");
            String inputRegex = regexScanner.nextLine();
            regexScanner.close();
            config.setInputRegex(inputRegex);

            Charset outputCharset = config.getOutputCharset();

            TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase,
                    terminologyProperties);
            if (depth > 0)
                termExtractor.setMaxDepth(depth);
            termExtractor.setOutFilePath(termFilePath);

            if (outFilePath != null) {
                if (outFilePath.lastIndexOf("/") >= 0) {
                    String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/"));
                    File outFileDir = new File(outFileDirPath);
                    outFileDir.mkdirs();
                }
                File outFile = new File(outFilePath);
                outFile.delete();
                outFile.createNewFile();

                Writer writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset));
                TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer);
                termExtractor.addTermObserver(termAnalysisWriter);
            }

            Talismane talismane = config.getTalismane();
            talismane.setParseConfigurationProcessor(termExtractor);
            talismane.process();
        } else if (command.equals(Command.list)) {

            List<Term> terms = terminologyBase.findTerms(2, null, 0, null, null);
            for (Term term : terms) {
                LOG.debug("Term: " + term.getText());
                LOG.debug("Frequency: " + term.getFrequency());
                LOG.debug("Heads: " + term.getHeads());
                LOG.debug("Expansions: " + term.getExpansions());
                LOG.debug("Contexts: " + term.getContexts());
            }
        }
    } finally {
        long endTime = new Date().getTime();
        long totalTime = endTime - startTime;
        LOG.info("Total time: " + totalTime);
    }
}

From source file:BookRank.java

/** Grab the sales rank off the web page and log it. */
public static void main(String[] args) throws Exception {

    Properties p = new Properties();
    String title = p.getProperty("title", "NO TITLE IN PROPERTIES");
    // The url must have the "isbn=" at the very end, or otherwise
    // be amenable to being string-catted to, like the default.
    String url = p.getProperty("url", "http://test.ing/test.cgi?isbn=");
    // The 10-digit ISBN for the book.
    String isbn = p.getProperty("isbn", "0000000000");
    // The RE pattern (MUST have ONE capture group for the number)
    String pattern = p.getProperty("pattern", "Rank: (\\d+)");

    // Looking for something like this in the input:
    //    <b>QuickBookShop.web Sales Rank: </b>
    //    26,252/*from ww  w.j a v  a  2s  . c  o m*/
    //    </font><br>

    Pattern r = Pattern.compile(pattern);

    // Open the URL and get a Reader from it.
    BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream()));
    // Read the URL looking for the rank information, as
    // a single long string, so can match RE across multi-lines.
    String input = "input from console";
    // System.out.println(input);

    // If found, append to sales data file.
    Matcher m = r.matcher(input);
    if (m.find()) {
        PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true));
        String date = // `date +'%m %d %H %M %S %Y'`;
                new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date());
        // Paren 1 is the digits (and maybe ','s) that matched; remove comma
        Matcher noComma = Pattern.compile(",").matcher(m.group(1));
        pw.println(date + noComma.replaceAll(""));
        pw.close();
    } else {
        System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!");
    }

    // Whether current data found or not, draw the graph, using
    // external plotting program against all historical data.
    // Could use gnuplot, R, any other math/graph program.
    // Better yet: use one of the Java plotting APIs.

    String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n"
            + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n"
            + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE
            + "\" using 1:7 title \"" + title + "\" with lines\n";

    Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot");
    PrintWriter gp = new PrintWriter(proc.getOutputStream());
    gp.print(gnuplot_cmd);
    gp.close();
}

From source file:com.jeeffy.test.streams.pageview.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",
            "streams-userprofile-store-name");

    KTable<String, String> userRegions = users.mapValues(new ValueMapper<JsonNode, String>() {
        @Override/*from  w ww  . j a va2 s. co 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);
                }
            }).groupByKey(Serdes.String(), jsonSerde)
            .count(TimeWindows.of(7 * 24 * 60 * 60 * 1000L).advanceBy(1000),
                    "RollingSevenDaysOfPageViewsByRegion")
            // 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.enjoyxstudy.selenium.htmlsuite.MultiHTMLSuiteRunner.java

/**
 * @param args/*from  w w w .j av a2s.  c o m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    String propertyFile = "htmlSuite.properties"; // default
    if (args.length != 0) {
        propertyFile = args[0];
    }
    Properties properties = new Properties();
    FileInputStream inputStream = new FileInputStream(propertyFile);
    try {
        properties.load(inputStream);
    } finally {
        inputStream.close();
    }

    MultiHTMLSuiteRunner runner = execute(properties);

    System.exit(runner.getResult() ? 0 : 1);
}