@Test public void method_decode_should_evocate_functions_that_reade_user_attributes() throws Exception { DecoderContext decoderContext = DecoderContext.builder().build(); PowerMockito.when(reader.readString("password")).thenReturn(PASSWORD); PowerMockito.when(reader.readString("phone")).thenReturn(PHONE); PowerMockito.when(reader.readBoolean("enable")).thenReturn(ENABLE); PowerMockito.when(reader.readBoolean("extraction")).thenReturn(EXTRACTIONENABLED); PowerMockito.when(reader.readString("surname")).thenReturn(SURNAME); PowerMockito.when(reader.readString("name")).thenReturn(NAME); PowerMockito.when(reader.readBoolean("adm")).thenReturn(ADMIN); PowerMockito.when(reader.readString("uuid")).thenReturn(UUIDString); PowerMockito.when(reader.readString("email")).thenReturn(EMAIL); PowerMockito.when(reader.readString("acronym")).thenReturn(FIELDCENTERACRONYM); PowerMockito.when(reader.readBsonType()).thenReturn(BsonType.END_OF_DOCUMENT); doThrow(new BsonInvalidOperationException("teste")).when(reader).readNull("fieldCenter"); doThrow(new BsonInvalidOperationException("teste")).when(reader).readNull("extraction"); User userLocal = UserCodec.decode(reader, decoderContext); assertEquals(userLocal.getEmail(),EMAIL); assertEquals(userLocal.getPassword(),PASSWORD); assertEquals(userLocal.getPhone(),PHONE); assertEquals(userLocal.isEnable(),ENABLE); assertEquals(userLocal.isExtractionEnabled(),EXTRACTIONENABLED); assertEquals(userLocal.getName(),NAME); assertEquals(userLocal.getFieldCenter().getAcronym(),FIELDCENTERACRONYM); assertEquals(userLocal.getUuid().toString(),UUID.fromString(UUIDString).toString()); }
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { final BsonType type = reader.getCurrentBsonType(); switch(type) { case INT32: return decode(reader.readInt32() != 0); case NULL: return null; case STRING: return decode(Boolean.parseBoolean(reader.readString())); case BOOLEAN: return decode(reader.readBoolean()); //$CASES-OMITTED$ default: final String errMsg = format("Invalid date type, found: %s", type); throw new BsonInvalidOperationException(errMsg); } }
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { final BsonType type = reader.getCurrentBsonType(); switch(type) { case DATE_TIME: return decode(reader.readDateTime()); case DOUBLE: return decode((long) reader.readDouble()); case INT32: return decode(reader.readInt32()); case INT64: return decode(reader.readInt64()); case NULL: return null; case STRING: return decode(Long.valueOf(reader.readString())); //$CASES-OMITTED$ default: final String errMsg = format("Invalid date type, found: %s", type); throw new BsonInvalidOperationException(errMsg); } }
/** * @param json * @return either a BsonDocument or a BsonArray from the json string * @throws JsonParseException */ public static BsonValue parse(String json) throws JsonParseException { if (json == null) { return null; } String trimmed = json.trim(); if (trimmed.startsWith("{")) { try { return BsonDocument.parse(json); } catch (BsonInvalidOperationException ex) { // this can happen parsing a bson type, e.g. // {"$oid": "xxxxxxxx" } // the string starts with { but is not a document return getBsonValue(json); } } else if (trimmed.startsWith("[")) { return BSON_ARRAY_CODEC.decode( new JsonReader(json), DecoderContext.builder().build()); } else { return getBsonValue(json); } }
@Test public void write_map_with_null_values_to_bson() { Map<String, Integer> mapToSerialise = new HashMap<>(); mapToSerialise.put("foo", 42); mapToSerialise.put("bar", null); BsonDocument doc = (BsonDocument) BsonMapSerialiser .writingValuesWith(BsonSerialisers.toInteger) .apply(mapToSerialise); assertEquals("invalid foo", 42, doc.getInt32("foo").getValue()); try { Integer value = doc.getInt32("bar").getValue(); fail("bar should not have been written to the document"); } catch (BsonInvalidOperationException e) { // expected } }
@Override public <T> T fromBson(BsonValue value, Class<T> type, SmofField fieldOpts) { checkArgument(value != null, "A value must be specified."); checkArgument(type != null, "A type must be specified."); final Codec<T> codec = getCodec(type); try { return deserializeWithCodec(codec, value); } catch (BsonInvalidOperationException e) { handleError(new RuntimeException("Cannot parse value for type: " + fieldOpts.getName(), e)); return null; } }
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { try { return Enum.valueOf(clazz, reader.readString()); } catch (IllegalArgumentException e) { throw new BsonInvalidOperationException(e.getMessage()); } }
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { final BsonType type = reader.getCurrentBsonType(); switch(type) { case DATE_TIME: return decode(Long.toString(reader.readDateTime())); case DOUBLE: return decode(Double.toString(reader.readDouble())); case INT32: return decode(Integer.toString(reader.readInt32())); case INT64: return decode(Long.toString(reader.readInt64())); case NULL: return null; case STRING: return decode(reader.readString()); case BINARY: return decode(new String(reader.readBinaryData().getData())); case BOOLEAN: return decode(Boolean.toString(reader.readBoolean())); case JAVASCRIPT: return decode(reader.readJavaScript()); case JAVASCRIPT_WITH_SCOPE: return decode(reader.readJavaScriptWithScope()); case OBJECT_ID: return decode(reader.readObjectId().toHexString()); case REGULAR_EXPRESSION: return decode(reader.readRegularExpression().getPattern()); case SYMBOL: return decode(reader.readSymbol()); //$CASES-OMITTED$ default: final String errMsg = format("Invalid date type, found: %s", type); throw new BsonInvalidOperationException(errMsg); } }
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { final BsonType type = reader.getCurrentBsonType(); if(type == BsonType.BINARY) { return decode(reader.readBinaryData()); } final String errMsg = format("Invalid date type, found: %s", type); throw new BsonInvalidOperationException(errMsg); }
private Collection<Byte> getInstance() { try { return CollectionUtils.create(encoderClass); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | SecurityException e) { throw new BsonInvalidOperationException(e.getMessage()); } }
@Override public Float decode(final BsonReader reader, final DecoderContext decoderContext) { double value = reader.readDouble(); if (value < -Float.MAX_VALUE || value > Float.MAX_VALUE) { throw new BsonInvalidOperationException(format("%s can not be converted into a Float.", value)); } return (float) value; }
@Override public Class decode(BsonReader reader, DecoderContext decoderContext) { String className = reader.readString(); try { return Class.forName(className); } catch (ClassNotFoundException e) { throw new BsonInvalidOperationException( String.format("Cannot create class from string '%s'", className)); } }
@Override public URL decode(BsonReader reader, DecoderContext decoderContext) { String urlString = reader.readString(); try { return new URL(urlString); } catch (MalformedURLException e) { throw new BsonInvalidOperationException( String.format("Cannot create URL from string '%s'", urlString)); } }
@Override public URI decode(BsonReader reader, DecoderContext decoderContext) { String uriString = reader.readString(); try { return new URI(uriString); } catch (URISyntaxException e) { throw new BsonInvalidOperationException( String.format("Cannot create URI from string '%s'", uriString)); } }
@Override public void addDecodeStatements(TypeMirror type, CodeGeneratorContext ctx) { Builder builder = ctx.builder(); switch (type.getKind()) { case BOOLEAN: builder.addStatement(ctx.setter("reader.readBoolean()")); break; case BYTE: builder.addStatement(ctx.setter("(byte)reader.readInt32()")); break; case SHORT: builder.addStatement(ctx.setter("(short)reader.readInt32()")); break; case INT: builder.addStatement(ctx.setter("reader.readInt32()")); break; case LONG: builder.addStatement(ctx.setter("reader.readInt64()")); break; case CHAR: builder.addStatement("String string = reader.readString()"); builder.beginControlFlow("if (string.length() != 1)"); builder.addStatement( "throw new $T(String.format(\"Attempting to builder the string '%s' to a character, but its length is not equal to one\", string))", BsonInvalidOperationException.class); builder.endControlFlow(); builder.addStatement(ctx.setter("string.charAt(0)")); break; case FLOAT: builder.addStatement(ctx.setter("(float)reader.readDouble()")); break; case DOUBLE: builder.addStatement(ctx.setter("reader.readDouble()")); break; default: break; } }
@Override public Validation<T> applyUnsafe(BsonValue p) throws BsonInvalidOperationException { try { return validated(reader.apply(p)); } catch (RecordValidationException e) { return e.toValidation(); } }
default S apply(BsonValue p) { try { return applyUnsafe(p); } catch (BsonInvalidOperationException e) { throw new BsonDeserialisationException(e); } }
Stream<Value> valuesFrom(BsonValue bsonValue) throws BsonInvalidOperationException { BsonDocument doc = bsonValue.asDocument(); return deserialiserMap.values().stream() .map(d -> d.apply(doc)) .filter(Optional::isPresent) .map(Optional::get); }
@Override public PMap<String, T> applyUnsafe(BsonValue p) throws BsonInvalidOperationException { BsonDocument doc = p.asDocument(); Map<String, T> values = new HashMap<>(); for (Map.Entry<String,BsonValue> e : doc.entrySet()) { values.put(e.getKey(), valueDeserialiser.apply(e.getValue())); } return HashTreePMap.from(values); }
@Override public void addDecodeStatements(TypeMirror type, CodeGeneratorContext ctx) { MethodSpec.Builder builder = ctx.builder(); if (Util.isSameType(type, Boolean.class)) { builder.addStatement(ctx.setter("$T.valueOf(reader.readBoolean())"), Boolean.class); } else if (Util.isSameType(type, Byte.class)) { builder.addStatement(ctx.setter("$T.valueOf((byte)reader.readInt32())"), Byte.class); } else if (Util.isSameType(type, Short.class)) { builder.addStatement(ctx.setter("$T.valueOf((short)reader.readInt32())"), Short.class); } else if (Util.isSameType(type, Integer.class)) { builder.addStatement(ctx.setter("$T.valueOf(reader.readInt32())"), Integer.class); } else if (Util.isSameType(type, Long.class)) { builder.addStatement(ctx.setter("$T.valueOf(reader.readInt64())"), Long.class); } else if (Util.isSameType(type, Character.class)) { builder.addStatement("String string = reader.readString()"); builder.beginControlFlow("if (string.length() != 1)"); builder.addStatement( "throw new $T(String.format(\"Attempting to builder the string '%s' to a character, but its length is not equal to one\", string))", BsonInvalidOperationException.class); builder.endControlFlow(); builder.addStatement(ctx.setter("$T.valueOf(string.charAt(0))"), Character.class); } else if (Util.isSameType(type, Float.class)) { builder.addStatement(ctx.setter("$T.valueOf((float)reader.readDouble())"), Float.class); } else if (Util.isSameType(type, Double.class)) { builder.addStatement(ctx.setter("$T.valueOf(reader.readDouble())"), Double.class); } }
public BsonDeserialisationException(BsonInvalidOperationException e) { super(e); }
@Override public Record applyUnsafe(BsonValue bsonValue) throws BsonInvalidOperationException { return Record.of(valuesFrom(bsonValue)); }
@Override public PVector<V> applyUnsafe(BsonValue p) throws BsonInvalidOperationException { BsonArray bsonArray = p.asArray(); List<V> values = bsonArray.getValues().stream().map(v -> itemDeserialiser.apply(v)).collect(Collectors.toList()); return TreePVector.from(values); }
S applyUnsafe(BsonValue p) throws BsonInvalidOperationException;