/** * @see org.alfasoftware.morf.xml.XmlStreamProvider#open() */ @Override public void open() { if (zipOutput != null) { throw new IllegalStateException("Archive data set instance for [" + file + "] already open"); } try { zipOutput = new AdaptedZipOutputStream(new FileOutputStream(file)); // Put the read me entry in ZipEntry entry = new ZipEntry("_ReadMe.txt"); zipOutput.putNextEntry(entry); ByteStreams.copy(new ByteArrayInputStream(READ_ME.getBytes("UTF-8")), zipOutput); } catch (Exception e) { throw new RuntimeException("Error opening zip archive [" + file + "]", e); } }
@Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { if (!channel.equals("BungeeCord")) { return; } final ByteArrayDataInput in = ByteStreams.newDataInput(message); final String type = in.readUTF(); if (type.equals("ServerIP")) { final String serverName = in.readUTF(); final String ip = in.readUTF(); final short port = in.readShort(); this.plugin.getServer().getScheduler().runTaskAsynchronously(this.plugin, () -> { final String data = BungeeCordProvider.this.receiveResultFromServer(serverName, ip, port); BungeeCordProvider.this.parseData(serverName, data); }); } }
@EventHandler public void handleChannel(PluginMessageEvent pluginMessageEvent) { if(!(pluginMessageEvent.getReceiver() instanceof ProxiedPlayer)) return; if(pluginMessageEvent.getTag().equalsIgnoreCase("CloudNet")) { ByteArrayDataInput byteArrayDataInput = ByteStreams.newDataInput(pluginMessageEvent.getData()); switch (byteArrayDataInput.readUTF().toLowerCase()) { case "connect": List<String> servers = CloudProxy.getInstance().getServers(byteArrayDataInput.readUTF()); if(servers.size() == 0) return; ((ProxiedPlayer)pluginMessageEvent.getReceiver()).connect(ProxyServer.getInstance().getServerInfo(servers.get(NetworkUtils.RANDOM.nextInt(servers.size())))); break; case "fallback": ((ProxiedPlayer)pluginMessageEvent.getReceiver()).connect(ProxyServer.getInstance() .getServerInfo(CloudProxy.getInstance() .fallback(((ProxiedPlayer)pluginMessageEvent.getReceiver())))); break; case "command": ProxyServer.getInstance().getPluginManager().dispatchCommand(((ProxiedPlayer)pluginMessageEvent.getReceiver()), byteArrayDataInput.readUTF()); break; } } }
private static void publicize(Path inPath, Path outPath) throws IOException { try (JarInputStream in = new JarInputStream(Files.newInputStream(inPath))) { try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(outPath))) { JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { if (entry.isDirectory()) { continue; } String name = entry.getName(); out.putNextEntry(new JarEntry(name)); if (name.endsWith(".class")) { ClassWriter writer = new ClassWriter(0); ClassReader reader = new ClassReader(in); reader.accept(new CheckClassAdapter(new ClassDefinalizer(new ClassPublicizer(writer)), true), 0); out.write(writer.toByteArray()); } else { ByteStreams.copy(in, out); } } } } }
public static DexBackedDexFile fromInputStream(@Nonnull Opcodes opcodes, @Nonnull InputStream is) throws IOException { if (!is.markSupported()) { throw new IllegalArgumentException("InputStream must support mark"); } is.mark(44); byte[] partialHeader = new byte[44]; try { ByteStreams.readFully(is, partialHeader); } catch (EOFException ex) { throw new NotADexFile("File is too short"); } finally { is.reset(); } verifyMagicAndByteOrder(partialHeader, 0); byte[] buf = ByteStreams.toByteArray(is); return new DexBackedDexFile(opcodes, buf, 0, false); }
@SuppressWarnings("unchecked") private BinData getFileAsBinData(FileHandle file, String filename) { try( InputStream in = fileSystemService.read(file, filename) ) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteStreams.copy(in, baos); BinData data = new BinData(); data.getContent().add(new PCData(new Base64().encode(baos.toByteArray()))); return data; } catch( IOException io ) { throw Throwables.propagate(io); } }
ZipMemDataSource(String fileName, InputStream content) { super(DataSourceUtil.getBaseName(fileName)); Objects.requireNonNull(content); try (ZipInputStream zipStream = new ZipInputStream(content)) { ZipEntry entry = zipStream.getNextEntry(); while (entry != null) { String entryName = entry.getName(); try (ByteArrayOutputStream bao = new ByteArrayOutputStream()) { ByteStreams.copy(zipStream, bao); putData(entryName, bao.toByteArray()); } entry = zipStream.getNextEntry(); } } catch (IOException e) { throw new UncheckedIOException(e); } }
@Override protected ReadOnlyMemDataSource testDataSource(String extension) throws IOException { ReadOnlyMemDataSource dataSource = super.testDataSource(extension); assertTrue(dataSource.exists("extra_data.xiidm")); assertArrayEquals(getExtraUncompressedData(), ByteStreams.toByteArray(dataSource.newInputStream("extra_data.xiidm"))); try { assertFalse(dataSource.exists("_data", "xiidm")); // baseName = data, data_data.xiidm does not exist assertArrayEquals(getExtraUncompressedData(), ByteStreams.toByteArray(dataSource.newInputStream("_data", "xiidm"))); fail(); } catch (IOException ignored) { } return dataSource; }
private void expandZippedApplication(InputStream stream, ApplicationDescription desc) throws IOException { ZipInputStream zis = new ZipInputStream(stream); ZipEntry entry; File appDir = new File(appsDir, desc.name()); while ((entry = zis.getNextEntry()) != null) { if (!entry.isDirectory()) { byte[] data = ByteStreams.toByteArray(zis); zis.closeEntry(); File file = new File(appDir, entry.getName()); createParentDirs(file); write(data, file); } } zis.close(); }
private FileWorker exporter(final Control control) { return new AbstractFileWorker<Object>(CurrentLocale.get("com.tle.admin.controls.exported"), //$NON-NLS-1$ CurrentLocale.get("com.tle.admin.controls.error.exporting")) //$NON-NLS-1$ { @Override public Object construct() throws Exception { final Driver driver = Driver.instance(); final PluginService pluginService = driver.getPluginService(); final ExportedControl ctl = getExportedControl(control, pluginService, driver.getVersion().getFull()); byte[] zipData = getCollectionService(driver).exportControl(new XStream().toXML(ctl)); ByteArrayInputStream stream = new ByteArrayInputStream(zipData); try( OutputStream out = new FileOutputStream(file) ) { ByteStreams.copy(stream, out); } return null; } }; }
public static List<File> unzip(String zipFile, File outDirectory, Predicate<ZipEntry> filter) throws IOException { final Path outDirectoryPath = outDirectory.toPath(); final List<File> outFiles = new ArrayList<>(); iter(zipFile, (entry, input) -> { String name = entry.getName(); if (!entry.isDirectory() && filter.test(entry)) { if (name.contains("..")) { // Protect against malicious archives. throw new CompilationError("Invalid entry name \"" + name + "\""); } Path outPath = outDirectoryPath.resolve(name); File outFile = outPath.toFile(); outFile.getParentFile().mkdirs(); FileOutputStream output = new FileOutputStream(outFile); ByteStreams.copy(input, output); outFiles.add(outFile); } }); return outFiles; }
@Test public void buildAndTreeShakeFromDeployJar() throws ExecutionException, IOException, ProguardRuleParserException, CompilationException { int maxSize = 20000000; AndroidApp app = runAndCheckVerification( CompilerUnderTest.R8, CompilationMode.RELEASE, BASE + APK, null, BASE + PG_CONF, null, // Don't pass any inputs. The input will be read from the -injars in the Proguard // configuration file. ImmutableList.of()); int bytes = 0; try (Closer closer = Closer.create()) { for (Resource dex : app.getDexProgramResources()) { bytes += ByteStreams.toByteArray(closer.register(dex.getStream())).length; } } assertTrue("Expected max size of " + maxSize + ", got " + bytes, bytes < maxSize); }
/** * Encodes a string in either UTF-8 or UTF-16 and returns the bytes of the encoded string. * Strings are prefixed by 2 values. The first is the number of characters in the string. * The second is the encoding length (number of bytes in the string). * * <p>Here's an example UTF-8-encoded string of ab©: * <pre>03 04 61 62 C2 A9 00</pre> * * @param str The string to be encoded. * @param type The encoding type that the {@link ResourceString} should be encoded in. * @return The encoded string. */ public static byte[] encodeString(String str, Type type) { byte[] bytes = str.getBytes(type.charset()); // The extra 5 bytes is for metadata (character count + byte count) and the NULL terminator. ByteArrayDataOutput output = ByteStreams.newDataOutput(bytes.length + 5); encodeLength(output, str.length(), type); if (type == Type.UTF8) { // Only UTF-8 strings have the encoding length. encodeLength(output, bytes.length, type); } output.write(bytes); // NULL-terminate the string if (type == Type.UTF8) { output.write(0); } else { output.writeShort(0); } return output.toByteArray(); }
@Test public void testHandleResponse() throws IOException, UnexpectedBlobDigestException { Blob testBlob = Blobs.from("some BLOB content"); DescriptorDigest testBlobDigest = testBlob.writeTo(ByteStreams.nullOutputStream()).getDigest(); Response mockResponse = Mockito.mock(Response.class); Mockito.when(mockResponse.getBody()).thenReturn(testBlob); BlobPuller blobPuller = new BlobPuller(fakeRegistryEndpointProperties, testBlobDigest, temporaryPath); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); BlobDescriptor blobDescriptor = blobPuller.handleResponse(mockResponse).writeTo(byteArrayOutputStream); Assert.assertEquals( "some BLOB content", new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8)); Assert.assertEquals(testBlobDigest, blobDescriptor.getDigest()); }
@Path("{resource}") @GET @Produces("image/png") public Response getBinResource(@PathParam("resource") String resource) throws IOException { String path = ROOT + resource; InputStream is = getClass().getClassLoader().getResourceAsStream(path); if (is == null) { log.warn("Didn't find resource {}", path); return Response.status(Response.Status.NOT_FOUND).build(); } byte[] bytes = ByteStreams.toByteArray(is); log.info("Processing resource {} ({} bytes)", path, bytes.length); return Response.ok(decodeAndMark(bytes)).build(); }
@Test public void testGetManifest() throws URISyntaxException, IOException, LayerPropertyNotFoundException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("json/translatedmanifest.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); // Translates the image to the manifest and writes the JSON string. Blob containerConfigurationBlob = imageToJsonTranslator.getContainerConfigurationBlob(); BlobDescriptor blobDescriptor = containerConfigurationBlob.writeTo(ByteStreams.nullOutputStream()); Blob manifestBlob = imageToJsonTranslator.getManifestBlob(blobDescriptor); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); manifestBlob.writeTo(byteArrayOutputStream); Assert.assertEquals( expectedJson, new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8)); }
public static GenesisJson loadGenesisJson(InputStream genesisJsonIS) throws RuntimeException { String json = null; try { json = new String(ByteStreams.toByteArray(genesisJsonIS)); ObjectMapper mapper = new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); GenesisJson genesisJson = mapper.readValue(json, GenesisJson.class); return genesisJson; } catch (Exception e) { Utils.showErrorAndExit("Problem parsing genesis: "+ e.getMessage(), json); throw new RuntimeException(e.getMessage(), e); } }
@Override public void write(OutputStream output, ByteArraySessionOutputBuffer buffer) throws IOException { buffer.reset(); final InputStream payload = writePayload(buffer); final long contentLength = buffer.contentLength(); this.warcHeaders.updateHeader(new WarcHeader(WarcHeader.Name.CONTENT_LENGTH, Long.toString(contentLength))); Util.toOutputStream(BasicLineFormatter.formatProtocolVersion(WarcRecord.PROTOCOL_VERSION, null), output); output.write(ByteArraySessionOutputBuffer.CRLF); writeHeaders(this.warcHeaders, output); output.write(ByteArraySessionOutputBuffer.CRLF); ByteStreams.copy(payload, output); output.write(ByteArraySessionOutputBuffer.CRLFCRLF); }
@Override public String getModuleSource(final org.opendaylight.yangtools.yang.model.api.ModuleIdentifier moduleIdentifier) { final CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> source = this.sourceProvider .getSource(SourceIdentifier.create(moduleIdentifier.getName(), Optional.fromNullable(QName.formattedRevision(moduleIdentifier.getRevision())))); try { final YangTextSchemaSource yangTextSchemaSource = source.checkedGet(); try (InputStream inStream = yangTextSchemaSource.openStream()) { return new String(ByteStreams.toByteArray(inStream), StandardCharsets.UTF_8); } } catch (SchemaSourceException | IOException e) { LOG.warn("Unable to provide source for {}", moduleIdentifier, e); throw new IllegalArgumentException("Unable to provide source for " + moduleIdentifier, e); } }
public static void createFile ( final File file, final InputStream resource, final IProgressMonitor monitor, final boolean exec ) throws Exception { file.getParentFile ().mkdirs (); try { try ( FileOutputStream fos = new FileOutputStream ( file ) ) { ByteStreams.copy ( resource, fos ); } file.setExecutable ( exec ); } finally { resource.close (); } }
@Nullable public ManifestData apkPackageName(File apkFile) { if (apkFile == null) { return null; } try { ZipFile zip = new ZipFile(apkFile); ZipEntry mft = zip.getEntry(AndroidConstants.ANDROID_MANIFEST_XML); ApkUtils decompresser = new ApkUtils(); String xml = decompresser.decompressXML(ByteStreams.toByteArray(zip.getInputStream(mft))); ManifestData manifest = AndroidProjects.parseProjectManifest(new ByteArrayInputStream(xml.getBytes())); return manifest; } catch (IOException ex) { LOG.log(Level.INFO, "cannot get package name from apk file " + apkFile, ex); return null; } }
/** * Returns the Teredo information embedded in a Teredo address. * * @param ip {@link Inet6Address} to be examined for embedded Teredo information * @return extracted {@code TeredoInfo} * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address */ public static TeredoInfo getTeredoInfo(Inet6Address ip) { checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip)); byte[] bytes = ip.getAddress(); Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8)); int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff; // Teredo obfuscates the mapped client port, per section 4 of the RFC. int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff; byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16); for (int i = 0; i < clientBytes.length; i++) { // Teredo obfuscates the mapped client IP, per section 4 of the RFC. clientBytes[i] = (byte) ~clientBytes[i]; } Inet4Address client = getInet4Address(clientBytes); return new TeredoInfo(server, client, port, flags); }
void saveDefaultConfig() { if (!getDataFolder().exists()) { getDataFolder().mkdir(); } File configFile = new File(getDataFolder(), "config.yml"); if (!configFile.exists()) { try { configFile.createNewFile(); try (InputStream is = getResourceAsStream("config.yml"); OutputStream os = new FileOutputStream(configFile)) { ByteStreams.copy(is, os); } } catch (IOException e) { throw new RuntimeException("Unable to create configuration file", e); } } }
protected Class<?> findClassInJarFile(String qualifiedClassName) throws ClassNotFoundException { URI classUri = URIUtil.buildUri(StandardLocation.CLASS_OUTPUT, qualifiedClassName); String internalClassName = classUri.getPath().substring(1); JarFile jarFile = null; try { for (int i = 0; i < jarFiles.size(); i++) { jarFile = jarFiles.get(i); JarEntry jarEntry = jarFile.getJarEntry(internalClassName); if (jarEntry != null) { InputStream inputStream = jarFile.getInputStream(jarEntry); try { byte[] byteCode = new byte[(int) jarEntry.getSize()]; ByteStreams.read(inputStream, byteCode, 0, byteCode.length); return defineClass(qualifiedClassName, byteCode, 0, byteCode.length); } finally { Closeables.closeQuietly(inputStream); } } } } catch (IOException e) { throw new IllegalStateException(String.format("Failed to lookup class %s in jar file %s", qualifiedClassName, jarFile), e); } return null; }
private Message decodeMessage(ChannelHandlerContext ctx, List<Frame> frames) throws IOException { long frameType = frames.get(0).getType(); byte[] payload = new byte[frames.size() == 1 ? frames.get(0).getSize() : frames.get(0).totalFrameSize]; int pos = 0; for (Frame frame : frames) { pos += ByteStreams.read(frame.getStream(), payload, pos, frame.getSize()); } if (loggerWire.isDebugEnabled()) { loggerWire.debug("Recv: Encoded: {} [{}]", frameType, Hex.toHexString(payload)); } Message msg = createMessage((byte) frameType, payload); if (loggerNet.isInfoEnabled()) { loggerNet.info("From: \t{} \tRecv: \t{}", channel, msg.toString()); } ethereumListener.onRecvMessage(channel, msg); channel.getNodeStatistics().rlpxInMessages.add(); return msg; }
public static void main(String[] args) throws IOException, JSAPException { SimpleJSAP jsap = new SimpleJSAP(GZIPArchiveReader.class.getName(), "Writes some random records on disk.", new Parameter[] { new Switch("fully", 'f', "fully", "Whether to read fully the record (and do a minimal cosnsistency check)."), new UnflaggedOption("path", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The path to read from."), }); JSAPResult jsapResult = jsap.parse(args); if (jsap.messagePrinted()) System.exit(1); final boolean fully = jsapResult.getBoolean("fully"); GZIPArchiveReader gzar = new GZIPArchiveReader(new FileInputStream(jsapResult.getString("path"))); for (;;) { ReadEntry e = gzar.getEntry(); if (e == null) break; InputStream inflater = e.lazyInflater.get(); if (fully) ByteStreams.toByteArray(inflater); e.lazyInflater.consume(); System.out.println(e); } }
@Test public void testAnyXmlStreaming() throws Exception { String xml = "<foo xmlns=\"http://www.w3.org/TR/html4/\" x=\"123\"><bar>one</bar><bar>two</bar></foo>"; final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Node xmlNode = factory.newDocumentBuilder().parse( new InputSource(new StringReader(xml))).getDocumentElement(); assertEquals("http://www.w3.org/TR/html4/", xmlNode.getNamespaceURI()); NormalizedNode<?, ?> anyXmlContainer = ImmutableContainerNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).withChild( Builders.anyXmlBuilder().withNodeIdentifier(new NodeIdentifier(TestModel.ANY_XML_QNAME)) .withValue(new DOMSource(xmlNode)).build()).build(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos)); nnout.writeNormalizedNode(anyXmlContainer); NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput( bos.toByteArray())); ContainerNode deserialized = (ContainerNode)nnin.readNormalizedNode(); Optional<DataContainerChild<? extends PathArgument, ?>> child = deserialized.getChild(new NodeIdentifier(TestModel.ANY_XML_QNAME)); assertEquals("AnyXml child present", true, child.isPresent()); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(((AnyXmlNode)child.get()).getValue(), xmlOutput); assertEquals("XML", xml, xmlOutput.getWriter().toString()); assertEquals("http://www.w3.org/TR/html4/", ((AnyXmlNode)child.get()).getValue().getNode().getNamespaceURI()); }
public ClassAnalysis getClassAnalysis(String className, InputStream input) throws IOException { ClassRelevancyFilter filter = new ClassRelevancyFilter(className); ClassReader reader = new Java9ClassReader(ByteStreams.toByteArray(input)); ClassDependenciesVisitor visitor = new ClassDependenciesVisitor(); reader.accept(visitor, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); Set<String> classDependencies = getClassDependencies(filter, reader); return new ClassAnalysis(classDependencies, visitor.dependentToAll); }
public static byte[] readResourceBytes(String resourceFile) { try (InputStream in = GetViewRequestExecutor.class.getResourceAsStream(resourceFile)) { return ByteStreams.toByteArray(in); } catch (IOException e) { throw new RuntimeException("Could not find resource " + resourceFile, e); } }
@Override public Observable<byte[]> getContainerLogsZipAsync() { return manager().inner().webApps().getWebSiteContainerLogsZipAsync(resourceGroupName(), name()) .map(new Func1<InputStream, byte[]>() { @Override public byte[] call(InputStream inputStream) { try { return ByteStreams.toByteArray(inputStream); } catch (IOException e) { throw Exceptions.propagate(e); } } }); }
@EventHandler public void handleRightClick(PlayerInteractEntityEvent e) { MobImpl mobImpl = CollectionWrapper.filter(mobs.values(), new Acceptable<MobImpl>() { @Override public boolean isAccepted(MobImpl value) { return value.getEntity().getEntityId() == e.getRightClicked().getEntityId(); } }); if (mobImpl != null) { e.setCancelled(true); if (!CloudAPI.getInstance().getServerGroupData(mobImpl.getMob().getTargetGroup()).isMaintenance()) { if(mobImpl.getMob().getAutoJoin() != null && mobImpl.getMob().getAutoJoin()) { ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput(); byteArrayDataOutput.writeUTF("Connect"); List<ServerInfo> serverInfos = getServers(mobImpl.getMob().getTargetGroup()); for (ServerInfo serverInfo : serverInfos) if (serverInfo.getOnlineCount() < serverInfo.getMaxPlayers() && serverInfo.getServerState().equals(ServerState.LOBBY)) { byteArrayDataOutput.writeUTF(serverInfo.getServiceId().getServerId()); e.getPlayer().sendPluginMessage(CloudServer.getInstance().getPlugin(), "BungeeCord", byteArrayDataOutput.toByteArray()); return; } } else e.getPlayer().openInventory(mobImpl.getInventory()); } else e.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', CloudAPI.getInstance().getCloudNetwork().getMessages().getString("mob-selector-maintenance-message"))); } }
public static InputSplit deserializeInputSplit(String base64, String className) throws IOException, ReflectiveOperationException{ Constructor<?> constructor = Class.forName(className).getDeclaredConstructor(); if (constructor == null) { throw new ReflectiveOperationException("Class " + className + " does not implement a default constructor."); } constructor.setAccessible(true); InputSplit split = (InputSplit) constructor.newInstance(); ByteArrayDataInput byteArrayDataInput = ByteStreams.newDataInput(Base64.decodeBase64(base64)); split.readFields(byteArrayDataInput); return split; }
private static byte[] toByteArray(InputStream is) { try { return ByteStreams.toByteArray(is); } catch (IOException e) { throw new UncheckedIOException(e); } }
protected void putData(String fileName, InputStream data) { try { putData(fileName, ByteStreams.toByteArray(data)); } catch (IOException e) { throw new UncheckedIOException(e); } }
private void writeThenReadTest(String suffix, String ext) throws IOException { // check file does not exist assertFalse(dataSource.exists(suffix, ext)); // write file try (OutputStream os = dataSource.newOutputStream(suffix, ext, false)) { os.write("line1".getBytes(StandardCharsets.UTF_8)); } if (appendTest()) { // write file in append mode try (OutputStream os = dataSource.newOutputStream(suffix, ext, true)) { os.write((System.lineSeparator() + "line2").getBytes(StandardCharsets.UTF_8)); } } // write another file try (OutputStream os = dataSource.newOutputStream("dummy.txt", false)) { os.write("otherline1".getBytes(StandardCharsets.UTF_8)); } // check files exists assertTrue(dataSource.exists(suffix, ext)); assertTrue(dataSource.exists("dummy.txt")); // check content is ok try (InputStream is = dataSource.newInputStream(suffix, ext)) { assertEquals("line1" + (appendTest() ? System.lineSeparator() + "line2" : ""), new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8)); } try (InputStream is = dataSource.newInputStream("dummy.txt")) { assertEquals("otherline1", new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8)); } }
private void handle(final AsynchronousSocketChannel channel) { requests.offer(executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { synchronized (output) { try (InputStream input = Channels.newInputStream(channel)) { ByteStreams.copy(input, output); } catch (IOException e) { throw new RuntimeException("Error processing user request", e); } } return null; } })); }
private void doFileExtract(File path) throws IOException { InputStream inputStream = getClass().getResourceAsStream("/"+getContainedFile()); FileOutputStream outputStream = new FileOutputStream(path); System.out.println("doFileExtract path = " + path.getAbsolutePath() + ", inputStream = " + inputStream + ", outputStream = " + outputStream); ByteStreams.copy(inputStream, outputStream); }
@Test public void invalidFormSubmit() throws Exception { // message missing final String boundary = "------TestBoundary" + UUID.randomUUID(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setBoundary(boundary); mockMvc.perform(post("/send") .content(ByteStreams.toByteArray(builder.build().getContent())) .contentType(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + boundary)) .andExpect(status().isOk()) .andExpect(content().contentType("text/html;charset=UTF-8")) .andExpect(model().hasErrors()); }
@Override protected final void onImport() { final int confirm = JOptionPane.showConfirmDialog( parentFrame, CurrentLocale.get("com.tle.admin.gui.baseentitytool.warningimport", getEntityNameLower(), CurrentLocale.get("com.tle.application.name")), CurrentLocale.get("com.tle.admin.gui.baseentitytool.import", getEntityNameNormal()), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if( confirm == JOptionPane.YES_OPTION ) { FileFilter filter = new ZipFileFilter(); final DialogResult result = DialogUtils.openDialog(parentFrame, null, filter, null); if( result.isOkayed() ) { try( InputStream in = new FileInputStream(result.getFile()) ) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteStreams.copy(in, out); doImport(service.importEntity(out.toByteArray())); } catch( Exception ex ) { Driver.displayInformation(parentFrame, CurrentLocale.get("com.tle.admin.gui.baseentitytool.notvalid")); LOGGER.error("Couldn't load selected file", ex); } } } }