Search in sources :

Example 1 with TemplateEntity

use of org.apache.nifi.web.api.entity.TemplateEntity in project nifi by apache.

the class TemplateResource method removeTemplate.

/**
 * Removes the specified template.
 *
 * @param httpServletRequest request
 * @param id                 The id of the template to remove.
 * @return A templateEntity.
 */
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(value = "Deletes a template", response = TemplateEntity.class, authorizations = { @Authorization(value = "Write - /templates/{uuid}"), @Authorization(value = "Write - Parent Process Group - /process-groups/{uuid}") })
@ApiResponses(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response removeTemplate(@Context final HttpServletRequest httpServletRequest, @ApiParam(value = "The template id.", required = true) @PathParam("id") final String id) {
    if (isReplicateRequest()) {
        return replicate(HttpMethod.DELETE);
    }
    final TemplateEntity requestTemplateEntity = new TemplateEntity();
    requestTemplateEntity.setId(id);
    return withWriteLock(serviceFacade, requestTemplateEntity, lookup -> {
        final Authorizable template = lookup.getTemplate(id);
        // ensure write permission to the template
        template.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
        // ensure write permission to the parent process group
        template.getParentAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
    }, null, (templateEntity) -> {
        // delete the specified template
        serviceFacade.deleteTemplate(templateEntity.getId());
        // build the response entity
        final TemplateEntity entity = new TemplateEntity();
        return generateOkResponse(entity).build();
    });
}
Also used : Authorizable(org.apache.nifi.authorization.resource.Authorizable) TemplateEntity(org.apache.nifi.web.api.entity.TemplateEntity) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 2 with TemplateEntity

use of org.apache.nifi.web.api.entity.TemplateEntity in project nifi by apache.

the class ProcessGroupResource method uploadTemplate.

/**
 * Imports the specified template.
 *
 * @param httpServletRequest request
 * @param in                 The template stream
 * @return A templateEntity or an errorResponse XML snippet.
 * @throws InterruptedException if interrupted
 */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_XML)
@Path("{id}/templates/upload")
@ApiOperation(value = "Uploads a template", response = TemplateEntity.class, authorizations = { @Authorization(value = "Write - /process-groups/{uuid}") })
@ApiImplicitParams(value = { @ApiImplicitParam(name = "template", value = "The binary content of the template file being uploaded.", required = true, type = "file", paramType = "formData") })
@ApiResponses(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response uploadTemplate(@Context final HttpServletRequest httpServletRequest, @Context final UriInfo uriInfo, @ApiParam(value = "The process group id.", required = true) @PathParam("id") final String groupId, @FormDataParam("template") final InputStream in) throws InterruptedException {
    // unmarshal the template
    final TemplateDTO template;
    try {
        JAXBContext context = JAXBContext.newInstance(TemplateDTO.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        XMLStreamReader xsr = XmlUtils.createSafeReader(in);
        JAXBElement<TemplateDTO> templateElement = unmarshaller.unmarshal(xsr, TemplateDTO.class);
        template = templateElement.getValue();
    } catch (JAXBException jaxbe) {
        logger.warn("An error occurred while parsing a template.", jaxbe);
        String responseXml = String.format("<errorResponse status=\"%s\" statusText=\"The specified template is not in a valid format.\"/>", Response.Status.BAD_REQUEST.getStatusCode());
        return Response.status(Response.Status.OK).entity(responseXml).type("application/xml").build();
    } catch (IllegalArgumentException iae) {
        logger.warn("Unable to import template.", iae);
        String responseXml = String.format("<errorResponse status=\"%s\" statusText=\"%s\"/>", Response.Status.BAD_REQUEST.getStatusCode(), iae.getMessage());
        return Response.status(Response.Status.OK).entity(responseXml).type("application/xml").build();
    } catch (Exception e) {
        logger.warn("An error occurred while importing a template.", e);
        String responseXml = String.format("<errorResponse status=\"%s\" statusText=\"Unable to import the specified template: %s\"/>", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e.getMessage());
        return Response.status(Response.Status.OK).entity(responseXml).type("application/xml").build();
    }
    // build the response entity
    TemplateEntity entity = new TemplateEntity();
    entity.setTemplate(template);
    if (isReplicateRequest()) {
        // convert request accordingly
        final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
        uriBuilder.segment("process-groups", groupId, "templates", "import");
        final URI importUri = uriBuilder.build();
        final Map<String, String> headersToOverride = new HashMap<>();
        headersToOverride.put("content-type", MediaType.APPLICATION_XML);
        // to the cluster nodes themselves.
        if (getReplicationTarget() == ReplicationTarget.CLUSTER_NODES) {
            return getRequestReplicator().replicate(HttpMethod.POST, importUri, entity, getHeaders(headersToOverride)).awaitMergedResponse().getResponse();
        } else {
            return getRequestReplicator().forwardToCoordinator(getClusterCoordinatorNode(), HttpMethod.POST, importUri, entity, getHeaders(headersToOverride)).awaitMergedResponse().getResponse();
        }
    }
    // otherwise import the template locally
    return importTemplate(httpServletRequest, groupId, entity);
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) TemplateDTO(org.apache.nifi.web.api.dto.TemplateDTO) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) URI(java.net.URI) NiFiRegistryException(org.apache.nifi.registry.client.NiFiRegistryException) ResourceNotFoundException(org.apache.nifi.web.ResourceNotFoundException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) JAXBException(javax.xml.bind.JAXBException) TemplateEntity(org.apache.nifi.web.api.entity.TemplateEntity) Unmarshaller(javax.xml.bind.Unmarshaller) UriBuilder(javax.ws.rs.core.UriBuilder) Path(javax.ws.rs.Path) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 3 with TemplateEntity

use of org.apache.nifi.web.api.entity.TemplateEntity in project nifi by apache.

the class ProcessGroupResource method importTemplate.

/**
 * Imports the specified template.
 *
 * @param httpServletRequest request
 * @param requestTemplateEntity     A templateEntity.
 * @return A templateEntity.
 */
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
@Path("{id}/templates/import")
@ApiOperation(value = "Imports a template", response = TemplateEntity.class, authorizations = { @Authorization(value = "Write - /process-groups/{uuid}") })
@ApiResponses(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response importTemplate(@Context final HttpServletRequest httpServletRequest, @ApiParam(value = "The process group id.", required = true) @PathParam("id") final String groupId, final TemplateEntity requestTemplateEntity) {
    // verify the template was specified
    if (requestTemplateEntity == null || requestTemplateEntity.getTemplate() == null || requestTemplateEntity.getTemplate().getSnippet() == null) {
        throw new IllegalArgumentException("Template details must be specified.");
    }
    if (isReplicateRequest()) {
        return replicate(HttpMethod.POST, requestTemplateEntity);
    }
    return withWriteLock(serviceFacade, requestTemplateEntity, lookup -> {
        final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
        processGroup.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
    }, () -> serviceFacade.verifyCanAddTemplate(groupId, requestTemplateEntity.getTemplate().getName()), templateEntity -> {
        try {
            // import the template
            final TemplateDTO template = serviceFacade.importTemplate(templateEntity.getTemplate(), groupId, getIdGenerationSeed());
            templateResource.populateRemainingTemplateContent(template);
            // build the response entity
            TemplateEntity entity = new TemplateEntity();
            entity.setTemplate(template);
            // build the response
            return generateCreatedResponse(URI.create(template.getUri()), entity).build();
        } catch (IllegalArgumentException | IllegalStateException e) {
            logger.info("Unable to import template: " + e);
            String responseXml = String.format("<errorResponse status=\"%s\" statusText=\"%s\"/>", Response.Status.BAD_REQUEST.getStatusCode(), e.getMessage());
            return Response.status(Response.Status.OK).entity(responseXml).type("application/xml").build();
        } catch (Exception e) {
            logger.warn("An error occurred while importing a template.", e);
            String responseXml = String.format("<errorResponse status=\"%s\" statusText=\"Unable to import the specified template: %s\"/>", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e.getMessage());
            return Response.status(Response.Status.OK).entity(responseXml).type("application/xml").build();
        }
    });
}
Also used : TemplateDTO(org.apache.nifi.web.api.dto.TemplateDTO) ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) Authorizable(org.apache.nifi.authorization.resource.Authorizable) SnippetAuthorizable(org.apache.nifi.authorization.SnippetAuthorizable) TemplateContentsAuthorizable(org.apache.nifi.authorization.TemplateContentsAuthorizable) ProcessGroupAuthorizable(org.apache.nifi.authorization.ProcessGroupAuthorizable) TemplateEntity(org.apache.nifi.web.api.entity.TemplateEntity) NiFiRegistryException(org.apache.nifi.registry.client.NiFiRegistryException) ResourceNotFoundException(org.apache.nifi.web.ResourceNotFoundException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) JAXBException(javax.xml.bind.JAXBException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 4 with TemplateEntity

use of org.apache.nifi.web.api.entity.TemplateEntity in project nifi by apache.

the class TemplatesEndpointMerger method merge.

@Override
public final NodeResponse merge(final URI uri, final String method, final Set<NodeResponse> successfulResponses, final Set<NodeResponse> problematicResponses, final NodeResponse clientResponse) {
    if (!canHandle(uri, method)) {
        throw new IllegalArgumentException("Cannot use Endpoint Mapper of type " + getClass().getSimpleName() + " to map responses for URI " + uri + ", HTTP Method " + method);
    }
    final TemplatesEntity responseEntity = clientResponse.getClientResponse().readEntity(getEntityClass());
    // Find the templates that all nodes know about. We do this by mapping Template ID to Template and
    // then for each node, removing any template whose ID is not known to that node. After iterating over
    // all of the nodes, we are left with a Map whose contents are those Templates known by all nodes.
    Map<String, TemplateEntity> templatesById = null;
    for (final NodeResponse nodeResponse : successfulResponses) {
        final TemplatesEntity entity = nodeResponse == clientResponse ? responseEntity : nodeResponse.getClientResponse().readEntity(TemplatesEntity.class);
        final Set<TemplateEntity> templateEntities = entity.getTemplates();
        final Map<String, TemplateEntity> nodeTemplatesById = templateEntities.stream().collect(Collectors.toMap(ent -> ent.getId(), ent -> ent));
        if (templatesById == null) {
            // Create new HashMap so that the map that we have is modifiable.
            templatesById = new HashMap<>(nodeTemplatesById);
        } else {
            // Only keep templates that are known by this node.
            templatesById.keySet().retainAll(nodeTemplatesById.keySet());
        }
    }
    // Set the templates to the set of templates that all nodes know about
    responseEntity.setTemplates(new HashSet<>(templatesById.values()));
    // create a new client response
    return new NodeResponse(clientResponse, responseEntity);
}
Also used : HashSet(java.util.HashSet) TemplatesEntity(org.apache.nifi.web.api.entity.TemplatesEntity) TemplateDTO(org.apache.nifi.web.api.dto.TemplateDTO) Map(java.util.Map) Set(java.util.Set) TemplateEntity(org.apache.nifi.web.api.entity.TemplateEntity) HashMap(java.util.HashMap) EndpointResponseMerger(org.apache.nifi.cluster.coordination.http.EndpointResponseMerger) URI(java.net.URI) Pattern(java.util.regex.Pattern) Collectors(java.util.stream.Collectors) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) TemplatesEntity(org.apache.nifi.web.api.entity.TemplatesEntity) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) TemplateEntity(org.apache.nifi.web.api.entity.TemplateEntity)

Example 5 with TemplateEntity

use of org.apache.nifi.web.api.entity.TemplateEntity in project nifi by apache.

the class FlowResource method getTemplates.

// ---------
// templates
// ---------
/**
 * Retrieves all the of templates in this NiFi.
 *
 * @return A templatesEntity.
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("templates")
@ApiOperation(value = "Gets all templates", response = TemplatesEntity.class, authorizations = { @Authorization(value = "Read - /flow") })
@ApiResponses(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response getTemplates() {
    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }
    // authorize access
    authorizeFlow();
    // get all the templates
    final Set<TemplateEntity> templates = serviceFacade.getTemplates();
    templateResource.populateRemainingTemplateEntitiesContent(templates);
    // create the response entity
    final TemplatesEntity entity = new TemplatesEntity();
    entity.setTemplates(templates);
    entity.setGenerated(new Date());
    // generate the response
    return generateOkResponse(entity).build();
}
Also used : TemplatesEntity(org.apache.nifi.web.api.entity.TemplatesEntity) TemplateEntity(org.apache.nifi.web.api.entity.TemplateEntity) Date(java.util.Date) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

TemplateEntity (org.apache.nifi.web.api.entity.TemplateEntity)8 ApiOperation (io.swagger.annotations.ApiOperation)5 ApiResponses (io.swagger.annotations.ApiResponses)5 Consumes (javax.ws.rs.Consumes)5 Path (javax.ws.rs.Path)5 Produces (javax.ws.rs.Produces)5 TemplateDTO (org.apache.nifi.web.api.dto.TemplateDTO)4 POST (javax.ws.rs.POST)3 IOException (java.io.IOException)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2 Response (javax.ws.rs.core.Response)2 JAXBException (javax.xml.bind.JAXBException)2 Authorizable (org.apache.nifi.authorization.resource.Authorizable)2 ExecuteCodeRestrictedProcessor (org.apache.nifi.integration.util.ExecuteCodeRestrictedProcessor)2 NiFiRegistryException (org.apache.nifi.registry.client.NiFiRegistryException)2 ResourceNotFoundException (org.apache.nifi.web.ResourceNotFoundException)2 CreateTemplateRequestEntity (org.apache.nifi.web.api.entity.CreateTemplateRequestEntity)2 FlowEntity (org.apache.nifi.web.api.entity.FlowEntity)2