Java Code Examples for javax.ws.rs.core.StreamingOutput#write()

The following examples show how to use javax.ws.rs.core.StreamingOutput#write() . 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
Source File: SupportUtil.java    From syndesis with Apache License 2.0 6 votes vote down vote up
protected void addSource(String integrationName, String integrationId, ZipOutputStream os) throws IOException {
    StreamingOutput export = integrationSupportHandler.export(Arrays.asList(integrationId));
    ZipEntry ze = new ZipEntry(integrationName + ".src.zip");
    os.putNextEntry(ze);
    File file = null;
    try {
        file = File.createTempFile(integrationName, ".src.zip");
        export.write(FileUtils.openOutputStream(file));
        FileUtils.copyFile(file, os);
        os.closeEntry();
    } finally {
        if (file != null && !file.delete()) {
            file.deleteOnExit();
        }
    }

}
 
Example 2
Source File: FunctionApiV2ResourceTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testDownloadFunctionFile() throws Exception {
    URL fileUrl = getClass().getClassLoader().getResource("test_worker_config.yml");
    File file = Paths.get(fileUrl.toURI()).toFile();
    String fileLocation = file.getAbsolutePath();
    String testDir = FunctionApiV2ResourceTest.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    FunctionsImplV2 function = new FunctionsImplV2(() -> mockedWorkerService);
    StreamingOutput streamOutput = (StreamingOutput) function.downloadFunction("file://" + fileLocation, null).getEntity();
    File pkgFile = new File(testDir, UUID.randomUUID().toString());
    OutputStream output = new FileOutputStream(pkgFile);
    streamOutput.write(output);
    Assert.assertTrue(pkgFile.exists());
    if (pkgFile.exists()) {
        pkgFile.delete();
    }
}
 
Example 3
Source File: FunctionApiV3ResourceTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testDownloadFunctionHttpUrl() throws Exception {
    String jarHttpUrl = "https://repo1.maven.org/maven2/org/apache/pulsar/pulsar-common/2.4.2/pulsar-common-2.4.2.jar";
    String testDir = FunctionApiV3ResourceTest.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    WorkerService worker = mock(WorkerService.class);
    doReturn(true).when(worker).isInitialized();
    WorkerConfig config = mock(WorkerConfig.class);
    when(config.isAuthorizationEnabled()).thenReturn(false);
    when(worker.getWorkerConfig()).thenReturn(config);
    FunctionsImpl function = new FunctionsImpl(()-> worker);
    StreamingOutput streamOutput = function.downloadFunction(jarHttpUrl, null, null);
    File pkgFile = new File(testDir, UUID.randomUUID().toString());
    OutputStream output = new FileOutputStream(pkgFile);
    streamOutput.write(output);
    Assert.assertTrue(pkgFile.exists());
    if (pkgFile.exists()) {
        pkgFile.delete();
    }
}
 
Example 4
Source File: FunctionApiV3ResourceTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testDownloadFunctionFile() throws Exception {
    URL fileUrl = getClass().getClassLoader().getResource("test_worker_config.yml");
    File file = Paths.get(fileUrl.toURI()).toFile();
    String fileLocation = file.getAbsolutePath();
    String testDir = FunctionApiV3ResourceTest.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    WorkerService worker = mock(WorkerService.class);
    doReturn(true).when(worker).isInitialized();
    WorkerConfig config = mock(WorkerConfig.class);
    when(config.isAuthorizationEnabled()).thenReturn(false);
    when(worker.getWorkerConfig()).thenReturn(config);
    FunctionsImpl function = new FunctionsImpl(() -> worker);
    StreamingOutput streamOutput = function.downloadFunction("file://" + fileLocation, null, null);
    File pkgFile = new File(testDir, UUID.randomUUID().toString());
    OutputStream output = new FileOutputStream(pkgFile);
    streamOutput.write(output);
    Assert.assertTrue(pkgFile.exists());
    if (pkgFile.exists()) {
        pkgFile.delete();
    }
}
 
Example 5
Source File: BufferedStreamingOutputTest.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void write() throws IOException {

    String testSentence = "robe";
    ByteArrayInputStream inputStream = new ByteArrayInputStream(testSentence.getBytes("UTF-8"));
    File file = Files.writeToTemp(inputStream);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
    StreamingOutput stream = new BufferedStreamingOutput(bufferedInputStream, 5);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    stream.write(outputStream);
    Assert.assertTrue(outputStream.size() == 4);


    bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
    stream = new BufferedStreamingOutput(bufferedInputStream, 3);

    outputStream = new ByteArrayOutputStream();
    stream.write(outputStream);
    Assert.assertTrue(outputStream.size() == 4);

}
 
Example 6
Source File: ConnectorHandlerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void connectorIconShouldHaveCorrectContentType() throws IOException {
    try (MockWebServer mockWebServer = new MockWebServer(); final Buffer resultBuffer = new Buffer()) {
        mockWebServer.start();

        resultBuffer.writeAll(Okio.source(getClass().getResourceAsStream("test-image.png")));

        mockWebServer.enqueue(new MockResponse().setHeader(CONTENT_TYPE, "image/png").setBody(resultBuffer));

        final Connector connector = new Connector.Builder().id("connector-id").icon(mockWebServer.url("/u/23079786").toString())
            .build();
        when(dataManager.fetch(Connector.class, "connector-id")).thenReturn(connector);
        when(dataManager.fetchAll(Integration.class)).thenReturn(ListResult.of(Collections.emptyList()));

        final Response response = handler.getConnectorIcon("connector-id").get();

        assertThat(response.getStatusInfo()).as("Wrong status code").isEqualTo(Response.Status.OK);
        assertThat(response.getHeaderString(CONTENT_TYPE)).as("Wrong content type").isEqualTo("image/png");
        assertThat(response.getHeaderString(CONTENT_LENGTH)).as("Wrong content length").isEqualTo("2018");

        final StreamingOutput so = (StreamingOutput) response.getEntity();
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (BufferedSink sink = Okio.buffer(Okio.sink(bos)); BufferedSource source = new Buffer();
             ImageInputStream iis = ImageIO.createImageInputStream(source.inputStream());) {
            so.write(sink.outputStream());
            source.readAll(sink);
            final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
            if (readers.hasNext()) {
                final ImageReader reader = readers.next();
                try {
                    reader.setInput(iis);
                    assertThat(reader.getHeight(0)).as("Wrong image height").isEqualTo(106d);
                    assertThat(reader.getWidth(0)).as("Wrong image width").isEqualTo(106d);
                } finally {
                    reader.dispose();
                }
            }
        }
    }
}
 
Example 7
Source File: FunctionApiV2ResourceTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testDownloadFunctionHttpUrl() throws Exception {
    String jarHttpUrl = "https://repo1.maven.org/maven2/org/apache/pulsar/pulsar-common/2.4.2/pulsar-common-2.4.2.jar";
    String testDir = FunctionApiV2ResourceTest.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    FunctionsImplV2 function = new FunctionsImplV2(() -> mockedWorkerService);
    StreamingOutput streamOutput = (StreamingOutput) function.downloadFunction(jarHttpUrl, null).getEntity();
    File pkgFile = new File(testDir, UUID.randomUUID().toString());
    OutputStream output = new FileOutputStream(pkgFile);
    streamOutput.write(output);
    Assert.assertTrue(pkgFile.exists());
    if (pkgFile.exists()) {
        pkgFile.delete();
    }
}
 
Example 8
Source File: BinaryDataProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testReadFrom() throws Exception {
    MessageBodyReader p = new BinaryDataProvider();
    byte[] bytes = (byte[])p.readFrom(byte[].class, byte[].class, new Annotation[]{},
                                      MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                      new MetadataMap<String, Object>(),
                                      new ByteArrayInputStream("hi".getBytes()));
    assertArrayEquals(new String("hi").getBytes(), bytes);

    InputStream is = (InputStream)p.readFrom(InputStream.class, InputStream.class, new Annotation[]{},
                                             MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                             new MetadataMap<String, Object>(),
        new ByteArrayInputStream("hi".getBytes()));
    bytes = IOUtils.readBytesFromStream(is);
    assertArrayEquals(new String("hi").getBytes(), bytes);

    Reader r = (Reader)p.readFrom(Reader.class, Reader.class, new Annotation[]{},
                                  MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                  new MetadataMap<String, Object>(),
                                  new ByteArrayInputStream("hi".getBytes()));
    assertEquals(IOUtils.toString(r), "hi");

    StreamingOutput so = (StreamingOutput)p.readFrom(StreamingOutput.class, StreamingOutput.class,
                                  new Annotation[]{},
                                  MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                  new MetadataMap<String, Object>(),
                                  new ByteArrayInputStream("hi".getBytes()));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    so.write(baos);
    bytes = baos.toByteArray();
    assertArrayEquals(new String("hi").getBytes(), bytes);
}
 
Example 9
Source File: StreamOutputEntityProvider.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void writeTo(StreamingOutput streamingOutput,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException {
    streamingOutput.write(entityStream);
}
 
Example 10
Source File: BulkExtractTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSampleExtract() throws Exception {
    injector.setEducatorContext();

    ResponseImpl res = (ResponseImpl) bulkExtract.get(req);
    assertEquals(200, res.getStatus());
    MultivaluedMap<String, Object> headers = res.getMetadata();
    assertNotNull(headers);
    assertTrue(headers.containsKey("content-disposition"));
    assertTrue(headers.containsKey("last-modified"));
    String header = (String) headers.getFirst("content-disposition");
    assertNotNull(header);
    assertTrue(header.startsWith("attachment"));
    assertTrue(header.indexOf("sample-extract.tar") > 0);

    Object entity = res.getEntity();
    assertNotNull(entity);
    StreamingOutput out = (StreamingOutput) entity;
    File file = new File("out.zip");
    FileOutputStream os = new FileOutputStream(file);
    out.write(os);
    os.flush();
    assertTrue(file.exists());

    assertEquals(798669192L, FileUtils.checksumCRC32(file));
    FileUtils.deleteQuietly(file);
}
 
Example 11
Source File: BulkExtractTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetExtractResponse() throws Exception {
    injector.setOauthAuthenticationWithEducationRole();
    mockApplicationEntity();
    mockBulkExtractEntity(null);

    HttpRequestContext context = new HttpRequestContextAdapter() {
        @Override
        public String getMethod() {
            return "GET";
        }
    };

    Response res = bulkExtract.getEdOrgExtractResponse(context, null, null);
    assertEquals(200, res.getStatus());
    MultivaluedMap<String, Object> headers = res.getMetadata();
    assertNotNull(headers);
    assertTrue(headers.containsKey("content-disposition"));
    assertTrue(headers.containsKey("last-modified"));
    String header = (String) headers.getFirst("content-disposition");
    assertNotNull(header);
    assertTrue(header.startsWith("attachment"));
    assertTrue(header.indexOf(INPUT_FILE_NAME) > 0);

    Object entity = res.getEntity();
    assertNotNull(entity);

    StreamingOutput out = (StreamingOutput) entity;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    out.write(os);
    os.flush();
    byte[] responseData = os.toByteArray();
    String s = new String(responseData);

    assertEquals(BULK_DATA, s);
}
 
Example 12
Source File: BulkExtractTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testEdOrgFullExtract() throws IOException, ParseException {
    injector.setOauthAuthenticationWithEducationRole();
    mockApplicationEntity();
    Entity mockedEntity = mockBulkExtractEntity(null);
    Mockito.when(edOrgHelper.byId(eq("ONE"))).thenReturn(mockedEntity);

    Map<String, Object> authBody = new HashMap<String, Object>();
    authBody.put("applicationId", "App1");
    authBody.put(ApplicationAuthorizationResource.EDORG_IDS, ApplicationAuthorizationResourceTest.getAuthList("ONE"));
    Entity mockAppAuth = Mockito.mock(Entity.class);
    Mockito.when(mockAppAuth.getBody()).thenReturn(authBody);
    Mockito.when(mockMongoEntityRepository.findOne(eq("applicationAuthorization"), Mockito.any(NeutralQuery.class)))
            .thenReturn(mockAppAuth);

    Response res = bulkExtract.getEdOrgExtract(CONTEXT, req, "ONE");

    assertEquals(200, res.getStatus());
    MultivaluedMap<String, Object> headers = res.getMetadata();
    assertNotNull(headers);
    assertTrue(headers.containsKey("content-disposition"));
    assertTrue(headers.containsKey("last-modified"));
    String header = (String) headers.getFirst("content-disposition");
    assertNotNull(header);
    assertTrue(header.startsWith("attachment"));
    assertTrue(header.indexOf(INPUT_FILE_NAME) > 0);

    Object entity = res.getEntity();
    assertNotNull(entity);

    StreamingOutput out = (StreamingOutput) entity;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    out.write(os);
    os.flush();
    byte[] responseData = os.toByteArray();
    String s = new String(responseData);

    assertEquals(BULK_DATA, s);
}
 
Example 13
Source File: BulkExtractTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublicExtract() throws IOException, ParseException {
    injector.setOauthAuthenticationWithEducationRole();
    mockApplicationEntity();
    Entity mockedEntity = mockBulkExtractEntity(null);
    Mockito.when(edOrgHelper.byId(eq("ONE"))).thenReturn(mockedEntity);

    Response res = bulkExtract.getPublicExtract(CONTEXT, req);

    assertEquals(200, res.getStatus());
    MultivaluedMap<String, Object> headers = res.getMetadata();
    assertNotNull(headers);
    assertTrue(headers.containsKey("content-disposition"));
    assertTrue(headers.containsKey("last-modified"));
    String header = (String) headers.getFirst("content-disposition");
    assertNotNull(header);
    assertTrue(header.startsWith("attachment"));
    assertTrue(header.indexOf(INPUT_FILE_NAME) > 0);

    Object entity = res.getEntity();
    assertNotNull(entity);

    StreamingOutput out = (StreamingOutput) entity;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    out.write(os);
    os.flush();
    byte[] responseData = os.toByteArray();
    String s = new String(responseData);

    assertEquals(BULK_DATA, s);
}