com.google.protobuf.ProtocolMessageEnum Java Examples

The following examples show how to use com.google.protobuf.ProtocolMessageEnum. 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: RoleServiceUtils.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getAccessibleResourceIds(
    CollaboratorBase hostUserInfo,
    CollaboratorBase currentLoginUserInfo,
    ProtocolMessageEnum resourceVisibility,
    ModelDBServiceResourceTypes modelDBServiceResourceTypes,
    List<String> requestedResourceIds) {
  List<String> accessibleResourceIds;
  if (hostUserInfo != null) {
    accessibleResourceIds =
        getReadOnlyAccessibleResourceIds(
            true, hostUserInfo, resourceVisibility, modelDBServiceResourceTypes);
  } else {
    accessibleResourceIds =
        getReadOnlyAccessibleResourceIds(
            false, currentLoginUserInfo, resourceVisibility, modelDBServiceResourceTypes);
  }

  if (requestedResourceIds != null && !requestedResourceIds.isEmpty()) {
    accessibleResourceIds.retainAll(requestedResourceIds);
  }
  return accessibleResourceIds;
}
 
Example #2
Source File: Protobuf2PojoHelp.java    From saluki with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: BaseInsightPoint.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Default metrics for any message type based RPC ServerSide translators.
 */
public void addProtocolMessageMetrics(List<MetricGroupDisplay> metrics,
    String prefix,
    Component.Type component,
    ProtocolMessageEnum[] types) {

  MetricGroupDisplay messageTypeCounters =
      new MetricGroupDisplay(component, "Message type counters");
  for (ProtocolMessageEnum type : types) {
    String typeName = type.toString();
    MetricDisplay metricDisplay = new MetricDisplay("Number of " + typeName,
        prefix + "_" + PrometheusMetricsSink
            .normalizeName(typeName));
    messageTypeCounters.addMetrics(metricDisplay);
  }
  metrics.add(messageTypeCounters);
}
 
Example #4
Source File: TupleTypeUtil.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a value into a type that can be stored within a {@link Tuple}.
 *
 * @param obj the value to convert
 * @return the value converted to some {@link Tuple}-encodable type
 */
@Nullable
static Object toTupleAppropriateValue(@Nullable Object obj) {
    if (obj instanceof Key.Evaluated.NullStandin) {
        return null;
    } else if (obj instanceof ByteString) {
        return ((ByteString) obj).toByteArray();
    } else if (obj instanceof List) {
        return toTupleAppropriateList((List<?>) obj);
    // Following two are both Internal.EnumLite, so could use that, too.
    } else if (obj instanceof ProtocolMessageEnum) {
        return ((ProtocolMessageEnum) obj).getNumber();
    } else if (obj instanceof Descriptors.EnumValueDescriptor) {
        return ((Descriptors.EnumValueDescriptor) obj).getNumber();
    } else if (obj instanceof FDBRecordVersion) {
        return ((FDBRecordVersion) obj).toVersionstamp(false);
    } else {
        return obj;
    }
}
 
Example #5
Source File: OpenRtbJsonUtils.java    From openrtb with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
  }
}
 
Example #6
Source File: StorageContainerDatanodeProtocolServerSideTranslatorPB.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public StorageContainerDatanodeProtocolServerSideTranslatorPB(
    StorageContainerDatanodeProtocol impl,
    ProtocolMessageMetrics<ProtocolMessageEnum> protocolMessageMetrics) {
  this.impl = impl;
  dispatcher =
      new OzoneProtocolMessageDispatcher<>("SCMDatanodeProtocol",
          protocolMessageMetrics,
          LOG);
}
 
Example #7
Source File: PublicRoleServiceUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getAccessibleResourceIds(
    CollaboratorBase hostUserInfo,
    CollaboratorBase currentLoginUserInfo,
    ProtocolMessageEnum resourceVisibility,
    ModelDBServiceResourceTypes modelDBServiceResourceTypes,
    List<String> requestedResourceIds) {
  return requestedResourceIds;
}
 
Example #8
Source File: ProtoByteBuddyUtils.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public Type convert(TypeDescriptor typeDescriptor) {
  if (typeDescriptor.equals(BYTE_STRING_TYPE_DESCRIPTOR)
      || typeDescriptor.isSubtypeOf(BYTE_STRING_TYPE_DESCRIPTOR)) {
    return byte[].class;
  } else if (typeDescriptor.isSubtypeOf(TypeDescriptor.of(ProtocolMessageEnum.class))) {
    return Integer.class;
  } else if (typeDescriptor.equals(PROTO_TIMESTAMP_TYPE_DESCRIPTOR)
      || typeDescriptor.equals(PROTO_DURATION_TYPE_DESCRIPTOR)) {
    return Row.class;
  } else {
    Type type = TYPE_OVERRIDES.get(typeDescriptor);
    return (type != null) ? type : super.convert(typeDescriptor);
  }
}
 
Example #9
Source File: Protobuf2PojoHelp.java    From saluki with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #10
Source File: TupleTypeUtil.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
/**
 * Normalize a value so that it compares equal to anything with the same {@link Tuple} representation.
 * The value that is returned cannot necessarily be packed by a {@code Tuple} (for example,
 * a <code>byte[]</code> is returned as a {@link ByteString}), but it does implement {@link Object#equals(Object)}
 * and {@link Object#hashCode()}, so the value can be used in hash-based data structures like
 * {@link java.util.HashSet HashSet}s and {@link java.util.HashMap HashMap}s. In other words, it should
 * bethe case that:
 *
 * <pre> {@code
 *   Objects.equals(toTupleEquivalentValue(value1), toTupleEquivalentValue(value2))
 *     == Arrays.equals(Tuple.from(value1).pack(), Tuple.from(value2).pack())
 * }</pre>
 *
 * <p>
 * for any two values {@code value1} and {@code value2}.
 * </p>
 *
 * <p>
 * This will only return {@code null} if {@link #toTupleAppropriateValue(Object)} would return {@code null}
 * on the same input. If the object is already in
 * </p>
 *
 * @param obj the value to normalize
 * @return a value that has the same representation when {@link Tuple}-encoded
 */
@Nullable
static Object toTupleEquivalentValue(@Nullable Object obj) {
    if (obj == null || obj instanceof Key.Evaluated.NullStandin) {
        return null;
    } else if (obj instanceof List<?>) {
        List<?> list = (List<?>)obj;
        return toTupleEquivalentList(list);
    } else if (obj instanceof Tuple) {
        return toTupleEquivalentList(((Tuple)obj).getItems());
    } else if (obj instanceof byte[]) {
        return ByteString.copyFrom((byte[]) obj);
    } else if ((obj instanceof Byte) || (obj instanceof Short) || (obj instanceof Integer)) {
        return ((Number)obj).longValue();
    } else if (obj instanceof BigInteger) {
        BigInteger bigInt = (BigInteger)obj;
        if (bigInt.compareTo(BIG_INT_MIN_LONG) > 0 && bigInt.compareTo(BIG_INT_MAX_LONG) < 0) {
            return bigInt.longValue();
        } else {
            return bigInt;
        }
    } else if (obj instanceof ProtocolMessageEnum) {
        return (long)((ProtocolMessageEnum)obj).getNumber();
    } else if (obj instanceof Descriptors.EnumValueDescriptor) {
        return (long)((Descriptors.EnumValueDescriptor)obj).getNumber();
    } else if (obj instanceof FDBRecordVersion) {
        return ((FDBRecordVersion)obj).toVersionstamp(false);
    } else {
        return obj;
    }
}
 
Example #11
Source File: ScanComparisons.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
public static Object toTupleItem(@Nullable Object item) {
    if (item instanceof ByteString) {
        return ((ByteString) item).toByteArray();
    // Following two are both Internal.EnumLite, so could use that, too.
    } else if (item instanceof ProtocolMessageEnum) {
        return ((ProtocolMessageEnum) item).getNumber();
    } else if (item instanceof Descriptors.EnumValueDescriptor) {
        return ((Descriptors.EnumValueDescriptor) item).getNumber();
    } else if (item instanceof FDBRecordVersion) {
        return ((FDBRecordVersion) item).toVersionstamp();
    } else {
        return item;
    }
}
 
Example #12
Source File: Comparisons.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
private boolean validForComparand(@Nonnull Descriptors.FieldDescriptor fieldDescriptor) {
    switch (fieldDescriptor.getJavaType()) {
        case BOOLEAN:
            return comparand instanceof Boolean;
        case BYTE_STRING:
            return comparand instanceof ByteString || comparand instanceof byte[];
        case DOUBLE:
            return comparand instanceof Double;
        case FLOAT:
            return comparand instanceof Float;
        case INT:
            return comparand instanceof Integer;
        case LONG:
            return comparand instanceof Long;
        case STRING:
            return comparand instanceof String;
        case ENUM:
            return comparand instanceof ProtocolMessageEnum &&
                  fieldDescriptor.getEnumType().equals(((ProtocolMessageEnum) comparand).getDescriptorForType());
        case MESSAGE:
            final Descriptors.Descriptor descriptor = fieldDescriptor.getMessageType();
            if (!TupleFieldsHelper.isTupleField(descriptor)) {
                return false;
            }
            if (descriptor == TupleFieldsProto.UUID.getDescriptor()) {
                return comparand instanceof UUID;
            }
            return validForComparand(descriptor.findFieldByName("value"));
        default:
            return false;
    }
}
 
Example #13
Source File: StorageContainerLocationProtocolServerSideTranslatorPB.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new StorageContainerLocationProtocolServerSideTranslatorPB.
 *
 * @param impl            {@link StorageContainerLocationProtocol} server
 *                        implementation
 * @param protocolMetrics
 */
public StorageContainerLocationProtocolServerSideTranslatorPB(
    StorageContainerLocationProtocol impl,
    ProtocolMessageMetrics<ProtocolMessageEnum> protocolMetrics)
    throws IOException {
  this.impl = impl;
  this.dispatcher =
      new OzoneProtocolMessageDispatcher<>("ScmContainerLocation",
          protocolMetrics, LOG);
}
 
Example #14
Source File: ProtoUtils.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
/**
 * 寻找protobuf枚举的映射信息
 *
 * @param clazz protoBuffer enum
 * @return map
 */
public static <T extends ProtocolMessageEnum> Internal.EnumLiteMap<T> findMapper(@Nonnull Class<T> clazz) {
    Objects.requireNonNull(clazz);
    try {
        final Method method = clazz.getDeclaredMethod("internalGetValueMap");
        method.setAccessible(true);
        @SuppressWarnings("unchecked") final Internal.EnumLiteMap<T> mapper = (Internal.EnumLiteMap<T>) method.invoke(null);
        return mapper;
    } catch (Exception e) {
        throw new IllegalArgumentException("bad class " + clazz.getName(), e);
    }
}
 
Example #15
Source File: HashTypeMappingStrategy.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
private static byte calNamespace(Class<?> messageClass) {
    if (Message.class.isAssignableFrom(messageClass)) {
        return 1;
    }
    if (ProtocolMessageEnum.class.isAssignableFrom(messageClass)) {
        return 2;
    }
    return 3;
}
 
Example #16
Source File: OzoneManagerProtocolServerSideTranslatorPB.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance of the server handler.
 *
 * @param impl OzoneManagerProtocolPB
 */
public OzoneManagerProtocolServerSideTranslatorPB(
    OzoneManager impl,
    OzoneManagerRatisServer ratisServer,
    ProtocolMessageMetrics<ProtocolMessageEnum> metrics,
    boolean enableRatis) {
  this.ozoneManager = impl;
  this.isRatisEnabled = enableRatis;

  if (isRatisEnabled) {
    // In case of ratis is enabled, handler in ServerSideTransaltorPB is used
    // only for read requests and read requests does not require
    // double-buffer to be initialized.
    this.ozoneManagerDoubleBuffer = null;
    handler = new OzoneManagerRequestHandler(impl, null);
  } else {
    this.ozoneManagerDoubleBuffer = new OzoneManagerDoubleBuffer.Builder()
        .setOmMetadataManager(ozoneManager.getMetadataManager())
        // Do nothing.
        // For OM NON-HA code, there is no need to save transaction index.
        // As we wait until the double buffer flushes DB to disk.
        .setOzoneManagerRatisSnapShot((i) -> {
        })
        .enableRatis(isRatisEnabled)
        .enableTracing(TracingUtil.isTracingEnabled(
            ozoneManager.getConfiguration()))
        .build();
    handler = new OzoneManagerRequestHandler(impl, ozoneManagerDoubleBuffer);
  }
  this.omRatisServer = ratisServer;
  dispatcher = new OzoneProtocolMessageDispatcher<>("OzoneProtocol",
      metrics, LOG);

}
 
Example #17
Source File: ReconDatanodeProtocolServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Override
public ProtocolMessageMetrics<ProtocolMessageEnum>
    getProtocolMessageMetrics() {
  return ProtocolMessageMetrics
      .create("ReconDatanodeProtocol", "Recon Datanode protocol",
          StorageContainerDatanodeProtocolProtos.Type.values());
}
 
Example #18
Source File: OzoneProtocolMessageDispatcher.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public RESPONSE processRequest(
    REQUEST request,
    FunctionWithServiceException<REQUEST, RESPONSE> methodCall,
    ProtocolMessageEnum type,
    String traceId) throws ServiceException {
  Span span = TracingUtil.importAndCreateSpan(type.toString(), traceId);
  try {
    if (logger.isTraceEnabled()) {
      logger.trace(
          "[service={}] [type={}] request is received: <json>{}</json>",
          serviceName,
          type.toString(),
          request.toString().replaceAll("\n", "\\\\n"));
    } else if (logger.isDebugEnabled()) {
      logger.debug("{} {} request is received",
          serviceName, type.toString());
    }

    long startTime = System.nanoTime();

    RESPONSE response = methodCall.apply(request);

    protocolMessageMetrics.increment(type, System.nanoTime() - startTime);

    if (logger.isTraceEnabled()) {
      logger.trace(
          "[service={}] [type={}] request is processed. Response: "
              + "<json>{}</json>",
          serviceName,
          type.toString(),
          response.toString().replaceAll("\n", "\\\\n"));
    }
    return response;

  } finally {
    span.finish();
  }
}
 
Example #19
Source File: OzoneProtocolMessageDispatcher.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public OzoneProtocolMessageDispatcher(String serviceName,
    ProtocolMessageMetrics<ProtocolMessageEnum> protocolMessageMetrics,
    Logger logger) {
  this.serviceName = serviceName;
  this.protocolMessageMetrics = protocolMessageMetrics;
  this.logger = logger;
}
 
Example #20
Source File: BinarySerializer.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
/**
 * @param typeModelMapper 类型映射信息
 * @param filter          由于{@link BinarySerializer}支持的消息类是确定的,不能加入,但是允许过滤删除
 */
@SuppressWarnings("unchecked")
public static BinarySerializer newInstance(TypeModelMapper typeModelMapper, Predicate<Class<?>> filter) {
    final Set<Class<?>> supportedClassSet = getFilteredSupportedClasses(filter);
    final List<PojoCodecImpl<?>> codecList = new ArrayList<>(supportedClassSet.size());
    try {
        for (Class<?> messageClazz : supportedClassSet) {
            // protoBuf消息
            if (Message.class.isAssignableFrom(messageClazz)) {
                Parser<?> parser = ProtoUtils.findParser((Class<? extends Message>) messageClazz);
                codecList.add(new ProtoMessageCodec(messageClazz, parser));
                continue;
            }

            // protoBufEnum
            if (ProtocolMessageEnum.class.isAssignableFrom(messageClazz)) {
                final Internal.EnumLiteMap<?> mapper = ProtoUtils.findMapper((Class<? extends ProtocolMessageEnum>) messageClazz);
                codecList.add(new ProtoEnumCodec(messageClazz, mapper));
                continue;
            }

            // 带有DBEntity和SerializableClass注解的所有类,和手写Serializer的类
            final Class<? extends PojoCodecImpl<?>> serializerClass = CodecScanner.getCodecClass(messageClazz);
            if (serializerClass != null) {
                final PojoCodecImpl<?> codec = createCodecInstance(serializerClass);
                codecList.add(new CustomPojoCodec(codec));
                continue;
            }

            throw new IllegalArgumentException("Unsupported class " + messageClazz.getName());
        }

        final CodecRegistry codecRegistry = CodecRegistrys.fromAppPojoCodecs(typeModelMapper, codecList);
        return new BinarySerializer(codecRegistry);
    } catch (Exception e) {
        return ExceptionUtils.rethrow(e);
    }
}
 
Example #21
Source File: SCMDatanodeProtocolServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Get the ProtocolMessageMetrics for this server.
 * @return ProtocolMessageMetrics
 */
protected ProtocolMessageMetrics<ProtocolMessageEnum>
      getProtocolMessageMetrics() {
  return ProtocolMessageMetrics
      .create("SCMDatanodeProtocol", "SCM Datanode protocol",
          StorageContainerDatanodeProtocolProtos.Type.values());
}
 
Example #22
Source File: ScmBlockLocationProtocolServerSideTranslatorPB.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ScmBlockLocationProtocolServerSideTranslatorPB.
 *
 * @param impl {@link ScmBlockLocationProtocol} server implementation
 */
public ScmBlockLocationProtocolServerSideTranslatorPB(
    ScmBlockLocationProtocol impl,
    ProtocolMessageMetrics<ProtocolMessageEnum> metrics)
    throws IOException {
  this.impl = impl;
  dispatcher = new OzoneProtocolMessageDispatcher<>(
      "BlockLocationProtocol", metrics, LOG);

}
 
Example #23
Source File: IssueStatusProtoMap.java    From compiler with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Class<? extends ProtocolMessageEnum> getEnumClass() {
	return boa.types.Issues.Issue.IssueStatus.class;
}
 
Example #24
Source File: StatementKindProtoMap.java    From compiler with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Class<? extends ProtocolMessageEnum> getEnumClass() {
	return boa.types.Ast.Statement.StatementKind.class;
}
 
Example #25
Source File: IssueLabelProtoMap.java    From compiler with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Class<? extends ProtocolMessageEnum> getEnumClass() {
	return boa.types.Issues.Issue.IssueLabel.class;
}
 
Example #26
Source File: TypeKindProtoMap.java    From compiler with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Class<? extends ProtocolMessageEnum> getEnumClass() {
	return boa.types.Ast.TypeKind.class;
}
 
Example #27
Source File: ModifierKindProtoMap.java    From compiler with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Class<? extends ProtocolMessageEnum> getEnumClass() {
	return boa.types.Ast.Modifier.ModifierKind.class;
}
 
Example #28
Source File: ForgeKindProtoMap.java    From compiler with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Class<? extends ProtocolMessageEnum> getEnumClass() {
	return boa.types.Toplevel.Project.ForgeKind.class;
}
 
Example #29
Source File: NodeTypeProtoMap.java    From compiler with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Class<? extends ProtocolMessageEnum> getEnumClass() {
	return boa.types.Control.Node.NodeType.class;
}
 
Example #30
Source File: RepositoryKindProtoMap.java    From compiler with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Class<? extends ProtocolMessageEnum> getEnumClass() {
	return boa.types.Code.CodeRepository.RepositoryKind.class;
}