Example usage for org.apache.commons.io IOUtils write

List of usage examples for org.apache.commons.io IOUtils write

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils write.

Prototype

public static void write(StringBuffer data, OutputStream output) throws IOException 

Source Link

Document

Writes chars from a StringBuffer to bytes on an OutputStream using the default character encoding of the platform.

Usage

From source file:com.thoughtworks.go.server.domain.JobInstanceLogTest.java

@Test
public void shouldFindIndexPageFromTestOutput() throws Exception {
    rootFolder = new File("root");
    final File testOutput = new File(rootFolder, "testoutput");
    testOutput.mkdirs();/*from w w w  . ja v  a 2  s .  c o  m*/
    File indexHtml = new File(testOutput, "index.html");
    FileOutputStream fileOutputStream = new FileOutputStream(indexHtml);
    IOUtils.write("Test", fileOutputStream);
    IOUtils.closeQuietly(fileOutputStream);
    HashMap map = new HashMap();
    map.put("artifactfolder", rootFolder);
    jobInstanceLog = new JobInstanceLog(null, map);
    assertThat(jobInstanceLog.getTestIndexPage(), is(indexHtml));
}

From source file:com.youTransactor.uCube.rpc.RPCManager.java

private void sendInsecureCommand(RPCCommand command) throws IOException {
    byte[] payload = command.getPayload();

    byte[] message = new byte[payload.length + Constants.RPC_HEADER_LEN];
    int offset = 0;

    message[offset++] = (byte) (payload.length / 0x100);
    message[offset++] = (byte) (payload.length % 0x100);
    message[offset++] = sequenceNumber++;
    message[offset++] = (byte) (command.getCommandId() / 0x100);
    message[offset++] = (byte) (command.getCommandId() % 0x100);

    System.arraycopy(payload, 0, message, offset, payload.length);

    int crc = computeChecksumCRC16(message);

    out.write(Constants.STX);//from   w  ww.j  ava 2s .c om
    IOUtils.write(message, out);
    out.write((byte) (crc / 0x100));
    out.write((byte) (crc % 0x100));
    out.write(Constants.ETX);

    LogManager.debug(RPCManager.class.getSimpleName(), "sent message: 0x" + Tools.bytesToHex(message));
}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File jenkinsTemplateWar = new File(warTemplateFile);

    if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) {
        String message = "The given Jenkins template WAR [" + jenkinsTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);/*w  w  w.ja v a  2 s . c  o m*/
        throw new IllegalStateException(message);
    }

    String pathProperty = perOrg ? configuration.getOrganizationIdentifier()
            : configuration.getProjectIdentifier();

    String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL)
            + jenkinsPath + pathProperty + "/jenkins/";
    deployedUrl.replace("//", "/");
    URL deployedJenkinsUrl;
    try {
        deployedJenkinsUrl = new URL(deployedUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    String webappName = deployedJenkinsUrl.getPath();
    if (webappName.startsWith("/")) {
        webappName = webappName.substring(1);
    }
    if (webappName.endsWith("/")) {
        webappName = webappName.substring(0, webappName.length() - 1);
    }
    webappName = webappName.replace("/", "#");
    webappName = webappName + ".war";

    // Calculate our final filename.

    String deployLocation = targetWebappsDir + webappName;

    File jenkinsDeployFile = new File(deployLocation);

    if (jenkinsDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct JENKINS_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar),
                jenkinsTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into its deployment location so that it can be picked up and deployed by the app server.
        FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:com.sangupta.dryrun.mongo.DryRunGridFSDBFile.java

@Override
public long writeTo(OutputStream out) throws IOException {
    IOUtils.write(this.bytes, out);
    return this.bytes.length;
}

From source file:ch.cyberduck.core.manta.MantaReadFeatureTest.java

@Test
public void testReadRangeUnknownLength() throws Exception {
    final Path drive = new MantaDirectoryFeature(session).mkdir(randomDirectory(), "", new TransferStatus());
    final Path test = new Path(drive, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.file));
    new MantaTouchFeature(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);//w ww. j ava 2 s.  c om
    IOUtils.write(content, out);
    out.close();
    new DefaultUploadFeature<Void>(new MantaWriteFeature(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 MantaReadFeature(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();
    final MantaDeleteFeature delete = new MantaDeleteFeature(session);
    delete.delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
}

From source file:ch.cyberduck.core.onedrive.OneDriveReadFeatureTest.java

@Test
public void testReadRangeUnknownLength() 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);/*  w w w.  j ava  2  s  .  com*/
    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(-1L);
    status.setAppend(true);
    status.setOffset(100L);
    final InputStream in = new OneDriveReadFeature(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 OneDriveDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:de.griffel.confluence.plugins.plantuml.PlantUmlMacroTest.java

@Test
public void ditaa() throws Exception {
    final MockExportDownloadResourceManager resourceManager = new MockExportDownloadResourceManager();
    resourceManager.setDownloadResourceWriter(new MockDownloadResourceWriter());
    final PlantUmlMacro macro = new PlantUmlMacro(resourceManager, null, mocks.getSpaceManager(),
            mocks.getSettingsManager(), mocks.getPluginAccessor(), mocks.getShortcutLinksManager(),
            mocks.getConfigurationManager(), mocks.getI18NBeanFactory());
    final ImmutableMap<String, String> macroParams = new ImmutableMap.Builder<String, String>()
            .put(PlantUmlMacroParams.Param.type.name(), DiagramType.DITAA.name().toLowerCase())
            .put(PlantUmlMacroParams.Param.align.name(), PlantUmlMacroParams.Alignment.center.name())
            .put(PlantUmlMacroParams.Param.border.name(), "3").build();
    final String macroBody = new StringBuilder().append("/--------\\   +-------+\n")
            .append("|cAAA    +---+Version|\n").append("|  Data  |   |   V3  |\n")
            .append("|  Base  |   |cRED{d}|\n").append("|     {s}|   +-------+\n").append("\\---+----/\n")
            .toString();//from w w  w.j  a va  2 s . com
    final String result = macro.execute(macroParams, macroBody, new PageContextMock());
    assertEquals(
            "<span class=\"image-wrap\" style=\"display: block; text-align: center;\"><img src='junit/resource.png' "
                    + "style=\"border:3px solid black;\" /></span>",
            result);
    final ByteArrayOutputStream out = (ByteArrayOutputStream) resourceManager
            .getResourceWriter(null, null, null).getStreamForWriting();
    assertTrue(out.toByteArray().length > 0); // file size depends on installation of graphviz
    IOUtils.write(out.toByteArray(), new FileOutputStream("target/junit-ditaat.png"));
}

From source file:com.github.tteofili.p2h.Par2HierTest.java

@Test
public void testP2HOnMTPapers() throws Exception {
    ParagraphVectors paragraphVectors;/*from  w  ww  . j  ava 2s. co m*/
    LabelAwareIterator iterator;
    TokenizerFactory tokenizerFactory;
    ClassPathResource resource = new ClassPathResource("papers/sbc");

    // build a iterator for our MT papers dataset
    iterator = new FilenamesLabelAwareIterator.Builder().addSourceFolder(resource.getFile()).build();

    tokenizerFactory = new DefaultTokenizerFactory();
    tokenizerFactory.setTokenPreProcessor(new CommonPreprocessor());

    Map<String, INDArray> hvs = new TreeMap<>();
    Map<String, INDArray> pvs = new TreeMap<>();

    paragraphVectors = new ParagraphVectors.Builder().iterate(iterator).tokenizerFactory(tokenizerFactory)
            .build();

    // fit model
    paragraphVectors.fit();

    Par2Hier par2Hier = new Par2Hier(paragraphVectors, method, k);

    // fit model
    par2Hier.fit();

    Map<String, String[]> comparison = new TreeMap<>();

    // extract paragraph vectors similarities
    WeightLookupTable<VocabWord> lookupTable = paragraphVectors.getLookupTable();
    List<String> labels = paragraphVectors.getLabelsSource().getLabels();
    for (String label : labels) {
        INDArray vector = lookupTable.vector(label);
        pvs.put(label, vector);
        Collection<String> strings = paragraphVectors.nearestLabels(vector, 2);
        Collection<String> hstrings = par2Hier.nearestLabels(vector, 2);
        String[] stringsArray = new String[2];
        stringsArray[0] = new LinkedList<>(strings).get(1);
        stringsArray[1] = new LinkedList<>(hstrings).get(1);
        comparison.put(label, stringsArray);
        hvs.put(label, par2Hier.getLookupTable().vector(label));
    }

    System.out.println("--->func(args):pv,p2h");

    // measure similarity indexes
    double[] intraDocumentSimilarity = getIntraDocumentSimilarity(comparison);
    System.out.println("ids(" + k + "," + method + "):" + Arrays.toString(intraDocumentSimilarity));
    double[] depthSimilarity = getDepthSimilarity(comparison);
    System.out.println("ds(" + k + "," + method + "):" + Arrays.toString(depthSimilarity));

    // classification
    Map<Integer, Map<Integer, Long>> pvCounts = new HashMap<>();
    Map<Integer, Map<Integer, Long>> p2hCounts = new HashMap<>();
    for (String label : labels) {

        INDArray vector = lookupTable.vector(label);
        int topN = 1;
        Collection<String> strings = paragraphVectors.nearestLabels(vector, topN);
        Collection<String> hstrings = par2Hier.nearestLabels(vector, topN);
        int labelDepth = label.split("\\.").length - 1;

        int stringDepth = getClass(strings);
        int hstringDepth = getClass(hstrings);

        updateCM(pvCounts, labelDepth, stringDepth);
        updateCM(p2hCounts, labelDepth, hstringDepth);
    }

    ConfusionMatrix pvCM = new ConfusionMatrix(pvCounts);
    ConfusionMatrix p2hCM = new ConfusionMatrix(p2hCounts);

    System.out.println("mf1(" + k + "," + method + "):" + pvCM.getF1Measure() + "," + p2hCM.getF1Measure());
    System.out.println("acc(" + k + "," + method + "):" + pvCM.getAccuracy() + "," + p2hCM.getAccuracy());

    // create a CSV with a raw comparison
    File pvFile = Files.createFile(Paths.get("target/comparison-" + k + "-" + method + ".csv")).toFile();
    FileOutputStream pvOutputStream = new FileOutputStream(pvFile);

    try {
        Map<String, INDArray> pvs2 = Par2HierUtils.svdPCA(pvs, 2);
        Map<String, INDArray> hvs2 = Par2HierUtils.svdPCA(hvs, 2);
        String pvCSV = asStrings(pvs2, hvs2);
        IOUtils.write(pvCSV, pvOutputStream);
    } finally {
        pvOutputStream.flush();
        pvOutputStream.close();
    }
}

From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java

/**
 * Create file from resource//from  ww w  . j a  v a 2s .c om
 *
 * @param resource_path
 * @param output_path
 */
public static void createFile(String resource_path, String output_path) {
    File file = new File(output_path);
    if (!file.exists()) {
        try {
            byte[] b = Utils.getBytesFromResource(resource_path);
            file.createNewFile();
            if (b != null) {
                try (FileOutputStream fos = new FileOutputStream(file, true)) {
                    IOUtils.write(b, fos);
                    fos.close();
                }
            }
        } catch (IOException ex) {
            DCXLogger.error(Utils.class, Level.SEVERE, ex);
        }
    }
}

From source file:com.googlecode.jgenhtml.JGenHtmlUtils.java

private static void writeStreamToFileAndReplace(final InputStream in, final File targetFile, String token,
        String substitute) {/*from w ww. j  av a2s  .c o  m*/
    try {
        OutputStream out = null;
        try {
            out = new FileOutputStream(targetFile);
            if (token != null && substitute != null) {
                String input = IOUtils.toString(in);
                input = input.replace(token, substitute);
                IOUtils.write(input, out);
            } else {
                IOUtils.copy(in, out);
            }
        } finally {
            if (out != null) {
                out.close();
            }
            in.close();
        }
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage());
    }
}