com.fasterxml.jackson.databind.node.TextNode Java Examples

The following examples show how to use com.fasterxml.jackson.databind.node.TextNode. 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: AmpRequestFactoryTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnFailedFutureIfStoredBidRequestExtCouldNotBeParsed() {
    // given
    final ObjectNode ext = mapper.createObjectNode()
            .set("prebid", new TextNode("non-ExtBidRequest"));
    givenBidRequest(builder -> builder.ext(ext), Imp.builder().build());

    // when
    final Future<?> future = factory.fromRequest(routingContext, 0L);

    // then
    assertThat(future.failed()).isTrue();
    assertThat(future.cause()).isInstanceOf(InvalidRequestException.class);
    assertThat(((InvalidRequestException) future.cause()).getMessages())
            .hasSize(1).element(0).asString().startsWith("Error decoding bidRequest.ext:");
}
 
Example #2
Source File: DistributedNetworkConfigStore.java    From onos with Apache License 2.0 6 votes vote down vote up
@Activate
public void activate() {
    KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder()
            .register(KryoNamespaces.API)
            .register(ConfigKey.class, ObjectNode.class, ArrayNode.class,
                      JsonNodeFactory.class, LinkedHashMap.class,
                      TextNode.class, BooleanNode.class,
                      LongNode.class, DoubleNode.class, ShortNode.class, IntNode.class,
                      NullNode.class);

    configs = storageService.<ConfigKey, JsonNode>consistentMapBuilder()
            .withSerializer(Serializer.using(kryoBuilder.build()))
            .withName("onos-network-configs")
            .withRelaxedReadConsistency()
            .build();
    configs.addListener(listener);
    log.info("Started");
}
 
Example #3
Source File: ExtractConnectorDescriptorsMojo.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private ObjectNode getComponentMeta(ClassLoader classLoader) {
    Properties properties = loadComponentProperties(classLoader);
    if (properties == null) {
        return null;
    }
    String components = (String) properties.get("components");
    if (components == null) {
        return null;
    }
    String[] part = components.split("\\s", -1);
    ObjectNode componentMeta = new ObjectNode(JsonNodeFactory.instance);
    for (String scheme : part) {
        // find the class name
        String javaType = extractComponentJavaType(classLoader, scheme);
        if (javaType == null) {
            continue;
        }
        String schemeMeta = loadComponentJSonSchema(classLoader, scheme, javaType);
        if (schemeMeta == null) {
            continue;
        }
        componentMeta.set(scheme, new TextNode(schemeMeta));
    }
    return componentMeta.size() > 0 ? componentMeta : null;
}
 
Example #4
Source File: EventTypeDbRepositoryTest.java    From nakadi with MIT License 6 votes vote down vote up
@Test
public void unknownAttributesAreIgnoredWhenDesserializing() throws Exception {
    final EventType eventType = buildDefaultEventType();
    final ObjectNode node = (ObjectNode) TestUtils.OBJECT_MAPPER.readTree(
            TestUtils.OBJECT_MAPPER.writeValueAsString(eventType));
    node.set("unknown_attribute", new TextNode("will just be ignored"));

    final String eventTypeName = eventType.getName();
    final String insertSQL = "INSERT INTO zn_data.event_type (et_name, et_event_type_object) " +
            "VALUES (?, to_json(?::json))";
    template.update(insertSQL,
            eventTypeName,
            TestUtils.OBJECT_MAPPER.writeValueAsString(node));

    final EventType persistedEventType = repository.findByName(eventTypeName);

    assertThat(persistedEventType, notNullValue());
}
 
Example #5
Source File: CacheServiceTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheBidsOpenrtbShouldNotModifyVastXmlWhenBidIdIsNotInToModifyList() throws IOException {
    // given
    final com.iab.openrtb.response.Bid bid = givenBidOpenrtb(builder ->
            builder.id("bid1").impid("impId1").adm("adm"));
    final Imp imp1 = givenImp(builder -> builder.id("impId1").video(Video.builder().build()));

    // when
    cacheService.cacheBidsOpenrtb(singletonList(bid), singletonList(imp1),
            CacheContext.builder()
                    .shouldCacheBids(true)
                    .shouldCacheVideoBids(true)
                    .bidderToVideoBidIdsToModify(singletonMap("bidder", singletonList("bid2")))
                    .bidderToBidIds(singletonMap("bidder", singletonList("bid1")))
                    .build(), account, eventsContext, timeout);

    // then
    final BidCacheRequest bidCacheRequest = captureBidCacheRequest();
    assertThat(bidCacheRequest.getPuts()).hasSize(2)
            .containsOnly(
                    PutObject.builder().type("json").value(mapper.valueToTree(bid)).build(),
                    PutObject.builder().type("xml").value(new TextNode("adm")).build());
}
 
Example #6
Source File: IntegerSampler.java    From log-synth with Apache License 2.0 6 votes vote down vote up
@Override
public JsonNode sample() {
    synchronized (this) {
        if (dist == null) {
            int r = power >= 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            if (power >= 0) {
                for (int i = 0; i <= power; i++) {
                    r = Math.min(r, min + base.nextInt(max - min));
                }
            } else {
                int n = -power;
                for (int i = 0; i <= n; i++) {
                    r = Math.max(r, min + base.nextInt(max - min));
                }
            }
            if (format == null) {
                return new IntNode(r);
            } else {
                return new TextNode(String.format(format, r));
            }
        } else {
            return new LongNode(dist.sample());
        }
    }
}
 
Example #7
Source File: ObjectToJsonNode.java    From yosegi with Apache License 2.0 6 votes vote down vote up
/**
 * Judge Java objects and create JsonNode.
 */
public static JsonNode get( final Object obj ) throws IOException {
  if ( obj instanceof PrimitiveObject ) {
    return PrimitiveObjectToJsonNode.get( (PrimitiveObject)obj );
  } else if ( obj instanceof String ) {
    return new TextNode( (String)obj );
  } else if ( obj instanceof Boolean ) {
    return BooleanNode.valueOf( (Boolean)obj );
  } else if ( obj instanceof Short ) {
    return IntNode.valueOf( ( (Short)obj ).intValue() );
  } else if ( obj instanceof Integer ) {
    return IntNode.valueOf( (Integer)obj );
  } else if ( obj instanceof Long ) {
    return new LongNode( (Long)obj );
  } else if ( obj instanceof Float ) {
    return new DoubleNode( ( (Float)obj ).doubleValue() );
  } else if ( obj instanceof Double ) {
    return new DoubleNode( (Double)obj );
  } else if ( obj instanceof byte[] ) {
    return new BinaryNode( (byte[])obj );
  } else if ( obj == null ) {
    return NullNode.getInstance();
  } else {
    return new TextNode( obj.toString() );
  }
}
 
Example #8
Source File: AuctionRequestFactoryTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnFailedFutureWithInvalidRequestExceptionWhenStringPriceGranularityInvalid() {
    // given
    givenBidRequest(BidRequest.builder()
            .imp(singletonList(Imp.builder().build()))
            .ext(mapper.valueToTree(ExtBidRequest.of(ExtRequestPrebid.builder()
                    .targeting(ExtRequestTargeting.builder().pricegranularity(new TextNode("invalid")).build())
                    .build())))
            .build());

    // when
    final Future<?> future = factory.fromRequest(routingContext, 0L);

    // then
    assertThat(future.failed()).isTrue();
    assertThat(future.cause())
            .isInstanceOf(InvalidRequestException.class)
            .hasMessage("Invalid string price granularity with value: invalid");
}
 
Example #9
Source File: AuctionRequestFactoryTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConvertStringPriceGranularityViewToCustom() {
    // given
    givenBidRequest(BidRequest.builder()
            .imp(singletonList(Imp.builder().ext(mapper.createObjectNode()).build()))
            .ext(mapper.valueToTree(ExtBidRequest.of(ExtRequestPrebid.builder()
                    .targeting(ExtRequestTargeting.builder().pricegranularity(new TextNode("low")).build())
                    .build())))
            .build());

    // when
    final BidRequest request = factory.fromRequest(routingContext, 0L).result().getBidRequest();

    // then
    // request was wrapped to list because extracting method works different on iterable and not iterable objects,
    // which force to make type casting or exception handling in lambdas
    assertThat(singletonList(request))
            .extracting(BidRequest::getExt)
            .extracting(ext -> mapper.treeToValue(ext, ExtBidRequest.class))
            .extracting(ExtBidRequest::getPrebid)
            .extracting(ExtRequestPrebid::getTargeting)
            .extracting(ExtRequestTargeting::getPricegranularity)
            .containsOnly(mapper.valueToTree(ExtPriceGranularity.of(2, singletonList(ExtGranularityRange.of(
                    BigDecimal.valueOf(5), BigDecimal.valueOf(0.5))))));
}
 
Example #10
Source File: DateJsonConvert.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Override
public InfoDTO deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
    throws IOException {
    InfoDTO infoDTO = new InfoDTO();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);

    TextNode appNameNode = (TextNode) treeNode.get("appName");
    infoDTO.setAppName(appNameNode.asText());
    TextNode versionNode = (TextNode) treeNode.get("version");
    infoDTO.setVersion(versionNode.asText());
    TextNode dateNode = (TextNode) treeNode.get("date");
    try {
        infoDTO.setDate(sdf.parse(dateNode.asText()));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return infoDTO;
}
 
Example #11
Source File: BurstyEvents.java    From log-synth with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
    private boolean addTimeFields(ObjectNode x) {
        Event e = null;
        while (e != Event.ACTION) {
            e = step();
//            System.out.printf("%8s/%-9s %11s %s %8.2f %8.2f %8.2f %8.2f\n",
//                    Util.isDaytime(Util.timeOfDay(now), sunriseTime, sunsetTime) ? "day" : "night",
//                    isActive ? "active" : "inactive",
//                    e, df.format((long) now),
//                    (nextQuery - now) / TimeUnit.HOURS.toMillis(1),
//                    (nextTransition - now) / TimeUnit.HOURS.toMillis(1),
//                    24 * Util.fractionalPart((sunriseTime - Util.timeOfDay(now)) / TimeUnit.HOURS.toMillis(24)),
//                    24 * Util.fractionalPart((sunsetTime - Util.timeOfDay(now)) / TimeUnit.HOURS.toMillis(24))
//            );
            if (e == Event.END) {
                return false;
            }
        }
        x.set("time", new TextNode(df.format((long) now)));
        x.set("timestamp_ms", new LongNode((long) now));
        x.set("timestamp_s", new LongNode((long) (now / 1000)));
        return true;
    }
 
Example #12
Source File: MultiplyOperator.java    From jslt with Apache License 2.0 6 votes vote down vote up
public JsonNode perform(JsonNode v1, JsonNode v2) {
  if (v1.isTextual() || v2.isTextual()) {
    // if one operand is string: do string multiplication

    String str;
    int num;
    if (v1.isTextual() && !v2.isTextual()) {
      str = v1.asText();
      num = v2.intValue();
    } else if (v2.isTextual()) {
      str = v2.asText();
      num = v1.intValue();
    } else
      throw new JsltException("Can't multiply two strings!");

    StringBuilder buf = new StringBuilder();
    for ( ; num > 0; num--)
      buf.append(str);

    return new TextNode(buf.toString());
  } else
    // do numeric operation
    return super.perform(v1, v2);
}
 
Example #13
Source File: PulsepointAdapterTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamAdSizeWidthIsInvalid() {
    // given
    final ObjectNode params = mapper.createObjectNode();
    params.set("cp", new IntNode(1));
    params.set("ct", new IntNode(1));
    params.set("cf", new TextNode("invalidX500"));
    adapterRequest = givenBidder(builder -> builder.params(params));

    // when and then
    assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
            .isExactlyInstanceOf(PreBidException.class)
            .hasMessage("Invalid Width param invalid");
}
 
Example #14
Source File: PulsepointAdapterTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamsCouldNotBeParsed() {
    // given
    final ObjectNode params = mapper.createObjectNode();
    params.set("cp", new TextNode("non-integer"));
    adapterRequest = givenBidder(builder -> builder.params(params));

    // when and then
    assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
            .isExactlyInstanceOf(PreBidException.class)
            .hasMessageStartingWith("Cannot deserialize value of type");
}
 
Example #15
Source File: CacheServiceTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void cacheBidsShouldPerformHttpRequestWithExpectedBody() throws Exception {
    // given
    final String adm3 = "<script type=\"application/javascript\" src=\"http://nym1-ib.adnxs"
            + "f3919239&pp=${AUCTION_PRICE}&\"></script>";
    final String adm4 = "<img src=\"https://tpp.hpppf.com/simgad/11261207092432736464\" border=\"0\" "
            + "width=\"184\" height=\"90\" alt=\"\" class=\"img_ad\">";

    // when
    cacheService.cacheBids(asList(
            givenBid(builder -> builder.adm("adm1").nurl("nurl1").height(100).width(200)),
            givenBid(builder -> builder.adm("adm2").nurl("nurl2").height(300).width(400)),
            givenBid(builder -> builder.adm(adm3).mediaType(MediaType.video)),
            givenBid(builder -> builder.adm(adm4).mediaType(MediaType.video))),
            timeout);

    // then
    final BidCacheRequest bidCacheRequest = captureBidCacheRequest();
    assertThat(bidCacheRequest.getPuts()).hasSize(4)
            .containsOnly(
                    PutObject.builder().type("json").value(
                            mapper.valueToTree(BannerValue.of("adm1", "nurl1", 200, 100))).build(),
                    PutObject.builder().type("json").value(
                            mapper.valueToTree(BannerValue.of("adm2", "nurl2", 400, 300))).build(),
                    PutObject.builder().type("xml").value(new TextNode(adm3)).build(),
                    PutObject.builder().type("xml").value(new TextNode(adm4)).build());
}
 
Example #16
Source File: HeaderDeserializerTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldGetStringWhenParsingTextNode() throws Exception {
    Map<String, JsonNode> tree = new HashMap<>();
    TextNode node = new TextNode("something here");
    tree.put("key", node);

    String text = deserializer.getString(tree, "key");
    assertThat(text, is(notNullValue()));
    assertThat(text, is("something here"));
}
 
Example #17
Source File: CacheServiceTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void cacheBidsVideoOnlyShouldPerformHttpRequestWithExpectedBody() throws IOException {
    // when
    cacheService.cacheBidsVideoOnly(asList(
            givenBid(builder -> builder.mediaType(MediaType.banner).adm("adm1")),
            givenBid(builder -> builder.mediaType(MediaType.video).adm("adm2"))),
            timeout);

    // then
    final BidCacheRequest bidCacheRequest = captureBidCacheRequest();
    assertThat(bidCacheRequest.getPuts()).hasSize(1)
            .containsOnly(PutObject.builder().type("xml").value(new TextNode("adm2")).build());
}
 
Example #18
Source File: TikaTextExtractorTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void asListOfStringShouldReturnASingletonWhenOneElement() {
    ContentAndMetadataDeserializer deserializer = new TikaTextExtractor.ContentAndMetadataDeserializer();
    List<String> listOfString = deserializer.asListOfString(TextNode.valueOf("text"));
    
    assertThat(listOfString).containsOnly("text");
}
 
Example #19
Source File: RubiconAdapterTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamsCouldNotBeParsed() {
    // given
    final ObjectNode params = mapper.createObjectNode();
    params.set("accountId", new TextNode("non-integer"));
    adapterRequest = givenBidderCustomizable(builder -> builder.params(params), identity());

    // when and then
    assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
            .isExactlyInstanceOf(PreBidException.class)
            .hasMessageStartingWith("Cannot deserialize value of type");
}
 
Example #20
Source File: AbstractYMLConfigurationAction.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void populateWriterReader(ObjectNode root, String path, String type, String[] includes, String[] excludes,
		Map<String, Object> params) {
	if (path != null && !"".equals(path)) {
		root.set("path", new TextNode(path));
	}

	if (type != null) {
		root.set("type", new TextNode(type));
	}

	if (includes != null && includes.length > 0) {
		ArrayNode includesNode = new ArrayNode(provider.getObjectMapper().getNodeFactory());
		for (int i = 0; i < includes.length; i++) {
			includesNode.add(new TextNode(includes[i]));
		}
		root.set("includes", includesNode);
	}

	if (excludes != null && excludes.length > 0) {
		ArrayNode excludesNode = new ArrayNode(provider.getObjectMapper().getNodeFactory());
		for (int i = 0; i < excludes.length; i++) {
			excludesNode.add(new TextNode(excludes[i]));
		}
		root.set("excludes", excludesNode);
	}
	if (params != null && !params.isEmpty()) {
		populateParams(root, params);
	}

}
 
Example #21
Source File: RestAccessInfo.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Builds RestAccessInfo from json.
 * @param root json root node for RestAccessinfo
 * @return REST access information
 * @throws WorkflowException workflow exception
 */
public static RestAccessInfo valueOf(JsonNode root) throws WorkflowException {

    JsonNode node = root.at(ptr(REMOTE_IP));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid remoteIp for " + root);
    }
    IpAddress remoteIp = IpAddress.valueOf(node.asText());

    node = root.at(ptr(PORT));
    if (node == null || !(node instanceof NumericNode)) {
        throw new WorkflowException("invalid port for " + root);
    }
    TpPort tpPort = TpPort.tpPort(node.asInt());

    node = root.at(ptr(USER));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid user for " + root);
    }
    String strUser = node.asText();

    node = root.at(ptr(PASSWORD));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid password for " + root);
    }
    String strPassword = node.asText();

    return new RestAccessInfo(remoteIp, tpPort, strUser, strPassword);
}
 
Example #22
Source File: JoinSampler.java    From log-synth with Apache License 2.0 5 votes vote down vote up
@Override
public JsonNode sample() {
    JsonNode value = delegate.sample();
    StringBuilder r = new StringBuilder();

    String separator="";
    for (JsonNode component : value) {
        r.append(separator);
        r.append(component.asText());
        separator = this.separator;
    }
    return new TextNode(r.toString());
}
 
Example #23
Source File: PayloadImplTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mapper = getDefaultObjectMapper();
    objectReader = mapper.reader();

    expiresAt = Mockito.mock(Date.class);
    notBefore = Mockito.mock(Date.class);
    issuedAt = Mockito.mock(Date.class);
    Map<String, JsonNode> tree = new HashMap<>();
    tree.put("extraClaim", new TextNode("extraValue"));
    payload = new PayloadImpl("issuer", "subject", Collections.singletonList("audience"), expiresAt, notBefore, issuedAt, "jwtId", tree, objectReader);
}
 
Example #24
Source File: BidderDetailsHandler.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns alias info as {@link ObjectNode}.
 */
private ObjectNode aliasNode(BidderCatalog bidderCatalog, String alias) {
    final String name = bidderCatalog.nameByAlias(alias);

    final ObjectNode node = bidderNode(bidderCatalog, name);
    node.set("aliasOf", new TextNode(name));
    return node;
}
 
Example #25
Source File: IntegerSamplerTest.java    From log-synth with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringSetter() {
    IntegerSampler s = new IntegerSampler();
    s.setMinAsInt(10);
    s.setMax(new TextNode("1K"));
    assertEquals(10, s.getMin());
    assertEquals(1000, s.getMax());
}
 
Example #26
Source File: SerializationTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void unmarshalCRDWithSchema() throws Exception {
  final String input = readYamlToString("/test-crd-schema.yml");
  final CustomResourceDefinition crd = Serialization.unmarshal(input, CustomResourceDefinition.class);
  JSONSchemaProps spec = crd.getSpec()
    .getValidation()
    .getOpenAPIV3Schema()
    .getProperties()
    .get("spec");

  assertEquals(spec.getRequired().size(), 3);
  assertEquals(spec.getRequired().get(0), "builderName");
  assertEquals(spec.getRequired().get(1), "edges");
  assertEquals(spec.getRequired().get(2), "dimensions");

  Map<String, JSONSchemaProps> properties = spec.getProperties();
  assertNotNull(properties.get("builderName"));
  assertEquals(properties.get("builderName").getExample(), new TextNode("builder-example"));
  assertEquals(properties.get("hollow").getDefault(), BooleanNode.FALSE);

  assertNotNull(properties.get("dimensions"));
  assertNotNull(properties.get("dimensions").getProperties().get("x"));
  assertEquals(properties.get("dimensions").getProperties().get("x").getDefault(), new IntNode(10));

  String output = Serialization.asYaml(crd);
  assertEquals(input.trim(), output.trim());
}
 
Example #27
Source File: ResourceIdentifierUtilsTest.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
@Test
void isReferenceOfType_WithTextNodeVsProductReferenceTypeId_ShouldReturnFalse() {
    // preparation
    final TextNode textNode = JsonNodeFactory.instance.textNode("foo");

    // test
    final boolean isReference = isReferenceOfType(textNode, Product.referenceTypeId());

    // assertion
    assertThat(isReference).isFalse();
}
 
Example #28
Source File: JsonFilterReader.java    From knox with Apache License 2.0 5 votes vote down vote up
protected String filterStreamValue( Level node ) {
  String value;
  if( node.isArray() ) {
    value = node.node.get( 0 ).asText();
  } else {
    value = node.node.get( node.field ).asText();
  }
  String rule = null;
  UrlRewriteFilterGroupDescriptor scope = node.scopeConfig;
  //TODO: Scan the top level apply rules for the first match.
  if( scope != null ) {
    for( UrlRewriteFilterPathDescriptor selector : scope.getSelectors() ) {
      JsonPath.Expression path = (JsonPath.Expression)selector.compiledPath( JPATH_COMPILER );
      List<JsonPath.Match> matches = path.evaluate( node.scopeNode );
      if( matches != null && !matches.isEmpty() ) {
        JsonPath.Match match = matches.get( 0 );
        if( match.getNode().isTextual() && selector instanceof UrlRewriteFilterApplyDescriptor ) {
          UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
          rule = apply.rule();
          break;
        }
      }
    }
  }
  try {
    value = filterValueString( node.field, value, rule );
    if( node.isArray() ) {
      ((ArrayNode)node.node).set( 0, new TextNode( value ) );
    } else {
      ((ObjectNode)node.node).put( node.field, value );
    }
  } catch( Exception e ) {
    LOG.failedToFilterValue( value, rule, e );
  }
  return value;
}
 
Example #29
Source File: AppnexusAdapterTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void makeHttpRequestsShouldFailIfAdUnitBidParamsCouldNotBeParsed() {
    // given
    final ObjectNode params = mapper.createObjectNode();
    params.set("placement_id", new TextNode("non-integer"));
    adapterRequest = givenBidder(builder -> builder.params(params), identity());

    // when and then
    assertThatThrownBy(() -> adapter.makeHttpRequests(adapterRequest, preBidRequestContext))
            .isExactlyInstanceOf(PreBidException.class)
            .hasMessageStartingWith("Cannot deserialize value of type");
}
 
Example #30
Source File: TsdbResult.java    From splicer with Apache License 2.0 5 votes vote down vote up
@Override
public Tags deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
	TreeNode n = jp.getCodec().readTree(jp);
	Map<String, String> tags = new HashMap<>();
	Iterator<String> namesIter = n.fieldNames();
	while(namesIter.hasNext()) {
		String field = namesIter.next();
		TreeNode child = n.get(field);
		if (child instanceof TextNode) {
			tags.put(field, ((TextNode) child).asText());
		}
	}
	return new Tags(tags);
}