Search in sources :

Example 1 with Icon

use of io.syndesis.common.model.icon.Icon in project syndesis by syndesisio.

the class ConnectorIconHandler method create.

@POST
@ApiOperation("Updates the connector icon for the specified connector and returns the updated connector")
@ApiResponses(@ApiResponse(code = 200, response = Connector.class, message = "Updated Connector icon"))
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@SuppressWarnings("PMD.CyclomaticComplexity")
public Connector create(MultipartFormDataInput dataInput) {
    if (dataInput == null || dataInput.getParts() == null || dataInput.getParts().isEmpty()) {
        throw new IllegalArgumentException("Multipart request is empty");
    }
    if (dataInput.getParts().size() != 1) {
        throw new IllegalArgumentException("Wrong number of parts in multipart request");
    }
    try {
        InputPart filePart = dataInput.getParts().iterator().next();
        InputStream result = filePart.getBody(InputStream.class, null);
        if (result == null) {
            throw new IllegalArgumentException("Can't find a valid 'icon' part in the multipart request");
        }
        try (BufferedInputStream iconStream = new BufferedInputStream(result)) {
            MediaType mediaType = filePart.getMediaType();
            if (!mediaType.getType().equals("image")) {
                // URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
                // can continue to be used, rather than being consumed.
                String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
                if (!guessedMediaType.startsWith("image/")) {
                    throw new IllegalArgumentException("Invalid file contents for an image");
                }
                mediaType = MediaType.valueOf(guessedMediaType);
            }
            Icon.Builder iconBuilder = new Icon.Builder().mediaType(mediaType.toString());
            Icon icon;
            String connectorIcon = connector.getIcon();
            if (connectorIcon != null && connectorIcon.startsWith("db:")) {
                String connectorIconId = connectorIcon.substring(3);
                iconBuilder.id(connectorIconId);
                icon = iconBuilder.build();
                getDataManager().update(icon);
            } else {
                icon = getDataManager().create(iconBuilder.build());
            }
            iconDao.write(icon.getId().get(), iconStream);
            Connector updatedConnector = new Connector.Builder().createFrom(connector).icon("db:" + icon.getId().get()).build();
            getDataManager().update(updatedConnector);
            return updatedConnector;
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Error while reading multipart request", e);
    }
}
Also used : Connector(io.syndesis.common.model.connection.Connector) InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) MediaType(javax.ws.rs.core.MediaType) Icon(io.syndesis.common.model.icon.Icon) IOException(java.io.IOException) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 2 with Icon

use of io.syndesis.common.model.icon.Icon in project syndesis by syndesisio.

the class ConnectorHandler method update.

@PUT
@Path(value = "/{id}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void update(@NotNull @PathParam("id") @ApiParam(required = true) String id, @MultipartForm ConnectorFormData connectorFormData) {
    if (connectorFormData.getConnector() == null) {
        throw new IllegalArgumentException("Missing connector parameter");
    }
    Connector connectorToUpdate = connectorFormData.getConnector();
    if (connectorFormData.getIconInputStream() != null) {
        try (BufferedInputStream iconStream = new BufferedInputStream(connectorFormData.getIconInputStream())) {
            // URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
            // can continue to be used, rather than being consumed.
            String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
            if (!guessedMediaType.startsWith("image/")) {
                throw new IllegalArgumentException("Invalid file contents for an image");
            }
            MediaType mediaType = MediaType.valueOf(guessedMediaType);
            Icon.Builder iconBuilder = new Icon.Builder().mediaType(mediaType.toString());
            Icon icon = getDataManager().create(iconBuilder.build());
            iconDao.write(icon.getId().get(), iconStream);
            final String oldIconId = connectorToUpdate.getIcon();
            if (oldIconId.toLowerCase(Locale.US).startsWith("db:")) {
                iconDao.delete(oldIconId.substring(3));
            }
            connectorToUpdate = connectorToUpdate.builder().icon("db:" + icon.getId().get()).build();
        } catch (IOException e) {
            throw new IllegalArgumentException("Error while reading multipart request", e);
        }
    }
    getDataManager().update(connectorToUpdate);
}
Also used : Connector(io.syndesis.common.model.connection.Connector) BufferedInputStream(java.io.BufferedInputStream) MediaType(javax.ws.rs.core.MediaType) Icon(io.syndesis.common.model.icon.Icon) IOException(java.io.IOException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 3 with Icon

use of io.syndesis.common.model.icon.Icon in project syndesis by syndesisio.

the class ConnectorIconHandler method get.

@GET
@SuppressWarnings("PMD.CyclomaticComplexity")
public Response get() {
    String connectorIcon = connector.getIcon();
    if (connectorIcon == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    if (connectorIcon.startsWith("db:")) {
        String connectorIconId = connectorIcon.substring(3);
        Icon icon = getDataManager().fetch(Icon.class, connectorIconId);
        if (icon == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        final StreamingOutput streamingOutput = (out) -> {
            try (BufferedSink sink = Okio.buffer(Okio.sink(out));
                Source source = Okio.source(iconDao.read(connectorIconId))) {
                sink.writeAll(source);
            }
        };
        return Response.ok(streamingOutput, icon.getMediaType()).build();
    } else if (connectorIcon.startsWith("extension:")) {
        String iconFile = connectorIcon.substring(10);
        Optional<InputStream> extensionIcon = connector.getDependencies().stream().filter(Dependency::isExtension).map(Dependency::getId).findFirst().flatMap(extensionId -> extensionDataManager.getExtensionIcon(extensionId, iconFile));
        if (extensionIcon.isPresent()) {
            final StreamingOutput streamingOutput = (out) -> {
                final BufferedSink sink = Okio.buffer(Okio.sink(out));
                sink.writeAll(Okio.source(extensionIcon.get()));
                sink.close();
            };
            return Response.ok(streamingOutput, extensionDataManager.getExtensionIconMediaType(iconFile)).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }
    // font awesome class name), return 404
    if (connectorIcon.startsWith("data:") || !connectorIcon.contains("/")) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    final OkHttpClient httpClient = new OkHttpClient();
    try {
        final okhttp3.Response externalResponse = httpClient.newCall(new Request.Builder().get().url(connectorIcon).build()).execute();
        final String contentType = externalResponse.header(CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);
        final String contentLength = externalResponse.header(CONTENT_LENGTH);
        final StreamingOutput streamingOutput = (out) -> {
            final BufferedSink sink = Okio.buffer(Okio.sink(out));
            sink.writeAll(externalResponse.body().source());
            sink.close();
        };
        final Response.ResponseBuilder actualResponse = Response.ok(streamingOutput, contentType);
        if (!StringUtils.isEmpty(contentLength)) {
            actualResponse.header(CONTENT_LENGTH, contentLength);
        }
        return actualResponse.build();
    } catch (final IOException e) {
        throw new SyndesisServerException(e);
    }
}
Also used : CONTENT_TYPE(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE) Okio(okio.Okio) BufferedInputStream(java.io.BufferedInputStream) Produces(javax.ws.rs.Produces) Source(okio.Source) GET(javax.ws.rs.GET) ApiResponses(io.swagger.annotations.ApiResponses) StringUtils(org.apache.commons.lang3.StringUtils) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) Consumes(javax.ws.rs.Consumes) BufferedSink(okio.BufferedSink) URLConnection(java.net.URLConnection) DataManager(io.syndesis.server.dao.manager.DataManager) FileDataManager(io.syndesis.server.dao.file.FileDataManager) Api(io.swagger.annotations.Api) Icon(io.syndesis.common.model.icon.Icon) CONTENT_LENGTH(javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH) Request(okhttp3.Request) POST(javax.ws.rs.POST) Connector(io.syndesis.common.model.connection.Connector) IOException(java.io.IOException) StreamingOutput(javax.ws.rs.core.StreamingOutput) Dependency(io.syndesis.common.model.Dependency) OkHttpClient(okhttp3.OkHttpClient) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) SyndesisServerException(io.syndesis.common.util.SyndesisServerException) Optional(java.util.Optional) MultipartFormDataInput(org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput) IconDao(io.syndesis.server.dao.file.IconDao) BaseHandler(io.syndesis.server.endpoint.v1.handler.BaseHandler) InputStream(java.io.InputStream) OkHttpClient(okhttp3.OkHttpClient) Optional(java.util.Optional) SyndesisServerException(io.syndesis.common.util.SyndesisServerException) Request(okhttp3.Request) StreamingOutput(javax.ws.rs.core.StreamingOutput) BufferedSink(okio.BufferedSink) Dependency(io.syndesis.common.model.Dependency) IOException(java.io.IOException) Source(okio.Source) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) Icon(io.syndesis.common.model.icon.Icon) GET(javax.ws.rs.GET)

Example 4 with Icon

use of io.syndesis.common.model.icon.Icon in project syndesis by syndesisio.

the class CustomConnectorHandler method create.

@POST
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation("Creates a new Connector based on the ConnectorTemplate identified by the provided `id` and the data given in `connectorSettings` multipart part, plus optional `icon` file")
@ApiResponses(@ApiResponse(code = 200, response = Connector.class, message = "Newly created Connector"))
public Connector create(@MultipartForm CustomConnectorFormData customConnectorFormData) throws IOException {
    final ConnectorSettings connectorSettings = customConnectorFormData.getConnectorSettings();
    if (connectorSettings == null) {
        throw new IllegalArgumentException("Missing connectorSettings parameter");
    }
    final ConnectorSettings connectorSettingsToUse;
    if (connectorSettings.getConfiguredProperties().containsKey("specification")) {
        connectorSettingsToUse = connectorSettings;
    } else {
        final String specification;
        try (BufferedSource source = Okio.buffer(Okio.source(customConnectorFormData.getSpecification()))) {
            specification = source.readUtf8();
        }
        connectorSettingsToUse = new ConnectorSettings.Builder().createFrom(connectorSettings).putConfiguredProperty("specification", specification).build();
    }
    Connector generatedConnector = withGeneratorAndTemplate(connectorSettingsToUse.getConnectorTemplateId(), (generator, template) -> generator.generate(template, connectorSettingsToUse));
    if (customConnectorFormData.getIconInputStream() != null) {
        // can continue to be used, rather than being consumed.
        try (BufferedInputStream iconStream = new BufferedInputStream(customConnectorFormData.getIconInputStream())) {
            String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
            if (!guessedMediaType.startsWith("image/")) {
                throw new IllegalArgumentException("Invalid file contents for an image");
            }
            MediaType mediaType = MediaType.valueOf(guessedMediaType);
            Icon.Builder iconBuilder = new Icon.Builder().mediaType(mediaType.toString());
            Icon icon = getDataManager().create(iconBuilder.build());
            iconDao.write(icon.getId().get(), iconStream);
            generatedConnector = new Connector.Builder().createFrom(generatedConnector).icon("db:" + icon.getId().get()).build();
        } catch (IOException e) {
            throw new IllegalArgumentException("Error while reading multipart request", e);
        }
    }
    return getDataManager().create(generatedConnector);
}
Also used : Connector(io.syndesis.common.model.connection.Connector) BufferedInputStream(java.io.BufferedInputStream) MediaType(javax.ws.rs.core.MediaType) Icon(io.syndesis.common.model.icon.Icon) IOException(java.io.IOException) ConnectorSettings(io.syndesis.common.model.connection.ConnectorSettings) BufferedSource(okio.BufferedSource) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 5 with Icon

use of io.syndesis.common.model.icon.Icon in project syndesis by syndesisio.

the class CustomConnectorITCase method shouldCreateNewCustomConnectorsFromMultipartWithIcon.

@Test
public void shouldCreateNewCustomConnectorsFromMultipartWithIcon() throws IOException {
    final ResponseEntity<Connector> response = post("/api/v1/connectors/custom", multipartBody(new ConnectorSettings.Builder().connectorTemplateId(TEMPLATE_ID).putConfiguredProperty("specification", "here-be-specification").build(), CustomConnectorITCase.class.getResourceAsStream("/io/syndesis/server/runtime/test-image.png")), Connector.class, tokenRule.validToken(), HttpStatus.OK, multipartHeaders());
    final Connector created = response.getBody();
    assertThat(created).isNotNull();
    assertThat(created.getDescription()).isEqualTo("test-description");
    assertThat(dataManager.fetch(Connector.class, response.getBody().getId().get())).isNotNull();
    assertThat(created.getIcon()).startsWith("db:");
    final Icon icon = dataManager.fetch(Icon.class, created.getIcon().substring(3));
    assertThat(icon.getMediaType()).isEqualTo(MediaType.IMAGE_PNG_VALUE);
    try (InputStream storedIcon = iconDao.read(icon.getId().get());
        InputStream expectedIcon = CustomConnectorITCase.class.getResourceAsStream("/io/syndesis/server/runtime/test-image.png")) {
        assertThat(storedIcon).hasSameContentAs(expectedIcon);
    }
}
Also used : Connector(io.syndesis.common.model.connection.Connector) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Icon(io.syndesis.common.model.icon.Icon) ConnectorSettings(io.syndesis.common.model.connection.ConnectorSettings) Test(org.junit.Test)

Aggregations

Connector (io.syndesis.common.model.connection.Connector)6 Icon (io.syndesis.common.model.icon.Icon)6 BufferedInputStream (java.io.BufferedInputStream)4 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4 Consumes (javax.ws.rs.Consumes)4 MediaType (javax.ws.rs.core.MediaType)4 ApiOperation (io.swagger.annotations.ApiOperation)3 ApiResponses (io.swagger.annotations.ApiResponses)3 POST (javax.ws.rs.POST)3 Produces (javax.ws.rs.Produces)3 ConnectorSettings (io.syndesis.common.model.connection.ConnectorSettings)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Path (javax.ws.rs.Path)2 InputPart (org.jboss.resteasy.plugins.providers.multipart.InputPart)2 Test (org.junit.Test)2 Api (io.swagger.annotations.Api)1 ApiResponse (io.swagger.annotations.ApiResponse)1 Dependency (io.syndesis.common.model.Dependency)1 SyndesisServerException (io.syndesis.common.util.SyndesisServerException)1