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

The following examples show how to use org.apache.commons.io.IOUtils#write() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 生成代码
 */
@RequestMapping("/code")
@RequiresPermissions("sys:generator:code")
public void code(HttpServletRequest request, HttpServletResponse response) throws IOException{
	String[] tableNames = new String[]{};
	String tables = request.getParameter("tables");
	tableNames = JSON.parseArray(tables).toArray(tableNames);
	
	byte[] data = sysGeneratorService.generatorCode(tableNames);
	
	response.reset();  
       response.setHeader("Content-Disposition", "attachment; filename=\"generate-code.zip\"");
       response.addHeader("Content-Length", "" + data.length);  
       response.setContentType("application/octet-stream; charset=UTF-8");  
 
       IOUtils.write(data, response.getOutputStream());  
}
 
Example 2
Source Project: karate   File: Consumer.java    License: MIT License 6 votes vote down vote up
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 3
Source Project: keycloak   File: Timer.java    License: Apache License 2.0 6 votes vote down vote up
private void saveData(String op) {
    try {
        File f = new File(DATA_DIR, op.replace(" ", "_") + ".txt");
        if (!f.createNewFile()) {
            throw new IOException("Couldn't create file: " + f);
        }
        OutputStream stream = new BufferedOutputStream(new FileOutputStream(f));
        for (Long duration : stats.get(op)) {
            IOUtils.write(duration.toString(), stream, "UTF-8");
            IOUtils.write("\n", stream, "UTF-8");
        }
        stream.flush();
        IOUtils.closeQuietly(stream);
    } catch (IOException ex) {
        log.error("Unable to save data for operation '" + op + "'", ex);
    }
}
 
Example 4
@Test
public void testUpload() throws Exception {
    final S3SingleUploadService service = new S3SingleUploadService(session, new S3WriteFeature(session, new S3DisabledMultipartService()));
    final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final String name = UUID.randomUUID().toString() + ".txt";
    final Path test = new Path(container, name, EnumSet.of(Path.Type.file));
    final Local local = new Local(System.getProperty("java.io.tmpdir"), name);
    final String random = new RandomStringGenerator.Builder().build().generate(1000);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(random, out, Charset.defaultCharset());
    out.close();
    final TransferStatus status = new TransferStatus();
    status.setLength(random.getBytes().length);
    status.setMime("text/plain");
    service.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
        new DisabledStreamListener(), status, new DisabledLoginCallback());
    assertTrue(new S3FindFeature(session).find(test));
    final PathAttributes attributes = new S3AttributesFinderFeature(session).find(test);
    assertEquals(random.getBytes().length, attributes.getSize());
    final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session)).getMetadata(test);
    assertFalse(metadata.isEmpty());
    assertEquals("text/plain", metadata.get("Content-Type"));
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    local.delete();
}
 
Example 5
Source Project: coffee-gb   File: FileBattery.java    License: MIT License 5 votes vote down vote up
private void saveClock(long[] clockData, OutputStream os) throws IOException {
    byte[] byteBuff = new byte[4 * clockData.length];
    ByteBuffer buff = ByteBuffer.wrap(byteBuff);
    buff.order(ByteOrder.LITTLE_ENDIAN);
    for (long d : clockData) {
        buff.putInt((int) d);
    }
    IOUtils.write(byteBuff, os);
}
 
Example 6
Source Project: fess   File: ProcessHelper.java    License: Apache License 2.0 5 votes vote down vote up
public void sendCommand(final String sessionId, final String command) {
    final JobProcess jobProcess = runningProcessMap.get(sessionId);
    if (jobProcess != null) {
        try {
            final OutputStream out = jobProcess.getProcess().getOutputStream();
            IOUtils.write(command + "\n", out, Constants.CHARSET_UTF_8);
            out.flush();
        } catch (final IOException e) {
            throw new JobProcessingException(e);
        }
    } else {
        throw new JobNotFoundException("Job for " + sessionId + " is not found.");
    }
}
 
Example 7
Source Project: archiva   File: FilesystemStorageTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void moveAsset() throws IOException {
    Path newFile=null;
    Path newDir=null;
    try {
        Assert.assertTrue(Files.exists(file1));
        try (OutputStream os = Files.newOutputStream(file1)) {
            IOUtils.write("testakdkkdkdkdk", os, "ASCII");
        }
        long fileSize = Files.size(file1);
        fsStorage.moveAsset(file1Asset, "/dir2/testfile2.dat");
        Assert.assertFalse(Files.exists(file1));
        newFile = baseDir.resolve("dir2/testfile2.dat");
        Assert.assertTrue(Files.exists(newFile));
        Assert.assertEquals(fileSize, Files.size(newFile));


        Assert.assertTrue(Files.exists(dir1));
        newDir = baseDir.resolve("dir2/testdir2");
        fsStorage.moveAsset(dir1Asset, "dir2/testdir2");
        Assert.assertFalse(Files.exists(dir1));
        Assert.assertTrue(Files.exists(newDir));
    } finally {
        if (newFile!=null) Files.deleteIfExists(newFile);
        if (newDir!=null) Files.deleteIfExists(newDir);
    }
}
 
Example 8
@Test
public void testUploadSinglePart() throws Exception {
    final S3MultipartUploadService service = new S3MultipartUploadService(session, new S3WriteFeature(session, new S3DisabledMultipartService()), 5 * 1024L, 2);
    final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final String name = String.format(" %s.txt", UUID.randomUUID().toString());
    final Path test = new Path(container, name, EnumSet.of(Path.Type.file));
    final Local local = new Local(System.getProperty("java.io.tmpdir"), name);
    final String random = new RandomStringGenerator.Builder().build().generate(1000);
    IOUtils.write(random, local.getOutputStream(false), Charset.defaultCharset());
    final TransferStatus status = new TransferStatus();
    status.setLength((long) random.getBytes().length);
    status.setMime("text/plain");
    status.setStorageClass(S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY);
    service.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
        new DisabledStreamListener(), status, new DisabledLoginCallback());
    assertEquals((long) random.getBytes().length, status.getOffset(), 0L);
    assertTrue(status.isComplete());
    assertTrue(new S3FindFeature(session).find(test));
    final PathAttributes attributes = new S3AttributesFinderFeature(session).find(test);
    assertEquals(random.getBytes().length, attributes.getSize());
    assertEquals(S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY, new S3StorageClassFeature(session).getClass(test));
    final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session)).getMetadata(test);
    assertFalse(metadata.isEmpty());
    assertEquals("text/plain", metadata.get("Content-Type"));
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    local.delete();
}
 
Example 9
public static void debugOutputModel(CrossValidatorModel model, TrainingSettings trainingSettings, String output) throws IOException {
    FileSystem fs = FileSystem.get(new Configuration());
    Path statsPath = new Path(output+"debug_"+trainingSettings.getClassificationMethod()+".txt");
    fs.delete(statsPath, true);

    FSDataOutputStream fsdos = fs.create(statsPath);
    PipelineModel pipelineModel = (PipelineModel) model.bestModel();
    switch (trainingSettings.getClassificationMethod()) {
        case RANDOM_FOREST:
            for(int i=0; i< pipelineModel.stages().length; i++) {
                if (pipelineModel.stages()[i] instanceof RandomForestClassificationModel) {
                    RandomForestClassificationModel rfModel = (RandomForestClassificationModel) (pipelineModel.stages()[i]);
                    IOUtils.write(rfModel.toDebugString(), fsdos);
                    logger.info(rfModel.toDebugString());
                }
            }
            break;
        case LOG_REG:
            for(int i=0; i< pipelineModel.stages().length; i++) {
                if (pipelineModel.stages()[i] instanceof LogisticRegressionModel) {
                    LogisticRegressionModel lgModel = (LogisticRegressionModel) (pipelineModel.stages()[i]);
                    IOUtils.write(lgModel.toString(), fsdos);
                    logger.info(lgModel.toString());
                }
            }
            break;
    }
    fsdos.flush();
    IOUtils.closeQuietly(fsdos);
}
 
Example 10
@Override
public void run(CommandLine cmdLine, OutputStream out, OutputStream err)
    throws Exception {
  Preconditions.checkNotNull(cmdLine);
  Preconditions.checkNotNull(out);
  Preconditions.checkNotNull(err);

  Writer writer = new OutputStreamWriter(out, "UTF-8");
  try {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(
        DefaultValidatorConfiguration.class);
    @SuppressWarnings("unchecked")
    Parser<ServiceMonitoringDefinitionsDescriptor> parser =
      ctx.getBean("mdlParser", Parser.class);
    @SuppressWarnings("unchecked")
    DescriptorValidator<ServiceMonitoringDefinitionsDescriptor> validator =
      ctx.getBean("serviceMonitoringDefinitionsDescriptorValidator",
                  DescriptorValidator.class);
    ValidationRunner runner =
        new DescriptorRunner<ServiceMonitoringDefinitionsDescriptor>(
            parser, validator);
    if (!runner.run(cmdLine.getOptionValue(OPT_MDL.getLongOpt()), writer)) {
      throw new RuntimeException("Validation failed.");
    }
  } catch (Exception ex) {
    LOG.error("Could not run validation tool.", ex);
    IOUtils.write(ex.getMessage() + "\n", err);
    throw ex;
  } finally {
    writer.close();
  }
}
 
Example 11
Source Project: kbase-doc   File: WatermarkWordTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 给 docx 文件加水印
 * @author eko.zhan at 2018年8月31日 下午1:41:50
 * @throws IOException 
 */
@Test
public void testDocx() throws IOException {
	String filepath = "E:\\ConvertTester\\docx\\NVR5X-I人脸比对配置-ekozhan.docx";

	WatermarkServiceImpl service = new WatermarkServiceImpl();
	byte[] bytes = service.handle(new File(filepath), "中华民国100");
	//		FileOutputStream out = new FileOutputStream("E:\\1.docx");
	//		IOUtils.write(bytes, out);
	try (FileOutputStream out = new FileOutputStream("E:\\1.docx")){
		IOUtils.write(bytes, out);
	}
}
 
Example 12
Source Project: metron   File: LocalWriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void write(byte[] obj, Optional<String> output, Configuration hadoopConfig) throws IOException {
  File outFile = new File(output.get());
  if(!outFile.getParentFile().exists()) {
    outFile.getParentFile().mkdirs();
  }
  try(FileOutputStream fs = new FileOutputStream(outFile)) {
    IOUtils.write(obj, fs);
    fs.flush();
  }
}
 
Example 13
@Test
public void testUploadSinglePartEncrypted() throws Exception {
    final S3MultipartUploadService service = new S3MultipartUploadService(session, new S3WriteFeature(session, new S3DisabledMultipartService()), 5 * 1024L, 2);
    final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final String name = UUID.randomUUID().toString() + ".txt";
    final Path test = new Path(container, name, EnumSet.of(Path.Type.file));
    final Local local = new Local(System.getProperty("java.io.tmpdir"), name);
    final String random = new RandomStringGenerator.Builder().build().generate(1000);
    IOUtils.write(random, local.getOutputStream(false), Charset.defaultCharset());
    final TransferStatus status = new TransferStatus();
    status.setEncryption(KMSEncryptionFeature.SSE_KMS_DEFAULT);
    status.setLength((long) random.getBytes().length);
    status.setMime("text/plain");
    status.setStorageClass(S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY);
    service.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
        new DisabledStreamListener(), status, new DisabledLoginCallback());
    assertEquals((long) random.getBytes().length, status.getOffset(), 0L);
    assertTrue(status.isComplete());
    assertTrue(new S3FindFeature(session).find(test));
    final PathAttributes attributes = new S3AttributesFinderFeature(session).find(test);
    assertEquals(random.getBytes().length, attributes.getSize());
    assertEquals(S3Object.STORAGE_CLASS_REDUCED_REDUNDANCY, new S3StorageClassFeature(session).getClass(test));
    final Map<String, String> metadata = new S3MetadataFeature(session, new S3AccessControlListFeature(session)).getMetadata(test);
    assertFalse(metadata.isEmpty());
    assertEquals("text/plain", metadata.get("Content-Type"));
    assertEquals("aws:kms", metadata.get("server-side-encryption"));
    assertNotNull(metadata.get("server-side-encryption-aws-kms-key-id"));
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    local.delete();
}
 
Example 14
private static void writeText(File target, String body) {
    try {
        IOUtils.write(body, new FileOutputStream(target), "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source Project: ripme   File: History.java    License: MIT License 4 votes vote down vote up
public void toFile(String filename) throws IOException {
    try (OutputStream os = new FileOutputStream(filename)) {
        IOUtils.write(toJSON().toString(2), os);
    }
}
 
Example 16
protected void saveParser() {
  JFileChooser chooser = new JFileChooser();
  chooser.setCurrentDirectory(AllPluginables.USER_LOG_IMPORTERS);
  chooser.addChoosableFileFilter(new FileFilter() {

    @Override
    public String getDescription() {
      return "*.pattern files";
    }

    @Override
    public boolean accept(File f) {
      return f.getName().endsWith(".pattern") || f.isDirectory();
    }
  });
  int showSaveDialog = chooser.showSaveDialog(this);
  if (showSaveDialog == JFileChooser.APPROVE_OPTION) {
    File selectedFile = chooser.getSelectedFile();
    if (!selectedFile.getName().endsWith(".pattern")) {
      selectedFile = new File(selectedFile.getAbsolutePath() + ".pattern");
    }
    if (selectedFile.exists()
      && JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(this, "Do you want to overwrite file " + selectedFile.getName() + "?", "Save parser",
      JOptionPane.YES_NO_OPTION)) {
      return;
    }
    String text = propertyEditor.getText();
    FileOutputStream output = null;
    try {
      output = new FileOutputStream(selectedFile);
      IOUtils.write(text, output);
      LogImporterUsingParser log4jImporter = craeteLogImporter(text);
      otrosApplication.getAllPluginables().getLogImportersContainer().addElement(log4jImporter);
    } catch (Exception e) {
      LOGGER.error("Can't save parser: ", e);
      JOptionPane.showMessageDialog(this, "Can't save parser: " + e.getMessage(), "Error saving parser", JOptionPane.ERROR_MESSAGE);
    } finally {
      IOUtils.closeQuietly(output);
    }
  }
}
 
Example 17
Source Project: ldp4j   File: OutputStreamMarshaller.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void marshall(Iterable<Triple> triples, OutputStream target) throws IOException {
	String output = new RDFModelFormater(getConfiguration().getBase(),getConfiguration().getNamespaces(),getConfiguration().getFormat()).format(triples);
	IOUtils.write(output, target);
}
 
Example 18
Source Project: OSPREY3   File: FileTools.java    License: GNU General Public License v2.0 4 votes vote down vote up
private static void writeStream(String text, OutputStream out)
throws IOException {
	IOUtils.write(text, out, (Charset)null);
}
 
Example 19
public static void saveStats(CrossValidatorModel model, TrainingSettings trainingSettings, String output) throws IOException {
    double[] avgMetrics = model.avgMetrics();
    double bestMetric = 0;
    int bestIndex=0;

    for(int i=0; i<avgMetrics.length; i++) {
        if(avgMetrics[i] > bestMetric) {
            bestMetric = avgMetrics[i];
            bestIndex = i;
        }
    }


    FileSystem fs = FileSystem.get(new Configuration());
    Path statsPath = new Path(output+"stats_"+trainingSettings.getClassificationMethod()+".txt");
    fs.delete(statsPath, true);

    FSDataOutputStream fsdos = fs.create(statsPath);

    String avgLine="Average cross-validation metrics: "+ Arrays.toString(model.avgMetrics());
    String bestMetricLine="\nBest cross-validation metric ["+trainingSettings.getMetricName()+"]: "+bestMetric;
    String bestSetParamLine= "\nBest set of parameters: "+model.getEstimatorParamMaps()[bestIndex];

    logger.info(avgLine);
    logger.info(bestMetricLine);
    logger.info(bestSetParamLine);


    IOUtils.write(avgLine, fsdos);
    IOUtils.write(bestMetricLine, fsdos);
    IOUtils.write(bestSetParamLine, fsdos);

    PipelineModel pipelineModel = (PipelineModel) model.bestModel();
    for(Transformer t : pipelineModel.stages()) {
        if(t instanceof ClassificationModel) {
            IOUtils.write("\n"+((Model) t).parent().extractParamMap().toString(), fsdos);
            logger.info(((Model) t).parent().extractParamMap().toString());
        }
    }

    fsdos.flush();
    IOUtils.closeQuietly(fsdos);

    debugOutputModel(model,trainingSettings, output);
}
 
Example 20
Source Project: smallrye-open-api   File: TckTestRunner.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Constructor.
 * 
 * @param testClass
 * @throws InitializationError
 */
public TckTestRunner(Class<?> testClass) throws InitializationError {
    super(testClass);
    this.testClass = testClass;
    this.tckTestClass = determineTckTestClass(testClass);

    // The Archive (shrinkwrap deployment)
    Archive archive = archive();
    // MPConfig
    OpenApiConfig config = ArchiveUtil.archiveToConfig(archive);

    try {
        IndexView index = ArchiveUtil.archiveToIndex(config, archive);
        OpenApiStaticFile staticFile = ArchiveUtil.archiveToStaticFile(archive);

        // Reset and then initialize the OpenApiDocument for this test.
        OpenApiDocument.INSTANCE.reset();
        OpenApiDocument.INSTANCE.config(config);
        OpenApiDocument.INSTANCE.modelFromStaticFile(OpenApiProcessor.modelFromStaticFile(staticFile));
        OpenApiDocument.INSTANCE.modelFromAnnotations(OpenApiProcessor.modelFromAnnotations(config, index));
        OpenApiDocument.INSTANCE.modelFromReader(OpenApiProcessor.modelFromReader(config, getContextClassLoader()));
        OpenApiDocument.INSTANCE.filter(OpenApiProcessor.getFilter(config, getContextClassLoader()));
        OpenApiDocument.INSTANCE.initialize();

        Assert.assertNotNull("Generated OAI document must not be null.", OpenApiDocument.INSTANCE.get());

        OPEN_API_DOCS.put(testClass, OpenApiDocument.INSTANCE.get());

        // Output the /openapi content to a file for debugging purposes
        File parent = new File("target", "TckTestRunner");
        if (!parent.exists()) {
            parent.mkdir();
        }
        File file = new File(parent, testClass.getName() + ".json");
        String content = OpenApiSerializer.serialize(OpenApiDocument.INSTANCE.get(), Format.JSON);
        try (FileWriter writer = new FileWriter(file)) {
            IOUtils.write(content, writer);
        }
    } catch (Exception e) {
        throw new InitializationError(e);
    }
}