public static void sendFrame(String type, String address, String replyAddress, String headers, Boolean send, String body, WriteStream<Buffer> handler) { final JsonObject payload = new JsonObject().put("type", type); if (address != null) { payload.put("address", address); } if (replyAddress != null) { payload.put("replyAddress", replyAddress); } if (headers != null) { payload.put("headers", headers); } if (body != null) { payload.put("body", body); } if (send != null) { payload.put("send", send); } writeFrame(payload, handler); }
@Override public FdfsClient download(FdfsFileId fileId, WriteStream<Buffer> stream, long offset, long bytes, Handler<AsyncResult<Void>> handler) { getTracker().setHandler(tracker -> { if (tracker.succeeded()) { tracker.result().getFetchStorage(fileId, storage -> { if (storage.succeeded()) { storage.result().download(fileId, stream, offset, bytes, download -> { handler.handle(download); }); } else { handler.handle(Future.failedFuture(storage.cause())); } }); } else { handler.handle(Future.failedFuture(tracker.cause())); } }); return this; }
public static Observable<Void> append(Buffer buffer, final WriteStream<Buffer> ws) { return Observable.defer(() -> { ObservableFuture<Void> drainHandler = RxHelper.observableFuture(); ws.exceptionHandler(drainHandler::fail); if (ws.writeQueueFull()) { ws.drainHandler(drainHandler::complete); } else { drainHandler.complete(null); } return drainHandler.flatMap(aVoid -> { ObservableFuture<Void> writeHandler = RxHelper.observableFuture(); ws.exceptionHandler(writeHandler::fail); ws.write(buffer); if (ws.writeQueueFull()) { ws.drainHandler(writeHandler::complete); } else { writeHandler.complete(null); } return writeHandler; }); }); }
@Override public Observable<Void> merge(ChunkReadStream chunk, XMLChunkMeta meta, WriteStream<Buffer> out) { return canMerge(meta) .flatMap(b -> { if (!b) { return Observable.error(new IllegalArgumentException( "Chunk cannot be merged with this strategy")); } if (!headerWritten) { writeHeader(out); headerWritten = true; } return writeChunk(chunk, meta, out); }); }
/** * Test a simple import * @param context the test context */ @Test public void simpleImport(TestContext context) { String url = "/store"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(202))); Async async = context.async(); WriteStream<Buffer> w = client.getStore().startImport( context.asyncAssertSuccess(v -> { verifyPosted(url, XML, context); async.complete(); })); w.end(Buffer.buffer(XML)); }
/** * Test importing to a layer * @param context the test context */ @Test public void importLayer(TestContext context) { String url = "/store/hello/world/"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(202))); Async async = context.async(); WriteStream<Buffer> w = client.getStore().startImport("hello/world", context.asyncAssertSuccess(v -> { verifyPosted(url, XML, context); async.complete(); })); w.end(Buffer.buffer(XML)); }
/** * Test importing to a layer with special characters * @param context the test context */ @Test public void importLayerWithSpecialChars(TestContext context) { String url = "/store/he%2Bllo/world/"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(202))); Async async = context.async(); WriteStream<Buffer> w = client.getStore().startImport("he+llo/world", context.asyncAssertSuccess(v -> { verifyPosted(url, XML, context); async.complete(); })); w.end(Buffer.buffer(XML)); }
/** * Test importing with tags * @param context the test context * @throws Exception if something goes wrong */ @Test public void importTags(TestContext context) throws Exception { String url = "/store?tags=hello%2Cworld"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(202))); Async async = context.async(); WriteStream<Buffer> w = client.getStore().startImport(null, Arrays.asList("hello", "world"), context.asyncAssertSuccess(v -> { verifyPosted(url, XML, context); async.complete(); })); w.end(Buffer.buffer(XML)); }
/** * Test importing properties * @param context the test context * @throws Exception if something goes wrong */ @Test public void importProperties(TestContext context) throws Exception { String url = "/store?props=hello%3Aworld%2Ckey%3Avalue"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(202))); Async async = context.async(); WriteStream<Buffer> w = client.getStore().startImport(null, null, Arrays.asList("hello:world", "key:value"), context.asyncAssertSuccess(v -> { verifyPosted(url, XML, context); async.complete(); })); w.end(Buffer.buffer(XML)); }
/** * Test importing tags and properties * @param context the test context * @throws Exception if something goes wrong */ @Test public void importTagsAndProperties(TestContext context) throws Exception { String url = "/store?tags=testTag%2CtestTag2&props=hello%3Awo%5C%3Arld%2Challo2%3Aworld2"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(202))); Async async = context.async(); WriteStream<Buffer> w = client.getStore().startImport(null, Arrays.asList("testTag", "testTag2"), Arrays.asList("hello:wo\\:rld", "hallo2:world2"), context.asyncAssertSuccess(v -> { verifyPosted(url, XML, context); async.complete(); })); w.end(Buffer.buffer(XML)); }
/** * Test importing tags and properties * @param context the test context * @throws Exception if something goes wrong */ @Test public void importCRS(TestContext context) throws Exception { String url = "/store?fallbackCRS=test"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(202))); Async async = context.async(); WriteStream<Buffer> w = client.getStore() .startImport(null, null, null, Optional.empty(), "test", context.asyncAssertSuccess(v -> { verifyPosted(url, XML, context); async.complete(); })); w.end(Buffer.buffer(XML)); }
/** * Test importing tags and properties * @param context the test context * @throws Exception if something goes wrong */ @Test public void importTagsAndCRS(TestContext context) throws Exception { String url = "/store?tags=testTag%2CtestTag2&props=" + "hello%3Awo%5C%3Arld%2Challo2%3Aworld2&fallbackCRS=test"; stubFor(post(urlEqualTo(url)) .willReturn(aResponse() .withStatus(202))); Async async = context.async(); WriteStream<Buffer> w = client.getStore() .startImport(null, Arrays.asList("testTag", "testTag2"), Arrays.asList("hello:wo\\:rld", "hallo2:world2"), Optional.empty(), "test", context.asyncAssertSuccess(v -> { verifyPosted(url, XML, context); async.complete(); })); w.end(Buffer.buffer(XML)); }
public static void sendFrame(String type, String address, String replyAddress, JsonObject headers, Boolean send, JsonObject body, WriteStream<Buffer> handler) { final JsonObject payload = new JsonObject().put("type", type); if (address != null) { payload.put("address", address); } if (replyAddress != null) { payload.put("replyAddress", replyAddress); } if (headers != null) { payload.put("headers", headers); } if (body != null) { payload.put("body", body); } if (send != null) { payload.put("send", send); } writeFrame(payload, handler); }
@Test public void testMethodWithTypeVarParamByGenericType() throws Exception { Runnable test = () -> { try { ClassModel model = new Generator().generateClass(MethodWithTypeVarParamByGenericType.class); MethodInfo meth = model.getMethods().get(0); ParamInfo param = meth.getParam(0); ParameterizedTypeInfo handler = (ParameterizedTypeInfo) param.getType(); assertEquals(Handler.class.getName(), handler.getRaw().getName()); ParameterizedTypeInfo genericInt2 = (ParameterizedTypeInfo) handler.getArg(0); assertEquals(GenericInterface2.class.getName(), genericInt2.getRaw().getName()); TypeVariableInfo k = (TypeVariableInfo) genericInt2.getArg(0); assertEquals("K", k.getName()); TypeVariableInfo v = (TypeVariableInfo) genericInt2.getArg(1); assertEquals("V", v.getName()); } catch (Exception e) { throw new AssertionError(e); } }; blacklist(test, Stream.of(WriteStream.class)); test.run(); }
@Override public WriteStream<PipelinePack> write(PipelinePack data) { return write(data, asyncResult -> { if (asyncResult.failed()) { if (exceptionHandler != null) exceptionHandler.handle(asyncResult.cause()); return; } if (writeCompleteHandler != null) { final WriteCompleteFuture<Void> future = WriteCompleteFuture.future(asyncResult.result()); future.setHandler(commitDone -> { if (commitDone.failed()) { logger.warn("StreamMux - Error during commit. Really nothing we can do here. The producer should retry " + "if it is 'reliable'. Invoking the mux exceptionHandler."); if (exceptionHandler != null) exceptionHandler.handle(asyncResult.cause()); } logger.debug("StreamMux - The exchange is complete now."); }); writeCompleteHandler.handle(future); } }); }
public static void sendErrFrame(String address, String replyAddress, ReplyException failure, WriteStream<Buffer> handler) { final JsonObject payload = new JsonObject() .put("type", "err") .put("address", replyAddress) .put("sourceAddress", address) .put("failureCode", failure.failureCode()) .put("failureType", failure.failureType().name()) .put("message", failure.getMessage()); writeFrame(payload, handler); }
public static void sendErrFrame(String message, WriteStream<Buffer> handler) { final JsonObject payload = new JsonObject() .put("type", "err") .put("message", message); writeFrame(payload, handler); }
@Override public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) { this.exceptionHandler = handler; BufferEndableWriteStream dst = maybeGetWriteStream(); if (dst != null) { dst.exceptionHandler(handler); } return this; }
@Override public WriteStream<Buffer> write(Buffer data) { checkReadStreamNotOpen(); size += data.length(); BufferEndableWriteStream dst = maybeGetWriteStream(); if (dst != null) { dst.write(data); } else { memory.appendBuffer(data); handleDrain(); } return this; }
@Override public Observable<Void> merge(ChunkReadStream chunk, ChunkMeta meta, WriteStream<Buffer> out) { return ensureMerger(meta) .flatMap(v -> { if (meta instanceof XMLChunkMeta) { return xmlMerger.merge(chunk, (XMLChunkMeta)meta, out); } return geoJsonMerger.merge(chunk, (GeoJsonChunkMeta)meta, out); }); }
@Override public void finish(WriteStream<Buffer> out) { if (xmlMerger != null) { xmlMerger.finish(out); } if (geoJsonMerger != null) { geoJsonMerger.finish(out); } }
@Override public Observable<Void> merge(ChunkReadStream chunk, XMLChunkMeta meta, WriteStream<Buffer> out) { mergeStarted = true; if (strategy == null) { return Observable.error(new IllegalStateException( "You must call init() at least once")); } return strategy.merge(chunk, meta, out); }
@Override public void finish(WriteStream<Buffer> out) { // close all parent elements for (int i = parents.size() - 1; i >= 0; --i) { XMLStartElement e = parents.get(i); out.write(Buffer.buffer("</" + e.getName() + ">")); } }
/** * Write the header * @param out the output stream to write to */ private void writeHeader(WriteStream<Buffer> out) { if (mergedType == FEATURE_COLLECTION) { out.write(Buffer.buffer("{\"type\":\"FeatureCollection\",\"features\":[")); } else if (mergedType == GEOMETRY_COLLECTION) { out.write(Buffer.buffer("{\"type\":\"GeometryCollection\",\"geometries\":[")); } }
@Override public Observable<Void> merge(ChunkReadStream chunk, GeoJsonChunkMeta meta, WriteStream<Buffer> out) { mergeStarted = true; if (!headerWritten) { writeHeader(out); headerWritten = true; } else { if (mergedType == FEATURE_COLLECTION || mergedType == GEOMETRY_COLLECTION) { out.write(Buffer.buffer(",")); } else { return Observable.error(new IllegalStateException( "Trying to merge two or more chunks but the merger has only been " + "initialized with one chunk.")); } } // check if we have to wrap a geometry into a feature boolean wrap = mergedType == FEATURE_COLLECTION && !"Feature".equals(meta.getType()); if (wrap) { out.write(Buffer.buffer("{\"type\":\"Feature\",\"geometry\":")); } return writeChunk(chunk, meta, out) .doOnNext(v -> { if (wrap) { out.write(Buffer.buffer("}")); } }); }
/** * <p>Start importing data to GeoRocket. The method opens a connection to the * GeoRocket server and returns a {@link WriteStream} that can be used to * send data.</p> * <p>The caller is responsible for closing the stream (and ending * the import process) through {@link WriteStream#end()} and handling * exceptions through {@link WriteStream#exceptionHandler(Handler)}.</p> * @param layer the layer to import to (may be <code>null</code> if data * should be imported to the root layer) * @param tags a collection of tags to attach to the imported data (may be * <code>null</code> if no tags need to be attached) * @param properties a collection of properties to attach to the imported * data (may be <code>null</code> if no properties need to be attached) * @param size size of the data to be sent in bytes (optional) * @param fallbackCRS the CRS which should be used if the imported file does * not specify one (may be <code>null</code>) * @param handler a handler that will be called when the data has been * imported by the GeoRocket server * @return a {@link WriteStream} that can be used to send data * @since 1.1.0 */ public WriteStream<Buffer> startImport(String layer, Collection<String> tags, Collection<String> properties, Optional<Long> size, String fallbackCRS, Handler<AsyncResult<Void>> handler) { String path = prepareImport(layer, tags, properties, fallbackCRS); HttpClientRequest request = client.post(path); if (size.isPresent() && size.get() != null) { request.putHeader("Content-Length", size.get().toString()); } else { // content length is not set, therefore chunked encoding must be set request.setChunked(true); } request.handler(response -> { if (response.statusCode() != 202) { fail(response, handler, message -> { ClientAPIException e = ClientAPIException.parse(message); String msg = String.format( "GeoRocket did not accept the file (status code %s: %s) %s", response.statusCode(), response.statusMessage(), e.getMessage()); return new ClientAPIException(e.getType(), msg); }); } else { handler.handle(Future.succeededFuture()); } }); return configureRequest(request); }
@Override public WriteStream<Buffer> drainHandler(Handler<Void> handler) { _drainHandler = handler; if (!_waitForDrain) { _socket.drainHandler(_drainHandler); } return this; }
/** * Creates a new instance of <code>AbstractDataHandler</code>. * * @param pServer the JVx server * @param pStream the write stream * @param pWaitForEnd <code>true</code> to wait for end of processing, <code>false</code> to continue processing */ protected AbstractDataHandler(Server pServer, WriteStream<Buffer> pStream, boolean pWaitForEnd) { server = pServer; stream = pStream; inputStream = new SyncedInputStream(); bWaitForEnd = pWaitForEnd; }
public static <T extends WriteStream<Buffer>> Observable<Tup2<T, Proto.Msg>> convertBufferStreamToMessages(T socket, Observable<Buffer> observable) { return Observable.create(new BufferAction(observable)).map(r -> { try { return Proto.Msg.parseFrom(r.getBytes(4, r.length())); } catch (Exception e) { throw new NetSocketException(socket, e); } }).map(b -> Tup2.create(socket, b)); }
private void sendResponse(Proto.Msg msg, WriteStream<Buffer> sock) { byte[] bytes = msg.toByteArray(); Buffer response = Buffer.buffer(); response.appendInt(bytes.length); response.appendBytes(bytes); sock.write(response); }
public void receiveResponseAsWriteStream(WebClient client, WriteStream<Buffer> writeStream) { client .get(8080, "myserver.mycompany.com", "/some-uri") .as(BodyCodec.pipe(writeStream)) .send(ar -> { if (ar.succeeded()) { HttpResponse<Void> response = ar.result(); System.out.println("Received response with status code" + response.statusCode()); } else { System.out.println("Something went wrong " + ar.cause().getMessage()); } }); }
@Override public WriteStream<Buffer> write(Buffer data) { logger.info(data.toString()); if (configObj.getBoolean("successResponse", false)) { dataHandler.handle(Buffer.buffer(new byte[] {0x1})); } return this; }
protected void sendMessageToClient(Buffer bytes, WriteStream<Buffer> writer, ReadStream<Buffer> reader) { try { writer.write(bytes); if (writer.writeQueueFull()) { reader.pause(); writer.drainHandler( done -> reader.resume() ); } } catch(Throwable e) { logger.error(e.getMessage()); } }
public SocketWrapper(WriteStream<Buffer> w, ReadStream<Buffer> r) { if(w==null) throw new IllegalArgumentException("SocketWrapper: write stream cannot be null"); if(r==null) throw new IllegalArgumentException("SocketWrapper: read stream cannot be null"); this.w = w; this.r = r; }
@Override public WriteStream<Buffer> write(Buffer data) { byte[] buffer = data.getBytes(); buffers.addLast(buffer); size += buffer.length; return this; }
public static void sendFrame(String type, String address, String replyAddress, String body, WriteStream<Buffer> handler) { sendFrame(type, address, replyAddress, null, null, body, handler); }
public static void sendFrame(String type, String address, String body, WriteStream<Buffer> handler) { sendFrame(type, address, null, null, null, body, handler); }
public static void sendFrame(String type, WriteStream<Buffer> handler) { sendFrame(type, null, null, null, null, null, handler); }