Search in sources :

Example 71 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project winery by eclipse.

the class RestUtils method getCsarOfSelectedResource.

/**
 * @param options the set of options that are applicable for exporting a csar
 */
public static Response getCsarOfSelectedResource(final AbstractComponentInstanceResource resource, CsarExportOptions options) {
    long start = System.currentTimeMillis();
    final CsarExporter exporter = new CsarExporter(RepositoryFactory.getRepository());
    Map<String, Object> exportConfiguration = new HashMap<>();
    StreamingOutput so = output -> {
        try {
            // check which options are chosen
            if (options.isAddToProvenance()) {
                // We wait for the accountability layer to confirm the transaction
                String result = exporter.writeCsarAndSaveManifestInProvenanceLayer(resource.getId(), output).get();
                LOGGER.debug("Stored state in accountability layer in transaction " + result);
            } else if (options.isIncludeDependencies() && resource.getId() instanceof ServiceTemplateId) {
                SelfContainmentPackager packager = new SelfContainmentPackager(RepositoryFactory.getRepository());
                DefinitionsChildId selfContainedVersion = packager.createSelfContainedVersion(resource.getId());
                exporter.writeSelfContainedCsar(RepositoryFactory.getRepository(), selfContainedVersion, output, exportConfiguration);
            } else {
                exporter.writeCsar(resource.getId(), output, exportConfiguration);
            }
            long duration = (System.currentTimeMillis() - start) / 1000;
            LOGGER.debug("CSAR export lasted {} min {} s", (int) duration / 60, duration % 60);
        } catch (Exception e) {
            LOGGER.error("Error while exporting CSAR", e);
            throw new WebApplicationException(e);
        }
    };
    String contentDisposition = String.format("attachment;filename=\"%s%s\"", resource.getXmlId().getEncoded(), Constants.SUFFIX_CSAR);
    return Response.ok().header("Content-Disposition", contentDisposition).type(MimeTypes.MIMETYPE_ZIP).entity(so).build();
}
Also used : MimeTypes(org.eclipse.winery.common.constants.MimeTypes) FormDataContentDisposition(org.glassfish.jersey.media.multipart.FormDataContentDisposition) FileTime(java.nio.file.attribute.FileTime) HasType(org.eclipse.winery.model.tosca.HasType) CsarExportConfiguration(org.eclipse.winery.repository.export.CsarExportConfiguration) TRelationshipTypeImplementation(org.eclipse.winery.model.tosca.TRelationshipTypeImplementation) WineryVersion(org.eclipse.winery.common.version.WineryVersion) MediaType(javax.ws.rs.core.MediaType) IPersistable(org.eclipse.winery.repository.rest.resources._support.IPersistable) Duration(java.time.Duration) Map(java.util.Map) GenericId(org.eclipse.winery.model.ids.GenericId) QNameApiData(org.eclipse.winery.repository.rest.resources.apiData.QNameApiData) TDefinitions(org.eclipse.winery.model.tosca.TDefinitions) WineryVersionUtils(org.eclipse.winery.repository.backend.WineryVersionUtils) EdmmManager(org.eclipse.winery.edmm.EdmmManager) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) QNameWithTypeApiData(org.eclipse.winery.repository.rest.resources.apiData.QNameWithTypeApiData) Constants(org.eclipse.winery.common.Constants) Set(java.util.Set) RelationshipTypeId(org.eclipse.winery.model.ids.definitions.RelationshipTypeId) CsarExportOptions(org.eclipse.winery.repository.export.CsarExportOptions) VersionUtils(org.eclipse.winery.common.version.VersionUtils) WebApplicationException(javax.ws.rs.WebApplicationException) LocalNameForAngular(org.eclipse.winery.repository.rest.datatypes.LocalNameForAngular) UriInfo(javax.ws.rs.core.UriInfo) QName(javax.xml.namespace.QName) LocalDateTime(java.time.LocalDateTime) ArrayList(java.util.ArrayList) RelationshipTypeImplementationId(org.eclipse.winery.model.ids.definitions.RelationshipTypeImplementationId) EdmmType(org.eclipse.winery.edmm.model.EdmmType) ArtifactTemplateId(org.eclipse.winery.model.ids.definitions.ArtifactTemplateId) XmlId(org.eclipse.winery.model.ids.XmlId) DefinitionsChildId(org.eclipse.winery.model.ids.definitions.DefinitionsChildId) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) ResourceResult(org.eclipse.winery.repository.rest.resources._support.ResourceResult) StringWriter(java.io.StringWriter) IOException(java.io.IOException) Family(javax.ws.rs.core.Response.Status.Family) TArtifactTemplate(org.eclipse.winery.model.tosca.TArtifactTemplate) UiConfigurationObject(org.eclipse.winery.common.configuration.UiConfigurationObject) ModelUtilities(org.eclipse.winery.model.tosca.utils.ModelUtilities) TNodeTypeImplementation(org.eclipse.winery.model.tosca.TNodeTypeImplementation) SortedSet(java.util.SortedSet) Date(java.util.Date) EdmmConverter(org.eclipse.winery.edmm.model.EdmmConverter) LoggerFactory(org.slf4j.LoggerFactory) Namespace(org.eclipse.winery.model.ids.Namespace) ArtifactTemplatesResource(org.eclipse.winery.repository.rest.resources.entitytemplates.artifacttemplates.ArtifactTemplatesResource) ContentDisposition(org.glassfish.jersey.media.multipart.ContentDisposition) NamespaceAndDefinedLocalNamesForAngular(org.eclipse.winery.repository.rest.datatypes.NamespaceAndDefinedLocalNamesForAngular) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) SelfContainmentPackager(org.eclipse.winery.repository.backend.selfcontainmentpackager.SelfContainmentPackager) ServiceTemplateResource(org.eclipse.winery.repository.rest.resources.servicetemplates.ServiceTemplateResource) Locale(java.util.Locale) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) Util(org.eclipse.winery.repository.common.Util) URI(java.net.URI) QNameConverter(org.eclipse.winery.repository.rest.resources.apiData.converter.QNameConverter) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference) Collection(java.util.Collection) StreamingOutput(javax.ws.rs.core.StreamingOutput) TNodeType(org.eclipse.winery.model.tosca.TNodeType) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) Objects(java.util.Objects) ArtifactTemplateResource(org.eclipse.winery.repository.rest.resources.entitytemplates.artifacttemplates.ArtifactTemplateResource) List(java.util.List) NamespaceAndDefinedLocalNames(org.eclipse.winery.repository.backend.xsd.NamespaceAndDefinedLocalNames) HttpHeaders(javax.ws.rs.core.HttpHeaders) TExtensibleElements(org.eclipse.winery.model.tosca.TExtensibleElements) YamlExporter(org.eclipse.winery.repository.yaml.export.YamlExporter) Response(javax.ws.rs.core.Response) IRepository(org.eclipse.winery.repository.backend.IRepository) AccessControlException(java.security.AccessControlException) MediaTypes(org.eclipse.winery.repository.backend.constants.MediaTypes) Marshaller(javax.xml.bind.Marshaller) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) HashMap(java.util.HashMap) HashSet(java.util.HashSet) ClientBuilder(javax.ws.rs.client.ClientBuilder) TConstraint(org.eclipse.winery.model.tosca.TConstraint) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) Application(org.eclipse.winery.model.selfservice.Application) NodeTypeImplementationId(org.eclipse.winery.model.ids.definitions.NodeTypeImplementationId) Status(javax.ws.rs.core.Response.Status) JAXBContext(javax.xml.bind.JAXBContext) CsarExporter(org.eclipse.winery.repository.export.CsarExporter) ToscaExportUtil(org.eclipse.winery.repository.export.ToscaExportUtil) Logger(org.slf4j.Logger) Environments(org.eclipse.winery.common.configuration.Environments) AbstractComponentInstanceResource(org.eclipse.winery.repository.rest.resources._support.AbstractComponentInstanceResource) TTag(org.eclipse.winery.model.tosca.TTag) ToscaElementId(org.eclipse.winery.model.ids.elements.ToscaElementId) GitBasedRepository(org.eclipse.winery.repository.backend.filebased.GitBasedRepository) EntityGraph(io.github.edmm.core.parser.EntityGraph) NamespaceManager(org.eclipse.winery.repository.backend.NamespaceManager) TRelationshipType(org.eclipse.winery.model.tosca.TRelationshipType) ComponentId(org.eclipse.winery.repository.rest.datatypes.ComponentId) PolicyTemplateId(org.eclipse.winery.model.ids.definitions.PolicyTemplateId) AbstractComponentsResource(org.eclipse.winery.repository.rest.resources._support.AbstractComponentsResource) InputStream(java.io.InputStream) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) IHasName(org.eclipse.winery.repository.rest.resources._support.IHasName) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) DefinitionsChildId(org.eclipse.winery.model.ids.definitions.DefinitionsChildId) SelfContainmentPackager(org.eclipse.winery.repository.backend.selfcontainmentpackager.SelfContainmentPackager) StreamingOutput(javax.ws.rs.core.StreamingOutput) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) AccessControlException(java.security.AccessControlException) CsarExporter(org.eclipse.winery.repository.export.CsarExporter) UiConfigurationObject(org.eclipse.winery.common.configuration.UiConfigurationObject)

Example 72 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project winery by eclipse.

the class RestUtils method getDefinitionsOfSelectedResource.

/**
 * Returns the plain XML for the selected resource
 */
public static Response getDefinitionsOfSelectedResource(final AbstractComponentInstanceResource resource, final URI uri) {
    final ToscaExportUtil exporter = new ToscaExportUtil();
    StreamingOutput so = output -> {
        Map<String, Object> conf = new HashMap<>();
        conf.put(CsarExportConfiguration.REPOSITORY_URI.toString(), uri);
        try {
            exporter.writeTOSCA(RepositoryFactory.getRepository(), resource.getId(), conf, output);
        } catch (Exception e) {
            throw new WebApplicationException(e);
        }
        output.close();
    };
    /*
         * this code is for offering a download action // Browser offers save as
         * // .tosca is more or less needed for debugging, only a CSAR makes
         * sense. // Therefore, we want to have the xml opened in the browser.
         * StringBuilder sb = new StringBuilder();
         * sb.append("attachment;filename=\"");
         * sb.append(resource.getXmlId().getEncoded()); sb.append(" - ");
         * sb.append(resource.getNamespace().getEncoded()); sb.append(".xml");
         * sb.append("\""); return Response.ok().header("Content-Disposition",
         * sb
         * .toString()).type(MediaType.APPLICATION_XML_TYPE).entity(so).buildProvenanceSmartContract();
         */
    return Response.ok().type(MediaType.APPLICATION_XML).entity(so).build();
}
Also used : MimeTypes(org.eclipse.winery.common.constants.MimeTypes) FormDataContentDisposition(org.glassfish.jersey.media.multipart.FormDataContentDisposition) FileTime(java.nio.file.attribute.FileTime) HasType(org.eclipse.winery.model.tosca.HasType) CsarExportConfiguration(org.eclipse.winery.repository.export.CsarExportConfiguration) TRelationshipTypeImplementation(org.eclipse.winery.model.tosca.TRelationshipTypeImplementation) WineryVersion(org.eclipse.winery.common.version.WineryVersion) MediaType(javax.ws.rs.core.MediaType) IPersistable(org.eclipse.winery.repository.rest.resources._support.IPersistable) Duration(java.time.Duration) Map(java.util.Map) GenericId(org.eclipse.winery.model.ids.GenericId) QNameApiData(org.eclipse.winery.repository.rest.resources.apiData.QNameApiData) TDefinitions(org.eclipse.winery.model.tosca.TDefinitions) WineryVersionUtils(org.eclipse.winery.repository.backend.WineryVersionUtils) EdmmManager(org.eclipse.winery.edmm.EdmmManager) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) QNameWithTypeApiData(org.eclipse.winery.repository.rest.resources.apiData.QNameWithTypeApiData) Constants(org.eclipse.winery.common.Constants) Set(java.util.Set) RelationshipTypeId(org.eclipse.winery.model.ids.definitions.RelationshipTypeId) CsarExportOptions(org.eclipse.winery.repository.export.CsarExportOptions) VersionUtils(org.eclipse.winery.common.version.VersionUtils) WebApplicationException(javax.ws.rs.WebApplicationException) LocalNameForAngular(org.eclipse.winery.repository.rest.datatypes.LocalNameForAngular) UriInfo(javax.ws.rs.core.UriInfo) QName(javax.xml.namespace.QName) LocalDateTime(java.time.LocalDateTime) ArrayList(java.util.ArrayList) RelationshipTypeImplementationId(org.eclipse.winery.model.ids.definitions.RelationshipTypeImplementationId) EdmmType(org.eclipse.winery.edmm.model.EdmmType) ArtifactTemplateId(org.eclipse.winery.model.ids.definitions.ArtifactTemplateId) XmlId(org.eclipse.winery.model.ids.XmlId) DefinitionsChildId(org.eclipse.winery.model.ids.definitions.DefinitionsChildId) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) ResourceResult(org.eclipse.winery.repository.rest.resources._support.ResourceResult) StringWriter(java.io.StringWriter) IOException(java.io.IOException) Family(javax.ws.rs.core.Response.Status.Family) TArtifactTemplate(org.eclipse.winery.model.tosca.TArtifactTemplate) UiConfigurationObject(org.eclipse.winery.common.configuration.UiConfigurationObject) ModelUtilities(org.eclipse.winery.model.tosca.utils.ModelUtilities) TNodeTypeImplementation(org.eclipse.winery.model.tosca.TNodeTypeImplementation) SortedSet(java.util.SortedSet) Date(java.util.Date) EdmmConverter(org.eclipse.winery.edmm.model.EdmmConverter) LoggerFactory(org.slf4j.LoggerFactory) Namespace(org.eclipse.winery.model.ids.Namespace) ArtifactTemplatesResource(org.eclipse.winery.repository.rest.resources.entitytemplates.artifacttemplates.ArtifactTemplatesResource) ContentDisposition(org.glassfish.jersey.media.multipart.ContentDisposition) NamespaceAndDefinedLocalNamesForAngular(org.eclipse.winery.repository.rest.datatypes.NamespaceAndDefinedLocalNamesForAngular) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) SelfContainmentPackager(org.eclipse.winery.repository.backend.selfcontainmentpackager.SelfContainmentPackager) ServiceTemplateResource(org.eclipse.winery.repository.rest.resources.servicetemplates.ServiceTemplateResource) Locale(java.util.Locale) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) Util(org.eclipse.winery.repository.common.Util) URI(java.net.URI) QNameConverter(org.eclipse.winery.repository.rest.resources.apiData.converter.QNameConverter) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference) Collection(java.util.Collection) StreamingOutput(javax.ws.rs.core.StreamingOutput) TNodeType(org.eclipse.winery.model.tosca.TNodeType) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) Objects(java.util.Objects) ArtifactTemplateResource(org.eclipse.winery.repository.rest.resources.entitytemplates.artifacttemplates.ArtifactTemplateResource) List(java.util.List) NamespaceAndDefinedLocalNames(org.eclipse.winery.repository.backend.xsd.NamespaceAndDefinedLocalNames) HttpHeaders(javax.ws.rs.core.HttpHeaders) TExtensibleElements(org.eclipse.winery.model.tosca.TExtensibleElements) YamlExporter(org.eclipse.winery.repository.yaml.export.YamlExporter) Response(javax.ws.rs.core.Response) IRepository(org.eclipse.winery.repository.backend.IRepository) AccessControlException(java.security.AccessControlException) MediaTypes(org.eclipse.winery.repository.backend.constants.MediaTypes) Marshaller(javax.xml.bind.Marshaller) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) HashMap(java.util.HashMap) HashSet(java.util.HashSet) ClientBuilder(javax.ws.rs.client.ClientBuilder) TConstraint(org.eclipse.winery.model.tosca.TConstraint) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) Application(org.eclipse.winery.model.selfservice.Application) NodeTypeImplementationId(org.eclipse.winery.model.ids.definitions.NodeTypeImplementationId) Status(javax.ws.rs.core.Response.Status) JAXBContext(javax.xml.bind.JAXBContext) CsarExporter(org.eclipse.winery.repository.export.CsarExporter) ToscaExportUtil(org.eclipse.winery.repository.export.ToscaExportUtil) Logger(org.slf4j.Logger) Environments(org.eclipse.winery.common.configuration.Environments) AbstractComponentInstanceResource(org.eclipse.winery.repository.rest.resources._support.AbstractComponentInstanceResource) TTag(org.eclipse.winery.model.tosca.TTag) ToscaElementId(org.eclipse.winery.model.ids.elements.ToscaElementId) GitBasedRepository(org.eclipse.winery.repository.backend.filebased.GitBasedRepository) EntityGraph(io.github.edmm.core.parser.EntityGraph) NamespaceManager(org.eclipse.winery.repository.backend.NamespaceManager) TRelationshipType(org.eclipse.winery.model.tosca.TRelationshipType) ComponentId(org.eclipse.winery.repository.rest.datatypes.ComponentId) PolicyTemplateId(org.eclipse.winery.model.ids.definitions.PolicyTemplateId) AbstractComponentsResource(org.eclipse.winery.repository.rest.resources._support.AbstractComponentsResource) InputStream(java.io.InputStream) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) IHasName(org.eclipse.winery.repository.rest.resources._support.IHasName) WebApplicationException(javax.ws.rs.WebApplicationException) ToscaExportUtil(org.eclipse.winery.repository.export.ToscaExportUtil) StreamingOutput(javax.ws.rs.core.StreamingOutput) Map(java.util.Map) HashMap(java.util.HashMap) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) AccessControlException(java.security.AccessControlException)

Example 73 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project carbon-apimgt by wso2.

the class RetrieveApiArtifactsApiServiceImpl method retrieveApiArtifactsPost.

public Response retrieveApiArtifactsPost(String xWSO2Tenant, String gatewayLabel, String type, UUIDListDTO uuidList, MessageContext messageContext) throws APIManagementException {
    xWSO2Tenant = SubscriptionValidationDataUtil.validateTenantDomain(xWSO2Tenant, messageContext);
    RuntimeArtifactDto runtimeArtifactDto = APIArtifactGeneratorUtil.generateAPIArtifact(uuidList.getUuids(), "", "", gatewayLabel, type, xWSO2Tenant);
    if (runtimeArtifactDto != null) {
        if (runtimeArtifactDto.isFile()) {
            File artifact = (File) runtimeArtifactDto.getArtifact();
            StreamingOutput streamingOutput = (outputStream) -> {
                try {
                    Files.copy(artifact.toPath(), outputStream);
                } finally {
                    Files.delete(artifact.toPath());
                }
            };
            return Response.ok(streamingOutput).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=apis.zip").header(RestApiConstants.HEADER_CONTENT_TYPE, APIConstants.APPLICATION_ZIP).build();
        } else {
            SynapseArtifactListDTO synapseArtifactListDTO = new SynapseArtifactListDTO();
            if (runtimeArtifactDto.getArtifact() instanceof List) {
                synapseArtifactListDTO.setList((List<String>) runtimeArtifactDto.getArtifact());
                synapseArtifactListDTO.setCount(((List<String>) runtimeArtifactDto.getArtifact()).size());
            }
            return Response.ok().entity(synapseArtifactListDTO).header(RestApiConstants.HEADER_CONTENT_TYPE, RestApiConstants.APPLICATION_JSON).build();
        }
    } else {
        return Response.status(Response.Status.NOT_FOUND).entity(RestApiUtil.getErrorDTO(ExceptionCodes.NO_API_ARTIFACT_FOUND)).build();
    }
}
Also used : SynapseArtifactListDTO(org.wso2.carbon.apimgt.internal.service.dto.SynapseArtifactListDTO) Files(java.nio.file.Files) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) RuntimeArtifactGeneratorUtil(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.RuntimeArtifactGeneratorUtil) APIArtifactGeneratorUtil(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.APIArtifactGeneratorUtil) RestApiUtil(org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil) StreamingOutput(javax.ws.rs.core.StreamingOutput) File(java.io.File) APIConstants(org.wso2.carbon.apimgt.impl.APIConstants) ArrayList(java.util.ArrayList) SubscriptionValidationDataUtil(org.wso2.carbon.apimgt.internal.service.utils.SubscriptionValidationDataUtil) List(java.util.List) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) Response(javax.ws.rs.core.Response) RestApiConstants(org.wso2.carbon.apimgt.rest.api.common.RestApiConstants) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UUIDListDTO(org.wso2.carbon.apimgt.internal.service.dto.UUIDListDTO) ExceptionCodes(org.wso2.carbon.apimgt.api.ExceptionCodes) RetrieveApiArtifactsApiService(org.wso2.carbon.apimgt.internal.service.RetrieveApiArtifactsApiService) SynapseArtifactListDTO(org.wso2.carbon.apimgt.internal.service.dto.SynapseArtifactListDTO) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) StreamingOutput(javax.ws.rs.core.StreamingOutput) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File)

Example 74 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project carbon-apimgt by wso2.

the class RuntimeMetadataApiServiceImpl method runtimeMetadataGet.

public Response runtimeMetadataGet(String xWSO2Tenant, String apiId, String gatewayLabel, MessageContext messageContext) throws APIManagementException {
    xWSO2Tenant = SubscriptionValidationDataUtil.validateTenantDomain(xWSO2Tenant, messageContext);
    RuntimeArtifactDto runtimeArtifactDto = RuntimeArtifactGeneratorUtil.generateMetadataArtifact(xWSO2Tenant, apiId, gatewayLabel);
    if (runtimeArtifactDto != null) {
        File artifact = (File) runtimeArtifactDto.getArtifact();
        StreamingOutput streamingOutput = (outputStream) -> {
            try {
                Files.copy(artifact.toPath(), outputStream);
            } finally {
                Files.delete(artifact.toPath());
            }
        };
        return Response.ok(streamingOutput).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=deployment.json").header(RestApiConstants.HEADER_CONTENT_TYPE, APIConstants.APPLICATION_JSON_MEDIA_TYPE).build();
    } else {
        return Response.status(Response.Status.NOT_FOUND).entity(RestApiUtil.getErrorDTO(ExceptionCodes.NO_API_ARTIFACT_FOUND)).build();
    }
}
Also used : Files(java.nio.file.Files) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) RuntimeArtifactGeneratorUtil(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.RuntimeArtifactGeneratorUtil) RestApiUtil(org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil) StreamingOutput(javax.ws.rs.core.StreamingOutput) File(java.io.File) APIConstants(org.wso2.carbon.apimgt.impl.APIConstants) SubscriptionValidationDataUtil(org.wso2.carbon.apimgt.internal.service.utils.SubscriptionValidationDataUtil) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) Response(javax.ws.rs.core.Response) RestApiConstants(org.wso2.carbon.apimgt.rest.api.common.RestApiConstants) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ExceptionCodes(org.wso2.carbon.apimgt.api.ExceptionCodes) RuntimeMetadataApiService(org.wso2.carbon.apimgt.internal.service.RuntimeMetadataApiService) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) StreamingOutput(javax.ws.rs.core.StreamingOutput) File(java.io.File)

Example 75 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project cxf by apache.

the class BinaryDataProviderTest method testReadFrom.

@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);
}
Also used : MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Reader(java.io.Reader) StringReader(java.io.StringReader) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) StreamingOutput(javax.ws.rs.core.StreamingOutput) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Annotation(java.lang.annotation.Annotation) Test(org.junit.Test)

Aggregations

StreamingOutput (javax.ws.rs.core.StreamingOutput)190 OutputStream (java.io.OutputStream)84 Response (javax.ws.rs.core.Response)76 Path (javax.ws.rs.Path)53 Produces (javax.ws.rs.Produces)52 IOException (java.io.IOException)50 GET (javax.ws.rs.GET)50 File (java.io.File)45 InputStream (java.io.InputStream)45 Test (org.junit.Test)44 WebApplicationException (javax.ws.rs.WebApplicationException)33 ByteArrayOutputStream (java.io.ByteArrayOutputStream)32 List (java.util.List)26 MediaType (javax.ws.rs.core.MediaType)24 ByteArrayInputStream (java.io.ByteArrayInputStream)20 ArrayList (java.util.ArrayList)20 Consumes (javax.ws.rs.Consumes)20 HashMap (java.util.HashMap)19 POST (javax.ws.rs.POST)19 FileOutputStream (java.io.FileOutputStream)17