List of usage examples for com.google.common.io BaseEncoding encode
public String encode(byte[] bytes)
From source file:org.jooby.Asset.java
/** * @return Generate a weak Etag using the {@link #path()}, {@link #lastModified()} and * {@link #length()}./*from w w w.j av a 2 s . c o m*/ */ @Nonnull default String etag() { StringBuilder b = new StringBuilder(32); b.append("W/\""); BaseEncoding b64 = BaseEncoding.base64(); int lhash = resource().hashCode(); b.append(b64.encode(Longs.toByteArray(lastModified() ^ lhash))); b.append(b64.encode(Longs.toByteArray(length() ^ lhash))); b.append('"'); return b.toString(); }
From source file:org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml.SimpleBinaryAttributeWritingStrategy.java
@Override protected Object preprocess(Object value) { Util.checkType(value, List.class); BaseEncoding en = BaseEncoding.base64(); List<?> list = (List<?>) value; byte[] decoded = new byte[list.size()]; int i = 0;/* w ww . j a v a 2 s . com*/ for (Object bAsStr : list) { Preconditions.checkArgument(bAsStr instanceof String, "Unexpected inner value for %s, expected string", value); byte b = Byte.parseByte((String) bAsStr); decoded[i++] = b; } return en.encode(decoded); }
From source file:cloud.google.com.windows.example.ExampleCode.java
@SuppressWarnings("unchecked") private JSONObject jsonEncode(KeyPair keys) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory factory = KeyFactory.getInstance("RSA"); // Get the RSA spec for key manipulation. RSAPublicKeySpec pubSpec = factory.getKeySpec(keys.getPublic(), RSAPublicKeySpec.class); // Extract required parts of the key. BigInteger modulus = pubSpec.getModulus(); BigInteger exponent = pubSpec.getPublicExponent(); // Grab an encoder for the modulus and exponent to encode using RFC 3548; // Java SE 7 requires an external library (Google's Guava used here) // Java SE 8 has a built-in Base64 class that can be used instead. Apache also has an RFC 3548 // encoder./*w ww . j a v a 2 s.c om*/ BaseEncoding stringEncoder = BaseEncoding.base64(); // Strip out the leading 0 byte in the modulus. byte[] arr = Arrays.copyOfRange(modulus.toByteArray(), 1, modulus.toByteArray().length); JSONObject returnJson = new JSONObject(); // Encode the modulus, add to returned JSON object. String modulusString = stringEncoder.encode(arr).replaceAll("\n", ""); returnJson.put("modulus", modulusString); // Encode exponent, add to returned JSON object. String exponentString = stringEncoder.encode(exponent.toByteArray()).replaceAll("\n", ""); returnJson.put("exponent", exponentString); return returnJson; }
From source file:com.google.devtools.build.lib.skyframe.ActionMetadataHandler.java
@Override public void injectDigest(ActionInput output, FileStatus statNoFollow, byte[] digest) { // Assumption: any non-Artifact output is 'virtual' and should be ignored here. if (output instanceof Artifact) { final Artifact artifact = (Artifact) output; Preconditions.checkState(injectedFiles.add(artifact), artifact); FileValue fileValue;/*from www . j av a 2 s . com*/ try { // This call may do an unnecessary call to Path#getFastDigest to see if the digest is // readily available. We cannot pass the digest in, though, because if it is not available // from the filesystem, this FileValue will not compare equal to another one created for the // same file, because the other one will be missing its digest. fileValue = fileValueFromArtifact(artifact, FileStatusWithDigestAdapter.adapt(statNoFollow), getTimestampGranularityMonitor(artifact)); // Ensure the digest supplied matches the actual digest if it exists. byte[] fileDigest = fileValue.getDigest(); if (fileDigest != null && !Arrays.equals(digest, fileDigest)) { BaseEncoding base16 = BaseEncoding.base16(); String digestString = (digest != null) ? base16.encode(digest) : "null"; String fileDigestString = base16.encode(fileDigest); throw new IllegalStateException("Expected digest " + digestString + " for artifact " + artifact + ", but got " + fileDigestString + " (" + fileValue + ")"); } outputArtifactData.put(artifact, fileValue); } catch (IOException e) { // Do nothing - we just failed to inject metadata. Real error handling will be done later, // when somebody will try to access that file. return; } // If needed, insert additional data. Note that this can only be true if the file is empty or // the filesystem does not support fast digests. Since we usually only inject digests when // running with a filesystem that supports fast digests, this is fairly unlikely. try { maybeStoreAdditionalData(artifact, fileValue, digest); } catch (IOException e) { if (fileValue.getSize() != 0) { // Empty files currently have their mtimes examined, and so could throw. No other files // should throw, since all filesystem access has already been done. throw new IllegalStateException( "Filesystem should not have been accessed while injecting data for " + artifact.prettyPrint(), e); } // Ignore exceptions for empty files, as above. } } }
From source file:com.google.cloud.storage.spi.DefaultStorageRpc.java
@Override public String open(StorageObject object, Map<Option, ?> options) { try {//from w w w . j a va 2 s . c o m Insert req = storage.objects().insert(object.getBucket(), object); GenericUrl url = req.buildHttpRequest().getUrl(); String scheme = url.getScheme(); String host = url.getHost(); String path = "/upload" + url.getRawPath(); url = new GenericUrl(scheme + "://" + host + path); url.set("uploadType", "resumable"); url.set("name", object.getName()); for (Option option : options.keySet()) { Object content = option.get(options); if (content != null) { url.set(option.value(), content.toString()); } } JsonFactory jsonFactory = storage.getJsonFactory(); HttpRequestFactory requestFactory = storage.getRequestFactory(); HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, object)); HttpHeaders requestHeaders = httpRequest.getHeaders(); requestHeaders.set("X-Upload-Content-Type", firstNonNull(object.getContentType(), "application/octet-stream")); String key = CUSTOMER_SUPPLIED_KEY.getString(options); if (key != null) { BaseEncoding base64 = BaseEncoding.base64(); HashFunction hashFunction = Hashing.sha256(); requestHeaders.set("x-goog-encryption-algorithm", "AES256"); requestHeaders.set("x-goog-encryption-key", key); requestHeaders.set("x-goog-encryption-key-sha256", base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes())); } HttpResponse response = httpRequest.execute(); if (response.getStatusCode() != 200) { GoogleJsonError error = new GoogleJsonError(); error.setCode(response.getStatusCode()); error.setMessage(response.getStatusMessage()); throw translate(error); } return response.getHeaders().getLocation(); } catch (IOException ex) { throw translate(ex); } }
From source file:org.spf4j.concurrent.UIDGenerator.java
/** * Construct a UID Generator//from w w w . ja v a 2 s.c o m * @param sequence * @param baseEncoding - if null MAC address based ID will not be included. */ public UIDGenerator(final Sequence sequence, @Nullable final BaseEncoding baseEncoding, final long customEpoch, final char separator, final String prefix) { this.sequence = sequence; StringBuilder sb = new StringBuilder(16 + prefix.length()); sb.append(prefix); if (baseEncoding != null) { byte[] intfMac; try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); if (networkInterfaces != null && networkInterfaces.hasMoreElements()) { do { intfMac = networkInterfaces.nextElement().getHardwareAddress(); } while ((intfMac == null || intfMac.length == 0) && networkInterfaces.hasMoreElements()); if (intfMac == null) { intfMac = new byte[] { 0 }; } } else { intfMac = new byte[] { 0 }; } } catch (SocketException ex) { throw new RuntimeException(ex); } sb.append(baseEncoding.encode(intfMac)).append(separator); } appendUnsignedString(sb, org.spf4j.base.Runtime.PID, 5); sb.append(separator); appendUnsignedString(sb, (System.currentTimeMillis() - customEpoch) / 1000, 5); sb.append(separator); base = sb; baseLength = base.length(); maxSize = baseLength + 16; }
From source file:com.google.cloud.storage.spi.v1.HttpStorageRpc.java
@Override public String open(StorageObject object, Map<Option, ?> options) { try {//from w ww. j ava 2 s . co m Insert req = storage.objects().insert(object.getBucket(), object); GenericUrl url = req.buildHttpRequest().getUrl(); String scheme = url.getScheme(); String host = url.getHost(); String path = "/upload" + url.getRawPath(); url = new GenericUrl(scheme + "://" + host + path); url.set("uploadType", "resumable"); url.set("name", object.getName()); for (Option option : options.keySet()) { Object content = option.get(options); if (content != null) { url.set(option.value(), content.toString()); } } JsonFactory jsonFactory = storage.getJsonFactory(); HttpRequestFactory requestFactory = storage.getRequestFactory(); HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, object)); HttpHeaders requestHeaders = httpRequest.getHeaders(); requestHeaders.set("X-Upload-Content-Type", firstNonNull(object.getContentType(), "application/octet-stream")); String key = Option.CUSTOMER_SUPPLIED_KEY.getString(options); if (key != null) { BaseEncoding base64 = BaseEncoding.base64(); HashFunction hashFunction = Hashing.sha256(); requestHeaders.set("x-goog-encryption-algorithm", "AES256"); requestHeaders.set("x-goog-encryption-key", key); requestHeaders.set("x-goog-encryption-key-sha256", base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes())); } HttpResponse response = httpRequest.execute(); if (response.getStatusCode() != 200) { GoogleJsonError error = new GoogleJsonError(); error.setCode(response.getStatusCode()); error.setMessage(response.getStatusMessage()); throw translate(error); } return response.getHeaders().getLocation(); } catch (IOException ex) { throw translate(ex); } }
From source file:org.dasein.cloud.google.compute.server.ServerSupport.java
private JSONObject jsonEncode(KeyPair keys) throws InternalException { JSONObject returnJson = new JSONObject(); try {//from w ww . j av a 2 s .co m KeyFactory factory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pubSpec = factory.getKeySpec(keys.getPublic(), RSAPublicKeySpec.class); BigInteger modulus = pubSpec.getModulus(); BigInteger exponent = pubSpec.getPublicExponent(); BaseEncoding stringEncoder = BaseEncoding.base64(); // Strip out the leading 0 byte in the modulus. byte[] arr = Arrays.copyOfRange(modulus.toByteArray(), 1, modulus.toByteArray().length); returnJson.put("modulus", stringEncoder.encode(arr).replaceAll("\n", "")); returnJson.put("exponent", stringEncoder.encode(exponent.toByteArray()).replaceAll("\n", "")); } catch (Exception e) { throw new InternalException(e); } return returnJson; }