io.rsocket.metadata.WellKnownMimeType Java Examples

The following examples show how to use io.rsocket.metadata.WellKnownMimeType. 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: RSocketServicesPublishHook.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(@NotNull ApplicationReadyEvent applicationReadyEvent) {
    UpstreamCluster brokerCluster = upstreamManager.findBroker();
    if (brokerCluster == null) return;
    //rsocket broker cluster logic
    CloudEventImpl<AppStatusEvent> appStatusEventCloudEvent = CloudEventBuilder.<AppStatusEvent>builder()
            .withId(UUID.randomUUID().toString())
            .withTime(ZonedDateTime.now())
            .withSource(URI.create("app://" + RSocketAppContext.ID))
            .withType(AppStatusEvent.class.getCanonicalName())
            .withDataContentType(WellKnownMimeType.APPLICATION_JSON.getString())
            .withData(new AppStatusEvent(RSocketAppContext.ID, AppStatusEvent.STATUS_SERVING))
            .build();
    LoadBalancedRSocket loadBalancedRSocket = brokerCluster.getLoadBalancedRSocket();
    String brokers = String.join(",", loadBalancedRSocket.getActiveSockets().keySet());
    loadBalancedRSocket.fireCloudEventToUpstreamAll(appStatusEventCloudEvent)
            .doOnSuccess(aVoid -> log.info(RsocketErrorCode.message("RST-301200", brokers)))
            .subscribe();
    CloudEventImpl<ServicesExposedEvent> servicesExposedEventCloudEvent = rsocketRequesterSupport.servicesExposedEvent().get();
    if (servicesExposedEventCloudEvent != null) {
        loadBalancedRSocket.fireCloudEventToUpstreamAll(servicesExposedEventCloudEvent).doOnSuccess(aVoid -> {
            String exposedServices = rsocketRequesterSupport.exposedServices().get().stream().map(ServiceLocator::getGsv).collect(Collectors.joining(","));
            log.info(RsocketErrorCode.message("RST-301201", exposedServices, brokers));
        }).subscribe();
    }
}
 
Example #2
Source File: UserServiceTest.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindById() throws Exception {
    RSocketCompositeMetadata compositeMetadata = new RSocketCompositeMetadata();
    GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata("", "com.alibaba.user.UserService2", "findById", "");
    compositeMetadata.addMetadata(routingMetadata);
    MessageMimeTypeMetadata dataEncodingMetadata = new MessageMimeTypeMetadata(WellKnownMimeType.APPLICATION_JSON);
    compositeMetadata.addMetadata(dataEncodingMetadata);
    rsocket.requestResponse(DefaultPayload.create(Unpooled.wrappedBuffer(objectMapper.writeValueAsBytes(1)), compositeMetadata.getContent()))
            .doOnTerminate(() -> {
                ReferenceCountUtil.safeRelease(compositeMetadata);
            })
            .subscribe(payload -> {
                System.out.println(payload.getDataUtf8());
            });
    Thread.sleep(1000);
}
 
Example #3
Source File: RSocketClientToServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 6 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());
    credentials = new UsernamePasswordMetadata("user", "pass");
    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

    requester = builder
            .setupRoute("shell-client")
            .setupData(UUID.randomUUID().toString())
            .setupMetadata(credentials, mimeType)
            .rsocketStrategies(b ->
                    b.encoder(new SimpleAuthenticationEncoder()))
            .rsocketConnector(connector -> connector.acceptor(responder))
            .connectTcp("localhost", port)
            .block();
}
 
Example #4
Source File: RSocketClientToSecuredServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 6 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());
    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

    // *******  The user 'test' is NOT in the required 'USER' role! **********
    credentials = new UsernamePasswordMetadata("test", "pass");

    requester = builder
            .setupRoute("shell-client")
            .setupData(UUID.randomUUID().toString())
            .setupMetadata(credentials, mimeType)
            .rsocketStrategies(b ->
                    b.encoder(new SimpleAuthenticationEncoder()))

            .rsocketConnector(connector -> connector.acceptor(responder))
            .connectTcp("localhost", port)
            .block();
}
 
Example #5
Source File: MetadataEncoder.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
public MetadataEncoder(MimeType metadataMimeType, RSocketStrategies strategies) {
	Assert.notNull(metadataMimeType, "'metadataMimeType' is required");
	Assert.notNull(strategies, "RSocketStrategies is required");
	this.metadataMimeType = metadataMimeType;
	this.strategies = strategies;
	this.isComposite = this.metadataMimeType.toString()
			.equals(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
	this.allocator = bufferFactory() instanceof NettyDataBufferFactory
			? ((NettyDataBufferFactory) bufferFactory()).getByteBufAllocator()
			: ByteBufAllocator.DEFAULT;
}
 
Example #6
Source File: Args.java    From rsc with Apache License 2.0 5 votes vote down vote up
List<String> metadataMimeType() {
	List<String> list = new ArrayList<>();
	if (this.options.has(this.route)) {
		list.add(WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString());
	}
	list.addAll(this.options.valuesOf(this.metadataMimeType).stream().map(mimeType -> {
		try {
			return WellKnownMimeType.valueOf(mimeType).getString();
		} catch (IllegalArgumentException ignored) {
			return mimeType;
		}
	}).collect(toList()));
	return list;
}
 
Example #7
Source File: Args.java    From rsc with Apache License 2.0 5 votes vote down vote up
public String dataMimeType() {
	final String mimeType = this.options.valueOf(this.dataMimeType);
	try {
		return WellKnownMimeType.valueOf(mimeType).getString();
	} catch (IllegalArgumentException ignored) {
		return mimeType;
	}
}
 
Example #8
Source File: RSocketClientDeniedConnectionToSecuredServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
    reqbuilder = builder;
    theport = port;

    // *******  The user 'fake' is NOT in the user list! **********
    credentials = new UsernamePasswordMetadata("fake", "pass");


}
 
Example #9
Source File: RSocketCompositeMetadataTest.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceIdRoutingMetadata() {
    Integer remoteServiceId = 114;
    BinaryRoutingMetadata serviceIdRoutingMetadata = new BinaryRoutingMetadata(remoteServiceId, 112);
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(serviceIdRoutingMetadata);
    ByteBuf compositeByteBuf = compositeMetadata.getContent();
    compositeByteBuf.resetReaderIndex();
    byte metadataTypeId = compositeByteBuf.getByte(0);
    System.out.println(metadataTypeId);
    Assertions.assertEquals(metadataTypeId, (byte) (WellKnownMimeType.MESSAGE_RSOCKET_BINARY_ROUTING.getIdentifier() | 0x80));
    int length = compositeByteBuf.getInt(0) & 0xFF;
    Assertions.assertEquals(length, 8);
    int serviceId = compositeByteBuf.getInt(4);
    Assertions.assertEquals(serviceId, remoteServiceId);
}
 
Example #10
Source File: CloudEventRSocket.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
default Payload constructEventReplyPayload(URI replyTo, EventReply eventReply) {
    String path = replyTo.getPath();
    String serviceName = path.substring(path.lastIndexOf("/") + 1);
    String method = replyTo.getFragment();
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(new GSVRoutingMetadata("", serviceName, method, ""), new MessageMimeTypeMetadata(WellKnownMimeType.APPLICATION_JSON));
    return ByteBufPayload.create(JsonUtils.toJsonByteBuf(eventReply), compositeMetadata.getContent());
}
 
Example #11
Source File: MessageMimeTypeMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public void load(ByteBuf byteBuf) {
    byte firstByte = byteBuf.readByte();
    if (firstByte < 0) {
        this.mimeTypeId = (byte) (firstByte & 0x7F);
        this.mimeType = WellKnownMimeType.fromIdentifier(mimeTypeId).getString();
    } else {
        byteBuf.readCharSequence(firstByte, StandardCharsets.US_ASCII);
    }
}
 
Example #12
Source File: MessageMimeTypeMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public MessageMimeTypeMetadata(String mimeType) {
    this.mimeType = mimeType;
    WellKnownMimeType wellKnownMimeType = WellKnownMimeType.fromString(mimeType);
    if (wellKnownMimeType != null) {
        this.mimeTypeId = wellKnownMimeType.getIdentifier();
    }
}
 
Example #13
Source File: BinaryRoutingMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public ByteBuf getHeaderAndContent() {
    int capacity = 12;
    if (this.routingText != null) {
        capacity = 12 + this.routingText.length;
    }
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer(capacity, capacity);
    byteBuf.writeByte(WellKnownMimeType.MESSAGE_RSOCKET_BINARY_ROUTING.getIdentifier() | 0x80);
    NumberUtils.encodeUnsignedMedium(byteBuf, capacity - 4);
    byteBuf.writeInt(this.serviceId);
    byteBuf.writeInt(this.handlerId);
    if (this.routingText != null) {
        byteBuf.writeBytes(this.routingText);
    }
    return byteBuf;
}
 
Example #14
Source File: RSocketCompositeMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuf getContent() {
    CompositeByteBuf compositeByteBuf = PooledByteBufAllocator.DEFAULT.compositeBuffer();
    for (Map.Entry<String, ByteBuf> entry : metadataStore.entrySet()) {
        WellKnownMimeType wellKnownMimeType = WellKnownMimeType.fromString(entry.getKey());
        if (wellKnownMimeType != UNPARSEABLE_MIME_TYPE) {
            CompositeMetadataCodec.encodeAndAddMetadata(compositeByteBuf, PooledByteBufAllocator.DEFAULT, wellKnownMimeType, entry.getValue());
        } else {
            CompositeMetadataCodec.encodeAndAddMetadata(compositeByteBuf, PooledByteBufAllocator.DEFAULT, entry.getKey(), entry.getValue());
        }
    }
    return compositeByteBuf;
}
 
Example #15
Source File: MessageAcceptMimeTypesMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public void load(ByteBuf byteBuf) {
    this.byteBufLength = byteBuf.readableBytes();
    while (byteBuf.isReadable()) {
        byte firstByte = byteBuf.readByte();
        if (firstByte < 0) {
            byte mimeTypeId = (byte) (firstByte & 0x7F);
            this.mimeTypes.add(WellKnownMimeType.fromIdentifier(mimeTypeId).getString());
        } else {
            byteBuf.readCharSequence(firstByte, StandardCharsets.US_ASCII);
        }
    }
}
 
Example #16
Source File: MessageAcceptMimeTypesMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public MessageAcceptMimeTypesMetadata(String... acceptedMimeTypes) {
    for (String acceptedMimeType : acceptedMimeTypes) {
        WellKnownMimeType wellKnownMimeType = WellKnownMimeType.fromString(acceptedMimeType);
        if (wellKnownMimeType == null) {
            this.mimeTypes.add(acceptedMimeType);
            this.byteBufLength += (acceptedMimeTypes.length + 1);
        } else {
            this.mimeTypes.add(wellKnownMimeType.getIdentifier());
            this.byteBufLength += 1;
        }
    }
}
 
Example #17
Source File: ReactiveGrpcMethodMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public ReactiveGrpcMethodMetadata(Method method, String group, String serviceName, String version) {
    this.serviceName = serviceName;
    this.name = method.getName();
    this.returnType = method.getReturnType();
    this.inferredClassForReturn = getInferredClassForGeneric(method.getGenericReturnType());
    Class<?> parameterType = method.getParameterTypes()[0];
    if (parameterType.isAssignableFrom(Mono.class) && returnType.isAssignableFrom(Mono.class)) {
        this.rpcType = UNARY;
    } else if (parameterType.isAssignableFrom(Mono.class) && returnType.isAssignableFrom(Flux.class)) {
        this.rpcType = SERVER_STREAMING;
    } else if (parameterType.isAssignableFrom(Flux.class) && returnType.isAssignableFrom(Mono.class)) {
        this.rpcType = CLIENT_STREAMING;
    } else if (parameterType.isAssignableFrom(Flux.class) && returnType.isAssignableFrom(Flux.class)) {
        this.rpcType = BIDIRECTIONAL_STREAMING;
    }
    this.serviceId = MurmurHash3.hash32(ServiceLocator.serviceId(group, serviceName, version));
    this.handlerId = MurmurHash3.hash32(serviceName + "." + name);
    GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata(group, serviceName, this.name, version);
    //payload binary routing metadata
    BinaryRoutingMetadata binaryRoutingMetadata = new BinaryRoutingMetadata(this.serviceId, this.handlerId,
            routingMetadata.assembleRoutingKey().getBytes(StandardCharsets.UTF_8));
    //add param encoding
    MessageMimeTypeMetadata messageMimeTypeMetadata = new MessageMimeTypeMetadata(WellKnownMimeType.APPLICATION_PROTOBUF);
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(routingMetadata, messageMimeTypeMetadata);
    CompositeByteBuf compositeMetadataContent = (CompositeByteBuf) compositeMetadata.getContent();
    //add BinaryRoutingMetadata as first
    compositeMetadataContent.addComponent(true, 0, binaryRoutingMetadata.getHeaderAndContent());
    this.compositeMetadataByteBuf = Unpooled.copiedBuffer(compositeMetadataContent);
    ReferenceCountUtil.safeRelease(compositeMetadataContent);
}
 
Example #18
Source File: RSocketBrokerResponderHandler.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
private ByteBuf constructDefaultDataEncoding() {
    ByteBuf buf = Unpooled.buffer(5, 5);
    buf.writeByte((byte) (WellKnownMimeType.MESSAGE_RSOCKET_MIMETYPE.getIdentifier() | 0x80));
    buf.writeByte(0);
    buf.writeByte(0);
    buf.writeByte(1);
    buf.writeByte(defaultMessageMimeType.getRSocketMimeType().getId() | 0x80);
    return buf;
}
 
Example #19
Source File: RSocketBrokerHandlerRegistryImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
private CloudEventImpl<UpstreamClusterChangedEvent> getBrokerClustersEvent(Collection<RSocketBroker> rSocketBrokers, String topology) {
    List<String> uris;
    if ("internet".equals(topology)) {
        uris = rSocketBrokers.stream()
                .filter(rsocketBroker -> rsocketBroker.isActive() && rsocketBroker.getExternalDomain() != null)
                .map(RSocketBroker::getAliasUrl)
                .collect(Collectors.toList());
    } else {
        uris = rSocketBrokers.stream()
                .filter(RSocketBroker::isActive)
                .map(RSocketBroker::getUrl)
                .collect(Collectors.toList());
    }
    UpstreamClusterChangedEvent upstreamClusterChangedEvent = new UpstreamClusterChangedEvent();
    upstreamClusterChangedEvent.setGroup("");
    upstreamClusterChangedEvent.setInterfaceName("*");
    upstreamClusterChangedEvent.setVersion("");
    upstreamClusterChangedEvent.setUris(uris);

    // passing in the given attributes
    return CloudEventBuilder.<UpstreamClusterChangedEvent>builder()
            .withType("com.alibaba.rsocket.upstream.UpstreamClusterChangedEvent")
            .withId(UUID.randomUUID().toString())
            .withTime(ZonedDateTime.now())
            .withDataschema(URI.create("rsocket:event:com.alibaba.rsocket.upstream.UpstreamClusterChangedEvent"))
            .withDataContentType(WellKnownMimeType.APPLICATION_JSON.getString())
            .withSource(URI.create("broker://" + RSocketAppContext.ID))
            .withData(upstreamClusterChangedEvent)
            .build();
}
 
Example #20
Source File: MessageMimeTypeMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
public MessageMimeTypeMetadata(WellKnownMimeType knownMimeType) {
    this.mimeTypeId = knownMimeType.getIdentifier();
    this.mimeType = knownMimeType.getString();
}
 
Example #21
Source File: MessageAcceptMimeTypesMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
public MessageAcceptMimeTypesMetadata(WellKnownMimeType... wellKnownMimeTypes) {
    for (WellKnownMimeType wellKnownMimeType : wellKnownMimeTypes) {
        this.mimeTypes.add(wellKnownMimeType.getIdentifier());
    }
    this.byteBufLength = wellKnownMimeTypes.length;
}