com.fasterxml.jackson.dataformat.cbor.CBORFactory Java Examples

The following examples show how to use com.fasterxml.jackson.dataformat.cbor.CBORFactory. 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: FileSystemTargetRepositoryTest.java    From ache with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldStoreContentAsCBOR() throws IOException {
	// given
	String folder = tempFolder.newFolder().toString();
	Page target = new Page(new URL(url), html, responseHeaders);
	FileSystemTargetRepository repository = new FileSystemTargetRepository(folder, DataFormat.CBOR, false);
	
	// when
	repository.insert(target);
	
	// then
	Path path = Paths.get(folder, "example.com", "http%3A%2F%2Fexample.com");
	
	assertThat(path.toFile().exists(), is(true));
	
	ObjectMapper mapper = new ObjectMapper(new CBORFactory());
	TargetModelCbor value = mapper.readValue(path.toFile(), TargetModelCbor.class);
	
	assertThat(value.url, is(url));
	assertThat(value.response.get("body").toString(), is(html));
}
 
Example #2
Source File: AbstractDDiApiIntegrationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Convert CBOR to JSON equivalent.
 * 
 * @param input
 *            CBOR data to convert
 * @return Equivalent JSON string
 * @throws IOException
 *             Invalid CBOR input
 */
protected static String cborToJson(byte[] input) throws IOException {
    CBORFactory cborFactory = new CBORFactory();
    CBORParser cborParser = cborFactory.createParser(input);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter stringWriter = new StringWriter();
    JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter);
    while (cborParser.nextToken() != null) {
        jsonGenerator.copyCurrentEvent(cborParser);
    }
    jsonGenerator.flush();
    return stringWriter.toString();
}
 
Example #3
Source File: AbstractDDiApiIntegrationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Convert JSON to a CBOR equivalent.
 * 
 * @param json
 *            JSON object to convert
 * @return Equivalent CBOR data
 * @throws IOException
 *             Invalid JSON input
 */
protected static byte[] jsonToCbor(String json) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jsonParser = jsonFactory.createParser(json);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    CBORFactory cborFactory = new CBORFactory();
    CBORGenerator cborGenerator = cborFactory.createGenerator(out);
    while (jsonParser.nextToken() != null) {
        cborGenerator.copyCurrentEvent(jsonParser);
    }
    cborGenerator.flush();
    return out.toByteArray();
}
 
Example #4
Source File: CborIllegalValuesTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void binaryValue() throws IOException {
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    final CBORGenerator generator = new CBORFactory().createGenerator(byteArrayOutputStream);
    generator.writeBinary(new byte[]{(byte) 0x42, (byte) 0x8, (byte) 0x15});
    generator.close();

    final byte[] array = byteArrayOutputStream.toByteArray();
    boolean exceptionThrown = false;
    try {
        CborFactory.readFrom(array);
    } catch (final JsonParseException e) {
        exceptionThrown = true;
        assertThat(e)
                .withFailMessage("offending Object not included in error")
                .hasMessageContaining("420815");
    }
    assertThat(exceptionThrown).isTrue();
}
 
Example #5
Source File: ObjectConverter.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public ObjectConverter(ObjectMapper jsonMapper, ObjectMapper cborMapper) {
    AssertUtil.notNull(jsonMapper, "jsonMapper must not be null");
    AssertUtil.notNull(cborMapper, "cborMapper must not be null");
    AssertUtil.isTrue(!(jsonMapper.getFactory() instanceof CBORFactory), "factory of jsonMapper must be JsonFactory.");
    AssertUtil.isTrue(cborMapper.getFactory() instanceof CBORFactory, "factory of cborMapper must be CBORFactory.");

    this.jsonConverter = new JsonConverter(jsonMapper);
    this.cborConverter = new CborConverter(cborMapper);

    initializeJsonMapper(jsonMapper, this);
    initializeCborMapper(cborMapper, this);
}
 
Example #6
Source File: GsonJacksonBridgeSerializationTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
public void cborFactoryTest() throws IOException {
  TestObject value = createTestObject();
  CBORFactory factory = new CBORFactory();
  Class<TestObject> clazz = TestObject.class;
  ByteArrayOutputStream outputStream = testWriting(value, factory, clazz);
  TestObject value2 = testReading(factory, clazz, outputStream);
  Assert.assertEquals(value2.toString(), value.toString());
}
 
Example #7
Source File: TargetModelTest.java    From ache with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeAndUnserializeFieldsCorrectly() throws Exception {
    // given
    ObjectMapper mapper = new ObjectMapper(new CBORFactory());

    final String name = "Name";
    final String email = "[email protected]";
    final String body = "Lorem ipsum dolor sit amet";
    final URL url = new URL("http://example.org/index.html");
    
    TargetModelCbor writtenValue = new TargetModelCbor(name, email, url, body);
    
    // when
    byte[] data = mapper.writeValueAsBytes(writtenValue);
    TargetModelCbor readValue = mapper.readValue(data, TargetModelCbor.class);

    // then
    assertThat(readValue, is(notNullValue()));
    
    assertThat(readValue.key, is(notNullValue()));
    assertThat(readValue.key, is(writtenValue.key));
    
    assertThat(readValue.timestamp, is(not(0L)));
    assertThat(readValue.timestamp, is(writtenValue.timestamp));
    
    assertThat(readValue.url, is(writtenValue.url));
    assertThat(readValue.url, is(url.toString()));
    
    assertThat(readValue.imported, is(writtenValue.imported));
    
    assertThat(readValue.request, is(notNullValue()));
    assertThat(readValue.request, is(writtenValue.request));
    
    assertThat(readValue.response, is(notNullValue()));
    assertThat(readValue.response, is(writtenValue.response));
    assertThat(((String)readValue.response.get("body")), is(body));
}
 
Example #8
Source File: JacksonCBORParserTest.java    From JsonSurfer with MIT License 5 votes vote down vote up
@Override
protected InputStream read(String resourceName) throws IOException {
    ObjectMapper om = new ObjectMapper();
    JsonNode node = om.readTree(this.readAsString(resourceName));
    CBORFactory f = new CBORFactory();
    ObjectMapper cborMapper = new ObjectMapper(f);
    byte[] cborData = cborMapper.writeValueAsBytes(node);
    return new ByteArrayInputStream(cborData);
}
 
Example #9
Source File: CBorJsonConverter.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceResponse<byte[]> fromJson(String json) {
	try {
		CBORFactory factory = new CBORFactory();
		ObjectMapper mapper = new ObjectMapper(factory);
		byte[] cborData = mapper.writeValueAsBytes(json);
		
		return ServiceResponseBuilder.<byte[]>ok().withResult(cborData).build();
	} catch (JsonProcessingException e) {
		LOGGER.error("Exception converting JSON to CBOR", e);
           return ServiceResponseBuilder.<byte[]>error().build();
	}
}
 
Example #10
Source File: CBorJsonConverter.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceResponse<String> toJson(byte[] bytes) {
	try {
		CBORFactory factory = new CBORFactory();
		ObjectMapper mapper = new ObjectMapper(factory);
		JsonNode json = mapper.readValue(bytes, JsonNode.class);
		
		return ServiceResponseBuilder.<String>ok().withResult(json.toString()).build();
	} catch (IOException e) {
		LOGGER.error("Exception converting CBOR to JSON", e);
           return ServiceResponseBuilder.<String>error().build();
	}
}
 
Example #11
Source File: CborTestUtils.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
static byte[] serializeWithJackson(JsonValue jsonValue) throws IOException {
    final JsonFactory jacksonFactory = new CBORFactory();
    final ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
    final SerializationContext serializationContext =
            new SerializationContext(jacksonFactory, new ByteBufferOutputStream(byteBuffer));
    jsonValue.writeValue(serializationContext);
    serializationContext.close();
    byteBuffer.flip();

    return sizedByteArrayFromByteBuffer(byteBuffer);
}
 
Example #12
Source File: CborAvailabilityChecker.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean calculateCborAvailable() {
    try {
        // used to determine availability of jackson-core at runtime
        new JsonFactory();
        // used to determine availability of jackson-databind-cbor at runtime
        new CBORFactory();
    } catch (final NoClassDefFoundError e) {
        return false;
    }
    return true;
}
 
Example #13
Source File: MetadataItemsProviderTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
MetadataItemsProviderTest() {
    ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.registerModule(new WebAuthnMetadataJSONModule());
    ObjectMapper cborMapper = new ObjectMapper(new CBORFactory());
    objectConverter = new ObjectConverter(jsonMapper, cborMapper);
    target = new FidoMdsMetadataItemsProvider(objectConverter, fidoMDSClient);
}
 
Example #14
Source File: ObjectConverterTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void constructor_test() {
    ObjectMapper jsonMapper = new ObjectMapper();
    ObjectMapper cborMapper = new ObjectMapper(new CBORFactory());
    ObjectConverter objectConverter = new ObjectConverter(jsonMapper, cborMapper);
    assertThat(objectConverter.getJsonConverter()).isNotNull();
    assertThat(objectConverter.getCborConverter()).isNotNull();
}
 
Example #15
Source File: WebSecurityBeanConfig.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Bean
public ObjectConverter objectConverter() {
    ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.registerModule(new WebAuthnMetadataJSONModule());
    jsonMapper.registerSubtypes(new NamedType(ExampleExtensionClientInput.class, ExampleExtensionClientInput.ID));
    ObjectMapper cborMapper = new ObjectMapper(new CBORFactory());
    cborMapper.registerSubtypes(new NamedType(ExampleExtensionAuthenticatorOutput.class, ExampleExtensionAuthenticatorOutput.ID));
    return new ObjectConverter(jsonMapper, cborMapper);
}
 
Example #16
Source File: WebSecurityBeanConfig.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Bean
public ObjectConverter objectConverter() {
    ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.registerModule(new WebAuthnMetadataJSONModule());
    ObjectMapper cborMapper = new ObjectMapper(new CBORFactory());
    return new ObjectConverter(jsonMapper, cborMapper);
}
 
Example #17
Source File: RSAKeyObject.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void decode(byte[] cbor) throws IOException {

        CBORFactory f = new CBORFactory();
        ObjectMapper mapper = new ObjectMapper(f);
        CBORParser parser = f.createParser(cbor);

        Map<String, Object> pkObjectMap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
        });

        for (String key : pkObjectMap.keySet()) {
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                    "key : " + key + ", Value : " + pkObjectMap.get(key).toString());
            switch (key) {
                case "1":
                    kty = (int) pkObjectMap.get(key);
                    break;
                case "3":
                    alg = (int) pkObjectMap.get(key);
                    break;
                case "-1":
                    n = (byte[]) pkObjectMap.get(key);
                    break;
                case "-2":
                    e = (byte[]) pkObjectMap.get(key);
                    break;
            }
        }
    }
 
Example #18
Source File: FIDO2Extensions.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public int decodeExtensions(byte[] extensionBytes) throws IOException {
    CBORFactory f = new CBORFactory();
    ObjectMapper mapper = new ObjectMapper(f);
    CBORParser parser = f.createParser(extensionBytes);
    extensionMap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {});

    //Return size of AttestedCredentialData
    int numRemainingBytes = 0;
    JsonToken leftoverCBORToken;
    while ((leftoverCBORToken = parser.nextToken()) != null) {
        numRemainingBytes += leftoverCBORToken.asByteArray().length;
    }
    return extensionBytes.length - numRemainingBytes;
}
 
Example #19
Source File: ECKeyObject.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void decode(byte[] cbor) throws IOException {

        CBORFactory f = new CBORFactory();
        ObjectMapper mapper = new ObjectMapper(f);
        CBORParser parser = f.createParser(cbor);

        Map<String, Object> pkObjectMap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
        });

        for (String key : pkObjectMap.keySet()) {
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                    "key : " + key);
            switch (key) {
                case "1":
                    kty = (int) pkObjectMap.get(key);
                    break;
                case "-1":
                    crv = (int) pkObjectMap.get(key);
                    break;
                case "3":
                    alg = (int) pkObjectMap.get(key);
                    break;
                case "-2":
                    x = (byte[]) pkObjectMap.get(key);
                    break;
                case "-3":
                    y = (byte[]) pkObjectMap.get(key);
                    break;
            }
        }
    }
 
Example #20
Source File: RSAKeyObject.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void decode(byte[] cbor) throws IOException
    {
        CBORFactory f = new CBORFactory();
        ObjectMapper mapper = new ObjectMapper(f);
        CBORParser parser = f.createParser(cbor);

        Map<String, Object> pkobjectsmap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
        });

        for (String key : pkobjectsmap.keySet()) {
//            System.out.println("key : " + key + ", Value : " + pkobjectsmap.get(key).toString());
            switch (key) {
                case "1":
                    kty = (int) pkobjectsmap.get(key);
                    break;
                case "3":
                    alg = (int) pkobjectsmap.get(key);
                    break;
                case "-1":
                    n = (byte[]) pkobjectsmap.get(key);
                    break;
                case "-2":
                    e = (byte[]) pkobjectsmap.get(key);
                    break;
            }
        }
    }
 
Example #21
Source File: FIDO2Extensions.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public int decodeExtensions(byte[] extensionBytes) throws IOException
{
    CBORFactory cbf = new CBORFactory();
    CBORParser cbp = cbf.createParser(extensionBytes);
    extensionMap = (new ObjectMapper(cbf)).readValue(cbp, new TypeReference<Map<String, Object>>() {});
    int numRemainingBytes = 0;
    JsonToken leftoverCBORToken;
    while ((leftoverCBORToken = cbp.nextToken()) != null) {
        numRemainingBytes += leftoverCBORToken.asByteArray().length;
    }
    return extensionBytes.length - numRemainingBytes;
}
 
Example #22
Source File: ECKeyObject.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void decode(byte[] cbor) throws IOException {

        CBORFactory f = new CBORFactory();
        ObjectMapper mapper = new ObjectMapper(f);
        CBORParser parser = f.createParser(cbor);

        Map<String, Object> pkobjectsmap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
        });

        for (String key : pkobjectsmap.keySet()) {
//            System.out.println("key : " + key);
            switch (key) {
                case "1":
                    kty = (int) pkobjectsmap.get(key);
                    break;
                case "-1":
                    crv = (int) pkobjectsmap.get(key);
                    break;
                case "3":
                    alg = (int) pkobjectsmap.get(key);
                    break;
                case "-2":
                    x = (byte[]) pkobjectsmap.get(key);
                    break;
                case "-3":
                    y = (byte[]) pkobjectsmap.get(key);
                    break;
            }
        }
    }
 
Example #23
Source File: SerializationContext.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
SerializationContext(final OutputStream outputStream) throws IOException {
    this(new CBORFactory(), outputStream);
}
 
Example #24
Source File: CborJacksonCodec.java    From redisson with Apache License 2.0 4 votes vote down vote up
public CborJacksonCodec(ClassLoader classLoader) {
    super(createObjectMapper(classLoader, new ObjectMapper(new CBORFactory())));
}
 
Example #25
Source File: CborJacksonCodec.java    From redisson with Apache License 2.0 4 votes vote down vote up
public CborJacksonCodec() {
    super(new ObjectMapper(new CBORFactory()));
}
 
Example #26
Source File: FIDO2AttestationObject.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void decodeAttestationObject(String attestationObject) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidParameterSpecException {
    CBORFactory f = new CBORFactory();
    ObjectMapper mapper = new ObjectMapper(f);
    byte[] authenticatorData = null;
    Object attestationStmt = null;
    CBORParser parser = f.createParser(org.apache.commons.codec.binary.Base64.decodeBase64(attestationObject));
    Map<String, Object> attObjectMap = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {
    });

    //Verify cbor is properly formatted cbor (no extra bytes)
    if(parser.nextToken() != null){
        throw new IllegalArgumentException("FIDO2AttestationObject contains invalid CBOR");
    }

    for (String key : attObjectMap.keySet()) {
        if (key.equalsIgnoreCase("fmt")) {
            attFormat = attObjectMap.get(key).toString();
        } else if (key.equalsIgnoreCase("authData")) {
            authenticatorData = (byte[]) attObjectMap.get(key);
        } else if (key.equalsIgnoreCase("attStmt")) {
            attestationStmt = attObjectMap.get(key);
        }
    }
    authData = new FIDO2AuthenticatorData();
    authData.decodeAuthData(authenticatorData);

    skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "ATTFORMAT = "  +attFormat);
    switch (attFormat) {
        case "fido-u2f":
            attStmt = new U2FAttestationStatment();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "packed":
            attStmt = new PackedAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "tpm":
            attStmt = new TPMAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "android-key":
            attStmt = new AndroidKeyAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "android-safetynet":
            attStmt = new AndroidSafetynetAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        case "none":
            attStmt = new NoneAttestationStatement();
            attStmt.decodeAttestationStatement(attestationStmt);
            break;

        default:
            throw new IllegalArgumentException("Invalid attestation format");
    }

}
 
Example #27
Source File: GzipCborFileWriter.java    From ache with Apache License 2.0 4 votes vote down vote up
public GzipCborFileWriter(String outputFilename) throws IOException {
    this(outputFilename, new ObjectMapper(new CBORFactory()));
}
 
Example #28
Source File: JacksonCBORParserTest.java    From JsonSurfer with MIT License 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    provider = new JacksonProvider();
    surfer = new JsonSurfer(new JacksonParser(new CBORFactory()), provider);
}
 
Example #29
Source File: KriptonCborContext.java    From kripton with Apache License 2.0 4 votes vote down vote up
@Override
protected JsonFactory createInnerFactory()
{
	return new CBORFactory();
}
 
Example #30
Source File: KriptonCborContext.java    From kripton with Apache License 2.0 4 votes vote down vote up
@Override
protected JsonFactory createInnerFactory()
{
	return new CBORFactory();
}