public void loadData() {
    SimpleDateFormat formatIn = new SimpleDateFormat("MMMM d, yyyy");
    SimpleDateFormat formatOut = new SimpleDateFormat("MM/d/yy");
    ObjectMapper objectMapper = new ObjectMapper();
    JsonFactory jsonFactory = new JsonFactory();
    Random random = new Random();
    try {
      JsonParser jsonParserBlog =
          jsonFactory.createParser(getResources().openRawResource(R.raw.blog));
      List<Blog> entries =
          objectMapper.readValue(jsonParserBlog, new TypeReference<List<Blog>>() {});
      JsonParser jsonParserEmoji =
          jsonFactory.createParser(getResources().openRawResource(R.raw.emoji));
      List<String> emojies =
          objectMapper.readValue(jsonParserEmoji, new TypeReference<List<String>>() {});

      int numEmoji = emojies.size();
      for (Blog blog : entries) {
        blog.setEmoji(emojies.get(random.nextInt(numEmoji)));
        try {
          blog.setDate(formatOut.format(formatIn.parse(blog.getDate())));
        } catch (ParseException e) {
          e.printStackTrace();
        }
      }
      Realm realm = Realm.getInstance(this);
      realm.beginTransaction();
      realm.copyToRealm(entries);
      realm.commitTransaction();
      realm.close();

    } catch (Exception e) {
      throw new IllegalStateException("Could not load blog data.");
    }
  }
Пример #2
0
  @Override
  public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
      throws HibernateException, SQLException {
    try {
      String value = rs.getString(names[0]);
      if (value == null) {
        return null;
      }

      Object object = null;
      if (isArray) {
        ObjectMapper objectMapper = ObjectMapperBeanFactory.getObjectMapper();

        JavaType type =
            objectMapper.getTypeFactory().constructCollectionType(List.class, targetClass);
        object = objectMapper.readValue(value, type);
      } else {
        ObjectMapper objectMapper = ObjectMapperBeanFactory.getObjectMapper();
        object = objectMapper.readValue(value, targetClass);
      }

      return object;
    } catch (IOException e) {
      throw new HibernateException(e);
    }
  }
Пример #3
0
  // 初始化list数据函数
  public void InitListDataForHistory(String url, JSONObject json, AjaxStatus status) {
    if (status.getCode() == AjaxStatus.NETWORK_ERROR
        && app.GetServiceData("user_Histories") == null) {
      aq.id(R.id.ProgressText).gone();
      app.MyToast(aq.getContext(), getResources().getString(R.string.networknotwork));
      return;
    }
    ObjectMapper mapper = new ObjectMapper();
    try {
      if (isLastisNext == 1) {
        m_ReturnUserPlayHistories =
            mapper.readValue(json.toString(), ReturnUserPlayHistories.class);
        app.SaveServiceData("user_Histories", json.toString());
      } else if (isLastisNext > 1) {
        m_ReturnUserPlayHistories = null;
        m_ReturnUserPlayHistories =
            mapper.readValue(json.toString(), ReturnUserPlayHistories.class);
      }
      // 创建数据源对象
      GetVideoMovies();

    } catch (JsonParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JsonMappingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  private FileMetaData getFileContentInfo(File file) {
    try {
      MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
      queryParams.add("redirect", "meta");
      ClientResponse resp =
          getRootApiWebResource()
              .path("files")
              .path(String.valueOf(file.getId()))
              .path("content")
              .queryParams(queryParams)
              .accept(MediaType.APPLICATION_OCTET_STREAM)
              .accept(MediaType.TEXT_HTML)
              .accept(MediaType.APPLICATION_XHTML_XML)
              .get(ClientResponse.class);

      String sResp = resp.getEntity(String.class);
      FileMetaData fileInfo =
          mapper.readValue(
              mapper.readValue(sResp, JsonNode.class).findPath(RESPONSE).toString(),
              FileMetaData.class);
      logger.info(fileInfo.toString());
      return fileInfo;
    } catch (BaseSpaceException bs) {
      throw bs;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
 @Override
 public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
     throws IOException, HttpMessageNotReadableException {
   try {
     TumblrResponse tumblrResponse =
         objectMapper.readValue(inputMessage.getBody(), TumblrResponse.class);
     checkResponse(tumblrResponse);
     Object result;
     if (TumblrResponse.class.equals(type)) {
       // don't parse the response json, callee is going to process is manually
       result = tumblrResponse;
     } else {
       // parse the response json into an instance of the given class
       JavaType javaType = getJavaType(type, contextClass);
       String response = tumblrResponse.getResponseJson();
       result = objectMapper.readValue(response, javaType);
     }
     return result;
   } catch (JsonParseException ex) {
     throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
   } catch (EOFException ex) {
     throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
   } catch (Exception e) {
     e.printStackTrace();
     throw new IOException(e);
   }
 }
  @Override
  public Object resolveArgument(MethodParameter param, NativeWebRequest request) throws Exception {

    if (request.getNativeRequest() instanceof ClientDataRequest
        && param.hasParameterAnnotation(PortletRequestBody.class)) {
      String value = param.getParameterAnnotation(PortletRequestBody.class).value();
      ClientDataRequest clientDataRequest = request.getNativeRequest(ClientDataRequest.class);
      if (!PortletRequestBody.DEFAULT.equals(value)) {
        if (isMethod(clientDataRequest, RequestMethod.POST)) {
          String json =
              JSON_MAPPER.readTree(getRequestBody(clientDataRequest)).get(value).toString();
          return JSON_MAPPER.readValue(json, param.getParameterType());
        } else if (isMethod(clientDataRequest, RequestMethod.GET)) {
          return JSON_MAPPER.readValue(request.getParameter(value), param.getParameterType());
        }
        throw new RuntimeException(
            MessageFormat.format(
                "REST Method {0} for values not supported.", clientDataRequest.getMethod()));
      }
      if (isMethod(clientDataRequest, RequestMethod.POST)) {
        return JSON_MAPPER.readValue(clientDataRequest.getReader(), param.getParameterType());
      }
      throw new RuntimeException(
          MessageFormat.format(
              "REST Method {0} for body not supported.", clientDataRequest.getMethod()));
    }
    return WebArgumentResolver.UNRESOLVED;
  }
Пример #7
0
  // Update and return given train line with the Jackson parser
  // AG
  public static <T> TrainLine updateLine(T address, TrainLine line) {
    try {
      Object trainData = new Object();
      if (address instanceof URL) {
        // Get train data from web
        trainData = mapper.readValue((URL) address, Object.class);
      } else if (address instanceof File) {
        // Get train data locally
        trainData = mapper.readValue((File) address, Object.class);
      }
      // System.out.println(trainData.toString());
      // Go inside the wrapper
      Object tripListObj = getFromMap(trainData, TRIP_LIST_KEY);

      line = new TrainLine(tripListObj);
    } catch (JsonParseException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return line;
  }
  @Before
  public void prepareTest() throws Exception {

    syncConfiguration =
        MAPPER.readValue(
            MongoElasticsearchSyncIT.class.getResourceAsStream("/testSync.json"),
            MongoElasticsearchSyncConfiguration.class);

    syncConfiguration.getDestination().setClusterName(cluster().getClusterName());

    MongoPersistWriter setupWriter = new MongoPersistWriter(syncConfiguration.getSource());

    setupWriter.prepare(null);

    InputStream testActivityFolderStream =
        MongoElasticsearchSyncIT.class.getClassLoader().getResourceAsStream("activities");
    List<String> files = IOUtils.readLines(testActivityFolderStream, Charsets.UTF_8);

    for (String file : files) {
      LOGGER.info("File: " + file);
      InputStream testActivityFileStream =
          MongoElasticsearchSyncIT.class.getClassLoader().getResourceAsStream("activities/" + file);
      Activity activity = MAPPER.readValue(testActivityFileStream, Activity.class);
      activity.getAdditionalProperties().remove("$license");
      StreamsDatum datum = new StreamsDatum(activity, activity.getVerb());
      setupWriter.write(datum);
      LOGGER.info("Wrote: " + activity.getVerb());
      srcCount++;
    }

    setupWriter.cleanUp();
  }
Пример #9
0
  @Test
  public void getInitTasks() throws Exception {
    String jsonTasks =
        given().filter(sessionFilter).get("/web/2016/4/25").then().extract().asString();
    Task[][] returned = om.readValue(jsonTasks, Task[][].class);
    assertThat(returned[4][0], equalTo(PermanentUserData.tasks.get(1)));
    assertThat(returned[0][0], equalTo(PermanentUserData.tasks.get(2)));
    assertThat(returned[2][0], equalTo(PermanentUserData.tasks.get(3)));
    Task[] futureTasks = {
      PermanentUserData.tasks.get(4), PermanentUserData.tasks.get(5), PermanentUserData.tasks.get(6)
    };
    assertThat(Arrays.asList(returned[1]), containsInAnyOrder(futureTasks));
    assertThat(returned[1].length, equalTo(futureTasks.length));

    jsonTasks =
        given()
            .header(PermanentUserData.tokenHeader)
            .get("/m/2016/5/2")
            .then()
            .extract()
            .asString();
    returned = om.readValue(jsonTasks, Task[][].class);
    assertThat(returned[0][0], equalTo(PermanentUserData.tasks.get(2)));
    assertThat(returned[3][0], equalTo(PermanentUserData.tasks.get(3)));
    assertThat(returned[2][0], equalTo(PermanentUserData.tasks.get(4)));
    Task[] futureTasks2 = {PermanentUserData.tasks.get(5), PermanentUserData.tasks.get(6)};
    assertThat(returned[1].length, equalTo(futureTasks2.length));
    assertThat(Arrays.asList(returned[1]), containsInAnyOrder(futureTasks2));
  }
  @Test
  public void vote() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Restaurant restaurantB =
        mapper.readValue(new StringReader(testRestaurantJson1), Restaurant.class);
    restaurantRepository.saveAndFlush(restaurantB);
    Restaurant restaurantA =
        mapper.readValue(new StringReader(testRestaurantJson2), Restaurant.class);
    restaurantRepository.saveAndFlush(restaurantA);

    doVote(restaurantB.getRestaurantName(), "qqq");
    doVote(restaurantB.getRestaurantName(), "www");
    doVote(restaurantB.getRestaurantName(), "ddd");

    doVote(restaurantA.getRestaurantName(), "kkk");
    doVote(restaurantA.getRestaurantName(), "lll");

    List<Vote> votes = votesRepository.findAll();
    // check all votes are here
    assertEquals(MAX_TOTAL_VOTES, votes.size());
    Map<Long, Long> res =
        votes.stream().collect(Collectors.groupingBy(Vote::getRestaurantId, Collectors.counting()));
    // check all votes counter correctly
    assertEquals(3l, res.get(restaurantB.getId()).longValue());
    assertEquals(2l, res.get(restaurantA.getId()).longValue());
  }
Пример #11
0
  public String createMessage(HttpClientErrorException ex) {
    String result = "";
    try {
      String responseBody = ex.getResponseBodyAsString();

      if (!TextUtils.isEmpty(responseBody)) {
        result = ex.getMessage() + ": " + responseBody;

        ErrorBody errorBody = mapper.readValue(ex.getResponseBodyAsByteArray(), ErrorBody.class);
        if (errorBody.fault != null) {
          result = ex.getMessage() + " " + errorBody.fault.reason + " " + errorBody.fault.detail;
        } else {
          ErrorBody.Fault fault =
              mapper.readValue(ex.getResponseBodyAsByteArray(), ErrorBody.Fault.class);
          if (fault != null) {
            result = ex.getMessage() + " " + fault.reason + " " + fault.detail;
          }
        }
      }
    } catch (Exception f) {
      result = f.getMessage();
    }

    if (TextUtils.isEmpty(result)) {
      result = ex.getMessage();
    }

    return result;
  }
Пример #12
0
 @Override
 public GraphRowModel next() {
   String json = response.next();
   if (json != null) {
     try {
       GraphRowModel graphRowModel = new GraphRowModel();
       JSONObject jsonObject = getOuterObject(json);
       JSONArray dataObject =
           jsonObject.getJSONArray("results").getJSONObject(0).getJSONArray("data");
       for (int i = 0; i < dataObject.length(); i++) {
         String graphJson = dataObject.getJSONObject(i).getString("graph");
         String rowJson = dataObject.getJSONObject(i).getString("row");
         GraphModel graphModel = objectMapper.readValue(graphJson, GraphModel.class);
         Object[] rows = objectMapper.readValue(rowJson, Object[].class);
         graphRowModel.addGraphRowResult(graphModel, rows);
       }
       return graphRowModel;
     } catch (Exception e) {
       LOGGER.error("failed to parse: {}", json);
       throw new RuntimeException(e);
     }
   } else {
     return null;
   }
 }
 /**
  * Load project's configuration.
  *
  * @throws IOException if cannot load configuration.
  */
 @SuppressWarnings("unchecked")
 public void load() throws IOException {
   getInternalPref().clear();
   getPkgclssExclude().clear();
   prjCfgFile.getParentFile().mkdirs();
   if (prjCfgFile.exists()) {
     try {
       getInternalPref()
           .putAll(
               (Map<Object, Object>) mapper.readValue(prjCfgFile, Map.class).get(JSON_GENERAL));
       getPkgclssExclude()
           .addAll(
               (Collection<? extends String>)
                   mapper.readValue(prjCfgFile, Map.class).get(JSON_PKGFILTER));
     } catch (IOException ex) {
       LOGGER.log(
           Level.INFO,
           "Project's JaCoCoverage configuration file format is outdated or invalid. Reset cause:",
           ex);
       String msg =
           "The project's JaCoCoverage configuration file format is outdated or invalid.\n"
               + "The configuration file has been reset to support new format.";
       DialogDisplayer.getDefault()
           .notify(new NotifyDescriptor.Message(msg, NotifyDescriptor.WARNING_MESSAGE));
     }
   }
 }
Пример #14
0
  @Test
  public void testKillTaskSerde() throws Exception {
    final KillTask task = new KillTask(null, "foo", new Interval("2010-01-01/P1D"), null);

    final String json = jsonMapper.writeValueAsString(task);

    Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change
    final KillTask task2 = (KillTask) jsonMapper.readValue(json, Task.class);

    Assert.assertEquals("foo", task.getDataSource());
    Assert.assertEquals(new Interval("2010-01-01/P1D"), task.getInterval());

    Assert.assertEquals(task.getId(), task2.getId());
    Assert.assertEquals(task.getGroupId(), task2.getGroupId());
    Assert.assertEquals(task.getDataSource(), task2.getDataSource());
    Assert.assertEquals(task.getInterval(), task2.getInterval());

    final KillTask task3 =
        (KillTask)
            jsonMapper.readValue(
                jsonMapper.writeValueAsString(
                    new ClientKillQuery("foo", new Interval("2010-01-01/P1D"))),
                Task.class);

    Assert.assertEquals("foo", task3.getDataSource());
    Assert.assertEquals(new Interval("2010-01-01/P1D"), task3.getInterval());
  }
 private <T> T jsonReadWriteRead(String s, Class<T> klass) {
   try {
     return jsonMapper.readValue(
         jsonMapper.writeValueAsBytes(jsonMapper.readValue(s, klass)), klass);
   } catch (Exception e) {
     throw Throwables.propagate(e);
   }
 }
  private <T> T deserializeResponse(final Response response, final Class<T> clazz)
      throws KillBillClientException {
    final T result;
    try {
      if (DEBUG) {
        final String content = response.getResponseBody();
        log.debug("Received: " + content);
        result = mapper.readValue(content, clazz);
      } else {
        InputStream in = null;
        try {
          in = response.getResponseBodyAsStream();
          result = mapper.readValue(in, clazz);
        } finally {
          if (in != null) {
            try {
              in.close();
            } catch (IOException e) {
              log.warn(
                  "Failed to close http-client - provided InputStream: {}",
                  e.getLocalizedMessage());
            }
          }
        }
      }
    } catch (final IOException e) {
      throw new KillBillClientException(e, response);
    }

    if (KillBillObjects.class.isAssignableFrom(clazz)) {
      final KillBillObjects objects = ((KillBillObjects) result);
      final String paginationCurrentOffset =
          response.getHeader(JaxrsResource.HDR_PAGINATION_CURRENT_OFFSET);
      if (paginationCurrentOffset != null) {
        objects.setPaginationCurrentOffset(Integer.parseInt(paginationCurrentOffset));
      }
      final String paginationNextOffset =
          response.getHeader(JaxrsResource.HDR_PAGINATION_NEXT_OFFSET);
      if (paginationNextOffset != null) {
        objects.setPaginationNextOffset(Integer.parseInt(paginationNextOffset));
      }
      final String paginationTotalNbRecords =
          response.getHeader(JaxrsResource.HDR_PAGINATION_TOTAL_NB_RECORDS);
      if (paginationTotalNbRecords != null) {
        objects.setPaginationTotalNbRecords(Integer.parseInt(paginationTotalNbRecords));
      }
      final String paginationMaxNbRecords =
          response.getHeader(JaxrsResource.HDR_PAGINATION_MAX_NB_RECORDS);
      if (paginationMaxNbRecords != null) {
        objects.setPaginationMaxNbRecords(Integer.parseInt(paginationMaxNbRecords));
      }
      objects.setPaginationNextPageUri(
          response.getHeader(JaxrsResource.HDR_PAGINATION_NEXT_PAGE_URI));
      objects.setKillBillHttpClient(this);
    }

    return result;
  }
Пример #17
0
  public void initRoutes() {
    get("api/devices", (request, response) -> deviceService.getAllDevices(), toJson());

    post(
        "api/devices",
        (req, res) -> {
          DeviceRequest createDeviceRequest = mapper.readValue(req.body(), DeviceRequest.class);
          deviceService.createDevice(createDeviceRequest);
          return "created";
        });

    get(
        "api/devices/:deviceId",
        (req, res) -> deviceService.getDevice(req.params("deviceId")),
        toJson());

    put(
        "api/devices/:deviceId",
        (req, res) -> {
          String deviceId = req.params("deviceId");
          if (deviceId != null && !deviceId.trim().isEmpty()) {
            DeviceRequest createDeviceRequest = mapper.readValue(req.body(), DeviceRequest.class);
            deviceService.changeDevice(deviceId, createDeviceRequest);
            return "modified";
          } else throw new RuntimeException("Incorrect request, missing device id");
        });

    delete(
        "api/devices/:deviceId",
        (req, res) -> {
          String deviceId = req.params("deviceId");
          if (deviceId != null && !deviceId.trim().isEmpty()) {
            deviceService.shutdownDevice(deviceId);
            return "Delete device " + deviceId;
          } else throw new RuntimeException("Incorrect request, missing device id");
        },
        toJson());

    post(
        "api/devices/:deviceId/tasks",
        (req, res) -> {
          String deviceId = req.params("deviceId");
          String requestBody = req.body();

          DeviceTask task = DeviceTaskParser.parseTask(mapper, mapper.readTree(requestBody));
          return deviceService.executeTask(deviceId, task);
        },
        toJson());

    get(
        "api/devices/:deviceId/tasks",
        (req, res) -> {
          String deviceId = req.params("deviceId");
          return deviceService.getCurrentTasks(deviceId);
        },
        toJson());
  }
  // [JACKSON-484]
  public void testInetAddress() throws IOException {
    InetAddress address = MAPPER.readValue(quote("127.0.0.1"), InetAddress.class);
    assertEquals("127.0.0.1", address.getHostAddress());

    // should we try resolving host names? That requires connectivity...
    final String HOST = "google.com";
    address = MAPPER.readValue(quote(HOST), InetAddress.class);
    assertEquals(HOST, address.getHostName());
  }
Пример #19
0
  @Test
  public void testV1Serialization() throws Exception {

    final Interval interval = new Interval("2011-10-01/2011-10-02");
    final ImmutableMap<String, Object> loadSpec =
        ImmutableMap.<String, Object>of("something", "or_other");

    DataSegment segment =
        new DataSegment(
            "something",
            interval,
            "1",
            loadSpec,
            Arrays.asList("dim1", "dim2"),
            Arrays.asList("met1", "met2"),
            NoneShardSpec.instance(),
            IndexIO.CURRENT_VERSION_ID,
            1);

    final Map<String, Object> objectMap =
        mapper.readValue(
            mapper.writeValueAsString(segment), new TypeReference<Map<String, Object>>() {});

    Assert.assertEquals(10, objectMap.size());
    Assert.assertEquals("something", objectMap.get("dataSource"));
    Assert.assertEquals(interval.toString(), objectMap.get("interval"));
    Assert.assertEquals("1", objectMap.get("version"));
    Assert.assertEquals(loadSpec, objectMap.get("loadSpec"));
    Assert.assertEquals("dim1,dim2", objectMap.get("dimensions"));
    Assert.assertEquals("met1,met2", objectMap.get("metrics"));
    Assert.assertEquals(ImmutableMap.of("type", "none"), objectMap.get("shardSpec"));
    Assert.assertEquals(IndexIO.CURRENT_VERSION_ID, objectMap.get("binaryVersion"));
    Assert.assertEquals(1, objectMap.get("size"));

    DataSegment deserializedSegment =
        mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class);

    Assert.assertEquals(segment.getDataSource(), deserializedSegment.getDataSource());
    Assert.assertEquals(segment.getInterval(), deserializedSegment.getInterval());
    Assert.assertEquals(segment.getVersion(), deserializedSegment.getVersion());
    Assert.assertEquals(segment.getLoadSpec(), deserializedSegment.getLoadSpec());
    Assert.assertEquals(segment.getDimensions(), deserializedSegment.getDimensions());
    Assert.assertEquals(segment.getMetrics(), deserializedSegment.getMetrics());
    Assert.assertEquals(segment.getShardSpec(), deserializedSegment.getShardSpec());
    Assert.assertEquals(segment.getSize(), deserializedSegment.getSize());
    Assert.assertEquals(segment.getIdentifier(), deserializedSegment.getIdentifier());

    deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class);
    Assert.assertEquals(0, segment.compareTo(deserializedSegment));

    deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class);
    Assert.assertEquals(0, deserializedSegment.compareTo(segment));

    deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class);
    Assert.assertEquals(segment.hashCode(), deserializedSegment.hashCode());
  }
Пример #20
0
  /**
   * Load a kernel function from a file path. If the .gz extension is specified, the file considered
   * compressed.
   *
   * @param kernel The input kernel
   * @param outputFilePath The output file path
   * @throws FileNotFoundException
   * @throws IOException
   */
  public static Kernel load(String inputFilePath) throws FileNotFoundException, IOException {
    ObjectMapper mapper = new ObjectMapper();

    if (inputFilePath.endsWith(".gz")) {
      GZIPInputStream zip = new GZIPInputStream(new FileInputStream(new File(inputFilePath)));
      return mapper.readValue(zip, Kernel.class);
    } else {
      return mapper.readValue(new File(inputFilePath), Kernel.class);
    }
  }
  // for [JACKSON-652]
  // @since 1.9
  public void testUntypedWithJsonArrays() throws Exception {
    // by default we get:
    Object ob = MAPPER.readValue("[1]", Object.class);
    assertTrue(ob instanceof List<?>);

    // but can change to produce Object[]:
    MAPPER.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
    ob = MAPPER.readValue("[1]", Object.class);
    assertEquals(Object[].class, ob.getClass());
  }
Пример #22
0
  public static JsonHeader deserializeJsonHeader(final String ratJson)
      throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    RATJsonObject ratJsonObject = (RATJsonObject) mapper.readValue(ratJson, RATJsonObject.class);

    TypeFactory typeFactory = mapper.getTypeFactory();
    MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, String.class);
    HashMap<String, String> map = mapper.readValue(ratJsonObject.getHeader(), mapType);
    JsonHeader header = new JsonHeader();
    header.setHeaderProperties(map);

    return header;
  }
  @Test
  public void testSerde() throws IOException {
    ObjectMapper jsonMapper = new DefaultObjectMapper();
    SearchSortSpec spec = new SearchSortSpec(StringComparators.ALPHANUMERIC);

    String expectJsonSpec = "{\"type\":{\"type\":\"alphanumeric\"}}";
    String jsonSpec = jsonMapper.writeValueAsString(spec);
    Assert.assertEquals(expectJsonSpec, jsonSpec);
    Assert.assertEquals(spec, jsonMapper.readValue(jsonSpec, SearchSortSpec.class));

    String expectJsonSpec2 = "{\"type\":\"alphanumeric\"}";
    Assert.assertEquals(spec, jsonMapper.readValue(expectJsonSpec2, SearchSortSpec.class));
  }
  @Test
  public void testSerde() throws Exception {
    final ObjectMapper objectMapper = new DefaultObjectMapper();
    final String json = "{ \"type\" : \"partial\", \"expr\" : \".(...)?\" }";
    MatchingDimExtractionFn extractionFn =
        (MatchingDimExtractionFn) objectMapper.readValue(json, ExtractionFn.class);

    Assert.assertEquals(".(...)?", extractionFn.getExpr());

    // round trip
    Assert.assertEquals(
        extractionFn,
        objectMapper.readValue(objectMapper.writeValueAsBytes(extractionFn), ExtractionFn.class));
  }
Пример #25
0
  /**
   * Performs roundtrip test for the specified class.
   *
   * @param <TClass> Item class
   * @param item Item to be checked
   * @param asclass Class to be used during conversions
   * @return Deserialized object after the roundtrip
   * @throws IOException JSON Conversion error
   * @throws AssertionError Validation error
   */
  public static <TClass> TClass testRoundTrip(TClass item, Class<TClass> asclass)
      throws IOException, AssertionError {
    ObjectMapper mapper = new ObjectMapper();

    String serialized1 = mapper.writeValueAsString(item);
    JsonNode json1 = mapper.readTree(serialized1);
    TClass deserialized1 = mapper.readValue(serialized1, asclass);
    String serialized2 = mapper.writeValueAsString(deserialized1);
    JsonNode json2 = mapper.readTree(serialized2);
    TClass deserialized2 = mapper.readValue(serialized2, asclass);

    assertEquals(json2, json1, "JSONs must be equal after the second roundtrip");
    return deserialized2;
  }
  // [JACKSON-597]
  public void testClass() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    assertSame(String.class, mapper.readValue(quote("java.lang.String"), Class.class));

    // then primitive types
    assertSame(Boolean.TYPE, mapper.readValue(quote("boolean"), Class.class));
    assertSame(Byte.TYPE, mapper.readValue(quote("byte"), Class.class));
    assertSame(Short.TYPE, mapper.readValue(quote("short"), Class.class));
    assertSame(Character.TYPE, mapper.readValue(quote("char"), Class.class));
    assertSame(Integer.TYPE, mapper.readValue(quote("int"), Class.class));
    assertSame(Long.TYPE, mapper.readValue(quote("long"), Class.class));
    assertSame(Float.TYPE, mapper.readValue(quote("float"), Class.class));
    assertSame(Double.TYPE, mapper.readValue(quote("double"), Class.class));
    assertSame(Void.TYPE, mapper.readValue(quote("void"), Class.class));
  }
  public void testDateMidnightDeser() throws IOException {
    // couple of acceptable formats, so:
    DateMidnight date = MAPPER.readValue("[2001,5,25]", DateMidnight.class);
    assertEquals(2001, date.getYear());
    assertEquals(5, date.getMonthOfYear());
    assertEquals(25, date.getDayOfMonth());

    DateMidnight date2 = MAPPER.readValue(quote("2005-07-13"), DateMidnight.class);
    assertEquals(2005, date2.getYear());
    assertEquals(7, date2.getMonthOfYear());
    assertEquals(13, date2.getDayOfMonth());

    // since 1.6.1, for [JACKSON-360]
    assertNull(MAPPER.readValue(quote(""), DateMidnight.class));
  }
Пример #28
0
  @SuppressWarnings("unchecked")
  @Override
  public final <T> List<T> decodeList(final String entitiesAsString, final Class<T> clazz) {
    Preconditions.checkNotNull(entitiesAsString);

    List<T> entities = null;
    try {
      if (clazz.equals(Role.class)) {
        entities =
            objectMapper.readValue(
                entitiesAsString,
                new TypeReference<List<Role>>() {
                  // ...
                });
      } else if (clazz.equals(Privilege.class)) {
        entities =
            objectMapper.readValue(
                entitiesAsString,
                new TypeReference<List<Privilege>>() {
                  // ...
                });
      } else if (clazz.equals(User.class)) {
        entities =
            objectMapper.readValue(
                entitiesAsString,
                new TypeReference<List<User>>() {
                  // ...
                });
      } else if (clazz.equals(Principal.class)) {
        entities =
            objectMapper.readValue(
                entitiesAsString,
                new TypeReference<List<Principal>>() {
                  // ...
                });
      } else {
        entities = objectMapper.readValue(entitiesAsString, List.class);
      }
    } catch (final JsonParseException parseEx) {
      logger.error("", parseEx);
    } catch (final JsonMappingException mappingEx) {
      logger.error("", mappingEx);
    } catch (final IOException ioEx) {
      logger.error("", ioEx);
    }

    return entities;
  }
Пример #29
0
  @RequestMapping(value = "/getGRNFromOderId", method = RequestMethod.GET)
  public void getGRNFromOderId(
      HttpServletResponse httpservletResponse,
      @RequestParam String oderId,
      @RequestParam String status) {

    try {
      List<GrnVO> valueObj = grnManager.getGRNFromOderId(oderId, status);
      if (valueObj != null && valueObj.size() > 0) {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode objectNode = new ObjectNode(mapper.getNodeFactory());
        JsonObjectUtil<GrnVO> jsonUtil = new JsonObjectUtil<GrnVO>();
        String m = jsonUtil.getJsonObjectDataDetail(valueObj, 1);
        ArrayNode node = mapper.readValue(m, ArrayNode.class);
        objectNode.put("Data", node);
        objectNode.put("success", true);
        writeJson(httpservletResponse, objectNode, mapper);
      } else {
        writeJsonString(httpservletResponse, "{\"Data\":\"Empty\",\"success\":false}");
      }
    } catch (Exception e) {
      getLogger().error(e.getMessage());
      writeJsonString(
          httpservletResponse, "{\"Data\":\"" + e.getMessage() + "\",\"success\":false}");
    }
  }
  @Test
  public void voteAndGetResults() throws Exception {
    // do 5 votes
    vote();

    MvcResult result =
        mockMvc
            .perform(
                get("/vote/showWinner")
                    .contentType(MediaType.APPLICATION_JSON)
                    .with(httpBasic("user", "")))
            .andExpect(status().isOk())
            .andReturn();

    String contentAsString = result.getResponse().getContentAsString();
    ObjectMapper mapper = new ObjectMapper();

    VoteResult[] voteResult =
        mapper.readValue(new StringReader(contentAsString), VoteResult[].class);
    // check we have results for all restaurants
    assertEquals(2, voteResult.length);

    // check it was sorted properly
    assertEquals(RESTAURANT_B_NAME, voteResult[0].getRestaurantName());
    // check votes counted properly
    assertEquals(3, voteResult[0].getVotes());
    assertEquals(2, voteResult[1].getVotes());
  }