com.wordnik.swagger.annotations.ApiParam Java Examples

The following examples show how to use com.wordnik.swagger.annotations.ApiParam. 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: FlowResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the specified remote process groups status history.
 *
 * @param id The id of the remote process group to retrieve the status fow.
 * @return A statusHistoryEntity.
 * @throws InterruptedException if interrupted
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("remote-process-groups/{id}/status/history")
@ApiOperation(
        value = "Gets the status history",
        response = StatusHistoryEntity.class,
        authorizations = {
                @Authorization(value = "Read - /flow", type = "")
        }
)
@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 getRemoteProcessGroupStatusHistory(
        @ApiParam(
                value = "The remote process group id.",
                required = true
        )
        @PathParam("id") String id) throws InterruptedException {

    authorizeFlow();

    // replicate if cluster manager
    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // get the specified processor status history
    final StatusHistoryEntity entity = serviceFacade.getRemoteProcessGroupStatusHistory(id);
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #2
Source File: FlowResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the specified connection status history.
 *
 * @param id The id of the connection to retrieve.
 * @return A statusHistoryEntity.
 * @throws InterruptedException if interrupted
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("connections/{id}/status/history")
@ApiOperation(
        value = "Gets the status history for a connection",
        response = StatusHistoryEntity.class,
        authorizations = {
                @Authorization(value = "Read - /flow", type = "")
        }
)
@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 getConnectionStatusHistory(
        @ApiParam(
                value = "The connection id.",
                required = true
        )
        @PathParam("id") String id) throws InterruptedException {

    authorizeFlow();

    // replicate if cluster manager
    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // get the specified processor status history
    final StatusHistoryEntity entity = serviceFacade.getConnectionStatusHistory(id);
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #3
Source File: FlowResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the types of controller services that this NiFi supports.
 *
 * @param serviceType Returns only services that implement this type
 * @return A controllerServicesTypesEntity.
 * @throws InterruptedException if interrupted
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("controller-service-types")
@ApiOperation(
        value = "Retrieves the types of controller services that this NiFi supports",
        notes = NON_GUARANTEED_ENDPOINT,
        response = ControllerServiceTypesEntity.class,
        authorizations = {
                @Authorization(value = "Read - /flow", type = "")
        }
)
@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 getControllerServiceTypes(
        @ApiParam(
                value = "If specified, will only return controller services of this type.",
                required = false
        )
        @QueryParam("serviceType") String serviceType) throws InterruptedException {

    authorizeFlow();

    // create response entity
    final ControllerServiceTypesEntity entity = new ControllerServiceTypesEntity();
    entity.setControllerServiceTypes(serviceFacade.getControllerServiceTypes(serviceType));

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #4
Source File: FlowResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the contents of the specified group.
 *
 * @param groupId The id of the process group.
 * @return A processGroupEntity.
 * @throws InterruptedException if interrupted
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("process-groups/{id}")
@ApiOperation(
        value = "Gets a process group",
        response = ProcessGroupFlowEntity.class,
        authorizations = {
                @Authorization(value = "Read - /flow", type = "")
        }
)
@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 getFlow(
        @ApiParam(
                value = "The process group id.",
                required = false
        )
        @PathParam("id") String groupId) throws InterruptedException {

    authorizeFlow();

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // get this process group flow
    final ProcessGroupFlowEntity entity = serviceFacade.getProcessGroupFlow(groupId);
    populateRemainingFlowContent(entity.getProcessGroupFlow());
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #5
Source File: ConnectionResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves the specified connection.
 *
 * @param id The id of the connection.
 * @return A connectionEntity.
 * @throws InterruptedException if interrupted
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}")
@ApiOperation(
        value = "Gets a connection",
        response = ConnectionEntity.class,
        authorizations = {
                @Authorization(value = "Read Source - /{component-type}/{uuid}", type = ""),
                @Authorization(value = "Read Destination - /{component-type}/{uuid}", type = "")
        }
)
@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 getConnection(
        @ApiParam(
                value = "The connection id.",
                required = true
        )
        @PathParam("id") final String id) throws InterruptedException {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        // ensure read access to this connection (checks source and destination)
        final Authorizable authorizable = lookup.getConnection(id).getAuthorizable();
        authorizable.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });

    // get the specified relationship
    ConnectionEntity entity = serviceFacade.getConnection(id);
    populateRemainingConnectionEntityContent(entity);

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #6
Source File: FlowResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the action for the corresponding id.
 *
 * @param id The id of the action to get.
 * @return An actionEntity.
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("history/{id}")
@ApiOperation(
        value = "Gets an action",
        notes = NON_GUARANTEED_ENDPOINT,
        response = ActionEntity.class,
        authorizations = {
                @Authorization(value = "Read - /flow", type = "")
        }
)
@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 getAction(
        @ApiParam(
                value = "The action id.",
                required = true
        )
        @PathParam("id") IntegerParameter id) {

    authorizeFlow();

    // ensure the id was specified
    if (id == null) {
        throw new IllegalArgumentException("The action id must be specified.");
    }

    // Note: History requests are not replicated throughout the cluster and are instead handled by the nodes independently

    // get the response entity for the specified action
    final ActionEntity entity = serviceFacade.getAction(id.getInteger());

    // generate the response
    return generateOkResponse(entity).build();
}
 
Example #7
Source File: ControllerServiceResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves the specified controller service.
 *
 * @param id The id of the controller service to retrieve
 * @return A controllerServiceEntity.
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Gets a controller service",
        response = ControllerServiceEntity.class,
        authorizations = {
                @Authorization(value = "Read - /controller-services/{uuid}", type = "")
        }
)
@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 getControllerService(
        @ApiParam(
                value = "The controller service id.",
                required = true
        )
        @PathParam("id") final String id) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable controllerService = lookup.getControllerService(id).getAuthorizable();
        controllerService.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });

    // get the controller service
    final ControllerServiceEntity entity = serviceFacade.getControllerService(id);
    populateRemainingControllerServiceEntityContent(entity);

    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #8
Source File: FlowFileQueueResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the content for the specified flowfile in the specified connection.
 *
 * @param clientId      Optional client id. If the client id is not specified, a new one will be generated. This value (whether specified or generated) is included in the response.
 * @param connectionId  The connection id
 * @param flowFileUuid  The flowfile uuid
 * @param clusterNodeId The cluster node id
 * @return The content stream
 * @throws InterruptedException if interrupted
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
@Path("{id}/flowfiles/{flowfile-uuid}/content")
@ApiOperation(
        value = "Gets the content for a FlowFile in a Connection.",
        authorizations = {
                @Authorization(value = "Read Source Data - /data/{component-type}/{uuid}", type = "")
        }
)
@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 downloadFlowFileContent(
        @ApiParam(
                value = "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response.",
                required = false
        )
        @QueryParam(CLIENT_ID) @DefaultValue(StringUtils.EMPTY) final ClientIdParameter clientId,
        @ApiParam(
                value = "The connection id.",
                required = true
        )
        @PathParam("id") final String connectionId,
        @ApiParam(
                value = "The flowfile uuid.",
                required = true
        )
        @PathParam("flowfile-uuid") final String flowFileUuid,
        @ApiParam(
                value = "The id of the node where the content exists if clustered.",
                required = false
        )
        @QueryParam("clusterNodeId") final String clusterNodeId) throws InterruptedException {

    // replicate if cluster manager
    if (isReplicateRequest()) {
        // determine where this request should be sent
        if (clusterNodeId == null) {
            throw new IllegalArgumentException("The id of the node in the cluster is required.");
        } else {
            // get the target node and ensure it exists
            final NodeIdentifier targetNode = getClusterCoordinator().getNodeIdentifier(clusterNodeId);
            if (targetNode == null) {
                throw new UnknownNodeException("The specified cluster node does not exist.");
            }

            return replicate(HttpMethod.GET, targetNode);
        }
    }

    // NOTE - deferred authorization so we can consider flowfile attributes in the access decision

    // get the uri of the request
    final String uri = generateResourceUri("flowfile-queues", connectionId, "flowfiles", flowFileUuid, "content");

    // get an input stream to the content
    final DownloadableContent content = serviceFacade.getContent(connectionId, flowFileUuid, uri);

    // generate a streaming response
    final StreamingOutput response = new StreamingOutput() {
        @Override
        public void write(final OutputStream output) throws IOException, WebApplicationException {
            try (InputStream is = content.getContent()) {
                // stream the content to the response
                StreamUtils.copy(is, output);

                // flush the response
                output.flush();
            }
        }
    };

    // use the appropriate content type
    String contentType = content.getType();
    if (contentType == null) {
        contentType = MediaType.APPLICATION_OCTET_STREAM;
    }

    return generateOkResponse(response).type(contentType).header("Content-Disposition", String.format("attachment; filename=\"%s\"", content.getFilename())).build();
}
 
Example #9
Source File: ProcessorResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Removes the specified processor.
 *
 * @param httpServletRequest request
 * @param version            The revision is used to verify the client is working with the latest version of the flow.
 * @param clientId           Optional client id. If the client id is not specified, a new one will be generated. This value (whether specified or generated) is included in the response.
 * @param id                 The id of the processor to remove.
 * @return A processorEntity.
 * @throws InterruptedException if interrupted
 */
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}")
@ApiOperation(
        value = "Deletes a processor",
        response = ProcessorEntity.class,
        authorizations = {
                @Authorization(value = "Write - /processors/{uuid}", type = ""),
                @Authorization(value = "Write - Parent Process Group - /process-groups/{uuid}", type = ""),
                @Authorization(value = "Read - any referenced Controller Services - /controller-services/{uuid}", type = "")
        }
)
@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 deleteProcessor(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The revision is used to verify the client is working with the latest version of the flow.",
                required = false
        )
        @QueryParam(VERSION) final LongParameter version,
        @ApiParam(
                value = "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response.",
                required = false
        )
        @QueryParam(CLIENT_ID) @DefaultValue(StringUtils.EMPTY) final ClientIdParameter clientId,
        @ApiParam(
                value = "The processor id.",
                required = true
        )
        @PathParam("id") final String id) throws InterruptedException {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.DELETE);
    }

    final ProcessorEntity requestProcessorEntity = new ProcessorEntity();
    requestProcessorEntity.setId(id);

    final Revision requestRevision = new Revision(version == null ? null : version.getLong(), clientId.getClientId(), id);
    return withWriteLock(
            serviceFacade,
            requestProcessorEntity,
            requestRevision,
            lookup -> {
                final ConfigurableComponentAuthorizable processor = lookup.getProcessor(id);

                // ensure write permission to the processor
                processor.getAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());

                // ensure write permission to the parent process group
                processor.getAuthorizable().getParentAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());

                // verify any referenced services
                AuthorizeControllerServiceReference.authorizeControllerServiceReferences(processor, authorizer, lookup, false);
            },
            () -> serviceFacade.verifyDeleteProcessor(id),
            (revision, processorEntity) -> {
                // delete the processor
                final ProcessorEntity entity = serviceFacade.deleteProcessor(revision, processorEntity.getId());

                // generate the response
                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #10
Source File: SnippetResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Removes the specified snippet.
 *
 * @param httpServletRequest request
 * @param snippetId          The id of the snippet to remove.
 * @return A entity containing the client id and an updated revision.
 */
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Deletes the components in a snippet and discards the snippet",
        response = SnippetEntity.class,
        authorizations = {
                @Authorization(value = "Write - /{component-type}/{uuid} - For each component in the Snippet and their descendant components", type = ""),
                @Authorization(value = "Write - Parent Process Group - /process-groups/{uuid}", type = ""),
        }
)
@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 deleteSnippet(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The snippet id.",
                required = true
        )
        @PathParam("id") final String snippetId) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.DELETE);
    }

    final ComponentEntity requestEntity = new ComponentEntity();
    requestEntity.setId(snippetId);

    // get the revision from this snippet
    final Set<Revision> requestRevisions = serviceFacade.getRevisionsFromSnippet(snippetId);
    return withWriteLock(
            serviceFacade,
            requestEntity,
            requestRevisions,
            lookup -> {
                // ensure write permission to every component in the snippet excluding referenced services
                final SnippetAuthorizable snippet = lookup.getSnippet(snippetId);
                authorizeSnippet(snippet, authorizer, lookup, RequestAction.WRITE, true, false);

                // ensure write permission to the parent process group
                snippet.getParentProcessGroup().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            () -> serviceFacade.verifyDeleteSnippet(snippetId, requestRevisions.stream().map(rev -> rev.getComponentId()).collect(Collectors.toSet())),
            (revisions, entity) -> {
                // delete the specified snippet
                final SnippetEntity snippetEntity = serviceFacade.deleteSnippet(revisions, entity.getId());
                return clusterContext(generateOkResponse(snippetEntity)).build();
            }
    );
}
 
Example #11
Source File: ConnectionResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Removes the specified connection.
 *
 * @param httpServletRequest request
 * @param version            The revision is used to verify the client is working with the latest version of the flow.
 * @param clientId           Optional client id. If the client id is not specified, a new one will be generated. This value (whether specified or generated) is included in the response.
 * @param id                 The id of the connection.
 * @return An Entity containing the client id and an updated revision.
 * @throws InterruptedException if interrupted
 */
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}")
@ApiOperation(
        value = "Deletes a connection",
        response = ConnectionEntity.class,
        authorizations = {
                @Authorization(value = "Write Source - /{component-type}/{uuid}", type = ""),
                @Authorization(value = "Write - Parent Process Group - /process-groups/{uuid}", type = ""),
                @Authorization(value = "Write Destination - /{component-type}/{uuid}", type = "")
        }
)
@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 deleteConnection(
        @Context HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The revision is used to verify the client is working with the latest version of the flow.",
                required = false
        )
        @QueryParam(VERSION) final LongParameter version,
        @ApiParam(
                value = "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response.",
                required = false
        )
        @QueryParam(CLIENT_ID) @DefaultValue(StringUtils.EMPTY) final ClientIdParameter clientId,
        @ApiParam(
                value = "The connection id.",
                required = true
        )
        @PathParam("id") final String id) throws InterruptedException {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.DELETE);
    }

    // determine the specified version
    final Long clientVersion = version == null ? null : version.getLong();
    final Revision requestRevision = new Revision(clientVersion, clientId.getClientId(), id);

    final ConnectionEntity requestConnectionEntity = new ConnectionEntity();
    requestConnectionEntity.setId(id);

    // get the current user
    return withWriteLock(
            serviceFacade,
            requestConnectionEntity,
            requestRevision,
            lookup -> {
                // verifies write access to the source and destination
                final Authorizable authorizable = lookup.getConnection(id).getAuthorizable();

                // ensure write permission to the connection
                authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());

                // ensure write permission to the parent process group
                authorizable.getParentAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            () -> serviceFacade.verifyDeleteConnection(id),
            (revision, connectionEntity) -> {
                // delete the connection
                final ConnectionEntity entity = serviceFacade.deleteConnection(revision, connectionEntity.getId());

                // generate the response
                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #12
Source File: FlowFileQueueResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the specified flowfile from the specified connection.
 *
 * @param connectionId  The connection id
 * @param flowFileUuid  The flowfile uuid
 * @param clusterNodeId The cluster node id where the flowfile resides
 * @return a flowFileDTO
 * @throws InterruptedException if interrupted
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/flowfiles/{flowfile-uuid}")
@ApiOperation(
        value = "Gets a FlowFile from a Connection.",
        authorizations = {
                @Authorization(value = "Read Source Data - /data/{component-type}/{uuid}", type = "")
        }
)
@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 getFlowFile(
        @ApiParam(
                value = "The connection id.",
                required = true
        )
        @PathParam("id") final String connectionId,
        @ApiParam(
                value = "The flowfile uuid.",
                required = true
        )
        @PathParam("flowfile-uuid") final String flowFileUuid,
        @ApiParam(
                value = "The id of the node where the content exists if clustered.",
                required = false
        )
        @QueryParam("clusterNodeId") final String clusterNodeId) throws InterruptedException {

    // replicate if cluster manager
    if (isReplicateRequest()) {
        // determine where this request should be sent
        if (clusterNodeId == null) {
            throw new IllegalArgumentException("The id of the node in the cluster is required.");
        } else {
            // get the target node and ensure it exists
            final NodeIdentifier targetNode = getClusterCoordinator().getNodeIdentifier(clusterNodeId);
            if (targetNode == null) {
                throw new UnknownNodeException("The specified cluster node does not exist.");
            }

            return replicate(HttpMethod.GET, targetNode);
        }
    }

    // NOTE - deferred authorization so we can consider flowfile attributes in the access decision

    // get the flowfile
    final FlowFileDTO flowfileDto = serviceFacade.getFlowFile(connectionId, flowFileUuid);
    populateRemainingFlowFileContent(connectionId, flowfileDto);

    // create the response entity
    final FlowFileEntity entity = new FlowFileEntity();
    entity.setFlowFile(flowfileDto);

    return generateOkResponse(entity).build();
}
 
Example #13
Source File: ProcessGroupResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Gets all the connections.
 *
 * @return A connectionsEntity.
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/connections")
@ApiOperation(
        value = "Gets all connections",
        response = ConnectionsEntity.class,
        authorizations = {
                @Authorization(value = "Read - /process-groups/{uuid}", type = "")
        }
)
@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 getConnections(
        @ApiParam(
                value = "The process group id.",
                required = true
        )
        @PathParam("id") String groupId) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
        processGroup.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });

    // all of the relationships for the specified source processor
    Set<ConnectionEntity> connections = serviceFacade.getConnections(groupId);

    // create the client response entity
    ConnectionsEntity entity = new ConnectionsEntity();
    entity.setConnections(connectionResource.populateRemainingConnectionEntitiesContent(connections));

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #14
Source File: CountersResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Update the specified counter. This will reset the counter value to 0.
 *
 * @param httpServletRequest request
 * @param id                 The id of the counter.
 * @return A counterEntity.
 */
@PUT
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Updates the specified counter. This will reset the counter value to 0",
        notes = NON_GUARANTEED_ENDPOINT,
        response = CounterEntity.class,
        authorizations = {
                @Authorization(value = "Write - /counters", type = "")
        }
)
@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 updateCounter(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The id of the counter."
        )
        @PathParam("id") final String id) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT);
    }

    final ComponentEntity requestComponentEntity = new ComponentEntity();
    requestComponentEntity.setId(id);

    return withWriteLock(
            serviceFacade,
            requestComponentEntity,
            lookup -> {
                authorizeCounters(RequestAction.WRITE);
            },
            null,
            (componentEntity) -> {
                // reset the specified counter
                final CounterDTO counter = serviceFacade.updateCounter(componentEntity.getId());

                // create the response entity
                final CounterEntity entity = new CounterEntity();
                entity.setCounter(counter);

                // generate the response
                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #15
Source File: ProcessGroupResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Removes the specified process group reference.
 *
 * @param httpServletRequest request
 * @param version            The revision is used to verify the client is working with the latest version of the flow.
 * @param clientId           Optional client id. If the client id is not specified, a new one will be generated. This value (whether specified or generated) is included in the response.
 * @param id                 The id of the process group to be removed.
 * @return A processGroupEntity.
 */
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Deletes a process group",
        response = ProcessGroupEntity.class,
        authorizations = {
                @Authorization(value = "Write - /process-groups/{uuid}", type = ""),
                @Authorization(value = "Write - Parent Process Group - /process-groups/{uuid}", type = ""),
                @Authorization(value = "Read - any referenced Controller Services by any encapsulated components - /controller-services/{uuid}", type = ""),
                @Authorization(value = "Write - /{component-type}/{uuid} - For all encapsulated components", type = "")
        }
)
@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 removeProcessGroup(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The revision is used to verify the client is working with the latest version of the flow.",
                required = false
        )
        @QueryParam(VERSION) final LongParameter version,
        @ApiParam(
                value = "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response.",
                required = false
        )
        @QueryParam(CLIENT_ID) @DefaultValue(StringUtils.EMPTY) final ClientIdParameter clientId,
        @ApiParam(
                value = "The process group id.",
                required = true
        )
        @PathParam("id") final String id) {

    // replicate if cluster manager
    if (isReplicateRequest()) {
        return replicate(HttpMethod.DELETE);
    }

    final ProcessGroupEntity requestProcessGroupEntity = new ProcessGroupEntity();
    requestProcessGroupEntity.setId(id);

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = new Revision(version == null ? null : version.getLong(), clientId.getClientId(), id);
    return withWriteLock(
            serviceFacade,
            requestProcessGroupEntity,
            requestRevision,
            lookup -> {
                final ProcessGroupAuthorizable processGroupAuthorizable = lookup.getProcessGroup(id);

                // ensure write to this process group and all encapsulated components including templates and controller services. additionally, ensure
                // read to any referenced services by encapsulated components
                authorizeProcessGroup(processGroupAuthorizable, authorizer, lookup, RequestAction.WRITE, true, true, true, false);

                // ensure write permission to the parent process group, if applicable... if this is the root group the
                // request will fail later but still need to handle authorization here
                final Authorizable parentAuthorizable = processGroupAuthorizable.getAuthorizable().getParentAuthorizable();
                if (parentAuthorizable != null) {
                    parentAuthorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
                }
            },
            () -> serviceFacade.verifyDeleteProcessGroup(id),
            (revision, processGroupEntity) -> {
                // delete the process group
                final ProcessGroupEntity entity = serviceFacade.deleteProcessGroup(revision, processGroupEntity.getId());

                // create the response
                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #16
Source File: ProcessorResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the specified processor with the specified values.
 *
 * @param httpServletRequest request
 * @param id                 The id of the processor to update.
 * @param requestProcessorEntity    A processorEntity.
 * @return A processorEntity.
 * @throws InterruptedException if interrupted
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}")
@ApiOperation(
        value = "Updates a processor",
        response = ProcessorEntity.class,
        authorizations = {
                @Authorization(value = "Write - /processors/{uuid}", type = ""),
                @Authorization(value = "Read - any referenced Controller Services if this request changes the reference - /controller-services/{uuid}", type = "")
        }
)
@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 updateProcessor(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The processor id.",
                required = true
        )
        @PathParam("id") final String id,
        @ApiParam(
                value = "The processor configuration details.",
                required = true
        ) final ProcessorEntity requestProcessorEntity) throws InterruptedException {

    if (requestProcessorEntity == null || requestProcessorEntity.getComponent() == null) {
        throw new IllegalArgumentException("Processor details must be specified.");
    }

    if (requestProcessorEntity.getRevision() == null) {
        throw new IllegalArgumentException("Revision must be specified.");
    }

    // ensure the same id is being used
    final ProcessorDTO requestProcessorDTO = requestProcessorEntity.getComponent();
    if (!id.equals(requestProcessorDTO.getId())) {
        throw new IllegalArgumentException(String.format("The processor id (%s) in the request body does "
                + "not equal the processor id of the requested resource (%s).", requestProcessorDTO.getId(), id));
    }

    final PositionDTO proposedPosition = requestProcessorDTO.getPosition();
    if (proposedPosition != null) {
        if (proposedPosition.getX() == null || proposedPosition.getY() == null) {
            throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified.");
        }
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestProcessorEntity);
    }

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = getRevision(requestProcessorEntity, id);
    return withWriteLock(
            serviceFacade,
            requestProcessorEntity,
            requestRevision,
            lookup -> {
                final NiFiUser user = NiFiUserUtils.getNiFiUser();

                final ConfigurableComponentAuthorizable authorizable = lookup.getProcessor(id);
                authorizable.getAuthorizable().authorize(authorizer, RequestAction.WRITE, user);

                final ProcessorConfigDTO config = requestProcessorDTO.getConfig();
                if (config != null) {
                    AuthorizeControllerServiceReference.authorizeControllerServiceReferences(config.getProperties(), authorizable, authorizer, lookup);
                }
            },
            () -> serviceFacade.verifyUpdateProcessor(requestProcessorDTO),
            (revision, processorEntity) -> {
                final ProcessorDTO processorDTO = processorEntity.getComponent();

                // update the processor
                final ProcessorEntity entity = serviceFacade.updateProcessor(revision, processorDTO);
                populateRemainingProcessorEntityContent(entity);

                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #17
Source File: FlowFileQueueResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a request to list the flowfiles in the queue of the specified connection.
 *
 * @param httpServletRequest request
 * @param id                 The id of the connection
 * @return A listRequestEntity
 */
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/listing-requests")
@ApiOperation(
        value = "Lists the contents of the queue in this connection.",
        response = ListingRequestEntity.class,
        authorizations = {
                @Authorization(value = "Read Source Data - /data/{component-type}/{uuid}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 202, message = "The request has been accepted. A HTTP response header will contain the URI where the response can be polled."),
                @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 createFlowFileListing(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The connection id.",
                required = true
        )
        @PathParam("id") final String id) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.POST);
    }

    final ConnectionEntity requestConnectionEntity = new ConnectionEntity();
    requestConnectionEntity.setId(id);

    return withWriteLock(
            serviceFacade,
            requestConnectionEntity,
            lookup -> {
                final ConnectionAuthorizable connAuth = lookup.getConnection(id);
                final Authorizable dataAuthorizable = connAuth.getSourceData();
                dataAuthorizable.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
            },
            () -> serviceFacade.verifyListQueue(id),
            (connectionEntity) -> {
                // ensure the id is the same across the cluster
                final String listingRequestId = generateUuid();

                // submit the listing request
                final ListingRequestDTO listingRequest = serviceFacade.createFlowFileListingRequest(connectionEntity.getId(), listingRequestId);
                populateRemainingFlowFileListingContent(connectionEntity.getId(), listingRequest);

                // create the response entity
                final ListingRequestEntity entity = new ListingRequestEntity();
                entity.setListingRequest(listingRequest);

                // generate the URI where the response will be
                final URI location = URI.create(listingRequest.getUri());
                return Response.status(Status.ACCEPTED).location(location).entity(entity).build();
            }
    );
}
 
Example #18
Source File: ProcessGroupResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new output port.
 *
 * @param httpServletRequest request
 * @param groupId            The group id
 * @param requestPortEntity         A outputPortEntity.
 * @return A outputPortEntity.
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/output-ports")
@ApiOperation(
        value = "Creates an output port",
        response = PortEntity.class,
        authorizations = {
                @Authorization(value = "Write - /process-groups/{uuid}", type = "")
        }
)
@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 createOutputPort(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The process group id.",
                required = true
        )
        @PathParam("id") final String groupId,
        @ApiParam(
                value = "The output port configuration.",
                required = true
        ) final PortEntity requestPortEntity) {

    if (requestPortEntity == null || requestPortEntity.getComponent() == null) {
        throw new IllegalArgumentException("Port details must be specified.");
    }

    if (requestPortEntity.getRevision() == null || (requestPortEntity.getRevision().getVersion() == null || requestPortEntity.getRevision().getVersion() != 0)) {
        throw new IllegalArgumentException("A revision of 0 must be specified when creating a new Output port.");
    }

    if (requestPortEntity.getComponent().getId() != null) {
        throw new IllegalArgumentException("Output port ID cannot be specified.");
    }

    final PositionDTO proposedPosition = requestPortEntity.getComponent().getPosition();
    if (proposedPosition != null) {
        if (proposedPosition.getX() == null || proposedPosition.getY() == null) {
            throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified.");
        }
    }

    if (requestPortEntity.getComponent().getParentGroupId() != null && !groupId.equals(requestPortEntity.getComponent().getParentGroupId())) {
        throw new IllegalArgumentException(String.format("If specified, the parent process group id %s must be the same as specified in the URI %s",
                requestPortEntity.getComponent().getParentGroupId(), groupId));
    }
    requestPortEntity.getComponent().setParentGroupId(groupId);

    if (isReplicateRequest()) {
        return replicate(HttpMethod.POST, requestPortEntity);
    }

    return withWriteLock(
            serviceFacade,
            requestPortEntity,
            lookup -> {
                final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
                processGroup.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            null,
            portEntity -> {
                // set the processor id as appropriate
                portEntity.getComponent().setId(generateUuid());

                // create the output port and generate the json
                final Revision revision = getRevision(portEntity, portEntity.getComponent().getId());
                final PortEntity entity = serviceFacade.createOutputPort(revision, groupId, portEntity.getComponent());
                outputPortResource.populateRemainingOutputPortEntityContent(entity);

                // build the response
                return clusterContext(generateCreatedResponse(URI.create(entity.getUri()), entity)).build();
            }
    );
}
 
Example #19
Source File: ProcessGroupResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves all the processors in this NiFi.
 *
 * @param groupId group id
 * @return A processorsEntity.
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/processors")
@ApiOperation(
        value = "Gets all processors",
        response = ProcessorsEntity.class,
        authorizations = {
                @Authorization(value = "Read - /process-groups/{uuid}", type = "")
        }
)
@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 getProcessors(
        @ApiParam(
                value = "The process group id.",
                required = true
        )
        @PathParam("id") final String groupId) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
        processGroup.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });

    // get the processors
    final Set<ProcessorEntity> processors = serviceFacade.getProcessors(groupId);

    // create the response entity
    final ProcessorsEntity entity = new ProcessorsEntity();
    entity.setProcessors(processorResource.populateRemainingProcessorEntitiesContent(processors));

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #20
Source File: FlowResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves all the of controller services in this NiFi.
 *
 * @return A controllerServicesEntity.
 * @throws InterruptedException if interrupted
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("process-groups/{id}/controller-services")
@ApiOperation(
        value = "Gets all controller services",
        response = ControllerServicesEntity.class,
        authorizations = {
                @Authorization(value = "Read - /flow", type = "")
        }
)
@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 getControllerServicesFromGroup(
        @ApiParam(
                value = "The process group id.",
                required = true
        )
        @PathParam("id") String groupId) throws InterruptedException {

    authorizeFlow();

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // get all the controller services
    final Set<ControllerServiceEntity> controllerServices = serviceFacade.getControllerServices(groupId);
    controllerServiceResource.populateRemainingControllerServiceEntitiesContent(controllerServices);

    // create the response entity
    final ControllerServicesEntity entity = new ControllerServicesEntity();
    entity.setCurrentTime(new Date());
    entity.setControllerServices(controllerServices);

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #21
Source File: OutputPortResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Removes the specified output port.
 *
 * @param httpServletRequest request
 * @param version            The revision is used to verify the client is working with the latest version of the flow.
 * @param clientId           Optional client id. If the client id is not specified, a new one will be generated. This value (whether specified or generated) is included in the response.
 * @param id                 The id of the output port to remove.
 * @return A outputPortEntity.
 */
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Deletes an output port",
        response = PortEntity.class,
        authorizations = {
                @Authorization(value = "Write - /output-ports/{uuid}", type = ""),
                @Authorization(value = "Write - Parent Process Group - /process-groups/{uuid}", type = "")
        }
)
@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 removeOutputPort(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The revision is used to verify the client is working with the latest version of the flow.",
                required = false
        )
        @QueryParam(VERSION) final LongParameter version,
        @ApiParam(
                value = "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response.",
                required = false
        )
        @QueryParam(CLIENT_ID) @DefaultValue(StringUtils.EMPTY) final ClientIdParameter clientId,
        @ApiParam(
                value = "The output port id.",
                required = true
        )
        @PathParam("id") final String id) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.DELETE);
    }

    final PortEntity requestPortEntity = new PortEntity();
    requestPortEntity.setId(id);

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = new Revision(version == null ? null : version.getLong(), clientId.getClientId(), id);
    return withWriteLock(
            serviceFacade,
            requestPortEntity,
            requestRevision,
            lookup -> {
                final Authorizable outputPort = lookup.getOutputPort(id);

                // ensure write permission to the output port
                outputPort.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());

                // ensure write permission to the parent process group
                outputPort.getParentAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            () -> serviceFacade.verifyDeleteOutputPort(id),
            (revision, portEntity) -> {
                // delete the specified output port
                final PortEntity entity = serviceFacade.deleteOutputPort(revision, portEntity.getId());
                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #22
Source File: OutputPortResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the specified output port.
 *
 * @param httpServletRequest request
 * @param id                 The id of the output port to update.
 * @param requestPortEntity         A outputPortEntity.
 * @return A outputPortEntity.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Updates an output port",
        response = PortEntity.class,
        authorizations = {
                @Authorization(value = "Write - /output-ports/{uuid}", type = "")
        }
)
@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 updateOutputPort(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The output port id.",
                required = true
        )
        @PathParam("id") final String id,
        @ApiParam(
                value = "The output port configuration details.",
                required = true
        ) final PortEntity requestPortEntity) {

    if (requestPortEntity == null || requestPortEntity.getComponent() == null) {
        throw new IllegalArgumentException("Output port details must be specified.");
    }

    if (requestPortEntity.getRevision() == null) {
        throw new IllegalArgumentException("Revision must be specified.");
    }

    // ensure the ids are the same
    PortDTO requestPortDTO = requestPortEntity.getComponent();
    if (!id.equals(requestPortDTO.getId())) {
        throw new IllegalArgumentException(String.format("The output port id (%s) in the request body does not equal the "
                + "output port id of the requested resource (%s).", requestPortDTO.getId(), id));
    }

    final PositionDTO proposedPosition = requestPortDTO.getPosition();
    if (proposedPosition != null) {
        if (proposedPosition.getX() == null || proposedPosition.getY() == null) {
            throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified.");
        }
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestPortEntity);
    }

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = getRevision(requestPortEntity, id);
    return withWriteLock(
            serviceFacade,
            requestPortEntity,
            requestRevision,
            lookup -> {
                Authorizable authorizable = lookup.getOutputPort(id);
                authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            () -> serviceFacade.verifyUpdateOutputPort(requestPortDTO),
            (revision, portEntity) -> {
                final PortDTO portDTO = portEntity.getComponent();

                // update the output port
                final PortEntity entity = serviceFacade.updateOutputPort(revision, portDTO);
                populateRemainingOutputPortEntityContent(entity);

                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #23
Source File: ProcessGroupResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Instantiates the specified template within this ProcessGroup. The template instance that is instantiated cannot be referenced at a later time, therefore there is no
 * corresponding URI. Instead the request URI is returned.
 * <p>
 * Alternatively, we could have performed a PUT request. However, PUT requests are supposed to be idempotent and this endpoint is certainly not.
 *
 * @param httpServletRequest               request
 * @param groupId                          The group id
 * @param requestInstantiateTemplateRequestEntity The instantiate template request
 * @return A flowEntity.
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/template-instance")
@ApiOperation(
        value = "Instantiates a template",
        response = FlowEntity.class,
        authorizations = {
                @Authorization(value = "Write - /process-groups/{uuid}", type = ""),
                @Authorization(value = "Read - /templates/{uuid}", type = ""),
                @Authorization(value = "Write - if the template contains any restricted components - /restricted-components", type = "")
        }
)
@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 instantiateTemplate(
        @Context HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The process group id.",
                required = true
        )
        @PathParam("id") String groupId,
        @ApiParam(
                value = "The instantiate template request.",
                required = true
        ) InstantiateTemplateRequestEntity requestInstantiateTemplateRequestEntity) {

    // ensure the position has been specified
    if (requestInstantiateTemplateRequestEntity == null || requestInstantiateTemplateRequestEntity.getOriginX() == null || requestInstantiateTemplateRequestEntity.getOriginY() == null) {
        throw new IllegalArgumentException("The  origin position (x, y) must be specified");
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.POST, requestInstantiateTemplateRequestEntity);
    }

    return withWriteLock(
            serviceFacade,
            requestInstantiateTemplateRequestEntity,
            lookup -> {
                final NiFiUser user = NiFiUserUtils.getNiFiUser();

                // ensure write on the group
                final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
                processGroup.authorize(authorizer, RequestAction.WRITE, user);

                // ensure read on the template
                final TemplateAuthorizable template = lookup.getTemplate(requestInstantiateTemplateRequestEntity.getTemplateId());
                template.getAuthorizable().authorize(authorizer, RequestAction.READ, user);

                // flag to only perform the restricted check once, atomic reference so we can mark final and use in lambda
                final AtomicBoolean restrictedCheckPerformed = new AtomicBoolean(false);
                final Consumer<ConfigurableComponentAuthorizable> authorizeRestricted = authorizable -> {
                    if (authorizable.isRestricted() && restrictedCheckPerformed.compareAndSet(false, true)) {
                        lookup.getRestrictedComponents().authorize(authorizer, RequestAction.WRITE, user);
                    }
                };

                // ensure restricted access if necessary
                template.getEncapsulatedProcessors().forEach(authorizeRestricted);
                template.getEncapsulatedControllerServices().forEach(authorizeRestricted);
            },
            null,
            instantiateTemplateRequestEntity -> {
                // create the template and generate the json
                final FlowEntity entity = serviceFacade.createTemplateInstance(groupId, instantiateTemplateRequestEntity.getOriginX(),
                        instantiateTemplateRequestEntity.getOriginY(), instantiateTemplateRequestEntity.getTemplateId(), getIdGenerationSeed().orElse(null));

                final FlowDTO flowSnippet = entity.getFlow();

                // prune response as necessary
                for (ProcessGroupEntity childGroupEntity : flowSnippet.getProcessGroups()) {
                    childGroupEntity.getComponent().setContents(null);
                }

                // create the response entity
                populateRemainingSnippetContent(flowSnippet);

                // generate the response
                return clusterContext(generateCreatedResponse(getAbsolutePath(), entity)).build();
            }
    );
}
 
Example #24
Source File: ReportingTaskResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Removes the specified reporting task.
 *
 * @param httpServletRequest request
 * @param version            The revision is used to verify the client is working with
 *                           the latest version of the flow.
 * @param clientId           Optional client id. If the client id is not specified, a
 *                           new one will be generated. This value (whether specified or generated) is
 *                           included in the response.
 * @param id                 The id of the reporting task to remove.
 * @return A entity containing the client id and an updated revision.
 */
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Deletes a reporting task",
        response = ReportingTaskEntity.class,
        authorizations = {
                @Authorization(value = "Write - /reporting-tasks/{uuid}", type = ""),
                @Authorization(value = "Write - /controller", type = ""),
                @Authorization(value = "Read - any referenced Controller Services - /controller-services/{uuid}", type = "")
        }
)
@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 removeReportingTask(
        @Context HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The revision is used to verify the client is working with the latest version of the flow.",
                required = false
        )
        @QueryParam(VERSION) LongParameter version,
        @ApiParam(
                value = "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response.",
                required = false
        )
        @QueryParam(CLIENT_ID) @DefaultValue(StringUtils.EMPTY) ClientIdParameter clientId,
        @ApiParam(
                value = "The reporting task id.",
                required = true
        )
        @PathParam("id") String id) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.DELETE);
    }

    final ReportingTaskEntity requestReportingTaskEntity = new ReportingTaskEntity();
    requestReportingTaskEntity.setId(id);

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = new Revision(version == null ? null : version.getLong(), clientId.getClientId(), id);
    return withWriteLock(
            serviceFacade,
            requestReportingTaskEntity,
            requestRevision,
            lookup -> {
                final ConfigurableComponentAuthorizable reportingTask = lookup.getReportingTask(id);

                // ensure write permission to the reporting task
                reportingTask.getAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());

                // ensure write permission to the parent process group
                reportingTask.getAuthorizable().getParentAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());

                // verify any referenced services
                AuthorizeControllerServiceReference.authorizeControllerServiceReferences(reportingTask, authorizer, lookup, false);
            },
            () -> serviceFacade.verifyDeleteReportingTask(id),
            (revision, reportingTaskEntity) -> {
                // delete the specified reporting task
                final ReportingTaskEntity entity = serviceFacade.deleteReportingTask(revision, reportingTaskEntity.getId());
                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #25
Source File: ReportingTaskResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the specified a Reporting Task.
 *
 * @param httpServletRequest  request
 * @param id                  The id of the reporting task to update.
 * @param requestReportingTaskEntity A reportingTaskEntity.
 * @return A reportingTaskEntity.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Updates a reporting task",
        response = ReportingTaskEntity.class,
        authorizations = {
                @Authorization(value = "Write - /reporting-tasks/{uuid}", type = ""),
                @Authorization(value = "Read - any referenced Controller Services if this request changes the reference - /controller-services/{uuid}", type = "")
        }
)
@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 updateReportingTask(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The reporting task id.",
                required = true
        )
        @PathParam("id") final String id,
        @ApiParam(
                value = "The reporting task configuration details.",
                required = true
        ) final ReportingTaskEntity requestReportingTaskEntity) {

    if (requestReportingTaskEntity == null || requestReportingTaskEntity.getComponent() == null) {
        throw new IllegalArgumentException("Reporting task details must be specified.");
    }

    if (requestReportingTaskEntity.getRevision() == null) {
        throw new IllegalArgumentException("Revision must be specified.");
    }

    // ensure the ids are the same
    final ReportingTaskDTO requestReportingTaskDTO = requestReportingTaskEntity.getComponent();
    if (!id.equals(requestReportingTaskDTO.getId())) {
        throw new IllegalArgumentException(String.format("The reporting task id (%s) in the request body does not equal the "
                + "reporting task id of the requested resource (%s).", requestReportingTaskDTO.getId(), id));
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestReportingTaskEntity);
    }

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = getRevision(requestReportingTaskEntity, id);
    return withWriteLock(
            serviceFacade,
            requestReportingTaskEntity,
            requestRevision,
            lookup -> {
                // authorize reporting task
                final ConfigurableComponentAuthorizable authorizable = lookup.getReportingTask(id);
                authorizable.getAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());

                // authorize any referenced services
                AuthorizeControllerServiceReference.authorizeControllerServiceReferences(requestReportingTaskDTO.getProperties(), authorizable, authorizer, lookup);
            },
            () -> serviceFacade.verifyUpdateReportingTask(requestReportingTaskDTO),
            (revision, reportingTaskEntity) -> {
                final ReportingTaskDTO reportingTaskDTO = reportingTaskEntity.getComponent();

                // update the reporting task
                final ReportingTaskEntity entity = serviceFacade.updateReportingTask(revision, reportingTaskDTO);
                populateRemainingReportingTaskEntityContent(entity);

                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #26
Source File: ReportingTaskResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Clears the state for a reporting task.
 *
 * @param httpServletRequest servlet request
 * @param id                 The id of the reporting task
 * @return a componentStateEntity
 */
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/state/clear-requests")
@ApiOperation(
        value = "Clears the state for a reporting task",
        response = ComponentStateDTO.class,
        authorizations = {
                @Authorization(value = "Write - /reporting-tasks/{uuid}", type = "")
        }
)
@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 clearState(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The reporting task id.",
                required = true
        )
        @PathParam("id") final String id) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.POST);
    }

    final ReportingTaskEntity requestReportTaskEntity = new ReportingTaskEntity();
    requestReportTaskEntity.setId(id);

    return withWriteLock(
            serviceFacade,
            requestReportTaskEntity,
            lookup -> {
                final Authorizable processor = lookup.getReportingTask(id).getAuthorizable();
                processor.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            () -> serviceFacade.verifyCanClearReportingTaskState(id),
            (reportingTaskEntity) -> {
                // get the component state
                serviceFacade.clearReportingTaskState(reportingTaskEntity.getId());

                // generate the response entity
                final ComponentStateEntity entity = new ComponentStateEntity();

                // generate the response
                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #27
Source File: ReportingTaskResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the state for a reporting task.
 *
 * @param id The id of the reporting task
 * @return a componentStateEntity
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/state")
@ApiOperation(
        value = "Gets the state for a reporting task",
        response = ComponentStateDTO.class,
        authorizations = {
                @Authorization(value = "Write - /reporting-tasks/{uuid}", type = "")
        }
)
@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 getState(
        @ApiParam(
                value = "The reporting task id.",
                required = true
        )
        @PathParam("id") final String id) {

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable reportingTask = lookup.getReportingTask(id).getAuthorizable();
        reportingTask.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
    });

    // get the component state
    final ComponentStateDTO state = serviceFacade.getReportingTaskState(id);

    // generate the response entity
    final ComponentStateEntity entity = new ComponentStateEntity();
    entity.setComponentState(state);

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #28
Source File: ReportingTaskResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the descriptor for the specified property.
 *
 * @param id           The id of the reporting task.
 * @param propertyName The property
 * @return a propertyDescriptorEntity
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/descriptors")
@ApiOperation(
        value = "Gets a reporting task property descriptor",
        response = PropertyDescriptorEntity.class,
        authorizations = {
                @Authorization(value = "Read - /reporting-tasks/{uuid}", type = "")
        }
)
@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 getPropertyDescriptor(
        @ApiParam(
                value = "The reporting task id.",
                required = true
        )
        @PathParam("id") final String id,
        @ApiParam(
                value = "The property name.",
                required = true
        )
        @QueryParam("propertyName") final String propertyName) {

    // ensure the property name is specified
    if (propertyName == null) {
        throw new IllegalArgumentException("The property name must be specified.");
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable reportingTask = lookup.getReportingTask(id).getAuthorizable();
        reportingTask.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });

    // get the property descriptor
    final PropertyDescriptorDTO descriptor = serviceFacade.getReportingTaskPropertyDescriptor(id, propertyName);

    // generate the response entity
    final PropertyDescriptorEntity entity = new PropertyDescriptorEntity();
    entity.setPropertyDescriptor(descriptor);

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #29
Source File: AccessPolicyResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Removes the specified access policy.
 *
 * @param httpServletRequest request
 * @param version            The revision is used to verify the client is working with
 *                           the latest version of the flow.
 * @param clientId           Optional client id. If the client id is not specified, a
 *                           new one will be generated. This value (whether specified or generated) is
 *                           included in the response.
 * @param id                 The id of the access policy to remove.
 * @return A entity containing the client id and an updated revision.
 */
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Deletes an access policy",
        response = AccessPolicyEntity.class,
        authorizations = {
                @Authorization(value = "Write - /policies/{resource}", type = ""),
                @Authorization(value = "Write - Policy of the parent resource - /policies/{resource}", type = "")
        }
)
@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 removeAccessPolicy(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The revision is used to verify the client is working with the latest version of the flow.",
                required = false
        )
        @QueryParam(VERSION) final LongParameter version,
        @ApiParam(
                value = "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response.",
                required = false
        )
        @QueryParam(CLIENT_ID) @DefaultValue(StringUtils.EMPTY) final ClientIdParameter clientId,
        @ApiParam(
                value = "The access policy id.",
                required = true
        )
        @PathParam("id") final String id) {

    // ensure we're running with a configurable authorizer
    if (!(authorizer instanceof AbstractPolicyBasedAuthorizer)) {
        throw new IllegalStateException(AccessPolicyDAO.MSG_NON_ABSTRACT_POLICY_BASED_AUTHORIZER);
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.DELETE);
    }

    final AccessPolicyEntity requestAccessPolicyEntity = new AccessPolicyEntity();
    requestAccessPolicyEntity.setId(id);

    // handle expects request (usually from the cluster manager)
    final Revision requestRevision = new Revision(version == null ? null : version.getLong(), clientId.getClientId(), id);
    return withWriteLock(
            serviceFacade,
            requestAccessPolicyEntity,
            requestRevision,
            lookup -> {
                final Authorizable accessPolicy = lookup.getAccessPolicyById(id);

                // ensure write permission to the access policy
                accessPolicy.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());

                // ensure write permission to the policy for the parent process group
                accessPolicy.getParentAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            null,
            (revision, accessPolicyEntity) -> {
                // delete the specified access policy
                final AccessPolicyEntity entity = serviceFacade.deleteAccessPolicy(revision, accessPolicyEntity.getId());
                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}
 
Example #30
Source File: AccessPolicyResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Updates an access policy.
 *
 * @param httpServletRequest request
 * @param id                 The id of the access policy to update.
 * @param requestAccessPolicyEntity An accessPolicyEntity.
 * @return An accessPolicyEntity.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(
        value = "Updates a access policy",
        response = AccessPolicyEntity.class,
        authorizations = {
                @Authorization(value = "Write - /policies/{resource}", type = "")
        }
)
@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 updateAccessPolicy(
        @Context final HttpServletRequest httpServletRequest,
        @ApiParam(
                value = "The access policy id.",
                required = true
        )
        @PathParam("id") final String id,
        @ApiParam(
                value = "The access policy configuration details.",
                required = true
        ) final AccessPolicyEntity requestAccessPolicyEntity) {

    // ensure we're running with a configurable authorizer
    if (!(authorizer instanceof AbstractPolicyBasedAuthorizer)) {
        throw new IllegalStateException(AccessPolicyDAO.MSG_NON_ABSTRACT_POLICY_BASED_AUTHORIZER);
    }

    if (requestAccessPolicyEntity == null || requestAccessPolicyEntity.getComponent() == null) {
        throw new IllegalArgumentException("Access policy details must be specified.");
    }

    if (requestAccessPolicyEntity.getRevision() == null) {
        throw new IllegalArgumentException("Revision must be specified.");
    }

    // ensure the ids are the same
    final AccessPolicyDTO requestAccessPolicyDTO = requestAccessPolicyEntity.getComponent();
    if (!id.equals(requestAccessPolicyDTO.getId())) {
        throw new IllegalArgumentException(String.format("The access policy id (%s) in the request body does not equal the "
                + "access policy id of the requested resource (%s).", requestAccessPolicyDTO.getId(), id));
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestAccessPolicyEntity);
    }

    // Extract the revision
    final Revision requestRevision = getRevision(requestAccessPolicyEntity, id);
    return withWriteLock(
            serviceFacade,
            requestAccessPolicyEntity,
            requestRevision,
            lookup -> {
                Authorizable authorizable = lookup.getAccessPolicyById(id);
                authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
            },
            null,
            (revision, accessPolicyEntity) -> {
                final AccessPolicyDTO accessPolicyDTO = accessPolicyEntity.getComponent();

                // update the access policy
                final AccessPolicyEntity entity = serviceFacade.updateAccessPolicy(revision, accessPolicyDTO);
                populateRemainingAccessPolicyEntityContent(entity);

                return clusterContext(generateOkResponse(entity)).build();
            }
    );
}