Java Code Examples for org.apache.commons.io.IOUtils.write()

The following are Jave code examples for showing how to use write() of the org.apache.commons.io.IOUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: pds   File: SysGeneratorController.java   View Source Code Vote up 7 votes
/**
 * 生成代码
 */
@RequestMapping("/code")
@RequiresPermissions("sys:generator:code")
public void code(HttpServletRequest request, HttpServletResponse response) throws IOException{
	String[] tableNames = new String[]{};
	//获取表名,不进行xss过滤
	HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request);
	String tables = orgRequest.getParameter("tables");
	tableNames = JSON.parseArray(tables).toArray(tableNames);
	
	byte[] data = sysGeneratorService.generatorCode(tableNames);
	
	response.reset();  
       response.setHeader("Content-Disposition", "attachment; filename=\"renren.zip\"");  
       response.addHeader("Content-Length", "" + data.length);  
       response.setContentType("application/octet-stream; charset=UTF-8");  
 
       IOUtils.write(data, response.getOutputStream());  
}
 
Example 2
Project: SuprDiscordBot   File: Configuration.java   View Source Code Vote up 7 votes
private Configuration save()
{
	try
	{
		if(json.entrySet().size() == 0)
		{
			if(this.file.exists())
			{
				this.file.delete();
			}
		}
		else
		{
			if(!this.file.exists())
			{
				this.file.createNewFile();
			}
			IOUtils.write(json.toString(), new FileOutputStream(this.file), "UTF-8");
		}
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	return this;
}
 
Example 3
Project: cyberduck   File: PlistWriter.java   View Source Code Vote up 7 votes
@Override
public void write(final Collection<S> collection, final Local file) throws AccessDeniedException {
    final NSArray list = new NSArray(collection.size());
    int i = 0;
    for(S bookmark : collection) {
        list.setValue(i, bookmark.<NSDictionary>serialize(SerializerFactory.get()));
        i++;
    }
    final String content = list.toXMLPropertyList();
    final OutputStream out = file.getOutputStream(false);
    try {
        IOUtils.write(content, out, Charset.forName("UTF-8"));
    }
    catch(IOException e) {
        throw new AccessDeniedException(String.format("Cannot create file %s", file.getAbsolute()), e);
    }
    finally {
        IOUtils.closeQuietly(out);
    }
}
 
Example 4
Project: convertigo-engine   File: GetTreeIconsCSS.java   View Source Code Vote up 6 votes
@Override
protected void writeResponseResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
	Set<String> classNames = CachedIntrospector.getClassNames();
	StringBuilder sb = new StringBuilder();
	for (String className : classNames) {
		sb.append(".")
		  .append(className.replaceAll("\\.", "-"))
		  .append("-16")
		  .append(" {background-image:url(")

		  .append("../../admin/services/database_objects.GetIcon?className=")
		  .append(className)
		  .append(") !important;")
		  .append("}\r\n");
	}

	response.setContentType(MimeType.Css.value());
	IOUtils.write(sb.toString(), response.getOutputStream(), "UTF-8");
}
 
Example 5
Project: karate   File: Consumer.java   View Source Code Vote up 6 votes
public Payment create(Payment payment) {
    try {
        HttpURLConnection con = getConnection("/payments");
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json");
        String json = JsonUtils.toJson(payment);
        IOUtils.write(json, con.getOutputStream(), "utf-8");
        int status = con.getResponseCode();
        if (status != 200) {
            throw new RuntimeException("status code was " + status);
        }
        String content = IOUtils.toString(con.getInputStream(), "utf-8");
        return JsonUtils.fromJson(content, Payment.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Project: mmsns   File: HadoopUtil.java   View Source Code Vote up 6 votes
/**
 * 从hadoop中下载文件
 *
 * @param taskName
 * @param filePath
 */
public static void download(String taskName, String filePath, boolean existDelete) {
    File file = new File(filePath);
    if (file.exists()) {
        if (existDelete) {
            file.deleteOnExit();
        } else {
            return;
        }
    }
    String hadoopAddress = propertyConfig.getProperty("sqoop.task." + taskName + ".tolink.linkConfig.uri");
    String itemmodels = propertyConfig.getProperty("sqoop.task." + taskName + ".recommend.itemmodels");
    try {
        DistributedFileSystem distributedFileSystem = distributedFileSystem(hadoopAddress);
        FSDataInputStream fsDataInputStream = distributedFileSystem.open(new Path(itemmodels));
        byte[] bs = new byte[fsDataInputStream.available()];
        fsDataInputStream.read(bs);
        log.info(new String(bs));

        FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
        IOUtils.write(bs, fileOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    } catch (IOException e) {
        log.error(e);
    }
}
 
Example 7
Project: urule   File: DefaultHtmlFileDebugWriter.java   View Source Code Vote up 6 votes
@Override
public void write(List<MessageItem> items) throws IOException{
	if(StringUtils.isBlank(path)){
		return;
	}
	StringBuilder msg=new StringBuilder();
	for(MessageItem item:items){
		msg.append(item.toHtml());
	}
	String fullPath=path+"/urule-debug.html";
	StringBuilder sb=new StringBuilder();
	sb.append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>URule调试日志信息</title><body style='font-size:12px'>");
	sb.append(msg.toString());
	sb.append("</body></html>");
	FileOutputStream out=new FileOutputStream(new File(fullPath));
	IOUtils.write(sb.toString(), out);
	out.flush();
	out.close();
}
 
Example 8
Project: cyberduck   File: B2ReadFeatureTest.java   View Source Code Vote up 5 votes
@Test
public void testReadRangeUnknownLength() throws Exception {
    final B2Session session = new B2Session(
            new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
                    new Credentials(
                            System.getProperties().getProperty("b2.user"), System.getProperties().getProperty("b2.key")
                    )));
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());

    final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path test = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    new B2TouchFeature(session).touch(test, new TransferStatus());

    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = RandomUtils.nextBytes(1000);
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);
    IOUtils.write(content, out);
    out.close();
    new B2SingleUploadService(new B2WriteFeature(session)).upload(
            test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            new TransferStatus().length(content.length),
            new DisabledConnectionCallback());
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    status.setAppend(true);
    status.setOffset(100L);
    final InputStream in = new B2ReadFeature(session).read(test, status, new DisabledConnectionCallback());
    assertNotNull(in);
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length - 100);
    new StreamCopier(status, status).transfer(in, buffer);
    final byte[] reference = new byte[content.length - 100];
    System.arraycopy(content, 100, reference, 0, content.length - 100);
    assertArrayEquals(reference, buffer.toByteArray());
    in.close();
    new B2DeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 9
Project: springboot-shiro-cas-mybatis   File: AbstractJacksonBackedJsonSerializer.java   View Source Code Vote up 5 votes
@Override
public void toJson(final OutputStream out, final T object) {
    try (StringWriter writer = new StringWriter()) {
        this.objectMapper.writer(this.prettyPrinter).writeValue(writer, object);
        final String hjsonString = JsonValue.readHjson(writer.toString()).toString(Stringify.HJSON);
        IOUtils.write(hjsonString, out);
    } catch (final Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 10
Project: cyberduck   File: DAVReadFeatureTest.java   View Source Code Vote up 5 votes
@Test
public void testReadRange() throws Exception {
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch", new Credentials(
            System.getProperties().getProperty("webdav.user"), System.getProperties().getProperty("webdav.password")
    ));
    host.setDefaultPath("/dav/basic");
    final DAVSession session = new DAVSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    session.getFeature(Touch.class).touch(test, new TransferStatus());

    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = new RandomStringGenerator.Builder().build().generate(1000).getBytes();
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);
    IOUtils.write(content, out);
    out.close();
    new DAVUploadFeature(new DAVWriteFeature(session)).upload(
            test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            new TransferStatus().length(content.length),
            new DisabledConnectionCallback());
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    status.setAppend(true);
    status.setOffset(100L);
    final InputStream in = new DAVReadFeature(session).read(test, status.length(content.length - 100), new DisabledConnectionCallback());
    assertNotNull(in);
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length - 100);
    new StreamCopier(status, status).transfer(in, buffer);
    final byte[] reference = new byte[content.length - 100];
    System.arraycopy(content, 100, reference, 0, content.length - 100);
    assertArrayEquals(reference, buffer.toByteArray());
    in.close();
    new DAVDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 11
Project: cyberduck   File: OneDriveReadFeatureTest.java   View Source Code Vote up 5 votes
@Test
public void testReadRange() throws Exception {
    final Path drive = new OneDriveHomeFinderFeature(session).find();
    final Path test = new Path(drive, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    new OneDriveTouchFeature(session).touch(test, new TransferStatus());

    final Local local = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random());
    final byte[] content = RandomUtils.nextBytes(1000);
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);
    IOUtils.write(content, out);
    out.close();
    new DefaultUploadFeature<Void>(new OneDriveWriteFeature(session)).upload(
            test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            new TransferStatus().length(content.length),
            new DisabledConnectionCallback());
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    status.setAppend(true);
    status.setOffset(100L);
    final OneDriveReadFeature read = new OneDriveReadFeature(session);
    assertTrue(read.offset(test));
    final InputStream in = read.read(test, status.length(content.length - 100), new DisabledConnectionCallback());
    assertNotNull(in);
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length - 100);
    new StreamCopier(status, status).transfer(in, buffer);
    final byte[] reference = new byte[content.length - 100];
    System.arraycopy(content, 100, reference, 0, content.length - 100);
    assertArrayEquals(reference, buffer.toByteArray());
    in.close();
    new OneDriveDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 12
Project: cyberduck   File: PlistWriter.java   View Source Code Vote up 5 votes
@Override
public void write(final S item, final Local file) throws AccessDeniedException {
    final String content = item.<NSDictionary>serialize(SerializerFactory.get()).toXMLPropertyList();
    final OutputStream out = file.getOutputStream(false);
    try {
        IOUtils.write(content, out, Charset.forName("UTF-8"));
    }
    catch(IOException e) {
        throw new AccessDeniedException(String.format("Cannot create file %s", file.getAbsolute()), e);
    }
    finally {
        IOUtils.closeQuietly(out);
    }
}
 
Example 13
Project: cyberduck   File: IRODSUploadFeatureTest.java   View Source Code Vote up 5 votes
@Test
public void testInterruptStatus() throws Exception {
    final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
    final Profile profile = new ProfilePlistReader(factory).read(
            new Local("../profiles/iRODS (iPlant Collaborative).cyberduckprofile"));
    final Host host = new Host(profile, profile.getDefaultHostname(), new Credentials(
            System.getProperties().getProperty("irods.key"), System.getProperties().getProperty("irods.secret")
    ));

    final IRODSSession session = new IRODSSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final int length = 32770;
    final byte[] content = RandomUtils.nextBytes(length);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);
    out.close();
    final Path test = new Path(new IRODSHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final TransferStatus status = new TransferStatus().length(content.length);
    final Checksum checksum = new IRODSUploadFeature(session).upload(
            test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener() {
                @Override
                public void sent(final long bytes) {
                    super.sent(bytes);
                    status.setCanceled();
                }
            },
            status,
            new DisabledConnectionCallback());
    assertTrue(status.isCanceled());
    assertFalse(status.isComplete());
    session.close();
}
 
Example 14
Project: QDrill   File: FilePStore.java   View Source Code Vote up 5 votes
public void put(String key, V value) {
  try (OutputStream os = fs.create(makePath(key))) {
    IOUtils.write(config.getSerializer().serialize(value), os);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 15
Project: Hydroangeas   File: ResourceManager.java   View Source Code Vote up 4 votes
public void extract(File dir ) throws IOException {
    File listDir[] = dir.listFiles();
    if (listDir.length!=0){
        for (File i:listDir){
    /*  Warning! this will try and extract all files in the directory
        if other files exist, a for loop needs to go here to check that
        the file (i) is an archive file before proceeding */
            if (i.isDirectory()){
                break;
            }
            String fileName = i.toString();
            String tarFileName = fileName +".tar";
            FileInputStream instream= new FileInputStream(fileName);
            GZIPInputStream ginstream =new GZIPInputStream(instream);
            FileOutputStream outstream = new FileOutputStream(tarFileName);
            byte[] buf = new byte[1024];
            int len;
            while ((len = ginstream.read(buf)) > 0)
            {
                outstream.write(buf, 0, len);
            }
            ginstream.close();
            outstream.close();
            //There should now be tar files in the directory
            //extract specific files from tar
            TarArchiveInputStream myTarFile=new TarArchiveInputStream(new FileInputStream(tarFileName));
            TarArchiveEntry entry = null;
            int offset;
            FileOutputStream outputFile=null;
            //read every single entry in TAR file
            while ((entry = myTarFile.getNextTarEntry()) != null) {
                //the following two lines remove the .tar.gz extension for the folder name
                fileName = i.getName().substring(0, i.getName().lastIndexOf('.'));
                fileName = fileName.substring(0, fileName.lastIndexOf('.'));
                File outputDir =  new File(i.getParent() + "/" + fileName + "/" + entry.getName());
                if(! outputDir.getParentFile().exists()){
                    outputDir.getParentFile().mkdirs();
                }
                //if the entry in the tar is a directory, it needs to be created, only files can be extracted
                if(entry.isDirectory()){
                    outputDir.mkdirs();
                }else{
                    byte[] content = new byte[(int) entry.getSize()];
                    offset=0;
                    myTarFile.read(content, offset, content.length - offset);
                    outputFile=new FileOutputStream(outputDir);
                    IOUtils.write(content,outputFile);
                    outputFile.close();
                }
            }
            //close and delete the tar files, leaving the original .tar.gz and the extracted folders
            myTarFile.close();
            File tarFile =  new File(tarFileName);
            tarFile.delete();
        }
    }
}
 
Example 16
Project: flume-release-1.7.0   File: TestNetcatSource.java   View Source Code Vote up 4 votes
private void sendEvent(Socket socket, String content, String encoding) throws IOException {
  OutputStream output = socket.getOutputStream();
  IOUtils.write(content + IOUtils.LINE_SEPARATOR_UNIX, output, encoding);
  output.flush();
}
 
Example 17
Project: cyberduck   File: SwiftLargeObjectUploadFeatureTest.java   View Source Code Vote up 4 votes
@Test
public void testAppendSecondPart() throws Exception {
    final SwiftSession session = new SwiftSession(
            new Host(new SwiftProtocol(), "identity.api.rackspacecloud.com",
                    new Credentials(
                            System.getProperties().getProperty("rackspace.key"), System.getProperties().getProperty("rackspace.secret"))));
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
    container.attributes().setRegion("DFW");
    final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final String name = UUID.randomUUID().toString();
    final Local local = new Local(System.getProperty("java.io.tmpdir"), name);
    final int length = 2 * 1024 * 1024;
    final byte[] content = RandomUtils.nextBytes(length);
    IOUtils.write(content, local.getOutputStream(false));
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    final AtomicBoolean interrupt = new AtomicBoolean();
    try {
        new SwiftLargeObjectUploadFeature(session, new SwiftRegionService(session), new SwiftWriteFeature(session, new SwiftRegionService(session)),
                1024L * 1024L, 1).upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener() {
            long count;

            @Override
            public void sent(final long bytes) {
                count += bytes;
                if(count >= 1.1 * 1024L * 1024L) {
                    throw new RuntimeException();
                }
            }
        }, status, new DisabledLoginCallback());
    }
    catch(BackgroundException e) {
        // Expected
        interrupt.set(true);
    }
    assertTrue(interrupt.get());
    assertEquals(1024L * 1024L, status.getOffset(), 0L);
    assertFalse(status.isComplete());

    final TransferStatus append = new TransferStatus().append(true).length(1024L * 1024L).skip(1024L * 1024L);
    new SwiftLargeObjectUploadFeature(session, new SwiftRegionService(session), new SwiftWriteFeature(session, new SwiftRegionService(session)),
            1024L * 1024L, 1).upload(test, local,
            new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), append,
            new DisabledLoginCallback());
    assertEquals(2 * 1024L * 1024L, append.getOffset(), 0L);
    assertTrue(append.isComplete());
    assertTrue(new SwiftFindFeature(session).find(test));
    assertEquals(2 * 1024L * 1024L, new SwiftAttributesFinderFeature(session).find(test).getSize(), 0L);
    final byte[] buffer = new byte[content.length];
    final InputStream in = new SwiftReadFeature(session, new SwiftRegionService(session)).read(test, new TransferStatus(), new DisabledConnectionCallback());
    IOUtils.readFully(in, buffer);
    in.close();
    assertArrayEquals(content, buffer);
    new SwiftDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    local.delete();
    session.close();
}
 
Example 18
Project: nest-spider   File: ElasticsearchDAO.java   View Source Code Vote up 4 votes
/**
 * 导出数据
 * @param builder
 * @param labelsSupplier
 * @param contentSupplier
 * @param out  经过分词器的输出流
 */
protected void exportData(QueryBuilder builder, Function<SearchResponse, List<List<String>>> labelsSupplier, 
		Function<SearchResponse, List<String>> contentSupplier, OutputStream out) {
	final int size = 50;
	String scrollId = null;
	int page = 1;
	while(true) {
		LOG.debug("正在输出第" + page + "页,query:" + builder);
		SearchResponse response;
		if(StringUtils.isBlank(scrollId)) {
			response = search().setQuery(builder).setSize(size)
					.setScroll(SCROLL_TIMEOUT).get();
			scrollId = response.getScrollId();
		} else {
			response = client.prepareSearchScroll(scrollId)
					.setScroll(SCROLL_TIMEOUT).get();
		}
		final List<List<String>> labels = labelsSupplier.apply(response);
		final List<String> contentList = contentSupplier.apply(response);
		Preconditions.checkNotNull(labels);
		Preconditions.checkNotNull(contentList);
		if(contentList.size()<=0)
			break;
		//开始分词
		List<String> combine;
		if(labels.size() > 0) {
			combine = labels.stream().map(list -> list.parallelStream().collect(Collectors.joining("/")))
					.collect(Collectors.toList());
			for(int i = 0;i<labels.size();i++) 
				combine.set(i, combine.get(i) + " " + contentList.get(i));
		} else
			combine = contentList;
		page++;
		try {
			IOUtils.write(combine.stream().collect(Collectors.joining("\n")) + "\n", out, "utf-8");
			out.flush();
		} catch(IOException e) {
			LOG.error("文件写出错误, 由于 " + e.getLocalizedMessage());
		}
	}
}
 
Example 19
Project: cyberduck   File: B2LargeUploadServiceTest.java   View Source Code Vote up 4 votes
@Test
public void testUploadWithBulk() throws Exception {
    // 5L * 1024L * 1024L
    final Host host = new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
            new Credentials(
                    System.getProperties().getProperty("b2.user"), System.getProperties().getProperty("b2.key")
            ));
    final B2Session session = new B2Session(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new Path("/test-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
    final CryptoVault cryptomator = new CryptoVault(
            new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new DisabledPasswordStore());
    final Path vault = cryptomator.create(session, null, new VaultCredentials("test"));
    final Path test = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    session.withRegistry(new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    final TransferStatus writeStatus = new TransferStatus();
    final int length = 5242885;
    final byte[] content = RandomUtils.nextBytes(length);
    writeStatus.setLength(content.length);
    final CryptoBulkFeature<Void> bulk = new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new B2DeleteFeature(session), cryptomator);
    bulk.pre(Transfer.Type.upload, Collections.singletonMap(test, writeStatus), new DisabledConnectionCallback());
    final CryptoUploadFeature m = new CryptoUploadFeature<>(session,
            new B2LargeUploadService(session, new B2WriteFeature(session), 5242880L, 5),
            new B2WriteFeature(session), cryptomator);
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    IOUtils.write(content, local.getOutputStream(false));
    m.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), writeStatus, null);
    assertEquals((long) content.length, writeStatus.getOffset(), 0L);
    assertTrue(writeStatus.isComplete());
    assertTrue(new CryptoFindFeature(session, new B2FindFeature(session), cryptomator).find(test));
    assertEquals(content.length, new CryptoAttributesFeature(session, new B2AttributesFinderFeature(session), cryptomator).find(test).getSize());
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
    final TransferStatus readStatus = new TransferStatus().length(content.length);
    final InputStream in = new CryptoReadFeature(session, new B2ReadFeature(session), cryptomator).read(test, readStatus, new DisabledConnectionCallback());
    new StreamCopier(readStatus, readStatus).transfer(in, buffer);
    assertArrayEquals(content, buffer.toByteArray());
    new CryptoDeleteFeature(session, new B2DeleteFeature(session), cryptomator).delete(Arrays.asList(test, vault), new DisabledLoginCallback(), new Delete.DisabledCallback());
    local.delete();
    session.close();
}
 
Example 20
Project: ares   File: IOManager.java   View Source Code Vote up 2 votes
/**
 * Write on a resource.
 * @param resource the resource to write on.
 * @param  string the string to write.
 * @throws IOException when resource cannot be read.
 */
public static void writeResource(String resource, String string) throws IOException {
  try (final OutputStream out = getOutputStream(resource)) {
    IOUtils.write(string, out, Charset.defaultCharset());
  }
}