Search in sources :

Example 1 with PathParam

use of javax.ws.rs.PathParam in project che by eclipse.

the class WorkspaceService method updateCommand.

@PUT
@Path("/{id}/command/{name}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Update the workspace command by replacing the command with a new one", notes = "This operation can be performed only by the workspace owner")
@ApiResponses({ @ApiResponse(code = 200, message = "The command successfully updated"), @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"), @ApiResponse(code = 403, message = "The user does not have access to update the workspace"), @ApiResponse(code = 404, message = "The workspace or the command not found"), @ApiResponse(code = 409, message = "The Command with such name already exists"), @ApiResponse(code = 500, message = "Internal server error occurred") })
public WorkspaceDto updateCommand(@ApiParam("The workspace id") @PathParam("id") String id, @ApiParam("The name of the command") @PathParam("name") String cmdName, @ApiParam(value = "The command update", required = true) CommandDto update) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException {
    requiredNotNull(update, "Command update");
    final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
    final List<CommandImpl> commands = workspace.getConfig().getCommands();
    if (!commands.removeIf(cmd -> cmd.getName().equals(cmdName))) {
        throw new NotFoundException(format("Workspace '%s' doesn't contain command '%s'", id, cmdName));
    }
    commands.add(new CommandImpl(update));
    validator.validateConfig(workspace.getConfig());
    return linksInjector.injectLinks(asDto(workspaceManager.updateWorkspace(workspace.getId(), workspace)), getServiceContext());
}
Also used : CommandImpl(org.eclipse.che.api.machine.server.model.impl.CommandImpl) EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) ApiParam(io.swagger.annotations.ApiParam) ApiOperation(io.swagger.annotations.ApiOperation) QueryParam(javax.ws.rs.QueryParam) Service(org.eclipse.che.api.core.rest.Service) Consumes(javax.ws.rs.Consumes) Example(io.swagger.annotations.Example) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) WsAgentHealthChecker(org.eclipse.che.api.agent.server.WsAgentHealthChecker) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) ImmutableMap(com.google.common.collect.ImmutableMap) LINK_REL_GET_WORKSPACES(org.eclipse.che.api.workspace.shared.Constants.LINK_REL_GET_WORKSPACES) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) DtoFactory.newDto(org.eclipse.che.dto.server.DtoFactory.newDto) WsAgentHealthStateDto(org.eclipse.che.api.workspace.shared.dto.WsAgentHealthStateDto) LINK_REL_GET_BY_NAMESPACE(org.eclipse.che.api.workspace.shared.Constants.LINK_REL_GET_BY_NAMESPACE) String.format(java.lang.String.format) SnapshotDto(org.eclipse.che.api.machine.shared.dto.SnapshotDto) List(java.util.List) BadRequestException(org.eclipse.che.api.core.BadRequestException) DtoConverter.asDto(org.eclipse.che.api.workspace.server.DtoConverter.asDto) Response(javax.ws.rs.core.Response) EnvironmentRecipeDto(org.eclipse.che.api.workspace.shared.dto.EnvironmentRecipeDto) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) CommandDto(org.eclipse.che.api.machine.shared.dto.CommandDto) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) WorkspaceDto(org.eclipse.che.api.workspace.shared.dto.WorkspaceDto) ApiResponses(io.swagger.annotations.ApiResponses) Inject(javax.inject.Inject) EnvironmentDto(org.eclipse.che.api.workspace.shared.dto.EnvironmentDto) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) ConflictException(org.eclipse.che.api.core.ConflictException) Api(io.swagger.annotations.Api) Named(javax.inject.Named) GenerateLink(org.eclipse.che.api.core.rest.annotations.GenerateLink) Collections.emptyMap(java.util.Collections.emptyMap) POST(javax.ws.rs.POST) ProjectConfigDto(org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto) WorkspaceStatus(org.eclipse.che.api.core.model.workspace.WorkspaceStatus) WorkspaceConfigDto(org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto) CHE_WORKSPACE_AUTO_START(org.eclipse.che.api.workspace.shared.Constants.CHE_WORKSPACE_AUTO_START) Maps(com.google.common.collect.Maps) NotFoundException(org.eclipse.che.api.core.NotFoundException) Collectors.toList(java.util.stream.Collectors.toList) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) ServerException(org.eclipse.che.api.core.ServerException) ApiResponse(io.swagger.annotations.ApiResponse) ExampleProperty(io.swagger.annotations.ExampleProperty) CommandImpl(org.eclipse.che.api.machine.server.model.impl.CommandImpl) ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ProjectConfigImpl(org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl) CHE_WORKSPACE_AUTO_SNAPSHOT(org.eclipse.che.api.workspace.shared.Constants.CHE_WORKSPACE_AUTO_SNAPSHOT) PUT(javax.ws.rs.PUT) CHE_WORKSPACE_AUTO_RESTORE(org.eclipse.che.api.workspace.shared.Constants.CHE_WORKSPACE_AUTO_RESTORE) LINK_REL_CREATE_WORKSPACE(org.eclipse.che.api.workspace.shared.Constants.LINK_REL_CREATE_WORKSPACE) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) NotFoundException(org.eclipse.che.api.core.NotFoundException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses)

Example 2 with PathParam

use of javax.ws.rs.PathParam in project jersey by jersey.

the class WebResourceFactory method invoke.

@Override
@SuppressWarnings("unchecked")
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if (args == null && method.getName().equals("toString")) {
        return toString();
    }
    if (args == null && method.getName().equals("hashCode")) {
        //unique instance in the JVM, and no need to override
        return hashCode();
    }
    if (args != null && args.length == 1 && method.getName().equals("equals")) {
        //unique instance in the JVM, and no need to override
        return equals(args[0]);
    }
    // get the interface describing the resource
    final Class<?> proxyIfc = proxy.getClass().getInterfaces()[0];
    // response type
    final Class<?> responseType = method.getReturnType();
    // determine method name
    String httpMethod = getHttpMethodName(method);
    if (httpMethod == null) {
        for (final Annotation ann : method.getAnnotations()) {
            httpMethod = getHttpMethodName(ann.annotationType());
            if (httpMethod != null) {
                break;
            }
        }
    }
    // create a new UriBuilder appending the @Path attached to the method
    WebTarget newTarget = addPathFromAnnotation(method, target);
    if (httpMethod == null) {
        if (newTarget == target) {
            // no path annotation on the method -> fail
            throw new UnsupportedOperationException("Not a resource method.");
        } else if (!responseType.isInterface()) {
            // not interface - can't help here
            throw new UnsupportedOperationException("Return type not an interface");
        }
    }
    // process method params (build maps of (Path|Form|Cookie|Matrix|Header..)Params
    // and extract entity type
    final MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<String, Object>(this.headers);
    final LinkedList<Cookie> cookies = new LinkedList<>(this.cookies);
    final Form form = new Form();
    form.asMap().putAll(this.form.asMap());
    final Annotation[][] paramAnns = method.getParameterAnnotations();
    Object entity = null;
    Type entityType = null;
    for (int i = 0; i < paramAnns.length; i++) {
        final Map<Class, Annotation> anns = new HashMap<>();
        for (final Annotation ann : paramAnns[i]) {
            anns.put(ann.annotationType(), ann);
        }
        Annotation ann;
        Object value = args[i];
        if (!hasAnyParamAnnotation(anns)) {
            entityType = method.getGenericParameterTypes()[i];
            entity = value;
        } else {
            if (value == null && (ann = anns.get(DefaultValue.class)) != null) {
                value = ((DefaultValue) ann).value();
            }
            if (value != null) {
                if ((ann = anns.get(PathParam.class)) != null) {
                    newTarget = newTarget.resolveTemplate(((PathParam) ann).value(), value);
                } else if ((ann = anns.get((QueryParam.class))) != null) {
                    if (value instanceof Collection) {
                        newTarget = newTarget.queryParam(((QueryParam) ann).value(), convert((Collection) value));
                    } else {
                        newTarget = newTarget.queryParam(((QueryParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((HeaderParam.class))) != null) {
                    if (value instanceof Collection) {
                        headers.addAll(((HeaderParam) ann).value(), convert((Collection) value));
                    } else {
                        headers.addAll(((HeaderParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((CookieParam.class))) != null) {
                    final String name = ((CookieParam) ann).value();
                    Cookie c;
                    if (value instanceof Collection) {
                        for (final Object v : ((Collection) value)) {
                            if (!(v instanceof Cookie)) {
                                c = new Cookie(name, v.toString());
                            } else {
                                c = (Cookie) v;
                                if (!name.equals(((Cookie) v).getName())) {
                                    // is this the right thing to do? or should I fail? or ignore the difference?
                                    c = new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion());
                                }
                            }
                            cookies.add(c);
                        }
                    } else {
                        if (!(value instanceof Cookie)) {
                            cookies.add(new Cookie(name, value.toString()));
                        } else {
                            c = (Cookie) value;
                            if (!name.equals(((Cookie) value).getName())) {
                                // is this the right thing to do? or should I fail? or ignore the difference?
                                cookies.add(new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion()));
                            }
                        }
                    }
                } else if ((ann = anns.get((MatrixParam.class))) != null) {
                    if (value instanceof Collection) {
                        newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), convert((Collection) value));
                    } else {
                        newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((FormParam.class))) != null) {
                    if (value instanceof Collection) {
                        for (final Object v : ((Collection) value)) {
                            form.param(((FormParam) ann).value(), v.toString());
                        }
                    } else {
                        form.param(((FormParam) ann).value(), value.toString());
                    }
                }
            }
        }
    }
    if (httpMethod == null) {
        // the method is a subresource locator
        return WebResourceFactory.newResource(responseType, newTarget, true, headers, cookies, form);
    }
    // accepted media types
    Produces produces = method.getAnnotation(Produces.class);
    if (produces == null) {
        produces = proxyIfc.getAnnotation(Produces.class);
    }
    final String[] accepts = (produces == null) ? EMPTY : produces.value();
    // determine content type
    String contentType = null;
    if (entity != null) {
        final List<Object> contentTypeEntries = headers.get(HttpHeaders.CONTENT_TYPE);
        if ((contentTypeEntries != null) && (!contentTypeEntries.isEmpty())) {
            contentType = contentTypeEntries.get(0).toString();
        } else {
            Consumes consumes = method.getAnnotation(Consumes.class);
            if (consumes == null) {
                consumes = proxyIfc.getAnnotation(Consumes.class);
            }
            if (consumes != null && consumes.value().length > 0) {
                contentType = consumes.value()[0];
            }
        }
    }
    Invocation.Builder builder = newTarget.request().headers(// this resets all headers so do this first
    headers).accept(// if @Produces is defined, propagate values into Accept header; empty array is NO-OP
    accepts);
    for (final Cookie c : cookies) {
        builder = builder.cookie(c);
    }
    final Object result;
    if (entity == null && !form.asMap().isEmpty()) {
        entity = form;
        contentType = MediaType.APPLICATION_FORM_URLENCODED;
    } else {
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }
        if (!form.asMap().isEmpty()) {
            if (entity instanceof Form) {
                ((Form) entity).asMap().putAll(form.asMap());
            } else {
            // TODO: should at least log some warning here
            }
        }
    }
    final GenericType responseGenericType = new GenericType(method.getGenericReturnType());
    if (entity != null) {
        if (entityType instanceof ParameterizedType) {
            entity = new GenericEntity(entity, entityType);
        }
        result = builder.method(httpMethod, Entity.entity(entity, contentType), responseGenericType);
    } else {
        result = builder.method(httpMethod, responseGenericType);
    }
    return result;
}
Also used : MatrixParam(javax.ws.rs.MatrixParam) Invocation(javax.ws.rs.client.Invocation) Form(javax.ws.rs.core.Form) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ParameterizedType(java.lang.reflect.ParameterizedType) Consumes(javax.ws.rs.Consumes) PathParam(javax.ws.rs.PathParam) Cookie(javax.ws.rs.core.Cookie) GenericType(javax.ws.rs.core.GenericType) Annotation(java.lang.annotation.Annotation) LinkedList(java.util.LinkedList) CookieParam(javax.ws.rs.CookieParam) MediaType(javax.ws.rs.core.MediaType) GenericType(javax.ws.rs.core.GenericType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) QueryParam(javax.ws.rs.QueryParam) Produces(javax.ws.rs.Produces) GenericEntity(javax.ws.rs.core.GenericEntity) Collection(java.util.Collection) WebTarget(javax.ws.rs.client.WebTarget) FormParam(javax.ws.rs.FormParam)

Example 3 with PathParam

use of javax.ws.rs.PathParam in project graylog2-server by Graylog2.

the class MessageResource method analyze.

@GET
@Path("/{index}/analyze")
@Timed
@ApiOperation(value = "Analyze a message string", notes = "Returns what tokens/terms a message string (message or full_message) is split to.")
@RequiresPermissions(RestPermissions.MESSAGES_ANALYZE)
@ApiResponses(value = { @ApiResponse(code = 404, message = "Specified index does not exist.") })
public MessageTokens analyze(@ApiParam(name = "index", value = "The index the message containing the string is stored in.", required = true) @PathParam("index") String index, @ApiParam(name = "analyzer", value = "The analyzer to use.") @QueryParam("analyzer") @Nullable String analyzer, @ApiParam(name = "string", value = "The string to analyze.", required = true) @QueryParam("string") @NotEmpty String string) {
    final String indexAnalyzer = indexSetRegistry.getForIndex(index).map(indexSet -> indexSet.getConfig().indexAnalyzer()).orElse("standard");
    final String messageAnalyzer = analyzer == null ? indexAnalyzer : analyzer;
    try {
        return MessageTokens.create(messages.analyze(string, index, messageAnalyzer));
    } catch (IndexNotFoundException e) {
        final String message = "Index " + index + " does not exist.";
        LOG.error(message, e);
        throw new NotFoundException(message);
    }
}
Also used : Configuration(org.graylog2.plugin.configuration.Configuration) PathParam(javax.ws.rs.PathParam) UUID(com.eaio.uuid.UUID) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Tools(org.graylog2.plugin.Tools) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) MessageTokens(org.graylog2.rest.models.messages.responses.MessageTokens) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) ApiResponses(io.swagger.annotations.ApiResponses) CodecFactory(org.graylog2.inputs.codecs.CodecFactory) MessageParseRequest(org.graylog2.rest.models.messages.requests.MessageParseRequest) Inject(javax.inject.Inject) ApiOperation(io.swagger.annotations.ApiOperation) ResolvableInetSocketAddress(org.graylog2.plugin.ResolvableInetSocketAddress) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) ResultMessage(org.graylog2.indexer.results.ResultMessage) Consumes(javax.ws.rs.Consumes) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Objects.requireNonNull(java.util.Objects.requireNonNull) RawMessage(org.graylog2.plugin.journal.RawMessage) Messages(org.graylog2.indexer.messages.Messages) BadRequestException(javax.ws.rs.BadRequestException) Api(io.swagger.annotations.Api) IndexSetRegistry(org.graylog2.indexer.IndexSetRegistry) Nullable(javax.annotation.Nullable) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) ForbiddenException(javax.ws.rs.ForbiddenException) RestResource(org.graylog2.shared.rest.resources.RestResource) InetSocketAddress(java.net.InetSocketAddress) NotFoundException(javax.ws.rs.NotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Timed(com.codahale.metrics.annotation.Timed) Codec(org.graylog2.plugin.inputs.codecs.Codec) ApiResponse(io.swagger.annotations.ApiResponse) RestPermissions(org.graylog2.shared.security.RestPermissions) NotEmpty(org.hibernate.validator.constraints.NotEmpty) InetAddresses(com.google.common.net.InetAddresses) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) Message(org.graylog2.plugin.Message) DocumentNotFoundException(org.graylog2.indexer.messages.DocumentNotFoundException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) NotFoundException(javax.ws.rs.NotFoundException) DocumentNotFoundException(org.graylog2.indexer.messages.DocumentNotFoundException) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 4 with PathParam

use of javax.ws.rs.PathParam in project eweb4j-framework by laiweiwei.

the class ActionUrlUtil method loadParam.

private static void loadParam(Class<?>[] paramTypes, Annotation[][] paramAnns, List<String> paramNames, List<Class<?>> paramClasses) {
    for (int j = 0; j < paramTypes.length; j++) {
        try {
            if (paramAnns[j].length > 0) {
                for (Annotation a : paramAnns[j]) {
                    if (a != null && PathParam.class.isAssignableFrom(a.annotationType())) {
                        PathParam rp = (PathParam) a;
                        paramNames.add(rp.value());
                        paramClasses.add(paramTypes[j]);
                        break;
                    }
                }
            } else if (ClassUtil.isPojo(paramTypes[j])) {
                Class<?> cls = paramTypes[j];
                pojoFieldToUrlParam(paramNames, paramClasses, cls);
            }
        } catch (Error e) {
            continue;
        } catch (Exception e) {
            continue;
        }
    }
}
Also used : PathParam(javax.ws.rs.PathParam) Annotation(java.lang.annotation.Annotation)

Example 5 with PathParam

use of javax.ws.rs.PathParam in project nifi by apache.

the class ControllerServiceResource method updateControllerServiceReferences.

/**
 * Updates the references of the specified controller service.
 *
 * @param httpServletRequest     request
 * @param requestUpdateReferenceRequest The update request
 * @return A controllerServiceReferencingComponentsEntity.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/references")
@ApiOperation(value = "Updates a controller services references", response = ControllerServiceReferencingComponentsEntity.class, authorizations = { @Authorization(value = "Write - /{component-type}/{uuid} - For each referencing component specified") })
@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 updateControllerServiceReferences(@Context final HttpServletRequest httpServletRequest, @ApiParam(value = "The controller service id.", required = true) @PathParam("id") final String id, @ApiParam(value = "The controller service request update request.", required = true) final UpdateControllerServiceReferenceRequestEntity requestUpdateReferenceRequest) {
    if (requestUpdateReferenceRequest.getId() == null) {
        throw new IllegalArgumentException("The controller service identifier must be specified.");
    }
    if (requestUpdateReferenceRequest.getReferencingComponentRevisions() == null) {
        throw new IllegalArgumentException("The controller service referencing components revisions must be specified.");
    }
    // parse the state to determine the desired action
    // need to consider controller service state first as it shares a state with
    // scheduled state (disabled) which is applicable for referencing services
    // but not referencing schedulable components
    ControllerServiceState requestControllerServiceState = null;
    try {
        requestControllerServiceState = ControllerServiceState.valueOf(requestUpdateReferenceRequest.getState());
    } catch (final IllegalArgumentException iae) {
    // ignore
    }
    ScheduledState requestScheduledState = null;
    try {
        requestScheduledState = ScheduledState.valueOf(requestUpdateReferenceRequest.getState());
    } catch (final IllegalArgumentException iae) {
    // ignore
    }
    // ensure an action has been specified
    if (requestScheduledState == null && requestControllerServiceState == null) {
        throw new IllegalArgumentException("Must specify the updated state. To update referencing Processors " + "and Reporting Tasks the state should be RUNNING or STOPPED. To update the referencing Controller Services the " + "state should be ENABLED or DISABLED.");
    }
    // ensure the controller service state is not ENABLING or DISABLING
    if (requestControllerServiceState != null && (ControllerServiceState.ENABLING.equals(requestControllerServiceState) || ControllerServiceState.DISABLING.equals(requestControllerServiceState))) {
        throw new IllegalArgumentException("Cannot set the referencing services to ENABLING or DISABLING");
    }
    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestUpdateReferenceRequest);
    }
    // convert the referencing revisions
    final Map<String, Revision> requestReferencingRevisions = requestUpdateReferenceRequest.getReferencingComponentRevisions().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> {
        final RevisionDTO rev = e.getValue();
        return new Revision(rev.getVersion(), rev.getClientId(), e.getKey());
    }));
    final Set<Revision> requestRevisions = new HashSet<>(requestReferencingRevisions.values());
    final ScheduledState verifyScheduledState = requestScheduledState;
    final ControllerServiceState verifyControllerServiceState = requestControllerServiceState;
    return withWriteLock(serviceFacade, requestUpdateReferenceRequest, requestRevisions, lookup -> {
        requestReferencingRevisions.entrySet().stream().forEach(e -> {
            final Authorizable controllerService = lookup.getControllerServiceReferencingComponent(id, e.getKey());
            controllerService.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
        });
    }, () -> serviceFacade.verifyUpdateControllerServiceReferencingComponents(requestUpdateReferenceRequest.getId(), verifyScheduledState, verifyControllerServiceState), (revisions, updateReferenceRequest) -> {
        ScheduledState scheduledState = null;
        try {
            scheduledState = ScheduledState.valueOf(updateReferenceRequest.getState());
        } catch (final IllegalArgumentException e) {
        // ignore
        }
        ControllerServiceState controllerServiceState = null;
        try {
            controllerServiceState = ControllerServiceState.valueOf(updateReferenceRequest.getState());
        } catch (final IllegalArgumentException iae) {
        // ignore
        }
        final Map<String, Revision> referencingRevisions = updateReferenceRequest.getReferencingComponentRevisions().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> {
            final RevisionDTO rev = e.getValue();
            return new Revision(rev.getVersion(), rev.getClientId(), e.getKey());
        }));
        // update the controller service references
        final ControllerServiceReferencingComponentsEntity entity = serviceFacade.updateControllerServiceReferencingComponents(referencingRevisions, updateReferenceRequest.getId(), scheduledState, controllerServiceState);
        return generateOkResponse(entity).build();
    });
}
Also used : Produces(javax.ws.rs.Produces) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) BundleDTO(org.apache.nifi.web.api.dto.BundleDTO) ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) StringUtils(org.apache.commons.lang3.StringUtils) ClientIdParameter(org.apache.nifi.web.api.request.ClientIdParameter) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) AuthorizeControllerServiceReference(org.apache.nifi.authorization.AuthorizeControllerServiceReference) PropertyDescriptorDTO(org.apache.nifi.web.api.dto.PropertyDescriptorDTO) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) UiExtension(org.apache.nifi.ui.extension.UiExtension) DefaultValue(javax.ws.rs.DefaultValue) UiExtensionType(org.apache.nifi.web.UiExtensionType) DELETE(javax.ws.rs.DELETE) ControllerServiceReferencingComponentsEntity(org.apache.nifi.web.api.entity.ControllerServiceReferencingComponentsEntity) Context(javax.ws.rs.core.Context) Authorizable(org.apache.nifi.authorization.resource.Authorizable) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) Set(java.util.Set) LongParameter(org.apache.nifi.web.api.request.LongParameter) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) ScheduledState(org.apache.nifi.controller.ScheduledState) UiExtensionMapping(org.apache.nifi.ui.extension.UiExtensionMapping) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) PathParam(javax.ws.rs.PathParam) Revision(org.apache.nifi.web.Revision) GET(javax.ws.rs.GET) ControllerServiceEntity(org.apache.nifi.web.api.entity.ControllerServiceEntity) PropertyDescriptorEntity(org.apache.nifi.web.api.entity.PropertyDescriptorEntity) ApiResponses(io.swagger.annotations.ApiResponses) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) HttpMethod(javax.ws.rs.HttpMethod) HashSet(java.util.HashSet) HttpServletRequest(javax.servlet.http.HttpServletRequest) UpdateControllerServiceReferenceRequestEntity(org.apache.nifi.web.api.entity.UpdateControllerServiceReferenceRequestEntity) Api(io.swagger.annotations.Api) NiFiServiceFacade(org.apache.nifi.web.NiFiServiceFacade) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) RequestAction(org.apache.nifi.authorization.RequestAction) Authorizer(org.apache.nifi.authorization.Authorizer) ApiResponse(io.swagger.annotations.ApiResponse) NiFiUserUtils(org.apache.nifi.authorization.user.NiFiUserUtils) ComponentStateDTO(org.apache.nifi.web.api.dto.ComponentStateDTO) ComponentStateEntity(org.apache.nifi.web.api.entity.ComponentStateEntity) ServletContext(javax.servlet.ServletContext) PUT(javax.ws.rs.PUT) Authorization(io.swagger.annotations.Authorization) ControllerServiceReferencingComponentsEntity(org.apache.nifi.web.api.entity.ControllerServiceReferencingComponentsEntity) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) Revision(org.apache.nifi.web.Revision) ScheduledState(org.apache.nifi.controller.ScheduledState) ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) Authorizable(org.apache.nifi.authorization.resource.Authorizable) Map(java.util.Map) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

PathParam (javax.ws.rs.PathParam)127 Path (javax.ws.rs.Path)105 GET (javax.ws.rs.GET)96 Produces (javax.ws.rs.Produces)96 Response (javax.ws.rs.core.Response)93 QueryParam (javax.ws.rs.QueryParam)82 List (java.util.List)72 MediaType (javax.ws.rs.core.MediaType)72 POST (javax.ws.rs.POST)71 DELETE (javax.ws.rs.DELETE)70 Consumes (javax.ws.rs.Consumes)66 Inject (javax.inject.Inject)62 Api (io.swagger.annotations.Api)60 ApiOperation (io.swagger.annotations.ApiOperation)59 Map (java.util.Map)59 ApiResponse (io.swagger.annotations.ApiResponse)58 ApiResponses (io.swagger.annotations.ApiResponses)57 Collectors (java.util.stream.Collectors)57 Logger (org.slf4j.Logger)52 LoggerFactory (org.slf4j.LoggerFactory)52