Java Code Examples for com.jayway.jsonpath.DocumentContext#set()

The following examples show how to use com.jayway.jsonpath.DocumentContext#set() . 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: JsonSetter.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected byte[] perform(byte[] input) throws Exception {
	
	if( getWhere().equals("") )
		return input; 
	
	DocumentContext document = JsonPath.parse(new String(input));
	
	try {
		document.read(getWhere());
	} catch( Exception e ) {
		
		if( !addIfNotPresent.isSelected() )
			throw new IllegalArgumentException("Key not found.");
		
		String insertPath = this.path.getText();
		if( insertPath.equals("Insert-Path") || insertPath.equals("") )
			insertPath = "$";
			
		document = document.put(insertPath, getWhere(), getWhat());
		return document.jsonString().getBytes();
	}
	
	document.set(getWhere(), getWhat());
	return document.jsonString().getBytes();
}
 
Example 2
Source File: FieldLevelEncryption.java    From client-encryption-java with MIT License 6 votes vote down vote up
private static void addDecryptedDataToPayload(DocumentContext payloadContext, String decryptedValue, String jsonPathOut) {
    JsonProvider jsonProvider = jsonPathConfig.jsonProvider();
    Object decryptedValueJsonElement = jsonEngine.parse(decryptedValue);

    if (!jsonEngine.isJsonObject(decryptedValueJsonElement)) {
        // Array or primitive: overwrite
        payloadContext.set(jsonPathOut, decryptedValueJsonElement);
        return;
    }

    // Object: merge
    int length = jsonProvider.length(decryptedValueJsonElement);
    Collection<String> propertyKeys = (0 == length) ? Collections.<String>emptyList() : jsonProvider.getPropertyKeys(decryptedValueJsonElement);
    for (String key : propertyKeys) {
        payloadContext.delete(jsonPathOut + "." + key);
        payloadContext.put(jsonPathOut, key, jsonProvider.getMapValue(decryptedValueJsonElement, key));
    }
}
 
Example 3
Source File: JsonPathIntegrationCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public Integration apply(Integration integration) {
    if (ObjectHelper.isEmpty(expression)) {
        return integration;
    }

    try {
        final Configuration configuration = Configuration.builder()
                .jsonProvider(new JacksonJsonProvider(JsonUtils.copyObjectMapperConfiguration()))
                .mappingProvider(new JacksonMappingProvider(JsonUtils.copyObjectMapperConfiguration()))
                .build();

        DocumentContext json = JsonPath.using(configuration).parse(JsonUtils.writer().forType(Integration.class).writeValueAsString(integration));

        if (ObjectHelper.isEmpty(key)) {
            json.set(expression, value);
        } else {
            json.put(expression, key, value);
        }

        return JsonUtils.reader().forType(Integration.class).readValue(json.jsonString());
    } catch (IOException e) {
        throw new IllegalStateException("Failed to evaluate json path expression on integration object", e);
    }
}
 
Example 4
Source File: ResponseTemplateProcessor.java    From restdocs-wiremock with Apache License 2.0 6 votes vote down vote up
String replaceTemplateFields() {
    if (templateDescriptors.isEmpty()) {
        return responseBody;
    }

    DocumentContext documentContext = JsonPath.parse(responseBody);

    for (ResponseFieldTemplateDescriptor descriptor: templateDescriptors) {
        String expression = null;
        if (uriTemplate != null && !uriTemplate.getVariableNames().isEmpty()) {
            expression = preProcessUriTemplateVariableNameExpression(descriptor);
        } else if (descriptor.getUriTemplateVariableName() != null) {
            throw new IllegalArgumentException("Descriptor for field '" + descriptor.getPath() + "' specifies a 'replacedWithUriTemplateVariableValue' but no URI Template could be found in. " +
                    "Make sure to construct your request with the methods in org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders that use URI templates");
        }
        if (expression == null) {
            if (descriptor.getWireMockTemplateExpression() == null) {
                throw new IllegalArgumentException("Descriptor for field '" + descriptor.getPath() + "' contains no replacedWithWireMockTemplateExpression");
            }
            expression = "{{" + descriptor.getWireMockTemplateExpression() + "}}";
        }
        documentContext.set(descriptor.getPath(), expression);
    }
    return documentContext.jsonString();
}
 
Example 5
Source File: GridSearchTuningAlgorithm.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private DetectionConfigDTO makeConfigFromParameters(Map<String, Number> currentParameters) throws IOException {
  DocumentContext jsonContext = JsonPath.parse(this.jsonProperties);
  // Replace parameters using json path
  for (Map.Entry<String, Number> entry : currentParameters.entrySet()) {
    String path = entry.getKey();
    Number value = entry.getValue();
    jsonContext.set(path, value);
  }
  Map<String, Object> properties = OBJECT_MAPPER.readValue(jsonContext.jsonString(), Map.class);
  DetectionConfigDTO config = new DetectionConfigDTO();
  config.setId(Long.MAX_VALUE);
  config.setName("preview");
  config.setDescription("previewing the detection");
  config.setProperties(properties);

  return config;
}
 
Example 6
Source File: JSONIOTest.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
@Test
public void updateVersions () throws ManipulationException, IOException
{
    String modifyPath = "$..version";
    DocumentContext doc = jsonIO.parseJSON( pluginFile );
    doc.set( modifyPath, "1.3.0.rebuild-1" );

    logger.debug ("Modified {} ", doc.jsonString());

    File target = tf.newFile();

    jsonIO.writeJSON( target, doc );

    assertFalse( doc.jsonString().contains( "1.2.2-SNAPSHOT" ) );
    assertTrue ( doc.jsonString().contains( "1.3.0.rebuild-1" ));
    assertFalse ( FileUtils.contentEquals( pluginFile, target ) );
}
 
Example 7
Source File: JSONIOTest.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
@Test
public void updateURL () throws ManipulationException, IOException
{
    String modifyPath = "$.repository.url";
    DocumentContext doc = jsonIO.parseJSON( pluginFile );
    doc.set( modifyPath, "https://maven.repository.redhat.com/ga/" );

    logger.debug ("Modified {} ", doc.jsonString());

    File target = tf.newFile();

    jsonIO.writeJSON( target, doc );

    assertTrue ( doc.jsonString().contains( "https://maven.repository.redhat.com/ga/" ));
    assertTrue ( doc.jsonString().contains( "1.2.2-SNAPSHOT" ));
    assertFalse ( FileUtils.contentEquals( pluginFile, target ) );
}
 
Example 8
Source File: JSONIOTest.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
@Test (expected = ManipulationException.class)
public void updateWithInvalidPath () throws ManipulationException
{
    String modifyPath = "$.I.really.do.not.exist.repository.url";
    try
    {
        DocumentContext doc = jsonIO.parseJSON( pluginFile );
        doc.set( modifyPath, "https://maven.repository.redhat.com/ga/" );
    }
    catch (JsonPathException e)
    {
        throw new ManipulationException( "Caught JsonPath", e );
    }
}
 
Example 9
Source File: JSONManipulator.java    From pom-manipulation-ext with Apache License 2.0 4 votes vote down vote up
void internalApplyChanges( Project project, JSONState.JSONOperation operation ) throws ManipulationException
{
    File target = new File( project.getPom().getParentFile(), operation.getFile() );

    logger.info( "Attempting to start JSON update to file {} with xpath {} and replacement '{}' ",
                 target, operation.getXPath(), operation.getUpdate() );

    DocumentContext dc = null;
    try
    {
        if ( !target.exists() )
        {
            logger.error( "Unable to locate JSON file {} ", target );
            throw new ManipulationException( "Unable to locate JSON file {}", target );
        }

        dc = jsonIO.parseJSON( target );

        List<?> o = dc.read( operation.getXPath() );
        if ( o.size() == 0 )
        {
            if ( project.isIncrementalPME() )
            {
                logger.warn ("Did not locate JSON using XPath " + operation.getXPath() );
                return;
            }
            else
            {
                logger.error( "XPath {} did not find any expressions within {} ", operation.getXPath(), operation.getFile() );
                throw new ManipulationException( "XPath did not resolve to a valid value" );
            }
        }

        if ( isEmpty( operation.getUpdate() ) )
        {
            // Delete
            logger.info( "Deleting {} on {}", operation.getXPath(), dc );
            dc.delete( operation.getXPath() );
        }
        else
        {
            // Update
            logger.info( "Updating {} on {}", operation.getXPath(), dc );
            dc.set( operation.getXPath(), operation.getUpdate() );
        }

        jsonIO.writeJSON( target, dc );
    }
    catch ( JsonPathException e )
    {
        logger.error( "Caught JSON exception processing file {}, document context {} ", target, dc, e );
        throw new ManipulationException( "Caught JsonPath", e );
    }
}
 
Example 10
Source File: JsonPathSetEvaluator.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public DocumentContext updateAttribute(DocumentContext documentContext, JsonPath jsonPath, Object value) {
    return documentContext.set(jsonPath, value);
}