Search in sources :

Example 16 with MediaType

use of org.infinispan.commons.dataconversion.MediaType in project infinispan by infinispan.

the class Encoder2x method writeHeader.

private ByteBuf writeHeader(HotRodHeader header, HotRodServer server, Channel channel, OperationStatus status, boolean sendMediaType) {
    ByteBuf buf = channel.alloc().ioBuffer();
    Cache<Address, ServerAddress> addressCache = HotRodVersion.forVersion(header.version) != HotRodVersion.UNKNOWN ? server.getAddressCache() : null;
    Optional<AbstractTopologyResponse> newTopology;
    MediaType keyMediaType = null;
    MediaType valueMediaType = null;
    boolean objectStorage = false;
    CacheTopology cacheTopology;
    if (header.op != HotRodOperation.ERROR) {
        if (CounterModuleLifecycle.COUNTER_CACHE_NAME.equals(header.cacheName)) {
            cacheTopology = getCounterCacheTopology(server.getCacheManager());
            newTopology = getTopologyResponse(header.clientIntel, header.topologyId, addressCache, CacheMode.DIST_SYNC, cacheTopology);
        } else if (header.cacheName.isEmpty() && !server.hasDefaultCache()) {
            cacheTopology = null;
            newTopology = Optional.empty();
        } else {
            HotRodServer.ExtendedCacheInfo cacheInfo = server.getCacheInfo(header);
            Configuration configuration = cacheInfo.configuration;
            CacheMode cacheMode = configuration.clustering().cacheMode();
            cacheTopology = cacheMode.isClustered() ? cacheInfo.distributionManager.getCacheTopology() : null;
            newTopology = getTopologyResponse(header.clientIntel, header.topologyId, addressCache, cacheMode, cacheTopology);
            keyMediaType = configuration.encoding().keyDataType().mediaType();
            valueMediaType = configuration.encoding().valueDataType().mediaType();
            objectStorage = APPLICATION_OBJECT.match(keyMediaType);
        }
    } else {
        cacheTopology = null;
        newTopology = Optional.empty();
    }
    buf.writeByte(Constants.MAGIC_RES);
    writeUnsignedLong(header.messageId, buf);
    buf.writeByte(header.op.getResponseOpCode());
    writeStatus(header, buf, server, objectStorage, status);
    if (newTopology.isPresent()) {
        AbstractTopologyResponse topology = newTopology.get();
        if (topology instanceof TopologyAwareResponse) {
            writeTopologyUpdate((TopologyAwareResponse) topology, buf, ((InetSocketAddress) channel.localAddress()).getAddress());
            if (header.clientIntel == Constants.INTELLIGENCE_HASH_DISTRIBUTION_AWARE)
                writeEmptyHashInfo(topology, buf);
        } else if (topology instanceof HashDistAware20Response) {
            writeHashTopologyUpdate((HashDistAware20Response) topology, cacheTopology, buf, ((InetSocketAddress) channel.localAddress()).getAddress());
        } else {
            throw new IllegalArgumentException("Unsupported response: " + topology);
        }
    } else {
        if (log.isTraceEnabled())
            log.trace("Write topology response header with no change");
        buf.writeByte(0);
    }
    if (sendMediaType && HotRodVersion.HOTROD_29.isAtLeast(header.version)) {
        writeMediaType(buf, keyMediaType);
        writeMediaType(buf, valueMediaType);
    }
    return buf;
}
Also used : InetAddress(java.net.InetAddress) InetSocketAddress(java.net.InetSocketAddress) Address(org.infinispan.remoting.transport.Address) EncodeUtil.encodeConfiguration(org.infinispan.counter.util.EncodeUtil.encodeConfiguration) Configuration(org.infinispan.configuration.cache.Configuration) CounterConfiguration(org.infinispan.counter.api.CounterConfiguration) InetSocketAddress(java.net.InetSocketAddress) CacheMode(org.infinispan.configuration.cache.CacheMode) ExtendedByteBuf(org.infinispan.server.hotrod.transport.ExtendedByteBuf) ByteBuf(io.netty.buffer.ByteBuf) CacheTopology(org.infinispan.topology.CacheTopology) MediaType(org.infinispan.commons.dataconversion.MediaType)

Example 17 with MediaType

use of org.infinispan.commons.dataconversion.MediaType in project infinispan by infinispan.

the class JsonTranscoderTest method testCharset.

@Test
public void testCharset() {
    Charset korean = Charset.forName("EUC-KR");
    MediaType textPlainKorean = TEXT_PLAIN.withCharset(korean);
    MediaType jsonKorean = APPLICATION_JSON.withCharset(korean);
    MediaType textPlainAsString = TEXT_PLAIN.withClassType(String.class);
    MediaType jsonAsString = APPLICATION_JSON.withClassType(String.class);
    String content = "{\"city_kr\":\"서울\"}";
    byte[] contentUTF = content.getBytes(UTF_8);
    byte[] contentKorean = convertCharset(contentUTF, UTF_8, korean);
    byte[] result = (byte[]) transcoder.transcode(contentKorean, jsonKorean, TEXT_PLAIN);
    assertArrayEquals(result, contentUTF);
    String strResult = (String) transcoder.transcode(contentKorean, jsonKorean, textPlainAsString);
    assertEquals(strResult, content);
    result = (byte[]) transcoder.transcode(contentKorean, jsonKorean, textPlainKorean);
    assertArrayEquals(result, contentKorean);
    result = (byte[]) transcoder.transcode(contentKorean, textPlainKorean, APPLICATION_JSON);
    assertArrayEquals(result, contentUTF);
    strResult = (String) transcoder.transcode(contentKorean, jsonKorean, jsonAsString);
    assertEquals(strResult, content);
    result = (byte[]) transcoder.transcode(contentKorean, textPlainKorean, jsonKorean);
    assertArrayEquals(result, contentKorean);
    result = (byte[]) transcoder.transcode(contentUTF, TEXT_PLAIN, jsonKorean);
    assertArrayEquals(result, contentKorean);
    result = (byte[]) transcoder.transcode(content, textPlainAsString, jsonKorean);
    assertArrayEquals(result, contentKorean);
    result = (byte[]) transcoder.transcode(contentUTF, APPLICATION_JSON, TEXT_PLAIN);
    assertArrayEquals(result, contentUTF);
    result = (byte[]) transcoder.transcode(contentUTF, APPLICATION_JSON, textPlainKorean);
    assertArrayEquals(result, contentKorean);
}
Also used : Charset(java.nio.charset.Charset) StandardConversions.convertCharset(org.infinispan.commons.dataconversion.StandardConversions.convertCharset) MediaType(org.infinispan.commons.dataconversion.MediaType) Test(org.testng.annotations.Test) AbstractTranscoderTest(org.infinispan.test.dataconversion.AbstractTranscoderTest)

Example 18 with MediaType

use of org.infinispan.commons.dataconversion.MediaType in project infinispan by infinispan.

the class ScriptConversions method convertToRequestType.

public Object convertToRequestType(Object obj, MediaType objType, MediaType requestType) {
    if (obj == null)
        return null;
    if (requestType.equals(MediaType.MATCH_ALL))
        return obj;
    // Older HR clients do not send request type and assume the script metadata type is the output type
    MediaType outputFormat = requestType.match(MediaType.APPLICATION_UNKNOWN) ? objType : requestType;
    OutputFormatter outputFormatter = formatterByMediaType.get(outputFormat.getTypeSubtype());
    if (obj instanceof Collection) {
        if (outputFormatter != null) {
            return outputFormatter.formatCollection((Collection<?>) obj, objType, requestType);
        }
    }
    Transcoder transcoder = encoderRegistry.getTranscoder(objType, requestType);
    return transcoder.transcode(obj, objType, requestType);
}
Also used : MediaType(org.infinispan.commons.dataconversion.MediaType) Collection(java.util.Collection) Transcoder(org.infinispan.commons.dataconversion.Transcoder)

Example 19 with MediaType

use of org.infinispan.commons.dataconversion.MediaType in project infinispan by infinispan.

the class ScriptConversions method convertParameters.

public Map<String, ?> convertParameters(TaskContext context) {
    if (!context.getParameters().isPresent())
        return null;
    Map<String, ?> contextParams = context.getParameters().get();
    Map<String, Object> converted = new HashMap<>(contextParams.size());
    if (context.getCache().isPresent()) {
        DataConversion valueDataConversion = context.getCache().get().getAdvancedCache().getValueDataConversion();
        MediaType requestMediaType = valueDataConversion.getRequestMediaType();
        contextParams.forEach((s, o) -> {
            Object c = requestMediaType == null ? o : encoderRegistry.convert(o, valueDataConversion.getRequestMediaType(), APPLICATION_OBJECT);
            converted.put(s, c);
        });
        return converted;
    } else {
        return contextParams;
    }
}
Also used : DataConversion(org.infinispan.encoding.DataConversion) HashMap(java.util.HashMap) MediaType(org.infinispan.commons.dataconversion.MediaType)

Example 20 with MediaType

use of org.infinispan.commons.dataconversion.MediaType in project infinispan by infinispan.

the class AbstractSchemaJdbcStore method createTableOperations.

@Override
protected TableOperations<K, V> createTableOperations(InitializationContext ctx, C config) throws SQLException {
    AdvancedCache<K, V> advancedCache = ctx.getCache().getAdvancedCache();
    // We use a type as the protostream -> json conversion leaves it as a String instead of byte[]
    MediaType jsonStringType = MediaType.fromString(MediaType.APPLICATION_JSON_TYPE + ";type=String");
    // This seems like a bug that `withRequestMediaType` isn't injected...
    DataConversion keyDataConversion = advancedCache.getKeyDataConversion().withRequestMediaType(jsonStringType);
    DataConversion valueDataConversion = advancedCache.getValueDataConversion().withRequestMediaType(jsonStringType);
    ComponentRegistry componentRegistry = advancedCache.getComponentRegistry();
    componentRegistry.wireDependencies(keyDataConversion, true);
    componentRegistry.wireDependencies(valueDataConversion, true);
    Parameter[] parameters = generateParameterInformation(config, connectionFactory);
    assert parameters.length != 0;
    Parameter[] primaryParameters = determinePrimaryParameters(config, parameters);
    assert primaryParameters.length != 0;
    assert Arrays.stream(primaryParameters).allMatch(Parameter::isPrimaryIdentifier);
    // We have to use the user serialization context as it will have the schemas they registered
    ImmutableSerializationContext serializationContext = componentRegistry.getComponent(SerializationContextRegistry.class).getUserCtx();
    ProtoSchemaOptions<K, V, C> options = verifySchemaAndCreateOptions(serializationContext, config.getSchemaJdbcConfiguration(), parameters, primaryParameters, keyDataConversion, valueDataConversion, ctx.getMarshallableEntryFactory());
    return actualCreateTableOperations(options);
}
Also used : DataConversion(org.infinispan.encoding.DataConversion) SerializationContextRegistry(org.infinispan.marshall.protostream.impl.SerializationContextRegistry) ComponentRegistry(org.infinispan.factories.ComponentRegistry) ImmutableSerializationContext(org.infinispan.protostream.ImmutableSerializationContext) MediaType(org.infinispan.commons.dataconversion.MediaType)

Aggregations

MediaType (org.infinispan.commons.dataconversion.MediaType)54 NettyRestResponse (org.infinispan.rest.NettyRestResponse)13 MediaTypeUtils.negotiateMediaType (org.infinispan.rest.resources.MediaTypeUtils.negotiateMediaType)12 EmbeddedCacheManager (org.infinispan.manager.EmbeddedCacheManager)9 Map (java.util.Map)8 EncoderRegistry (org.infinispan.marshall.core.EncoderRegistry)7 ConfigurationBuilder (org.infinispan.configuration.cache.ConfigurationBuilder)6 List (java.util.List)5 Function (java.util.function.Function)5 AdvancedCache (org.infinispan.AdvancedCache)5 Cache (org.infinispan.Cache)5 DataConversion (org.infinispan.encoding.DataConversion)5 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 CacheException (org.infinispan.commons.CacheException)4 Configuration (org.infinispan.configuration.cache.Configuration)4 IOException (java.io.IOException)3 Collections (java.util.Collections)3 Optional (java.util.Optional)3