List of usage examples for io.netty.buffer ByteBufInputStream ByteBufInputStream
public ByteBufInputStream(ByteBuf buffer)
From source file:divconq.net.ssl.JdkSslServerContext.java
License:Apache License
public JdkSslServerContext(File certChainFile, File keyFile, String keyPassword, Iterable<String> ciphers, Iterable<String> nextProtocols, long sessionCacheSize, long sessionTimeout) throws SSLException { super(ciphers); if (certChainFile == null) { throw new NullPointerException("certChainFile"); }/*w w w .j av a 2s .c om*/ if (keyFile == null) { throw new NullPointerException("keyFile"); } if (keyPassword == null) { keyPassword = ""; } if (nextProtocols != null && nextProtocols.iterator().hasNext()) { throw new SSLException("NPN/ALPN unsupported: " + nextProtocols); } else { this.nextProtocols = Collections.emptyList(); } String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } try { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); KeyFactory rsaKF = KeyFactory.getInstance("RSA"); KeyFactory dsaKF = KeyFactory.getInstance("DSA"); ByteBuf encodedKeyBuf = PemReader.readPrivateKey(keyFile); byte[] encodedKey = new byte[encodedKeyBuf.readableBytes()]; encodedKeyBuf.readBytes(encodedKey).release(); char[] keyPasswordChars = keyPassword.toCharArray(); PKCS8EncodedKeySpec encodedKeySpec = generateKeySpec(keyPasswordChars, encodedKey); PrivateKey key; try { key = rsaKF.generatePrivate(encodedKeySpec); } catch (InvalidKeySpecException ignore) { key = dsaKF.generatePrivate(encodedKeySpec); } List<Certificate> certChain = new ArrayList<Certificate>(); ByteBuf[] certs = PemReader.readCertificates(certChainFile); try { for (ByteBuf buf : certs) { certChain.add(cf.generateCertificate(new ByteBufInputStream(buf))); } } finally { for (ByteBuf buf : certs) { buf.release(); } } ks.setKeyEntry("key", key, keyPasswordChars, certChain.toArray(new Certificate[certChain.size()])); // Set up key manager factory to use our key store KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(ks, keyPasswordChars); // Initialize the SSLContext to work with our key managers. ctx = SSLContext.getInstance(PROTOCOL); ctx.init(kmf.getKeyManagers(), null, null); SSLSessionContext sessCtx = ctx.getServerSessionContext(); if (sessionCacheSize > 0) { sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE)); } if (sessionTimeout > 0) { sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE)); } } catch (Exception e) { throw new SSLException("failed to initialize the server-side SSL context", e); } }
From source file:eastwind.webpush.WebPushHandler.java
License:Apache License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame Channel channel = ctx.channel(); if (frame instanceof CloseWebSocketFrame) { handshaker.close(channel, (CloseWebSocketFrame) frame.retain()); return;/*from www . ja va 2 s . co m*/ } UserLite u = UserLite.get(channel); Session s = sessionManager.get(u.uid, u.uuid); if (s == null) { UserLite.set(channel, null); ctx.writeAndFlush(Message.FORBIDDEN); return; } Stat.setLastRead(channel); if (frame instanceof PingWebSocketFrame) { channel.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame tf = (TextWebSocketFrame) frame; ByteBufInputStream is = new ByteBufInputStream(tf.content()); try { handleWsOper(channel, u, s, is); } catch (IOException e) { e.printStackTrace(); } } }
From source file:etcd.client.DefaultEtcdClient.java
License:Open Source License
private void throwException(FullHttpResponse response) { try {/*from w w w . java2 s. co m*/ final ErrorBody errorBody = MAPPER.readValue(new ByteBufInputStream(response.content()), ErrorBody.class); final String message = errorBody.message == null ? "Error executing request" : errorBody.message; if (response.getStatus().code() == HttpResponseStatus.NOT_FOUND.code()) { throw new KeyNotFoundException(message, errorBody.errorCode, errorBody.index, errorBody.cause); } final Long etcdIndex = Long.valueOf(response.headers().get("X-Etcd-Index")); throw new EtcdRequestException(message, errorBody.errorCode, etcdIndex, errorBody.cause); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:etcd.client.DefaultEtcdClient.java
License:Open Source License
private Result marshalResult(FullHttpResponse response) { try {//from w ww.j a v a 2s. c om final EtcdMeta meta = new EtcdMeta(convertLong(response.headers().get("X-Etcd-Index")), convertLong(response.headers().get("X-Raft-Index")), convertLong(response.headers().get("X-Raft-Term"))); final ByteBuf content = response.content(); if (content.readableBytes() > 0) { final ByteBufInputStream inputStream = new ByteBufInputStream(content); final JsonResult json = MAPPER.readValue(inputStream, JsonResult.class); return new Result() { @Override public EtcdMeta getResponseMeta() { return meta; } @Override public Action getAction() { return json.action; } @Override public Node getNode() { return json.node; } @Override public Optional<Node> getPreviousNode() { return Optional.ofNullable(json.previousNode); } @Override public String toString() { return "Result {" + "meta = " + getResponseMeta() + ", action = " + getAction() + ", node = " + getNode() + ", prevNode = " + getPreviousNode().orElse(null) + "}"; } }; } else { throw new EtcdException("Empty response from server."); } } catch (IOException e) { throw new EtcdException(e); } }
From source file:forestry.core.network.PacketHandler.java
License:Open Source License
@SubscribeEvent public void onPacket(ServerCustomPacketEvent event) { onPacketData(new ByteBufInputStream(event.packet.payload()), ((NetHandlerPlayServer) event.handler).playerEntity); }
From source file:forestry.core.network.PacketHandler.java
License:Open Source License
@SubscribeEvent public void onPacket(ClientCustomPacketEvent event) { onPacketData(new ByteBufInputStream(event.packet.payload()), null); }
From source file:fr.javatic.vertx.webjar.Webjar.java
License:Open Source License
public Webjar(Buffer buffer) { mapPathContent = new HashMap<>(); try (JarInputStream jar = new JarInputStream(new ByteBufInputStream(buffer.getByteBuf()))) { JarEntry jarEntry;//w w w . ja v a 2 s.c o m while ((jarEntry = jar.getNextJarEntry()) != null) { if (!isWebjarResource(jarEntry)) { continue; } String path = jarEntryAsPath(jarEntry); String content = getCurrentEntryContent(jar); mapPathContent.put(path, content); } } catch (IOException e) { throw new WebjarLoadingException("Failed to load webjar content", e); } }
From source file:gribbit.server.siteresources.CacheExtension.java
License:Open Source License
/** * Create a hash URI (which allows the browser to cache this resource indefinitely) if the last modified * timestamp has increased, or if there is no hash URI yet for this resource. For a new hash URI to be created, * the passed object is scheduled to be hashed by a background thread. * * This method can be called by any route handler that stores or returns database objects. It should be called * both when storing objects and when returning them, since the hash URI cache is held in RAM and is empty when * the server starts, so it needs to be built as requests start to come in. IMPORTANT NOTE: If the database can * be written to by other database clients, then this method must also be called when those changes are * detected, otherwise web clients connected to this web server will continue to serve old linked resources. * //from w w w . j a v a 2 s . c o m * This method should only be used when the total keyspace of URIs that map to database objects easily fits in * RAM, and when the objects that need to be hashed are not large (i.e. tens of MB is OK, hundreds of MB is * probably not, since there are several background worker threads and they all can be hashing objects in * parallel). */ public static void updateHashURI(String origURI, ByteBuf content, long lastModifiedEpochSeconds) { // Can only hash absolute but local (i.e. domain-less) URIs that have not already been hashed if (origURI.startsWith("/") && !origURI.startsWith("//") && !origURI.startsWith("/_/")) { // Check to see if there is already a mapping to hash URI for this original URI HashInfo hashInfo = origURIToHashInfo.get(origURI); if (hashInfo == null || hashInfo.lastModifiedEpochSeconds < lastModifiedEpochSeconds) { // There is no hash URI yet for origURI, or there is already a hash URI corresponding to origURI, // but the modification time has increased since the cached version, so need to re-hash. // Check if another thread has already enqueued the URI for hashing. Object alreadyInQueue = scheduledURIsToHash.put(origURI, new Object()); if (alreadyInQueue == null) { content.retain(); // This URI is not currently queued for hashing by background workers, add it to the queue scheduleHasher(origURI, lastModifiedEpochSeconds, new Hasher() { @Override public String computeHashKey() { // Compute MD5 hash of the ByteBuf contents, then base64-encode the results try { String hash = Base64Safe .base64Encode(DigestUtils.md5(new ByteBufInputStream(content))); content.release(); // TODO: does ByteBufInputStream call release()? return hash; } catch (IOException e) { return null; } } }); } } } }
From source file:hellfirepvp.astralsorcery.common.util.ByteBufUtils.java
License:Open Source License
@Nonnull public static NBTTagCompound readNBTTag(ByteBuf byteBuf) { try (DataInputStream dis = new DataInputStream(new ByteBufInputStream(byteBuf))) { return CompressedStreamTools.read(dis); } catch (Exception exc) { }//from ww w. jav a2 s .c o m throw new IllegalStateException("Could not load NBT Tag from incoming byte buffer!"); }
From source file:io.github.vastframework.codecs.codecs.ProtobufCodec.java
License:Apache License
@SuppressWarnings("unchecked") @Override// w w w .j a v a 2s .c o m public T decode(@NotNull ByteBuf buffer, @NotNull DecodingContext context) throws Exception { ByteBufInputStream inputStream = new ByteBufInputStream(buffer); if (this.extensionRegistry == null) { return (T) this.prototype.getParserForType().parseFrom(inputStream); } else { return (T) this.prototype.getParserForType().parseFrom(inputStream, this.extensionRegistry); } }