Example usage for com.fasterxml.jackson.databind.node ObjectNode put

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode put

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode put.

Prototype

public ObjectNode put(String paramString1, String paramString2) 

Source Link

Usage

From source file:org.bimserver.javamodelchecker.WriteToJson.java

public static void main(String[] args) {
    try {//from w  ww.ja v a 2s .  co m
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode rootNode = objectMapper.createObjectNode();
        ArrayNode array = objectMapper.createArrayNode();
        rootNode.set("modelcheckers", array);

        ObjectNode objectNode = objectMapper.createObjectNode();
        array.add(objectNode);
        objectNode.put("name", "Check window widths");
        objectNode.put("description", "Check window widths");
        objectNode.put("modelCheckerPluginClassName", "org.bimserver.javamodelchecker.JavaModelCheckerPlugin");
        objectNode.put("code",
                changeClassName(
                        FileUtils.readFileToString(
                                new File("src/org/bimserver/javamodelchecker/WindowWidthChecker.java")),
                        "WindowWidthChecker"));

        objectNode = objectMapper.createObjectNode();
        array.add(objectNode);
        objectNode.put("name", "Pass always");
        objectNode.put("description", "Pass always");
        objectNode.put("modelCheckerPluginClassName", "org.bimserver.javamodelchecker.JavaModelCheckerPlugin");
        objectNode.put("code", changeClassName(
                FileUtils.readFileToString(new File("src/org/bimserver/javamodelchecker/PassAlways.java")),
                "PassAlways"));

        objectNode = objectMapper.createObjectNode();
        array.add(objectNode);
        objectNode.put("name", "Fail always");
        objectNode.put("description", "Fail always");
        objectNode.put("modelCheckerPluginClassName", "org.bimserver.javamodelchecker.JavaModelCheckerPlugin");
        objectNode.put("code", changeClassName(
                FileUtils.readFileToString(new File("src/org/bimserver/javamodelchecker/FailAlways.java")),
                "FailAlways"));

        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File("modelcheckers.json"), rootNode);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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 ww.j  a  v  a2  s.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.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  w  w .jav a 2 s  .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);
                }
            }).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:squash.tools.FakeBookingCreator.java

public static void main(String[] args) throws IOException {
    int numberOfDays = 21;
    int numberOfCourts = 5;
    int maxCourtSpan = 5;
    int numberOfSlots = 16;
    int maxSlotSpan = 3;
    int minSurnameLength = 2;
    int maxSurnameLength = 20;
    int minBookingsPerDay = 0;
    int maxBookingsPerDay = 8;
    LocalDate startDate = LocalDate.of(2016, 7, 5);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    List<Booking> bookings = new ArrayList<>();
    for (LocalDate date = startDate; date.isBefore(startDate.plusDays(numberOfDays)); date = date.plusDays(1)) {
        int numBookings = ThreadLocalRandom.current().nextInt(minBookingsPerDay, maxBookingsPerDay + 1);
        List<Booking> daysBookings = new ArrayList<>();
        for (int bookingIndex = 0; bookingIndex < numBookings; bookingIndex++) {
            String player1 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic(
                    ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1));
            String player2 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic(
                    ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1));

            Set<ImmutablePair<Integer, Integer>> bookedCourts = new HashSet<>();
            daysBookings.forEach((booking) -> {
                addBookingToSet(booking, bookedCourts);
            });/*from  ww w. j  a  va 2 s  . com*/

            Booking booking;
            Set<ImmutablePair<Integer, Integer>> courtsToBook = new HashSet<>();
            do {
                // Loop until we create a booking of free courts
                int court = ThreadLocalRandom.current().nextInt(1, numberOfCourts + 1);
                int courtSpan = ThreadLocalRandom.current().nextInt(1,
                        Math.min(maxCourtSpan + 1, numberOfCourts - court + 2));
                int slot = ThreadLocalRandom.current().nextInt(1, numberOfSlots + 1);
                int slotSpan = ThreadLocalRandom.current().nextInt(1,
                        Math.min(maxSlotSpan + 1, numberOfSlots - slot + 2));
                booking = new Booking(court, courtSpan, slot, slotSpan, player1 + "/" + player2);
                booking.setDate(date.format(formatter));
                courtsToBook.clear();
                addBookingToSet(booking, courtsToBook);
            } while (Boolean.valueOf(Sets.intersection(courtsToBook, bookedCourts).size() > 0));

            daysBookings.add(booking);
        }
        bookings.addAll(daysBookings);
    }

    // Encode bookings as JSON
    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);
    // Create a json factory to write the treenode as json.
    JsonFactory jsonFactory = new JsonFactory();
    ObjectNode rootNode = factory.objectNode();

    ArrayNode bookingsNode = rootNode.putArray("bookings");
    for (int i = 0; i < bookings.size(); i++) {
        Booking booking = bookings.get(i);
        ObjectNode bookingNode = factory.objectNode();
        bookingNode.put("court", booking.getCourt());
        bookingNode.put("courtSpan", booking.getCourtSpan());
        bookingNode.put("slot", booking.getSlot());
        bookingNode.put("slotSpan", booking.getSlotSpan());
        bookingNode.put("name", booking.getName());
        bookingNode.put("date", booking.getDate());
        bookingsNode.add(bookingNode);
    }
    // Add empty booking rules array - just so restore works
    rootNode.putArray("bookingRules");
    rootNode.put("clearBeforeRestore", true);

    try (JsonGenerator generator = jsonFactory.createGenerator(new File("FakeBookings.json"),
            JsonEncoding.UTF8)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_EMPTY);
        mapper.setSerializationInclusion(Include.NON_NULL);
        mapper.writeTree(generator, rootNode);
    }
}

From source file:test.TestFinal.java

public static void main(String[] args) {
    //??//ww  w  .  jav a2s. co  m

    //      ObjectNode datanode = JsonNodeFactory.instance.objectNode();
    //      datanode.put(Constant.JSON_VERIFYCODES, "00c49b0ba48843e9946a3f9636406950");
    //      createNewIMUserSingle(datanode);
    // LOGIN  regist1
    ObjectNode datanode = JsonNodeFactory.instance.objectNode();
    datanode.put(Constant.JSON_PASSWORD, "liufacai1");
    datanode.put(Constant.JSON_TELEPHONE, "9999");

    ObjectNode createNewIMUserSingleNode = createNewIMUserSingle(datanode);
    // regist2
    //      ObjectNode datanode = JsonNodeFactory.instance.objectNode();
    //      datanode.put(Constant.JSON_ID, "ff8080814dd21098014dd213e3d20001");
    //      datanode.put(Constant.JSON_NAME, "3test");
    //      datanode.put(Constant.JSON_COMPANY_NAME, "3?");
    //      datanode.put(Constant.JSON_COMPANY_ISSAMEPEOPLE, "0");
    //      datanode.put(Constant.JSON_COMPANY_BUSINESSLICENSE, "??xcv".getBytes());
    //      datanode.put(Constant.JSON_COMPANY_IDCARD, "test".getBytes());
    //      datanode.put(Constant.JSON_COMPANY_POSITIONPROVE, "".getBytes());
    //      createNewIMUserSingle(datanode);
}

From source file:json_cmp.Comparer.java

public static void main(String[] args) {
    System.out.println("Testing Begin");
    try {/*w w  w  .  ja v  a2s  .  c o m*/

        String accessLogFolder = "/Users/herizhao/workspace/accessLog/";
        //        String yqlFileName = "json_cmp/test1.log";
        //        String yqlpFileName = "json_cmp/test2.log";
        String yqlFileName = "tempLog/0812_yql.res";
        String yqlpFileName = "tempLog/0812_yqlp.res";
        ReadResults input1 = new ReadResults(accessLogFolder + yqlFileName);
        ReadResults input2 = new ReadResults(accessLogFolder + yqlpFileName);
        Integer diffNum = 0;
        Integer errorCount = 0;
        Integer totalIDNum1 = 0;
        Integer totalIDNum2 = 0;
        Integer equalIDwithDuplicate = 0;
        Integer beacons = 0;
        Integer lineNum = 0;
        Integer tempCount = 0;
        HashMap<String, IDclass> IDarray = new HashMap<String, IDclass>();
        FileOutputStream fos = new FileOutputStream(
                "/Users/herizhao/workspace/accessLog/json_cmp/cmp_result.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        BufferedWriter bw = new BufferedWriter(osw);
        FileOutputStream consoleStream = new FileOutputStream(
                "/Users/herizhao/workspace/accessLog/json_cmp/console");
        OutputStreamWriter consoleOSW = new OutputStreamWriter(consoleStream);
        BufferedWriter console = new BufferedWriter(consoleOSW);
        while (true) {
            input1.ReadNextLine();
            if (input1.line == null)
                break;
            input2.ReadNextLine();
            if (input2.line == null)
                break;
            while (input1.line.equals("")) {
                lineNum++;
                input1.ReadNextLine();
                input2.ReadNextLine();
            }
            if (input2.line == null)
                break;
            if (input1.line == null)
                break;
            lineNum++;
            System.out.println("lineNum = " + lineNum);
            String str1 = input1.line;
            String str2 = input2.line;
            ObjectMapper mapper1 = new ObjectMapper();
            ObjectMapper mapper2 = new ObjectMapper();
            JsonNode root1 = mapper1.readTree(str1);
            JsonNode root2 = mapper2.readTree(str2);
            JsonNode mediaNode1 = root1.path("query").path("results").path("mediaObj");
            JsonNode mediaNode2 = root2.path("query").path("results").path("mediaObj");
            if (mediaNode2.isMissingNode() && !mediaNode1.isMissingNode())
                tempCount += mediaNode1.size();
            //For yqlp
            if (mediaNode2.isArray()) {
                totalIDNum2 += mediaNode2.size();
                for (int i = 0; i < mediaNode2.size(); i++) {
                    ObjectNode mediaObj = (ObjectNode) mediaNode2.get(i);
                    mediaObj.put("yvap", "");
                    JsonNode streamsNode = mediaObj.path("streams");
                    //streams
                    if (streamsNode.isArray()) {
                        for (int j = 0; j < streamsNode.size(); j++) {
                            ObjectNode streamsObj = (ObjectNode) streamsNode.get(j);
                            changeStreamsPath(streamsObj);
                            ChangedHost(streamsObj);
                            //if(streamsObj.path("h264_profile").isMissingNode())
                            streamsObj.put("h264_profile", "");
                            if (streamsObj.path("is_primary").isMissingNode())
                                streamsObj.put("is_primary", false);
                        }
                    }
                    //meta
                    if (!mediaObj.path("meta").isMissingNode()) {
                        ObjectNode metaObj = (ObjectNode) mediaObj.path("meta");
                        changeMetaThumbnail(metaObj);
                        if (metaObj.path("show_name").isMissingNode())
                            metaObj.put("show_name", "");
                        if (metaObj.path("event_start").isMissingNode())
                            metaObj.put("event_start", "");
                        if (metaObj.path("event_stop").isMissingNode())
                            metaObj.put("event_stop", "");
                        //if(metaObj.path("credits").path("label").isMissingNode())
                        ((ObjectNode) metaObj.path("credits")).put("label", "");
                    }
                    //Metrics -> plidl & isrc
                    changeMetrics(mediaObj);
                }
            }

            //For yql
            if (mediaNode1.isArray()) {
                totalIDNum1 += mediaNode1.size();
                for (int i = 0; i < mediaNode1.size(); i++) {
                    JsonNode mediaObj = mediaNode1.get(i);
                    ((ObjectNode) mediaObj).put("yvap", "");
                    //Meta
                    //System.out.println("meta: ");
                    if (!mediaObj.path("meta").isMissingNode()) {
                        ObjectNode metaObj = (ObjectNode) mediaObj.path("meta");
                        changeMetaThumbnail(metaObj);
                        metaObj.put("event_start", "");
                        metaObj.put("event_stop", "");
                        FloatingtoInt(metaObj, "duration");
                        if (metaObj.path("show_name").isMissingNode())
                            metaObj.put("show_name", "");
                        //System.out.println("thub_dem: ");
                        if (!metaObj.path("thumbnail_dimensions").isMissingNode()) {
                            ObjectNode thub_demObj = (ObjectNode) metaObj.path("thumbnail_dimensions");
                            FloatingtoInt(thub_demObj, "height");
                            FloatingtoInt(thub_demObj, "width");
                        }
                        ((ObjectNode) metaObj.path("credits")).put("label", "");
                    }
                    //Visualseek
                    //System.out.println("visualseek: ");
                    if (!mediaObj.path("visualseek").isMissingNode()) {
                        ObjectNode visualseekObj = (ObjectNode) mediaObj.path("visualseek");
                        FloatingtoInt(visualseekObj, "frequency");
                        FloatingtoInt(visualseekObj, "width");
                        FloatingtoInt(visualseekObj, "height");
                        //visualseek -> images, float to int
                        JsonNode imagesNode = visualseekObj.path("images");
                        if (imagesNode.isArray()) {
                            for (int j = 0; j < imagesNode.size(); j++) {
                                ObjectNode imageObj = (ObjectNode) imagesNode.get(j);
                                FloatingtoInt(imageObj, "start_index");
                                FloatingtoInt(imageObj, "count");
                            }
                        }
                    }
                    //Streams
                    //System.out.println("streams: ");
                    JsonNode streamsNode = mediaObj.path("streams");
                    if (streamsNode.isArray()) {
                        for (int j = 0; j < streamsNode.size(); j++) {
                            ObjectNode streamsObj = (ObjectNode) streamsNode.get(j);
                            FloatingtoInt(streamsObj, "height");
                            FloatingtoInt(streamsObj, "bitrate");
                            FloatingtoInt(streamsObj, "duration");
                            FloatingtoInt(streamsObj, "width");
                            changeStreamsPath(streamsObj);
                            ChangedHost(streamsObj);
                            //                        if(streamsObj.path("h264_profile").isMissingNode())
                            streamsObj.put("h264_profile", "");
                            if (streamsObj.path("is_primary").isMissingNode())
                                streamsObj.put("is_primary", false);
                        }
                    }
                    //Metrics -> plidl & isrc
                    changeMetrics(mediaObj);
                }
            }

            //Compare
            if (mediaNode2.isArray() && mediaNode1.isArray()) {
                for (int i = 0; i < mediaNode2.size() && i < mediaNode1.size(); i++) {
                    JsonNode mediaObj1 = mediaNode1.get(i);
                    JsonNode mediaObj2 = mediaNode2.get(i);
                    if (!mediaObj1.equals(mediaObj2)) {
                        if (!mediaObj1.path("id").toString().equals(mediaObj2.path("id").toString())) {
                            errorCount++;
                        } else {
                            Integer IFdiffStreams = 0;
                            Integer IFdiffMeta = 0;
                            Integer IFdiffvisualseek = 0;
                            Integer IFdiffMetrics = 0;
                            Integer IFdifflicense = 0;
                            Integer IFdiffclosedcaptions = 0;
                            String statusCode = "";
                            MetaClass tempMeta = new MetaClass();
                            if (!mediaObj1.path("status").equals(mediaObj2.path("status"))) {
                                JsonNode statusNode1 = mediaObj1.path("status");
                                JsonNode statusNode2 = mediaObj2.path("status");
                                if (statusNode2.path("code").toString().equals("\"100\"")
                                        || (statusNode1.path("code").toString().equals("\"400\"")
                                                && statusNode1.path("code").toString().equals("\"404\""))
                                        || (statusNode1.path("code").toString().equals("\"200\"")
                                                && statusNode1.path("code").toString().equals("\"200\""))
                                        || (statusNode1.path("code").toString().equals("\"200\"")
                                                && statusNode1.path("code").toString().equals("\"403\"")))
                                    statusCode = "";
                                else
                                    statusCode = "yql code: " + mediaObj1.path("status").toString()
                                            + " yqlp code:" + mediaObj2.path("status").toString();
                            } else {//Status code is 100
                                if (!mediaObj1.path("streams").equals(mediaObj2.path("streams")))
                                    IFdiffStreams = 1;
                                if (!tempMeta.CompareMeta(mediaObj1.path("meta"), mediaObj2.path("meta"),
                                        lineNum))
                                    IFdiffMeta = 1;
                                if (!mediaObj1.path("visualseek").equals(mediaObj2.path("visualseek")))
                                    IFdiffvisualseek = 1;
                                if (!mediaObj1.path("metrics").equals(mediaObj2.path("metrics"))) {
                                    IFdiffMetrics = 1;
                                    JsonNode metrics1 = mediaObj1.path("metrics");
                                    JsonNode metrics2 = mediaObj2.path("metrics");
                                    if (!metrics1.path("beacons").equals(metrics2.path("beacons")))
                                        beacons++;
                                }
                                if (!mediaObj1.path("license").equals(mediaObj2.path("license")))
                                    IFdifflicense = 1;
                                if (!mediaObj1.path("closedcaptions").equals(mediaObj2.path("closedcaptions")))
                                    IFdiffclosedcaptions = 1;
                            }
                            if (IFdiffStreams + IFdiffMeta + IFdiffvisualseek + IFdiffMetrics + IFdifflicense
                                    + IFdiffclosedcaptions != 0 || !statusCode.equals("")) {
                                String ID_str = mediaObj1.path("id").toString();
                                if (!IDarray.containsKey(ID_str)) {
                                    IDclass temp_IDclass = new IDclass(ID_str);
                                    temp_IDclass.addNum(IFdiffStreams, IFdiffMeta, IFdiffvisualseek,
                                            IFdiffMetrics, IFdifflicense, IFdiffclosedcaptions, lineNum);
                                    if (!statusCode.equals(""))
                                        temp_IDclass.statusCode = statusCode;
                                    IDarray.put(ID_str, temp_IDclass);
                                } else {
                                    IDarray.get(ID_str).addNum(IFdiffStreams, IFdiffMeta, IFdiffvisualseek,
                                            IFdiffMetrics, IFdifflicense, IFdiffclosedcaptions, lineNum);
                                    if (!statusCode.equals(""))
                                        IDarray.get(ID_str).statusCode = statusCode;
                                }
                                IDarray.get(ID_str).stream.CompareStream(IFdiffStreams,
                                        mediaObj1.path("streams"), mediaObj2.path("streams"), lineNum);
                                if (!IDarray.get(ID_str).metaDone) {
                                    IDarray.get(ID_str).meta = tempMeta;
                                    IDarray.get(ID_str).metaDone = true;
                                }
                            } else
                                equalIDwithDuplicate++;
                        }
                    } else
                        equalIDwithDuplicate++;
                }
            }
            bw.flush();
            console.flush();

        } //while
        System.out.println("done");
        bw.write("Different ID" + "   " + "num   ");
        bw.write(PrintStreamsTitle());
        bw.write(PrintMetaTitle());
        bw.write(PrintTitle());
        bw.newLine();
        Iterator<String> iter = IDarray.keySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            bw.write(key + "   ");
            bw.write(IDarray.get(key).num.toString() + "   ");
            bw.write(IDarray.get(key).stream.print());
            bw.write(IDarray.get(key).meta.print());
            bw.write(IDarray.get(key).print());
            bw.newLine();
            //System.out.println(key);
        }
        //System.out.println("different log num = " + diffNum);
        //System.out.println("same log num = " + sameLogNum);
        System.out.println("Different ID size = " + IDarray.size());
        //         System.out.println("streamEqual = " + streamEqual);
        //         System.out.println("metaEqual = " + metaEqual);
        //         System.out.println("metricsEqual = " + metricsEqual);
        //         System.out.println("visualseekEqual = " + visualseekEqual);
        //         System.out.println("licenseEqual = " + licenseEqual);
        //         System.out.println("closedcaptionsEqualEqual = " + closedcaptionsEqual);
        System.out.println(tempCount);
        System.out.println("beacons = " + beacons);
        System.out.println("equalIDwithDuplicate = " + equalIDwithDuplicate);
        System.out.println("Total ID num yql (including duplicates) = " + totalIDNum1);
        System.out.println("Total ID num yqpl (including duplicates) = " + totalIDNum2);
        System.out.println("Error " + errorCount);
        bw.close();
        console.close();
    } catch (IOException e) {
    }
}

From source file:org.waarp.openr66.protocol.http.rest.test.HttpTestRestR66Client.java

/**
 * @param args//from w ww .  j  a  v  a  2s . com
 */
@SuppressWarnings("unused")
public static void main(String[] args) {
    if (args.length > 2) {
        WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(WaarpLogLevel.DEBUG));
    } else {
        WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null));
    }
    logger = WaarpLoggerFactory.getLogger(HttpTestRestR66Client.class);
    Configuration.configuration.HOST_ID = hostid;
    if (args.length > 0) {
        NB = Integer.parseInt(args[0]);
        if (Configuration.configuration.CLIENT_THREAD < NB) {
            Configuration.configuration.CLIENT_THREAD = NB + 1;
        }
        if (args.length > 1) {
            NBPERTHREAD = Integer.parseInt(args[1]);
        }
    }
    if (NB == 1 && NBPERTHREAD == 1) {
        DEBUG = true;
    }

    try {
        HttpTestR66PseudoMain.config = HttpTestR66PseudoMain.getTestConfiguration();
    } catch (CryptoException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
        return;
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
        return;
    }
    if (HttpTestR66PseudoMain.config.REST_ADDRESS != null) {
        host = HttpTestR66PseudoMain.config.REST_ADDRESS;
    }
    String filename = keydesfilename;
    Configuration.configuration.cryptoFile = filename;
    File keyfile = new File(filename);
    Des des = new Des();
    try {
        des.setSecretKey(keyfile);
    } catch (CryptoException e) {
        logger.error("Unable to load CryptoKey from Config file");
        return;
    } catch (IOException e) {
        logger.error("Unable to load CryptoKey from Config file");
        return;
    }
    Configuration.configuration.cryptoKey = des;
    HttpRestR66Handler.instantiateHandlers(HttpTestR66PseudoMain.config);
    // Configure the client.
    clientHelper = new HttpRestR66Client(baseURI, new HttpTestRestClientInitializer(null),
            Configuration.configuration.CLIENT_THREAD, Configuration.configuration.TIMEOUTCON);
    logger.warn("ClientHelper created");
    try {
        try {
            long start = System.currentTimeMillis();
            for (int i = 0; i < NBPERTHREAD; i++) {
                options(null);
            }
            long stop = System.currentTimeMillis();
            long diff = stop - start == 0 ? 1 : stop - start;
            logger.warn("Options: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get());
        } catch (HttpInvalidAuthenticationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        count.set(0);
        long start = System.currentTimeMillis();
        if (false) {
            for (RESTHANDLERS handler : HttpRestR66Handler.RESTHANDLERS.values()) {
                try {
                    deleteData(handler);
                } catch (HttpInvalidAuthenticationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        long stop = System.currentTimeMillis();
        long diff = stop - start == 0 ? 1 : stop - start;
        if (false) {
            logger.warn("Delete: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get());
        }
        count.set(0);
        start = System.currentTimeMillis();
        for (RestMethodHandler methodHandler : HttpTestR66PseudoMain.config.restHashMap.values()) {
            if (methodHandler instanceof DataModelRestMethodHandler<?>) {
                RESTHANDLERS handler = RESTHANDLERS.getRESTHANDLER(methodHandler.getPath());
                try {
                    multiDataRequests(handler);
                } catch (HttpInvalidAuthenticationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        stop = System.currentTimeMillis();
        diff = stop - start == 0 ? 1 : stop - start;
        logger.warn("Create: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get());
        count.set(0);
        start = System.currentTimeMillis();
        for (RestMethodHandler methodHandler : HttpTestR66PseudoMain.config.restHashMap.values()) {
            if (methodHandler instanceof DataModelRestMethodHandler<?>) {
                RESTHANDLERS handler = RESTHANDLERS.getRESTHANDLER(methodHandler.getPath());
                try {
                    realAllData(handler);
                } catch (HttpInvalidAuthenticationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        stop = System.currentTimeMillis();
        diff = stop - start == 0 ? 1 : stop - start;
        logger.warn("ReadAll: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get());

        count.set(0);
        start = System.currentTimeMillis();
        for (int i = 0; i < NBPERTHREAD; i++) {
            try {
                multiDataRequests(RESTHANDLERS.DbTaskRunner);
            } catch (HttpInvalidAuthenticationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        stop = System.currentTimeMillis();
        diff = stop - start == 0 ? 1 : stop - start;
        logger.warn(
                "CreateMultiple: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get());

        count.set(0);
        start = System.currentTimeMillis();
        launchThreads();
        stop = System.currentTimeMillis();
        diff = stop - start == 0 ? 1 : stop - start;
        logger.warn("CreateMultipleThread: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD * NB + "=?"
                + count.get());

        // Set usefull item first
        if (RestConfiguration.CRUD.UPDATE.isValid(
                HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[RESTHANDLERS.DbHostConfiguration.ordinal()])) {
            String key = null, value = null;
            Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT);
            if (channel != null) {
                String buz = null;
                if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) {
                    key = userAuthent;
                    value = keyAuthent;
                    // Need business
                    buz = "<business><businessid>hostas</businessid><businessid>hosta2</businessid><businessid>hostas2</businessid>"
                            + "<businessid>hosta</businessid><businessid>test</businessid><businessid>tests</businessid>"
                            + "<businessid>" + userAuthent + "</businessid></business>";
                } else {
                    // Need business
                    buz = "<business><businessid>hostas</businessid><businessid>hosta2</businessid><businessid>hostas2</businessid>"
                            + "<businessid>hosta</businessid><businessid>test</businessid><businessid>tests</businessid>"
                            + "<businessid>monadmin</businessid></business>";
                }
                ObjectNode node = JsonHandler.createObjectNode();
                node.put(DbHostConfiguration.Columns.BUSINESS.name(), buz);
                logger.warn("Send query: " + RESTHANDLERS.DbHostConfiguration.uri);
                RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel,
                        HttpMethod.PUT, host, RESTHANDLERS.DbHostConfiguration.uri + "/hosta", key, value, null,
                        JsonHandler.writeAsString(node));
                try {
                    future.await();
                } catch (InterruptedException e) {
                }
                WaarpSslUtility.closingSslChannel(channel);
            }
            // Need Hostzz
            channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT);
            if (channel != null) {
                AbstractDbData dbData;
                dbData = new DbHostAuth(null, hostid, address, HttpTestR66PseudoMain.config.REST_PORT, false,
                        hostkey.getBytes(), true, false);
                logger.warn("Send query: " + RESTHANDLERS.DbHostAuth.uri);
                RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel,
                        HttpMethod.POST, host, RESTHANDLERS.DbHostAuth.uri, key, value, null, dbData.asJson());
                try {
                    future.await();
                } catch (InterruptedException e) {
                }
                WaarpSslUtility.closingSslChannel(channel);
            }
        }

        // Other Command as actions
        count.set(0);
        start = System.currentTimeMillis();
        for (RestMethodHandler methodHandler : HttpTestR66PseudoMain.config.restHashMap.values()) {
            if (methodHandler instanceof DataModelRestMethodHandler<?>) {
                RESTHANDLERS handler = RESTHANDLERS.getRESTHANDLER(methodHandler.getPath());
                try {
                    action(handler);
                } catch (HttpInvalidAuthenticationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        getStatus();
        stop = System.currentTimeMillis();
        diff = stop - start == 0 ? 1 : stop - start;
        logger.warn(
                "Commands: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD * NB + "=?" + count.get());

        count.set(0);
        start = System.currentTimeMillis();
        for (int i = 0; i < NBPERTHREAD; i++) {
            getStatus();
        }
        stop = System.currentTimeMillis();
        diff = stop - start == 0 ? 1 : stop - start;
        logger.warn("GetStatusMultiple: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?"
                + count.get());

        count.set(0);
        isStatus = true;
        start = System.currentTimeMillis();
        launchThreads();
        stop = System.currentTimeMillis();
        diff = stop - start == 0 ? 1 : stop - start;
        logger.warn("GetStatusMultipleThread: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD * NB
                + "=?" + count.get());

        // Clean
        if (RestConfiguration.CRUD.UPDATE.isValid(
                HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[RESTHANDLERS.DbHostConfiguration.ordinal()])) {
            String key = null, value = null;
            Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT);
            if (channel != null) {
                if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) {
                    key = userAuthent;
                    value = keyAuthent;
                }
                // Reset business
                String buz = "<business><businessid>hostas</businessid><businessid>hosta2</businessid><businessid>hostas2</businessid>"
                        + "<businessid>hosta</businessid><businessid>test</businessid><businessid>tests</businessid></business>";
                ObjectNode node = JsonHandler.createObjectNode();
                node.put(DbHostConfiguration.Columns.BUSINESS.name(), buz);
                logger.warn("Send query: " + RESTHANDLERS.DbHostConfiguration.uri);
                RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel,
                        HttpMethod.PUT, host, RESTHANDLERS.DbHostConfiguration.uri + "/hosta", key, value, null,
                        JsonHandler.writeAsString(node));
                try {
                    future.await();
                } catch (InterruptedException e) {
                }
                WaarpSslUtility.closingSslChannel(channel);
            }
            // Remove Hostzz
            channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT);
            if (channel != null) {
                try {
                    RestFuture future = deleteData(channel, RESTHANDLERS.DbHostAuth);
                    try {
                        future.await();
                    } catch (InterruptedException e) {
                    }
                } catch (HttpInvalidAuthenticationException e1) {
                }
                WaarpSslUtility.closingSslChannel(channel);
            }
            // Shutdown
            channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT);
            if (channel != null) {
                ShutdownOrBlockJsonPacket shutd = new ShutdownOrBlockJsonPacket();
                shutd.setRestartOrBlock(false);
                shutd.setShutdownOrBlock(true);
                shutd.setRequestUserPacket(LocalPacketFactory.SHUTDOWNPACKET);
                String pwd = "pwdhttp";
                byte[] bpwd = FilesystemBasedDigest.passwdCrypt(pwd.getBytes(WaarpStringUtils.UTF8));
                shutd.setKey(bpwd);
                logger.warn("Send query: " + RESTHANDLERS.Server.uri);
                RestFuture future = action(channel, HttpMethod.PUT, RESTHANDLERS.Server.uri, shutd);
                try {
                    future.await();
                } catch (InterruptedException e) {
                }
                WaarpSslUtility.closingSslChannel(channel);
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e1) {
        }
    } finally {
        logger.debug("ClientHelper closing");
        clientHelper.closeAll();
        logger.warn("ClientHelper closed");
    }
}

From source file:com.pros.jsontransform.expression.FunctionSet.java

public static JsonNode evaluate(final JsonNode argsNode, final JsonNode valueNode,
        final ObjectTransformer transformer) throws ObjectTransformerException {
    ObjectNode resultNode = (ObjectNode) argsNode;
    resultNode.put("returnValue", transformArgument(argsNode.path(ARGUMENT_WITH), transformer));

    return resultNode.get("returnValue");
}

From source file:com.pros.jsontransform.expression.FunctionAppend.java

public static JsonNode evaluate(final JsonNode argsNode, final JsonNode valueNode,
        final ObjectTransformer transformer) throws ObjectTransformerException {
    ObjectNode resultNode = (ObjectNode) argsNode;
    resultNode.put("returnValue", transformValue(valueNode, transformer)
            + transformArgument(argsNode.path(ARGUMENT_WHAT), transformer).asText());

    return resultNode.get("returnValue");
}

From source file:com.pros.jsontransform.expression.FunctionRandomUUID.java

public static JsonNode evaluate(final JsonNode argsNode, final JsonNode valueNode,
        final ObjectTransformer transformer) throws ObjectTransformerException {
    ObjectNode resultNode = (ObjectNode) argsNode;
    resultNode.put("returnValue", UUID.randomUUID().toString());

    return resultNode.get("returnValue");
}