List of usage examples for com.google.common.io ByteSource wrap
public static ByteSource wrap(byte[] b)
From source file:com.google.devtools.build.xcode.plmerge.PlistMerging.java
public static NSDictionary readPlistFile(final Path sourceFilePath) throws IOException { ByteSource rawBytes = new Utf8BomSkippingByteSource(sourceFilePath); try {/* w ww .j av a 2 s. c o m*/ try (InputStream in = rawBytes.openStream()) { return (NSDictionary) PropertyListParser.parse(in); } catch (PropertyListFormatException | ParseException e) { // If we failed to parse, the plist may implicitly be a map. To handle this, wrap the plist // with {}. // TODO(bazel-team): Do this in a cleaner way. ByteSource concatenated = ByteSource.concat(ByteSource.wrap(new byte[] { '{' }), rawBytes, ByteSource.wrap(new byte[] { '}' })); try (InputStream in = concatenated.openStream()) { return (NSDictionary) PropertyListParser.parse(in); } } } catch (PropertyListFormatException | ParseException | ParserConfigurationException | SAXException e) { throw new IOException(e); } }
From source file:com.facebook.buck.artifact_cache.HybridPayloadGenerator.java
public void encodeHybridStoreRequestOnePayload() throws IOException { ThriftArtifactCacheProtocol.Request request = ThriftArtifactCacheProtocol.createRequest(PROTOCOL, createStoreRequest(), ByteSource.wrap(Arrays.copyOf(PAYLOAD_ONE_BYTES, PAYLOAD_ONE_BYTES.length))); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { request.writeAndClose(stream);/*from w w w . j a v a 2 s . c o m*/ stream.flush(); byte[] buffer = stream.toByteArray(); System.out.println("Store request:"); System.out.println(BaseEncoding.base64().encode(buffer)); } }
From source file:org.jclouds.examples.glacier.MainApp.java
private static void interruptionExample(final BlobStore blobstore) throws IOException { // Create a container final String containerName = "jclouds_interruptionExample_" + UUID.randomUUID().toString(); blobstore.createContainerInLocation(null, containerName); // Create a vault // Create a blob ByteSource payload = ByteSource.wrap("data".getBytes(Charsets.UTF_8)); Blob blob = blobstore.blobBuilder("ignored") // The blob name is ignored in Glacier .payload(payload).contentLength(payload.size()).build(); // Put the blob in the container final String blobId = blobstore.putBlob(containerName, blob); // New thread Thread thread = new Thread() { public void run() { try { blobstore.getBlob(containerName, blobId); } catch (RuntimeException e) { System.out.println("The request was aborted"); }/*from w w w. j a va 2 s. co m*/ } }; // Start and interrupt the thread thread.start(); thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { Throwables.propagate(e); } }
From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java
public static String decrypt(byte[] data, Path keyPath) throws IOException, DecoderException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException { String keyData = new String(readFileToByteArray(keyPath.toFile()), StandardCharsets.UTF_8); byte[] keyBytes = decodeHex(keyData.toCharArray()); SecretKey secretKey = new SecretKeySpec(keyBytes, MigrationZipConstants.KEY_ALGORITHM); Cipher cipher = Cipher.getInstance(MigrationZipConstants.CIPHER_ALGORITHM); IvParameterSpec iv = new IvParameterSpec(MigrationZipConstants.CIPHER_IV); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); String decryptedContent;/*from w w w .j av a 2s .c o m*/ try (InputStream is = new CipherInputStream(ByteSource.wrap(data).openStream(), cipher)) { decryptedContent = IOUtils.toString(is, StandardCharsets.UTF_8); } return decryptedContent; }
From source file:org.attribyte.api.http.ResponseBuilder.java
/** * Creates an immutable streamed response. * @return The response.//from ww w . ja va2 s . com */ public StreamedResponse createStreamed() { final ByteSource bodySource = this.bodySource != null ? this.bodySource : body != null ? ByteSource.wrap(body.toByteArray()) : null; return new StreamedResponse(statusCode, headers, bodySource, attributes); }
From source file:org.apache.brooklyn.util.core.internal.ssh.process.ProcessTool.java
@Override public int execScript(final Map<String, ?> props, final List<String> commands, final Map<String, ?> env) { return new ToolAbstractExecScript(props) { public int run() { try { String directory = getOptionalVal(props, PROP_DIRECTORY); File directoryDir = (directory != null) ? new File(Os.tidyPath(directory)) : null; String scriptContents = toScript(props, commands, env); if (LOG.isTraceEnabled()) LOG.trace("Running shell process (process) as script:\n{}", scriptContents); File to = new File(scriptPath); Files.createParentDirs(to); ByteSource.wrap(scriptContents.getBytes()).copyTo(Files.asByteSink(to)); List<String> cmds = buildRunScriptCommand(); cmds.add(0, "chmod +x " + scriptPath); return asInt(execProcesses(cmds, null, directoryDir, out, err, separator, getOptionalVal(props, PROP_LOGIN_SHELL), this), -1); } catch (IOException e) { throw Throwables.propagate(e); }//from w w w .java 2 s. c om } }.run(); }
From source file:org.dcache.macaroons.ZookeeperSecretStorage.java
private IdentifiedSecret decodeSecret(byte[] data) throws IOException { String id = null;/*w w w. j a va 2 s . co m*/ String encodedSecret = null; for (String line : ByteSource.wrap(data).asCharSource(StandardCharsets.US_ASCII).readLines()) { if (line.startsWith(IDENTITY_KEY)) { id = line.substring(IDENTITY_KEY.length()); } else if (line.startsWith(SECRET_KEY)) { encodedSecret = line.substring(SECRET_KEY.length()); } } if (id == null) { throw new IOException("Missing '" + IDENTITY_KEY + "' line"); } if (encodedSecret == null) { throw new IOException("Missing '" + SECRET_KEY + "' line"); } try { return new IdentifiedSecret(id, BaseEncoding.base64().decode(encodedSecret)); } catch (IllegalArgumentException e) { throw new IOException("Bad encoded secret '" + encodedSecret + "': " + e.getMessage()); } }
From source file:org.opendaylight.yangide.ext.model.editor.YinBuilder.java
public void build(OutputStream outputStream) throws XMLStreamException, SchemaSourceException, IOException, YangSyntaxErrorException { YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("yangide"); IFile file = ((IFileEditorInput) editor.getEditorInput()).getFile(); final IntHolder errorCountHolder = new IntHolder(); org.opendaylight.yangide.core.dom.Module module = YangParserUtil.parseYangFile( yangSourceEditor.getDocument().get().toCharArray(), file.getProject(), new IYangValidationListener() { @Override//w ww.j av a 2 s . c o m public void validationError(String msg, int lineNumber, int charStart, int charEnd) { ++errorCountHolder.value; } @Override public void syntaxError(String msg, int lineNumber, int charStart, int charEnd) { ++errorCountHolder.value; } }); // If module is null or there were errors, then don't continue to render the view. It would be hard for this to happen, as the // YMPE doesn't run this job if the synchronizer says the source is invalid. if (module == null || (errorCountHolder.value > 0)) return; // Now have to register the source contents for all the referenced files. The // easy one is the contents of the current file. Getting the contents of the // imported files requires a little more work. The files will be indexed in the // IndexManager, but access to that is encapsulated in the YangModelManager. List<SourceIdentifier> sourceIdentifiers = collectSourceIds(module); resolver.registerSource(YangTextSchemaSource.delegateForByteSource(sourceIdentifiers.get(0), ByteSource.wrap(yangSourceEditor.getDocument().get().getBytes()))); for (int ctr = 1; ctr < sourceIdentifiers.size(); ++ctr) { String name = sourceIdentifiers.get(ctr).getName(); String revision = sourceIdentifiers.get(ctr).getRevision(); ElementIndexInfo[] infos = YangModelManager.search(null, revision, name, ElementIndexType.MODULE, file.getProject(), null); try { // Just use the first element of the array and quit. for (ElementIndexInfo info : infos) { // Pretty much only two choices. It's either an entry in a jar file, or // a raw file. if (info.getEntry() != null && info.getEntry().length() > 0) { YangJarEntry jarEntry = YangCorePlugin.createJarEntry(new Path(info.getPath()), info.getEntry()); resolver.registerSource(YangTextSchemaSource.delegateForByteSource(sourceIdentifiers.get(0), ByteSource.wrap(new String(jarEntry.getContent()).getBytes()))); } else { YangFile yangFile = YangCorePlugin.createYangFile(info.getPath()); resolver.registerSource(YangTextSchemaSource.delegateForByteSource(sourceIdentifiers.get(0), ByteSource.wrap(new String(yangFile.getContents()).getBytes()))); } break; } } catch (YangModelException ex) { YangCorePlugin.log(ex); } } YinExportUtils.writeModuleToOutputStream(resolver.getSchemaContext().get(), new ModuleApiProxy(module), outputStream); }
From source file:org.jclouds.examples.rackspace.cloudfiles.UploadObjectsWithServiceNet.java
/** * Upload an object from a String using the Swift API. *///from ww w . j a v a2 s .co m private void uploadObjectFromString() { System.out.format("Upload Object From String%n"); String filename = "uploadObjectFromString.txt"; ByteSource source = ByteSource.wrap("uploadObjectFromString".getBytes()); Payload payload = Payloads.newByteSourcePayload(source); cloudFiles.getObjectApi(REGION, CONTAINER).put(filename, payload); System.out.format(" %s%n", filename); }
From source file:com.facebook.buck.apple.ApplePackage.java
@Override public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) { ImmutableList.Builder<Step> commands = ImmutableList.builder(); // Remove the output .ipa file if it exists already commands.add(new RmStep(getProjectFilesystem(), pathToOutputFile, /* force delete */ true)); // Create temp folder to store the files going to be zipped commands.add(new MakeCleanDirectoryStep(getProjectFilesystem(), temp)); Path payloadDir = temp.resolve("Payload"); commands.add(new MkdirStep(getProjectFilesystem(), payloadDir)); // Recursively copy the .app directory into the Payload folder Path bundleOutputPath = bundle.getPathToOutput(); commands.add(CopyStep.forDirectory(getProjectFilesystem(), bundleOutputPath, payloadDir, CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS)); // For .ipas with WatchOS2 support, Apple apparently requires the following for App Store // submissions: // 1. Have a empty "Symbols" directory on the top level. // 2. Copy the unmodified WatchKit stub binary for WatchOS2 apps to WatchKitSupport2/WK // We can't use the copy of the binary in the bundle because that has already been re-signed // with our own identity. for (BuildRule rule : bundle.getDeps()) { if (rule instanceof BuildRuleWithAppleBundle) { AppleBundle appleBundle = ((BuildRuleWithAppleBundle) rule).getAppleBundle(); if (appleBundle.getBinary().isPresent() && appleBundle.getPlatformName().startsWith("watch")) { BuildRule binary = appleBundle.getBinary().get(); if (binary instanceof WriteFile) { commands.add(new MkdirStep(getProjectFilesystem(), temp.resolve("Symbols"))); Path watchKitSupportDir = temp.resolve("WatchKitSupport2"); commands.add(new MkdirStep(getProjectFilesystem(), watchKitSupportDir)); commands.add(new WriteFileStep(getProjectFilesystem(), ByteSource.wrap(((WriteFile) binary).getFileContents()), watchKitSupportDir.resolve("WK"), true /* executable */ ));//from w w w . j av a 2 s . c om } } } } // do the zipping commands.add(new MkdirStep(getProjectFilesystem(), pathToOutputFile.getParent())); commands.add(new ZipStep(getProjectFilesystem(), pathToOutputFile, ImmutableSet.<Path>of(), false, ZipCompressionLevel.DEFAULT_COMPRESSION_LEVEL, temp)); buildableContext.recordArtifact(getPathToOutput()); return commands.build(); }