com.fasterxml.jackson.databind.ObjectMapper Java Examples

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestGeometry.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
@Test
public void test_validate() throws Exception {
  final ObjectMapper mp = new ObjectMapper();

  String json = "{\"type\":\"GeometryCollection\",\"geometries\":[]}";
  GeometryCollection geometryCollection = mp.readValue(json, GeometryCollection.class);
  geometryCollection.validate();

  json = "{\"type\":\"GeometryCollection\",\"geometries\":[" + //
      "{\"type\":\"Point\",\"coordinates\":[0,0,0]}," + //
      "{\"type\":\"MultiPoint\",\"coordinates\":[]}," + //
      "{\"type\":\"MultiPoint\",\"coordinates\":[[0,0,0], [1,1,1]]}" + //
      "]}";
  geometryCollection = mp.readValue(json, GeometryCollection.class);
  geometryCollection.validate();
}
 
Example #2
Source File: AbstractServletContainerIntegrationTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
public List<JsonNode> getEvents(String eventType) {
    try {
        final List<JsonNode> events = new ArrayList<>();
        final ObjectMapper objectMapper = new ObjectMapper();
        for (HttpRequest httpRequest : mockServerContainer.getClient().retrieveRecordedRequests(request(INTAKE_V2_URL))) {
            final String bodyAsString = httpRequest.getBodyAsString();
            for (String ndJsonLine : bodyAsString.split("\n")) {
                final JsonNode ndJson = objectMapper.readTree(ndJsonLine);
                if (ndJson.get(eventType) != null) {
                    // as inferred spans are created only after the profiling session ends
                    // they can leak into another test
                    if (!isInferredSpan(ndJson.get(eventType))) {
                        validateEventMetadata(bodyAsString);
                    }
                    events.add(ndJson.get(eventType));
                }
            }
        }
        return events;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #3
Source File: HttpLocalDownloadServiceFetcher.java    From Singularity with Apache License 2.0 6 votes vote down vote up
public HttpLocalDownloadServiceFetcher(
  AsyncHttpClient httpClient,
  ObjectMapper objectMapper,
  SingularityExecutorConfiguration executorConfiguration,
  SingularityS3Configuration s3Configuration
) {
  this.httpClient = httpClient;
  this.objectMapper = objectMapper;
  this.executorConfiguration = executorConfiguration;
  this.localDownloadUri =
    String.format(
      LOCAL_DOWNLOAD_STRING_FORMAT,
      s3Configuration.getLocalDownloadHttpPort(),
      s3Configuration.getLocalDownloadPath()
    );
}
 
Example #4
Source File: VoteResourceTest.java    From kaif with Apache License 2.0 6 votes vote down vote up
@Test
public void ignoreDuplicateVote() throws Exception {
  Account account = accountCitizen("foo");
  String token = prepareAccessToken(account);

  VoteResource.VoteArticle voteArticle = new VoteResource.VoteArticle();
  voteArticle.articleId = FlakeId.fromString("a");
  voteArticle.newState = VoteState.DOWN;
  voteArticle.previousCount = 100L;
  voteArticle.previousState = VoteState.EMPTY;

  Mockito.doThrow(new DuplicateKeyException("vote dup"))
      .when(voteService)
      .voteArticle(eq(VoteState.DOWN),
          eq(FlakeId.fromString("a")),
          isA(Authorization.class),
          eq(VoteState.EMPTY),
          eq(100L));

  mockMvc.perform(post("/api/vote/article").header(AccountAccessToken.HEADER_KEY, token)
      .contentType(MediaType.APPLICATION_JSON)
      .content(new ObjectMapper().writeValueAsBytes(voteArticle))).andExpect(status().isOk());
}
 
Example #5
Source File: AdvancedOptionsPanel.java    From datasync with MIT License 6 votes vote down vote up
private void showEditControlFileDialog() {
    try {
        ObjectMapper mapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true);
        String textAreaContent = mapper.writeValueAsString(model.getControlFile());

        JTextArea controlFileContentTextArea = new JTextArea();
        controlFileContentTextArea.setEditable(false);
        controlFileContentTextArea.setText(textAreaContent);
        JScrollPane scrollPane = new JScrollPane(controlFileContentTextArea);
        controlFileContentTextArea.setLineWrap(true);
        controlFileContentTextArea.setWrapStyleWord(true);
        controlFileContentTextArea.setCaretPosition(0);
        scrollPane.setPreferredSize(CONTROL_FILE_VIEWER_DIMENSIONS);

        JOptionPane.showMessageDialog(this,scrollPane,"View Control File",JOptionPane.PLAIN_MESSAGE);
    }
    catch (IOException e){
         JOptionPane.showMessageDialog(this,"Could not load control file.  Please contact support");
    }

}
 
Example #6
Source File: HerokuDeployApi.java    From heroku-maven-plugin with MIT License 6 votes vote down vote up
private BuildInfo handleBuildInfoResponse(String appName, ObjectMapper mapper, CloseableHttpResponse response) throws IOException, HerokuDeployApiException {
    switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_NOT_FOUND:
            throw new AppNotFoundException(String.format("App %s could not be found!", appName));

        case HttpStatus.SC_FORBIDDEN:
            throw new InsufficientAppPermissionsException(String.format("Could not access app %s: insufficient permissions", appName));

        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
            HttpEntity responseEntity = response.getEntity();
            String responseStringBody = Util.readLinesFromInputStream(responseEntity.getContent()).collect(Collectors.joining());

            return mapper.readValue(responseStringBody, BuildInfo.class);

        default:
            throw new HerokuDeployApiException(String.format("Unexpected status code: %d!", response.getStatusLine().getStatusCode()));
    }
}
 
Example #7
Source File: DataSourceControllerTest.java    From metamodel-membrane with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutWithValidationPassing() throws Exception {
    final String tenant = name.getMethodName();
    tenantRegistry.createTenantContext(tenant);

    final RestDataSourceDefinition dataSourceDefinition = new RestDataSourceDefinition();
    dataSourceDefinition.setType("pojo");

    final GetDatasourceResponse resp = dataSourceController.put(tenant, "ds1", true, dataSourceDefinition);

    final ObjectMapper objectMapper = new ObjectMapper();

    assertEquals(
            "[{'name':'information_schema','uri':'/testPutWithValidationPassing/ds1/s/information_schema'},"
                    + "{'name':'Schema','uri':'/testPutWithValidationPassing/ds1/s/Schema'}]",
            objectMapper.writeValueAsString(resp.getSchemas()).replace('\"', '\''));
}
 
Example #8
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceWithoutLock() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/configmaps/map1").andReturn(200, new ConfigMapBuilder()
    .withNewMetadata().withResourceVersion("1000").and().build()).always();

  server.expect().put().withPath("/api/v1/namespaces/test/configmaps/map1").andReturn(200, new ConfigMapBuilder()
    .withNewMetadata().withResourceVersion("1001").and().build()).once();

  KubernetesClient client = server.getClient();
  ConfigMap map = client.configMaps().withName("map1").replace(new ConfigMapBuilder()
    .withNewMetadata().withName("map1").and().build());
  assertNotNull(map);
  assertEquals("1001", map.getMetadata().getResourceVersion());

  RecordedRequest request = server.getLastRequest();
  ConfigMap replacedMap = new ObjectMapper().readerFor(ConfigMap.class).readValue(request.getBody().inputStream());
  assertEquals("1000", replacedMap.getMetadata().getResourceVersion());
}
 
Example #9
Source File: MessageProcessor.java    From product-emm with Apache License 2.0 6 votes vote down vote up
/**
 * Local notification message handler.
 *
 * @param context Context of the application.
 */
public MessageProcessor(Context context) {
	this.context = context;

	deviceId = Preference.getString(context, DEVICE_ID_PREFERENCE_KEY);
	operationProcessor = new OperationProcessor(context.getApplicationContext());
	mapper = new ObjectMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	this.devicePolicyManager =
			(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);

	if (deviceId == null) {
		DeviceInfo deviceInfo = new DeviceInfo(context.getApplicationContext());
		deviceId = deviceInfo.getDeviceId();
		Preference.putString(context, DEVICE_ID_PREFERENCE_KEY, deviceId);
	}
}
 
Example #10
Source File: OpenstackNetworkingUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Adds router interfaces to openstack admin service.
 *
 * @param osPort        port
 * @param adminService  openstack admin service
 */
public static void addRouterIface(Port osPort,
                                  OpenstackRouterAdminService adminService) {
    osPort.getFixedIps().forEach(p -> {
        JsonNode jsonTree = new ObjectMapper().createObjectNode()
                .put("id", osPort.getDeviceId())
                .put("tenant_id", osPort.getTenantId())
                .put("subnet_id", p.getSubnetId())
                .put("port_id", osPort.getId());
        try {
            RouterInterface rIface = getContext(NeutronRouterInterface.class)
                    .readerFor(NeutronRouterInterface.class)
                    .readValue(jsonTree);
            if (adminService.routerInterface(rIface.getPortId()) != null) {
                adminService.updateRouterInterface(rIface);
            } else {
                adminService.addRouterInterface(rIface);
            }
        } catch (IOException e) {
            log.error("IOException occurred because of {}", e);
        }
    });
}
 
Example #11
Source File: LmWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateLm() throws CfmConfigException, SoamConfigException {
    MepEntry mep1 = DefaultMepEntry.builder(MEPID1, DeviceId.deviceId("netconf:1.2.3.4:830"),
            PortNumber.portNumber(1), Mep.MepDirection.UP_MEP, MDNAME1, MANAME1).buildEntry();

    expect(mepService.getMep(MDNAME1, MANAME1, MEPID1)).andReturn(mep1).anyTimes();
    replay(mepService);

    ObjectMapper mapper = new ObjectMapper();
    CfmCodecContext context = new CfmCodecContext();
    ObjectNode node = mapper.createObjectNode();
    node.set("lm", context.codec(LossMeasurementCreate.class).encode(lm1, context));

    final WebTarget wt = target();
    final Response response = wt.path("md/" + MDNAME1.mdName() + "/ma/" +
            MANAME1.maName() + "/mep/" + MEPID1.value() + "/lm")
            .request().post(Entity.json(node.toString()));
    assertEquals(201, response.getStatus());
}
 
Example #12
Source File: MapperUtils.java    From yfshop with Apache License 2.0 6 votes vote down vote up
/**
 * 把 JSON 解析成 List,如果 List 内部的元素存在 jsonString,继续解析
 *
 * @param json
 * @param mapper 解析工具
 * @return
 * @throws Exception
 */
private static List<Object> json2ListRecursion(String json, ObjectMapper mapper) throws Exception {
    if (json == null) {
        return null;
    }

    List<Object> list = mapper.readValue(json, List.class);

    for (Object obj : list) {
        if (obj != null && obj instanceof String) {
            String str = (String) obj;
            if (str.startsWith("[")) {
                obj = json2ListRecursion(str, mapper);
            } else if (obj.toString().startsWith("{")) {
                obj = json2MapRecursion(str, mapper);
            }
        }
    }

    return list;
}
 
Example #13
Source File: ApiInterceptor.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (StrUtil.equals(TrueFalseEnum.TRUE.getDesc(), HaloConst.OPTIONS.get(BlogPropertiesEnum.API_STATUS.getProp()))) {
        if (StrUtil.equals(request.getHeader("token"), HaloConst.OPTIONS.get(BlogPropertiesEnum.API_TOKEN.getProp()))) {
            return true;
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            Map<String, Object> map = new HashMap<>(2);
            ObjectMapper mapper = new ObjectMapper();
            map.put("code", 400);
            map.put("msg", "Invalid Token");
            response.getWriter().write(mapper.writeValueAsString(map));
            return false;
        }
    }
    response.sendRedirect("/404");
    return false;
}
 
Example #14
Source File: CORSServiceTestHelper.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static ResourceAdd getSampleResourceAdd(List<CORSOrigin> corsOrigins) {

        ObjectMapper mapper = new ObjectMapper();

        ResourceAdd resourceAdd = new ResourceAdd();
        resourceAdd.setName(CORS_ORIGIN_RESOURCE_NAME);
        List<Attribute> attributeList = new ArrayList<>();
        for (CORSOrigin corsOrigin : corsOrigins) {
            Attribute attribute = new Attribute();
            attribute.setKey(String.valueOf(corsOrigin.hashCode()));
            try {
                String corsOriginString = mapper.writeValueAsString(corsOrigin);
                attribute.setValue(corsOriginString);
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Error while converting a CORS Origin to a String.", e);
                }
            }
            attributeList.add(attribute);
        }
        resourceAdd.setAttributes(attributeList);

        return resourceAdd;
    }
 
Example #15
Source File: SimpleRestClient.java    From next-api-v2-examples with MIT License 6 votes vote down vote up
public JsonNode login(String user, String password)
    throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {

  String authParameters = encryptAuthParameter(user, password);

  // Send login request
  Response response =
      baseResource
          .path("login")
          .queryParam("service", Main.SERVICE)
          .queryParam("auth", authParameters)
          .request(responseType)
          .post(null);

  ObjectNode json = response.readEntity(ObjectNode.class);

  JsonNode node = new ObjectMapper().readTree(json.toString());

  String sessionKey = json.get("session_key").asText();

  // Add the session key to basic auth for all calls
  baseResource.register(HttpAuthenticationFeature.basic(sessionKey, sessionKey));

  return node;
}
 
Example #16
Source File: JweTokenSerializer.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
public Map<String, Object> decode(String base64EncodedKey, String content) {
    try {
        byte[] decodedKey = Base64.getDecoder().decode(base64EncodedKey);
        SecretKey key = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        JWEObject jwe = JWEObject.parse(content);
        jwe.decrypt(new AESDecrypter(key));

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectReader reader = objectMapper.readerFor(Map.class);
        return reader.with(DeserializationFeature.USE_LONG_FOR_INTS)
                .readValue(jwe.getPayload().toString());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example #17
Source File: SeedManager.java    From joal with Apache License 2.0 6 votes vote down vote up
public SeedManager(final String joalConfFolder, final ObjectMapper mapper, final ApplicationEventPublisher publisher) throws IOException {
    this.isSeeding = false;
    this.joalFoldersPath = new JoalFoldersPath(Paths.get(joalConfFolder));
    this.torrentFileProvider = new TorrentFileProvider(joalFoldersPath);
    this.configProvider = new JoalConfigProvider(mapper, joalFoldersPath, publisher);
    this.bitTorrentClientProvider = new BitTorrentClientProvider(configProvider, mapper, joalFoldersPath);
    this.publisher = publisher;
    this.connectionHandler = new ConnectionHandler();


    final SocketConfig sc = SocketConfig.custom()
            .setSoTimeout(30000)
            .build();
    final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(100);
    connManager.setMaxTotal(200);
    connManager.setValidateAfterInactivity(1000);
    connManager.setDefaultSocketConfig(sc);
    this.httpClient = HttpClients.custom()
            .setConnectionTimeToLive(1, TimeUnit.MINUTES)
            .setConnectionManager(connManager)
            .setConnectionManagerShared(true)
            .build();
}
 
Example #18
Source File: CommonHandlerTest.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateWrappedExceptionResponse() throws Exception {
    // given
    Exception e = new Exception(new Exception(new Exception("Wrapped message")));
    // when
    CommonResponse httpResponse = HTTP_SERVER_HANDLER.newHttpResponseFromException(
            mock(CommonRequest.class), mock(Authentication.class), e);
    // then
    String content = (String) httpResponse.getContent();
    ObjectNode node = (ObjectNode) new ObjectMapper().readTree(content);
    assertThat(node.get("message").asText()).isEqualTo("java.lang.Exception: Wrapped message");
    assertThat(node.get("stackTrace")).isNotNull();
    assertThat(httpResponse.getStatus()).isEqualTo(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
 
Example #19
Source File: CBOR.java    From mcumgr-android with Apache License 2.0 5 votes vote down vote up
public static Map<String, String> toStringMap(byte[] data) throws IOException {
    ObjectMapper mapper = new ObjectMapper(sFactory);
    TypeReference<HashMap<String, String>> typeRef =
            new TypeReference<HashMap<String, String>>() {};
    ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
    return mapper.readValue(inputStream, typeRef);
}
 
Example #20
Source File: JwtUtils.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
 * Convert JsonObject to {@link Map}<{@link String}, {@link Object}>
 *
 * @param jsonObject The JsonObject
 * @return {@link Map}<{@link String}, {@link Object}>
 */
@SuppressWarnings("unchecked")
public static Map<String, Object> getClaimsFromJSONObjectBodyRequest(String jsonObject) {

    Map<String, Object> claims = new HashMap<>();

    try {
        claims = new ObjectMapper().readValue(jsonObject, HashMap.class);
        claims = claims.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return claims;
}
 
Example #21
Source File: JsonPatchApplierTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test(expected = PatchApplicationException.class)
public void throwsPatchApplicationExceptionWhenNotAValidPatch() throws Exception {
  JsonNode road = mapper.readTree("{\"description\":\"description1\"}");

  List<PatchOperation> operations = singletonList(PatchOperation.replace("/description", "description2"));

  JsonNode jsonNodePatch = mapper.readTree("{}");

  ObjectMapper mockObjectMapper = mock(ObjectMapper.class);
  when(mockObjectMapper.convertValue(any(), eq(JsonNode.class))).thenReturn(jsonNodePatch);

  underTest = new JsonPatchApplier(mockObjectMapper);
  underTest.apply(road, operations);
}
 
Example #22
Source File: ConanUrlIndexer.java    From nexus-repository-conan with Eclipse Public License 1.0 5 votes vote down vote up
private Map<String, URL> readIndex(final InputStream stream) {
  ObjectMapper objectMapper = new ObjectMapper();

  TypeReference<HashMap<String, URL>> typeRef = new TypeReference<HashMap<String, URL>>() { };
  try {
    return objectMapper.readValue(stream, typeRef);
  }
  catch (IOException e) {
    log.warn("Unable to read index for asset", e);
  }
  return emptyMap();
}
 
Example #23
Source File: ApiService_Update_DefaultLoggingMaxDurationTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldOverrideTimestampCaseTimestampLessOrEqual() throws TechnicalException {
    Logging logging = new Logging();
    logging.setMode(LoggingMode.CLIENT_PROXY);
    logging.setCondition("#request.timestamp <= 2550166583090l");
    existingApi.getProxy().setLogging(logging);
    when(parameterService.findAll(eq(Key.LOGGING_DEFAULT_MAX_DURATION), any())).thenReturn(singletonList(1L));

    apiService.update(API_ID, existingApi);

    verify(apiRepository, times(1)).update(argThat(api -> {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode json = objectMapper.readTree(api.getDefinition());
            JsonNode proxy = json.get("proxy");
            JsonNode logging1 = proxy.get("logging");
            JsonNode mode = logging1.get("mode");
            JsonNode condition = logging1.get("condition");

            return "CLIENT_PROXY".equals(mode.asText())
                    && "#request.timestamp <= 1l".equals(condition.asText());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }));
}
 
Example #24
Source File: JiraApi.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 5 votes vote down vote up
@Inject
public JiraApi(
        final OkHttpClient httpClient, final ObjectMapper objectMapper, final String apiUrl) {
    this.httpClient = Objects.requireNonNull(httpClient);
    this.objectMapper = Objects.requireNonNull(objectMapper);
    this.apiEndpoint = apiUrl;
}
 
Example #25
Source File: ExportTestCase.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param httpServletRequest servlet request
 * @param httpServletResponse servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    try {
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestCaseService testService = appContext.getBean(ITestCaseService.class);

        PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
        String test = policy.sanitize(httpServletRequest.getParameter("test"));
        String testcase = policy.sanitize(httpServletRequest.getParameter("testcase"));

        TestCase tcInfo = testService.findTestCaseByKeyWithDependency(test, testcase);

        // Java object to JSON string
        ObjectMapper mapper = new ObjectMapper();
        JSONObject jo = new JSONObject(mapper.writeValueAsString(tcInfo));
        jo.put("bugs", tcInfo.getBugs());

        JSONObject export = new JSONObject();
        export.put("version", Infos.getInstance().getProjectVersion());
        export.put("user", httpServletRequest.getUserPrincipal());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        export.put("date", formatter.format(new Date()));
        export.put("testCase", jo);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + test + "-" + testcase + ".json");
        // Nice formating the json result by putting indent 4 parameter.
        httpServletResponse.getOutputStream().print(export.toString(4));

    } catch (CerberusException | JSONException ex) {
        LOG.warn(ex);
    }
}
 
Example #26
Source File: ErrorMesssageTests.java    From botanic-ng with Apache License 2.0 5 votes vote down vote up
@Test
public void testErrorMessageSerialization() throws JsonProcessingException {

	final ObjectMapper objectMapper = new ObjectMapper();

	ErrorMessage errorMessage = new ErrorMessage(new Date(), 404, "NotFoundException", "We did not find it.");
	String json = objectMapper.writeValueAsString(errorMessage);
	System.out.print(json);
}
 
Example #27
Source File: DefaultMavenSearchBuilder.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
public String getPomUrl(InputStream is, String endsWith) throws Exception {
    ObjectMapper objectMapper = JsonMapper.defaultMapper().getMapper();
    SearchResult results = objectMapper.readValue(is, SearchResult.class);
    if (results.getResponse() != null && results.getResponse().getDocs() != null
        && results.getResponse().getDocs().length > 0) {
        PomDoc pomInfo = results.getResponse().getDocs()[0];
        String pomUrl = "https://search.maven.org/remotecontent?filepath=" + //
            pomInfo.getG().replace('.', '/') + "/" + //
            pomInfo.getA() + "/" + pomInfo.getV() + "/" + pomInfo.getA() + "-" + pomInfo.getV() + endsWith;
        log.debug(pomUrl);
        return pomUrl;
    }
    return null;
}
 
Example #28
Source File: ToTupleConverter.java    From immutables with Apache License 2.0 5 votes vote down vote up
private ProjectedField(Expression expr, ObjectMapper mapper) {
  Path path = (Path) expr;
  this.path =  path;
  this.mapper = mapper;
  this.pathAsString = path.toStringPath();
  this.javaType = mapper.getTypeFactory().constructType(path.returnType());
}
 
Example #29
Source File: RangePartitionSerializationTest.java    From presto-kudu with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializationSerialization() throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    for (String input : testInputs) {
        RangePartition partition = mapper.readValue(input, RangePartition.class);

        String serialized = mapper.writeValueAsString(partition);
        Assert.assertEquals(serialized, input);
    }
}
 
Example #30
Source File: OpenshiftStartedEnvironment.java    From pnc with Apache License 2.0 5 votes vote down vote up
/**
 * Return an escaped string of the JSON representation of the object
 *
 * By 'escaped', it means that strings like '"' are escaped to '\"'
 * 
 * @param object object to marshall
 * @return Escaped Json String
 */
private String toEscapedJsonString(Object object) {
    ObjectMapper mapper = new ObjectMapper();
    JsonStringEncoder jsonStringEncoder = JsonStringEncoder.getInstance();
    try {
        return new String(jsonStringEncoder.quoteAsString(mapper.writeValueAsString(object)));
    } catch (JsonProcessingException e) {
        logger.error("Could not parse object: " + object, e);
        throw new RuntimeException(e);
    }
}