public RestRequest value(Object value, MediaType contentType) { this.value = value; this.contentType = contentType.toString(); return this; }
@Test public void testToString() { assertEquals("application/xml", new MediaType("application", "xml", createMap(new MapEntry("q", "0.9"))).toString()); assertEquals("text/csv", new MediaType("text", "csv").toString()); assertEquals("foo/bar; a=2", new MediaType("foo", "bar", createMap(new MapEntry("a", "2"))).toString()); assertEquals("foo/bar; a=2; b=1; c=2", new MediaType("foo", "bar", createMap(new MapEntry("a", "2"), new MapEntry("b", "1"), new MapEntry("c", "2"))).toString()); assertEquals("a/b; p=1", MediaType.fromString("a/b; p=1; q=2;").toStringExcludingParam("q")); }
@Override public void setEnvironment(Cache<Object, Object> cache, Set<Object> inputKeys) { scriptManager = (ScriptingManagerImpl) SecurityActions.getGlobalComponentRegistry(cache.getCacheManager()).getComponent(ScriptingManager.class); bindings = new SimpleBindings(); bindings.put("inputKeys", inputKeys); String scriptMediaType = metadata.dataType().toString(); DataTypedCacheManager dataTypedCacheManager = new DataTypedCacheManager(scriptMediaType, cache.getCacheManager(), null); bindings.put("cacheManager", dataTypedCacheManager); bindings.put("cache", cache.getAdvancedCache().withMediaType(scriptMediaType, scriptMediaType)); ctxParams.forEach((key, value) -> bindings.put(key, value)); } }
@Override public Object transcode(Object content, MediaType contentType, MediaType destinationType) { switch (destinationType.toString()) { case "application/foo": return content.toString().replaceAll("bar", "foo"); case "application/bar": return content.toString().replaceAll("foo", "bar"); default: throw new EncodingException("Not supported!"); } }
private void writeMediaType(ByteBuf buf, MediaType mediaType) { if (mediaType == null) { buf.writeByte(0); } else { Short id = MediaTypeIds.getId(mediaType); if (id != null) { buf.writeByte(1); VInt.write(buf, id); } else { buf.writeByte(2); ExtendedByteBuf.writeString(mediaType.toString(), buf); } Map<String, String> parameters = mediaType.getParameters(); VInt.write(buf, parameters.size()); parameters.forEach((key, value) -> { ExtendedByteBuf.writeString(key, buf); ExtendedByteBuf.writeString(value, buf); }); } }
private String readViaRest(Integer key, MediaType valueFormat) throws IOException { HttpGet get = new HttpGet(getURL(key)); get.addHeader("Accept", valueFormat.toString()); get.addHeader("Key-Content-Type", "application/x-java-object; type=java.lang.Integer"); HttpResponse getResponse = httpClient.execute(get); assertEquals(HttpStatus.SC_OK, getResponse.getStatusLine().getStatusCode()); return EntityUtils.toString(getResponse.getEntity()); }
private void writeViaRest(Integer key, String newCurrency, MediaType valueFormat) throws IOException { HttpPost httpPost = new HttpPost(getURL(key)); httpPost.addHeader("Content-Type", valueFormat.toString()); httpPost.addHeader("Key-Content-Type", "application/x-java-object; type=java.lang.Integer"); httpPost.setEntity(new StringEntity(newCurrency)); CloseableHttpResponse response = httpClient.execute(httpPost); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); }
/** * Converts an octet stream to a Java object * * @param source The source to convert * @param destination The type of the converted object. * @return an instance of a java object compatible with the supplied destination type. */ public static Object convertOctetStreamToJava(byte[] source, MediaType destination, Marshaller marshaller) { if (source == null) return null; if (!destination.match(MediaType.APPLICATION_OBJECT)) { throw log.invalidMediaType(APPLICATION_OBJECT_TYPE, destination.toString()); } String classType = destination.getClassType(); if (classType == null) return source; if (classType.equals("ByteArray")) { return source; } if (destination.hasStringType()) { return new String(source, UTF_8); } try { return marshaller.objectFromByteBuffer(source); } catch (IOException | ClassNotFoundException e) { throw log.conversionNotSupported(source, MediaType.APPLICATION_OCTET_STREAM_TYPE, destination.toString()); } }
public MemcachedDecoder(AdvancedCache<byte[], byte[]> memcachedCache, ScheduledExecutorService scheduler, NettyTransport transport, Predicate<? super String> ignoreCache, MediaType valuePayload) { super(MemcachedDecoderState.DECODE_HEADER); this.cache = (AdvancedCache<byte[], byte[]>) memcachedCache.withMediaType(TEXT_PLAIN_TYPE, valuePayload.toString()); this.scheduler = scheduler; this.transport = transport; this.ignoreCache = ignoreCache; isStatsEnabled = cache.getCacheConfiguration().jmxStatistics().enabled(); }
private static KeyValuePair<String, String> getRequestMediaTypes(HotRodHeader header, Configuration configuration) { String keyRequestType = header == null ? APPLICATION_UNKNOWN_TYPE : header.getKeyMediaType().toString(); String valueRequestType = header == null ? APPLICATION_UNKNOWN_TYPE : header.getValueMediaType().toString(); if (header != null && HotRodVersion.HOTROD_28.isOlder(header.version)) { // Pre-2.8 clients always send protobuf payload to the metadata cache if (header.cacheName.equals(PROTOBUF_METADATA_CACHE_NAME)) { keyRequestType = APPLICATION_PROTOSTREAM_TYPE; valueRequestType = APPLICATION_PROTOSTREAM_TYPE; } else { // Pre-2.8 clients always sent query encoded as protobuf unless object store is used. if (header.op == HotRodOperation.QUERY) { boolean objectStorage = APPLICATION_OBJECT.match(configuration.encoding().valueDataType().mediaType()); keyRequestType = objectStorage ? APPLICATION_JBOSS_MARSHALLING_TYPE : APPLICATION_PROTOSTREAM_TYPE; valueRequestType = objectStorage ? APPLICATION_JBOSS_MARSHALLING_TYPE : APPLICATION_PROTOSTREAM_TYPE; } } } return new KeyValuePair<>(keyRequestType, valueRequestType); }
/** * Convert text content to a different encoding. * * @param source The source content. * @param sourceType MediaType for the source content. * @param destinationType the MediaType of the converted content. * @return content conforming to the destination MediaType. */ public static Object convertTextToText(Object source, MediaType sourceType, MediaType destinationType) { if (source == null) return null; if (sourceType == null) throw new NullPointerException("MediaType cannot be null!"); if (!sourceType.match(MediaType.TEXT_PLAIN)) throw log.invalidMediaType(TEXT_PLAIN_TYPE, sourceType.toString()); boolean asString = destinationType.hasStringType(); Charset sourceCharset = sourceType.getCharset(); Charset destinationCharset = destinationType.getCharset(); if (sourceCharset.equals(destinationCharset)) return convertTextClass(source, destinationType, asString); byte[] byteContent = source instanceof byte[] ? (byte[]) source : source.toString().getBytes(sourceCharset); return convertTextClass(convertCharset(byteContent, sourceCharset, destinationCharset), destinationType, asString); }
void setEventMarshaller(Optional<Marshaller> eventMarshaller) { eventMarshaller.ifPresent(m -> { TranscoderMarshallerAdapter adapter = new TranscoderMarshallerAdapter(m); if (encoderRegistry.isConversionSupported(MediaType.APPLICATION_OBJECT, m.mediaType())) { log.skippingMarshallerWrapping(m.mediaType().toString()); } else { encoderRegistry.registerTranscoder(adapter); } }); }
Object read() throws IOException { HttpMethod get = new GetMethod(getEndpoint(this.cacheName) + "/" + this.key); if (this.accept != null) { get.setRequestHeader(ACCEPT, this.accept.toString()); } if (keyContentType != null) { get.setRequestHeader("Key-Content-Type", this.keyContentType); } restClient.executeMethod(get); assertEquals(get.getStatusCode(), HttpStatus.SC_OK); return get.getResponseBody(); } }
String scriptMediaType = metadata.dataType().toString(); MediaType requestMediaType = context.getCache().map(c -> c.getAdvancedCache().getValueDataConversion().getRequestMediaType()).orElse(MediaType.MATCH_ALL); Bindings userBindings = context.getParameters()
protected void write(int id, String contents, HttpMethod method, MediaType contentType) throws Exception { ContentResponse response = client .newRequest(String.format("http://localhost:%d/rest/%s/%d", pickServer().getPort(), CACHE_NAME, id)) .method(method) .content(new StringContentProvider(contents)) .header(HttpHeader.CONTENT_TYPE, contentType.toString()) .send(); assertEquals(response.getStatus(), HttpStatus.OK_200); }
@Test public void testByteArrayKeysAndByteArrayValues() throws Exception { // Write via Hot Rod the byte[] content directly byte[] key = new byte[]{0x13, 0x26}; byte[] value = new byte[]{10, 20}; defaultRemoteCache.put(key, value); assertArrayEquals(defaultRemoteCache.get(key), value); // Read via Rest Object bytesFromRest = new RestRequest().cache(DEFAULT_CACHE_NAME) .key("0x1326", APPLICATION_OCTET_STREAM.withParameter("encoding", "hex").toString()) .accept(APPLICATION_OCTET_STREAM) .read(); assertEquals(bytesFromRest, value); // Write via rest byte[] newKey = new byte[]{0, 0, 0, 1}; // Write via rest new RestRequest().cache(DEFAULT_CACHE_NAME) .key("0x00000001", MediaType.APPLICATION_OCTET_STREAM.withParameter("encoding", "hex").toString()) .value(value) .write(); // Read via Hot Rod assertEquals(defaultRemoteCache.get(newKey), value); }
void putBinaryValueInCache(String cacheName, String key, byte[] value, MediaType mediaType) throws InterruptedException, ExecutionException, TimeoutException { ContentResponse response = client .newRequest(String.format("http://localhost:%d/rest/%s/%s", restServer().getPort(), cacheName, key)) .content(new BytesContentProvider(value)) .header(HttpHeader.CONTENT_TYPE, mediaType.toString()) .method(HttpMethod.PUT) .send(); ResponseAssertion.assertThat(response).isOk(); }
@Test public void shouldGetOctetStreamValueStoredInSpecificFormat() throws Exception { //given TestClass testClass = new TestClass(); testClass.setName("test"); putBinaryValueInCache("serialized", "test", convertToBytes(testClass), APPLICATION_SERIALIZED_OBJECT); //when ContentResponse response = client .newRequest(String.format("http://localhost:%d/rest/%s/%s", restServer().getPort(), "serialized", "test")) .send(); TestClass convertedObject = convertFromBytes(response.getContent(), TestClass.class); //then ResponseAssertion.assertThat(response).isOk(); ResponseAssertion.assertThat(response).hasContentType(APPLICATION_SERIALIZED_OBJECT.toString()); ResponseAssertion.assertThat(response).hasNoCharset(); Assertions.assertThat(convertedObject.getName()).isEqualTo("test"); }
@Test public void testRestPutEmbeddedMemcachedHotRodGetTest() throws Exception { final String key = "3"; final Object value = "<hey>ho</hey>"; final Marshaller marshaller = cacheFactory.getMarshaller(); // 1. Put with REST byte[] bytes = marshaller.objectToByteBuffer(value); EntityEnclosingMethod put = new PutMethod(cacheFactory.getRestUrl() + "/" + key); put.setRequestEntity(new ByteArrayRequestEntity(bytes, marshaller.mediaType().toString())); HttpClient restClient = cacheFactory.getRestClient(); restClient.executeMethod(put); assertEquals(HttpStatus.SC_OK, put.getStatusCode()); assertEquals("", put.getResponseBodyAsString().trim()); // 2. Get with Embedded (given a marshaller, it can unmarshall the result) assertEquals(value, cacheFactory.getEmbeddedCache().get(key)); // 3. Get with Memcached (given a marshaller, it can unmarshall the result) assertEquals(value, cacheFactory.getMemcachedClient().get(key)); // 4. Get with Hot Rod assertEquals(value, cacheFactory.getHotRodCache().get(key)); } }