com.jayway.jsonpath.Configuration Java Examples

The following examples show how to use com.jayway.jsonpath.Configuration. 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: EnrichIntegrationJsonPathTestCase.java    From micro-integrator with Apache License 2.0 7 votes vote down vote up
private void setJsonPathConfiguration() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new GsonJsonProvider(new GsonBuilder().serializeNulls().create());
        private final MappingProvider mappingProvider = new GsonMappingProvider();

        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #2
Source File: JsonFunctions.java    From Quicksql with MIT License 6 votes vote down vote up
public static String jsonRemove(JsonValueContext input, String... pathSpecs) {
  try {
    DocumentContext ctx = JsonPath.parse(input.obj,
        Configuration
            .builder()
            .options(Option.SUPPRESS_EXCEPTIONS)
            .jsonProvider(JSON_PATH_JSON_PROVIDER)
            .mappingProvider(JSON_PATH_MAPPING_PROVIDER)
            .build());
    for (String pathSpec : pathSpecs) {
      if ((pathSpec != null) && (ctx.read(pathSpec) != null)) {
        ctx.delete(pathSpec);
      }
    }
    return ctx.jsonString();
  } catch (Exception ex) {
    throw RESOURCE.invalidInputForJsonRemove(
        input.toString(), Arrays.toString(pathSpecs)).ex();
  }
}
 
Example #3
Source File: FastJsonReader.java    From hop with Apache License 2.0 6 votes vote down vote up
private Configuration deleteOptionFromConfiguration( Configuration config, Option option ) {
  Configuration currentConf = config;
  if ( currentConf != null ) {
    EnumSet<Option> currentOptions = EnumSet.noneOf( Option.class );
    currentOptions.addAll( currentConf.getOptions() );
    if ( currentOptions.remove( option ) ) {
      if ( log.isDebug() ) {
        log.logDebug( BaseMessages.getString( PKG, "JsonReader.Debug.Configuration.Option.Delete", option ) );
      }
      currentConf = Configuration.defaultConfiguration().addOptions( currentOptions.toArray( new Option[currentOptions.size()] ) );
    }
  }
  if ( log.isDebug() ) {
    log.logDebug( BaseMessages.getString( PKG, "JsonReader.Debug.Configuration.Options", currentConf.getOptions() ) );
  }
  return currentConf;
}
 
Example #4
Source File: ServiceIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenStructure_whenRequestingHighestRevenueMovieTitle_thenSucceed() {
    DocumentContext context = JsonPath.parse(jsonString);
    List<Object> revenueList = context.read("$[*]['box office']");
    Integer[] revenueArray = revenueList.toArray(new Integer[0]);
    Arrays.sort(revenueArray);

    int highestRevenue = revenueArray[revenueArray.length - 1];
    Configuration pathConfiguration = Configuration.builder()
        .options(Option.AS_PATH_LIST)
        .build();
    List<String> pathList = JsonPath.using(pathConfiguration)
        .parse(jsonString)
        .read("$[?(@['box office'] == " + highestRevenue + ")]");

    Map<String, String> dataRecord = context.read(pathList.get(0));
    String title = dataRecord.get("title");

    assertEquals("Skyfall", title);
}
 
Example #5
Source File: JSONRecordFactory.java    From rmlmapper-java with MIT License 6 votes vote down vote up
/**
 * This method returns the records from a JSON document based on an iterator.
 * @param document the document from which records need to get.
 * @param iterator the used iterator.
 * @return a list of records.
 * @throws IOException
 */
@Override
List<Record> getRecordsFromDocument(Object document, String iterator) throws IOException {
    List<Record> records = new ArrayList<>();

    Configuration conf = Configuration.builder()
            .options(Option.AS_PATH_LIST).build();

    try {
        List<String> pathList = JsonPath.using(conf).parse(document).read(iterator);

        for(String p :pathList) {
            records.add(new JSONRecord(document, p));
        }
    } catch(PathNotFoundException e) {
        logger.warn(e.getMessage(), e);
    }

    return records;
}
 
Example #6
Source File: JsonPathTest.java    From light with Apache License 2.0 6 votes vote down vote up
@Override
public Object map(Object currentValue, Configuration configuration) {
    if(currentValue instanceof Map) {
        ((Map) currentValue).remove("roles");
        ((Map) currentValue).remove("credential");
        ((Map) currentValue).remove("createDate");
        ((Map) currentValue).remove("host");
        ((Map) currentValue).remove("out_Create");
        String rid = (String)((Map) currentValue).get("@rid");
        if(userMap.get(rid) == null) {
            userMap.put(rid, currentValue);
        }
    } else if(currentValue instanceof String) {
        currentValue = userMap.get((String)currentValue);
    }
    return currentValue;
}
 
Example #7
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 #8
Source File: MaskTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void runOnceBeforeClass() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new JacksonJsonProvider();
        private final MappingProvider mappingProvider = new JacksonMappingProvider();

        @Override
        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        @Override
        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        @Override
        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #9
Source File: JsonPathStartupHookProvider.java    From light-4j with Apache License 2.0 6 votes vote down vote up
static void configJsonPath() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new JacksonJsonProvider();
        private final MappingProvider mappingProvider = new JacksonMappingProvider();

        @Override
        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        @Override
        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        @Override
        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #10
Source File: EnrichIntegrationJsonPathTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
private void setJsonPathConfiguration() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new GsonJsonProvider(new GsonBuilder().serializeNulls().create());
        private final MappingProvider mappingProvider = new GsonMappingProvider();

        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #11
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * A JSONObject can be created from another JSONObject plus a list of names.
 * In this test, some of the starting JSONObject keys are not in the 
 * names list.
 */
@Test
public void jsonObjectByNames() {
    String str = 
        "{"+
            "\"trueKey\":true,"+
            "\"falseKey\":false,"+
            "\"nullKey\":null,"+
            "\"stringKey\":\"hello world!\","+
            "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+
            "\"intKey\":42,"+
            "\"doubleKey\":-23.45e67"+
        "}";
    String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"};
    JSONObject jsonObject = new JSONObject(str);

    // validate JSON
    JSONObject jsonObjectByName = new JSONObject(jsonObject, keys);
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString());
    assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4);
    assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey")));
    assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey")));
    assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey")));
    assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObjectByName.query("/doubleKey")));
}
 
Example #12
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * JSONObjects can be built from a Map<String, Object>. 
 * In this test all of the map entries are valid JSON types.
 */
@Test
public void jsonObjectByMap() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("trueKey", new Boolean(true));
    map.put("falseKey", new Boolean(false));
    map.put("stringKey", "hello world!");
    map.put("escapeStringKey", "h\be\tllo w\u1234orld!");
    map.put("intKey", new Long(42));
    map.put("doubleKey", new Double(-23.45e67));
    JSONObject jsonObject = new JSONObject(map);

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
    assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
    assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
    assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey")));
    assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
    assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
}
 
Example #13
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * JSONObjects can be built from a Map<String, Object>. 
 * In this test the map entries are not valid JSON types.
 * The actual conversion is kind of interesting.
 */
@Test
public void jsonObjectByMapWithUnsupportedValues() {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    // Just insert some random objects
    jsonMap.put("key1", new CDL());
    jsonMap.put("key2", new Exception());

    JSONObject jsonObject = new JSONObject(jsonMap);

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
    assertTrue("expected 0 key1 items", ((Map<?,?>)(JsonPath.read(doc, "$.key1"))).size() == 0);
    assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2")));
}
 
Example #14
Source File: JSONIO.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
public DocumentContext parseJSON( File jsonFile ) throws ManipulationException
{
    if ( jsonFile == null || !jsonFile.exists() )
    {
        throw new ManipulationException( "JSON File not found" );
    }

    this.encoding = detectEncoding( jsonFile );
    this.charset = Charset.forName( encoding.getJavaName() );
    this.jsonFile = jsonFile;
    this.eol = detectEOL( jsonFile );

    DocumentContext doc;

    try ( FileInputStream in = new FileInputStream( jsonFile ) )
    {
        Configuration conf = Configuration.builder().options( Option.ALWAYS_RETURN_LIST ).build();
        doc = JsonPath.using( conf ).parse( in, charset.name() );
    }
    catch ( IOException e )
    {
        logger.error( "Unable to parse JSON File", e );
        throw new ManipulationException( "Unable to parse JSON File", e );
    }
    return doc;
}
 
Example #15
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * Exercise the JSONObject from resource bundle functionality.
 * The test resource bundle is uncomplicated, but provides adequate test coverage.
 */
@Test
public void jsonObjectByResourceBundle() {
    JSONObject jsonObject = new
            JSONObject("org.json.junit.data.StringsResourceBundle",
                    Locale.getDefault());

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
    assertTrue("expected 2 greetings items", ((Map<?,?>)(JsonPath.read(doc, "$.greetings"))).size() == 2);
    assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello")));
    assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world")));
    assertTrue("expected 2 farewells items", ((Map<?,?>)(JsonPath.read(doc, "$.farewells"))).size() == 2);
    assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later")));
    assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator")));
}
 
Example #16
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * Populate a JSONArray from a JSONObject names() method.
 * Confirm that it contains the expected names.
 */
@Test
public void jsonObjectNamesToJsonAray() {
    String str = 
        "{"+
            "\"trueKey\":true,"+
            "\"falseKey\":false,"+
            "\"stringKey\":\"hello world!\","+
        "}";

    JSONObject jsonObject = new JSONObject(str);
    JSONArray jsonArray = jsonObject.names();

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
    assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3);
    assertTrue("expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1);
    assertTrue("expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1);
    assertTrue("expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1);
}
 
Example #17
Source File: JSONArrayTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * Confirm the creation of a JSONArray from an array of ints
 */
@Test
public void objectArrayVsIsArray() {
    int[] myInts = { 1, 2, 3, 4, 5, 6, 7 };
    Object myObject = myInts;
    JSONArray jsonArray = new JSONArray(myObject);

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
    assertTrue("expected 7 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 7);
    assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0")));
    assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1")));
    assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2")));
    assertTrue("expected 4", Integer.valueOf(4).equals(jsonArray.query("/3")));
    assertTrue("expected 5", Integer.valueOf(5).equals(jsonArray.query("/4")));
    assertTrue("expected 6", Integer.valueOf(6).equals(jsonArray.query("/5")));
    assertTrue("expected 7", Integer.valueOf(7).equals(jsonArray.query("/6")));
}
 
Example #18
Source File: PropertiesBuilder.java    From querqy with Apache License 2.0 6 votes vote down vote up
public PropertiesBuilder() {
    objectMapper = new ObjectMapper();
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
    objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true);



    jsonPathConfiguration = Configuration.builder()
            .jsonProvider(new JacksonJsonProvider())
            .mappingProvider(new JacksonMappingProvider()).build();
    jsonPathConfiguration.addOptions(Option.ALWAYS_RETURN_LIST);

    primitiveProperties = new HashMap<>();
    jsonObjectString =  new StringBuilder();

}
 
Example #19
Source File: InstructionsPropertiesTest.java    From querqy with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatches() {

    final Map<String, Object> props = new HashMap<>();
    props.put("p1", 1);
    props.put("p2", "2");
    props.put("p3", Arrays.asList("3", 33));

    final Map<String, Object> p4 = new HashMap<>();
    p4.put("p41", "41");
    p4.put("p42", 42);
    props.put("p4", p4);

    final InstructionsProperties instructionsProperties = new InstructionsProperties(props, Configuration.builder()
            .jsonProvider(new JacksonJsonProvider()).mappingProvider(new JacksonMappingProvider()).build());

    assertTrue(instructionsProperties.matches("$[?(@.p2 == '2')]"));
    assertFalse(instructionsProperties.matches("$.[?(@.p2 == 1)]"));

    assertTrue(instructionsProperties.matches("$.p3[?(@ == '3')]"));
    assertTrue(instructionsProperties.matches("$.p4[?(@.p42 == 42)]"));
    assertTrue(instructionsProperties.matches("$.p4[?(@.p42 > 5)]"));


}
 
Example #20
Source File: TestSchemaValidator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() {
    // Set GsonJsonProvider as the default Jayway JSON path default configuration
    // Which is set by synapse-core at runtime of the server
    Configuration.setDefaults(new Configuration.Defaults() {
        private final JsonProvider jsonProvider = new GsonJsonProvider(new GsonBuilder().serializeNulls().create());
        private final MappingProvider mappingProvider = new GsonMappingProvider();

        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #21
Source File: JsonFunctions.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static String jsonRemove(JsonValueContext input, String... pathSpecs) {
  try {
    DocumentContext ctx = JsonPath.parse(input.obj,
        Configuration
            .builder()
            .options(Option.SUPPRESS_EXCEPTIONS)
            .jsonProvider(JSON_PATH_JSON_PROVIDER)
            .mappingProvider(JSON_PATH_MAPPING_PROVIDER)
            .build());
    for (String pathSpec : pathSpecs) {
      if ((pathSpec != null) && (ctx.read(pathSpec) != null)) {
        ctx.delete(pathSpec);
      }
    }
    return ctx.jsonString();
  } catch (Exception ex) {
    throw RESOURCE.invalidInputForJsonRemove(
        input.toString(), Arrays.toString(pathSpecs)).ex();
  }
}
 
Example #22
Source File: AbstractCommentRule.java    From light with Apache License 2.0 6 votes vote down vote up
@Override
public Object map(Object currentValue, Configuration configuration) {
    if(currentValue instanceof Map) {
        ((Map) currentValue).remove("roles");
        ((Map) currentValue).remove("email");
        ((Map) currentValue).remove("credential");
        ((Map) currentValue).remove("createDate");
        ((Map) currentValue).remove("host");
        ((Map) currentValue).remove("out_Create");
        ((Map) currentValue).remove("out_Update");
        ((Map) currentValue).remove("out_ReportSpam");
        ((Map) currentValue).remove("out_UpVote");
        ((Map) currentValue).remove("out_DownVote");
        String rid = (String)((Map) currentValue).get("@rid");
        if(userMap.get(rid) == null) {
            userMap.put(rid, currentValue);
        }
    } else if(currentValue instanceof String) {
        currentValue = userMap.get((String)currentValue);
    }
    return currentValue;
}
 
Example #23
Source File: LightServer.java    From light with Apache License 2.0 6 votes vote down vote up
static void configJsonPath() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new JacksonJsonProvider();
        private final MappingProvider mappingProvider = new JacksonMappingProvider();

        @Override
        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        @Override
        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        @Override
        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #24
Source File: JsonPathUtilsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testConfiguration()
{
    JsonPathUtils.setJacksonConfiguration();
    Configuration configuration = Configuration.defaultConfiguration();
    Assertions.assertTrue(configuration.jsonProvider() instanceof JacksonJsonProvider);
    Assertions.assertTrue(configuration.mappingProvider() instanceof JacksonMappingProvider);
}
 
Example #25
Source File: FieldLevelEncryption.java    From client-encryption-java with MIT License 5 votes vote down vote up
/**
 * Specify the JSON engine to be used.
 * @param jsonEngine A {@link com.mastercard.developer.json.JsonEngine} instance
 */
public static synchronized Configuration withJsonEngine(JsonEngine jsonEngine) {
    FieldLevelEncryption.jsonEngine = jsonEngine;
    FieldLevelEncryption.jsonPathConfig = new Configuration.ConfigurationBuilder()
            .jsonProvider(jsonEngine.getJsonProvider())
            .options(Option.SUPPRESS_EXCEPTIONS)
            .build();
    return jsonPathConfig;
}
 
Example #26
Source File: JsonPathTest.java    From light with Apache License 2.0 5 votes vote down vote up
@Override
public Object map(Object currentValue, Configuration configuration) {
    String value = null;
    if(currentValue instanceof Map) {
        value = (String) ((Map) currentValue).get("@rid");
    }
    return value;
}
 
Example #27
Source File: GeneratorResource.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
@PostMapping("/generate-application")
@Secured(AuthoritiesConstants.USER)
public ResponseEntity generateApplicationOnGit(@RequestBody String applicationConfiguration) throws Exception {
    log.info("Generating application on GitHub - .yo-rc.json: {}", applicationConfiguration);
    User user = userService.getUser();
    log.debug("Reading application configuration");
    Object document = Configuration.defaultConfiguration().jsonProvider().parse(applicationConfiguration);
    GitProvider provider = GitProvider.getGitProviderByValue(JsonPath.read(document, "$.git-provider"))
        .orElseThrow(() -> new Exception("No git provider"));
    String gitCompany = JsonPath.read(document, "$.git-company");
    String applicationName = JsonPath.read(document, "$.generator-jhipster.baseName");
    String repositoryName = JsonPath.read(document, "$.repository-name");
    String applicationId = UUID.randomUUID().toString();

    log.debug("Using provider: {} ({})", provider, JsonPath.read(document, "$.git-provider"));
    log.debug("Generating application in repository id={} - {} / {}", applicationId, gitCompany, repositoryName);
    this.logsService.addLog(applicationId, "Generating application in repository " + gitCompany + "/" +
        repositoryName);

    try {
        if (provider.equals(GitProvider.GITHUB)) {
            this.githubService.createGitProviderRepository(
                user, applicationId, applicationConfiguration, gitCompany, repositoryName);
        } else if (provider.equals(GitProvider.GITLAB)) {
            this.gitlabService.createGitProviderRepository(
                user, applicationId, applicationConfiguration, gitCompany, repositoryName);
        }

    } catch (Exception e) {
        log.error("Error generating application", e);
        this.logsService.addLog(applicationId, "An error has occurred: " + e.getMessage());
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity<>(applicationId, HttpStatus.CREATED);
}
 
Example #28
Source File: PluggableParameterOperatorJson.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Parameter operate(Runner runner, Map<String, Parameter> operands, String name, String resultant) throws Exception
{
	Parameter param1 = assertAndGetParameter(operands, "value");
    Parameter param2 = assertAndGetParameter(operands, "value2");
    
    Parameter result = new Parameter();
    
    try
    {        	        	
        for (int i = 0; i < param1.length(); i++)
        {
            String var1 = param1.get(i).toString();
            String var2 = param2.get(i).toString();
            
            // Retrieve JSON content
            GlobalLogger.instance().getSessionLogger().debug(TextEvent.Topic.USER, NAME_JSON_JPATH + ": JSON content is " + var1);
            GlobalLogger.instance().getSessionLogger().debug(TextEvent.Topic.USER, NAME_JSON_JPATH + ": JSON path is " + var2);
            
			      Object document = Configuration.defaultConfiguration().jsonProvider().parse(var1);
            Object path_result = JsonPath.read(document, var2);
            
            // Prepare result
            if( path_result instanceof JSONArray && ((JSONArray) path_result).size() > 0)
            {
            	for( int cptR=0 ; cptR!=((JSONArray) path_result).size() ; cptR++ )
            		result.add(((JSONArray) path_result).get(cptR).toString());
            }
            else
            	result.add(path_result.toString());
            
            GlobalLogger.instance().getSessionLogger().debug(TextEvent.Topic.USER, NAME_JSON_JPATH + ": JSON result is " + result.toString());
        }
    }
    catch (Exception e)
    {
    	throw e;
    }
    return result;
}
 
Example #29
Source File: JsonSourceMapper.java    From siddhi-map-json with Apache License 2.0 5 votes vote down vote up
private Event processCustomEvent(ReadContext readContext) {
    Configuration conf = Configuration.defaultConfiguration();
    Event event = new Event(streamAttributesSize);
    Object[] data = event.getData();
    Object childObject = readContext.read(DEFAULT_ENCLOSING_ELEMENT);
    readContext = JsonPath.using(conf).parse(childObject);
    Gson gsonWithNull = new GsonBuilder().serializeNulls().create();
    for (MappingPositionData mappingPositionData : this.mappingPositions) {
        int position = mappingPositionData.getPosition();
        Object mappedValue;
        try {
            mappedValue = readContext.read(mappingPositionData.getMapping());
            if (mappedValue == null) {
                data[position] = null;
            } else if (mappedValue instanceof Map) {
                data[position] = attributeConverter.getPropertyValue(gsonWithNull.toJson(mappedValue),
                        streamAttributes.get(position).getType());
            } else {
                data[position] = attributeConverter.getPropertyValue(mappedValue.toString(),
                        streamAttributes.get(position).getType());
            }
        } catch (PathNotFoundException e) {
            if (failOnMissingAttribute) {
                log.error("Json message " + childObject.toString() +
                        " contains missing attributes. Hence dropping the message.");
                return null;
            }
            data[position] = null;
        }
    }
    return event;
}
 
Example #30
Source File: SoapConnectorTemplate.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static ConnectorTemplate fetchSoapConnectorTemplateFromDeployment() {
    final Configuration configuration = Configuration.builder()//
        .jsonProvider(new JacksonJsonProvider(JsonUtils.copyObjectMapperConfiguration()))//
        .mappingProvider(new JacksonMappingProvider(JsonUtils.copyObjectMapperConfiguration()))//
        .build();

    final List<ConnectorTemplate> templates = JsonPath.using(configuration)
        .parse(SoapConnectorTemplate.class.getResourceAsStream("/io/syndesis/server/dao/deployment.json"))
        .read("$..[?(@['id'] == 'soap-connector-template')]", new TypeRef<List<ConnectorTemplate>>() {
            // type token pattern
        });

    return templates.get(0);
}