Search in sources :

Example 6 with APPLICATION_JSON

use of javax.ws.rs.core.MediaType.APPLICATION_JSON in project keywhiz by square.

the class ClientResource method modifyClientGroups.

/**
   * Modify groups a client has membership in
   *
   * @excludeParams automationClient
   * @param name Client name
   * @param request JSON request specifying which groups to add or remove
   * @return Listing of groups client has membership in
   *
   * @responseMessage 201 Client modified successfully
   * @responseMessage 404 Client not found
   */
@Timed
@ExceptionMetered
@PUT
@Path("{name}/groups")
@Produces(APPLICATION_JSON)
public Iterable<String> modifyClientGroups(@Auth AutomationClient automationClient, @PathParam("name") String name, @Valid ModifyGroupsRequestV2 request) {
    Client client = clientDAOReadWrite.getClient(name).orElseThrow(NotFoundException::new);
    String user = automationClient.getName();
    long clientId = client.getId();
    Set<String> oldGroups = aclDAOReadWrite.getGroupsFor(client).stream().map(Group::getName).collect(toSet());
    Set<String> groupsToAdd = Sets.difference(request.addGroups(), oldGroups);
    Set<String> groupsToRemove = Sets.intersection(request.removeGroups(), oldGroups);
    // TODO: should optimize AclDAO to use names and return only name column
    groupsToGroupIds(groupsToAdd).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAOReadWrite.findAndEnrollClient(clientId, groupId, auditLog, user, new HashMap<>())));
    groupsToGroupIds(groupsToRemove).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAOReadWrite.findAndEvictClient(clientId, groupId, auditLog, user, new HashMap<>())));
    return aclDAOReadWrite.getGroupsFor(client).stream().map(Group::getName).collect(toSet());
}
Also used : NotImplementedException(org.apache.commons.lang3.NotImplementedException) PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) Produces(javax.ws.rs.Produces) ClientDAO(keywhiz.service.daos.ClientDAO) GET(javax.ws.rs.GET) ClientDetailResponseV2(keywhiz.api.automation.v2.ClientDetailResponseV2) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) HashMap(java.util.HashMap) Inject(javax.inject.Inject) Valid(javax.validation.Valid) AutomationClient(keywhiz.api.model.AutomationClient) ClientDAOFactory(keywhiz.service.daos.ClientDAO.ClientDAOFactory) Consumes(javax.ws.rs.Consumes) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) ModifyGroupsRequestV2(keywhiz.api.automation.v2.ModifyGroupsRequestV2) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) GroupDAO(keywhiz.service.daos.GroupDAO) Collectors.toSet(java.util.stream.Collectors.toSet) DELETE(javax.ws.rs.DELETE) CreateClientRequestV2(keywhiz.api.automation.v2.CreateClientRequestV2) AuditLog(keywhiz.log.AuditLog) ModifyClientRequestV2(keywhiz.api.automation.v2.ModifyClientRequestV2) Group(keywhiz.api.model.Group) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) Set(java.util.Set) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) String.format(java.lang.String.format) Timed(com.codahale.metrics.annotation.Timed) EventTag(keywhiz.log.EventTag) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) PUT(javax.ws.rs.PUT) NotFoundException(javax.ws.rs.NotFoundException) AutomationClient(keywhiz.api.model.AutomationClient) Client(keywhiz.api.model.Client) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) PUT(javax.ws.rs.PUT)

Example 7 with APPLICATION_JSON

use of javax.ws.rs.core.MediaType.APPLICATION_JSON in project ddf by codice.

the class MetacardApplication method init.

@Override
public void init() {
    get("/metacardtype", (req, res) -> {
        return util.getJson(util.getMetacardTypeMap());
    });
    get("/metacard/:id", (req, res) -> {
        String id = req.params(":id");
        return util.metacardToJson(id);
    });
    get("/metacard/:id/attribute/validation", (req, res) -> {
        String id = req.params(":id");
        return util.getJson(validator.getValidation(util.getMetacard(id)));
    });
    get("/metacard/:id/validation", (req, res) -> {
        String id = req.params(":id");
        return util.getJson(validator.getFullValidation(util.getMetacard(id)));
    });
    post("/metacards", APPLICATION_JSON, (req, res) -> {
        List<String> ids = JsonFactory.create().parser().parseList(String.class, req.body());
        List<Metacard> metacards = util.getMetacards(ids, "*").entrySet().stream().map(Map.Entry::getValue).map(Result::getMetacard).collect(Collectors.toList());
        return util.metacardsToJson(metacards);
    });
    delete("/metacards", APPLICATION_JSON, (req, res) -> {
        List<String> ids = JsonFactory.create().parser().parseList(String.class, req.body());
        DeleteResponse deleteResponse = catalogFramework.delete(new DeleteRequestImpl(new ArrayList<>(ids), Metacard.ID, null));
        if (deleteResponse.getProcessingErrors() != null && !deleteResponse.getProcessingErrors().isEmpty()) {
            res.status(500);
            return ImmutableMap.of("message", "Unable to archive metacards.");
        }
        return ImmutableMap.of("message", "Successfully archived metacards.");
    }, util::getJson);
    patch("/metacards", APPLICATION_JSON, (req, res) -> {
        List<MetacardChanges> metacardChanges = JsonFactory.createUseJSONDates().parser().parseList(MetacardChanges.class, req.body());
        UpdateResponse updateResponse = patchMetacards(metacardChanges);
        if (updateResponse.getProcessingErrors() != null && !updateResponse.getProcessingErrors().isEmpty()) {
            res.status(500);
            return updateResponse.getProcessingErrors();
        }
        return req.body();
    });
    put("/validate/attribute/:attribute", TEXT_PLAIN, (req, res) -> {
        String attribute = req.params(":attribute");
        String value = req.body();
        return util.getJson(validator.validateAttribute(attribute, value));
    });
    get("/history/:id", (req, res) -> {
        String id = req.params(":id");
        List<Result> queryResponse = getMetacardHistory(id);
        if (queryResponse.isEmpty()) {
            res.status(204);
            return "[]";
        }
        List<HistoryResponse> response = queryResponse.stream().map(Result::getMetacard).map(mc -> new HistoryResponse(mc.getId(), (String) mc.getAttribute(MetacardVersion.EDITED_BY).getValue(), (Date) mc.getAttribute(MetacardVersion.VERSIONED_ON).getValue())).sorted(Comparator.comparing(HistoryResponse::getVersioned)).collect(Collectors.toList());
        return util.getJson(response);
    });
    get("/history/revert/:id/:revertid", (req, res) -> {
        String id = req.params(":id");
        String revertId = req.params(":revertid");
        Metacard versionMetacard = util.getMetacard(revertId);
        List<Result> queryResponse = getMetacardHistory(id);
        if (queryResponse == null || queryResponse.isEmpty()) {
            throw new NotFoundException("Could not find metacard with id: " + id);
        }
        Optional<Metacard> contentVersion = queryResponse.stream().map(Result::getMetacard).filter(mc -> getVersionedOnDate(mc).isAfter(getVersionedOnDate(versionMetacard)) || getVersionedOnDate(mc).equals(getVersionedOnDate(versionMetacard))).filter(mc -> CONTENT_ACTIONS.contains(Action.ofMetacard(mc))).filter(mc -> mc.getResourceURI() != null).filter(mc -> ContentItem.CONTENT_SCHEME.equals(mc.getResourceURI().getScheme())).sorted(Comparator.comparing((Metacard mc) -> util.parseToDate(mc.getAttribute(MetacardVersion.VERSIONED_ON).getValue()))).findFirst();
        if (!contentVersion.isPresent()) {
            /* no content versions, just restore metacard */
            revertMetacard(versionMetacard, id, false);
        } else {
            revertContentandMetacard(contentVersion.get(), versionMetacard, id);
        }
        return util.metacardToJson(MetacardVersionImpl.toMetacard(versionMetacard, types));
    });
    get("/associations/:id", (req, res) -> {
        String id = req.params(":id");
        return util.getJson(associated.getAssociations(id));
    });
    put("/associations/:id", (req, res) -> {
        String id = req.params(":id");
        List<Associated.Edge> edges = JsonFactory.create().parser().parseList(Associated.Edge.class, req.body());
        associated.putAssociations(id, edges);
        return req.body();
    });
    post("/subscribe/:id", (req, res) -> {
        String email = getSubjectEmail();
        if (isEmpty(email)) {
            throw new NotFoundException("Login to subscribe to workspace.");
        }
        String id = req.params(":id");
        subscriptions.addEmail(id, email);
        return ImmutableMap.of("message", String.format("Successfully subscribed to id = %s.", id));
    }, util::getJson);
    post("/unsubscribe/:id", (req, res) -> {
        String email = getSubjectEmail();
        if (isEmpty(email)) {
            throw new NotFoundException("Login to un-subscribe from workspace.");
        }
        String id = req.params(":id");
        subscriptions.removeEmail(id, email);
        return ImmutableMap.of("message", String.format("Successfully un-subscribed to id = %s.", id));
    }, util::getJson);
    get("/workspaces/:id", (req, res) -> {
        String id = req.params(":id");
        String email = getSubjectEmail();
        Metacard metacard = util.getMetacard(id);
        // NOTE: the isEmpty is to guard against users with no email (such as guest).
        boolean isSubscribed = !isEmpty(email) && subscriptions.getEmails(metacard.getId()).contains(email);
        return ImmutableMap.builder().putAll(transformer.transform(metacard)).put("subscribed", isSubscribed).build();
    }, util::getJson);
    get("/workspaces", (req, res) -> {
        String email = getSubjectEmail();
        Map<String, Result> workspaceMetacards = util.getMetacardsByFilter(WorkspaceAttributes.WORKSPACE_TAG);
        // NOTE: the isEmpty is to guard against users with no email (such as guest).
        Set<String> ids = isEmpty(email) ? Collections.emptySet() : subscriptions.getSubscriptions(email);
        return workspaceMetacards.entrySet().stream().map(Map.Entry::getValue).map(Result::getMetacard).map(metacard -> {
            boolean isSubscribed = ids.contains(metacard.getId());
            try {
                return ImmutableMap.builder().putAll(transformer.transform(metacard)).put("subscribed", isSubscribed).build();
            } catch (RuntimeException e) {
                LOGGER.debug("Could not transform metacard. WARNING: This indicates there is invalid data in the system. Metacard title: '{}', id:'{}'", metacard.getTitle(), metacard.getId(), e);
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }, util::getJson);
    post("/workspaces", APPLICATION_JSON, (req, res) -> {
        Map<String, Object> incoming = JsonFactory.create().parser().parseMap(req.body());
        Metacard saved = saveMetacard(transformer.transform(incoming));
        Map<String, Object> response = transformer.transform(saved);
        res.status(201);
        return util.getJson(response);
    });
    put("/workspaces/:id", APPLICATION_JSON, (req, res) -> {
        String id = req.params(":id");
        Map<String, Object> workspace = JsonFactory.create().parser().parseMap(req.body());
        Metacard metacard = transformer.transform(workspace);
        metacard.setAttribute(new AttributeImpl(Metacard.ID, id));
        Metacard updated = updateMetacard(id, metacard);
        return util.getJson(transformer.transform(updated));
    });
    delete("/workspaces/:id", APPLICATION_JSON, (req, res) -> {
        String id = req.params(":id");
        catalogFramework.delete(new DeleteRequestImpl(id));
        return ImmutableMap.of("message", "Successfully deleted.");
    }, util::getJson);
    get("/enumerations/metacardtype/:type", APPLICATION_JSON, (req, res) -> {
        return util.getJson(enumExtractor.getEnumerations(req.params(":type")));
    });
    get("/enumerations/attribute/:attribute", APPLICATION_JSON, (req, res) -> {
        return util.getJson(enumExtractor.getAttributeEnumerations(req.params(":attribute")));
    });
    get("/localcatalogid", (req, res) -> {
        return String.format("{\"%s\":\"%s\"}", "local-catalog-id", catalogFramework.getId());
    });
    after((req, res) -> {
        res.type(APPLICATION_JSON);
    });
    exception(IngestException.class, (ex, req, res) -> {
        res.status(404);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        LOGGER.debug("Failed to ingest metacard", ex);
        res.body(util.getJson(ImmutableMap.of("message", UPDATE_ERROR_MESSAGE)));
    });
    exception(NotFoundException.class, (ex, req, res) -> {
        res.status(404);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        LOGGER.debug("Failed to find metacard.", ex);
        res.body(util.getJson(ImmutableMap.of("message", ex.getMessage())));
    });
    exception(NumberFormatException.class, (ex, req, res) -> {
        res.status(400);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        res.body(util.getJson(ImmutableMap.of("message", "Invalid values for numbers")));
    });
    exception(RuntimeException.class, (ex, req, res) -> {
        LOGGER.debug("Exception occured.", ex);
        res.status(404);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        res.body(util.getJson(ImmutableMap.of("message", "Could not find what you were looking for")));
    });
}
Also used : CONTENT_TYPE(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE) Spark.delete(spark.Spark.delete) Spark.patch(spark.Spark.patch) Date(java.util.Date) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) Spark.exception(spark.Spark.exception) LoggerFactory(org.slf4j.LoggerFactory) UpdateStorageRequestImpl(ddf.catalog.content.operation.impl.UpdateStorageRequestImpl) SparkApplication(spark.servlet.SparkApplication) AttributeType(ddf.catalog.data.AttributeType) ExperimentalEnumerationExtractor(org.codice.ddf.catalog.ui.metacard.enumerations.ExperimentalEnumerationExtractor) MetacardVersion(ddf.catalog.core.versioning.MetacardVersion) HistoryResponse(org.codice.ddf.catalog.ui.metacard.history.HistoryResponse) Map(java.util.Map) Action(ddf.catalog.core.versioning.MetacardVersion.Action) DeleteRequestImpl(ddf.catalog.operation.impl.DeleteRequestImpl) Spark.put(spark.Spark.put) SubjectUtils(ddf.security.SubjectUtils) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) MetacardVersionImpl(ddf.catalog.core.versioning.impl.MetacardVersionImpl) ImmutableSet(com.google.common.collect.ImmutableSet) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) StringUtils.isEmpty(org.apache.commons.lang.StringUtils.isEmpty) ImmutableMap(com.google.common.collect.ImmutableMap) WorkspaceAttributes(org.codice.ddf.catalog.ui.metacard.workspace.WorkspaceAttributes) ResourceRequestById(ddf.catalog.operation.impl.ResourceRequestById) Spark.after(spark.Spark.after) DeletedMetacard(ddf.catalog.core.versioning.DeletedMetacard) Set(java.util.Set) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) MetacardType(ddf.catalog.data.MetacardType) Serializable(java.io.Serializable) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) Objects(java.util.Objects) QueryResponse(ddf.catalog.operation.QueryResponse) List(java.util.List) Validator(org.codice.ddf.catalog.ui.metacard.validation.Validator) SubscriptionsPersistentStore(org.codice.ddf.catalog.ui.query.monitor.api.SubscriptionsPersistentStore) Optional(java.util.Optional) MetacardChanges(org.codice.ddf.catalog.ui.metacard.edit.MetacardChanges) UpdateResponse(ddf.catalog.operation.UpdateResponse) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) SecurityUtils(org.apache.shiro.SecurityUtils) ResourceResponse(ddf.catalog.operation.ResourceResponse) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) Spark.get(spark.Spark.get) ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) FilterBuilder(ddf.catalog.filter.FilterBuilder) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) CatalogFramework(ddf.catalog.CatalogFramework) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) Spark.post(spark.Spark.post) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) DeleteResponse(ddf.catalog.operation.DeleteResponse) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) SortBy(org.opengis.filter.sort.SortBy) EndpointUtil(org.codice.ddf.catalog.ui.util.EndpointUtil) ContentItem(ddf.catalog.content.data.ContentItem) Metacard(ddf.catalog.data.Metacard) AttributeChange(org.codice.ddf.catalog.ui.metacard.edit.AttributeChange) ByteSource(com.google.common.io.ByteSource) Result(ddf.catalog.data.Result) WorkspaceTransformer(org.codice.ddf.catalog.ui.metacard.workspace.WorkspaceTransformer) Associated(org.codice.ddf.catalog.ui.metacard.associations.Associated) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) CreateStorageRequestImpl(ddf.catalog.content.operation.impl.CreateStorageRequestImpl) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Logger(org.slf4j.Logger) Security(org.codice.ddf.security.common.Security) JsonFactory(org.boon.json.JsonFactory) IngestException(ddf.catalog.source.IngestException) IOException(java.io.IOException) Subject(ddf.security.Subject) FederationException(ddf.catalog.federation.FederationException) TimeUnit(java.util.concurrent.TimeUnit) ResourceNotSupportedException(ddf.catalog.resource.ResourceNotSupportedException) ExecutionException(org.apache.shiro.subject.ExecutionException) Filter(org.opengis.filter.Filter) Comparator(java.util.Comparator) Collections(java.util.Collections) InputStream(java.io.InputStream) HistoryResponse(org.codice.ddf.catalog.ui.metacard.history.HistoryResponse) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) ArrayList(java.util.ArrayList) NotFoundException(javax.ws.rs.NotFoundException) ResourceNotFoundException(ddf.catalog.resource.ResourceNotFoundException) Result(ddf.catalog.data.Result) UpdateResponse(ddf.catalog.operation.UpdateResponse) Associated(org.codice.ddf.catalog.ui.metacard.associations.Associated) DeleteRequestImpl(ddf.catalog.operation.impl.DeleteRequestImpl) MetacardChanges(org.codice.ddf.catalog.ui.metacard.edit.MetacardChanges) Date(java.util.Date) DeletedMetacard(ddf.catalog.core.versioning.DeletedMetacard) Metacard(ddf.catalog.data.Metacard) DeleteResponse(ddf.catalog.operation.DeleteResponse)

Example 8 with APPLICATION_JSON

use of javax.ws.rs.core.MediaType.APPLICATION_JSON in project che by eclipse.

the class WorkspaceService method updateProject.

@PUT
@Path("/{id}/project/{path:.*}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Update the workspace project by replacing it with a new one", notes = "This operation can be performed only by the workspace owner")
@ApiResponses({ @ApiResponse(code = 200, message = "The project 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 project"), @ApiResponse(code = 404, message = "The workspace or the project not found"), @ApiResponse(code = 500, message = "Internal server error occurred") })
public WorkspaceDto updateProject(@ApiParam("The workspace id") @PathParam("id") String id, @ApiParam("The path to the project") @PathParam("path") String path, @ApiParam(value = "The project update", required = true) ProjectConfigDto update) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException {
    requiredNotNull(update, "Project config");
    final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
    final List<ProjectConfigImpl> projects = workspace.getConfig().getProjects();
    final String normalizedPath = path.startsWith("/") ? path : '/' + path;
    if (!projects.removeIf(project -> project.getPath().equals(normalizedPath))) {
        throw new NotFoundException(format("Workspace '%s' doesn't contain project with path '%s'", id, normalizedPath));
    }
    projects.add(new ProjectConfigImpl(update));
    validator.validateConfig(workspace.getConfig());
    return linksInjector.injectLinks(asDto(workspaceManager.updateWorkspace(id, workspace)), getServiceContext());
}
Also used : 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) ProjectConfigImpl(org.eclipse.che.api.workspace.server.model.impl.ProjectConfigImpl) 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 9 with APPLICATION_JSON

use of javax.ws.rs.core.MediaType.APPLICATION_JSON in project keywhiz by square.

the class ClientResource method createClient.

/**
   * Creates a client and assigns to given groups
   *
   * @excludeParams automationClient
   * @param request JSON request to create a client
   *
   * @responseMessage 201 Created client and assigned to given groups
   * @responseMessage 409 Client already exists
   */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createClient(@Auth AutomationClient automationClient, @Valid CreateClientRequestV2 request) {
    String creator = automationClient.getName();
    String client = request.name();
    clientDAOReadWrite.getClient(client).ifPresent((c) -> {
        logger.info("Automation ({}) - Client {} already exists", creator, client);
        throw new ConflictException("Client name already exists.");
    });
    // Creates new client record
    long clientId = clientDAOReadWrite.createClient(client, creator, request.description());
    auditLog.recordEvent(new Event(Instant.now(), EventTag.CLIENT_CREATE, creator, client));
    // Enrolls client in any requested groups
    groupsToGroupIds(request.groups()).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAOReadWrite.findAndEnrollClient(clientId, groupId, auditLog, creator, new HashMap<>())));
    URI uri = UriBuilder.fromResource(ClientResource.class).path(client).build();
    return Response.created(uri).build();
}
Also used : NotImplementedException(org.apache.commons.lang3.NotImplementedException) PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) Produces(javax.ws.rs.Produces) ClientDAO(keywhiz.service.daos.ClientDAO) GET(javax.ws.rs.GET) ClientDetailResponseV2(keywhiz.api.automation.v2.ClientDetailResponseV2) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) HashMap(java.util.HashMap) Inject(javax.inject.Inject) Valid(javax.validation.Valid) AutomationClient(keywhiz.api.model.AutomationClient) ClientDAOFactory(keywhiz.service.daos.ClientDAO.ClientDAOFactory) Consumes(javax.ws.rs.Consumes) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) ModifyGroupsRequestV2(keywhiz.api.automation.v2.ModifyGroupsRequestV2) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) GroupDAO(keywhiz.service.daos.GroupDAO) Collectors.toSet(java.util.stream.Collectors.toSet) DELETE(javax.ws.rs.DELETE) CreateClientRequestV2(keywhiz.api.automation.v2.CreateClientRequestV2) AuditLog(keywhiz.log.AuditLog) ModifyClientRequestV2(keywhiz.api.automation.v2.ModifyClientRequestV2) Group(keywhiz.api.model.Group) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) Set(java.util.Set) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) String.format(java.lang.String.format) Timed(com.codahale.metrics.annotation.Timed) EventTag(keywhiz.log.EventTag) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) PUT(javax.ws.rs.PUT) ConflictException(keywhiz.service.exceptions.ConflictException) Event(keywhiz.log.Event) URI(java.net.URI) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 10 with APPLICATION_JSON

use of javax.ws.rs.core.MediaType.APPLICATION_JSON in project keywhiz by square.

the class SecretResource method modifySecretGroups.

/**
   * Modify the groups a secret is assigned to
   *
   * @excludeParams automationClient
   * @param name Secret series name
   * @param request JSON request to modify groups
   *
   * @responseMessage 201 Group membership changed
   * @responseMessage 404 Secret series not found
   */
@Timed
@ExceptionMetered
@PUT
@Path("{name}/groups")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Iterable<String> modifySecretGroups(@Auth AutomationClient automationClient, @PathParam("name") String name, @Valid ModifyGroupsRequestV2 request) {
    // TODO: Use latest version instead of non-versioned
    Secret secret = secretController.getSecretByName(name).orElseThrow(NotFoundException::new);
    String user = automationClient.getName();
    long secretId = secret.getId();
    Set<String> oldGroups = aclDAO.getGroupsFor(secret).stream().map(Group::getName).collect(toSet());
    Set<String> groupsToAdd = Sets.difference(request.addGroups(), oldGroups);
    Set<String> groupsToRemove = Sets.intersection(request.removeGroups(), oldGroups);
    // TODO: should optimize AclDAO to use names and return only name column
    groupsToGroupIds(groupsToAdd).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAO.findAndAllowAccess(secretId, groupId, auditLog, user, new HashMap<>())));
    groupsToGroupIds(groupsToRemove).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAO.findAndRevokeAccess(secretId, groupId, auditLog, user, new HashMap<>())));
    return aclDAO.getGroupsFor(secret).stream().map(Group::getName).collect(toSet());
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) Secret(keywhiz.api.model.Secret) Produces(javax.ws.rs.Produces) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) Valid(javax.validation.Valid) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) ModifyGroupsRequestV2(keywhiz.api.automation.v2.ModifyGroupsRequestV2) BadRequestException(javax.ws.rs.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) ContentCryptographer(keywhiz.service.crypto.ContentCryptographer) GroupDAO(keywhiz.service.daos.GroupDAO) Collectors.toSet(java.util.stream.Collectors.toSet) DELETE(javax.ws.rs.DELETE) Group(keywhiz.api.model.Group) SecretVersion(keywhiz.api.model.SecretVersion) CreateSecretRequestV2(keywhiz.api.automation.v2.CreateSecretRequestV2) HOURS(java.time.temporal.ChronoUnit.HOURS) Set(java.util.Set) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) String.format(java.lang.String.format) Timed(com.codahale.metrics.annotation.Timed) Base64(java.util.Base64) List(java.util.List) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) SecretDAOFactory(keywhiz.service.daos.SecretDAO.SecretDAOFactory) SecretContent(keywhiz.api.model.SecretContent) PathParam(javax.ws.rs.PathParam) SecretDetailResponseV2(keywhiz.api.automation.v2.SecretDetailResponseV2) AclDAO(keywhiz.service.daos.AclDAO) SanitizedSecretWithGroups(keywhiz.api.model.SanitizedSecretWithGroups) GET(javax.ws.rs.GET) Auth(io.dropwizard.auth.Auth) PartialUpdateSecretRequestV2(keywhiz.api.automation.v2.PartialUpdateSecretRequestV2) HashMap(java.util.HashMap) SecretSeriesDAO(keywhiz.service.daos.SecretSeriesDAO) Inject(javax.inject.Inject) AutomationClient(keywhiz.api.model.AutomationClient) ImmutableList(com.google.common.collect.ImmutableList) SecretDAO(keywhiz.service.daos.SecretDAO) SecretBuilder(keywhiz.service.daos.SecretController.SecretBuilder) AuditLog(keywhiz.log.AuditLog) DataAccessException(org.jooq.exception.DataAccessException) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) SecretSeriesDAOFactory(keywhiz.service.daos.SecretSeriesDAO.SecretSeriesDAOFactory) Readonly(keywhiz.service.config.Readonly) UTF_8(java.nio.charset.StandardCharsets.UTF_8) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) SetSecretVersionRequestV2(keywhiz.api.automation.v2.SetSecretVersionRequestV2) SecretController(keywhiz.service.daos.SecretController) EventTag(keywhiz.log.EventTag) Collectors.toList(java.util.stream.Collectors.toList) CreateOrUpdateSecretRequestV2(keywhiz.api.automation.v2.CreateOrUpdateSecretRequestV2) SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent) PUT(javax.ws.rs.PUT) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) PUT(javax.ws.rs.PUT)

Aggregations

APPLICATION_JSON (javax.ws.rs.core.MediaType.APPLICATION_JSON)10 List (java.util.List)8 Map (java.util.Map)8 DELETE (javax.ws.rs.DELETE)8 GET (javax.ws.rs.GET)8 POST (javax.ws.rs.POST)8 PUT (javax.ws.rs.PUT)8 Path (javax.ws.rs.Path)8 PathParam (javax.ws.rs.PathParam)8 Produces (javax.ws.rs.Produces)8 Response (javax.ws.rs.core.Response)8 String.format (java.lang.String.format)7 Set (java.util.Set)7 Inject (javax.inject.Inject)7 Consumes (javax.ws.rs.Consumes)7 HashMap (java.util.HashMap)6 DefaultValue (javax.ws.rs.DefaultValue)6 QueryParam (javax.ws.rs.QueryParam)6 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)5 Timed (com.codahale.metrics.annotation.Timed)5