Java Code Examples for com.fasterxml.jackson.databind.type.CollectionType

The following are top voted examples for showing how to use com.fasterxml.jackson.databind.type.CollectionType. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: xm-commons   File: TenantListRepository.java   Source Code and License 6 votes vote down vote up
@SneakyThrows
private void updateTenants(String key, String config) {
    log.info("Tenants list was updated");

    if (!TENANTS_LIST_CONFIG_KEY.equals(key)) {
        throw new IllegalArgumentException("Wrong config key to update " + key);
    }

    assertExistsTenantsListConfig(config);

    CollectionType setType = defaultInstance().constructCollectionType(HashSet.class, TenantState.class);
    MapType type = defaultInstance().constructMapType(HashMap.class, defaultInstance().constructType(String.class), setType);
    Map<String, Set<TenantState>> tenantsByServiceMap = objectMapper.readValue(config, type);
    Set<TenantState> tenantKeys = tenantsByServiceMap.get(applicationName);

    assertExistTenants(tenantKeys);

    this.tenants = tenantKeys;
    this.suspendedTenants = tenantKeys.stream().filter(tenant -> SUSPENDED_STATE.equals(tenant.getState()))
        .map(TenantState::getName).collect(Collectors.toSet());
}
 
Example 2
Project: xm-gate   File: TenantMappingServiceImpl.java   Source Code and License 6 votes vote down vote up
@SneakyThrows
private void updateTenants(String config)  {
    log.info("Tenants list was updated");

    CollectionType setType = defaultInstance().constructCollectionType(HashSet.class, TenantState.class);
    MapType type = defaultInstance().constructMapType(HashMap.class, defaultInstance().constructType(String.class), setType);
    Map<String, Set<TenantState>> tenantsByServiceMap = objectMapper.readValue(config, type);

    final Map<String, String> tenants = new HashMap<>();
    for (TenantState tenant: tenantsByServiceMap.getOrDefault(applicationName, emptySet())) {
        for (String host : hosts) {
            tenants.put(tenant.getName() + "." + host, tenant.getName().toUpperCase());
        }
    }

    this.tenants = tenants;
}
 
Example 3
Project: pyplyn   File: RawJsonCollectionDeserializer.java   Source Code and License 6 votes vote down vote up
private Collection<Object> deserializeWithRetry(JsonParser p, DeserializationContext ctxt, JavaType contentType) throws IOException {
    final CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(Collection.class, contentType);

    try {
        return p.getCodec().readValue(p, collectionType);

    } catch (JsonMappingException e) {
        // attempt to read the value as string
        final String escapedString = p.getValueAsString();

        // stop here if value could not be read
        if (isNull(escapedString)) {
            throw ctxt.instantiationException(Collection.class, "Read null value when attempting to deserialize " + collectionType.toString());
        }

        // un-escape double quotes
        String unescapedString = escapedString.replaceAll("\"", "\"");

        // and attempt to parse again
        return new ObjectMapper().readValue(unescapedString, collectionType);
    }
}
 
Example 4
Project: spring-boot-seed   File: JsonUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 反序列化复杂Collection如List<Bean>
 *
 * @param <L>             the type parameter
 * @param <E>             the type parameter
 * @param jsonString      the json string
 * @param collectionClass the collection class
 * @param elementClass    the element class
 * @return 转换失败时返回 null
 */
public static <L extends Collection<E>, E> L fromJson(String jsonString,
                                                      Class<L> collectionClass,
                                                      Class<E> elementClass) {
    if (!StringUtils.hasText(jsonString)) {
        return null;
    }
    try {
        CollectionType type = mapper.getTypeFactory().constructCollectionType(collectionClass,
                elementClass);
        return mapper.readValue(jsonString, type);
    } catch (Exception e) {
        (new JsonUtil()).logger.error(e.getMessage(), e);
        return null;
    }
}
 
Example 5
Project: OpenChatAlytics   File: JsonHipChatDAO.java   Source Code and License 6 votes vote down vote up
/**
 * Helper method for deserializing a chat JSON response to a collection of objects.
 *
 * @param jsonStr
 *            The chat JSON response.
 * @param mapElement
 *            Chat JSON responses are actually maps with a single element. This argument is
 *            the value of the element to pull out from the map.
 * @param colClassElements
 *            The types of objects that the collection object will contain.
 * @param objMapper
 *            The JSON object mapper used to deserialize the JSON string.
 * @return A collection of elements of type <code>colClassElements</code>.
 */
private <T> Collection<T> deserializeJsonStr(String jsonStr, String mapElement,
                                             Class<T> colClassElements,
                                             ObjectMapper objMapper) {
    Map<String, Collection<T>> re;
    try {
        TypeFactory typeFactory = objMapper.getTypeFactory();
        CollectionType type = typeFactory.constructCollectionType(List.class, colClassElements);
        MapType thetype = typeFactory.constructMapType(HashMap.class,
                                                       typeFactory.constructType(String.class),
                                                       type);
        re = objMapper.readValue(jsonStr, thetype);
    } catch (IOException e) {
        LOG.error("Got exception when trying to deserialize list of {}", colClassElements, e);
        return Lists.newArrayListWithExpectedSize(0);
    }
    return re.get(mapElement);
}
 
Example 6
Project: allure2   File: XmlParserModule.java   Source Code and License 6 votes vote down vote up
@Override
public void setupModule(final SetupContext context) {
    super.setupModule(context);
    context.addBeanDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyCollectionDeserializer(final DeserializationConfig config,
                                                                final CollectionType type,
                                                                final BeanDescription beanDesc,
                                                                final JsonDeserializer<?> deserializer) {
            if (deserializer instanceof CollectionDeserializer) {
                return new ListDeserializer((CollectionDeserializer) deserializer);
            } else {
                return super.modifyCollectionDeserializer(config, type, beanDesc,
                        deserializer);
            }
        }
    });
}
 
Example 7
Project: cosmic   File: RESTServiceConnectorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCustomDeserializerForCustomLists() throws Exception {
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    when(response.getEntity()).thenReturn(new StringEntity("{results: [{field : \"SomeValue\"}], results_count: 1}"));
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final Class<? extends CollectionType> clazzListOfTestPojo = new ObjectMapper().getTypeFactory().constructCollectionType(List.class, TestPojo.class).getClass();
    final RESTServiceConnector connector = new RESTServiceConnector.Builder()
            .client(restClient)
            .classToDeserializerEntry(clazzListOfTestPojo, new CustomListDeserializer<TestPojoDeserializer>())
            .build();

    connector.executeRetrieveObject(TestPojo.class, "/somepath");
}
 
Example 8
Project: base   File: RestServiceImpl.java   Source Code and License 6 votes vote down vote up
private Map<String, ContainerQuota> getChangedContainers( final String quotaContainers ) throws java.io.IOException
{
    Map<String, ContainerQuota> changedContainersFiltered = new HashMap<>();
    TypeFactory typeFactory = mapper.getTypeFactory();
    CollectionType arrayType = typeFactory.constructCollectionType( ArrayList.class, ChangedContainerDto.class );
    List<ChangedContainerDto> changedContainers = mapper.readValue( quotaContainers, arrayType );
    for ( ChangedContainerDto cont : changedContainers )
    {
        ContainerQuotaDto containerQuotaDto = cont.getQuota();
        ContainerSize containerSize = containerQuotaDto.getContainerSize();
        ContainerQuota defaultQuota = ContainerSize.getDefaultContainerQuota( containerSize );
        if ( containerSize == ContainerSize.CUSTOM )
        {
            defaultQuota = containerQuotaDto.getContainerQuota();
        }

        changedContainersFiltered.put( cont.getHostId(), defaultQuota );
    }
    return changedContainersFiltered;
}
 
Example 9
Project: Camel   File: JacksonDataFormat.java   Source Code and License 6 votes vote down vote up
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {

        // is there a header with the unmarshal type?
        Class<?> clazz = unmarshalType;
        String type = exchange.getIn().getHeader(JacksonConstants.UNMARSHAL_TYPE, String.class);
        if (type == null && isAllowJmsType()) {
            type = exchange.getIn().getHeader("JMSType", String.class);
        }
        if (type != null) {
            clazz = exchange.getContext().getClassResolver().resolveMandatoryClass(type);
        }
        if (collectionType != null) {
            CollectionType collType = objectMapper.getTypeFactory().constructCollectionType(collectionType, clazz);
            return this.objectMapper.readValue(stream, collType);
        } else {
            return this.objectMapper.readValue(stream, clazz);
        }
    }
 
Example 10
Project: Camel   File: JacksonXMLDataFormat.java   Source Code and License 6 votes vote down vote up
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {

        // is there a header with the unmarshal type?
        Class<?> clazz = unmarshalType;
        String type = exchange.getIn().getHeader(JacksonXMLConstants.UNMARSHAL_TYPE, String.class);
        if (type == null && isAllowJmsType()) {
            type = exchange.getIn().getHeader("JMSType", String.class);
        }
        if (type != null) {
            clazz = exchange.getContext().getClassResolver().resolveMandatoryClass(type);
        }
        if (collectionType != null) {
            CollectionType collType = xmlMapper.getTypeFactory().constructCollectionType(collectionType, clazz);
            return this.xmlMapper.readValue(stream, collType);
        } else {
            return this.xmlMapper.readValue(stream, clazz);
        }
    }
 
Example 11
Project: zucchini-ui   File: ReportConverterServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void convertAndSaveFeatures(
    final String testRunId,
    final InputStream featureStream,
    final Optional<String> group,
    final boolean dryRun,
    final boolean onlyNewScenarii,
    final boolean mergeOnlyNewPassedScenarii) {
    final CollectionType featureListJavaType = objectMapper.getTypeFactory().constructCollectionType(List.class, ReportFeature.class);
    try {
        final List<ReportFeature> reportFeatures = objectMapper.readValue(featureStream, featureListJavaType);
        for (final ReportFeature reportFeature : reportFeatures) {
            convertAndSaveFeature(testRunId, reportFeature, group, dryRun, onlyNewScenarii, mergeOnlyNewPassedScenarii);
        }
    } catch (final IOException e) {
        throw new IllegalStateException("Can't parse report feature stream", e);
    }
}
 
Example 12
Project: Pinot   File: ThirdEyeServerUtils.java   Source Code and License 6 votes vote down vote up
/**
 * @param host
 * @param port
 * @param collection
 * @return
 *  The latest segment available at the ThirdEye server.
 * @throws IOException
 */
public static long getLatestTime(String host, short port, String collection) throws IOException {
  String urlString = "http://" + host + ":" + port + "/collections/" + collection + "/segments";
  URL url = new URL(urlString);
  final CollectionType listType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class,
      SegmentDescriptor.class);
  List<SegmentDescriptor> segments = OBJECT_MAPPER.readValue(new InputStreamReader(url.openStream(), "UTF-8"),
      listType);
  DateTime latestDataTime = null;
  for (SegmentDescriptor segment : segments) {
    if (segment.getEndDataTime() != null && (latestDataTime == null ||
        segment.getEndDataTime().compareTo(latestDataTime) > 0)) {
      latestDataTime = segment.getEndDataTime();
    }
  }
  return latestDataTime.getMillis();
}
 
Example 13
Project: secucard-connect-java-sdk   File: ObjectIdTypeResolver.java   Source Code and License 6 votes vote down vote up
@Override
public JavaType typeFromId(DatabindContext context, String id) {
  DeserializationContext ctx = (DeserializationContext) context;
  Map<String, Class> map = (Map) ctx.getAttribute("secucardobjectmap");

  Class type = map.get(id);

  JavaType javatype;
  if (type == null) {
    javatype = MapType.construct(HashMap.class, SimpleType.construct(String.class), SimpleType.construct(Object.class));
  } else {
    javatype = SimpleType.construct(type);
  }

  if (JsonToken.END_ARRAY.equals(ctx.getParser().getCurrentToken())) {
    // it is expected to get called here when reading the last token.
    javatype = CollectionType.construct(ArrayList.class, javatype);
  }

  return javatype;
}
 
Example 14
Project: jackson-datatype-bolts   File: BoltsDeserializers.java   Source Code and License 6 votes vote down vote up
@Override
public JsonDeserializer<?> findCollectionDeserializer(CollectionType type, DeserializationConfig config, BeanDescription beanDesc,
        TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException
{
    Class<?> raw = type.getRawClass();
    if (CollectionF.class.isAssignableFrom(raw)) {
        if (Option.class.isAssignableFrom(raw)) {
            return new OptionDeserializer(type, elementTypeDeserializer, elementDeserializer);
        }
        if (ListF.class.isAssignableFrom(raw)) {
            return new ListFDeserializer(type, elementTypeDeserializer, elementDeserializer);
        }
        if (SetF.class.isAssignableFrom(raw)) {
            return new SetFDeserializer(type, elementTypeDeserializer, elementDeserializer);
        }
        return new ListFDeserializer(type, elementTypeDeserializer, elementDeserializer);
    }
    return null;
}
 
Example 15
Project: calcite   File: DruidConnectionImpl.java   Source Code and License 6 votes vote down vote up
/** Reads data source names from Druid. */
Set<String> tableNames() {
  final Map<String, String> requestHeaders =
      ImmutableMap.of("Content-Type", "application/json");
  final String data = null;
  final String url = coordinatorUrl + "/druid/coordinator/v1/metadata/datasources";
  if (CalcitePrepareImpl.DEBUG) {
    System.out.println("Druid: table names" + data + "; " + url);
  }
  try (InputStream in0 = post(url, data, requestHeaders, 10000, 1800000);
       InputStream in = traceResponse(in0)) {
    final ObjectMapper mapper = new ObjectMapper();
    final CollectionType listType =
        mapper.getTypeFactory().constructCollectionType(List.class,
            String.class);
    final List<String> list = mapper.readValue(in, listType);
    return ImmutableSet.copyOf(list);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 16
Project: cloudconductor-server   File: IndexFileIndexer.java   Source Code and License 6 votes vote down vote up
@Override
public Set<PackageVersion> getRepoIndex(IRepoProvider provider) {
	RepoEntry indexEntry = provider.getEntry(IndexFileIndexer.INDEX_FILE);
	if (indexEntry != null) {
		if (!indexEntry.hasChanged(this.latest)) {
			return null;
		}
		this.latest = indexEntry;
		try {
			String indexString = StreamUtils.copyToString(provider.getEntryStream(IndexFileIndexer.INDEX_FILE), Charset.forName("UTF-8"));
			CollectionType indexType = CollectionType.construct(Set.class, SimpleType.construct(PackageVersion.class));
			return this.mapper.readValue(indexString, indexType);
		} catch (IOException e) {
			throw new RuntimeException("Failed to read index", e);
		}
	}
	throw new RuntimeException("Didn't find index file");
}
 
Example 17
Project: docker-java   File: ContainerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void serderJson1() throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final CollectionType type = mapper.getTypeFactory().constructCollectionType(List.class, Container.class);

    final List<Container> containers = testRoundTrip(RemoteApiVersion.VERSION_1_22,
            "containers/json/filter1.json",
            type
    );

    assertThat(containers.size(), equalTo(1));

    final Container container = containers.get(0);

    assertThat(container.getImageId(),
            equalTo("sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efe7ec9"));
    assertThat(container.getSizeRootFs(), equalTo(1113554L));

    final ContainerHostConfig hostConfig = container.getHostConfig();
    assertThat(hostConfig, notNullValue());
    assertThat(hostConfig.getNetworkMode(), equalTo("default"));
}
 
Example 18
Project: cloudstack   File: RESTServiceConnectorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCustomDeserializerForCustomLists() throws Exception {
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    when(response.getEntity()).thenReturn(new StringEntity("{results: [{field : \"SomeValue\"}], results_count: 1}"));
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final Class<? extends CollectionType> clazzListOfTestPojo = new ObjectMapper().getTypeFactory().constructCollectionType(List.class, TestPojo.class).getClass();
    final RESTServiceConnector connector = new RESTServiceConnector.Builder()
        .client(restClient)
        .classToDeserializerEntry(clazzListOfTestPojo, new CustomListDeserializer<TestPojoDeserializer>())
        .build();

    connector.executeRetrieveObject(TestPojo.class, "/somepath");
}
 
Example 19
Project: iiif-apis   File: SerializerModifier.java   Source Code and License 5 votes vote down vote up
@Override
public JsonSerializer<?> modifyCollectionSerializer(SerializationConfig config, CollectionType valueType,
    BeanDescription beanDesc, JsonSerializer<?> serializer) {
  if (valueType.getRawClass() == ArrayList.class) {
    return new IiifIndexedListSerializer((IndexedListSerializer) serializer, config.getTypeFactory());
  }
  return super.modifyCollectionSerializer(config, valueType, beanDesc, serializer);
}
 
Example 20
Project: PeSanKita-android   File: RecentEmojiPageModel.java   Source Code and License 5 votes vote down vote up
private LinkedHashSet<String> getPersistedCache() {
  String serialized = prefs.getString(EMOJI_LRU_PREFERENCE, "[]");
  try {
    CollectionType collectionType = TypeFactory.defaultInstance()
                                               .constructCollectionType(LinkedHashSet.class, String.class);
    return JsonUtils.getMapper().readValue(serialized, collectionType);
  } catch (IOException e) {
    Log.w(TAG, e);
    return new LinkedHashSet<>();
  }
}
 
Example 21
Project: document-management-store-app   File: CustomResultMatcher.java   Source Code and License 5 votes vote down vote up
public CustomResultMatcher containsExactly(Object... expected) {
    matchers.add(result -> {
        CollectionType valueType = objectMapper.getTypeFactory().constructCollectionType(List.class, expectedClass);
        List<Object> actual = objectMapper.readValue(result.getResponse().getContentAsByteArray(), valueType);
        assertThat(actual).containsExactly(expected);
    });
    return this;
}
 
Example 22
Project: theskeleton   File: ProfileRestControllerTest.java   Source Code and License 5 votes vote down vote up
@Test
@WithMockUser("user123")
public void testFindProfileConnectedApps() throws Exception {
	final UserEntity user = new UserEntity().setUsername("user123");
	final OAuth2ClientEntity client = new OAuth2ClientEntity().setId("client123").setName("client123");
	final UserOAuth2ClientApprovalEntity approval1 = new UserOAuth2ClientApprovalEntity()
		.setUser(user)
		.setClient(client)
		.setScope("scope1")
		.setApprovalStatus(Approval.ApprovalStatus.APPROVED);
	final UserOAuth2ClientApprovalEntity approval2 = new UserOAuth2ClientApprovalEntity()
		.setUser(user)
		.setClient(client)
		.setScope("scope2")
		.setApprovalStatus(Approval.ApprovalStatus.DENIED);
	when(profileService.findOAuth2ClientApprovalByUsername("user123")).thenReturn(Arrays.asList(approval1, approval2));
	MockHttpServletRequestBuilder request = get("/api/profile/connected-apps")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andDo(document("user-profile-connected-apps-view"))
		.andReturn()
		.getResponse();
	assertThat(response.getStatus()).isEqualTo(200);
	CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, UserOAuth2ClientApprovalRestData.class);
	List<UserOAuth2ClientApprovalRestData> returnedData = objectMapper
		.readValue(response.getContentAsByteArray(), collectionType);
	assertThat(returnedData).hasSize(1);
	UserOAuth2ClientApprovalRestData restData = returnedData.get(0);
	assertThat(restData.getClientId()).isEqualTo(client.getId());
	assertThat(restData.getClientName()).isEqualTo(client.getName());
	assertThat(restData.getUsername()).isEqualTo(user.getUsername());
	ImmutableMap<String, Approval.ApprovalStatus> scopeAndStatus = restData.getScopeAndStatus();
	assertThat(scopeAndStatus).hasSize(2);
	assertThat(scopeAndStatus).containsEntry(approval1.getScope(), approval1.getApprovalStatus());
	assertThat(scopeAndStatus).containsEntry(approval2.getScope(), approval2.getApprovalStatus());
	verify(profileService).findOAuth2ClientApprovalByUsername("user123");
}
 
Example 23
Project: xm-ms-config   File: TenantResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@SneakyThrows
public void testAddTenants() {
    ObjectMapper om = new ObjectMapper();

    mockMvc.perform(post("/api/tenants/entity")
                .content("xm")
                .contentType(MediaType.TEXT_PLAIN))
            .andExpect(status().is2xxSuccessful());
    mockMvc.perform(post("/api/tenants/entity")
            .content("ecs")
            .contentType(MediaType.TEXT_PLAIN))
            .andExpect(status().is2xxSuccessful());
    mockMvc.perform(post("/api/tenants/entity")
            .content("demo")
            .contentType(MediaType.TEXT_PLAIN))
            .andExpect(status().is2xxSuccessful());
    mockMvc.perform(post("/api/tenants/entity")
            .content("olololo")
            .contentType(MediaType.TEXT_PLAIN))
            .andExpect(status().is2xxSuccessful());
    mockMvc.perform(post("/api/tenants/entity")
            .content("test2")
            .contentType(MediaType.TEXT_PLAIN))
            .andExpect(status().is2xxSuccessful());
    mockMvc.perform(get("/api/tenants/entity")
            .contentType(MediaType.TEXT_PLAIN))
            .andDo(mvc -> {
                CollectionType stringSet = om.getTypeFactory().constructCollectionType(Set.class, TenantState.class);
                Set<TenantState> value = om.readValue(mvc.getResponse().getContentAsString(), stringSet);
                assertTrue(value.contains(new TenantState("xm","")));
                assertTrue(value.contains(new TenantState("ecs", "")));
                assertTrue(value.contains(new TenantState("demo", "")));
                assertTrue(value.contains(new TenantState("olololo", "")));
                assertTrue(value.contains(new TenantState("test2", "")));
                assertFalse(value.contains(new TenantState("test123123", "")));
            })
            .andExpect(status().is2xxSuccessful());
}
 
Example 24
Project: oma-riista-android   File: JsonUtils.java   Source Code and License 5 votes vote down vote up
public static <T> List<T> jsonToList(String json, Class<T> klass) {
    CollectionType ct = sMapper.getTypeFactory().constructCollectionType(ArrayList.class, klass);
    try {
        return sMapper.readValue(json, ct);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new ArrayList<>();
}
 
Example 25
Project: oma-riista-android   File: JsonListTask.java   Source Code and License 5 votes vote down vote up
@Override
protected final void onAsyncStream(InputStream stream) throws Exception 
{
    ObjectMapper mapper = getObjectMapper();
    
    CollectionType ct = mapper.getTypeFactory().constructCollectionType(ArrayList.class, mClass);
    mResults = mapper.readValue(stream, ct);
    if (mResults == null) {
        throw new Exception("Can't parse Json into a list");
    }
}
 
Example 26
Project: JWaves   File: Address.java   Source Code and License 5 votes vote down vote up
/**
 * Create new address.
 *
 * @param chain chain.
 * @param n     world count.
 * @return new address.
 * @throws IOException
 */
public static Address createNew(@NotNull final String chain, final int n) throws IOException {
    if (n <= 0)
        throw new IllegalArgumentException("n must be positive");

    final File file = new File("src/main/resources/words.json");
    final ObjectMapper mapper = new ObjectMapper();
    final CollectionType type = mapper.getTypeFactory().constructCollectionType(List.class, String.class);
    final List<String> wordList = mapper.readValue(file, type);

    final StringBuilder words = new StringBuilder();
    final Random rand = new Random();
    for (int i = 0; i < n; i++) {
        int index = rand.nextInt(wordList.size());
        words.append(wordList.get(index));
        if (i < n - 1) {
            words.append(" ");
        }

        wordList.remove(index);
    }

    final String seed = words.toString();
    byte[] seedEncode = seed.getBytes(StandardCharsets.UTF_8);

    final byte[] seedHash = Crypto.hashChain(seedEncode);
    final byte[] accountSeedHash = Crypto.sha256(seedHash);
    final Curve25519KeyPairGenerator gen = new Curve25519KeyPairGenerator();
    final KeyPair pair = gen.generateKeyPair(accountSeedHash);

    return generate(pair, seed, chain);
}
 
Example 27
Project: keti   File: JsonUtils.java   Source Code and License 5 votes vote down vote up
public <C extends Collection<T>, T> C deserialize(final String jsonString, final Class<C> collectionType,
        final Class<T> elementType) {
    try {
        final CollectionType javaType = OBJECT_MAPPER.getTypeFactory()
                .constructCollectionType(collectionType, elementType);

        return OBJECT_MAPPER.readValue(jsonString, javaType);
    } catch (IOException e) {
        LOGGER.error(UNEXPECTED_EXCEPTION, e);
        return null;
    }
}
 
Example 28
Project: Cable-Android   File: RecentEmojiPageModel.java   Source Code and License 5 votes vote down vote up
private LinkedHashSet<String> getPersistedCache() {
  String serialized = prefs.getString(EMOJI_LRU_PREFERENCE, "[]");
  try {
    CollectionType collectionType = TypeFactory.defaultInstance()
                                               .constructCollectionType(LinkedHashSet.class, String.class);
    return JsonUtils.getMapper().readValue(serialized, collectionType);
  } catch (IOException e) {
    Log.w(TAG, e);
    return new LinkedHashSet<>();
  }
}
 
Example 29
Project: BlogBookApp   File: MyWebService.java   Source Code and License 5 votes vote down vote up
public <T> T getObjectFromJson(String json, CollectionType classType) {
    try {
        return mObjectMapper.readValue(json, classType);
    } catch (Exception e) {
        ExceptionTracker.track(e);
    }
    return null;
}
 
Example 30
Project: QuizOff   File: StorageController.java   Source Code and License 5 votes vote down vote up
List<T> load(Class<?> resultType) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    File file = new File(fileName);
    if (file.exists()) {
        CollectionType mapType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, resultType);
        return Collections.synchronizedList(objectMapper.readValue(file, mapType));
    } else {
        return Collections.synchronizedList(new ArrayList<>());
    }
}
 
Example 31
Project: jurl   File: Jurl.java   Source Code and License 5 votes vote down vote up
public <S> List<S> getResponseJsonList(Class<S> clazz) {
    assertGone();
    if (clazz == null) {
        return null;
    }
    CollectionType listType = jacksonObjectMapper.getTypeFactory().constructCollectionType(List.class, clazz);
    try {
        return jacksonObjectMapper.readValue(responseBody, listType);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 32
Project: spring-boot   File: MyJacksonUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 非常麻烦
 *
 * @param jsonString
 * @param clazz
 * @param <T>
 * @return
 */
public static <T> List<T> parseArray(String jsonString, Class<T> clazz) {

    //注册一种类型
    // 非常麻烦 ,不同的应用,需要注册不同的类型,直接用 fast json 吧
    CollectionType javaType = objectMapper.getTypeFactory().constructCollectionType(List.class, clazz);
    try {
        return objectMapper.readValue(jsonString, javaType);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}
 
Example 33
Project: vdr-jonglisto   File: ChannelMapServiceImpl.java   Source Code and License 5 votes vote down vote up
private List<IdModel> readJsonStr(String json) throws JsonProcessingException, IOException {
    ObjectMapper mapper = new ObjectMapper();

    final JsonNode response = mapper.readTree(json);
    final CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class,
            IdModel.class);
    List<Object> object = mapper.readerFor(collectionType).readValues(response.traverse()).readAll();

    @SuppressWarnings("unchecked")
    List<IdModel> result = (List<IdModel>) object.get(0);

    return result;
}
 
Example 34
Project: unxml   File: JsonUtil.java   Source Code and License 5 votes vote down vote up
private <A> List<A> readValue(JsonParser jsonParser, CollectionType type){
    try {
        return mapper.readValue(jsonParser, type);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 35
Project: mccy-engine   File: ModsService.java   Source Code and License 5 votes vote down vote up
FmlModInfo extractFmlModInfo(InputStream in) throws IOException {
    final Path tempModInfo = Files.createTempFile("fmlmodinfo", null);
    Files.copy(in, tempModInfo, StandardCopyOption.REPLACE_EXISTING);

    String detectedCharset = UniversalDetector.detectCharset(tempModInfo.toFile());
    if (detectedCharset == null) {
        detectedCharset = filesSettings.getFallbackCharset();
    }
    final Charset cs = Charset.forName(detectedCharset);

    String modinfoJson = fixUnquotedVersionStrings(new String(Files.readAllBytes(tempModInfo), cs));

    modinfoJson = fixMissingCommas(modinfoJson);

    try {
        return objectMapper.readValue(modinfoJson, FmlModInfo.class);
    } catch (JsonParseException | JsonMappingException e) {
        LOG.debug("Failed to parse as full structure, will try list only", e);

        CollectionType modListEntriesType =
                objectMapper.getTypeFactory()
                        .constructCollectionType(ArrayList.class, FmlModListEntry.class);
        ArrayList<FmlModListEntry> entries =
                objectMapper.readValue(modinfoJson, modListEntriesType);

        return new FmlModInfo(entries);
    } finally {
        Files.delete(tempModInfo);
    }
}
 
Example 36
Project: android-rxjava-training   File: TotallylazyCollectionDeserializer.java   Source Code and License 5 votes vote down vote up
protected TotallylazyCollectionDeserializer(CollectionType type,
                                            TypeDeserializer typeDeser, JsonDeserializer<?> deser) {
    super(type);
    _containerType = type;
    _typeDeserializerForValue = typeDeser;
    _valueDeserializer = deser;
}
 
Example 37
Project: android-rxjava-training   File: TotallylazyDeserializers.java   Source Code and License 5 votes vote down vote up
/**
 * We have plenty of collection types to support...
 */
@Override
public JsonDeserializer<?> findCollectionDeserializer(CollectionType type,
                                                      DeserializationConfig config, BeanDescription beanDesc,
                                                      TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer)
        throws JsonMappingException {
    return new SequenceDeserializer(type,
            elementTypeDeserializer, elementDeserializer);
}
 
Example 38
Project: alex   File: CompactMealyMachineProxy.java   Source Code and License 5 votes vote down vote up
/**
 * Setter method to interact with the DB, because the Java standard deserialization doesn't work.
 *
 * @param nodesAsString
 *         The Nodes of the machine as JSON string.
 */
@JsonIgnore
public void setNodesDB(String nodesAsString) {
    try {
        CollectionType valueType = OBJECT_MAPPER.getTypeFactory()
                                                .constructCollectionType(List.class, Integer.class);
        this.nodes = OBJECT_MAPPER.readValue(nodesAsString, valueType);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 39
Project: alex   File: CompactMealyMachineProxy.java   Source Code and License 5 votes vote down vote up
/**
 * Setter method to interact with the DB, because the Java standard deserialization doesn't work.
 *
 * @param edgesAsString
 *         The Edges of the machine as JSON string.
 */
@JsonIgnore
public void setEdgesDB(String edgesAsString) {
    try {
        CollectionType valueType = OBJECT_MAPPER.getTypeFactory()
                                               .constructCollectionType(List.class,
                                                                        CompactMealyTransitionProxy.class);
        this.edges = OBJECT_MAPPER.readValue(edgesAsString, valueType);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 40
Project: owsi-core-parent   File: AjaxItemItBehavior.java   Source Code and License 5 votes vote down vote up
@Override
public void onRequest() {
	String term = this.getComponent().getRequest().getQueryParameters().getParameterValue("term").toString();
	
	if (!Strings.isEmpty(term)) {
		StringWriter sw = new StringWriter();
		try {
			J value = null;
			Integer index = 0;
			List<J> toSerializeObjects = Lists.newArrayList();
			
			for (I item : getValues(term)) {
				item = HibernateUtils.unwrap(item);
				index++;
				value = newAutocompleteJson(index, item, getComponent().getLocale());
				toSerializeObjects.add(value);
			}
			
			// il est important d'utiliser un typeReference sinon les paramètres de sérialisation
			// polymorphiques de J ne seront pas appliqués.
			CollectionType collectionType = OBJECT_MAPPER.getTypeFactory()
					.constructCollectionType(List.class, getJsonType());
			OBJECT_MAPPER.writerFor(collectionType).writeValue(sw, toSerializeObjects);
		} catch (IOException e) {
			throw new WicketRuntimeException(e);
		}
		
		RequestCycle.get().scheduleRequestHandlerAfterCurrent(
			new TextRequestHandler("application/json", "utf-8", sw.toString()));
	}
}
 
Example 41
Project: training-totally-lazy   File: TotallylazyCollectionDeserializer.java   Source Code and License 5 votes vote down vote up
protected TotallylazyCollectionDeserializer(CollectionType type,
                                            TypeDeserializer typeDeser, JsonDeserializer<?> deser) {
    super(type);
    _containerType = type;
    _typeDeserializerForValue = typeDeser;
    _valueDeserializer = deser;
}
 
Example 42
Project: training-totally-lazy   File: TotallylazyDeserializers.java   Source Code and License 5 votes vote down vote up
/**
 * We have plenty of collection types to support...
 */
@Override
public JsonDeserializer<?> findCollectionDeserializer(CollectionType type,
                                                      DeserializationConfig config, BeanDescription beanDesc,
                                                      TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer)
        throws JsonMappingException {
    return new SequenceDeserializer(type,
            elementTypeDeserializer, elementDeserializer);
}
 
Example 43
Project: NyBatisCore   File: SerializerModifier.java   Source Code and License 5 votes vote down vote up
public JsonSerializer<?> modifyCollectionSerializer( SerializationConfig config, CollectionType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer ) {

        Class<?> klass = beanDesc.getBeanClass();

        if( ClassUtil.isExtendedBy(klass, Set.class) ) {
            return new SetSerializer( serializer );
        } else {
            return new ListSerializer( serializer );
        }

    }
 
Example 44
Project: TextSecureSMP   File: RecentEmojiPageModel.java   Source Code and License 5 votes vote down vote up
private LinkedHashSet<String> getPersistedCache() {
  String serialized = prefs.getString(EMOJI_LRU_PREFERENCE, "[]");
  try {
    CollectionType collectionType = TypeFactory.defaultInstance()
                                               .constructCollectionType(LinkedHashSet.class, String.class);
    return JsonUtils.getMapper().readValue(serialized, collectionType);
  } catch (IOException e) {
    Log.w(TAG, e);
    return new LinkedHashSet<>();
  }
}
 
Example 45
Project: Silence   File: RecentEmojiPageModel.java   Source Code and License 5 votes vote down vote up
private LinkedHashSet<String> getPersistedCache() {
  String serialized = prefs.getString(EMOJI_LRU_PREFERENCE, "[]");
  try {
    CollectionType collectionType = TypeFactory.defaultInstance()
                                               .constructCollectionType(LinkedHashSet.class, String.class);
    return JsonUtils.getMapper().readValue(serialized, collectionType);
  } catch (IOException e) {
    Log.w(TAG, e);
    return new LinkedHashSet<>();
  }
}
 
Example 46
Project: zucchini-ui   File: JsonImportTest.java   Source Code and License 5 votes vote down vote up
public static void main(final String[] args) {
    System.out.println("args=" + Arrays.toString(args));
    final ObjectMapper objectMapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);;
    final CollectionType featureListJavaType = objectMapper.getTypeFactory().constructCollectionType(List.class, ReportFeature.class);
    try {
        final InputStream featureStream = new FileInputStream(args[0]);
        objectMapper.readValue(featureStream, featureListJavaType);
    } catch (FileNotFoundException fnfe) {
        throw new RuntimeException(fnfe);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example 47
Project: canvas-data-tools   File: CanvasApiClient.java   Source Code and License 5 votes vote down vote up
public List<CanvasDataDump> getDumps()
    throws DataConfigurationException, UnexpectedApiResponseException, IOException {
  final CollectionType type = typeFactory.constructCollectionType(List.class,
      CanvasDataDump.class);
  final List<CanvasDataDump> dumps = rest.makeApiCall("/api/account/self/dump", 200, type);
  for (final CanvasDataDump dump : dumps) {
    dump.setRestUtils(rest);
  }
  return dumps;
}
 
Example 48
Project: demyo   File: ApplicationConfiguration.java   Source Code and License 5 votes vote down vote up
/**
 * Merges the current application configuration with the provided one.
 * 
 * @param config The configuration to retrieve values from.
 */
public void merge(Map<String, String> config) {
	String languageCode = getString(config, "language");
	Locale theLanguage;
	if (languageCode != null) {
		theLanguage = Locale.forLanguageTag(languageCode);
	} else {
		theLanguage = Locale.getDefault();
	}
	setLanguage(theLanguage);

	pageSizeForText = getInt(config, "paging.textPageSize");
	pageSizeForImages = getInt(config, "paging.imagePageSize");
	pageSizeForAlbums = getInt(config, "paging.albumPageSize");
	thumbnailWidth = getInt(config, "thumbnail.width");
	thumbnailHeight = getInt(config, "thumbnail.height");

	// Load the header links as JSON data
	headerLinksSpec = getString(config, "header.quickLinks", "[]");
	JsonFactory jsonFactory = new JsonFactory();
	ObjectMapper jsonMapper = new ObjectMapper(jsonFactory);
	CollectionType jsonType = jsonMapper.getTypeFactory().constructCollectionType(ArrayList.class,
			HeaderLink.class);
	List<HeaderLink> links = new ArrayList<>();
	try {
		LOGGER.debug("Header links: {}", headerLinksSpec);
		JsonParser jsonParser = jsonFactory.createParser(headerLinksSpec);
		links = jsonMapper.<List<HeaderLink>> readValue(jsonParser, jsonType);
	} catch (RuntimeJsonMappingException | IOException e) {
		LOGGER.warn("Failed to load the header configuration", e);
	}
	headerLinks = links;
}
 
Example 49
Project: OpenConext-pdp   File: PdpController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(method = GET, value = "/internal/saml-attributes")
public List<JsonPolicyRequest.Attribute> allowedSamlAttributes() throws IOException {
    InputStream inputStream = new ClassPathResource("xacml/attributes/extra_saml_attributes.json").getInputStream();
    CollectionType type = objectMapper.getTypeFactory().constructCollectionType(List.class, JsonPolicyRequest.Attribute.class);
    List<JsonPolicyRequest.Attribute> attributes = objectMapper.readValue(inputStream, type);
    attributes.addAll(allowedAttributes());
    return attributes;
}
 
Example 50
Project: Umweltzone   File: ContentProvider.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked") // for Collections.EMPTY_LIST
@NonNull
private static <T> List<T> getContent(
        final Context context,
        final String fileName,
        final String folderName,
        Class<T> contentType) {
    int rawResourceId = getResourceId(context, fileName, folderName);

    InputStream inputStream = context.getResources().openRawResource(rawResourceId);
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Circuit.class, new CircuitDeserializer());
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(module);
    String datePattern = context.getString(R.string.config_zone_number_since_date_format);
    objectMapper.setDateFormat(DateFormats.getDateFormat(datePattern));
    try {
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        CollectionType collectionType = typeFactory.constructCollectionType(
                List.class, contentType);
        return objectMapper.readValue(inputStream, collectionType);
    } catch (IOException e) {
        // TODO Aware that app will crash when JSON is mis-structured.
        String filePath = getFilePath(folderName, fileName);
        Umweltzone.getTracker().trackError(TrackingPoint.ResourceNotFoundError, filePath);
        e.printStackTrace();
    }
    Log.e(ContentProvider.class.getName(), "Failure parsing zone data for: " + fileName);
    return Collections.EMPTY_LIST;
}
 
Example 51
Project: QuizUpWinner   File: BasicDeserializerFactory.java   Source Code and License 5 votes vote down vote up
protected JsonDeserializer<?> _findCustomCollectionDeserializer(CollectionType paramCollectionType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer)
{
  Iterator localIterator = this._factoryConfig.deserializers().iterator();
  while (localIterator.hasNext())
  {
    JsonDeserializer localJsonDeserializer = ((Deserializers)localIterator.next()).findCollectionDeserializer(paramCollectionType, paramDeserializationConfig, paramBeanDescription, paramTypeDeserializer, paramJsonDeserializer);
    if (localJsonDeserializer != null)
      return localJsonDeserializer;
  }
  return null;
}
 
Example 52
Project: QuizUpWinner   File: BasicDeserializerFactory.java   Source Code and License 5 votes vote down vote up
protected CollectionType _mapAbstractCollectionType(JavaType paramJavaType, DeserializationConfig paramDeserializationConfig)
{
  Class localClass1 = paramJavaType.getRawClass();
  Class localClass2 = (Class)_collectionFallbacks.get(localClass1.getName());
  if (localClass2 == null)
    return null;
  return (CollectionType)paramDeserializationConfig.constructSpecializedType(paramJavaType, localClass2);
}
 
Example 53
Project: QuizUpWinner   File: DeserializerCache.java   Source Code and License 5 votes vote down vote up
protected final JsonDeserializer<?> _createDeserializer2(DeserializationContext paramDeserializationContext, DeserializerFactory paramDeserializerFactory, JavaType paramJavaType, BeanDescription paramBeanDescription)
{
  DeserializationConfig localDeserializationConfig = paramDeserializationContext.getConfig();
  if (paramJavaType.isEnumType())
    return paramDeserializerFactory.createEnumDeserializer(paramDeserializationContext, paramJavaType, paramBeanDescription);
  if (paramJavaType.isContainerType())
  {
    if (paramJavaType.isArrayType())
      return paramDeserializerFactory.createArrayDeserializer(paramDeserializationContext, (ArrayType)paramJavaType, paramBeanDescription);
    if (paramJavaType.isMapLikeType())
    {
      MapLikeType localMapLikeType = (MapLikeType)paramJavaType;
      if (localMapLikeType.isTrueMapType())
        return paramDeserializerFactory.createMapDeserializer(paramDeserializationContext, (MapType)localMapLikeType, paramBeanDescription);
      return paramDeserializerFactory.createMapLikeDeserializer(paramDeserializationContext, localMapLikeType, paramBeanDescription);
    }
    if (paramJavaType.isCollectionLikeType())
    {
      JsonFormat.Value localValue = paramBeanDescription.findExpectedFormat(null);
      if ((localValue == null) || (localValue.getShape() != JsonFormat.Shape.OBJECT))
      {
        CollectionLikeType localCollectionLikeType = (CollectionLikeType)paramJavaType;
        if (localCollectionLikeType.isTrueCollectionType())
          return paramDeserializerFactory.createCollectionDeserializer(paramDeserializationContext, (CollectionType)localCollectionLikeType, paramBeanDescription);
        return paramDeserializerFactory.createCollectionLikeDeserializer(paramDeserializationContext, localCollectionLikeType, paramBeanDescription);
      }
    }
  }
  if (JsonNode.class.isAssignableFrom(paramJavaType.getRawClass()))
    return paramDeserializerFactory.createTreeDeserializer(localDeserializationConfig, paramJavaType, paramBeanDescription);
  return paramDeserializerFactory.createBeanDeserializer(paramDeserializationContext, paramJavaType, paramBeanDescription);
}
 
Example 54
Project: jabbot   File: AttackCommand.java   Source Code and License 5 votes vote down vote up
/**
 * Initialize an operations map using the http://foaas.herokuapp.com/operations
 * If the operation requires more than 2 fields discard it.
 * discarding should be done until at least proper args delimiter is supported
 *
 * supported fields are:
 * From: represents the user which triggered the command
 * Name: represents the first argument passed to the command
 */
private void initializeOperations(){
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	String json;
	List<Operation> operations;
	try {
		json = query("/operations");
		TypeFactory typeFactory = mapper.getTypeFactory();
		CollectionType collectionType = typeFactory.constructCollectionType(
				List.class, Operation.class);
		operations = mapper.readValue(json, collectionType);
		for (Operation operation : operations) {
			//Only allow 2 fields commands for now (from & name)
			if(operation.getFields().size() <= 2) {
				if (!operationsMap.containsKey(operation.getFields().size())) {
					ArrayList<Operation> array = new ArrayList<>();
					array.add(operation);
					operationsMap.put(operation.getFields().size(), array);
				} else {
					operationsMap.get(operation.getFields().size()).add(operation);
				}
			}
		}
	} catch (IOException e) {
		logger.error("error initializing operation map",e);
	}

}
 
Example 55
Project: stem   File: JsonUtils.java   Source Code and License 5 votes vote down vote up
public static JavaType constructHashOfLists(Class<?> keyClass, Class<?> listElementClass) {
    JavaType keyType = mapper.getTypeFactory().uncheckedSimpleType(keyClass);

    CollectionType listType = mapper.getTypeFactory().
            constructCollectionType(List.class, listElementClass);

    JavaType type = mapper.getTypeFactory().
            constructMapType(Map.class, keyType, listType);

    return type;
}
 
Example 56
Project: visearch-sdk-java   File: BaseViSearchOperations.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
<T> List<T> deserializeListResult(String rawResponse, JsonNode node, Class<T> clazz) {
    String json = node.toString();
    try {
        CollectionType listType = TypeFactory.defaultInstance().constructCollectionType(List.class, clazz);
        return (List<T>) objectMapper.readerFor(listType).readValue(json);
    } catch (IOException e) {
        throw new InternalViSearchException(ResponseMessages.PARSE_RESPONSE_ERROR, e, rawResponse);
    }
}
 
Example 57
Project: jackson-datatype-bolts   File: BoltsSerializers.java   Source Code and License 5 votes vote down vote up
@Override
public JsonSerializer<?> findCollectionSerializer(SerializationConfig config, CollectionType type,
        BeanDescription beanDesc, TypeSerializer elementTypeSerializer,
        JsonSerializer<Object> elementValueSerializer)
{

    if (Option.class.isAssignableFrom(type.getRawClass())) {
        return new OptionSerializer(type);
    }

    return super.findCollectionSerializer(config, type, beanDesc, elementTypeSerializer, elementValueSerializer);
}
 
Example 58
Project: data-prep   File: HtmlSerializerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void html_serializer_with_jira_export() throws Exception {

    final SchemaParser.Request request;
    final Schema result;
    try (InputStream inputStream = this.getClass().getResourceAsStream("jira_export.xls")) {
        // We do know the format and therefore we go directly to the HTML schema guessing
        request = getRequest(inputStream, "#2");
        request.getMetadata().setEncoding("UTF-16");

        result = htmlSchemaGuesser.parse(request);
    }

    try (InputStream inputStream = this.getClass().getResourceAsStream("jira_export.xls")) {

        final List<ColumnMetadata> columns = result.getSheetContents().get(0).getColumnMetadatas();
        Assert.assertThat(columns.size(), is(98));
        request.getMetadata().getRowMetadata().setColumns(columns);

        InputStream jsonStream = htmlSerializer.serialize(inputStream, request.getMetadata(), -1);

        String json = IOUtils.toString(jsonStream, UTF_8);
        ObjectMapper mapper = new ObjectMapper();
        CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, TreeMap.class);
        List<Map<String, String>> values = mapper.readValue(json, collectionType);
        Map<String, String> row0 = values.get(0);
        for (String s : row0.keySet()) {
            row0.put(s, row0.get(s).trim());
        }
        Assertions.assertThat(row0).contains(MapEntry.entry("0001", "TDP-1"));
    }
}
 
Example 59
Project: data-prep   File: APIClientTest.java   Source Code and License 5 votes vote down vote up
public List<UserDataSetMetadata> listDataSets(String name) throws IOException {
    InputStream result;
    if (name == null) {
        result = when().get("/api/datasets").asInputStream();
    }else {
        result = when().get("/api/datasets?name={name}", name).asInputStream();
    }
    CollectionType resultType = TypeFactory.defaultInstance().constructCollectionType(ArrayList.class,
            UserDataSetMetadata.class);
    return mapper.readValue(result, resultType);
}
 
Example 60
Project: ameba   File: FindSerializers.java   Source Code and License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public JsonSerializer<?> findCollectionSerializer(SerializationConfig config, CollectionType type, BeanDescription
        beanDesc, TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer) {

    if (Collection.class.isAssignableFrom(type.getRawClass())
            && jsonContext.isSupportedType(type.getContentType().getRawClass())) {
        return createSerializer();
    }

    return null;
}