Exemplo n.º 1
1
  /**
   * Save the input kernel in a file. If the .gz extension is specified, the file is compressed.
   *
   * @param kernel The input kernel
   * @param outputFilePath The output file path
   * @throws FileNotFoundException
   * @throws IOException
   */
  public static void save(Kernel kernel, String outputFilePath)
      throws FileNotFoundException, IOException {
    ObjectMapper mapper = new ObjectMapper();

    if (outputFilePath.endsWith(".gz")) {
      GZIPOutputStream zip = new GZIPOutputStream(new FileOutputStream(new File(outputFilePath)));
      mapper.writeValue(zip, kernel);
    } else {
      mapper.writeValue(new File(outputFilePath), kernel);
    }
  }
  /** Unit test to check for regression of [JACKSON-18]. */
  public void testSmallNumbers() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode root = mapper.createArrayNode();
    for (int i = -20; i <= 20; ++i) {
      JsonNode n = root.numberNode(i);
      root.add(n);
      // Hmmh. Not sure why toString() won't be triggered otherwise...
      assertEquals(String.valueOf(i), n.toString());
    }

    // Loop over 2 different serialization methods
    for (int type = 0; type < 2; ++type) {
      StringWriter sw = new StringWriter();
      if (type == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }

      String doc = sw.toString();
      JsonParser p = new JsonFactory().createParser(new StringReader(doc));

      assertEquals(JsonToken.START_ARRAY, p.nextToken());
      for (int i = -20; i <= 20; ++i) {
        assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(i, p.getIntValue());
        assertEquals("" + i, p.getText());
      }
      assertEquals(JsonToken.END_ARRAY, p.nextToken());
      p.close();
    }
  }
  @Test
  public void testSerializeWorkspaceSnapshot() throws Exception {
    Product definingProduct = RECORDS.newProduct("zee product");
    definingProduct.setWorkspace(definingProduct.getId());
    definingProduct.insert();
    Agency pseudoScientist = RECORDS.newAgency("Behold the Pseudo Scientist!");
    pseudoScientist.setWorkspace(definingProduct.getId());
    pseudoScientist.insert();
    WorkspaceLabelRecord auth =
        RECORDS.newWorkspaceLabel("Su Su Sudio", definingProduct, pseudoScientist);
    auth.insert();

    WorkspaceSnapshot retrieved = new WorkspaceSnapshot(definingProduct, create);
    assertEquals(2, retrieved.getRecords().size());
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new CoREModule());
    File temp = File.createTempFile("snaptest", "wsp");
    temp.deleteOnExit();
    try (FileOutputStream os = new FileOutputStream(temp)) {
      mapper.writeValue(os, retrieved);
    }
    WorkspaceSnapshot deserialized;
    try (FileInputStream is = new FileInputStream(temp)) {
      deserialized = mapper.readValue(is, WorkspaceSnapshot.class);
    }
    assertEquals(2, deserialized.getRecords().size());

    assertTrue(deserialized.getRecords().stream().anyMatch(r -> pseudoScientist.equals(r)));
    assertFalse(deserialized.getRecords().stream().anyMatch(r -> definingProduct.equals(r)));
    create.configuration().connectionProvider().acquire().rollback();
    WorkspaceSnapshot.load(create, temp.toURI().toURL());
  }
  @Override
  public void writeDataPoints(Iterable<DataPoint> dataPoints) throws IOException {

    for (DataPoint dataPoint : dataPoints) {
      objectMapper.writeValue(System.out, dataPoint);
    }
  }
Exemplo n.º 5
0
 /**
  * write properties to disk
  *
  * @return success True if successfully written
  * @throws IOException
  */
 private void write() throws IOException {
   if (channel != null) {
     channel.position(0);
   }
   om.writeValue(fos, properties);
   fos.flush();
 }
  @Test(expected = JsonMappingException.class)
  public void unsupportedGeometry() throws IOException {
    Geometry unsupportedGeometry = EasyMock.createNiceMock("NonEuclideanGeometry", Geometry.class);
    EasyMock.replay(unsupportedGeometry);

    mapper.writeValue(System.out, unsupportedGeometry);
  }
Exemplo n.º 7
0
  @Transactional(value = "rest_tm")
  public void add(String clientId, EmlGroupVo groupVo) {

    groupVo.setClientId(clientId);

    // 그룹 설정 초기화
    groupVo.setServerConfig(new EmlGroupConfigVo());

    // 엔티티 생성

    EmlGroup group = new EmlGroup(groupVo);

    // 아이디 생성
    group.setId(idProvider.next());

    StringWriter writer = new StringWriter();
    try {
      objectMapper.writeValue(writer, groupVo.getServerConfig());
    } catch (IOException e) {
      e.printStackTrace();
    }

    group.setServerConfig(writer.toString());

    // 그룹 엔티티 추가
    logger.debug("그룹을 추가합니다.: " + group);
    groupDao.insert(group);

    groupVo.setId(group.getId());
  }
  void generatePropertiesFile(@NotNull Properties properties, File base, String propertiesFilename)
      throws IOException {
    FileWriter fileWriter = null;
    File gitPropsFile = new File(base, propertiesFilename);
    try {
      Files.createParentDirs(gitPropsFile);

      fileWriter = new FileWriter(gitPropsFile);
      if ("json".equalsIgnoreCase(format)) {
        log(
            "Writing json file to [",
            gitPropsFile.getAbsolutePath(),
            "] (for module ",
            project.getName() + (++counter),
            ")...");
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(fileWriter, properties);
      } else {
        log(
            "Writing properties file to [",
            gitPropsFile.getAbsolutePath(),
            "] (for module ",
            project.getName() + (++counter),
            ")...");
        properties.store(fileWriter, "Generated by Git-Commit-Id-Plugin");
      }

    } catch (IOException ex) {
      throw new RuntimeException("Cannot create custom git properties file: " + gitPropsFile, ex);
    } finally {
      Closeables.closeQuietly(fileWriter);
    }
  }
Exemplo n.º 9
0
 /**
  * Serializes the data to JSON.
  *
  * @param data The object to be serialized
  * @param writer The writer for the serialized data
  */
 public void serialize(Object data, Writer writer) {
   try {
     mapper.writeValue(writer, data);
   } catch (IOException e) {
     throw new SerializationException(e.getMessage(), e);
   }
 }
  public void testFromMap() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();
    root.put(FIELD4, TEXT2);
    root.put(FIELD3, -1);
    root.putArray(FIELD2);
    root.put(FIELD1, DOUBLE_VALUE);

    /* Let's serialize using one of two alternate methods:
     * first preferred (using generator)
     * (there are 2 variants here too)
     */
    for (int i = 0; i < 2; ++i) {
      StringWriter sw = new StringWriter();
      if (i == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }
      verifyFromMap(sw.toString());
    }

    // And then convenient but less efficient alternative:
    verifyFromMap(root.toString());
  }
  public void testFromArray() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode root = mapper.createArrayNode();
    root.add(TEXT1);
    root.add(3);
    ObjectNode obj = root.addObject();
    obj.put(FIELD1, true);
    obj.putArray(FIELD2);
    root.add(false);

    /* Ok, ready... let's serialize using one of two alternate
     * methods: first preferred (using generator)
     * (there are 2 variants here too)
     */
    for (int i = 0; i < 2; ++i) {
      StringWriter sw = new StringWriter();
      if (i == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }
      verifyFromArray(sw.toString());
    }

    // And then convenient but less efficient alternative:
    verifyFromArray(root.toString());
  }
  public static void outputDoctorSentimentReviewsToJson(
      Map<Integer, List<SentimentReview>> docToSentimentReviews, String updatedDatasetPath) {

    ObjectMapper mapper = new ObjectMapper();
    try {
      Files.deleteIfExists(Paths.get(updatedDatasetPath));
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    int count = 1;
    for (Integer docId : docToSentimentReviews.keySet()) {
      try (BufferedWriter writer =
          Files.newBufferedWriter(
              Paths.get(updatedDatasetPath),
              StandardOpenOption.CREATE,
              StandardOpenOption.APPEND)) {
        if (count > 1) writer.newLine();
        DoctorSentimentReview doctorReview =
            new DoctorSentimentReview(docId, docToSentimentReviews.get(docId));
        mapper.writeValue(writer, doctorReview);

        count++;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    System.out.println("Num of Outputed docIDs " + count);
  }
Exemplo n.º 13
0
  @Override
  public void addSegment(DataSegment segment) {
    try {
      log.info("Loading segment %s", segment.getIdentifier());

      try {
        serverManager.loadSegment(segment);
      } catch (Exception e) {
        removeSegment(segment);
        throw new SegmentLoadingException(
            e, "Exception loading segment[%s]", segment.getIdentifier());
      }

      File segmentInfoCacheFile = new File(config.getInfoDir(), segment.getIdentifier());
      if (!segmentInfoCacheFile.exists()) {
        try {
          jsonMapper.writeValue(segmentInfoCacheFile, segment);
        } catch (IOException e) {
          removeSegment(segment);
          throw new SegmentLoadingException(
              e, "Failed to write to disk segment info cache file[%s]", segmentInfoCacheFile);
        }
      }

      try {
        announcer.announceSegment(segment);
      } catch (IOException e) {
        throw new SegmentLoadingException(
            e, "Failed to announce segment[%s]", segment.getIdentifier());
      }

    } catch (SegmentLoadingException e) {
      log.makeAlert(e, "Failed to load segment for dataSource").addData("segment", segment).emit();
    }
  }
Exemplo n.º 14
0
  private void createNetworkCache() throws NdexException {

    String networkIdStr = this.getTask().getResource();

    try (NetworkDAO dao = new NetworkDAO(NdexDatabase.getInstance().getAConnection())) {
      Long taskCommitId = (Long) getTask().getAttribute(TaskAttribute.readOnlyCommitId);

      String fullpath =
          Configuration.getInstance().getNdexNetworkCachePath() + taskCommitId + ".gz";

      ODocument d = dao.getNetworkDocByUUIDString(networkIdStr);
      d.reload();
      Long actId = d.field(NdexClasses.Network_P_readOnlyCommitId);

      if (!actId.equals(taskCommitId)) {
        // stop task
        getTask()
            .setMessage(
                "Network cache not created. readOnlyCommitId="
                    + actId
                    + " in db, but in task we have commitId="
                    + taskCommitId);
        return;
      }

      // create cache.

      Network n = dao.getNetworkById(UUID.fromString(networkIdStr));

      try (GZIPOutputStream w = new GZIPOutputStream(new FileOutputStream(fullpath), 16384)) {
        //  String s = mapper.writeValueAsString( original);
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(w, n);
      } catch (FileNotFoundException e) {
        throw new NdexException("Can't create network cache file in server: " + fullpath);
      } catch (IOException e) {
        throw new NdexException(
            "IO Error when writing cache file: " + fullpath + ". Cause: " + e.getMessage());
      }

      // check again.
      d.reload();
      actId = d.field(NdexClasses.Network_P_readOnlyCommitId);
      if (!actId.equals(taskCommitId)) {
        // stop task
        getTask()
            .setMessage(
                "Network cache not created. Second check found network readOnlyCommitId is"
                    + actId
                    + ", task has commitId "
                    + taskCommitId);
        return;
      }

      d.field(NdexClasses.Network_P_cacheId, taskCommitId).save();
      logger.info("Cache " + actId + " created.");
      dao.commit();
    }
  }
Exemplo n.º 15
0
 private void sendGauge(String name, Number count, Long epoch) {
   DatadogGauge gauge = new DatadogGauge(name, count, epoch, host);
   try {
     mapper.writeValue(jsonOut, gauge);
   } catch (Exception e) {
     LOG.error("Error writing gauge", e);
   }
 }
Exemplo n.º 16
0
 public void save(ArrayList<Imagen> imagenes) {
   try {
     ObjectMapper mapper = new ObjectMapper();
     mapper.writeValue(new File("imagenes.json"), imagenes);
   } catch (IOException ex) {
     Logger.getLogger(ImagenesDAO.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
Exemplo n.º 17
0
 private void pushCounter(String name, Long count, Long epoch) {
   DatadogCounter counter = new DatadogCounter(name, count, epoch, host);
   try {
     mapper.writeValue(jsonOut, counter);
   } catch (Exception e) {
     LOG.error("Error writing counter", e);
   }
 }
Exemplo n.º 18
0
 public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint)
     throws JsonMappingException, JsonGenerationException, IOException {
   JsonGenerator jg = jf.createGenerator(fw);
   if (prettyPrint) {
     jg.useDefaultPrettyPrinter();
   }
   m.writeValue(jg, pojo);
 }
 /**
  * Store project's configuration.
  *
  * @throws IOException if cannot store configuration.
  */
 public void store() throws IOException {
   prjCfgFile.getParentFile().mkdirs();
   if (prjCfgFile.exists() && !prjCfgFile.delete()) {
     throw new IOException("Cannot write project's jacocoverage config to: " + prjCfgFile);
   } else {
     mapper.writeValue(prjCfgFile, pref);
   }
 }
Exemplo n.º 20
0
 public static String writeObjectAsString(final Object object) {
   final ByteArrayOutputStream out = new ByteArrayOutputStream(512);
   try {
     mapper.writeValue(out, object);
   } catch (IOException ioe) {
     throw Exceptions.toUndeclared(ioe);
   }
   return new String(out.toByteArray(), Charsets.UTF_8);
 }
 @Test
 public void polygonWithoutHolesSerializerTest() throws Exception {
   Geometry polygon = reader.read("POLYGON ((35 10, 10 20, 15 40," + " 45 45, 35 10))");
   polygon.setSRID(4326);
   String polygonGeoJsonString = mapper.writeValueAsString(polygon);
   logger.info(":::::::::::::::::::::::GEO_JSON_POLYGON : \n{}\n", polygonGeoJsonString);
   org.geojson.Polygon p = mapper.readValue(polygonGeoJsonString, org.geojson.Polygon.class);
   mapper.writeValue(new File("./target/PolygonWithoutHoles.json"), p);
 }
 @Test
 public void pointSerializerTest() throws Exception {
   Coordinate ptc = new Coordinate(10, 20);
   Point point = geometryFactory.createPoint(ptc);
   point.setSRID(4326);
   String geoJsonPoint = mapper.writeValueAsString(point);
   logger.info(":::::::::::::::::::::::GEO_JSON_POINT : \n{}\n", geoJsonPoint);
   org.geojson.Point p = mapper.readValue(geoJsonPoint, org.geojson.Point.class);
   mapper.writeValue(new File("./target/Point.json"), p);
 }
Exemplo n.º 23
0
 protected String toJSON(Object answer) throws IOException {
   try {
     StringWriter writer = new StringWriter();
     mapper.writeValue(writer, answer);
     return writer.toString();
   } catch (IOException e) {
     LOG.warn("Failed to marshal the events: " + e, e);
     throw new IOException(e.getMessage());
   }
 }
 @Test
 public void testWriteToFile() throws IOException {
   RoadData data = new RoadData();
   data.add(new RoadEntry("1", Arrays.asList(new Point(42.4, 11.1)), 2, "speed", "replace"));
   StringWriter sWriter = new StringWriter();
   mapper.writeValue(sWriter, data);
   assertEquals(
       "[{\"points\":[[11.1,42.4]],\"value\":2.0,\"value_type\":\"speed\",\"mode\":\"replace\",\"id\":\"1\"}]",
       sWriter.toString());
 }
 @Test
 public void multiPointSerializerTest() throws Exception {
   Geometry multiPoint = reader.read("MULTIPOINT ((10 40), (40 30), " + "(20 20), (30 10))");
   multiPoint.setSRID(4326);
   String multiPointGeoJsonString = mapper.writeValueAsString(multiPoint);
   logger.info(":::::::::::::::::::::::GEO_JSON_MULTI_POINT : \n{}\n", multiPointGeoJsonString);
   org.geojson.MultiPoint multiPointGeoJson =
       mapper.readValue(multiPointGeoJsonString, org.geojson.MultiPoint.class);
   mapper.writeValue(new File("./target/MultiPoint.json"), multiPointGeoJson);
 }
Exemplo n.º 26
0
 public static String toJson(Object pojo, boolean prettyPrint)
     throws JsonMappingException, JsonGenerationException, IOException {
   StringWriter sw = new StringWriter();
   JsonGenerator jg = jf.createGenerator(sw);
   if (prettyPrint) {
     jg.useDefaultPrettyPrinter();
   }
   m.writeValue(jg, pojo);
   return sw.toString();
 }
Exemplo n.º 27
0
 public static String toJSON(Object object) {
   ObjectMapper mapper = new ObjectMapper();
   StringWriter writer = new StringWriter();
   try {
     mapper.writeValue(writer, object);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   return writer.toString();
 }
 @Test
 public void createComplexGeometryCollectionTest() throws Exception {
   Coordinate ptc = new Coordinate(10, 20);
   Point point = geometryFactory.createPoint(ptc);
   point.setSRID(4326);
   Coordinate[] lsc = new Coordinate[8];
   lsc[0] = new Coordinate(5.0d, 5.0d);
   lsc[1] = new Coordinate(6.0d, 5.0d);
   lsc[2] = new Coordinate(6.0d, 6.0d);
   lsc[3] = new Coordinate(7.0d, 6.0d);
   lsc[4] = new Coordinate(7.0d, 7.0d);
   lsc[5] = new Coordinate(8.0d, 7.0d);
   lsc[6] = new Coordinate(8.0d, 8.0d);
   lsc[7] = new Coordinate(9.0d, 9.0d);
   LineString lineString = geometryFactory.createLineString(lsc);
   lineString.setSRID(4326);
   Coordinate[] lrc = new Coordinate[10];
   lrc[0] = new Coordinate(7, 7);
   lrc[1] = new Coordinate(6, 9);
   lrc[2] = new Coordinate(6, 11);
   lrc[3] = new Coordinate(7, 12);
   lrc[4] = new Coordinate(9, 11);
   lrc[5] = new Coordinate(11, 12);
   lrc[6] = new Coordinate(13, 11);
   lrc[7] = new Coordinate(13, 9);
   lrc[8] = new Coordinate(11, 7);
   lrc[9] = new Coordinate(7, 7);
   LinearRing linearRing = geometryFactory.createLinearRing(lrc);
   linearRing.setSRID(4326);
   Geometry polygon =
       reader.read(
           "POLYGON ((35 10, 10 20, 15 40," + " 45 45, 35 10), (20 30, 35 35, 30 20, 20 30))");
   polygon.setSRID(4326);
   Geometry multiPoint = reader.read("MULTIPOINT ((10 40), (40 30), " + "(20 20), (30 10))");
   multiPoint.setSRID(4326);
   Geometry multiPolygon =
       reader.read(
           "MULTIPOLYGON (((40 40, 20 45,"
               + " 45 30, 40 40)), ((20 35, 45 20, 30 5, "
               + "10 10, 10 30, 20 35), (30 20, 20 25, 20 15, 30 20)))");
   multiPolygon.setSRID(4326);
   GeometryCollection geometryCollection =
       new GeometryCollection(
           new Geometry[] {point, linearRing, lineString, polygon, multiPoint, multiPolygon},
           geometryFactory);
   String geometryCollectionGeoJsonString = mapper.writeValueAsString(geometryCollection);
   logger.info(
       ":::::::::::::::::::::::GEO_JSON_GEOMETRY_COLLECTION : \n{}\n",
       geometryCollectionGeoJsonString);
   org.geojson.GeometryCollection p =
       mapper.readValue(geometryCollectionGeoJsonString, org.geojson.GeometryCollection.class);
   mapper.writeValue(new File("./target/GeometryCollectionComplex.json"), p);
 }
 @Override
 public void writeTo(
     GameResponse gameResponse,
     Class<?> aClass,
     Type type,
     Annotation[] annotations,
     MediaType mediaType,
     MultivaluedMap<String, Object> multivaluedMap,
     OutputStream outputStream)
     throws IOException, WebApplicationException {
   MAPPER.writeValue(outputStream, gameResponse);
 }
  @Test
  public void verifySerializeAnHttpBasedServiceCredentialToJson() throws IOException {
    final HttpBasedServiceCredential credentialMetaDataWritten =
        new HttpBasedServiceCredential(
            new URL("http://www.cnn.com"),
            RegisteredServiceTestUtils.getRegisteredService("https://some.app.edu"));

    MAPPER.writeValue(JSON_FILE, credentialMetaDataWritten);
    final CredentialMetaData credentialMetaDataRead =
        MAPPER.readValue(JSON_FILE, HttpBasedServiceCredential.class);
    assertEquals(credentialMetaDataWritten, credentialMetaDataRead);
  }