@Override public void fileTransferRequest(FileTransferRequest request) { final IncomingFileTransfer transfer = request.accept(); Thread transferThread = new Thread(new Runnable() { public void run() { try { OutputStream os = new NullOutputStream(); InputStream is = transfer.recieveFile(); log.debug("Reading from stream: " + is.available()); IOUtils.copy(is, os); log.debug("Left in stream: " + is.available()); } catch (Exception e) { log.error("Failed incoming file transfer", e); } } }); transferThread.start(); }
@Test public void testDownloadGzip() throws Exception { final Host host = new Host(new SwiftProtocol(), "identity.api.rackspacecloud.com", new Credentials( System.getProperties().getProperty("rackspace.key"), System.getProperties().getProperty("rackspace.secret") )); final SwiftSession session = new SwiftSession(host); session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final TransferStatus status = new TransferStatus(); status.setLength(182L); final Path container = new Path(".ACCESS_LOGS", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("DFW"); final SwiftRegionService regionService = new SwiftRegionService(session); final InputStream in = new SwiftReadFeature(session, regionService).read(new Path(container, "/cdn.cyberduck.ch/2015/03/01/10/3b1d6998c430d58dace0c16e58aaf925.log.gz", EnumSet.of(Path.Type.file)), status, new DisabledConnectionCallback()); assertNotNull(in); new StreamCopier(status, status).transfer(in, new NullOutputStream()); assertEquals(182L, status.getOffset()); assertEquals(182L, status.getLength()); in.close(); session.close(); }
@Test public void testDownloadGzip() throws Exception { final Host host = new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials( System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret") )); final S3Session session = new S3Session(host); session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final int length = 1457; final byte[] content = RandomUtils.nextBytes(length); final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final TransferStatus status = new TransferStatus().length(content.length); status.setChecksum(new SHA256ChecksumCompute().compute(new ByteArrayInputStream(content), status)); final OutputStream out = new S3WriteFeature(session).write(file, status, new DisabledConnectionCallback()); new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out); out.close(); final InputStream in = new S3ReadFeature(session).read(file, status, new DisabledConnectionCallback()); assertNotNull(in); new StreamCopier(status, status).transfer(in, new NullOutputStream()); assertEquals(content.length, status.getOffset()); assertEquals(content.length, status.getLength()); in.close(); new S3DefaultDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); session.close(); }
@Test public void shouldRejectMissingEnv() { Map<String, String> requiredEnv = new HashMap<>(); requiredEnv.put("FN_PATH", "/route"); requiredEnv.put("FN_METHOD", "GET"); requiredEnv.put("FN_APP_NAME", "app_name"); requiredEnv.put("FN_REQUEST_URL", "http://test.com/fn/tryInvoke"); for (String key : requiredEnv.keySet()) { Map<String, String> newEnv = new HashMap<>(requiredEnv); newEnv.remove(key); DefaultEventCodec codec = new DefaultEventCodec(newEnv, asStream("input"), new NullOutputStream()); try{ codec.readEvent(); fail("Should have rejected missing env "+ key); }catch(FunctionInputHandlingException e){ assertThat(e).hasMessageContaining("Required environment variable " + key+ " is not set - are you running a function outside of fn run?"); } } }
public MediniQVTFamiliesToPersonsConfig() { super(new FamiliesComparator(), new PersonsComparator()); logger = new OutputStreamLog(new PrintStream(new NullOutputStream())); // logger = new OutputStreamLog(System.err); processorImpl = new EMFQvtProcessorImpl(this.logger); processorImpl.setProperty(QVTProcessorConsts.PROP_DEBUG, "true"); basePath = "./src/org/benchmarx/examples/familiestopersons/implementations/medini/base/"; // Tell the QVT engine, which transformation to execute transformation = "families2personsconfig"; // Tell the QVT engine a directory to work in - e.g. to store the trace (meta)models File tracesFile = new File(basePath + "traces/trace.trafo"); tracesFile.delete(); }
/** * launch the transformation in the QVT execution engine * * @param direction : the desired execution direction */ public void launch(String direction) { PrintStream ps = System.out; PrintStream ps_err = System.err; // Load the QVT relations try { System.setOut(new PrintStream(new NullOutputStream())); System.setErr(new PrintStream(new NullOutputStream())); qvtRuleSet = new FileReader(basePath + RULESET); this.transform(qvtRuleSet, transformation, direction); } catch (FileNotFoundException fileNotFoundException) { fileNotFoundException.printStackTrace(); return; } catch (Throwable throwable) { throwable.printStackTrace(); } finally { System.setOut(ps); System.setErr(ps_err); } }
public MediniQVTFamiliesToPersons() { super(new FamiliesComparator(), new PersonsComparator()); logger = new OutputStreamLog(new PrintStream(new NullOutputStream())); // logger = new OutputStreamLog(System.err); processorImpl = new EMFQvtProcessorImpl(this.logger); processorImpl.setProperty(QVTProcessorConsts.PROP_DEBUG, "true"); basePath = "./src/org/benchmarx/examples/familiestopersons/implementations/medini/base/"; // Tell the QVT engine, which transformation to execute transformation = "families2persons"; // Tell the QVT engine a directory to work in - e.g. to store the trace (meta)models File tracesFile = new File(basePath + "traces/trace.trafo"); tracesFile.delete(); }
/** * launch the transformation in the QVT execution engine * * @param direction : the desired execution direction */ public void launch(String direction) { PrintStream ps = System.out; PrintStream ps_err = System.err; // Load the QVT relations try { System.setOut(new PrintStream(new NullOutputStream())); System.setErr(new PrintStream(new NullOutputStream())); qvtRuleSet = new FileReader(basePath + RULESET); this.transform(qvtRuleSet, transformation, direction); } catch (FileNotFoundException fileNotFoundException) { fileNotFoundException.printStackTrace(); return; } catch (Throwable throwable) { throwable.printStackTrace(); System.out.println(throwable.getMessage()); } finally { System.setOut(ps); System.setErr(ps_err); } }
/** * Custom serialization method. * * @param oos the object output stream * @throws IOException */ protected void writeObject(ObjectOutputStream oos) throws IOException { // figure out size of the written network CountingOutputStream cos = new CountingOutputStream(new NullOutputStream()); if (replaceMissingFilter != null) { ModelSerializer.writeModel(model, cos, false); } modelSize = cos.getByteCount(); // default serialization oos.defaultWriteObject(); // actually write the network if (replaceMissingFilter != null) { ModelSerializer.writeModel(model, oos, false); } }
/** * Demonstrates idiomatic exception handling with try-with-resources * * @throws Exception if something exceptional happens */ @Test public void testIdiomaticInvokationThrowsException() throws Exception { final InputStream mockBody = mock(InputStream.class); final IOException ioe = new IOException("Mocked IOE"); when(mockBody.read(any(byte[].class))).thenThrow(ioe); final FcrepoClient client = mock(FcrepoClient.class); final GetBuilder getBuilder = mock(GetBuilder.class); when(client.get(any(URI.class))).thenReturn(getBuilder); when(getBuilder.perform()).thenReturn(new FcrepoResponse(null, 200, null, mockBody)); try (FcrepoResponse res = client.get(URI.create("foo")).perform()) { ByteStreams.copy(res.getBody(), NullOutputStream.NULL_OUTPUT_STREAM); fail("Expected an IOException to be thrown."); } catch (IOException e) { assertSame(ioe, e); } verify(mockBody).close(); }
@Test public void workflowBundle() throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); // To test that seeAlso URIs are stored serializer.workflowDoc(new NullOutputStream(), workflowBundle.getMainWorkflow(), URI.create(HELLOWORLD_RDF)); serializer.profileDoc(new NullOutputStream(), workflowBundle.getProfiles().getByName("tavernaWorkbench"), URI.create(TAVERNAWORKBENCH_RDF)); serializer.profileDoc(new NullOutputStream(), workflowBundle.getProfiles().getByName("tavernaServer"), URI.create(TAVERNASERVER_RDF)); serializer.workflowBundleDoc(outStream, URI.create("workflowBundle.rdf")); //System.out.write(outStream.toByteArray()); Document doc = parseXml(outStream); Element root = doc.getRootElement(); checkRoot(root); checkWorkflowBundleDocument(root); }
public void prepareFileEntry(RmpFileEntry entry) throws IOException, InterruptedException { EntryInfo info = new EntryInfo(); info.name = entry.getFileName(); info.extendsion = entry.getFileExtension(); long pos = rmpOutputFile.getFilePointer(); info.offset = pos; CountingOutputStream cout = new CountingOutputStream(new NullOutputStream()); entry.writeFileContent(cout); info.length = cout.getBytesWritten(); long newPos = pos + info.length; if ((info.length % 2) != 0) newPos++; if (newPos > MAX_FILE_SIZE) throwRmpTooLarge(); rmpOutputFile.seek(newPos); entries.add(info); log.debug("Prepared data of entry " + entry + " bytes=" + info.length); }
/** * Gets a map of unsafe result elements, ie. elements that cannot be saved * because serialization fails. * * @return */ public Map<ComponentJob, AnalyzerResult> getUnsafeResultElements() { if (_unsafeResultElements == null) { _unsafeResultElements = new LinkedHashMap<>(); final Map<ComponentJob, AnalyzerResult> resultMap = _analysisResult.getResultMap(); for (final Entry<ComponentJob, AnalyzerResult> entry : resultMap.entrySet()) { final AnalyzerResult analyzerResult = entry.getValue(); try { SerializationUtils.serialize(analyzerResult, new NullOutputStream()); } catch (final SerializationException e) { _unsafeResultElements.put(entry.getKey(), analyzerResult); } } } return _unsafeResultElements; }
@Test public void prettyPrint() throws Exception { // given final String version = versionService.version().getVersionId(); final List<Action> actions = getSimpleAction("uppercase", "column_name", "lastname"); final PreparationActions newContent = new PreparationActions(actions, version); final Step step = new Step(Step.ROOT_STEP.id(), newContent.id(), version); final Preparation preparation = new Preparation("#15325878", "1234", step.id(), version); repository.add(newContent); repository.add(step); repository.add(preparation); // when PreparationUtils.prettyPrint(repository, preparation, new NullOutputStream()); // Basic walk through code, no assert. }
/** * Add the following preparation in cache. * * @param preparation the preparation to cache. * @param stepId the preparation step id. */ private void addPreparationInCache(Preparation preparation, String stepId) { final ExportParameters exportParameters = new ExportParameters(); exportParameters.setPreparationId(preparation.getId()); exportParameters.setExportType("JSON"); exportParameters.setStepId(stepId); exportParameters.setDatasetId(preparation.getDataSetId()); final StreamingResponseBody streamingResponseBody = executeSampleExportStrategy(exportParameters); try { // the result is not important here as it will be cached ! streamingResponseBody.writeTo(new NullOutputStream()); } catch (IOException e) { throw new TDPException(UNEXPECTED_EXCEPTION, e); } }
@Test public void shouldUsedVersionedPreparation() throws IOException { // Given final ExportParameters parameters = new ExportParameters(); parameters.setExportType("JSON"); parameters.setPreparationId("prep-1234"); parameters.setStepId("step-1234"); final Preparation preparation = new Preparation(); preparation.setId("prep-1234"); preparation.setHeadId("step-1234"); configurePreparation(preparation, "prep-1234", "step-1234"); // When final StreamingResponseBody body = strategy.execute(parameters); body.writeTo(new NullOutputStream()); // Then final ArgumentCaptor<Configuration> captor = ArgumentCaptor.forClass(Configuration.class); verify(transformer).buildExecutable(any(), captor.capture()); assertEquals("prep-1234", captor.getValue().getPreparationId()); assertEquals("step-1234", captor.getValue().getPreparation().getHeadId()); }
@Test public void shouldUsedHeadPreparation() throws IOException { // Given final ExportParameters parameters = new ExportParameters(); parameters.setExportType("JSON"); parameters.setPreparationId("prep-1234"); parameters.setStepId("head"); final Preparation preparation = new Preparation(); preparation.setId("prep-1234"); preparation.setHeadId("head"); configurePreparation(preparation, "prep-1234", "head"); // When final StreamingResponseBody body = strategy.execute(parameters); body.writeTo(new NullOutputStream()); // Then final ArgumentCaptor<Configuration> captor = ArgumentCaptor.forClass(Configuration.class); verify(transformer).buildExecutable(any(), captor.capture()); assertEquals("prep-1234", captor.getValue().getPreparationId()); assertEquals("head", captor.getValue().getPreparation().getHeadId()); }
public void loopAllEntitiesAndProperties() throws IOException { NullOutputStream nullOutputStream = new NullOutputStream(); List<Person> listOfPersons = Service.getListOfPersons(100 * 1000); long currentTimeMillis = System.currentTimeMillis(); ListContainer<Person> listContainer = new ListContainer<>( listOfPersons); Collection<?> ids = listContainer.getContainerPropertyIds(); for (int i = 0; i < listContainer.size(); i++) { Item item = listContainer.getItem(listOfPersons.get(i)); for (Object propertyId : ids) { Property itemProperty = item.getItemProperty(propertyId); final Object value = itemProperty.getValue(); nullOutputStream.write(value.toString().getBytes()); LOG.log(Level.FINEST, "Property: %s", value); } } LOG. log(Level.INFO, "Looping all properties in 100 000 Items took {0}ms", (System.currentTimeMillis() - currentTimeMillis)); }
public void loopAllEntitiesAndPropertiesWithBeanItemContainer() throws IOException { NullOutputStream nullOutputStream = new NullOutputStream(); List<Person> listOfPersons = Service.getListOfPersons(100 * 1000); long currentTimeMillis = System.currentTimeMillis(); BeanItemContainer<Person> c = new BeanItemContainer<>( Person.class, listOfPersons); Collection<?> ids = c.getContainerPropertyIds(); for (int i = 0; i < c.size(); i++) { Item item = c.getItem(listOfPersons.get(i)); for (Object propertyId : ids) { Property itemProperty = item.getItemProperty(propertyId); final Object value = itemProperty.getValue(); nullOutputStream.write(value.toString().getBytes()); LOG.log(Level.FINEST, "Property: %s", value); } } // ~ 350ms in 1.34, MacBook Pro (Retina, Mid 2012) 2.3Gz i7 // ~ + 3-10ms in 1.35, when changing ListContainer to use PropertyUtils instead of WrapDynaBean LOG. log(Level.INFO, "BIC from core: Looping all properties in 100 000 Items took {0}ms", (System.currentTimeMillis() - currentTimeMillis)); }
@Test public void testOutputStreamBigDataBigChunks() { // don't run if the JVM doesn't have enough memory Assume.assumeTrue("testOutputStreamBigDataBigChunks: JVM has enough memory (~4GB)", Runtime.getRuntime().maxMemory() > 4e9); final int dataSize = (Integer.MAX_VALUE - 8) /*=max array size*/ - 5 /*=array header size*/; byte[] data = new byte[dataSize - 1]; AutoBuffer ab = new AutoBuffer(NullOutputStream.NULL_OUTPUT_STREAM, false); // make sure the buffer can take the full array ab.putA1(data); // now try to stream 1TB of data through the buffer for (int i = 0; i < 512; i++) { if (i % 10 == 0) System.out.println(i); ab.putA1(data); } ab.close(); }
public static void main(String[] args) throws Exception { final String strtoken = args[0]; final String contents = makeString(FILE_SIZE); final AuthToken token = AuthService.validateToken(strtoken); final BasicShockClient bsc = new BasicShockClient(new URL(SHOCK_URL), token); final byte[] conbytes = contents.getBytes(); final List<String> ids = new LinkedList<>(); final long presave = System.nanoTime(); for (int i = 0; i < COUNT; i++) { final ByteArrayInputStream bais = new ByteArrayInputStream(conbytes); final ShockNode node = bsc.addNode(bais, "foo", "text"); ids.add(node.getId().getId()); } double elapsed = printElapse("shock load", presave); System.out.println((elapsed / COUNT) + " sec / node"); final long preget = System.nanoTime(); for (final String id: ids) { bsc.getFile(new ShockNodeId(id), new NullOutputStream()); } elapsed = printElapse("shock get", preget); System.out.println((elapsed / COUNT) + " sec / node"); }
private static int[] computeTrailerSizeByVersion() { int versionToSize[] = new int[HFile.MAX_FORMAT_VERSION + 1]; for (int version = HFile.MIN_FORMAT_VERSION; version <= HFile.MAX_FORMAT_VERSION; ++version) { FixedFileTrailer fft = new FixedFileTrailer(version, HFileBlock.MINOR_VERSION_NO_CHECKSUM); DataOutputStream dos = new DataOutputStream(NullOutputStream.NULL_OUTPUT_STREAM); try { fft.serialize(dos); } catch (IOException ex) { // The above has no reason to fail. throw new RuntimeException(ex); } versionToSize[version] = dos.size(); } return versionToSize; }
public com.ning.http.client.AsyncHandler.STATE onBodyPartReceived( HttpResponseBodyPart bodyPart) throws Exception { String contType = testCase.getExpectedResContentType(); if(isMatchesContentType(MediaType.APPLICATION_JSON_TYPE, contType) || isMatchesContentType(MediaType.APPLICATION_XML_TYPE, contType) || isMatchesContentType(MediaType.TEXT_PLAIN_TYPE, contType) || isMatchesContentType(MediaType.TEXT_HTML_TYPE, contType) || isMatchesContentType(MediaType.TEXT_XML_TYPE, contType)) { builder.accumulate(bodyPart); } else { bodyPart.writeTo(NullOutputStream.NULL_OUTPUT_STREAM); } testCaseReport.setResponseContentType(contType); return STATE.CONTINUE; }
private void eatMemory(int callIndex, File foFile, int replicatorRepeats) throws Exception { Source src = new StreamSource(foFile); Transformer transformer = replicatorTemplates.newTransformer(); transformer.setParameter("repeats", new Integer(replicatorRepeats)); OutputStream out = new NullOutputStream(); //write to /dev/nul try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setBaseURL(foFile.getParentFile().toURI().toURL().toExternalForm()); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); stats.notifyPagesProduced(fop.getResults().getPageCount()); if (callIndex == 0) { System.out.println(foFile.getName() + " generates " + fop.getResults().getPageCount() + " pages."); } stats.checkStats(); } finally { IOUtils.closeQuietly(out); } }
public void testWriteGiantRecord() throws IOException { PrintStream dummyStream = new PrintStream(new NullOutputStream()); ARCWriter arcWriter = new ARCWriter( SERIAL_NO, dummyStream, new File("dummy"), new WriterPoolSettingsData( "", "", -1, false, null, null)); assertNotNull(arcWriter); // Start the record with an arbitrary 14-digit date per RFC2540 long now = System.currentTimeMillis(); long recordLength = org.apache.commons.io.FileUtils.ONE_GB * 3; arcWriter.write("dummy:uri", "application/octet-stream", "0.1.2.3", now, recordLength, new NullInputStream(recordLength)); arcWriter.close(); }
public void runBeeLine(String sqlScriptFile) throws IOException { List<String> argList = new ArrayList<String>(); argList.add("-u"); argList.add(connectionURL); argList.add("-d"); argList .add(driver); argList.add("-n"); argList.add(userName); argList.add("-p"); argList.add(passWord); argList.add("-f"); argList.add(sqlScriptFile); BeeLine beeLine = new BeeLine(); if (!verbose) { beeLine.setOutputStream(new PrintStream(new NullOutputStream())); // beeLine.getOpts().setSilent(true); } // beeLine.getOpts().setAllowMultiLineCommand(false); // beeLine.getOpts().setIsolation("TRANSACTION_READ_COMMITTED"); int status = beeLine.begin(argList.toArray(new String[0]), null); if (status != 0) { throw new IOException("Schema script failed, errorcode " + status); } }
/** * @return The stream to write to after the entry signal was received. */ public OutputStream getStream() { if(null == stream) { // Nothing to write return NullOutputStream.NULL_OUTPUT_STREAM; } return stream; }
@Test(expected = IOException.class) public void testClose() throws Exception { try { new HttpResponseOutputStream<Void>(new NullOutputStream()) { @Override public Void getStatus() throws BackgroundException { throw new InteroperabilityException("d"); } }.close(); } catch(IOException e) { assertEquals("d. Please contact your web hosting service provider for assistance.", e.getMessage()); throw e; } }
@Test public void testTransferFixedLength() throws Exception { final TransferStatus status = new TransferStatus().length(432768L); new StreamCopier(status, status).withLimit(432768L).transfer(new NullInputStream(432768L), new NullOutputStream()); assertTrue(status.isComplete()); assertEquals(432768L, status.getOffset(), 0L); }
@Test public void testTransferFixedLengthIncomplete() throws Exception { final TransferStatus status = new TransferStatus().length(432768L); new StreamCopier(status, status).withLimit(432767L).transfer(new NullInputStream(432768L), new NullOutputStream()); assertEquals(432767L, status.getOffset(), 0L); assertTrue(status.isComplete()); }
@Test public void testReadNoEndofStream() throws Exception { final TransferStatus status = new TransferStatus().length(432768L); new StreamCopier(status, status).withLimit(432768L).transfer(new NullInputStream(432770L), new NullOutputStream()); assertEquals(432768L, status.getOffset(), 0L); assertTrue(status.isComplete()); }
@Test(expected = InteroperabilityException.class) public void testClose() throws Exception { new DefaultStreamCloser().close(new HttpResponseOutputStream<Void>(new NullOutputStream()) { @Override public Void getStatus() throws BackgroundException { throw new InteroperabilityException("d"); } }); }
/** * Test if the OfflineImageViewerPB can correctly parse a fsimage containing * snapshots */ @Test public void testOfflineImageViewer() throws Exception { runTestSnapshot(1); // retrieve the fsimage. Note that we already save namespace to fsimage at // the end of each iteration of runTestSnapshot. File originalFsimage = FSImageTestUtil.findLatestImageFile( FSImageTestUtil.getFSImage( cluster.getNameNode()).getStorage().getStorageDir(0)); assertNotNull("Didn't generate or can't find fsimage", originalFsimage); PrintStream o = new PrintStream(NullOutputStream.NULL_OUTPUT_STREAM); PBImageXmlWriter v = new PBImageXmlWriter(new Configuration(), o); v.visit(new RandomAccessFile(originalFsimage, "r")); }
@Test(expected = IOException.class) public void testTruncatedFSImage() throws IOException { File truncatedFile = folder.newFile(); PrintStream output = new PrintStream(NullOutputStream.NULL_OUTPUT_STREAM); copyPartOfFile(originalFsimage, truncatedFile); new FileDistributionCalculator(new Configuration(), 0, 0, output) .visit(new RandomAccessFile(truncatedFile, "r")); }
@Test public void shouldExtractBasicEvent() { Map<String, String> env = new HashMap<>(); env.put("FN_FORMAT", "default"); env.put("FN_METHOD", "GET"); env.put("FN_APP_NAME", "testapp"); env.put("FN_PATH", "/route"); env.put("FN_REQUEST_URL", "http://test.com/fn/tryInvoke"); env.put("FN_HEADER_CONTENT_TYPE", "text/plain"); env.put("FN_HEADER_ACCEPT", "text/html, text/plain;q=0.9"); env.put("FN_HEADER_ACCEPT_ENCODING", "gzip"); env.put("FN_HEADER_USER_AGENT", "userAgent"); Map<String, String> config = new HashMap<>(); config.put("configparam", "configval"); config.put("CONFIGPARAM", "CONFIGVAL"); DefaultEventCodec codec = new DefaultEventCodec(env, asStream("input"), new NullOutputStream()); InputEvent evt = codec.readEvent().get(); assertThat(evt.getMethod()).isEqualTo("GET"); assertThat(evt.getAppName()).isEqualTo("testapp"); assertThat(evt.getRoute()).isEqualTo("/route"); assertThat(evt.getRequestUrl()).isEqualTo("http://test.com/fn/tryInvoke"); assertThat(evt.getHeaders().getAll().size()).isEqualTo(4); assertThat(evt.getHeaders().getAll()).contains( headerEntry("CONTENT_TYPE", "text/plain"), headerEntry("ACCEPT_ENCODING", "gzip"), headerEntry("ACCEPT", "text/html, text/plain;q=0.9"), headerEntry("USER_AGENT", "userAgent")); evt.consumeBody((body) -> assertThat(body).hasSameContentAs(asStream("input"))); assertThat(codec.shouldContinue()).isFalse(); }
public Checksum update( InputStream stream ) throws IOException { try (DigestInputStream dig = new DigestInputStream( stream, md )) { IOUtils.copy( dig, new NullOutputStream() ); } return this; }
private void setStream() { try { stream = new PrintStream(fileCreator.getReportFile("txt", getReportStartingDate()), StandardCharsets.UTF_8.name()); } catch (IOException e) { LOG.error("Can't create simple reporter file", e); try { stream = new PrintStream(new NullOutputStream(), false, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e2) { LOG.error("UTF-8 is not supported", e2); } } }