List of usage examples for io.netty.buffer ByteBufInputStream ByteBufInputStream
public ByteBufInputStream(ByteBuf buffer)
From source file:com.mastfrog.acteur.ContentConverter.java
License:Open Source License
protected <T> T readObject(ByteBuf buf, MediaType mimeType, Class<T> type) throws IOException, InvalidInputException { if (type == String.class || type == CharSequence.class) { return type.cast(toString(buf, findCharset(mimeType))); }// ww w .j a va 2 s. c o m Origin origin = type.getAnnotation(Origin.class); if (origin != null) { Map map; try (InputStream in = new ByteBufInputStream(buf)) { map = codec.readValue(in, Map.class); validate(origin, map).throwIfFatalPresent(); } catch (IOException ioe) { ioe.printStackTrace(); throw ioe; } finally { buf.resetReaderIndex(); } } buf.resetReaderIndex(); try (InputStream in = new ByteBufInputStream(buf)) { T result = codec.readValue(in, type); return result; } catch (IOException ioe) { ioe.printStackTrace(); throw ioe; } finally { buf.resetReaderIndex(); } }
From source file:com.mastfrog.acteur.resources.ClasspathResources.java
License:Open Source License
static void gzip(ByteBuf in, ByteBuf out) throws IOException { try (GZIPOutputStream outStream = new GZIPOutputStream(new ByteBufOutputStream(out), 9)) { try (ByteBufInputStream inStream = new ByteBufInputStream(in)) { Streams.copy(inStream, outStream, 512); }//w ww.ja va 2 s. co m } }
From source file:com.mastfrog.acteur.server.EventImpl.java
License:Open Source License
@Override public <T> T getContentAsJSON(Class<T> type) throws IOException { // Special handling for strings if (type == String.class || type == CharSequence.class) { String result = Streams.readString(new ByteBufInputStream(getContent())); if (result.length() > 0 && result.charAt(0) == '"') { result = result.substring(1); }//w w w . j a va 2 s . co m if (result.length() > 1 && result.charAt(result.length() - 1) == '"') { result = result.substring(0, result.length() - 2); } return (T) result; } ByteBuf content = getContent(); try { return codec.readValue(new ByteBufInputStream(content), type); } finally { content.resetReaderIndex(); } }
From source file:com.mastfrog.netty.http.client.ResponseHandler.java
License:Open Source License
protected void internalReceive(HttpResponseStatus status, HttpHeaders headers, ByteBuf content) { try {/*from www .j ava 2 s . co m*/ if (status.code() > 399) { byte[] b = new byte[content.readableBytes()]; content.readBytes(b); onErrorResponse(status, headers, new String(b, CharsetUtil.UTF_8)); return; } if (type == ByteBuf.class) { _doReceive(status, headers, type.cast(content)); } else if (type == String.class || type == CharSequence.class) { byte[] b = new byte[content.readableBytes()]; content.readBytes(b); _doReceive(status, headers, type.cast(new String(b, CharsetUtil.UTF_8))); } else if (type == byte[].class) { byte[] b = new byte[content.readableBytes()]; content.readBytes(b); _doReceive(status, headers, type.cast(b)); } else { byte[] b = new byte[content.readableBytes()]; content.readBytes(b); try { Object o = mapper.readValue(b, type); _doReceive(status, headers, type.cast(o)); } catch (JsonParseException ex) { content.resetReaderIndex(); try { String s = Streams.readString(new ByteBufInputStream(content), "UTF-8"); onErrorResponse(HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE, headers, s); } catch (IOException ex1) { Exceptions.chuck(ex1); } } catch (Exception ex) { Exceptions.chuck(ex); } } } finally { latch.countDown(); } }
From source file:com.mastfrog.scamper.compression.CompressingCodec.java
License:Open Source License
static String bb2s(ByteBuf buf) throws IOException { int old = buf.readerIndex(); try (ByteBufInputStream in = new ByteBufInputStream(buf)) { return Streams.readString(in); } finally {//from w ww . ja va2s . c o m buf.readerIndex(old); } }
From source file:com.mastfrog.scamper.compression.CompressingCodec.java
License:Open Source License
protected void compress(ByteBuf in, ByteBuf out) throws IOException { try (GZIPOutputStream outStream = new GZIPOutputStream(new ByteBufOutputStream(out), level)) { try (ByteBufInputStream inStream = new ByteBufInputStream(in)) { Streams.copy(inStream, outStream, 512); }// w w w .j a va2 s .co m } }
From source file:com.mastfrog.scamper.compression.CompressingCodec.java
License:Open Source License
protected void uncompress(ByteBuf in, ByteBuf out) throws IOException { try (GZIPInputStream ins = new GZIPInputStream(new ByteBufInputStream(in))) { try (ByteBufOutputStream outs = new ByteBufOutputStream(out)) { Streams.copy(ins, outs, 512); }/*from ww w. j a va 2s . c o m*/ } }
From source file:com.mastfrog.scamper.password.crypto.EncryptingCodecTest.java
License:Open Source License
private String dataFrom(ByteBuf buf) throws IOException { int old = buf.readerIndex(); try (ByteBufInputStream in = new ByteBufInputStream(buf)) { return Streams.readString(in); } finally {/*from w w w . jav a 2 s.c om*/ buf.readerIndex(old); } }
From source file:com.mastfrog.tinymavenproxy.FileFinder.java
License:Open Source License
public synchronized void put(final Path path, final ByteBuf content, final DateTime lastModified) { // This method is currently unused, but if we enhance the server to accept // uploads, we will likely need code a lot like this if (content.readableBytes() == 0) { return;/* w w w. ja v a 2 s . c o m*/ } final ByteBuf buf = content.duplicate(); threadPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { final File target = new File(config.dir, path.toString().replace('/', File.separatorChar)); buf.retain(); if (!target.exists()) { if (!target.getParentFile().exists()) { if (!target.getParentFile().mkdirs()) { throw new IOException("Could not create " + target.getParentFile()); } } if (!target.createNewFile()) { throw new IOException("Could not create " + target); } } try (ByteBufInputStream in = new ByteBufInputStream(buf)) { try (OutputStream out = new BufferedOutputStream(new FileOutputStream(target))) { Streams.copy(in, out, 1024); } } catch (IOException ioe) { if (target.exists()) { target.delete(); } throw ioe; } finally { buf.release(); } threadPool.submit(new Runnable() { @Override public void run() { if (lastModified != null) { target.setLastModified(lastModified.getMillis()); } } }); return null; } }); }
From source file:com.mesosphere.mesos.rx.java.test.simulation.MesosServerSimulation.java
License:Apache License
/** * Create a {@code MesosServerSimulation} that will use {@code events} as the event stream to return to a * a client when {@code isSubscribePredicate} evaluates to {@code true} * <p>/*from w w w . j a v a 2 s . c o m*/ * The simulation server must be started using {@link #start()} before requests can be serviced by the server. * * @param events The event stream to be returned by the server upon {@code isSubscribePredicate} * evaluating to {@code true} For each {@link Event} sent to {@code events}, the event * will be sent by the server. * @param sendCodec The {@link MessageCodec} to use to encode {@link Event}s sent by the server * @param receiveCodec The {@link MessageCodec} to use to decode {@link Call}s received by the server * @param isSubscribePredicate The predicate used to determine if a {@link Call} is a "Subscribe" call */ public MesosServerSimulation(@NotNull final Observable<Event> events, @NotNull final MessageCodec<Event> sendCodec, @NotNull final MessageCodec<Call> receiveCodec, @NotNull final Predicate<Call> isSubscribePredicate) { this.callsReceived = Collections.synchronizedList(new ArrayList<>()); this.started = new AtomicBoolean(false); this.eventsCompletedLatch = new CountDownLatch(1); this.subscribedLatch = new CountDownLatch(1); this.sem = new Semaphore(0); this.server = RxNetty.createHttpServer(0, (request, response) -> { response.getHeaders().setHeader("Accept", receiveCodec.mediaType()); if (!"/api/v1/scheduler".equals(request.getUri())) { response.setStatus(HttpResponseStatus.NOT_FOUND); response.getHeaders().setHeader("Content-Length", "0"); return response.close(); } if (!HttpMethod.POST.equals(request.getHttpMethod()) || !receiveCodec.mediaType().equals(request.getHeaders().getHeader("Content-Type")) || request.getHeaders().getContentLength() <= 0) { response.setStatus(HttpResponseStatus.BAD_REQUEST); response.getHeaders().setHeader("Content-Length", "0"); return response.close(); } return request.getContent().flatMap(buf -> { final ByteBufInputStream in = new ByteBufInputStream(buf); final Call call = receiveCodec.decode(in); if (callsReceived.add(call)) { sem.release(); } LOGGER.debug(RECEIVE_MARKER, "Call: {}", receiveCodec.show(call)); if (isSubscribePredicate.test(call)) { if (subscribedLatch.getCount() == 0) { final String message = "Only one event stream can be open per server"; response.setStatus(HttpResponseStatus.CONFLICT); response.getHeaders().set("Content-Type", "test/plain;charset=utf-8"); response.writeString(message); return response.close(); } LOGGER.debug("Responding with event stream from source: {}", events); response.getHeaders().setTransferEncodingChunked(); response.getHeaders().set("Content-Type", sendCodec.mediaType()); response.getHeaders().add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); response.getHeaders().add("Pragma", "no-cache"); final Subject<Void, Void> subject = PublishSubject.create(); final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription(); final Subscription actionSubscription = events .doOnSubscribe(() -> LOGGER.debug("Event stream subscription active")) .doOnNext(e -> LOGGER.debug(SEND_MARKER, "Event: {}", sendCodec.show(e))) .doOnError((t) -> LOGGER.error("Error while creating response", t)) .doOnCompleted(() -> { eventsCompletedLatch.countDown(); LOGGER.debug("Sending events complete"); if (!response.isCloseIssued()) { response.close(true); } }).map(sendCodec::encode).map(RecordIOUtils::createChunk).subscribe(bytes -> { if (!response.getChannel().isOpen()) { subscription.unsubscribe(); return; } try { LOGGER.trace(SEND_MARKER, "bytes: {}", Arrays.toString(bytes)); response.writeBytesAndFlush(bytes); } catch (Exception e) { subject.onError(e); } }); subscription.set(actionSubscription); subscribedLatch.countDown(); return subject; } else { response.setStatus(HttpResponseStatus.ACCEPTED); return response.close(); } }); }); }