use of org.apache.commons.io.output.TeeOutputStream in project sonarlint-core by SonarSource.
the class CommandExecutor method createStreamHandler.
private ExecuteStreamHandler createStreamHandler() throws IOException {
out = new ByteArrayOutputStream();
err = new ByteArrayOutputStream();
PipedOutputStream outPiped = new PipedOutputStream();
InputStream inPiped = new PipedInputStream(outPiped);
in = outPiped;
TeeOutputStream teeOut = new TeeOutputStream(out, System.out);
TeeOutputStream teeErr = new TeeOutputStream(err, System.err);
return new PumpStreamHandler(teeOut, teeErr, inPiped);
}
use of org.apache.commons.io.output.TeeOutputStream in project grakn by graknlabs.
the class GraqlShellIT method runShell.
private ShellResponse runShell(String input, String... args) throws Exception {
args = addKeyspaceAndUriParams(args);
InputStream in = new ByteArrayInputStream(input.getBytes());
OutputStream bout = new ByteArrayOutputStream();
OutputStream berr = new ByteArrayOutputStream();
OutputStream tout = bout;
OutputStream terr = berr;
if (showStdOutAndErr) {
// Intercept stdout and stderr, but make sure it is still printed using the TeeOutputStream
tout = new TeeOutputStream(bout, System.out);
terr = new TeeOutputStream(berr, System.err);
}
PrintStream out = new PrintStream(tout);
PrintStream err = new PrintStream(terr);
Boolean success = null;
GraknConfig config = GraknConfig.create();
try {
System.setIn(in);
GraqlShellOptions options = GraqlShellOptions.create(args);
success = GraqlConsole.start(options, new GraknSessionProvider(config), historyFile, out, err);
} catch (Exception e) {
e.printStackTrace();
err.flush();
fail(berr.toString());
} finally {
resetIO();
}
out.flush();
err.flush();
assertNotNull(success);
return ShellResponse.of(bout.toString(), berr.toString(), success);
}
use of org.apache.commons.io.output.TeeOutputStream in project data-prep by Talend.
the class OptimizedExportStrategy method performOptimizedTransform.
private void performOptimizedTransform(ExportParameters parameters, OutputStream outputStream) throws IOException {
// Initial check
final OptimizedPreparationInput optimizedPreparationInput = new OptimizedPreparationInput(parameters).invoke();
if (optimizedPreparationInput == null) {
throw new IllegalStateException("Unable to use this strategy (call accept() before calling this).");
}
final String preparationId = parameters.getPreparationId();
final String dataSetId = optimizedPreparationInput.getDataSetId();
final TransformationCacheKey transformationCacheKey = optimizedPreparationInput.getTransformationCacheKey();
final DataSetMetadata metadata = optimizedPreparationInput.getMetadata();
final String previousVersion = optimizedPreparationInput.getPreviousVersion();
final String version = optimizedPreparationInput.getVersion();
final ExportFormat format = getFormat(parameters.getExportType());
// Get content from previous step
try (JsonParser parser = mapper.getFactory().createParser(new InputStreamReader(contentCache.get(transformationCacheKey), UTF_8))) {
// Create dataset
final DataSet dataSet = mapper.readerFor(DataSet.class).readValue(parser);
dataSet.setMetadata(metadata);
// get the actions to apply (no preparation ==> dataset export ==> no actions)
final String actions = getActions(preparationId, previousVersion, version);
final PreparationMessage preparation = getPreparation(preparationId);
preparation.setSteps(getMatchingSteps(preparation.getSteps(), previousVersion, version));
LOGGER.debug("Running optimized strategy for preparation {} @ step #{}", preparationId, version);
// create tee to broadcast to cache + service output
final TransformationCacheKey key = //
cacheKeyGenerator.generateContentKey(//
dataSetId, //
preparationId, //
version, //
parameters.getExportType(), //
parameters.getFrom(), //
parameters.getArguments(), //
parameters.getFilter());
LOGGER.debug("Cache key: " + key.getKey());
LOGGER.debug("Cache key details: " + key.toString());
try (final TeeOutputStream tee = new TeeOutputStream(outputStream, contentCache.put(key, ContentCache.TimeToLive.DEFAULT))) {
final Configuration configuration = //
Configuration.builder().args(//
parameters.getArguments()).outFilter(//
rm -> filterService.build(parameters.getFilter(), rm)).sourceType(parameters.getFrom()).format(//
format.getName()).actions(//
actions).preparation(//
preparation).stepId(//
version).volume(//
Configuration.Volume.SMALL).output(//
tee).limit(//
limit).build();
factory.get(configuration).buildExecutable(dataSet, configuration).execute();
tee.flush();
} catch (Throwable e) {
// NOSONAR
contentCache.evict(key);
throw e;
}
} catch (TDPException e) {
throw e;
} catch (Exception e) {
throw new TDPException(TransformationErrorCodes.UNABLE_TO_TRANSFORM_DATASET, e);
}
}
use of org.apache.commons.io.output.TeeOutputStream in project tutorials by eugenp.
the class CommonsIOUnitTest method whenUsingTeeInputOutputStream_thenWriteto2OutputStreams.
@SuppressWarnings("resource")
@Test
public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() throws IOException {
final String str = "Hello World.";
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]);
Assert.assertEquals(str, String.valueOf(outputStream1));
Assert.assertEquals(str, String.valueOf(outputStream2));
}
use of org.apache.commons.io.output.TeeOutputStream in project hudson-2.x by hudson.
the class UpdateSite method verifySignature.
/**
* Verifies the signature in the update center data file.
*/
private boolean verifySignature(JSONObject o) throws GeneralSecurityException, IOException {
JSONObject signature = o.getJSONObject("signature");
if (signature.isNullObject()) {
LOGGER.severe("No signature block found");
return false;
}
o.remove("signature");
List<X509Certificate> certs = new ArrayList<X509Certificate>();
{
// load and verify certificates
CertificateFactory cf = CertificateFactory.getInstance("X509");
for (Object cert : o.getJSONArray("certificates")) {
X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
c.checkValidity();
certs.add(c);
}
// all default root CAs in JVM are trusted, plus certs bundled in Hudson
Set<TrustAnchor> anchors = CertificateUtil.getDefaultRootCAs();
ServletContext context = Hudson.getInstance().servletContext;
for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
// skip text files that are meant to be documentation
if (cert.endsWith(".txt"))
continue;
anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(context.getResourceAsStream(cert)), null));
}
CertificateUtil.validatePath(certs);
}
// 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);
JSONCanonicalUtils.write(o, new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8"));
// 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.getString("digest");
if (!computedDigest.equalsIgnoreCase(providedDigest)) {
LOGGER.severe("Digest mismatch: " + computedDigest + " vs " + providedDigest);
return false;
}
if (!sig.verify(Base64.decode(signature.getString("signature").toCharArray()))) {
LOGGER.severe("Signature in the update center doesn't match with the certificate");
return false;
}
return true;
}
Aggregations