Java Code Examples for io.netty.handler.codec.base64.Base64#encode()

The following examples show how to use io.netty.handler.codec.base64.Base64#encode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Http2ClientUpgradeCodec.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the current settings for the handler to the Base64-encoded representation used in
 * the HTTP2-Settings upgrade header.
 */
private CharSequence getSettingsHeaderValue(ChannelHandlerContext ctx) {
    ByteBuf buf = null;
    ByteBuf encodedBuf = null;
    try {
        // Get the local settings for the handler.
        Http2Settings settings = connectionHandler.decoder().localSettings();

        // Serialize the payload of the SETTINGS frame.
        int payloadLength = SETTING_ENTRY_LENGTH * settings.size();
        buf = ctx.alloc().buffer(payloadLength);
        for (CharObjectMap.PrimitiveEntry<Long> entry : settings.entries()) {
            buf.writeChar(entry.key());
            buf.writeInt(entry.value().intValue());
        }

        // Base64 encode the payload and then convert to a string for the header.
        encodedBuf = Base64.encode(buf, URL_SAFE);
        return encodedBuf.toString(UTF_8);
    } finally {
        release(buf);
        release(encodedBuf);
    }
}
 
Example 2
Source File: Hash.java    From redisson with Apache License 2.0 6 votes vote down vote up
public static String hash128toBase64(ByteBuf objectState) {
    long[] hash = hash128(objectState);

    ByteBuf buf = Unpooled.copyLong(hash[0], hash[1]);
    try {
        ByteBuf b = Base64.encode(buf);
        try {
            String s = b.toString(CharsetUtil.UTF_8);
            return s.substring(0, s.length() - 2);
        } finally {
            b.release();
        }
    } finally {
        buf.release();
    }
}
 
Example 3
Source File: SpotifyWebAPI.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
public boolean resolveTrackImage(final SpotifyNewTrack track) throws IOException {
    URL url = new URL(track.getImageUrl());
    BufferedImage image = ImageIO.read(url);
    BufferedImage image1 = new BufferedImage(128, 128, image.getType());
    Graphics graphics = image1.getGraphics();
    try {
        graphics.drawImage(image, 0, 0, image1.getWidth(), image1.getHeight(), null);
    } finally {
        graphics.dispose();
    }
    // Converting Image byte array into Base64 String
    ByteBuf localByteBuf1 = Unpooled.buffer();
    ImageIO.write(image1, "PNG", new ByteBufOutputStream(localByteBuf1));
    ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
    String imageDataString = localByteBuf2.toString(Charsets.UTF_8);

    track.setImage(imageDataString);
    TRACK_IMAGE_LOOKUP.put(track.getId(), imageDataString);

    return true;
}
 
Example 4
Source File: HttpProxyHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public HttpProxyHandler(SocketAddress proxyAddress, String username, String password,
                        HttpHeaders headers) {
    super(proxyAddress);
    if (username == null) {
        throw new NullPointerException("username");
    }
    if (password == null) {
        throw new NullPointerException("password");
    }
    this.username = username;
    this.password = password;

    ByteBuf authz = Unpooled.copiedBuffer(username + ':' + password, CharsetUtil.UTF_8);
    ByteBuf authzBase64 = Base64.encode(authz, false);

    authorization = new AsciiString("Basic " + authzBase64.toString(CharsetUtil.US_ASCII));

    authz.release();
    authzBase64.release();

    this.headers = headers;
}
 
Example 5
Source File: Favicon.java    From ServerListPlus with GNU General Public License v3.0 6 votes vote down vote up
public static String create(BufferedImage image) throws IOException {
    checkArgument(image.getWidth() == 64, "favicon must be 64 pixels wide");
    checkArgument(image.getHeight() == 64, "favicon must be 64 pixels high");

    ByteBuf buf = Unpooled.buffer();
    try {
        ImageIO.write(image, "PNG", new ByteBufOutputStream(buf));
        ByteBuf base64 = Base64.encode(buf, false);
        try {
            return FAVICON_PREFIX + base64.toString(Charsets.UTF_8);
        } finally {
            base64.release();
        }
    } finally {
        buf.release();
    }
}
 
Example 6
Source File: EinsLiveManager.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
private void resolveImage(ITunesSearchResultEntry searchEntry) {
	try {
		URL url = new URL(searchEntry.getArtworkUrl100());
		BufferedImage image = ImageIO.read(url);
		BufferedImage image1 = new BufferedImage(60, 60, image.getType());
		Graphics graphics = image1.getGraphics();
		try {
			graphics.drawImage(image, 0, 0, image1.getWidth(), image1.getHeight(), null);
		} finally {
			graphics.dispose();
		}
		// Converting Image byte array into Base64 String
		ByteBuf localByteBuf1 = Unpooled.buffer();
		ImageIO.write(image1, "PNG", new ByteBufOutputStream(localByteBuf1));
		ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
		String imageDataString = localByteBuf2.toString(Charsets.UTF_8);

		searchEntry.setImage(imageDataString);
	} catch (Exception e) {
		The5zigMod.logger.warn("Could not resolve image for track " + searchEntry.getTrackName() + "!");
	}
}
 
Example 7
Source File: Base64Renderer.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
public static Base64Renderer getRenderer(BufferedImage icon, String id) {
	Base64Renderer renderer = CACHE.getIfPresent(id);
	if (renderer != null) {
		return renderer;
	}
	final Base64Renderer finalRenderer = new Base64Renderer(null, icon.getWidth(), icon.getHeight());
	CACHE.put(id, finalRenderer);
	try {
		ByteBuf decodedBuffer = Unpooled.buffer();
		ImageIO.write(icon, "PNG", new ByteBufOutputStream(decodedBuffer));
		ByteBuf encodedBuffer = Base64.encode(decodedBuffer);
		String imageDataString = encodedBuffer.toString(Charsets.UTF_8);

		finalRenderer.setBase64String(imageDataString, id);
	} catch (Exception e) {
		The5zigMod.logger.error("Could not load icon " + id, e);
	}
	return finalRenderer;
}
 
Example 8
Source File: EinsLiveManager.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
private void resolveImage(ITunesSearchResultEntry searchEntry) {
	try {
		URL url = new URL(searchEntry.getArtworkUrl100());
		BufferedImage image = ImageIO.read(url);
		BufferedImage image1 = new BufferedImage(60, 60, image.getType());
		Graphics graphics = image1.getGraphics();
		try {
			graphics.drawImage(image, 0, 0, image1.getWidth(), image1.getHeight(), null);
		} finally {
			graphics.dispose();
		}
		// Converting Image byte array into Base64 String
		ByteBuf localByteBuf1 = Unpooled.buffer();
		ImageIO.write(image1, "PNG", new ByteBufOutputStream(localByteBuf1));
		ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
		String imageDataString = localByteBuf2.toString(Charsets.UTF_8);

		searchEntry.setImage(imageDataString);
	} catch (Exception e) {
		The5zigMod.logger.warn("Could not resolve image for track " + searchEntry.getTrackName() + "!");
	}
}
 
Example 9
Source File: AbstractGenericHandler.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
/**
 * Add basic authentication headers to a {@link HttpRequest}.
 *
 * The given information is Base64 encoded and the authorization header is set appropriately. Since this needs
 * to be done for every request, it is refactored out.
 *
 * @param ctx the handler context.
 * @param request the request where the header should be added.
 * @param user the username for auth.
 * @param password the password for auth.
 */
public static void addHttpBasicAuth(final ChannelHandlerContext ctx, final HttpRequest request, final String user,
    final String password) {

    // if both user and password are null or empty, don't add http basic auth
    // this is usually the case when certificate auth is used.
    if ((user == null || user.isEmpty()) && (password == null || password.isEmpty())) {
        return;
    }

    final String pw = password == null ? "" : password;

    ByteBuf raw = ctx.alloc().buffer(user.length() + pw.length() + 1);
    raw.writeBytes((user + ":" + pw).getBytes(CHARSET));
    ByteBuf encoded = Base64.encode(raw, false);
    request.headers().add(HttpHeaders.Names.AUTHORIZATION, "Basic " + encoded.toString(CHARSET));
    encoded.release();
    raw.release();
}
 
Example 10
Source File: EtcdNettyClient.java    From etcd4j with Apache License 2.0 5 votes vote down vote up
private void addBasicAuthHeader(HttpRequest request) {
  ByteBuf byteBuf = Base64.encode(
          Unpooled.copiedBuffer( securityContext.username() + ":" + securityContext.password(), CharsetUtil.UTF_8));
  final String auth;
  try {
    auth = byteBuf.toString(CharsetUtil.UTF_8);
  } finally {
    byteBuf.release();
  }

  request.headers().add(HttpHeaderNames.AUTHORIZATION, "Basic " + auth);
}
 
Example 11
Source File: WebSocketUtil.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Performs base64 encoding on the specified data
 *
 * @param data The data to encode
 * @return An encoded string containing the data
 */
static String base64(byte[] data) {
    ByteBuf encodedData = Unpooled.wrappedBuffer(data);
    ByteBuf encoded = Base64.encode(encodedData);
    String encodedString = encoded.toString(CharsetUtil.UTF_8);
    encoded.release();
    return encodedString;
}
 
Example 12
Source File: SslUtils.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link Base64#encode(ByteBuf, boolean)} but allows the use of a custom {@link ByteBufAllocator}.
 *
 * @see Base64#encode(ByteBuf, boolean)
 */
static ByteBuf toBase64(ByteBufAllocator allocator, ByteBuf src) {
    ByteBuf dst = Base64.encode(src, src.readerIndex(),
            src.readableBytes(), true, Base64Dialect.STANDARD, allocator);
    src.readerIndex(src.writerIndex());
    return dst;
}
 
Example 13
Source File: CraftServer.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
static CraftIconCache loadServerIcon0(BufferedImage image) throws Exception {
    ByteBuf bytebuf = Unpooled.buffer();

    Validate.isTrue(image.getWidth() == 64, "Must be 64 pixels wide");
    Validate.isTrue(image.getHeight() == 64, "Must be 64 pixels high");
    ImageIO.write(image, "PNG", new ByteBufOutputStream(bytebuf));
    ByteBuf bytebuf1 = Base64.encode(bytebuf);

    return new CraftIconCache("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8));
}
 
Example 14
Source File: IpCameraHandler.java    From IpCamera with Eclipse Public License 2.0 5 votes vote down vote up
public boolean setBasicAuth(boolean useBasic) {
    if (useBasic == false) {
        logger.debug("Clearing out the stored BASIC auth now.");
        basicAuth = "";
        return false;
    } else if (!basicAuth.equals("")) {
        // due to camera may have been sent multiple requests before the auth was set, this may trigger falsely.
        logger.warn("Camera is reporting your username and/or password is wrong.");
        return false;
    }
    if (!username.equals("") && !password.equals("")) {
        String authString = username + ":" + password;
        ByteBuf byteBuf = null;
        try {
            byteBuf = Base64.encode(Unpooled.wrappedBuffer(authString.getBytes(CharsetUtil.UTF_8)));
            basicAuth = byteBuf.getCharSequence(0, byteBuf.capacity(), CharsetUtil.UTF_8).toString();
        } finally {
            if (byteBuf != null) {
                byteBuf.release();
                byteBuf = null;
            }
        }
        return true;
    } else {
        cameraConfigError(
                "Camera is asking for Basic Auth when you have not provided a username and/or password !");
    }
    return false;
}
 
Example 15
Source File: CraftServer.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
static CraftIconCache loadServerIcon0(BufferedImage image) throws Exception {
    ByteBuf bytebuf = Unpooled.buffer();

    Validate.isTrue(image.getWidth() == 64, "Must be 64 pixels wide");
    Validate.isTrue(image.getHeight() == 64, "Must be 64 pixels high");
    ImageIO.write(image, "PNG", new ByteBufOutputStream(bytebuf));
    ByteBuf bytebuf1 = Base64.encode(bytebuf);

    return new CraftIconCache("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8));
}
 
Example 16
Source File: WebSocketUtil.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Performs base64 encoding on the specified data
 *
 * @param data The data to encode
 * @return An encoded string containing the data
 */
static String base64(byte[] data) {
    ByteBuf encodedData = Unpooled.wrappedBuffer(data);
    ByteBuf encoded = Base64.encode(encodedData);
    String encodedString = encoded.toString(CharsetUtil.UTF_8);
    encoded.release();
    return encodedString;
}
 
Example 17
Source File: NettyConnector.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
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();
   return encodedString;
}
 
Example 18
Source File: SelfSignedCertificate.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
static String[] newSelfSignedCertificate(
        String fqdn, PrivateKey key, X509Certificate cert) throws IOException, CertificateEncodingException {
    // Encode the private key into a file.
    ByteBuf wrappedBuf = Unpooled.wrappedBuffer(key.getEncoded());
    ByteBuf encodedBuf;
    final String keyText;
    try {
        encodedBuf = Base64.encode(wrappedBuf, true);
        try {
            keyText = "-----BEGIN PRIVATE KEY-----\n" +
                      encodedBuf.toString(CharsetUtil.US_ASCII) +
                      "\n-----END PRIVATE KEY-----\n";
        } finally {
            encodedBuf.release();
        }
    } finally {
        wrappedBuf.release();
    }

    File keyFile = File.createTempFile("keyutil_" + fqdn + '_', ".key");
    keyFile.deleteOnExit();

    OutputStream keyOut = new FileOutputStream(keyFile);
    try {
        keyOut.write(keyText.getBytes(CharsetUtil.US_ASCII));
        keyOut.close();
        keyOut = null;
    } finally {
        if (keyOut != null) {
            safeClose(keyFile, keyOut);
            safeDelete(keyFile);
        }
    }

    wrappedBuf = Unpooled.wrappedBuffer(cert.getEncoded());
    final String certText;
    try {
        encodedBuf = Base64.encode(wrappedBuf, true);
        try {
            // Encode the certificate into a CRT file.
            certText = "-----BEGIN CERTIFICATE-----\n" +
                       encodedBuf.toString(CharsetUtil.US_ASCII) +
                       "\n-----END CERTIFICATE-----\n";
        } finally {
            encodedBuf.release();
        }
    } finally {
        wrappedBuf.release();
    }

    File certFile = File.createTempFile("keyutil_" + fqdn + '_', ".crt");
    certFile.deleteOnExit();

    OutputStream certOut = new FileOutputStream(certFile);
    try {
        certOut.write(certText.getBytes(CharsetUtil.US_ASCII));
        certOut.close();
        certOut = null;
    } finally {
        if (certOut != null) {
            safeClose(certFile, certOut);
            safeDelete(certFile);
            safeDelete(keyFile);
        }
    }

    return new String[] { certFile.getPath(), keyFile.getPath() };
}
 
Example 19
Source File: ITunesWindowsDelegate.java    From The-5zig-Mod with MIT License 4 votes vote down vote up
private void loadArtwork(ITunesTrack iTunesTrack, int trackID, IITArtwork artwork) {
		artwork.SaveArtworkToFile(artworkFile.getAbsolutePath());
		String imageFormat;
		switch (artwork.getFormat()) {
			case ITArtworkFormatPNG:
				imageFormat = "PNG";
				break;
			case ITArtworkFormatJPEG:
				imageFormat = "JPEG";
				break;
			case ITArtworkFormatBMP:
				imageFormat = "BMP";
				break;
			default:
				imageFormat = "PNG";
				break;
		}

		try {
			BufferedImage image = ImageIO.read(artworkFile);
			BufferedImage image1 = new BufferedImage(128, 128, image.getType());

			Graphics graphics = image1.getGraphics();
			try {
				graphics.drawImage(image, 0, 0, image1.getWidth(), image1.getHeight(), null);
			} finally {
				graphics.dispose();
			}

			// Converting Image byte array into Base64 String
			ByteBuf localByteBuf1 = Unpooled.buffer();
			ImageIO.write(image1, imageFormat, new ByteBufOutputStream(localByteBuf1));
			ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
			String imageDataString = localByteBuf2.toString(Charsets.UTF_8);

			artworkCache.put(trackID, new Container<String>(imageDataString));
			iTunesTrack.setImage(imageDataString);
		} catch (IOException e) {
			The5zigMod.logger.warn("Could not load iTunes artwork!", e);
		} finally {
			FileUtils.deleteQuietly(artworkFile);
		}
}
 
Example 20
Source File: ITunesWindowsDelegate.java    From The-5zig-Mod with GNU General Public License v3.0 4 votes vote down vote up
private void loadArtwork(ITunesTrack iTunesTrack, int trackID, IITArtwork artwork) {
		artwork.SaveArtworkToFile(artworkFile.getAbsolutePath());
		String imageFormat;
		switch (artwork.getFormat()) {
			case ITArtworkFormatPNG:
				imageFormat = "PNG";
				break;
			case ITArtworkFormatJPEG:
				imageFormat = "JPEG";
				break;
			case ITArtworkFormatBMP:
				imageFormat = "BMP";
				break;
			default:
				imageFormat = "PNG";
				break;
		}

		try {
			BufferedImage image = ImageIO.read(artworkFile);
			BufferedImage image1 = new BufferedImage(128, 128, image.getType());

			Graphics graphics = image1.getGraphics();
			try {
				graphics.drawImage(image, 0, 0, image1.getWidth(), image1.getHeight(), null);
			} finally {
				graphics.dispose();
			}

			// Converting Image byte array into Base64 String
			ByteBuf localByteBuf1 = Unpooled.buffer();
			ImageIO.write(image1, imageFormat, new ByteBufOutputStream(localByteBuf1));
			ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
			String imageDataString = localByteBuf2.toString(Charsets.UTF_8);

			artworkCache.put(trackID, new Container<String>(imageDataString));
			iTunesTrack.setImage(imageDataString);
		} catch (IOException e) {
			The5zigMod.logger.warn("Could not load iTunes artwork!", e);
		} finally {
			FileUtils.deleteQuietly(artworkFile);
		}
}