Example usage for org.apache.commons.io.output NullOutputStream nullOutputStream

List of usage examples for org.apache.commons.io.output NullOutputStream nullOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.output NullOutputStream nullOutputStream.

Prototype

public static OutputStream nullOutputStream() 

Source Link

Document

Returns a new OutputStream which discards all bytes.

Usage

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImplTest.java

/**
 * Test method for {@link de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImpl#importAttributes(java.io.InputStream, java.io.PrintWriter)}.
 * @throws IOException if the test Excel file will be not found
 *//* ww w.  j a  v a  2s. com*/
@Test
public void testImportAttributesText() throws IOException {
    PrintWriter logWriter = new PrintWriter(new NullOutputStream());
    Resource excel = new ClassPathResource(EXCEL_TEST_FILES + "textAttributesTest.xls");

    excelAttributesImportService.importAttributes(excel.getInputStream(), logWriter);
    commit();
    beginTransaction();

    TextAT textAt1 = (TextAT) attributeTypeService.getAttributeTypeByName("TextAt1");
    assertNotNull(textAt1);
    assertEquals("TextAt1 description", textAt1.getDescription());
    assertTrue(textAt1.isMandatory());
    assertFalse(textAt1.isMultiline());

    TextAT textAt2 = (TextAT) attributeTypeService.getAttributeTypeByName("TextAt2");
    assertNotNull(textAt2);
    assertEquals("TextAt2 description", textAt2.getDescription());
    assertFalse(textAt2.isMandatory());
    assertTrue(textAt2.isMultiline());
}

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImplValuesTest.java

/**
 * Test method for {@link de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImpl#importAttributes(java.io.InputStream, java.io.PrintWriter)}.
 * @throws IOException if the test Excel file will be not found
 *//*  ww  w. j  a  v  a2 s  .c  o  m*/
@Test
public void testImportAttributesEnumValuesRenameNotExisting() throws IOException {
    AttributeTypeGroup atg = testDataHelper.createAttributeTypeGroup("testATG", "", Boolean.TRUE);
    EnumAT at = testDataHelper.createEnumAttributeType("Test", "", Boolean.FALSE, atg);

    PrintWriter logWriter = new PrintWriter(new NullOutputStream());
    Resource excel = new ClassPathResource(EXCEL_TEST_FILES + "enumAttributesValuesRenameTest.xls");

    excelAttributesImportService.importAttributes(excel.getInputStream(), logWriter);
    commit();
    beginTransaction();

    assertTrue(at.getAttributeValues().isEmpty());
}

From source file:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *//*from  www. j av a2s . com*/
private FormValidation verifySignature(final JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        final JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        final List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            final CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (final Object cert : signature.getJSONArray("certificates")) {
                final X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (final CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (final CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            final ServletContext context = Jenkins.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (final String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                final InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        final DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        final Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        final SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        final String computedDigest = new String(Base64.encode(sha1.digest()));
        final String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        final String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (final GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}

From source file:com.ontotext.s4.client.HttpClient.java

/**
* Read a response or error message from the given connection, handling any 303 redirect responses
* if <code>followRedirects</code> is true.
*///from w w w .j  a  v  a2 s  .co  m
private <T> T readResponseOrError(HttpURLConnection connection, TypeReference<T> responseType,
        boolean followRedirects) throws HttpClientException {

    InputStream stream = null;
    try {
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            return null;
        }
        String encoding = connection.getContentEncoding();
        if ("gzip".equalsIgnoreCase(encoding)) {
            stream = new GZIPInputStream(connection.getInputStream());
        } else {
            stream = connection.getInputStream();
        }

        if (responseCode < 300 || responseCode >= 400 || !followRedirects) {
            try {
                return MAPPER.readValue(stream, responseType);
            } finally {
                stream.close();
            }
        } else {
            // redirect - all redirects we care about from the S4
            // APIs are 303. We have to follow them manually to make
            // authentication work properly.
            String location = connection.getHeaderField("Location");
            // consume body
            IOUtils.copy(stream, new NullOutputStream());
            IOUtils.closeQuietly(stream);
            // follow the redirect
            return get(location, responseType);
        }
    } catch (Exception e) {
        readError(connection);
        return null; // unreachable, as readError always throws exception
    }
}

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImplTest.java

/**
 * Test method for {@link de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImpl#importAttributes(java.io.InputStream, java.io.PrintWriter)}.
 * @throws IOException if the test Excel file will be not found
 *//* w  w w.  j  av a  2  s . c o  m*/
@Test
public void testImportAttributesCreate() throws IOException {
    PrintWriter logWriter = new PrintWriter(new NullOutputStream());
    Resource excel = new ClassPathResource(EXCEL_TEST_FILES + "enumAttributesCreateTest.xls");

    excelAttributesImportService.importAttributes(excel.getInputStream(), logWriter);
    commit();
    beginTransaction();

    EnumAT enumAt = (EnumAT) attributeTypeService.getAttributeTypeByName("Test");
    assertNotNull(enumAt);
    assertEquals("Test description", enumAt.getDescription());
    assertFalse(enumAt.isMultiassignmenttype());
    assertTrue(enumAt.isMandatory());
}

From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *//*from  w  w w .j a v  a 2 s. co m*/
private FormValidation verifySignature(JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (Object cert : signature.getJSONArray("certificates")) {
                X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            ServletContext context = Hudson.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        String computedDigest = new String(Base64.encode(sha1.digest()));
        String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImplValuesTest.java

/**
 * Test method for {@link de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImpl#importAttributes(java.io.InputStream, java.io.PrintWriter)}.
 * @throws IOException if the test Excel file will be not found
 *//*w  w  w  .  j a va2s .  co m*/
@Test
public void testImportAttributesEnumValuesRenameToExisting() throws IOException {
    AttributeTypeGroup atg = testDataHelper.createAttributeTypeGroup("testATG", "", Boolean.TRUE);
    EnumAT at = testDataHelper.createEnumAttributeType("Test", "", Boolean.FALSE, atg);
    EnumAV av1 = testDataHelper.createEnumAV("testValue", "d1", at);
    EnumAV av2 = testDataHelper.createEnumAV("value", "d2", at);

    PrintWriter logWriter = new PrintWriter(new NullOutputStream());
    Resource excel = new ClassPathResource(EXCEL_TEST_FILES + "enumAttributesValuesRenameTest.xls");

    excelAttributesImportService.importAttributes(excel.getInputStream(), logWriter);
    commit();
    beginTransaction();

    List<EnumAV> attributeValues = at.getSortedAttributeValues();
    assertEquals(2, attributeValues.size());
    assertEquals(av1, attributeValues.get(0));
    assertEquals("testValue", av1.getName());
    assertEquals("d1", av1.getDescription());
    assertEquals(av2, attributeValues.get(1));
    assertEquals("value", av2.getName());
    assertEquals("d2", av2.getDescription());
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetFactory.java

private String getDigest(Path aFile, String aDigest) throws IOException {
    MessageDigest digest;/*from ww w  . java  2  s  . c  o  m*/
    try {
        digest = MessageDigest.getInstance(aDigest);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
    try (InputStream is = Files.newInputStream(aFile)) {
        DigestInputStream digestFilter = new DigestInputStream(is, digest);
        IOUtils.copy(digestFilter, new NullOutputStream());
        return new String(Hex.encodeHex(digestFilter.getMessageDigest().digest()));
    }
}

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImplTest.java

/**
 * Test method for {@link de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImpl#importAttributes(java.io.InputStream, java.io.PrintWriter)}.
 * @throws IOException if the test Excel file will be not found
 *//*from   w w w .  j  a  v  a 2s.co  m*/
@Test
public void testImportAttributesEmptyLines() throws IOException {
    PrintWriter logWriter = new PrintWriter(new NullOutputStream());
    Resource excel = new ClassPathResource(EXCEL_TEST_FILES + "enumAttributesEmptyLinesTest.xls");

    excelAttributesImportService.importAttributes(excel.getInputStream(), logWriter);
    commit();
    beginTransaction();

    EnumAT enumAt = (EnumAT) attributeTypeService.getAttributeTypeByName("Test");
    assertNotNull(enumAt);
    assertEquals("Test description", enumAt.getDescription());
    assertFalse(enumAt.isMultiassignmenttype());
    assertTrue(enumAt.isMandatory());
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Copies the entirety of an input stream to a {@link NullOutputStream}.
 * @param input stream to copy/* w  ww. ja  va 2  s.co m*/
 * @throws IOException thrown when you can't copy to nothing
 */
@SuppressWarnings("InnerAssignment")
private static void copyToTheEther(final InputStream input) throws IOException {

    try (OutputStream output = new NullOutputStream()) {
        final byte[] buffer = new byte[512];

        for (int n; -1 != (n = input.read(buffer));) {
            output.write(buffer, 0, n);
        }
    }
}