下面列出了怎么用 io.netty.handler.codec.base64.Base64 的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
private String resolveCover(final String path) throws ExecutionException {
return TRACK_IMAGE_LOOKUP.get(path, new Callable<String>() {
@Override
public String call() throws Exception {
URL url = new URL(path);
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);
return localByteBuf2.toString(Charsets.UTF_8);
}
});
}
private void downloadBase64Skin(final String uuid) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("https://cravatar.eu/avatar/" + uuid + "/64.png");
BufferedImage image = ImageIO.read(url);
// Converting Image byte array into Base64 String
ByteBuf localByteBuf1 = Unpooled.buffer();
ImageIO.write(image, "PNG", new ByteBufOutputStream(localByteBuf1));
ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
String imageDataString = localByteBuf2.toString(Charsets.UTF_8);
setBase64EncodedSkin(uuid, imageDataString);
The5zigMod.logger.debug("Got Base64 encoded skin for {}", uuid);
} catch (Exception e) {
The5zigMod.logger.warn("Could not get Base64 skin for " + uuid, e);
}
}
});
}
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() + "!");
}
}
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;
}
private String resolveCover(final String path) throws ExecutionException {
return TRACK_IMAGE_LOOKUP.get(path, new Callable<String>() {
@Override
public String call() throws Exception {
URL url = new URL(path);
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);
return localByteBuf2.toString(Charsets.UTF_8);
}
});
}
private void downloadBase64Skin(final String uuid) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("https://cravatar.eu/avatar/" + uuid + "/64.png");
BufferedImage image = ImageIO.read(url);
// Converting Image byte array into Base64 String
ByteBuf localByteBuf1 = Unpooled.buffer();
ImageIO.write(image, "PNG", new ByteBufOutputStream(localByteBuf1));
ByteBuf localByteBuf2 = Base64.encode(localByteBuf1);
String imageDataString = localByteBuf2.toString(Charsets.UTF_8);
setBase64EncodedSkin(uuid, imageDataString);
The5zigMod.logger.debug("Got Base64 encoded skin for {}", uuid);
} catch (Exception e) {
The5zigMod.logger.warn("Could not get Base64 skin for " + uuid, e);
}
}
});
}
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() + "!");
}
}
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;
}
ByteBuf readPrivateKey(InputStream in) throws KeyException {
String content;
try {
content = readContent(in);
} catch (IOException e) {
throw new KeyException("failed to read key input stream", e);
}
Matcher m = KEY_PATTERN.matcher(content);
if (!m.find()) {
throw new KeyException(
"could not find a PKCS #8 private key in input stream"
+ " (see https://netty.io/wiki/sslcontextbuilder-and-private-key.html for more information)");
}
ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII);
ByteBuf der = Base64.decode(base64);
base64.release();
return der;
}
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;
}
/**
* 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);
}
}
/**
* Decodes the settings header and returns a {@link Http2Settings} object.
*/
private Http2Settings decodeSettingsHeader(ChannelHandlerContext ctx, CharSequence settingsHeader)
throws Http2Exception {
ByteBuf header = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(settingsHeader), CharsetUtil.UTF_8);
try {
// Decode the SETTINGS payload.
ByteBuf payload = Base64.decode(header, URL_SAFE);
// Create an HTTP/2 frame for the settings.
ByteBuf frame = createSettingsFrame(ctx, payload);
// Decode the SETTINGS frame and return the settings object.
return decodeSettings(ctx, frame);
} finally {
header.release();
}
}
static ByteBuf readPrivateKey(InputStream in) throws KeyException {
String content;
try {
content = readContent(in);
} catch (IOException e) {
throw new KeyException("failed to read key input stream", e);
}
Matcher m = KEY_PATTERN.matcher(content);
if (!m.find()) {
throw new KeyException("could not find a PKCS #8 private key in input stream" +
" (see http://netty.io/wiki/sslcontextbuilder-and-private-key.html for more information)");
}
ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII);
ByteBuf der = Base64.decode(base64);
base64.release();
return der;
}
static ByteBuf readPrivateKey(File file) throws KeyException {
String content;
try {
content = readContent(file);
} catch (IOException e) {
throw new KeyException("failed to read a file: " + file, e);
}
Matcher m = KEY_PATTERN.matcher(content);
if (!m.find()) {
throw new KeyException("found no private key: " + file);
}
ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII);
ByteBuf der = Base64.decode(base64);
base64.release();
return der;
}
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();
}
}
/**
* 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();
}
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();
}
}
private void prepareImage() {
if (base64String == null) {
delete(resourceLocation);
this.dynamicImage = null;
return;
}
ByteBuf localByteBuf1 = Unpooled.copiedBuffer(base64String, Charsets.UTF_8);
ByteBuf localByteBuf2 = null;
BufferedImage localBufferedImage;
try {
localByteBuf2 = Base64.decode(localByteBuf1);
localBufferedImage = read(new ByteBufInputStream(localByteBuf2));
Validate.validState(localBufferedImage.getWidth() == width, "Must be " + width + " pixels wide");
Validate.validState(localBufferedImage.getHeight() == height, "Must be " + height + " pixels high");
} catch (Exception e) {
The5zigMod.logger.error("Could not prepare base64 renderer image", e);
delete(resourceLocation);
dynamicImage = null;
return;
} finally {
localByteBuf1.release();
if (localByteBuf2 != null) {
localByteBuf2.release();
}
}
if (this.dynamicImage == null) {
this.dynamicImage = The5zigMod.getVars().loadDynamicImage(resourceLocation.callGetResourcePath(), localBufferedImage);
}
}
private void prepareImage() {
if (base64String == null) {
delete(resourceLocation);
this.dynamicImage = null;
return;
}
ByteBuf localByteBuf1 = Unpooled.copiedBuffer(base64String, Charsets.UTF_8);
ByteBuf localByteBuf2 = null;
BufferedImage localBufferedImage;
try {
localByteBuf2 = Base64.decode(localByteBuf1);
localBufferedImage = read(new ByteBufInputStream(localByteBuf2));
Validate.validState(localBufferedImage.getWidth() == width, "Must be " + width + " pixels wide");
Validate.validState(localBufferedImage.getHeight() == height, "Must be " + height + " pixels high");
} catch (Exception e) {
The5zigMod.logger.error("Could not prepare base64 renderer image", e);
delete(resourceLocation);
dynamicImage = null;
return;
} finally {
localByteBuf1.release();
if (localByteBuf2 != null) {
localByteBuf2.release();
}
}
if (this.dynamicImage == null) {
this.dynamicImage = The5zigMod.getVars().loadDynamicImage(resourceLocation.getResourcePath(), localBufferedImage);
}
}
public ByteBuf[] readCertificates(InputStream in) throws CertificateException {
String content;
try {
content = readContent(in);
} catch (IOException e) {
throw new CertificateException("failed to read certificate input stream", e);
}
List<ByteBuf> certs = new ArrayList<ByteBuf>();
Matcher m = CERT_PATTERN.matcher(content);
int start = 0;
for (; ; ) {
if (!m.find(start)) {
break;
}
ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII);
ByteBuf der = Base64.decode(base64);
base64.release();
certs.add(der);
start = m.end();
}
if (certs.isEmpty()) {
throw new CertificateException("found no certificates in input stream");
}
return certs.toArray(new ByteBuf[0]);
}
/**
* 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;
}
private boolean authenticate(ChannelHandlerContext ctx, FullHttpRequest req) {
assertThat(req.method(), is(HttpMethod.CONNECT));
if (testMode != TestMode.INTERMEDIARY) {
ctx.pipeline().addBefore(ctx.name(), "lineDecoder", new LineBasedFrameDecoder(64, false, true));
}
ctx.pipeline().remove(HttpObjectAggregator.class);
ctx.pipeline().get(HttpServerCodec.class).removeInboundHandler();
boolean authzSuccess = false;
if (username != null) {
CharSequence authz = req.headers().get(HttpHeaderNames.PROXY_AUTHORIZATION);
if (authz != null) {
String[] authzParts = authz.toString().split(" ", 2);
ByteBuf authzBuf64 = Unpooled.copiedBuffer(authzParts[1], CharsetUtil.US_ASCII);
ByteBuf authzBuf = Base64.decode(authzBuf64);
String expectedAuthz = username + ':' + password;
authzSuccess = "Basic".equals(authzParts[0]) &&
expectedAuthz.equals(authzBuf.toString(CharsetUtil.US_ASCII));
authzBuf64.release();
authzBuf.release();
}
} else {
authzSuccess = true;
}
return authzSuccess;
}
static ByteBuf[] readCertificates(InputStream in) throws CertificateException {
String content;
try {
content = readContent(in);
} catch (IOException e) {
throw new CertificateException("failed to read certificate input stream", e);
}
List<ByteBuf> certs = new ArrayList<ByteBuf>();
Matcher m = CERT_PATTERN.matcher(content);
int start = 0;
for (;;) {
if (!m.find(start)) {
break;
}
ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII);
ByteBuf der = Base64.decode(base64);
base64.release();
certs.add(der);
start = m.end();
}
if (certs.isEmpty()) {
throw new CertificateException("found no certificates in input stream");
}
return certs.toArray(new ByteBuf[certs.size()]);
}
/**
* 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;
}
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));
}
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;
}
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));
}
/**
* 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;
}
static ByteBuf[] readCertificates(File file) throws CertificateException {
String content;
try {
content = readContent(file);
} catch (IOException e) {
throw new CertificateException("failed to read a file: " + file, e);
}
List<ByteBuf> certs = new ArrayList<ByteBuf>();
Matcher m = CERT_PATTERN.matcher(content);
int start = 0;
for (;;) {
if (!m.find(start)) {
break;
}
ByteBuf base64 = Unpooled.copiedBuffer(m.group(1), CharsetUtil.US_ASCII);
ByteBuf der = Base64.decode(base64);
base64.release();
certs.add(der);
start = m.end();
}
if (certs.isEmpty()) {
throw new CertificateException("found no certificates: " + file);
}
return certs.toArray(new ByteBuf[certs.size()]);
}