Example usage for io.netty.handler.codec.base64 Base64 encode

List of usage examples for io.netty.handler.codec.base64 Base64 encode

Introduction

In this page you can find the example usage for io.netty.handler.codec.base64 Base64 encode.

Prototype

public static ByteBuf encode(ByteBuf src) 

Source Link

Usage

From source file:com.comphenix.protocol.compat.netty.independent.IndependentNetty.java

License:Open Source License

@Override
public String toEncodedText(CompressedImage image) {
    final ByteBuf buffer = Unpooled.wrappedBuffer(image.getDataCopy());
    String computed = "data:" + image.getMime() + ";base64," + Base64.encode(buffer).toString(Charsets.UTF_8);
    return computed;
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private Packet parseBinary(ClientHead head, ByteBuf frame) throws IOException {
    if (frame.getByte(0) == 1) {
        frame.readByte();/*  w  w w . j ava 2s  .  c  o m*/
        int headEndIndex = frame.bytesBefore((byte) -1);
        int len = (int) readLong(frame, headEndIndex);
        ByteBuf oldFrame = frame;
        frame = frame.slice(oldFrame.readerIndex() + 1, len);
        oldFrame.readerIndex(oldFrame.readerIndex() + 1 + len);
    }

    if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') {
        frame.readShort();
    } else if (frame.getByte(0) == 4) {
        frame.readByte();
    }

    Packet binaryPacket = head.getLastBinaryPacket();
    if (binaryPacket != null) {
        ByteBuf attachBuf;
        if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') {
            attachBuf = frame;
        } else {
            attachBuf = Base64.encode(frame);
        }
        binaryPacket.addAttachment(Unpooled.copiedBuffer(attachBuf));
        frame.readerIndex(frame.readerIndex() + frame.readableBytes());

        if (binaryPacket.isAttachmentsLoaded()) {
            LinkedList<ByteBuf> slices = new LinkedList<ByteBuf>();
            ByteBuf source = binaryPacket.getDataSource();
            for (int i = 0; i < binaryPacket.getAttachments().size(); i++) {
                ByteBuf attachment = binaryPacket.getAttachments().get(i);
                ByteBuf scanValue = Unpooled.copiedBuffer("{\"_placeholder\":true,\"num\":" + i + "}",
                        CharsetUtil.UTF_8);
                int pos = PacketEncoder.find(source, scanValue);
                if (pos == -1) {
                    throw new IllegalStateException(
                            "Can't find attachment by index: " + i + " in packet source");
                }

                ByteBuf prefixBuf = source.slice(source.readerIndex(), pos - source.readerIndex());
                slices.add(prefixBuf);
                slices.add(QUOTES);
                slices.add(attachment);
                slices.add(QUOTES);

                source.readerIndex(pos + scanValue.readableBytes());
            }
            slices.add(source.slice());

            ByteBuf compositeBuf = Unpooled.wrappedBuffer(slices.toArray(new ByteBuf[slices.size()]));
            parseBody(head, compositeBuf, binaryPacket);
            head.setLastBinaryPacket(null);
            return binaryPacket;
        }
    }
    return new Packet(PacketType.MESSAGE);
}

From source file:com.couchbase.client.core.util.HttpUtils.java

License:Open Source License

/**
 * Add the HTTP basic auth headers to a netty request.
 *
 * @param request the request to modify.
 * @param user the user of the request./*from   w  ww  .j  a  v a2s .  c  o  m*/
 * @param password the password of the request.
 */
public static void addAuth(final HttpRequest request, final String user, final String password) {
    ByteBuf rawBuf = Unpooled.copiedBuffer(user + ":" + password, CharsetUtil.UTF_8);
    try {
        ByteBuf encoded = Base64.encode(rawBuf);
        request.headers().add(HttpHeaders.Names.AUTHORIZATION, encoded.toString(CharsetUtil.UTF_8));
    } finally {
        rawBuf.release();
    }
}

From source file:com.kixeye.kixmpp.client.KixmppClient.java

License:Apache License

/**
 * Performs auth./*www .j  av a2 s  . com*/
 */
private void performAuth() {
    byte[] authToken = ("\0" + jid.getNode() + "\0" + password).getBytes(StandardCharsets.UTF_8);

    Element auth = new Element("auth", "urn:ietf:params:xml:ns:xmpp-sasl");
    auth.setAttribute("mechanism", "PLAIN");

    ByteBuf rawCredentials = channel.get().alloc().buffer().writeBytes(authToken);
    ByteBuf encodedCredentials = Base64.encode(rawCredentials);
    String encodedCredentialsString = encodedCredentials.toString(StandardCharsets.UTF_8);
    encodedCredentials.release();
    rawCredentials.release();

    auth.setText(encodedCredentialsString);

    channel.get().writeAndFlush(auth);
}

From source file:io.reactivex.netty.samples.SimplePostClient.java

License:Apache License

public Observable<String> postMessage() {

    HttpClient<String, ByteBuf> client = RxNetty.<String, ByteBuf>newHttpClientBuilder(host, port)
            .pipelineConfigurator(PipelineConfigurators.httpClientConfigurator())
            .enableWireLogging(LogLevel.ERROR).build();

    HttpClientRequest<String> request = HttpClientRequest.create(HttpMethod.POST, path);

    request.withHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");

    String authString = USERNAME + ":" + PASSWORD;
    ByteBuf authByteBuf = Unpooled.copiedBuffer(authString.toCharArray(), CharsetUtil.UTF_8);
    ByteBuf encodedAuthByteBuf = Base64.encode(authByteBuf);
    request.withHeader(HttpHeaders.Names.AUTHORIZATION,
            "Basic " + encodedAuthByteBuf.toString(CharsetUtil.UTF_8));

    request.withRawContentSource(Observable.just(MESSAGE), StringTransformer.DEFAULT_INSTANCE);

    return client.submit(request).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() {

        @Override// w w w .  jav a  2 s  .co  m
        public Observable<String> call(HttpClientResponse<ByteBuf> response) {

            if (!response.getStatus().equals(HttpResponseStatus.OK)) {
                return Observable.<String>error(new HttpStatusNotOKException());
            }

            return response.getContent()
                    // .defaultIfEmpty(Unpooled.EMPTY_BUFFER)
                    .map(new Func1<ByteBuf, ByteBuf>() {

                        @Override
                        public ByteBuf call(ByteBuf buf) {
                            return Unpooled.copiedBuffer(buf);
                        }
                    }).reduce(new Func2<ByteBuf, ByteBuf, ByteBuf>() {

                        @Override
                        public ByteBuf call(ByteBuf buf1, ByteBuf buf2) {
                            ByteBuf buf3 = Unpooled.copiedBuffer(buf1, buf2);
                            buf1.release();
                            buf2.release();
                            return buf3;
                        }
                    }).map(new Func1<ByteBuf, String>() {

                        @Override
                        public String call(ByteBuf buf4) {

                            String str = buf4.toString(Charset.defaultCharset());
                            buf4.release();

                            return str;
                        }
                    });
        }
    }).retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {

        @Override
        public Observable<?> call(Observable<? extends Throwable> notificationHandler) {
            return notificationHandler.flatMap(new Func1<Throwable, Observable<Throwable>>() {

                @Override
                public Observable<Throwable> call(Throwable e) {

                    if ((e instanceof ConnectException
                            && e.getMessage().subSequence(0, 18).equals("Connection refused"))
                            || (e instanceof HttpStatusNotOKException) || (e instanceof NoSuchElementException
                                    && e.getMessage().equals("Sequence contains no elements"))) {
                        // logger.error(e.getMessage(), e);
                        return Observable.<Throwable>just(e);
                    }

                    return Observable.<Throwable>error(e);
                }
            }).zipWith(Observable.range(1, 4), (e, i) -> {
                // TODO create tuple class to contain both e, i
                if (i < 4) {
                    return new Throwable(String.valueOf(i));
                } else {
                    return e;
                }
            }).flatMap((e) -> {
                try {
                    int i = Integer.valueOf(e.getMessage());
                    logger.info("retry({}{}) after {}sec", i,
                            (i == 1) ? "st" : (i == 2) ? "nd" : (i == 3) ? "rd" : "th", 1);
                    return Observable.timer(3, TimeUnit.SECONDS);
                } catch (NumberFormatException nfe) {
                    return Observable.<Throwable>error(e);
                }
            });
        }

    });
    // .toBlocking().singleOrDefault("No Data");
}

From source file:io.urmia.proxy.HttpProxyFrontendHandler.java

License:Open Source License

private String digestFinal() {
    final byte[] md5 = DirectDigest.md5_final(md5ctx);
    return new String(Base64.encode(Unpooled.wrappedBuffer(md5)).array()).trim();
}

From source file:io.urmia.util.DigestUtils.java

License:Open Source License

public static String md5sum(InputStream in) throws IOException {
    DigestInputStream md5stream = null;

    byte[] buffer = new byte[1024];

    try {/* w w  w  .j  a v a  2  s.c  o  m*/
        //in = new FileInputStream(file);
        md5stream = new DigestInputStream(in, (MessageDigest) md.clone());
        //noinspection StatementWithEmptyBody
        while (md5stream.read(buffer) > -1)
            ;
        byte[] md5Digest = md5stream.getMessageDigest().digest();

        return new String(Base64.encode(Unpooled.wrappedBuffer(md5Digest)).array()).trim();

    } catch (CloneNotSupportedException e) {
        throw new RuntimeException(e);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException ignored) {
            }
        if (md5stream != null)
            try {
                md5stream.close();
            } catch (IOException ignored) {
            }
    }
}

From source file:net.minecrell.quartz.status.QuartzFavicon.java

License:MIT License

private static String encode(BufferedImage favicon) throws IOException {
    checkArgument(favicon.getWidth() == 64, "favicon must be 64 pixels wide");
    checkArgument(favicon.getHeight() == 64, "favicon must be 64 pixels high");

    ByteBuf buf = Unpooled.buffer();/*  ww w. ja va 2s.c o  m*/
    try {
        ImageIO.write(favicon, "PNG", new ByteBufOutputStream(buf));
        ByteBuf base64 = Base64.encode(buf);
        try {
            return FAVICON_PREFIX + base64.toString(Charsets.UTF_8);
        } finally {
            base64.release();
        }
    } finally {
        buf.release();
    }
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java

License:Apache License

private static String base64(byte[] data) {
    ByteBuf encodedData = Unpooled.wrappedBuffer(data);
    ByteBuf encoded = Base64.encode(encodedData);
    String encodedString = encoded.toString(StandardCharsets.UTF_8);
    encoded.release();//from   w w w  .j  a  v a2 s.  co  m
    return encodedString;
}

From source file:org.apache.spark.network.sasl.SparkSaslServer.java

License:Apache License

/** Return a Base64-encoded string. */
private static String getBase64EncodedString(String str) {
    ByteBuf byteBuf = null;/*w  w  w. j a  v  a 2 s. c  o m*/
    ByteBuf encodedByteBuf = null;
    try {
        byteBuf = Unpooled.wrappedBuffer(str.getBytes(StandardCharsets.UTF_8));
        encodedByteBuf = Base64.encode(byteBuf);
        return encodedByteBuf.toString(StandardCharsets.UTF_8);
    } finally {
        // The release is called to suppress the memory leak error messages raised by netty.
        if (byteBuf != null) {
            byteBuf.release();
            if (encodedByteBuf != null) {
                encodedByteBuf.release();
            }
        }
    }
}