public static final void setPojoFieldValue(Object pojo, String setter, Object protobufValue, ProtobufAttribute protobufAttribute, Field field) throws InstantiationException, IllegalAccessException, JException { Class<? extends Object> argClazz = null; if (protobufValue instanceof List) { final ArrayList<Object> newCollectionValues = new ArrayList<>(); newCollectionValues.addAll((Collection<?>) protobufValue); protobufValue = newCollectionValues; argClazz = ArrayList.class; } else if (protobufValue instanceof Map) { final Map<Object, Object> newMapValues = new HashMap<>(); newMapValues.putAll((Map<?, ?>) protobufValue); protobufValue = newMapValues; argClazz = Map.class; } else if (protobufValue instanceof ProtocolMessageEnum) { Class<?> fieldType = field.getType(); protobufValue = JReflectionUtils.runStaticMethod(fieldType, "forNumber", ((ProtocolMessageEnum) protobufValue).getNumber()); argClazz = field.getType(); } else { protobufValue.getClass(); } JReflectionUtils.runSetter(pojo, setter, protobufValue, argClazz); }
/** * Checks whether this request is supported, forms the proper {@link Error error} * and packs it into an exception. * * @param request the request to check for support * @return an instance of exception or {@code Optional.absent()} if the request is supported. */ private Optional<InvalidRequestException> checkSupported(M request) { final Optional<RequestNotSupported<M>> supported = isSupported(request); if (!supported.isPresent()) { return Optional.absent(); } final RequestNotSupported<M> result = supported.get(); final ProtocolMessageEnum unsupportedErrorCode = result.getErrorCode(); final String errorMessage = result.getErrorMessage(); final String errorTypeName = unsupportedErrorCode.getDescriptorForType() .getFullName(); final Error.Builder errorBuilder = Error.newBuilder() .setType(errorTypeName) .setCode(unsupportedErrorCode.getNumber()) .setMessage(errorMessage); final Error error = errorBuilder.build(); final InvalidRequestException exception = result.createException(errorMessage, request, error); return Optional.of(exception); }
private static <T> void putField(Message.Builder builder, Class<T> fieldClass, int fieldNumber, JSONObject jsonObject, String key, boolean required, Function<String, T> handler) { if (jsonObject.containsKey(key)) { String value = (String) jsonObject.get(key); if (value != null && !value.isEmpty()) { Object object = handler.apply(value); if (object instanceof ProtocolMessageEnum) { Descriptors.EnumDescriptor enumDescriptor = builder.getDescriptorForType().findFieldByNumber(fieldNumber).getEnumType(); checkNotNull(enumDescriptor, "No enumDescriptor for " + fieldClass.getSimpleName()); Descriptors.EnumValueDescriptor enumValueDescriptor = enumDescriptor.findValueByNumber(((ProtocolMessageEnum) object).getNumber()); checkNotNull(enumValueDescriptor, "No enumValueDescriptor for " + ((ProtocolMessageEnum) object).getNumber()); object = enumValueDescriptor; } builder.setField(getFieldDesciptor(builder, fieldNumber), object); } } else if (required) { throw new IllegalArgumentException("Required field " + key + " not set"); } }
@SuppressWarnings("rawtypes") public static final Object getProtobufFieldValue(Message protoBuf, ProtobufAttribute protobufAttribute, Field field) throws JException, InstantiationException, IllegalAccessException { final String getter = ProtobufSerializerUtils.getProtobufGetter(protobufAttribute, field); // This is used to determine if the Protobuf message has populated this value Boolean isCollection = Boolean.FALSE; if (Collection.class.isAssignableFrom(field.getType())) { isCollection = Boolean.TRUE; } // Go ahead and fun the getter Object protobufValue = JReflectionUtils.runMethod(protoBuf, getter, (Object[]) null); if (isCollection && ((Collection) protobufValue).isEmpty()) { return null; } // If the field itself is a ProtbufEntity, serialize that! if (protobufValue instanceof Message && ProtobufSerializerUtils.isProtbufEntity(field.getType())) { protobufValue = serializeFromProtobufEntity((Message) protobufValue, field.getType()); } if (protobufValue instanceof Collection) { protobufValue = convertCollectionFromProtobufs(field, (Collection<?>) protobufValue); if (((Collection) protobufValue).isEmpty()) { return null; } } if (protobufValue instanceof ProtocolMessageEnum) { protobufValue = JReflectionUtils.runStaticMethod(field.getType(), "forNumber", ((ProtocolMessageEnum) protobufValue).getNumber()); } return protobufValue; }
/** * Checks whether the {@code Message} of the given request conforms the constraints * * @param request the request message to validate. * @return an instance of exception, * or {@code Optional.absent()} if the request message is valid. */ private Optional<InvalidRequestException> validateMessage(M request) { final List<ConstraintViolation> violations = MessageValidator.newInstance() .validate(request); if (violations.isEmpty()) { return Optional.absent(); } final ValidationError validationError = ValidationError.newBuilder() .addAllConstraintViolation(violations) .build(); final ProtocolMessageEnum errorCode = getInvalidMessageErrorCode(); final String typeName = errorCode.getDescriptorForType() .getFullName(); final String errorTextTemplate = getErrorText(request); final String errorText = format("%s %s", errorTextTemplate, toText(violations)); final Error.Builder errorBuilder = Error.newBuilder() .setType(typeName) .setCode(errorCode.getNumber()) .setValidationError(validationError) .setMessage(errorText); final Error error = errorBuilder.build(); return Optional.of(onInvalidMessage(formatExceptionMessage(request), request, error)); }
public static <T> EnumValueDescriptor getEnumValue(final FieldDescriptor key, final T value) { MessageAdapter.verifyArgument(key.getJavaType() == JavaType.ENUM, "Not enum type!"); if (value instanceof EnumValueDescriptor) { return getEnumValue(key, (EnumValueDescriptor) value); } else if (value instanceof ProtocolMessageEnum) { return getEnumValue(key, (ProtocolMessageEnum) value); } else if (value instanceof String) { return getEnumValue(key, (String) value); } else if (value instanceof Integer) { return getEnumValue(key, (Integer) value); } else { throw new IllegalArgumentException("value is not of the allowed type"); } }
private boolean isProtoEnum(DeclaredType type) { return env.getTypeUtils() .isSubtype( type, env.getElementUtils() .getTypeElement(ProtocolMessageEnum.class.getCanonicalName()) .asType()); }
/** * Writes a enum array if not empty. * * @see #writeEnum(ProtocolMessageEnum, JsonGenerator) */ public static void writeEnums( String fieldName, List<? extends ProtocolMessageEnum> enums, JsonGenerator gen) throws IOException { if (!enums.isEmpty()) { gen.writeArrayFieldStart(fieldName); for (ProtocolMessageEnum e : enums) { writeEnum(e, gen); } gen.writeEndArray(); } }
/** * Nails all the per-pipeline configuration parameters to a given Guice scope. * * @param config Configuration parameters to be fixed for the pipeline run duration. * @param scope Guice scope used to fix the parameters. */ public static void nailConfigToScope(GroningenConfig config, BlockScope scope) { scope.seed(GroningenConfig.class, config); for (FieldDescriptor fd : GroningenParams.getDescriptor().getFields()) { switch (fd.getJavaType()) { case ENUM: nailConfigParamToScope(ProtocolMessageEnum.class, fd, config, scope); break; case INT: nailConfigParamToScope(Integer.class, fd, config, scope); break; case LONG: nailConfigParamToScope(Long.class, fd, config, scope); break; case DOUBLE: nailConfigParamToScope(Double.class, fd, config, scope); break; case STRING: nailConfigParamToScope(String.class, fd, config, scope); break; default: log.warning(String.format("unrecognized field descriptor type: %s.", fd.getJavaType())); break; } } }
/** * GroningenConfigParamsModule binds pipelineIterationScope to a specific SimpleScope * implementation and binds all the configuration parameters (fields annotated with * @NamedConfigParam) to a SimpleScope.seededKeyProvider(), which prevents them being * injected outside of the scope (see bindConfigParamToSeededKeyProvider()). */ @Override protected void configure() { bind(GroningenConfig.class) .toProvider(SimpleScope.<GroningenConfig>seededKeyProvider()) .in(PipelineIterationScoped.class); for (FieldDescriptor fd : GroningenParams.getDescriptor().getFields()) { switch (fd.getJavaType()) { case ENUM: bindConfigParamToSeededKeyProvider(ProtocolMessageEnum.class, fd); break; case INT: bindConfigParamToSeededKeyProvider(Integer.class, fd); break; case LONG: bindConfigParamToSeededKeyProvider(Long.class, fd); break; case DOUBLE: bindConfigParamToSeededKeyProvider(Double.class, fd); break; case STRING: bindConfigParamToSeededKeyProvider(String.class, fd); break; default: log.warning(String.format("unrecognized field descriptor type: %s.", fd.getJavaType())); break; } } }
/** * Creates an instance of {@code RequestNotSupported} value object * by the specific error code and the error message. */ RequestNotSupported(ProtocolMessageEnum errorCode, String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; }
private ProtocolMessageEnum getErrorCode() { return errorCode; }
/** * Returns the {@link Class} representing the Java enumeration of this type. */ protected Class<? extends ProtocolMessageEnum> getEnumClass() { return null; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Ast.Comment.CommentKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Ast.Expression.ExpressionKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Issues.Issue.IssuePriority.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Graph.Traversal.TraversalKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Control.CFGNode.CFGNodeType.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Ast.Modifier.Visibility.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Control.CFGEdge.CFGEdgeLabel.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Ast.Statement.StatementKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Toplevel.Project.ForgeKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Ast.Modifier.ModifierKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Ast.TypeKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Issues.Issue.IssueLabel.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Issues.Issue.IssueStatus.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Code.CodeRepository.RepositoryKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Shared.ChangeKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Diff.ChangedFile.FileKind.class; }
/** {@inheritDoc} */ @Override protected Class<? extends ProtocolMessageEnum> getEnumClass() { return boa.types.Graph.Traversal.TraversalDirection.class; }
public static EnumValueDescriptor getEnumValue(final FieldDescriptor key, final ProtocolMessageEnum value) { MessageAdapter.verifyArgument(key.getEnumType() == value.getDescriptorForType(), "Wrong enum type!"); return value.getValueDescriptor(); }
/** * Converts a Java object into an equivalent SoyValueProvider. * * @param obj The object to convert. * @return An equivalent SoyValueProvider. * @throws SoyDataException If the given object cannot be converted. */ @Nonnull public SoyValueProvider convert(@Nullable Object obj) { SoyValueProvider convertedPrimitive = convertPrimitive(obj); if (convertedPrimitive != null) { return convertedPrimitive; } else if (obj instanceof Map<?, ?>) { // TODO: Instead of hoping that the map is string-keyed, we should only enter this case if we // know the map is string-keyed. Otherwise, we should fall through and let the user's custom // converters have a chance at converting the map. @SuppressWarnings("unchecked") Map<String, ?> objCast = (Map<String, ?>) obj; // TODO(b/69064671): Change this to use runtime type detection. return newDictFromMap(objCast); } else if (obj instanceof Collection<?> || obj instanceof FluentIterable<?>) { // NOTE: We don't trap Iterable itself, because many types extend from Iterable but are not // meant to be enumerated. (e.g. ByteString implements Iterable<Byte>) return newListFromIterable((Iterable<?>) obj); } else if (obj instanceof SoyGlobalsValue) { return convert(((SoyGlobalsValue) obj).getSoyGlobalValue()); } else if (obj instanceof ByteString) { // Encode ByteStrings as base 64, as a safe and consistent way to send them to JS return StringData.forValue(BaseEncoding.base64().encode(((ByteString) obj).toByteArray())); } else if (obj instanceof EnumValueDescriptor) { // Proto enum that was obtained via reflection (e.g. from SoyProtoValue) return IntegerData.forValue(((EnumValueDescriptor) obj).getNumber()); } else if (obj instanceof ProtocolMessageEnum) { // Proto enum that was directly passed into the template return IntegerData.forValue(((ProtocolMessageEnum) obj).getNumber()); } else { if (customValueConverters != null) { for (SoyCustomValueConverter customConverter : customValueConverters) { SoyValueProvider result = customConverter.convert(this, obj); if (result != null) { return result; } } } throw new SoyDataException( "Attempting to convert unrecognized object to Soy value (object type " + obj.getClass().getName() + ")."); } }
private SoyExpression interpretExtensionField(Expression field) { switch (descriptor.getJavaType()) { case FLOAT: case DOUBLE: return SoyExpression.forFloat( field.checkedCast(Number.class).invoke(MethodRef.NUMBER_DOUBLE_VALUE)); case ENUM: return SoyExpression.forInt( numericConversion( field.checkedCast(ProtocolMessageEnum.class).invoke(PROTO_ENUM_GET_NUMBER), Type.LONG_TYPE)); case INT: if (isUnsigned(descriptor)) { return SoyExpression.forInt( MethodRef.UNSIGNED_INTS_TO_LONG.invoke( field.checkedCast(Integer.class).invoke(MethodRef.NUMBER_INT_VALUE))); } else { return SoyExpression.forInt( field.checkedCast(Integer.class).invoke(MethodRef.NUMBER_LONG_VALUE)); } case LONG: if (shouldConvertBetweenStringAndLong(descriptor)) { if (isUnsigned(descriptor)) { return SoyExpression.forString( MethodRef.UNSIGNED_LONGS_TO_STRING.invoke( field.checkedCast(Long.class).invoke(MethodRef.NUMBER_LONG_VALUE))); } else { return SoyExpression.forString(field.invoke(MethodRef.OBJECT_TO_STRING)); } } return SoyExpression.forInt( field.checkedCast(Number.class).invoke(MethodRef.NUMBER_LONG_VALUE)); case BOOLEAN: return SoyExpression.forBool( field.checkedCast(Boolean.class).invoke(MethodRef.BOOLEAN_VALUE)); case STRING: return SoyExpression.forString(field.checkedCast(String.class)); case MESSAGE: return messageToSoyExpression(field); case BYTE_STRING: // Current tofu support for ByteString is to base64 encode it. return byteStringToBase64String(field.checkedCast(ByteString.class)); default: throw new AssertionError("unsupported field type: " + descriptor); } }
/** * Writes a enum value as an int, using its Protobuf number. */ public static void writeEnum(ProtocolMessageEnum e, JsonGenerator gen) throws IOException { gen.writeNumber(e.getNumber()); }
/** * Writes a enum value as an int, using its Protobuf number. */ public static void writeEnumField( String fieldName, ProtocolMessageEnum e, JsonGenerator gen) throws IOException { gen.writeNumberField(fieldName, e.getNumber()); }
/** * Returns the error code to use in the {@linkplain Error validation error}, in case * the validated request message does not satisfy the validation constraints. */ protected abstract ProtocolMessageEnum getInvalidMessageErrorCode();