List of usage examples for com.fasterxml.jackson.databind JsonNode spliterator
default Spliterator<T> spliterator()
From source file:io.syndesis.dao.DeploymentDescriptorTest.java
@Test @SuppressWarnings({ "PMD.JUnitTestsShouldIncludeAssert", "PMD.JUnitTestContainsTooManyAsserts" }) public void deploymentDescriptorTakeCueFromConnectorDescriptor() { for (final JsonNode entry : deployment) { if ("connector".equals(entry.get("kind").asText())) { final String connectorId = entry.get("data").get("id").asText(); final JsonNode connectorData = entry.get("data"); final JsonNode connectorPropertiesJson = connectorData.get("properties"); final JsonNode actions = connectorData.get("actions"); StreamSupport.stream(actions.spliterator(), true).forEach(action -> { final String actionName = action.get("name").asText(); final String gav = action.get("camelConnectorGAV").asText(); assertThat(gav).as("Action `%s` does not have `camelConnectorGAV` property", actionName) .isNotEmpty();//from ww w . j a v a 2s .co m final String[] coordinates = gav.split(":"); final Set<String> names = mavenArtifactProvider.addArtifactToCatalog(camelCatalog, connectorCatalog, coordinates[0], coordinates[1], coordinates[2]); assertThat(names).as("Could not resolve artifact for Camel catalog with GAV: %s:%s:%s", (Object[]) coordinates).isNotEmpty(); final String scheme = action.get("camelConnectorPrefix").asText(); try { camelCatalog.asEndpointUri(scheme, new HashMap<>(), false); } catch (final URISyntaxException e) { fail("Action `%s` cannot be added to Camel context", actionName, e); } final String componentJsonSchemaFromCatalog = camelCatalog.componentJSonSchema(scheme); final JsonNode catalogedJsonSchema; try { catalogedJsonSchema = MAPPER.readTree(componentJsonSchemaFromCatalog); } catch (final IOException e) { fail("Unable to parse Camel component JSON schema", e); return;// never happens } final JsonNode component = catalogedJsonSchema.get("component"); final String groupId = component.get("groupId").asText(); final String artifactId = component.get("artifactId").asText(); final String version = component.get("version").asText(); assertThat(new String[] { groupId, artifactId, version }) .as("The scheme `%s` was resolved from a unexpected artifact", scheme) .isEqualTo(coordinates); final JsonNode componentPropertiesFromCatalog = catalogedJsonSchema.get("componentProperties"); assertConnectorProperties(connectorId, connectorPropertiesJson, componentPropertiesFromCatalog); assertActionProperties(connectorId, action, actionName, catalogedJsonSchema); assertActionDataShapes(connectorCatalog, action, actionName, coordinates); }); } } }
From source file:com.jaredjstewart.SampleSecurityManager.java
private Map<String, Role> readRoles(final JsonNode jsonNode) { if (jsonNode.get("roles") == null) { return Collections.EMPTY_MAP; }//w ww .ja v a 2 s .co m Map<String, Role> roleMap = new HashMap<>(); for (JsonNode rolesNode : jsonNode.get("roles")) { Role role = new Role(); role.name = rolesNode.get("name").asText(); String regionNames = null; String keys = null; JsonNode regionsNode = rolesNode.get("regions"); if (regionsNode != null) { if (regionsNode.isArray()) { regionNames = StreamSupport.stream(regionsNode.spliterator(), false).map(JsonNode::asText) .collect(Collectors.joining(",")); } else { regionNames = regionsNode.asText(); } } for (JsonNode operationsAllowedNode : rolesNode.get("operationsAllowed")) { String[] parts = operationsAllowedNode.asText().split(":"); String resourcePart = (parts.length > 0) ? parts[0] : null; String operationPart = (parts.length > 1) ? parts[1] : null; if (parts.length > 2) { regionNames = parts[2]; } if (parts.length > 3) { keys = parts[3]; } String regionPart = (regionNames != null) ? regionNames : "*"; String keyPart = (keys != null) ? keys : "*"; role.permissions.add(new ResourcePermission(resourcePart, operationPart, regionPart, keyPart)); } roleMap.put(role.name, role); if (rolesNode.has("serverGroup")) { role.serverGroup = rolesNode.get("serverGroup").asText(); } } return roleMap; }
From source file:jp.classmethod.aws.brian.BrianClient.java
@Override public List<String> listTriggerGroups() throws BrianClientException, BrianServerException { logger.debug("list trigger groups: {}"); HttpResponse httpResponse = null;/*from w w w . jav a2 s .c o m*/ try { URI uri = new URI(scheme, null, hostname, port, "/triggers", null, null); HttpUriRequest httpRequest = RequestBuilder.get().setUri(uri).build(); httpResponse = httpClientExecute(httpRequest); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("statusCode: {}", statusCode); if (statusCode == HttpStatus.SC_OK) { JsonNode tree = mapper.readTree(httpResponse.getEntity().getContent()); return StreamSupport.stream(tree.spliterator(), false).map(item -> item.textValue()) .collect(Collectors.toList()); } else if (statusCode >= 500) { throw new BrianServerException("status = " + statusCode); } else if (statusCode >= 400) { throw new BrianClientException("status = " + statusCode); } else { throw new Error("status = " + statusCode); } } catch (URISyntaxException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new BrianServerException(e); } catch (IllegalStateException e) { throw new Error(e); } finally { if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } }
From source file:jp.classmethod.aws.brian.BrianClient.java
@Override public List<String> listTriggers(String group) throws BrianClientException, BrianServerException { logger.debug("list triggers: {}", group); HttpResponse httpResponse = null;/*from w ww.j a v a 2s. c o m*/ try { String path = String.format("/triggers/%s", group); URI uri = new URI(scheme, null, hostname, port, path, null, null); HttpUriRequest httpRequest = RequestBuilder.get().setUri(uri).build(); httpResponse = httpClientExecute(httpRequest); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("statusCode: {}", statusCode); if (statusCode == HttpStatus.SC_OK) { JsonNode tree = mapper.readTree(httpResponse.getEntity().getContent()); return StreamSupport.stream(tree.spliterator(), false).map(item -> item.textValue()) .collect(Collectors.toList()); } else if (statusCode >= 500) { throw new BrianServerException("status = " + statusCode); } else if (statusCode >= 400) { throw new BrianClientException("status = " + statusCode); } else { throw new Error("status = " + statusCode); } } catch (URISyntaxException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new BrianServerException(e); } catch (IllegalStateException e) { throw new Error(e); } finally { if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } }
From source file:fi.vm.sade.eperusteet.ylops.service.ops.impl.OpetussuunnitelmaServiceImpl.java
private void fetchOrganisaatioNimet(OpetussuunnitelmaBaseDto opetussuunnitelmaDto) { for (OrganisaatioDto organisaatioDto : opetussuunnitelmaDto.getOrganisaatiot()) { Map<String, String> tekstit = new HashMap<>(); List<String> tyypit = new ArrayList<>(); JsonNode organisaatio = organisaatioService.getOrganisaatio(organisaatioDto.getOid()); if (organisaatio != null) { JsonNode nimiNode = organisaatio.get("nimi"); if (nimiNode != null) { Iterator<Map.Entry<String, JsonNode>> it = nimiNode.fields(); while (it.hasNext()) { Map.Entry<String, JsonNode> field = it.next(); tekstit.put(field.getKey(), field.getValue().asText()); }//ww w.j ava2 s . c o m } JsonNode tyypitNode = ofNullable(organisaatio.get("tyypit")) .orElse(organisaatio.get("organisaatiotyypit")); if (tyypitNode != null) { tyypit = StreamSupport.stream(tyypitNode.spliterator(), false).map(JsonNode::asText) .collect(Collectors.toList()); } } organisaatioDto.setNimi(new LokalisoituTekstiDto(tekstit)); organisaatioDto.setTyypit(tyypit); } }
From source file:fi.vm.sade.eperusteet.ylops.service.ops.impl.OpetussuunnitelmaServiceImpl.java
@Override @Transactional(readOnly = true)//from w ww .j a v a2s.c om public List<OpetussuunnitelmaJulkinenDto> getAllJulkiset(OpetussuunnitelmaQuery query) { List<Opetussuunnitelma> opetussuunnitelmat; if (query != null) { query.setTyyppi(Tyyppi.OPS); opetussuunnitelmat = findByQuery(query).stream().filter(ops -> ops.getTila() == Tila.JULKAISTU) .collect(Collectors.toList()); } else { opetussuunnitelmat = repository.findAllByTyyppiAndTilaIsJulkaistu(Tyyppi.OPS); } final List<OpetussuunnitelmaJulkinenDto> dtot = mapper.mapAsList(opetussuunnitelmat, OpetussuunnitelmaJulkinenDto.class); dtot.forEach(dto -> { for (KoodistoDto koodistoDto : dto.getKunnat()) { Map<String, String> tekstit = new HashMap<>(); KoodistoKoodiDto kunta = koodistoService.get("kunta", koodistoDto.getKoodiUri()); if (kunta != null) { for (KoodistoMetadataDto metadata : kunta.getMetadata()) { tekstit.put(metadata.getKieli(), metadata.getNimi()); } } koodistoDto.setNimi(new LokalisoituTekstiDto(tekstit)); } for (OrganisaatioDto organisaatioDto : dto.getOrganisaatiot()) { Map<String, String> tekstit = new HashMap<>(); List<String> tyypit = new ArrayList<>(); JsonNode organisaatio = organisaatioService.getOrganisaatio(organisaatioDto.getOid()); if (organisaatio != null) { JsonNode nimiNode = organisaatio.get("nimi"); if (nimiNode != null) { Iterator<Map.Entry<String, JsonNode>> it = nimiNode.fields(); while (it.hasNext()) { Map.Entry<String, JsonNode> field = it.next(); tekstit.put(field.getKey(), field.getValue().asText()); } } JsonNode tyypitNode = Optional.ofNullable(organisaatio.get("tyypit")) .orElse(organisaatio.get("organisaatiotyypit")); if (tyypitNode != null) { tyypit = StreamSupport.stream(tyypitNode.spliterator(), false).map(JsonNode::asText) .collect(Collectors.toList()); } } organisaatioDto.setNimi(new LokalisoituTekstiDto(tekstit)); organisaatioDto.setTyypit(tyypit); } }); return dtot; }
From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_Buckets.java
/** Builds a V2 bucket out of a V1 source * @param src_json/*from ww w .j a va2 s . c om*/ * @return * @throws JsonParseException * @throws JsonMappingException * @throws IOException * @throws ParseException */ protected static DataBucketBean getBucketFromV1Source(final JsonNode src_json) throws JsonParseException, JsonMappingException, IOException, ParseException { // (think we'll use key instead of _id): //final String _id = safeJsonGet(JsonUtils._ID, src_json).asText(); final String key = safeJsonGet("key", src_json).asText(); final String created = safeJsonGet("created", src_json).asText(); final String modified = safeJsonGet("modified", src_json).asText(); final String title = safeJsonGet("title", src_json).asText(); final String description = safeJsonGet("description", src_json).asText(); final String owner_id = safeJsonGet("ownerId", src_json).asText(); final JsonNode tags = safeJsonGet("tags", src_json); // collection of strings //final JsonNode comm_ids = safeJsonGet("communityIds", src_json); // collection of strings final JsonNode px_pipeline = safeJsonGet("processingPipeline", src_json); // collection of JSON objects, first one should have data_bucket final JsonNode px_pipeline_first_el = ((ObjectNode) px_pipeline.get(0)) .without(Arrays.asList("test_params")); final JsonNode data_bucket_tmp = safeJsonGet("data_bucket", px_pipeline_first_el);// (WARNING: mutable, see below) final JsonNode scripting = safeJsonGet("scripting", data_bucket_tmp); // HANDLE SUBSTITUTION final String sub_prefix = Optional.ofNullable(scripting.get("sub_prefix")).map(x -> x.asText()) .orElse("$$SCRIPT_"); final String sub_suffix = Optional.ofNullable(scripting.get("sub_suffix")).map(x -> x.asText()) .orElse("$$"); final List<UnaryOperator<String>> search_replace = StreamSupport .stream(Spliterators.spliteratorUnknownSize(scripting.fieldNames(), Spliterator.ORDERED), false) .filter(f -> !f.equals("sub_prefix") && !f.equals("sub_suffix")) // (remove non language fields) .map(lang -> Tuples._2T(scripting.get(lang), lang)) // Get (separator regex, entire script, sub prefix) .map(scriptobj_lang -> Tuples._3T(safeJsonGet("separator_regex", scriptobj_lang._1()).asText(), safeJsonGet("script", scriptobj_lang._1()).asText(), sub_prefix + scriptobj_lang._2())) // Split each "entire script" up into blocks of format (bloc, lang) .<Stream<Tuple2<String, String>>>map(regex_script_lang -> Stream.concat( Stream.of(Tuples._2T(regex_script_lang._2(), regex_script_lang._3())), regex_script_lang._1().isEmpty() ? Stream.of(Tuples._2T(regex_script_lang._2(), regex_script_lang._3())) : Arrays.stream(regex_script_lang._2().split(regex_script_lang._1())) .<Tuple2<String, String>>map(s -> Tuples._2T(s, regex_script_lang._3())))) // Associate a per-lang index with each script block -> (replacement, string_sub) .<Tuple2<String, String>>flatMap(stream -> StreamUtils.zip(stream, Stream.iterate(0, i -> i + 1), (script_lang, i) -> Tuples._2T( script_lang._1().replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r"), i == 0 ? script_lang._2() + sub_suffix // (entire thing) : script_lang._2() + "_" + i + sub_suffix))) //(broken down components) .<UnaryOperator<String>>map(t2 -> (String s) -> s.replace(t2._2(), t2._1())) //(need to escape "s and newlines) .collect(Collectors.toList()); // Apply the list of transforms to the string ((ObjectNode) data_bucket_tmp).remove("scripting"); // (WARNING: mutable) final String data_bucket_str = search_replace.stream().reduce(data_bucket_tmp.toString(), (acc, s) -> s.apply(acc), (acc1, acc2) -> acc1); // Convert back to the bucket JSON final JsonNode data_bucket = ((ObjectNode) _mapper.readTree(data_bucket_str)) .without(Arrays.asList("test_params")); final DataBucketBean bucket = BeanTemplateUtils.build(data_bucket, DataBucketBean.class) .with(DataBucketBean::_id, getBucketIdFromV1SourceKey(key)) .with(DataBucketBean::created, parseJavaDate(created)) .with(DataBucketBean::modified, parseJavaDate(modified)).with(DataBucketBean::display_name, title) .with(DataBucketBean::description, description).with(DataBucketBean::owner_id, owner_id) .with(DataBucketBean::tags, StreamSupport.stream(tags.spliterator(), false).map(jt -> jt.asText()) .collect(Collectors.toSet())) .done().get(); return bucket; }
From source file:org.talend.dataprep.preparation.service.PreparationControllerTest.java
/** * Check that the folder search is correct. * * @param folderId the folder to search. * @param expectedIds the expected preparations id. * @throws IOException if an error occurs. *//* w w w.j a v a2 s . co m*/ private void checkSearchFolder(final String folderId, final List<String> expectedIds, String sort) throws IOException { // when final Response response = given() // .queryParam("folderId", folderId) // .queryParam("sort", sort) // .queryParam("order", "asc") // .when().expect().statusCode(200).log().ifError() // .get("/preparations/search"); // then assertThat(response.getStatusCode(), is(200)); final JsonNode rootNode = mapper.reader().readTree(response.asInputStream()); assertTrue(rootNode.isArray()); assertEquals(expectedIds.size(), rootNode.size()); final List<String> actualIds = StreamSupport.stream(rootNode.spliterator(), false) .map(n -> n.get("id").asText()).collect(Collectors.toList()); assertEquals(expectedIds, actualIds); }
From source file:org.talend.dataprep.preparation.service.PreparationControllerTest.java
private void checkSearchByName(String name, boolean exactMatch, List<String> expectedIds) throws IOException { // when/*from w w w . j av a 2 s. co m*/ final Response response = given() // .queryParam("name", name) // .queryParam("exactMatch", exactMatch) // .queryParam("sort", "creationDate") // .queryParam("order", "asc") // .when().expect().statusCode(200).log().ifError() // .get("/preparations/search"); // then assertThat(response.getStatusCode(), is(200)); final JsonNode rootNode = mapper.reader().readTree(response.asInputStream()); assertTrue(rootNode.isArray()); assertEquals(expectedIds.size(), rootNode.size()); final List<String> actualIds = StreamSupport.stream(rootNode.spliterator(), false) .map(n -> n.get("id").asText()).collect(Collectors.toList()); assertEquals(expectedIds.size(), actualIds.stream().filter(expectedIds::contains).count()); }