Java Examples for javax.ws.rs.DELETE

The following java examples will help you to understand the usage of javax.ws.rs.DELETE. These source code samples are taken from different open source projects.

Example 1
Project: airship-master  File: CoordinatorSlotResource.java View source code
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response terminateSlots(@Context UriInfo uriInfo, @HeaderParam(AIRSHIP_SLOTS_VERSION_HEADER) String expectedSlotsVersion) {
    // build filter
    List<UUID> uuids = transform(coordinator.getAllSlotStatus(), uuidGetter());
    Predicate<SlotStatus> slotFilter = SlotFilterBuilder.build(uriInfo, true, uuids);
    // terminate slots
    List<SlotStatus> result = coordinator.terminate(slotFilter, expectedSlotsVersion);
    // build response
    return Response.ok(transform(result, fromSlotStatus(coordinator.getAllSlotStatus(), repository))).header(AIRSHIP_SLOTS_VERSION_HEADER, createSlotsVersion(result)).build();
}
Example 2
Project: atlas-lb-master  File: BackupResource.java View source code
@DELETE
public Response deleteBackup() {
    if (!isUserInRole("cp,ops")) {
        return ResponseFactory.accessDenied();
    }
    try {
        org.openstack.atlas.service.domain.entities.Host domainHost = hostService.getById(hostId);
        org.openstack.atlas.service.domain.entities.Backup domainBackup = hostService.getBackupByHostIdAndBackupId(hostId, id);
        if (!hostService.isActiveHost(domainHost)) {
            String message = String.format("Host %d is currently immutable. Canceling delete backup request...", domainHost.getId());
            LOG.warn(message);
            throw new ImmutableEntityException(message);
        }
        try {
            LOG.debug("Deleting backup in Zeus...");
            reverseProxyLoadBalancerService.deleteHostBackup(domainHost, domainBackup.getName());
            LOG.info("Backup successfully deleted in Zeus.");
        } catch (ObjectDoesNotExist odno) {
            String message = String.format("A backup named '%s' does not exist. Ignoring...", domainBackup.getName());
            LOG.warn(message);
        } catch (Exception e) {
            String message = String.format("Error deleting backup '%d' in Zeus.", domainBackup.getId());
            LOG.error(message, e);
            notificationService.saveAlert(e, AlertType.ZEUS_FAILURE.name(), message);
            throw e;
        }
        LOG.debug("Removing the backup from the database...");
        hostService.deleteBackup(domainBackup);
        LOG.info("Delete backup operation complete.");
        return Response.status(Response.Status.OK).build();
    } catch (Exception e) {
        return ResponseFactory.getErrorResponse(e, null, null);
    }
}
Example 3
Project: NemakiWare-master  File: CacheResource.java View source code
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public String delete(@PathParam("repositoryId") String repositoryId, @PathParam("id") String objectId, @Context HttpServletRequest httpRequest) {
    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray errMsg = new JSONArray();
    Lock lock = threadLockService.getWriteLock(repositoryId, objectId);
    try {
        lock.lock();
        nemakiCachePool.get(repositoryId).removeCmisAndContentCache(objectId);
    } finally {
        lock.unlock();
    }
    result = makeResult(status, result, errMsg);
    return result.toJSONString();
}
Example 4
Project: SALSA-master  File: ConductorStop.java View source code
@Override
public void execute() {
    if (conductorID == null || conductorID.equals("")) {
        RestHandler.callRest(Main.getSalsaAPI("/manager/conductor/" + conductorID.trim()), RestHandler.HttpVerb.DELETE, null, null, MediaType.TEXT_PLAIN);
    } else {
        System.out.println("Stopped conductor via pioneer is not implemented yet, just use empty parameter!");
    }
}
Example 5
Project: speakeasy-plugin-master  File: UserResource.java View source code
@DELETE
@Path("{pluginKey}")
@Produces("application/json")
public Response disableAccess(@PathParam("pluginKey") String pluginKey) throws UnauthorizedAccessException {
    String user = userManager.getRemoteUsername();
    String affectedKey = speakeasyService.disableExtension(pluginKey, user);
    UserPlugins entity = speakeasyService.getRemotePluginList(user, pluginKey);
    if (affectedKey != null) {
        entity.setUpdated(asList(affectedKey));
    }
    return Response.ok().entity(entity).build();
}
Example 6
Project: traccar-master  File: UserResource.java View source code
@Path("{id}")
@DELETE
public Response remove(@PathParam("id") long id) throws SQLException {
    Context.getPermissionsManager().checkReadonly(getUserId());
    Context.getPermissionsManager().checkUser(getUserId(), id);
    Context.getPermissionsManager().removeUser(id);
    if (Context.getGeofenceManager() != null) {
        Context.getGeofenceManager().refreshUserGeofences();
    }
    if (Context.getNotificationManager() != null) {
        Context.getNotificationManager().refresh();
    }
    return Response.noContent().build();
}
Example 7
Project: zen-project-master  File: HyperApiIntrospector.java View source code
@Nullable
public Set<Annotation> findAllHttpMethods(Method method) {
    Set<Annotation> res = new LinkedHashSet<Annotation>();
    Annotation[] methodAnnotations = method.getAnnotations();
    for (Annotation a : methodAnnotations) {
        if (a instanceof GET || a instanceof POST || a instanceof PUT || a instanceof DELETE) {
            res.add(a);
        }
    }
    return res.isEmpty() ? null : res;
}
Example 8
Project: ambari-master  File: SettingsService.java View source code
/**
   * Deletes a setting for the current user
   */
@DELETE
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") String id) {
    try {
        resourceManager.removeSetting(id);
    } catch (ItemNotFound itemNotFound) {
        LOG.error("Error occurred while updating setting : ", itemNotFound);
        throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
    }
    return Response.noContent().build();
}
Example 9
Project: amza-master  File: AmzaBotEndpoints.java View source code
@DELETE
@Path("/keys/{name}")
public Response delete(@PathParam("name") String key) {
    try {
        String value = service.delete(key);
        if (value == null) {
            return Response.noContent().build();
        }
        return Response.accepted().build();
    } catch (Exception e) {
        LOG.error("Failed to handle delete name:{}", new Object[] { key }, e);
        return Response.serverError().build();
    }
}
Example 10
Project: bennu-master  File: ExternalApplicationScopesResource.java View source code
@DELETE
@Path("/{scope}")
public Response delete(@PathParam("scope") ExternalApplicationScope scope) {
    accessControl(Group.managers());
    atomic(() -> {
        for (ExternalApplication externalApplication : Bennu.getInstance().getApplicationsSet()) {
            externalApplication.removeScope(scope);
        }
        Bennu.getInstance().removeScopes(scope);
    });
    return ok();
}
Example 11
Project: cloud-management-master  File: InstanceResource.java View source code
@DELETE
public Response deleteInstance(@PathParam("id") String instanceId) {
    checkNotNull(instanceId, "Instance ID cannot be null");
    for (InstanceConnector instanceConnector : instanceConnectorMap.values()) {
        if (instanceConnector.destroyInstance(instanceId) == InstanceDestructionStatus.DESTROYED) {
            return Response.noContent().build();
        }
    }
    return Response.status(Status.NOT_FOUND).build();
}
Example 12
Project: cloudmix-master  File: AgentResourceTest.java View source code
public void testAnnotations() throws Exception {
    Class<AgentResource> cls = AgentResource.class;
    Method get = cls.getDeclaredMethod("get");
    assertNotNull(get.getAnnotation(GET.class));
    Method update = cls.getDeclaredMethod("update", AgentDetails.class);
    assertNotNull(update.getAnnotation(PUT.class));
    Method delete = cls.getDeclaredMethod("delete");
    assertNotNull(delete.getAnnotation(DELETE.class));
    Method history = cls.getDeclaredMethod("history", Request.class);
    assertNotNull(history.getAnnotation(GET.class));
    assertNotNull(history.getAnnotation(Path.class));
    assertEquals(1, history.getParameterAnnotations().length);
    assertEquals(1, history.getParameterAnnotations()[0].length);
    assertEquals(Context.class, history.getParameterAnnotations()[0][0].annotationType());
}
Example 13
Project: community-plugins-master  File: UserRosterService.java View source code
@DELETE
@Path("/{rosterJid}")
public Response deleteRoster(@PathParam("username") String username, @PathParam("rosterJid") String rosterJid) throws ServiceException {
    try {
        plugin.deleteRosterItem(username, rosterJid);
    } catch (SharedGroupException e) {
        throw new ServiceException("Could not delete the roster item", rosterJid, ExceptionType.SHARED_GROUP_EXCEPTION, Response.Status.BAD_REQUEST, e);
    }
    return Response.status(Response.Status.OK).build();
}
Example 14
Project: defense4all-master  File: PNResource.java View source code
@DELETE
public PNResourceStatus deletePN() {
    try {
        log.debug("DeletePN: invoked");
        boolean success = DFHolder.get().getMgmtPoint().removePN(pnLabel);
        return success ? PNResourceStatus.OK : PNResourceStatus.CONFLICT;
    } catch (ExceptionControlApp e) {
        log.error("Failed to delete pn " + pnLabel, e);
        return PNResourceStatus.SERVER_ERROR;
    }
}
Example 15
Project: fast-http-master  File: AnnotationBasedRoutingDefinition.java View source code
private void setupRoutes() {
    for (Method m : underlyingObject.getClass().getMethods()) {
        if (m.isAnnotationPresent(GET.class)) {
            addRoute(m, InvocationVerb.GET);
        }
        if (m.isAnnotationPresent(PUT.class)) {
            addRoute(m, InvocationVerb.PUT);
        }
        if (m.isAnnotationPresent(POST.class)) {
            addRoute(m, InvocationVerb.POST);
        }
        if (m.isAnnotationPresent(DELETE.class)) {
            addRoute(m, InvocationVerb.DELETE);
        }
        if (m.isAnnotationPresent(HEAD.class)) {
            addRoute(m, InvocationVerb.HEAD);
        }
    }
}
Example 16
Project: gae-studio-master  File: EntitiesResource.java View source code
@DELETE
public Response deleteEntities(@QueryParam(UrlParameters.KIND) String kind, @QueryParam(UrlParameters.NAMESPACE) String namespace, @QueryParam(UrlParameters.TYPE) DeleteEntities deleteType, @QueryParam(UrlParameters.KEY) String encodedKeys) {
    ResponseBuilder responseBuilder;
    if (isValidDeleteRequest(kind, namespace, deleteType, encodedKeys)) {
        entitiesService.deleteEntities(kind, namespace, deleteType, encodedKeys);
        responseBuilder = Response.noContent();
    } else {
        responseBuilder = Response.status(Status.BAD_REQUEST);
    }
    return responseBuilder.build();
}
Example 17
Project: guvnor-master  File: PermissionsTest.java View source code
@Test
public void allRestMethodsHaveRolesAssigned() {
    Set<Method> restMethods = reflections.getMethodsAnnotatedWith(Path.class);
    restMethods.addAll(reflections.getMethodsAnnotatedWith(GET.class));
    restMethods.addAll(reflections.getMethodsAnnotatedWith(POST.class));
    restMethods.addAll(reflections.getMethodsAnnotatedWith(DELETE.class));
    restMethods.addAll(reflections.getMethodsAnnotatedWith(PUT.class));
    for (Method pathMethod : restMethods) {
        RolesAllowed rolesAllowedAnno = pathMethod.getAnnotation(RolesAllowed.class);
        assertNotNull(pathMethod.getDeclaringClass() + "." + pathMethod.getName() + "(...) is missing a @RolesAllowed annotation!", rolesAllowedAnno);
        boolean basicRestRoleFound = false;
        for (String role : rolesAllowedAnno.value()) {
            if (PermissionConstants.REST_ROLE.equals(role)) {
                basicRestRoleFound = true;
                break;
            }
        }
        assertTrue(pathMethod.getDeclaringClass() + "." + pathMethod.getName() + "(...) is does not have the " + PermissionConstants.REST_ROLE + " role", basicRestRoleFound);
    }
}
Example 18
Project: jersey-doc-generator-master  File: MethodParser.java View source code
/**
	 * Parse a method to get annotation from
	 * 
	 * @param method
	 * @return The method content parsed
	 */
public static MethodContent parse(Method method) {
    MethodContent mc = new MethodContent();
    Annotation[] annotationMethodList = method.getDeclaredAnnotations();
    boolean found = false;
    mc.setName(method.getName());
    for (Annotation annotationMethod : annotationMethodList) {
        // HTTP Verb check
        if (annotationMethod instanceof GET || annotationMethod instanceof POST || annotationMethod instanceof PUT || annotationMethod instanceof DELETE || annotationMethod instanceof HEAD || annotationMethod instanceof OPTIONS) {
            found = true;
            mc.setType(annotationMethod.annotationType().getName());
        }
        // HTTP Verb check (another way)
        if (annotationMethod instanceof HttpMethod) {
            found = true;
            HttpMethod hm = (HttpMethod) annotationMethod;
            String value = hm.value();
            if (value != null && !value.equals("")) {
                value = value.toUpperCase();
            }
            mc.setType("javax.ws.rs." + value);
        }
        // Complete already parsed annotation
        if (BaseParser.complete(annotationMethod, mc)) {
            found = true;
        }
    }
    // With the return type, we try to check if it's a sub resource or not
    if (found) {
        /*
			 * 
			 * PARSING INPUT TYPE(S)
			 * 
			 */
        Class<?>[] parameterList = method.getParameterTypes();
        Annotation[][] annotationParameterList = method.getParameterAnnotations();
        int parameterLength = parameterList.length;
        if (parameterLength > 0) {
            for (int i = 0; i < parameterLength; ++i) {
                ParameterContent pctmp = ParameterParser.parse(parameterList[i], annotationParameterList[i]);
                if (pctmp != null) {
                    mc.getInputList().add(pctmp);
                }
            }
        }
        /*
			 * 
			 * PARSING RETURN TYPE
			 * 
			 */
        Class<?> rt = method.getReturnType();
        // If it's not void type return, or not a basic "Response" type
        if (rt != null && !rt.equals(Void.TYPE)) {
            ClassContent cc = ClassParser.parse(rt);
            if (cc != null) {
                mc.setSubResource(true);
                mc.setOutput(cc);
            } else {
                EmptyContent ec = new EmptyContent();
                ec.setName(rt.getName());
                mc.setOutput(ec);
            }
        }
    }
    return found ? mc : null;
}
Example 19
Project: muikku-master  File: ForumAcceptanceTestsRESTService.java View source code
@DELETE
@Path("/areas/{AREAID}/threads/{THREADID}")
@RESTPermit(handling = Handling.UNSECURED)
public Response deleteForumThread(@PathParam("AREAID") Long forumAreaId, @PathParam("THREADID") Long forumThreadId) {
    ForumThread forumThread = forumController.getForumThread(forumThreadId);
    if (forumThread == null) {
        return Response.status(Status.NOT_FOUND).entity("ForumThread not found").build();
    }
    forumController.deleteThread(forumThread);
    return Response.noContent().build();
}
Example 20
Project: nuxeo-master  File: UserToGroupObject.java View source code
@DELETE
public Response doRemoveUserFromGroup() {
    try {
        UserManager um = Framework.getLocalService(UserManager.class);
        checkPrincipalCanAdministerGroupAndUser(um);
        List<String> groups = principal.getGroups();
        groups.remove(group.getName());
        principal.setGroups(groups);
        um.updateUser(principal.getModel());
        return Response.ok(principal.getName()).build();
    } catch (NuxeoException e) {
        throw WebException.wrap(e);
    }
}
Example 21
Project: OG-Platform-master  File: WebPortfolioNodePositionResource.java View source code
//-------------------------------------------------------------------------
@DELETE
@Produces(MediaType.TEXT_HTML)
public Response deleteHTML() {
    ObjectId positionId = ObjectId.parse(data().getUriPositionId());
    PortfolioDocument doc = data().getPortfolio();
    if (doc.isLatest()) {
        ManageablePortfolioNode node = data().getNode();
        if (node.getPositionIds().remove(positionId) == false) {
            throw new DataNotFoundException("Position id not found: " + positionId);
        }
        doc = data().getPortfolioMaster().update(doc);
    }
    return Response.seeOther(WebPortfolioNodeResource.uri(data())).build();
}
Example 22
Project: semanticMDR-master  File: AuthenticationService.java View source code
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response logout(@CookieParam(SID) String sessionID) {
    boolean status = false;
    try {
        status = AuthenticationManager.getInstance().logoutUserFromSessionID(sessionID);
    } catch (AuthenticationException e) {
        logger.error("Cannot signout user from sessionID", e);
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
    if (status) {
        return Response.ok().build();
    } else {
        return Response.status(Status.BAD_REQUEST).build();
    }
}
Example 23
Project: seqware-master  File: CustomSampleFacadeREST.java View source code
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@DELETE
@Path("{id}/removeNullHierarchy")
@Consumes({ "application/xml", "application/json" })
public void removeNullHierarchy(@PathParam("id") Integer id) {
    // verify that the entity exists
    Sample find = super.find(id);
    // verify that a null relation already exists
    Query removeSelectNullParentCountQuery = Sample.selectNullParentCountQuery(super.getEntityManager(), id);
    Long count = (Long) removeSelectNullParentCountQuery.getSingleResult();
    // remove the null relationship
    if (count == 1) {
        int executeUpdate = super.getEntityManager().createNativeQuery("DELETE FROM sample_hierarchy sh WHERE sh.sample_id=" + id + " AND sh.parent_id IS NULL;").executeUpdate();
        if (executeUpdate == 1) {
            return;
        }
        throw new ConflictException("could not remove null parent hierarchy relationship");
    }
}
Example 24
Project: user-manager-master  File: PermissionResource.java View source code
@DELETE
@Path("{name}")
public Response deletePermission(@PathParam("name") final String name) {
    // FIXME: Un-comment this!!
    // SecurityUtils.getSubject()
    // .checkPermission( Permission.name( Permission.NAMESPACE, Permission.ADMIN ) );
    ResponseBuilder builder;
    try {
        dataManager.deletePermission(name);
        builder = Response.ok();
    } catch (final UserDataException e) {
        logger.error("Failed to remove permission: %s. Reason: %s", e, name, e.getMessage());
        builder = Response.serverError();
    }
    return builder.build();
}
Example 25
Project: wsdoc-master  File: JaxRSRestImplementationSupport.java View source code
@Override
public String getRequestMethod(ExecutableElement executableElement, TypeElement contextClass) {
    List<String> methods = new ArrayList<String>();
    gatherMethod(executableElement, methods, GET.class);
    gatherMethod(executableElement, methods, PUT.class);
    gatherMethod(executableElement, methods, POST.class);
    gatherMethod(executableElement, methods, DELETE.class);
    if (methods.size() != 1)
        throw new IllegalStateException(String.format("The method annotation for %s.%s is not parseable. Exactly one request method (GET/POST/PUT/DELETE) is required. Found: %s", contextClass.getQualifiedName(), executableElement.getSimpleName(), methods));
    return methods.get(0);
}
Example 26
Project: AIDR-master  File: UserResource.java View source code
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("id") Long id) throws PropertyNotSetException {
    Integer userDeleted = userLocalEJB.deleteUser(id);
    return userDeleted != null && userDeleted == 1 ? Response.ok(new ResponseWrapper(TaggerAPIConfigurator.getInstance().getProperty(TaggerAPIConfigurationProperty.STATUS_CODE_SUCCESS))).build() : Response.ok(new ResponseWrapper(TaggerAPIConfigurator.getInstance().getProperty(TaggerAPIConfigurationProperty.STATUS_CODE_FAILED))).build();
}
Example 27
Project: apis-master  File: AccessTokenResource.java View source code
/**
   * Delete an existing access token.
   */
@DELETE
@Path("/{accessTokenId}")
public Response delete(@Context HttpServletRequest request, @PathParam("accessTokenId") Long id) {
    Response validateScopeResponse = validateScope(request, Collections.singletonList(AbstractResource.SCOPE_WRITE));
    if (validateScopeResponse != null) {
        return validateScopeResponse;
    }
    AccessToken accessToken = getAccessToken(request, id);
    if (accessToken == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    LOG.debug("About to delete accessToken {}", id);
    accessTokenRepository.delete(id);
    return Response.noContent().build();
}
Example 28
Project: bagri-master  File: TransactionService.java View source code
@DELETE
@Path("/{txId}")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "deleteTx: rolls back the specified user Transaction")
public Response deleteTx(@PathParam("txId") long txId) {
    TransactionManagement txMgr = getTxManager();
    try {
        txMgr.rollbackTransaction(txId);
        return Response.ok().build();
    } catch (Exception ex) {
        logger.error("deleteTx.error", ex);
        throw new WebApplicationException(ex, Status.INTERNAL_SERVER_ERROR);
    }
}
Example 29
Project: cdap-master  File: ExploreMetadataHttpHandler.java View source code
@DELETE
@Path("namespaces/{namespace-id}")
public void delete(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") final String namespaceId) throws ExploreException, IOException {
    handleResponseEndpointExecution(request, responder, new EndpointCoreExecution<QueryHandle>() {

        @Override
        public QueryHandle execute(HttpRequest request, HttpResponder responder) throws IllegalArgumentException, SQLException, ExploreException, IOException {
            return exploreService.deleteNamespace(Id.Namespace.from(namespaceId));
        }
    });
}
Example 30
Project: cxf-master  File: AnnotatedCorsServer.java View source code
@OPTIONS
@Path("/delete")
@LocalPreflight
public Response deleteOptions() {
    String origin = headers.getRequestHeader("Origin").get(0);
    if ("http://area51.mil:3333".equals(origin)) {
        return Response.ok().header(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS, "DELETE PUT").header(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS, "false").header(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN, "http://area51.mil:3333").build();
    } else {
        return Response.ok().build();
    }
}
Example 31
Project: cyREST-master  File: SessionResource.java View source code
/**
	 * 
	 * @summary Delete current session and start new one
	 * 
	 * @return Success message
	 * 
	 */
@DELETE
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public String deleteSession() {
    try {
        TaskIterator itr = newSessionTaskFactory.createTaskIterator(true);
        while (itr.hasNext()) {
            final Task task = itr.next();
            task.run(new HeadlessTaskMonitor());
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw getError("Could not delete current session.", e, Response.Status.INTERNAL_SERVER_ERROR);
    }
    return "{\"message\": \"New session created.\"}";
}
Example 32
Project: droolsjbpm-integration-master  File: RestKieServerControllerImpl.java View source code
@DELETE
@Path("server/{id}")
public Response disposeContainer(@Context HttpHeaders headers, @PathParam("id") String id, @QueryParam("location") String serverLocation) {
    KieServerInfo serverInfo = null;
    try {
        serverInfo = new KieServerInfo(id, "", "", Collections.<String>emptyList(), URLDecoder.decode(serverLocation, "UTF-8"));
        disconnect(serverInfo);
        logger.info("Server with id '{}' disconnected", id);
    } catch (UnsupportedEncodingException e) {
        logger.debug("Cannot URL decode kie server location due to unsupported encoding exception", e);
    }
    return null;
}
Example 33
Project: glassfish-main-master  File: RestResourceMetadata.java View source code
private Annotation getMethodDesignator(Method method) {
    Annotation a = method.getAnnotation(GET.class);
    if (a == null) {
        a = method.getAnnotation(POST.class);
        if (a == null) {
            a = method.getAnnotation(DELETE.class);
            if (a == null) {
                a = method.getAnnotation(OPTIONS.class);
            }
        }
    }
    return a;
}
Example 34
Project: glassfish-master  File: RestResourceMetadata.java View source code
private Annotation getMethodDesignator(Method method) {
    Annotation a = method.getAnnotation(GET.class);
    if (a == null) {
        a = method.getAnnotation(POST.class);
        if (a == null) {
            a = method.getAnnotation(DELETE.class);
            if (a == null) {
                a = method.getAnnotation(OPTIONS.class);
            }
        }
    }
    return a;
}
Example 35
Project: graylog2-server-master  File: AuditCoverageTest.java View source code
@Test
public void testAuditCoverage() throws Exception {
    final ConfigurationBuilder configurationBuilder = new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.graylog2")).setScanners(new MethodAnnotationsScanner());
    final Set<String> auditEventTypes = new AuditEventTypes().auditEventTypes();
    final Reflections reflections = new Reflections(configurationBuilder);
    final ImmutableSet.Builder<Method> methods = ImmutableSet.builder();
    final ImmutableSet.Builder<Method> missing = ImmutableSet.builder();
    final ImmutableSet.Builder<Method> unregisteredAction = ImmutableSet.builder();
    methods.addAll(reflections.getMethodsAnnotatedWith(POST.class));
    methods.addAll(reflections.getMethodsAnnotatedWith(PUT.class));
    methods.addAll(reflections.getMethodsAnnotatedWith(DELETE.class));
    for (Method method : methods.build()) {
        if (!method.isAnnotationPresent(AuditEvent.class) && !method.isAnnotationPresent(NoAuditEvent.class)) {
            missing.add(method);
        } else {
            if (method.isAnnotationPresent(AuditEvent.class)) {
                final AuditEvent annotation = method.getAnnotation(AuditEvent.class);
                if (!auditEventTypes.contains(annotation.type())) {
                    unregisteredAction.add(method);
                }
            }
        }
    }
    assertThat(missing.build()).describedAs("Check that there are no POST, PUT and DELETE resources which do not have the @AuditEvent annotation").isEmpty();
    assertThat(unregisteredAction.build()).describedAs("Check that there are no @AuditEvent annotations with unregistered event types").isEmpty();
}
Example 36
Project: grendel-master  File: LinkedDocumentResource.java View source code
/**
	 * Responds to a {@link DELETE} request by deleting the {@link User}'s
	 * access to this {@link Document}. This does <strong>not</strong> delete
	 * the document itself, nor does it re-encrypt the document.
	 * <p>
	 * <strong>N.B.:</strong> Requires Basic authentication.
	 */
@DELETE
@Transactional
public Response delete(@Context Credentials credentials, @PathParam("user_id") String userId, @PathParam("owner_id") String ownerId, @PathParam("name") String name) {
    final Session session = credentials.buildSession(userDAO, userId);
    final User owner = findUser(ownerId);
    final Document doc = findDocument(owner, name);
    checkLinkage(doc, session.getUser());
    doc.unlinkUser(session.getUser());
    documentDAO.saveOrUpdate(doc);
    return Response.noContent().build();
}
Example 37
Project: hermes-message-master  File: BaseApi.java View source code
@ApiOperation(value = "Deletes a resource item by id", response = Response.class, httpMethod = "DELETE")
@DELETE
@Path("/{id}")
public Response deleteItem(@PathParam(value = "id") int id) {
    Logger.getLogger(this.getClass()).info("Delete item: " + id);
    try {
        delete(id);
        Logger.getLogger(this.getClass()).info("Deleted: " + id);
        return Response.status(Response.Status.NO_CONTENT).build();
    } catch (ApiException ex) {
        Logger.getLogger(this.getClass()).error("Error deleting item with id: " + id + ".", ex);
        return Response.serverError().status(Response.Status.PRECONDITION_FAILED).build();
    }
}
Example 38
Project: highway-to-urhell-master  File: JaxRsService.java View source code
private EntryPathData getEntryForClassJAXRS(String pathClass, Method m, String nameClass, Path pMethod) {
    EntryPathData entry = new EntryPathData();
    // method
    if (m.getAnnotation(GET.class) != null) {
        entry.setHttpMethod("GET");
    } else if (m.getAnnotation(POST.class) != null) {
        entry.setHttpMethod("POST");
    } else if (m.getAnnotation(PUT.class) != null) {
        entry.setHttpMethod("PUT");
    } else if (m.getAnnotation(DELETE.class) != null) {
        entry.setHttpMethod("DELETE");
    } else {
        entry.setHttpMethod("");
    }
    //
    entry.setUri(pathClass + pMethod.value());
    entry.setClassName(nameClass);
    entry.setMethodName(m.getName());
    entry.setTypePath(TypePath.DYNAMIC);
    entry.setSignatureName(getInternalSignature(m));
    entry.setListEntryPathData(searchParameterMethod(m.getParameterTypes()));
    return entry;
}
Example 39
Project: interruptus-master  File: TypeResource.java View source code
@DELETE
@Path("/{name}")
@ApiOperation(value = "Removes a type configuration", notes = "Removes a type configuration, throws exception if does not exists", response = Type.class)
@ApiResponses({ @ApiResponse(code = 404, message = "Type doesn't exists") })
public Boolean remove(@ApiParam(value = "Flow name to lookup for", required = true) @PathParam("name") String name) {
    try {
        final Type entity = repository.findById(name);
        repository.remove(name);
        dispatcher.dispatchDelete(entity);
        return true;
    } catch (EntityNotFoundException ex) {
        throw new ResourceException(ex);
    } catch (Exception ex) {
        logger.error(this, ex);
        throw new ResourceException(Response.Status.SERVICE_UNAVAILABLE, ex.getMessage());
    }
}
Example 40
Project: javaone2015-cloudone-master  File: ServiceResource.java View source code
@DELETE
@Path("{group}/{application}/{version}/{instance}")
@Produces("application/json")
public void unregister(@PathParam("group") String group, @PathParam("application") String app, @PathParam("version") String version, @PathParam("instance") int instance, @QueryParam("seccode") String secCode) {
    if (secCode == null || secCode.length() == 0) {
        throw new WebApplicationException("Parameter seccode must be specified", 400);
    }
    ServiceFullName name = new ServiceFullName(group, app, version);
    RegisteredRuntime runtime = ServiceRegistryService.getInstance().getRuntime(secCode);
    if (runtime == null) {
        throw new WebApplicationException("No registered runtime!", 404);
    }
    if (!name.equals(runtime.getServiceName()) || instance != runtime.getInstanceId()) {
        throw new WebApplicationException("Invalid sec code!", 400);
    }
    ServiceRegistryService.getInstance().unregister(runtime);
}
Example 41
Project: jbpm-master  File: PersonList.java View source code
/*
     * http://localhost:8080/register-rest-1.0/PersonList/delete?name=Don&middlename
     * =Non&surname=Existent
     */
@DELETE
@Produces(MediaType.TEXT_PLAIN)
@Path("/delete")
public String delete(@QueryParam("name") String name, @QueryParam("middlename") String middlename, @QueryParam("surname") String surname) {
    Person wanted = onList(name, middlename, surname);
    if (entryList.contains(wanted)) {
        System.out.println("\tDeleting - result '" + wanted + "'");
        entryList.remove(wanted);
        return "Ok";
    } else {
        System.out.println("\tNo - result '" + wanted + "'");
        return "Fail";
    }
}
Example 42
Project: jersey-1.x-old-master  File: HttpMethodTest.java View source code
public void testAll() {
    startServer(HttpMethodResource.class);
    WebResource r = Client.create().resource(getUri().path("test").build());
    assertEquals("GET", r.get(String.class));
    r = Client.create().resource(getUri().path("test").build());
    assertEquals("POST", r.post(String.class, "POST"));
    r = Client.create().resource(getUri().path("test").build());
    assertEquals("PUT", r.post(String.class, "PUT"));
    r = Client.create().resource(getUri().path("test").build());
    assertEquals("DELETE", r.delete(String.class));
}
Example 43
Project: jersey-old-master  File: BookmarkResource.java View source code
@DELETE
public void deleteBookmark() {
    TransactionManager.manage(utx, new Transactional(em) {

        public void transact() {
            em.persist(bookmarkEntity);
            UserEntity userEntity = bookmarkEntity.getUserEntity();
            userEntity.getBookmarkEntityCollection().remove(bookmarkEntity);
            em.merge(userEntity);
            em.remove(bookmarkEntity);
        }
    });
}
Example 44
Project: jira-wechat-master  File: WeChatAccountInfo.java View source code
@Path("/{username}")
@DELETE
@AnonymousAllowed
public Response deleteInfo(@PathParam("username") String username) {
    if (!userInfoAccess.hasUserInfo(username)) {
        return Response.ok(new GeneralContent()).build();
    }
    UserInfo userInfo = userInfoAccess.getUserInfo(username);
    // Connect to WeChat server
    try {
        connection.deleteMember(userInfo.getUserId());
    } catch (ConnectionException e) {
        e.printStackTrace();
        return Response.serverError().build();
    }
    // Remove info
    userInfoAccess.setUserInfo(username, null);
    return Response.ok(new GeneralContent()).build();
}
Example 45
Project: lilyproject-master  File: TableResource.java View source code
@DELETE
@Path("{name}")
public Response dropTable(@PathParam("name") String tableName, @Context UriInfo uriInfo) {
    try {
        TableManager tableManager = getRepository(uriInfo).getTableManager();
        if (!tableManager.tableExists(tableName)) {
            throw new ResourceException("Table '" + tableName + "' not found", NOT_FOUND.getStatusCode());
        }
        tableManager.dropTable(tableName);
        return Response.ok().build();
    } catch (IOException ioe) {
        throw new ResourceException("Error dropping table '" + tableName + "'", ioe, INTERNAL_SERVER_ERROR.getStatusCode());
    } catch (InterruptedException ie) {
        throw new ResourceException("Interrupted while dropping table '" + tableName + "'", ie, INTERNAL_SERVER_ERROR.getStatusCode());
    }
}
Example 46
Project: MIFOSX-master  File: ProvisioningCategoryApiResource.java View source code
@DELETE
@Path("{categoryId}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String deleteProvisioningCategory(@PathParam("categoryId") final Long categoryId) {
    this.platformSecurityContext.authenticatedUser();
    final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteProvisioningCategory(categoryId).build();
    final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
    return this.toApiJsonSerializer.serialize(result);
}
Example 47
Project: multibit-merchant-master  File: SupplierUserResource.java View source code
/**
   * @param supplierUser The Supplier User
   *
   * @return A HAL representation of the result
   */
@DELETE
@Timed
public Response deregisterUser(@RestrictedTo({ Authority.ROLE_SUPPLIER }) User supplierUser) {
    Preconditions.checkNotNull(supplierUser);
    // Remove all identifying information from the User
    // but leave the entity available for audit purposes
    // We leave the secret key in case the user has been
    // accidentally deleted and the user wants to be
    // reinstated
    supplierUser.setApiKey("");
    supplierUser.setContactMethodMap(Maps.<ContactMethod, ContactMethodDetail>newHashMap());
    supplierUser.setUsername("");
    supplierUser.setPasswordDigest("");
    supplierUser.setPasswordResetAt(DateUtils.nowUtc());
    supplierUser.setLocked(true);
    supplierUser.setDeleted(true);
    supplierUser.setReasonForDelete("Supplier deregistered");
    supplierUser.setUserFieldMap(Maps.<UserField, UserFieldDetail>newHashMap());
    // Persist the User with cascade for the Supplier
    User persistentUser = userDao.saveOrUpdate(supplierUser);
    // Provide a minimal representation to the client
    // so that they can see their secret key as a last resort
    // manual recovery option
    ClientUserBridge bridge = new ClientUserBridge(uriInfo, Optional.of(supplierUser));
    URI location = uriInfo.getAbsolutePathBuilder().path(persistentUser.getApiKey()).build();
    return created(bridge, persistentUser, location);
}
Example 48
Project: onos-master  File: TunnelWebResource.java View source code
/**
     * Delete a segment routing tunnel.
     *
     * @param input JSON stream for tunnel to delete
     * @return 204 NO CONTENT, if the tunnel is removed
     * @throws IOException if JSON is invalid
     */
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
public Response removeTunnel(InputStream input) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode tunnelJson = (ObjectNode) mapper.readTree(input);
    SegmentRoutingService srService = get(SegmentRoutingService.class);
    Tunnel tunnelInfo = TUNNEL_CODEC.decode(tunnelJson, this);
    srService.removeTunnel(tunnelInfo);
    return Response.noContent().build();
}
Example 49
Project: OpenDolphin-master  File: ScheduleResource.java View source code
@DELETE
@Path("/pvt/{param}")
public void deletePvt(@PathParam("param") String param) throws Exception {
    String[] params = param.split(",");
    long pvtPK = Long.parseLong(params[0]);
    long ptPK = Long.parseLong(params[1]);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date d = sdf.parse(params[2]);
    int cnt = scheduleService.removePvt(pvtPK, ptPK, d);
    debug(String.valueOf(cnt));
}
Example 50
Project: Openfire-master  File: UserRosterService.java View source code
@DELETE
@Path("/{rosterJid}")
public Response deleteRoster(@PathParam("username") String username, @PathParam("rosterJid") String rosterJid) throws ServiceException {
    try {
        plugin.deleteRosterItem(username, rosterJid);
    } catch (SharedGroupException e) {
        throw new ServiceException("Could not delete the roster item", rosterJid, ExceptionType.SHARED_GROUP_EXCEPTION, Response.Status.BAD_REQUEST, e);
    }
    return Response.status(Response.Status.OK).build();
}
Example 51
Project: Payara-master  File: SessionResource.java View source code
@DELETE
public Response delete() {
    Response.Status status;
    ActionReport.ExitCode exitCode;
    String message;
    if (!sessionManager.deleteSession(sessionId)) {
        status = Response.Status.BAD_REQUEST;
        exitCode = ActionReport.ExitCode.FAILURE;
        message = "Session with id " + sessionId + " does not exist";
    } else {
        status = Response.Status.OK;
        exitCode = ActionReport.ExitCode.SUCCESS;
        message = "Session with id " + sessionId + " deleted";
    }
    return Response.status(status).entity(ResourceUtil.getActionReportResult(exitCode, message, requestHeaders, uriInfo)).build();
}
Example 52
Project: picketlink-master  File: UsersEndpoint.java View source code
@DELETE
@Path("{id}")
public Response deleteUser(@Context HttpServletRequest request, @Context ServletContext sc, @PathParam("id") String userId) {
    verifyDataProvider(sc);
    try {
        dataProvider.initializeConnection();
        boolean result = dataProvider.deleteUser(userId);
        int responseCode = 404;
        if (result) {
            responseCode = 200;
        }
        return Response.status(responseCode).build();
    } finally {
        dataProvider.closeConnection();
    }
}
Example 53
Project: PlexRBAC-master  File: ServerStatusServiceImpl.java View source code
/*
     * (non-Javadoc)
     * 
     * @see com.plexobject.rbac.service.CacheFlushService#flushCaches()
     */
@Override
@DELETE
@Consumes({ MediaType.WILDCARD })
public Response flushCaches() {
    try {
        CacheFlusher.getInstance().flushCaches();
        mbean.incrementRequests();
        return Response.ok().build();
    } catch (Exception e) {
        LOGGER.error("failed to flush caches", e);
        mbean.incrementError();
        return Response.status(RestClient.SERVER_INTERNAL_ERROR).type("text/plain").entity("failed to flush caches due to " + e + "\n").build();
    }
}
Example 54
Project: pull-request-notifier-for-bitbucket-master  File: NotificationServlet.java View source code
@DELETE
@Path("{uuid}")
@XsrfProtectionExcluded
@Produces(APPLICATION_JSON)
public Response delete(@PathParam("uuid") UUID notification) {
    PrnfbNotification notificationDto = this.settingsService.getNotification(notification);
    if (!this.userCheckService.isAdminAllowed(notificationDto)) {
        return status(UNAUTHORIZED).build();
    }
    this.settingsService.deleteNotification(notification);
    return status(OK).build();
}
Example 55
Project: restdoc-java-server-master  File: MyCrudBean.java View source code
@Override
public RestResource[] getRestDocResources() {
    final RestResource rootRes = new RestResource().id("getItemlist").description("list of items").path("/api/strings");
    rootRes.method("GET", new MethodDefinition().description("get list of items").statusCode("200", "OK"));
    final MethodDefinition createItem = new MethodDefinition().description("create new item").statusCode("201", "Created");
    createItem.response(new ResponseDefinition().header("Location", "URI of the created resource", true));
    rootRes.method("POST", createItem);
    final RestResource idRes = new RestResource().id("getItem").description("single items").path("/api/strings/{id}");
    idRes.param("id", "the item id");
    idRes.method("GET", new MethodDefinition().description("get item").statusCode("200", "OK"));
    idRes.method("POST", new MethodDefinition().description("update item").statusCode("200", "OK"));
    idRes.method("DELETE", new MethodDefinition().description("delete item").statusCode("200", "OK"));
    return new RestResource[] { rootRes, idRes };
}
Example 56
Project: roboconf-platform-master  File: RestIndexerTest.java View source code
@Test
public void testMapBuilding() {
    RestIndexer indexer = new RestIndexer();
    // Checking that all the REST methods have been registered
    int cpt = 0;
    for (Class<?> clazz : RestApplication.getResourceClasses()) {
        Class<?> superClass = clazz.getInterfaces()[0];
        for (Method m : superClass.getMethods()) {
            // Only consider REST annotated classes
            if (!m.isAnnotationPresent(POST.class) && !m.isAnnotationPresent(GET.class) && !m.isAnnotationPresent(DELETE.class) && !m.isAnnotationPresent(PUT.class))
                continue;
            cpt++;
            boolean found = false;
            for (RestOperationBean ab : indexer.restMethods) {
                if (m.getName().equals(ab.getMethodName())) {
                    found = true;
                    break;
                }
            }
            Assert.assertTrue(clazz.getSimpleName() + " - " + m.getName(), found);
        }
    }
    // Verify the number of methods
    Assert.assertEquals(cpt, indexer.restMethods.size());
    // Verify toString()
    RestOperationBean ab = indexer.restMethods.get(0);
    Assert.assertEquals(ab.getMethodName(), ab.toString());
}
Example 57
Project: romar-master  File: Preferences.java View source code
@DELETE
@Path("/{user}/{item}")
public Response removePreference(@PathParam("user") String userString, @PathParam("item") String itemString) {
    long[] tmp = getUserAndItem(userString, itemString);
    long user = tmp[0];
    long item = tmp[1];
    PreferenceRomarRequest request = new PreferenceRomarRequest(RequestPath.REMOVE);
    request.setUserId(user);
    request.setItemId(item);
    RomarResponse response = _romarCore.execute(request);
    checkErrors(response);
    return Response.status(Status.ACCEPTED).build();
}
Example 58
Project: servicemix-master  File: CustomerService.java View source code
@DELETE
@Path("/customers/{id}/")
public Response deleteCustomer(@PathParam("id") String id) {
    System.out.println("----invoking deleteCustomer, Customer id is: " + id);
    long idNumber = Long.parseLong(id);
    Customer c = customers.get(idNumber);
    Response r;
    if (c != null) {
        r = Response.ok().build();
        customers.remove(idNumber);
    } else {
        r = Response.notModified().build();
    }
    return r;
}
Example 59
Project: Singularity-master  File: PriorityResource.java View source code
@DELETE
@Path("/freeze")
@ApiOperation("Stops the active priority freeze.")
@ApiResponses({ @ApiResponse(code = 202, message = "The active priority freeze was deleted."), @ApiResponse(code = 400, message = "There was no active priority freeze to delete.") })
public void deleteActivePriorityFreeze() {
    authorizationHelper.checkAdminAuthorization(user);
    final SingularityDeleteResult deleteResult = priorityManager.deleteActivePriorityFreeze();
    checkBadRequest(deleteResult == SingularityDeleteResult.DELETED, "No active priority freeze to delete.");
    priorityManager.clearPriorityKill();
}
Example 60
Project: sislegis-app-master  File: AgendaComissaoEndpoint.java View source code
@DELETE
@Path("/{casa}/{comissao}")
public Response unfollow(@PathParam("casa") String casa, @PathParam("comissao") String comissao, @HeaderParam("Authorization") String authorization) {
    try {
        Usuario user = controleUsuarioAutenticado.carregaUsuarioAutenticado(authorization);
        service.unfollowComissao(Origem.valueOf(casa), comissao, user);
        return Response.noContent().build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}
Example 61
Project: smart-user-master  File: UserRoleResource.java View source code
@DELETE
public Response delete() {
    ResponseBuilder responseBuilder;
    try {
        responseBuilder = Response.status(Status.OK);
        user.getRoles().remove(role);
        Services.getInstance().getUserService().update(user);
    } catch (Exception ex) {
        responseBuilder = Response.status(Status.INTERNAL_SERVER_ERROR);
    }
    return responseBuilder.build();
}
Example 62
Project: Tenuki-master  File: GraphResource.java View source code
@Path("{graphUri}")
@DELETE
public Response deleteGraph(@PathParam("graphUri") String graphUri) {
    Model dsModel = getDataset().getNamedModel(graphUri);
    try {
        if (dsModel.supportsTransactions()) {
            dsModel.begin();
        }
        dsModel.removeAll();
        dsModel.close();
        if (dsModel.supportsTransactions()) {
            dsModel.commit();
        }
    } catch (RuntimeException e) {
        if (dsModel.supportsTransactions()) {
            dsModel.abort();
        }
    }
    return Response.noContent().build();
}
Example 63
Project: thrift-swift-finagle-example-master  File: ContactResource.java View source code
@DELETE
@Timed
@Path("/{id}")
public Response deleteContact(@PathParam("id") String id) {
    try {
        Future<String> contactFuture = client.get().delete(id);
        Await.result(contactFuture);
        return Response.ok().build();
    } catch (Exception e) {
        return Response.status(Response.Status.NOT_FOUND).entity(new ExampleResponse(ContactService.ERROR_CODE_CONTACT_NOT_FOUND, e.getMessage())).build();
    }
}
Example 64
Project: Wink-master  File: DifferentCaptureVariablesTest.java View source code
public void testDifferentCaptureVariableNames() throws Exception {
    MockHttpServletResponse resp = invoke(MockRequestConstructor.constructMockRequest("GET", "/test/1234", "*/*"));
    assertEquals("", "1234", resp.getContentAsString());
    resp = invoke(MockRequestConstructor.constructMockRequest("DELETE", "/test/5678", "*/*"));
    assertEquals("", "5678", resp.getContentAsString());
}
Example 65
Project: 1ed-master  File: CarrosResource.java View source code
@DELETE
@Path("{id}")
public Response delete(@PathParam("id") long id) {
    if (id != 0) {
        if (id >= 1 && id <= 30) {
            return Response.Error("Este carro foi cadastrado pelo admin, não é possível excluí-lo.");
        }
        carroService.delete(id);
        return Response.Ok("Carro deletado com sucesso");
    }
    return Response.Error("Chamada incorreta");
}
Example 66
Project: abiquo-master  File: SubscriptionResource.java View source code
/**
     * Unsubscribes from changes to the given virtual machine.
     * 
     * @param subscriptionId The id of the virtual machine.
     */
@DELETE
@Path(SUBSCRIPTION_PATH)
public void unsubscribe(@PathParam(SUBSCRIPTION_PARAM) String subscriptionId) {
    checkSystem();
    subscriptionId = decodeParameter(subscriptionId);
    VirtualMachine vm = dao.getVirtualMachine(Integer.valueOf(subscriptionId));
    if (vm == null) {
        throw new VSMException(Status.NOT_FOUND, "There is no subscription with id " + subscriptionId);
    }
    vsmService.unsubscribe(vm.getPhysicalMachine().getAddress(), vm.getPhysicalMachine().getType(), vm.getName());
}
Example 67
Project: activemq-artemis-master  File: TopicResource.java View source code
@DELETE
public void deleteTopic(@Context UriInfo uriInfo) throws Exception {
    ActiveMQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\"");
    topicDestinationsResource.getTopics().remove(destination);
    try {
        stop();
    } catch (Exception ignored) {
    }
    ClientSession session = serviceManager.getSessionFactory().createSession(false, false, false);
    try {
        SimpleString topicName = new SimpleString(destination);
        session.deleteQueue(topicName);
    } finally {
        try {
            session.close();
        } catch (Exception ignored) {
        }
    }
}
Example 68
Project: aerogear-unifiedpush-server-master  File: AbstractVariantEndpoint.java View source code
/**
     * Delete Variant
     *
     * @param variantId id of {@link Variant}
     *
     * @return no content or 404
     *
     * @statuscode 204 The Variant successfully deleted
     * @statuscode 404 The requested Variant resource does not exist
     */
@DELETE
@Path("/{variantId}")
@ReturnType("java.lang.Void")
public Response deleteVariant(@PathParam("variantId") String variantId) {
    Variant variant = variantService.findByVariantID(variantId);
    if (variant != null) {
        logger.trace("Deleting: {}", variant.getClass().getSimpleName());
        variantService.removeVariant(variant);
        return Response.noContent().build();
    }
    return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Variant").build();
}
Example 69
Project: AIR-master  File: QueryResource.java View source code
@DELETE
@Path("saved/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteQuery(@Auth AirpalUser user, @PathParam("uuid") UUID uuid) {
    if (user != null) {
        if (queryStore.deleteSavedQuery(user, uuid)) {
            return Response.status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }
    return Response.status(Response.Status.UNAUTHORIZED).build();
}
Example 70
Project: airpal-master  File: QueryResource.java View source code
@DELETE
@Path("saved/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteQuery(@Auth AirpalUser user, @PathParam("uuid") UUID uuid) {
    if (user != null) {
        if (queryStore.deleteSavedQuery(user, uuid)) {
            return Response.status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }
    return Response.status(Response.Status.UNAUTHORIZED).build();
}
Example 71
Project: alchemy-rest-client-generator-master  File: RestInterfaceAnalyzer.java View source code
/**
     * Get rest meta data for the method.
     *
     * @param method
     *            the method to analyze.
     * @return the metadata for a method.
     */
private RestMethodMetadata analyzeMethod(final Method method) {
    String path = "";
    String httpMethod = null;
    final List<String> produced = new ArrayList<String>();
    final List<String> consumed = new ArrayList<String>();
    final Annotation[] annotations = method.getDeclaredAnnotations();
    for (final Annotation annotation : annotations) {
        if (annotation instanceof Path) {
            path = ((Path) annotation).value();
        } else if (annotation instanceof GET) {
            httpMethod = HttpMethod.GET;
        } else if (annotation instanceof PUT) {
            httpMethod = HttpMethod.PUT;
        } else if (annotation instanceof POST) {
            httpMethod = HttpMethod.POST;
        } else if (annotation instanceof DELETE) {
            httpMethod = HttpMethod.DELETE;
        } else if (annotation instanceof Produces) {
            final Produces produces = (Produces) annotation;
            produced.addAll(Arrays.asList(produces.value()));
        } else if (annotation instanceof Consumes) {
            final Consumes consumes = (Consumes) annotation;
            consumed.addAll(Arrays.asList(consumes.value()));
        }
    }
    if (StringUtils.isBlank(httpMethod)) {
        // no http method specified.
        return null;
    }
    return new RestMethodMetadata(path, httpMethod, produced, consumed, method.getParameterAnnotations());
}
Example 72
Project: anycook-api-master  File: DraftApi.java View source code
@DELETE
@Path("{id}")
public void remove(@PathParam("id") String id) {
    try (RecipeDraftsStore draftsStore = RecipeDraftsStore.getRecipeDraftStore()) {
        int userId = session.getUser().getId();
        draftsStore.deleteDraft(id, userId);
    } catch (Exception e) {
        logger.error(e, e);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Example 73
Project: Baragon-master  File: ElbResource.java View source code
@DELETE
@Path("/{elbName}/update")
public DeregisterInstancesFromLoadBalancerResult removeFromElb(@PathParam("elbName") String elbName, @QueryParam("instanceId") String instanceId) {
    if (config.isPresent()) {
        DeregisterInstancesFromLoadBalancerRequest request = new DeregisterInstancesFromLoadBalancerRequest(elbName, Arrays.asList(new Instance(instanceId)));
        return elbClient.deregisterInstancesFromLoadBalancer(request);
    } else {
        throw new BaragonWebException("ElbSync and related actions are not currently enabled");
    }
}
Example 74
Project: camel-master  File: CustomerService.java View source code
@DELETE
@Path("/customers/{id}/")
public Response deleteCustomer(@PathParam("id") String id) {
    long idNumber = Long.parseLong(id);
    Customer c = customers.get(idNumber);
    Response r;
    if (c != null) {
        r = Response.ok().build();
        customers.remove(idNumber);
    } else {
        r = Response.notModified().build();
    }
    if (idNumber == currentId.get()) {
        currentId.decrementAndGet();
    }
    return r;
}
Example 75
Project: candlepin-master  File: RulesResource.java View source code
@ApiOperation(notes = "Removes the Rules  Deletes any uploaded rules, uses bundled rules instead", value = "delete")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public void delete() {
    Rules deleteRules = rulesCurator.getRules();
    rulesCurator.delete(deleteRules);
    log.warn("Deleting rules version: " + deleteRules.getVersion());
    sink.emitRulesDeleted(deleteRules);
    // Trigger a recompile of the JS rules so version/source are set correctly:
    jsProvider.compileRules(true);
}
Example 76
Project: carbon-registry-master  File: Rating.java View source code
/**
     * this method delete the user's rating on the given resource
     *
     * @param resourcePath - path of the resource
     * @return Response     - HTTP 204 No Content
     */
@DELETE
@Produces("application/json")
@ApiOperation(value = "Delete the user's rating on the given resource", httpMethod = "DELETE", notes = "Delete the user's rating on the given resource")
@ApiResponses(value = { @ApiResponse(code = 204, message = "User's rating deleted successfully"), @ApiResponse(code = 401, message = "Invalid credentials provided"), @ApiResponse(code = 404, message = "Specified resource not found"), @ApiResponse(code = 500, message = "Internal server error occurred") })
public Response removeRating(@QueryParam("path") String resourcePath, @HeaderParam("X-JWT-Assertion") String JWTToken) {
    RestAPIAuthContext authContext = RestAPISecurityUtils.getAuthContext(PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken);
    if (!authContext.isAuthorized()) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    try {
        Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId());
        if (!registry.resourceExists(resourcePath)) {
            return Response.status(Response.Status.NOT_FOUND).entity(RestAPIConstants.RESOURCE_NOT_FOUND + resourcePath).build();
        }
        // set the user specific rating to 0
        registry.rateResource(resourcePath, 0);
        return Response.status(Response.Status.NO_CONTENT).build();
    } catch (RegistryException e) {
        log.error("Failed to remove rating on  resource " + resourcePath, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
}
Example 77
Project: CCIndex_HBase_0.90.0-master  File: ScannerInstanceResource.java View source code
@DELETE
public Response delete(@Context final UriInfo uriInfo) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("DELETE " + uriInfo.getAbsolutePath());
    }
    servlet.getMetrics().incrementRequests(1);
    if (servlet.isReadOnly()) {
        throw new WebApplicationException(Response.Status.FORBIDDEN);
    }
    ScannerResource.delete(id);
    return Response.ok().build();
}
Example 78
Project: cloud-odata-java-master  File: ODataSubLocator.java View source code
@POST
public Response handlePost(@HeaderParam("X-HTTP-Method") final String xHttpMethod) throws ODataException {
    Response response;
    if (xHttpMethod == null) {
        response = handle(ODataHttpMethod.POST);
    } else {
        /* tunneling */
        if ("MERGE".equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.MERGE);
        } else if ("PATCH".equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.PATCH);
        } else if (HttpMethod.DELETE.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.DELETE);
        } else if (HttpMethod.PUT.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.PUT);
        } else if (HttpMethod.GET.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.GET);
        } else if (HttpMethod.POST.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.POST);
        } else if (HttpMethod.HEAD.equals(xHttpMethod)) {
            response = handleHead();
        } else if (HttpMethod.OPTIONS.equals(xHttpMethod)) {
            response = handleOptions();
        } else {
            response = returnNotImplementedResponse(ODataNotImplementedException.TUNNELING);
        }
    }
    return response;
}
Example 79
Project: cloud-weatherapp-master  File: FavoriteCityService.java View source code
@SuppressWarnings("unchecked")
@DELETE
@Path("/{id}")
public List<FavoriteCity> removeFavoriteCity(@PathParam(value = "id") String id, @Context SecurityContext ctx) {
    List<FavoriteCity> retVal = null;
    String userName = (ctx.getUserPrincipal() != null) ? ctx.getUserPrincipal().getName() : "anonymous";
    Map<String, String> props = new HashMap<String, String>();
    props.put("tenant.id", userName);
    EntityManager em = this.getEntityManagerFactory().createEntityManager(props);
    try {
        Query query = em.createNamedQuery("FavoriteCityById");
        query.setParameter("id", id);
        FavoriteCity city = (FavoriteCity) query.getSingleResult();
        if (city != null) {
            em.getTransaction().begin();
            em.remove(city);
            em.getTransaction().commit();
        }
        retVal = em.createNamedQuery("FavoriteCities").getResultList();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        em.close();
    }
    return retVal;
}
Example 80
Project: CSAR_Repository-master  File: CsarResource.java View source code
@DELETE
public Response deleteCsar() {
    DeleteCsarService service = new DeleteCsarService(0, this.id);
    if (service.hasErrors()) {
        String message = StringUtils.join(service.getErrors());
        LOGGER.error(message);
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(message).build();
    }
    return Response.ok().build();
}
Example 81
Project: elasticinbox-master  File: AccountResource.java View source code
/**
	 * Delete account and all associated objects
	 * 
	 * @param account
	 * @return
	 */
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("user") final String user, @PathParam("domain") final String domain) {
    final Mailbox mailbox = new Mailbox(user, domain);
    try {
        // run deletion work in separate thread
        Thread t = new Thread() {

            @Override
            public void run() {
                try {
                    accountDAO.delete(mailbox);
                } catch (IOException e) {
                    logger.info("Account deletion failed: ", e);
                }
            }
        };
        // start thread
        t.start();
        t.join();
    } catch (Exception e) {
        logger.error("Account deletion failed: ", e);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
    return Response.noContent().build();
}
Example 82
Project: fenixedu-cms-master  File: PostResource.java View source code
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{oid}")
public Response deletePost(@PathParam("oid") Post post) {
    ensureCanDoThis(post.getSite(), EDIT_POSTS, DELETE_POSTS);
    if (post.isVisible()) {
        ensureCanDoThis(post.getSite(), EDIT_POSTS, DELETE_POSTS_PUBLISHED);
    }
    if (!Authenticate.getUser().equals(post.getCreatedBy())) {
        ensureCanDoThis(post.getSite(), EDIT_POSTS, DELETE_OTHERS_POSTS);
    }
    post.delete();
    return Response.ok().build();
}
Example 83
Project: freedomotic-master  File: AbstractResource.java View source code
/**
     *
     * @param UUID
     * @return
     */
@Override
@DELETE
@Path("/{id}")
@ApiOperation(value = "Delete an item", position = 50)
@ApiResponses(value = { @ApiResponse(code = 404, message = "Item not found") })
public Response delete(@ApiParam(value = "ID of item to delete", required = true) @PathParam("id") String UUID) {
    if (api.getAuth().isPermitted(authContext + ":create") && api.getAuth().isPermitted(authContext + ":read:" + UUID)) {
        if (doDelete(UUID)) {
            return Response.ok().build();
        } else {
            throw new ItemNotFoundException("Cannot find item: " + UUID);
        }
    }
    throw new ForbiddenException("User " + api.getAuth().getSubject().getPrincipal() + " cannot copy " + authContext + " with UUID " + UUID);
}
Example 84
Project: gmc-master  File: ClustersResource.java View source code
@Path("{" + PATH_PARAM_CLUSTER_NAME + "}")
@DELETE
public Response unregisterCluster(@PathParam(PATH_PARAM_CLUSTER_NAME) String clusterName) {
    if (clusterName == null || clusterName.isEmpty()) {
        throw new GlusterValidationException("Parameter [" + FORM_PARAM_CLUSTER_NAME + "] is missing in request!");
    }
    ClusterInfo cluster = clusterService.getCluster(clusterName);
    if (cluster == null) {
        throw new GlusterValidationException("Cluster [" + clusterName + "] does not exist!");
    }
    clusterService.unregisterCluster(cluster);
    return noContentResponse();
}
Example 85
Project: goodwill-master  File: Registrar.java View source code
@DELETE
@Path("/{type}/")
public Response deleteType(@PathParam("type") String typeName) throws IOException {
    if (!config.allowDeleteEvent()) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }
    if (typeName == null) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    } else {
        GoodwillSchema typeFound = store.findByName(typeName);
        if (typeFound != null) {
            if (store.deleteType(typeFound)) {
                return Response.noContent().build();
            } else {
                return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
            }
        } else {
            //return Response.status(Response.Status.GONE)
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }
}
Example 86
Project: gwt-jackson-rest-master  File: RestService.java View source code
/**
     * Check if the method is a REST method. If the method has a HTTP method annotation like {@link GET} and is not ignored with {@link
     * GenRestIgnore} then it's a REST method.
     *
     * @param method the method to check
     *
     * @return the HTTP method annotation found or null if the method is not a REST method or is ignored
     */
private AnnotationMirror isRestMethod(ExecutableElement method) {
    AnnotationMirror httpMethod = null;
    for (AnnotationMirror m : method.getAnnotationMirrors()) {
        if (m.getAnnotationType().toString().equals(GenRestIgnore.class.getName())) {
            return null;
        }
        if (m.getAnnotationType().toString().equals(GET.class.getName())) {
            httpMethod = m;
        } else if (m.getAnnotationType().toString().equals(POST.class.getName())) {
            httpMethod = m;
        } else if (m.getAnnotationType().toString().equals(PUT.class.getName())) {
            httpMethod = m;
        } else if (m.getAnnotationType().toString().equals(DELETE.class.getName())) {
            httpMethod = m;
        } else if (m.getAnnotationType().toString().equals(HEAD.class.getName())) {
            httpMethod = m;
        }
    }
    return httpMethod;
}
Example 87
Project: hadoop-hbase-master  File: ScannerInstanceResource.java View source code
@DELETE
public Response delete(@Context final UriInfo uriInfo) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("DELETE " + uriInfo.getAbsolutePath());
    }
    servlet.getMetrics().incrementRequests(1);
    if (servlet.isReadOnly()) {
        throw new WebApplicationException(Response.Status.FORBIDDEN);
    }
    ScannerResource.delete(id);
    return Response.ok().build();
}
Example 88
Project: hawkular-inventory-master  File: RestMetadataPacks.java View source code
@DELETE
@Path("/{id}")
@ApiOperation("Deletes a metadata pack.")
@ApiResponses({})
public Response delete(@PathParam("id") String id) {
    String tenantId = getTenantId();
    if (!security.canDelete(CanonicalPath.of().tenant(tenantId).metadataPack(id).get())) {
        return Response.status(FORBIDDEN).build();
    }
    inventory.tenants().get(tenantId).metadataPacks().delete(id);
    return Response.noContent().build();
}
Example 89
Project: hbase-trunk-mttr-master  File: ScannerInstanceResource.java View source code
@DELETE
public Response delete(@Context final UriInfo uriInfo) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("DELETE " + uriInfo.getAbsolutePath());
    }
    servlet.getMetrics().incrementRequests(1);
    if (servlet.isReadOnly()) {
        throw new WebApplicationException(Response.Status.FORBIDDEN);
    }
    if (ScannerResource.delete(id)) {
        servlet.getMetrics().incrementSucessfulDeleteRequests(1);
    } else {
        servlet.getMetrics().incrementFailedDeleteRequests(1);
    }
    return Response.ok().build();
}
Example 90
Project: HealtheMe-master  File: WeightResource.java View source code
/**
     * Delete method for deleting an instance of Weight identified by id.
     */
@DELETE
public void delete() {
    //check healthrecord is genuine
    try {
        Long local = new Long(getEntity().getHealthRecordId());
        Long session = new Long(servletRequest.getSession().getAttribute("healthRecordId").toString());
        if (local.compareTo(session) != 0) {
            throw new WebApplicationException(Response.Status.FORBIDDEN);
        }
    } catch (NullPointerException ex) {
        throw new WebApplicationException(Response.Status.FORBIDDEN);
    }
    PersistenceService persistenceSvc = PersistenceService.getInstance();
    try {
        //check updateable
        if (getEntity().getDataSourceId() != 1) {
            throw new WebApplicationException(Response.Status.FORBIDDEN);
        }
        persistenceSvc.beginTx();
        deleteEntity(getEntity());
        persistenceSvc.commitTx();
    } finally {
        persistenceSvc.close();
    }
}
Example 91
Project: HMS-master  File: ControllerManager.java View source code
@DELETE
@Path("abort/{command}")
public Response abortCommand(@PathParam("command") String cmdId) {
    try {
        Controller ci = Controller.getInstance();
        CommandHandler ch = ci.getCommandHandler();
        if (ch == null) {
            LOG.error("ClientHandler is empty");
        }
        String cmdPath = CommonConfigurationKeys.ZOOKEEPER_COMMAND_QUEUE_PATH_DEFAULT + "/" + cmdId;
        Command cmd = ch.getCommand(cmdPath);
        ch.failCommand(cmdPath, cmd);
        Response r = new Response();
        r.setOutput(cmdId + " is aborted.");
        return r;
    } catch (Exception e) {
        LOG.error(ExceptionUtil.getStackTrace(e));
        throw new WebApplicationException(e);
    }
}
Example 92
Project: huahin-emanager-master  File: JobFlowService.java View source code
@Path("/kill/step/{" + STEP_NAME + "}")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public JSONObject kill(@PathParam(STEP_NAME) String stepName) throws JSONException {
    Map<String, String> status = new HashMap<String, String>();
    status.put(Response.STATUS, stepName + " killed");
    try {
        Config config = QueueUtils.get(stepName);
        String masterPublicDnsName = config.getMasterPublicDnsName();
        if (config.getStatus() != Config.JOB_STATUS_RUNNING || isEmpty(masterPublicDnsName)) {
            status.put(Response.STATUS, stepName + " not running");
            return new JSONObject(status);
        }
        Resource resource = null;
        RestClient client = new RestClient();
        resource = client.resource(String.format(RUNNING_PATH, masterPublicDnsName));
        JSONArray runnings = resource.get(JSONArray.class);
        if (runnings.length() != 1) {
            status.put(Response.STATUS, stepName + " not running");
            return new JSONObject(status);
        }
        String jobId = runnings.getJSONObject(0).getString("jobid");
        resource = client.resource(String.format(KILL_PATH, masterPublicDnsName, jobId));
        JSONObject killStatuses = resource.delete(JSONObject.class);
        String killStatus = killStatuses.getString("status");
        if (isEmpty(killStatus) || !killStatus.equals(String.format(STATUS_KILLED, jobId))) {
            status.put(Response.STATUS, "kill failed");
            return new JSONObject(status);
        }
        config.setStatus(Config.JOB_STATUS_KILLED);
        QueueUtils.updateQueue(config);
    } catch (Exception e) {
        log.error(e);
        status.put(Response.STATUS, e.getMessage());
    }
    return new JSONObject(status);
}
Example 93
Project: huahin-manager-master  File: QueueService.java View source code
/**
     * @return {@link JSONObject}
     */
@Path("/kill/{" + QUEUEID + "}")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public JSONObject killJobId(@PathParam(QUEUEID) String queueId) {
    Map<String, String> status = new HashMap<String, String>();
    try {
        Map<String, Queue> queueMap = QueueUtils.readQueue(getQueuePath());
        for (Entry<String, Queue> entry : queueMap.entrySet()) {
            Queue q = entry.getValue();
            if (q.getId().equals(queueId)) {
                QueueUtils.removeQueue(getQueuePath(), q);
                status.put(Response.STATUS, "Killed queue " + queueId);
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e);
        status.put(Response.STATUS, e.getMessage());
    }
    if (status.isEmpty()) {
        status.put(Response.STATUS, "Could not find queue " + queueId);
    }
    return new JSONObject(status);
}
Example 94
Project: jax-rs-base-api-master  File: BaseApi.java View source code
@ApiOperation(value = "Deletes a resource item by id", response = Response.class, httpMethod = "DELETE")
@DELETE
@Path("/{id}")
public Response deleteItem(@PathParam(value = "id") int id) {
    Logger.getLogger(this.getClass()).info("Delete item: " + id);
    try {
        delete(id);
        Logger.getLogger(this.getClass()).info("Deleted: " + id);
        return Response.status(Response.Status.NO_CONTENT).build();
    } catch (ApiException ex) {
        Logger.getLogger(this.getClass()).error("Error deleting item with id: " + id + ".", ex);
        return Response.serverError().status(Response.Status.PRECONDITION_FAILED).build();
    }
}
Example 95
Project: jboss-jdg-quickstarts-master  File: CacheRestService.java View source code
@DELETE
@Path("/remove")
@Produces("application/json")
public CacheOperationResult<Boolean> remove(@QueryParam("key") final String key, @QueryParam("value") final String value) {
    final CacheOperationResult<Boolean> cor = new CacheOperationResult<Boolean>();
    Subject subject = SecurityContextAssociation.getSubject();
    try {
        Boolean returnValue = Security.doAs(subject, new PrivilegedAction<Boolean>() {

            public Boolean run() {
                Cache<String, String> cache;
                cache = cm.getCache("secured");
                return cache.remove(key, value);
            }
        });
        ArrayList<Boolean> returnValues = new ArrayList<Boolean>();
        returnValues.add(returnValue);
        cor.setOutputEntries(returnValues);
    } catch (Exception e) {
        cor.setFailed(true);
        cor.setFailureMessage(e.getMessage());
    }
    return cor;
}
Example 96
Project: jersey-master  File: BookmarkResource.java View source code
@DELETE
public void deleteBookmark() {
    TransactionManager.manage(utx, new Transactional(em) {

        public void transact() {
            em.persist(bookmarkEntity);
            UserEntity userEntity = bookmarkEntity.getUserEntity();
            userEntity.getBookmarkEntityCollection().remove(bookmarkEntity);
            em.merge(userEntity);
            em.remove(bookmarkEntity);
        }
    });
}
Example 97
Project: keycloak-master  File: AlbumService.java View source code
@Path("{id}")
@DELETE
public Response delete(@PathParam("id") String id) {
    Album album = this.entityManager.find(Album.class, Long.valueOf(id));
    try {
        deleteProtectedResource(album);
        this.entityManager.remove(album);
    } catch (Exception e) {
        throw new RuntimeException("Could not delete album.", e);
    }
    return Response.ok().build();
}
Example 98
Project: keywhiz-master  File: AutomationSecretAccessResource.java View source code
/**
   * Remove Secret from Group
   *
   * @excludeParams automationClient
   * @param secretId the ID of the Secret to unassign
   * @param groupId the ID of the Group to be removed from
   *
   * @description Unassigns the Secret specified by the secretID from the Group specified by the groupID
   * @responseMessage 200 Successfully removed Secret from Group
   * @responseMessage 404 Could not find Secret or Group
   */
@Timed
@ExceptionMetered
@DELETE
public Response disallowAccess(@Auth AutomationClient automationClient, @PathParam("secretId") LongParam secretId, @PathParam("groupId") LongParam groupId) {
    logger.info("Client '{}' disallowing groupId={} access to secretId={}", automationClient, secretId, groupId);
    try {
        Map<String, String> extraInfo = new HashMap<>();
        extraInfo.put("deprecated", "true");
        aclDAO.findAndRevokeAccess(secretId.get(), groupId.get(), auditLog, automationClient.getName(), extraInfo);
    } catch (IllegalStateException e) {
        throw new NotFoundException();
    }
    return Response.ok().build();
}
Example 99
Project: libreplan-master  File: WorkReportServiceREST.java View source code
@Override
@DELETE
@Path("/{code}/")
@Transactional
public Response removeWorkReport(@PathParam("code") String code) {
    try {
        WorkReport workReport = workReportDAO.findByCode(code);
        Set<OrderElement> orderElements = sumChargedEffortDAO.getOrderElementsToRecalculateTimsheetDates(null, workReport.getWorkReportLines());
        sumChargedEffortDAO.updateRelatedSumChargedEffortWithDeletedWorkReportLineSet(workReport.getWorkReportLines());
        workReportDAO.remove(workReport.getId());
        sumChargedEffortDAO.recalculateTimesheetData(orderElements);
        return Response.ok().build();
    } catch (InstanceNotFoundException e) {
        return Response.status(Status.NOT_FOUND).build();
    }
}
Example 100
Project: lyo.server-master  File: ConsumersService.java View source code
/**
	 * Deletes an OAuth consumer.
	 * 
	 * @param key
	 *            the consumer key
	 * @return the HTTP response
	 */
@DELETE
@Path("/{key}")
public Response removeConsumer(@PathParam("key") String key) {
    CSRFPrevent.check(httpRequest);
    try {
        if (!OAuthConfiguration.getInstance().getApplication().isAdminSession(httpRequest)) {
            return Response.status(Status.FORBIDDEN).type(MediaType.TEXT_PLAIN).entity("You must be an administrator.").build();
        }
        OAuthConfiguration.getInstance().getConsumerStore().removeConsumer(key);
        return Response.noContent().build();
    } catch (ConsumerStoreException e) {
        return handleConsumerStoreException(e);
    } catch (OAuthProblemException e) {
        return Response.status(Status.SERVICE_UNAVAILABLE).build();
    }
}
Example 101
Project: marketplace-master  File: MarketplaceService.java View source code
@DELETE
@Path("/plugin/{pluginId}")
@Produces(MediaType.APPLICATION_JSON)
public OperationResultDTO uninstallPlugin(@PathParam("pluginId") String pluginId) {
    OperationResultDTO result = new OperationResultDTO();
    //uninstall plugin
    IDomainStatusMessage statusMessage = this.RDO.getPluginService().uninstallPlugin(pluginId);
    //send installation string
    result.statusMessage = this.statusMessageDTOMapper.toDTO(statusMessage);
    return result;
}