Java Examples for groovy.json.JsonSlurper

The following java examples will help you to understand the usage of groovy.json.JsonSlurper. These source code samples are taken from different open source projects.

Example 1
Project: hale-master  File: JsonValueRepresentation.java View source code
@Override
public Object getValueRepresentation(Value value) {
    if (value == null) {
        return null;
    }
    if (value.isRepresentedAsDOM()) {
        // try conversion using complex value mechanism
        Object intern = value.getValue();
        if (intern == null) {
            return null;
        }
        ComplexValueDefinition cdv = ComplexValueExtension.getInstance().getDefinition(intern.getClass());
        if (cdv != null && cdv.getJsonConverter() != null) {
            return cdv.getJsonConverter().toJson(intern);
        }
        // fall-back to generic XML-JSON conversion
        Element element = value.getDOMRepresentation();
        if (element == null) {
            return null;
        } else {
            String json = null;
            try {
                String xmlString = XmlUtil.serialize(element, false);
                try (StringReader xmlReader = new StringReader(xmlString);
                    StringWriter jsonWriter = new StringWriter()) {
                    JsonXML.toJson(xmlReader, jsonWriter);
                    json = jsonWriter.toString();
                }
            } catch (Exception e) {
                log.error("Failed to created JSON representation of value", e);
                return null;
            }
            Object res = new JsonSlurper().parseText(json);
            return res;
        }
    } else {
        return value.getStringRepresentation();
    }
}
Example 2
Project: pact-master  File: Defect266Test.java View source code
@Pact(provider = "266_provider", consumer = "test_consumer")
public RequestResponsePact getUsersFragment(PactDslWithProvider builder) {
    Map<String, Map<String, Object>> matchers = (Map<String, Map<String, Object>>) new JsonSlurper().parseText("{" + "\"$.body[0][*].userName\": {\"match\": \"type\"}," + "\"$.body[0][*].id\": {\"regex\": \"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\"}," + "\"$.body[0]\": {\"match\": \"type\", \"max\": 5}," + "\"$.body[0][*].email\": {\"match\": \"type\"}" + "}");
    DslPart body = new PactDslJsonArray().maxArrayLike(5).uuid("id").stringType("userName").stringType("email").closeObject();
    RequestResponsePact pact = builder.given("a user with an id named 'user' exists").uponReceiving("get all users for max").path("/idm/user").method("GET").willRespondWith().status(200).body(body).toPact();
    assertThat(pact.getInteractions().get(0).getResponse().getMatchingRules(), is(equalTo(matchers)));
    return pact;
}
Example 3
Project: liferay-portal-master  File: LiferayOSGiDefaultsPlugin.java View source code
private void _checkJsonVersion(Project project, String fileName) {
    File file = project.file(fileName);
    if (!file.exists()) {
        return;
    }
    JsonSlurper jsonSlurper = new JsonSlurper();
    Map<String, Object> map = (Map<String, Object>) jsonSlurper.parse(file);
    String jsonVersion = (String) map.get("version");
    if (Validator.isNotNull(jsonVersion) && !jsonVersion.equals(String.valueOf(project.getVersion()))) {
        throw new GradleException("Version in " + fileName + " must match project version");
    }
}
Example 4
Project: gradle-aws-plugin-master  File: AWSElasticBeanstalkCreateConfigurationTemplateTask.java View source code
List<ConfigurationOptionSetting> loadConfigurationOptions(String json) {
    List<ConfigurationOptionSetting> options = new ArrayList<>();
    @SuppressWarnings("unchecked") Collection<Map<String, Object>> c = (Collection<Map<String, Object>>) new groovy.json.JsonSlurper().parseText(json);
    c.forEach( it -> options.add(new ConfigurationOptionSetting((String) it.get("Namespace"), (String) it.get("OptionName"), (String) it.get("Value"))));
    return options;
}
Example 5
Project: spring-xd-master  File: TwitterSearchChannelAdapter.java View source code
/*
	 * Unwrap and split the search results into individual tweets. Advance the cursor ("since_id") for the next query.
	 * To avoid rate limit errors, wait at least 2 seconds (maximum rate according to twitter is 450/15 min or once every 2 seconds).
	 * If no data
	 * is returned, wait 10 seconds.
	 */
@Override
protected void doSendLine(String line) {
    ObjectMapper mapper = new ObjectMapper();
    JsonSlurper jsonSlurper = new JsonSlurper();
    @SuppressWarnings("unchecked") Map<String, List<Map<String, ?>>> map = (Map<String, List<Map<String, ?>>>) jsonSlurper.parseText(line);
    List<Map<String, ?>> statuses = map.get("statuses");
    for (Map<String, ?> tweet : statuses) {
        StringWriter sw = new StringWriter();
        try {
            mapper.writeValue(sw, tweet);
            sendMessage(MessageBuilder.withPayload(sw.toString()).build());
        } catch (JsonGenerationException ex) {
            logger.error("Failed to convert tweet to json: " + ex.getMessage());
            break;
        } catch (JsonMappingException ex) {
            logger.error("Failed to convert tweet to json: " + ex.getMessage());
            break;
        } catch (IOException ex) {
            logger.error("Failed to convert tweet to json: " + ex.getMessage());
            break;
        }
    }
    if (!CollectionUtils.isEmpty(statuses)) {
        this.sinceId = ((Long) (statuses.get(statuses.size() - 1).get("id")));
        wait(2100);
    } else {
        wait(10000);
    }
}
Example 6
Project: json-benchmarks-master  File: SerializationBenchmarks.java View source code
@Setup(Level.Iteration)
public void setup() throws JsonParseException, JsonMappingException, IOException {
    String resource = Helper.getResource(resourceName + ".json");
    if (dataStyle == DATA_STYLE_POJO) {
        switch(resourceName) {
            case RESOURCE_CITYS:
                data = jacksonMapper.readValue(resource, CityInfo[].class);
                break;
            case RESOURCE_REPOS:
                data = jacksonMapper.readValue(resource, Repo[].class);
                break;
            case RESOURCE_USER:
                data = jacksonMapper.readValue(resource, UserProfile.class);
                break;
            case RESOURCE_REQUEST:
                data = jacksonMapper.readValue(resource, Request.class);
                break;
        }
        needCastToMap = false;
    } else {
        data = new JsonSlurper().parseText(resource);
        needCastToMap = Arrays.asList(RESOURCE_USER, RESOURCE_REQUEST).contains(resourceName);
    }
}
Example 7
Project: gradle-master  File: BuildOperationTrace.java View source code
private static List<BuildOperationRecord> readLogToTreeRoots(File logFile) {
    try {
        final JsonSlurper slurper = new JsonSlurper();
        final List<BuildOperationRecord> roots = new ArrayList<BuildOperationRecord>();
        final Map<Object, SerializedOperationStart> pending = new HashMap<Object, SerializedOperationStart>();
        final Map<Object, List<BuildOperationRecord>> childrens = new HashMap<Object, List<BuildOperationRecord>>();
        Files.asCharSource(logFile, Charsets.UTF_8).readLines(new LineProcessor<Void>() {

            @Override
            public boolean processLine(String line) throws IOException {
                Map<String, ?> map = uncheckedCast(slurper.parseText(line));
                if (map.containsKey("startTime")) {
                    SerializedOperationStart serialized = new SerializedOperationStart(map);
                    pending.put(serialized.id, serialized);
                    childrens.put(serialized.id, new LinkedList<BuildOperationRecord>());
                } else {
                    SerializedOperationFinish finish = new SerializedOperationFinish(map);
                    SerializedOperationStart start = pending.remove(finish.id);
                    assert start != null;
                    List<BuildOperationRecord> children = childrens.remove(finish.id);
                    assert children != null;
                    Map<String, ?> detailsMap = uncheckedCast(start.details);
                    Map<String, ?> resultMap = uncheckedCast(finish.result);
                    BuildOperationRecord record = new BuildOperationRecord(start.id, start.parentId, start.displayName, start.startTime, finish.endTime, detailsMap == null ? null : Collections.unmodifiableMap(detailsMap), start.detailsClassName, resultMap == null ? null : Collections.unmodifiableMap(resultMap), finish.resultClassName, finish.failureMsg, children);
                    if (start.parentId == null) {
                        roots.add(record);
                    } else {
                        List<BuildOperationRecord> parentChildren = childrens.get(start.parentId);
                        assert parentChildren != null;
                        parentChildren.add(record);
                    }
                }
                return true;
            }

            @Override
            public Void getResult() {
                return null;
            }
        });
        assert pending.isEmpty();
        return roots;
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
Example 8
Project: FollowTheBitcoin-master  File: CoinBaseOAuth.java View source code
public boolean refreshTokens(String refreshToken) {
    if (refreshToken == null) {
        return false;
    }
    String postContent = "";
    try {
        URL tokenURL = new URL("https://coinbase.com/oauth/token");
        HttpURLConnection uc = (HttpURLConnection) tokenURL.openConnection();
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);
        postContent = "grant_type=refresh_token" + "&refresh_token=" + refreshToken + "&redirect_uri=" + CALLBACK_URL + "&client_id=" + COINBASE_CLIENT_ID + "&client_secret=" + COINBASE_CLIENT_SECRET;
        uc.getOutputStream().write(postContent.getBytes());
        uc.connect();
        JsonSlurper slurper = new JsonSlurper();
        // TODO cleanup
        Map m = (Map) slurper.parse(new InputStreamReader(uc.getInputStream()));
        long expire = System.currentTimeMillis() + ((((Number) m.get("expires_in")).longValue() * 1000));
        saveToken((String) m.get("access_token"), "access_token");
        saveToken((String) m.get("refresh_token"), "refresh_token");
        saveToken(Long.toString(expire), "expire");
        Platform.runLater(() -> accessToken.setValue((String) m.get("access_token")));
        return true;
    } catch (IOException e) {
        Platform.runLater(() -> accessToken.setValue(""));
        System.out.println(postContent);
        e.printStackTrace();
    }
    return false;
}
Example 9
Project: entermedia-core-master  File: BaseWebPageRequest.java View source code
@Override
public Map getJsonRequest() {
    Map jsonRequest = (Map) getPageValue("_jsonRequest");
    if (jsonRequest == null && getRequest() != null) {
        JsonSlurper slurper = new JsonSlurper();
        try {
            Reader reader = getRequest().getReader();
            if (reader != null) {
                //this is real, the other way is just for t
                jsonRequest = (Map) slurper.parse(reader);
                putPageValue("_jsonRequest", jsonRequest);
            }
        } catch (Throwable ex) {
            putPageValue("_jsonRequest", new HashMap());
        }
    }
    return jsonRequest;
}
Example 10
Project: openicf-master  File: ScriptedConnectorTest.java View source code
// =======================================================================
// Search Operation Test
// =======================================================================
@Test
public void testFilterTranslator() throws Exception {
    Filter left = startsWith(AttributeBuilder.build("attributeString", "reti"));
    left = and(left, contains(AttributeBuilder.build("attributeString", "pipi")));
    left = and(left, endsWith(AttributeBuilder.build("attributeString", "ter")));
    Filter right = lessThanOrEqualTo(AttributeBuilder.build("attributeInteger", 42));
    right = or(right, lessThan(AttributeBuilder.build("attributeFloat", Float.MAX_VALUE)));
    right = or(right, greaterThanOrEqualTo(AttributeBuilder.build("attributeDouble", Double.MIN_VALUE)));
    right = or(right, greaterThan(AttributeBuilder.build("attributeLong", Long.MIN_VALUE)));
    right = and(right, not(equalTo(AttributeBuilder.build("attributeByte", new Byte("33")))));
    ToListResultsHandler handler = new ToListResultsHandler();
    SearchResult result = getFacade(TEST_NAME).search(TEST, and(left, right), handler, null);
    Assert.assertEquals(handler.getObjects().size(), 10);
    Assert.assertNotNull(result.getPagedResultsCookie());
    Map queryMap = (Map) new JsonSlurper().parseText(result.getPagedResultsCookie());
    assertThat(queryMap).contains(entry("operation", "AND"));
    left = and(left, containsAllValues(AttributeBuilder.build("attributeStringMultivalue", "value1", "value2")));
    try {
        handler = new ToListResultsHandler();
        getFacade(TEST_NAME).search(TEST, and(left, right), handler, null);
        fail("containsAllValues should raise exception if not implemented");
    } catch (UnsupportedOperationException e) {
        Assert.assertEquals(e.getMessage(), "ContainsAllValuesFilter transformation is not supported");
    }
}
Example 11
Project: pact-jvm-master  File: Defect266Test.java View source code
@Pact(provider = "266_provider", consumer = "test_consumer")
public RequestResponsePact getUsersFragment(PactDslWithProvider builder) {
    Map<String, Map<String, Object>> matchers = (Map<String, Map<String, Object>>) new JsonSlurper().parseText("{" + "\"$.body[0][*].userName\": {\"match\": \"type\"}," + "\"$.body[0][*].id\": {\"match\": \"regex\", \"regex\": \"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\"}," + "\"$.body[0]\": {\"match\": \"type\", \"max\": 5}," + "\"$.body[0][*].email\": {\"match\": \"type\"}" + "}");
    DslPart body = new PactDslJsonArray().maxArrayLike(5).uuid("id").stringType("userName").stringType("email").closeObject();
    RequestResponsePact pact = builder.given("a user with an id named 'user' exists").uponReceiving("get all users for max").path("/idm/user").method("GET").willRespondWith().status(200).body(body).toPact();
    assertThat(pact.getInteractions().get(0).getResponse().getMatchingRules(), is(equalTo(matchers)));
    return pact;
}
Example 12
Project: detective-master  File: JsonBuilderTask.java View source code
@Override
protected void doExecute(Parameters config, Parameters output) {
    String json = this.readAsString(config, "jsoninput", null, false, "jsoninput is missing");
    output.put("json", new JsonSlurper().parseText(json));
}
Example 13
Project: easyweb-master  File: Command.java View source code
public Object getJsonObj() {
    try {
        return new JsonSlurper().parseText(new String(this.data, "utf-8"));
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
Example 14
Project: Crud2Go-master  File: JsonParser.java View source code
@Override
protected Object parseData(Reader reader) {
    return new JsonSlurper().parse(reader);
}
Example 15
Project: json-parsers-benchmark-master  File: OldJsonGroovySlurper.java View source code
private Object parse(String str) throws Exception {
    JsonSlurper slurper = new JsonSlurper();
    return slurper.parseText(str);
}
Example 16
Project: jenkernetes-master  File: KubernetesClient.java View source code
private static Object parse(CloseableHttpResponse resp) throws IOException {
    try {
        return (new JsonSlurper()).parse((new InputStreamReader(resp.getEntity().getContent())));
    } finally {
        resp.close();
    }
}
Example 17
Project: groovy-master  File: JsonSlurper.java View source code
/**
     * Max size before Slurper starts to use windowing buffer parser.
     * @since 2.3
     * @return JsonSlurper
     */
public JsonSlurper setMaxSizeForInMemory(int maxSizeForInMemory) {
    this.maxSizeForInMemory = maxSizeForInMemory;
    return this;
}
Example 18
Project: httpbuilder-master  File: ParserRegistry.java View source code
/**
     * Default parser used to decode a JSON response.
     * @see ContentType#JSON
     * @param resp
     * @return
     * @throws IOException
     */
public Object parseJSON(HttpResponse resp) throws IOException {
    //String jsonTxt = DefaultGroovyMethods.getText( parseText( resp ) );
    return new JsonSlurper().parse(parseText(resp));
}