private void addVertexToPolygon(double lat, double lon, double hae) throws JsonGenerationException, IOException { try { if (firstVertex) { firstVertex = false; cachedLat = lat; cachedLon = lon; cachedHae = hae; firstVertex = false; } generator.writeStartArray(); generator.writeNumber(lon); generator.writeNumber(lat); // generator.writeNumber(hae); generator.writeEndArray(); } catch (Exception e) { log.error(e); log.error(e.getStackTrace()); } }
private void addVertexToPolygon(double lat, double lon, double hae) throws JsonGenerationException, IOException { if( firstVertex ) { firstVertex = false; cachedLat = lat; cachedLon = lon; cachedHae = hae; firstVertex = false; } generator.writeStartArray(); generator.writeNumber(lon); generator.writeNumber(lat); //generator.writeNumber(hae); generator.writeEndArray(); }
@Test public void testBucketCache() throws JsonGenerationException, JsonMappingException, IOException { this.conf.set(HConstants.BUCKET_CACHE_IOENGINE_KEY, "offheap"); this.conf.setInt(HConstants.BUCKET_CACHE_SIZE_KEY, 100); CacheConfig cc = new CacheConfig(this.conf); assertTrue(cc.getBlockCache() instanceof CombinedBlockCache); logPerBlock(cc.getBlockCache()); final int count = 3; addDataAndHits(cc.getBlockCache(), count); // The below has no asserts. It is just exercising toString and toJSON code. LOG.info(cc.getBlockCache().getStats()); BlockCacheUtil.CachedBlocksByFile cbsbf = logPerBlock(cc.getBlockCache()); LOG.info(cbsbf); logPerFile(cbsbf); bucketCacheReport(cc.getBlockCache()); LOG.info(BlockCacheUtil.toJSON(cbsbf)); }
@Test public void testLruBlockCache() throws JsonGenerationException, JsonMappingException, IOException { CacheConfig cc = new CacheConfig(this.conf); assertTrue(cc.isBlockCacheEnabled()); assertTrue(CacheConfig.DEFAULT_IN_MEMORY == cc.isInMemory()); assertTrue(cc.getBlockCache() instanceof LruBlockCache); logPerBlock(cc.getBlockCache()); addDataAndHits(cc.getBlockCache(), 3); // The below has no asserts. It is just exercising toString and toJSON code. BlockCache bc = cc.getBlockCache(); LOG.info("count=" + bc.getBlockCount() + ", currentSize=" + bc.getCurrentSize() + ", freeSize=" + bc.getFreeSize() ); LOG.info(cc.getBlockCache().getStats()); BlockCacheUtil.CachedBlocksByFile cbsbf = logPerBlock(cc.getBlockCache()); LOG.info(cbsbf); logPerFile(cbsbf); bucketCacheReport(cc.getBlockCache()); LOG.info(BlockCacheUtil.toJSON(cbsbf)); }
private void logPerFile(final BlockCacheUtil.CachedBlocksByFile cbsbf) throws JsonGenerationException, JsonMappingException, IOException { for (Map.Entry<String, NavigableSet<CachedBlock>> e: cbsbf.getCachedBlockStatsByFile().entrySet()) { int count = 0; long size = 0; int countData = 0; long sizeData = 0; for (CachedBlock cb: e.getValue()) { count++; size += cb.getSize(); BlockType bt = cb.getBlockType(); if (bt != null && bt.isData()) { countData++; sizeData += cb.getSize(); } } LOG.info("filename=" + e.getKey() + ", count=" + count + ", countData=" + countData + ", size=" + size + ", sizeData=" + sizeData); LOG.info(BlockCacheUtil.toJSON(e.getKey(), e.getValue())); } }
public void output(Map<String, Object> parameters, boolean withRequest, boolean prettyPrint) throws JsonGenerationException, JsonMappingException, IOException { Map<String, Object> result = new LinkedHashMap<String, Object>(); // put request to result if (withRequest) { Map<String, Object> request = new LinkedHashMap<String, Object>(); request.put("command", getName()); request.put("parameters", parameters); result.put("request", request); } // put response to result putResponse("status", getStatus()); putResponse("message", getMessage()); result.put("response", getResponse()); ObjectMapper mapper = new ObjectMapper(); if (prettyPrint) { // enable pretty print System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result)); } else { System.out.println(mapper.writeValueAsString(result)); } }
public CommandImpl(Long id, IPolicy policy, ITask task, List<String> dnList, DNType dnType, List<String> uidList, String commandOwnerUid, Date activationDate, Date expirationDate, Date createDate, List<CommandExecutionImpl> commandExecutions, boolean sentMail) throws JsonGenerationException, JsonMappingException, IOException { this.id = id; this.policy = (PolicyImpl) policy; this.task = (TaskImpl) task; ObjectMapper mapper = new ObjectMapper(); this.dnListJsonString = mapper.writeValueAsString(dnList); setDnType(dnType); this.uidListJsonString = uidList != null ? mapper.writeValueAsString(uidList) : null; this.commandOwnerUid = commandOwnerUid; this.activationDate = activationDate; this.expirationDate = expirationDate; this.createDate = createDate; this.commandExecutions = commandExecutions; this.sentMail = sentMail; }
public CommandImpl(ICommand command) throws JsonGenerationException, JsonMappingException, IOException { this.id = command.getId(); this.policy = (PolicyImpl) command.getPolicy(); this.task = (TaskImpl) command.getTask(); ObjectMapper mapper = new ObjectMapper(); this.dnListJsonString = mapper.writeValueAsString(command.getDnList()); setDnType(command.getDnType()); this.uidListJsonString = command.getUidList() != null ? mapper.writeValueAsString(command.getUidList()) : null; this.commandOwnerUid = command.getCommandOwnerUid(); this.activationDate = command.getActivationDate(); this.expirationDate = command.getExpirationDate(); this.createDate = command.getCreateDate(); this.sentMail = command.isSentMail(); this.mailThreadingActive=command.isMailThreadingActive(); // Convert ICommandExecution to CommandExecutionImpl List<? extends ICommandExecution> tmpCommandExecutions = command.getCommandExecutions(); if (tmpCommandExecutions != null) { for (ICommandExecution commandExecution : tmpCommandExecutions) { addCommandExecution(commandExecution); } } }
/*********** stdin/namedpipe loop ***********/ void namedpipeLoop() throws JsonGenerationException, JsonMappingException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); String inputline; BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(outpipeFilename, true)); // OutputStream out = new FileOutputStream(outpipeFilename, true); log("Waiting for commands on stdin"); while ( (inputline=reader.readLine()) != null) { JsonNode result = parseAndRunCommand(inputline); writeResultToStream(result, out); out.flush(); checkTimings(); } }
public HashMap<String, Object> execute(String operation, String content) throws JsonGenerationException, JsonMappingException, IOException, UserSysException { HashMap<String, Object> res = callOpenAPI(operation, content); //try { //int status = (Integer)res.get("status"); String body = (String)res.get("body"); ObjectMapper mapper = new ObjectMapper(); Object json = mapper.readValue(body, Object.class); res.put("json", json); //} catch (JsonGenerationException ex) { // res.put("exception", ex); //} catch (JsonMappingException ex) { // res.put("exception", ex); //} catch (IOException ex) { // res.put("exception", ex); //} catch (UserSysException ex) { //} return res; }
private static void setOrRemoveOptionalAttributeList(GluuCustomPerson destination, List<?> items, String attributeName) throws JsonGenerationException, JsonMappingException, IOException { if (items == null) { log.trace(" removing " + attributeName); destination.removeAttribute(attributeName); } else { log.trace(" setting " + attributeName); StringWriter listOfItems = new StringWriter(); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(listOfItems, items); destination.setAttribute(attributeName, listOfItems.toString()); } }
public static String toJsonString(Object obj, boolean bStripJsReservedWords) throws JsonGenerationException, JsonMappingException, IOException { String strResult = null; if (obj != null) { if (bStripJsReservedWords && obj instanceof JetstreamEvent) obj = ((JetstreamEvent)obj).getFilteredEvent(); try { ObjectMapper mapper = new ObjectMapper(); Writer writer = new StringWriter(); mapper.writeValue(writer, obj); strResult = writer.toString(); } catch (Throwable t) { if (m_nErrorCount++ % 10000 == 0 && LOGGER.isErrorEnabled()) LOGGER.error( "", t); } } return strResult; }
private boolean isDoubleBroadcast(HttpServletRequest request, Object responseEntity) throws JsonGenerationException, JsonMappingException, IOException { String clientId = request.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); // return false if the X-Atmosphere-tracking-id is not set if (clientId == null || clientId.isEmpty()) { return false; } CacheEntry entry = ResourceStateChangeListener.getCachedEntries().put( clientId, new CacheEntry(responseEntity)); // there was an existing cached entry, see if its the same if (entry != null) { ObjectMapper mapper = new ObjectMapper(); // cached data final String firedResponse = mapper.writeValueAsString(entry.getData()); // new data final String responseValue = mapper.writeValueAsString(responseEntity); // the same ? return responseValue.equals(firedResponse); } return false; }
/** * Open a JSON output file * The file output may be derived from many input sources * * @param name * @param string * @throws XMLStreamException * @throws IOException */ public void open(File file) throws XMLStreamException, IOException { // Mapped convention JsonFactory f = new JsonFactory(); try { generator = f.createJsonGenerator(new FileWriter(file)); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); generator.setCodec(mapper); generator.useDefaultPrettyPrinter(); rootNode = mapper.createObjectNode(); rootNode.put("name", "odfestyles"); rootArray = rootNode.putArray(CHILDREN_TAG); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void open(File file) throws XMLStreamException, IOException { // Mapped convention JsonFactory f = new JsonFactory(); try { generator = f.createJsonGenerator(new FileWriter(file)); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); generator.setCodec(mapper); generator.useDefaultPrettyPrinter(); rootNode = mapper.createObjectNode(); rootNode.put("name", "odfpaths"); rootArray = rootNode.putArray(CHILDREN_TAG); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@GET @Produces(MediaType.APPLICATION_JSON) public String list() throws JsonGenerationException, JsonMappingException, IOException { this.logger.info("list()"); ObjectWriter viewWriter; if (this.isAdmin()) { viewWriter = this.mapper.writerWithView(JsonViews.Admin.class); } else { viewWriter = this.mapper.writerWithView(JsonViews.User.class); } List<NewsEntry> allEntries = this.newsEntryDao.findAll(); return viewWriter.writeValueAsString(allEntries); }
private static void sendMessage() throws IOException, JsonProcessingException, JsonGenerationException, JsonMappingException, UnsupportedEncodingException, HttpException { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> m = new HashMap<String, Object>(); m.put("si", "12345"); m.put("ct", System.currentTimeMillis()); String payload = mapper.writeValueAsString(m); HttpClient client = new HttpClient(); PostMethod method = new PostMethod("http://localhost:8080/tracking/ingest/PulsarRawEvent"); // method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch"); method.setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8")); int status = client.executeMethod(method); System.out.println(Arrays.toString(method.getResponseHeaders())); System.out.println("Status code: " + status + ", Body: " + method.getResponseBodyAsString()); }
public void derp() throws JsonGenerationException, JsonMappingException, IOException { // TorrentClient tc = TorrentClient.start(); // ScanDirectory.start(new File(DataSources.SAMPLE_MUSIC_DIR), tc); // List all the music files in the sub or sub directories // String[] types = {"mp3"}; // // Collection<File> files = FileUtils.listFiles(new File(DataSources.SAMPLE_MUSIC_DIR), types , true); // // // Set<ScanInfo> scanInfos = new LinkedHashSet<ScanInfo>(); // // for (File file : files) { // scanInfos.add(ScanInfo.create(file)); // } // // String json = Tools.MAPPER.writeValueAsString(scanInfos); // System.out.println(json); Song song = Song.fetchSong(new File("/home/tyler/.torrenttunes-client/cache/1-06 Raconte-Moi Une Histoire.mp3")); System.out.println(song.getRecording()); }
public static void derp6() throws JsonGenerationException, JsonMappingException, IOException { // Song song = Song.fetchSong(new File(DataSources.SAMPLE_SONG)); // // String songJson = Tools.MAPPER.writeValueAsString(song); // // // Add the mac_address // ObjectNode on = Tools.MAPPER.valueToTree(Tools.jsonToNode(songJson)); // on.put("uploader_ip_hash", DataSources.IP_HASH); // // String songUploadJson = Tools.nodeToJson(on); // log.info("song upload json:\n" + songUploadJson); // System.out.println(Tools.GSON2.toJson(Strings.EN.map)); // Map<String, String> map = Strings.EN.map; // // for (Entry<String, String> e : map.entrySet()) { // System.out.println(e.getKey() + " : " + e.getValue()); // } // WriteMultilingualHTMLFiles.write(); }
@Test void testThreeDimsTeam() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows = { { 1, (int) 1, (int) 2, (int) 1 }, { 2, (int) 1, (int) 2, (int) 2 }, { 3, (int) 1, (int) 1, (int) 1 }, { 4, (int) 1, (int) 1, (int) 2 }, { 5, (int) 2, (int) 2, (int) 2 } }; String[] expected = new String[] { "(1,2,1,1)", "(1,2,2,1)", "(1,1,1,1)", "(1,1,2,1)", "(2,2,2,1)", "(1,,,4)", "(2,,,1)", "(,1,,2)", "(,2,,3)", "(,,1,2)", "(,,2,3)", "(1,1,,2)", "(1,2,,2)", "(2,2,,1)", "(,1,1,1)", "(,1,2,1)", "(,2,1,1)", "(,2,2,2)", "(1,,1,2)", "(1,,2,2)", "(2,,2,1)", "(,,,5)" }; validate(rows, expected); }
public final void writeEndArray() throws IOException, JsonGenerationException { if (!this._writeContext.inArray()) _reportError("Current context not an ARRAY but " + this._writeContext.getTypeDesc()); if (this._cfgPrettyPrinter != null) this._cfgPrettyPrinter.writeEndArray(this, this._writeContext.getEntryCount()); while (true) { this._writeContext = this._writeContext.getParent(); return; if (this._outputTail >= this._outputEnd) _flushBuffer(); char[] arrayOfChar = this._outputBuffer; int i = this._outputTail; this._outputTail = (i + 1); arrayOfChar[i] = ']'; } }
public void writeString(char[] paramArrayOfChar, int paramInt1, int paramInt2) throws IOException, JsonGenerationException { _verifyValueWrite("write text value"); if (this._outputTail >= this._outputEnd) _flushBuffer(); char[] arrayOfChar1 = this._outputBuffer; int i = this._outputTail; this._outputTail = (i + 1); arrayOfChar1[i] = '"'; _writeString(paramArrayOfChar, paramInt1, paramInt2); if (this._outputTail >= this._outputEnd) _flushBuffer(); char[] arrayOfChar2 = this._outputBuffer; int j = this._outputTail; this._outputTail = (j + 1); arrayOfChar2[j] = '"'; }
StringRepresentation getClustersRepresentation() throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); ClusterSetup setupTool = new ClusterSetup(zkClient); List<String> clusters = setupTool.getClusterManagementTool().getClusters(); ZNRecord clustersRecord = new ZNRecord("Clusters Summary"); clustersRecord.setListField("clusters", clusters); StringRepresentation representation = new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(clustersRecord), MediaType.APPLICATION_JSON); return representation; }
@Test public void testSimpleRead() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { Object[][] rows = { { 1 }, { 2 }, { 3 } }; Block block = new ArrayBlock(Arrays.asList(rows), new String[] { "a" }); long count = 1; Tuple tuple; while ((tuple = block.next()) != null) { int val = (Integer) tuple.get(0); assert val == count; count++; } Assert.assertEquals(count, 4); }
public void serialize(LocalDateTime paramLocalDateTime, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider) throws IOException, JsonGenerationException { if (paramSerializerProvider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)) { paramJsonGenerator.writeStartArray(); paramJsonGenerator.writeNumber(paramLocalDateTime.year().get()); paramJsonGenerator.writeNumber(paramLocalDateTime.monthOfYear().get()); paramJsonGenerator.writeNumber(paramLocalDateTime.dayOfMonth().get()); paramJsonGenerator.writeNumber(paramLocalDateTime.hourOfDay().get()); paramJsonGenerator.writeNumber(paramLocalDateTime.minuteOfHour().get()); paramJsonGenerator.writeNumber(paramLocalDateTime.secondOfMinute().get()); paramJsonGenerator.writeNumber(paramLocalDateTime.millisOfSecond().get()); paramJsonGenerator.writeEndArray(); return; } paramJsonGenerator.writeString(printLocalDateTime(paramLocalDateTime)); }
public final void writeStartArray() throws IOException, JsonGenerationException { _verifyValueWrite("start an array"); this._writeContext = this._writeContext.createChildArrayContext(); if (this._cfgPrettyPrinter != null) { this._cfgPrettyPrinter.writeStartArray(this); return; } if (this._outputTail >= this._outputEnd) _flushBuffer(); byte[] arrayOfByte = this._outputBuffer; int i = this._outputTail; this._outputTail = (i + 1); arrayOfByte[i] = 91; }
private final void _writeUTF8Segment(byte[] paramArrayOfByte, int paramInt1, int paramInt2) throws IOException, JsonGenerationException { int[] arrayOfInt = this._outputEscapes; int i = paramInt1 + paramInt2; int k; for (int j = paramInt1; j < i; j = k) { k = j + 1; int m = paramArrayOfByte[j]; if ((m < 0) || (arrayOfInt[m] == 0)) continue; _writeUTF8Segment2(paramArrayOfByte, paramInt1, paramInt2); return; } if (paramInt2 + this._outputTail > this._outputEnd) _flushBuffer(); System.arraycopy(paramArrayOfByte, paramInt1, this._outputBuffer, this._outputTail, paramInt2); this._outputTail = (paramInt2 + this._outputTail); }
@Test public void testSerializeComment() throws IOException { final Comment aComment = new Comment(); aComment.setContent("<b>There it is</b>"); ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out, new Writer() { @Override public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException { FilterProvider fp = new SimpleFilterProvider().addFilter( JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties()); objectMapper.writer(fp).writeValue(generator, aComment); } }); assertTrue(out.toString().contains("{\"content\":\"<b>There it is</b>\"")); }
@Test void testLongType() throws JsonGenerationException, JsonMappingException, IOException, InterruptedException { // members: srinivas, maneesh, krishna, saurabh, rui // dimensions: country code, number of monitors, vegetarian Object[][] rows = { { 1, (long) 1, (long) 2, (long) 1 }, { 2, (long) 1, (long) 2, (long) 2 }, { 3, (long) 1, (long) 1, (long) 1 }, { 4, (long) 1, (long) 1, (long) 2 }, { 5, (long) 2, (long) 2, (long) 2 } }; String[] expected = new String[] { "(1,2,1,1)", "(1,2,2,1)", "(1,1,1,1)", "(1,1,2,1)", "(2,2,2,1)", "(1,,,4)", "(2,,,1)", "(,1,,2)", "(,2,,3)", "(,,1,2)", "(,,2,3)", "(1,1,,2)", "(1,2,,2)", "(2,2,,1)", "(,1,1,1)", "(,1,2,1)", "(,2,1,1)", "(,2,2,2)", "(1,,1,2)", "(1,,2,2)", "(2,,2,1)", "(,,,5)" }; validate(rows, expected); }
public final void writeEndObject() throws IOException, JsonGenerationException { if (!this._writeContext.inObject()) _reportError("Current context not an object but " + this._writeContext.getTypeDesc()); this._writeContext = this._writeContext.getParent(); if (this._cfgPrettyPrinter != null) { this._cfgPrettyPrinter.writeEndObject(this, this._writeContext.getEntryCount()); return; } if (this._outputTail >= this._outputEnd) _flushBuffer(); byte[] arrayOfByte = this._outputBuffer; int i = this._outputTail; this._outputTail = (i + 1); arrayOfByte[i] = 125; }
@Test public void testFeatureCollection() throws JsonGenerationException, JsonMappingException, IOException { FeatureCollection features = new FeatureCollection(); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("prop1", "value"); properties.put("prop2", 1234); Feature pointFeature = new Feature(new Point(12.34, 56.78, 90.00), properties); features.getFeatures().add(pointFeature); Collection<Collection<Double>> coordinates = new ArrayList<Collection<Double>>(); Collection<Double> point1 = new ArrayList<Double>(); point1.add(1.0); point1.add(2.0); point1.add(3.0); coordinates.add(point1); Collection<Double> point2 = new ArrayList<Double>(); point2.add(1.0); point2.add(2.0); point2.add(3.0); coordinates.add(point2); Feature lineFeature = new Feature(new LineString(coordinates), properties); features.getFeatures().add(lineFeature); String geojson = mapper.writeValueAsString(features); System.out.println(geojson); }
public Writer open(final PrintWriter writer) throws IOException { final JsonGenerator jg = jsonFactory.createJsonGenerator(writer); jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); jg.useDefaultPrettyPrinter(); jg.writeStartObject(); return new Writer() { @Override public void flush() throws IOException { jg.flush(); } @Override public void close() throws IOException { jg.close(); } @Override public void write(String key, String value) throws JsonGenerationException, IOException { jg.writeStringField(key, value); } @Override public int write(MBeanServer mBeanServer, ObjectName qry, String attribute, boolean description) throws IOException { return JSONBean.write(jg, mBeanServer, qry, attribute, description); } }; }
/** * @param filename * @param blocks * @return A JSON String of <code>filename</code> and counts of <code>blocks</code> * @throws JsonGenerationException * @throws JsonMappingException * @throws IOException */ public static String toJSON(final String filename, final NavigableSet<CachedBlock> blocks) throws JsonGenerationException, JsonMappingException, IOException { CachedBlockCountsPerFile counts = new CachedBlockCountsPerFile(filename); for (CachedBlock cb: blocks) { counts.count++; counts.size += cb.getSize(); BlockType bt = cb.getBlockType(); if (bt != null && bt.isData()) { counts.countData++; counts.sizeData += cb.getSize(); } } return MAPPER.writeValueAsString(counts); }