javatips.net counter

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: jerseytest-master  File: TodoResource.java View source code
@DELETE
@Path("/{todo}")
public void removeTodo(@PathParam("todo") String todoToRemove) {
    todoService.removeTodo(todoToRemove);
}
Example 2
Project: dataverse-master  File: Index.java View source code
@DELETE
@Path("timestamps")
public Response deleteAllTimestamps() {
    int numItemsCleared = dvObjectService.clearAllIndexTimes();
    return ok("cleared: " + numItemsCleared);
}
Example 3
Project: eclipselink.runtime-master  File: EntityResource.java View source code
@DELETE
@Path("{type}/{id}/{attribute}")
public Response removeAttribute(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("id") String id, @PathParam("attribute") String attribute, @Context HttpHeaders hh, @Context UriInfo ui) {
    setRequestUniqueId();
    return removeAttributeInternal(null, persistenceUnit, type, id, attribute, hh, ui);
}
Example 4
Project: fenixedu-cms-master  File: SiteResource.java View source code
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{oid}")
public Response deleteSite(@PathParam("oid") Site site) {
    site.delete();
    return Response.ok().build();
}
Example 5
Project: keycloak-master  File: RealmAdminResource.java View source code
/**
     * Delete the realm
     *
     */
@DELETE
public void deleteRealm() {
    auth.requireManage();
    if (!new RealmManager(session).removeRealm(realm)) {
        throw new NotFoundException("Realm doesn't exist");
    }
}
Example 6
Project: bennu-master  File: ExternalApplicationResource.java View source code
@DELETE
@Path("/{app}")
public Response delete(@PathParam("app") ExternalApplication app) {
    verifyAndGetRequestAuthor(app);
    atomic(() -> {
        app.setDeleted();
    });
    return ok();
}
Example 7
Project: sql-layer-master  File: SecurityResource.java View source code
@Path("/users/{user}")
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MEDIATYPE_JSON_JAVASCRIPT)
public Response deleteUser(@Context HttpServletRequest request, @PathParam("user") final String user) {
    RestResponseBuilder response = RestResponseBuilder.forRequest(request);
    if (!request.isUserInRole(SecurityService.ADMIN_ROLE)) {
        return response.status(Response.Status.FORBIDDEN).build();
    }
    response.body(new RestResponseBuilder.BodyGenerator() {

        @Override
        public void write(PrintWriter writer) throws Exception {
            try (Session session = reqs.sessionService.createSession()) {
                reqs.dxlService.ddlFunctions().dropSchema(session, user);
                reqs.securityService.deleteUser(user);
            }
        }
    });
    return response.build();
}
Example 8
Project: AIDR-master  File: CrisisResource.java View source code
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteCrisis(@PathParam("id") Long id) throws PropertyNotSetException {
    int crisisDeleted = crisisLocalEJB.deleteCrisis(id);
    return crisisDeleted == 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 9
Project: Payara-master  File: TemplateRestResource.java View source code
@DELETE
public Response delete(HashMap<String, String> data) {
    return Response.ok(ResourceUtil.getActionReportResult(doDelete(data), localStrings.getLocalString("rest.resource.delete.message", "\"{0}\" deleted successfully.", new Object[] { uriInfo.getAbsolutePath() }), requestHeaders, uriInfo)).build();
//200 - ok
}
Example 10
Project: p4-master  File: Conf.java View source code
@DELETE
@Path("/user")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response deleteUser(@FormParam("userID") String userID) {
    logger.debug("Called deleteUser...");
    ResponseBuilder rb;
    ConfigurationManager.getUserInstance().deleteUser(userID);
    rb = Response.status(Status.OK);
    return rb.build();
}
Example 11
Project: ecms-develop-master  File: WebDavServiceImpl.java View source code
@GET
@Path("/{repoName}/{repoPath:.*}/")
public Response get(@PathParam("repoName") String repoName, @PathParam("repoPath") String repoPath, @HeaderParam(ExtHttpHeaders.RANGE) String rangeHeader, @HeaderParam(ExtHttpHeaders.IF_MODIFIED_SINCE) String ifModifiedSince, @HeaderParam(ExtHttpHeaders.IF_NONE_MATCH) String ifNoneMatch, @QueryParam("version") String version, @Context UriInfo uriInfo) {
    try {
        repoPath = convertRepoPath(repoPath, true);
    } catch (PathNotFoundException exc) {
        return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build();
    } catch (NoSuchWorkspaceException exc) {
        return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build();
    } catch (Exception e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("Cannot find the item at " + repoName + "/" + repoPath, e);
        }
        return Response.serverError().build();
    }
    Response response = super.get(repoName, repoPath, rangeHeader, ifModifiedSince, ifNoneMatch, version, uriInfo);
    if (HTTPStatus.OK == response.getStatus()) {
        return Response.fromResponse(response).header("Access-Control-Allow-Origin", uriInfo.getRequestUri().getHost()).header("Access-Control-Allow-Credentials", true).header("Access-Control-Allow-Methods", "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, " + "MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL").header("Access-Control-Allow-Headers", "Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range," + " Timeout, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Location, Lock-Token, If").header("Access-Control-Expose-Header", "DAV, content-length, Allow").header("Access-Control-Max-Age", 3600).build();
    }
    return response;
}
Example 12
Project: airlift-master  File: TestOverrideMethodFilterInHttpServer.java View source code
@Test
public void testNonOverridableMethodsWithHeader() throws IOException, ExecutionException, InterruptedException {
    assertNonOverridableMethod(buildRequestWithHeader(GET, POST));
    assertNonOverridableMethod(buildRequestWithHeader(GET, DELETE));
    assertNonOverridableMethod(buildRequestWithHeader(GET, PUT));
    assertNonOverridableMethod(buildRequestWithHeader(DELETE, POST));
    assertNonOverridableMethod(buildRequestWithHeader(DELETE, GET));
    assertNonOverridableMethod(buildRequestWithHeader(DELETE, PUT));
    assertNonOverridableMethod(buildRequestWithHeader(PUT, POST));
    assertNonOverridableMethod(buildRequestWithHeader(PUT, DELETE));
    assertNonOverridableMethod(buildRequestWithHeader(PUT, GET));
}
Example 13
Project: libreplan-master  File: OrderElementServiceREST.java View source code
@Override
@DELETE
@Path("/{code}/")
@Transactional
public Response removeOrderElement(@PathParam("code") String code) {
    try {
        OrderElement orderElement = orderElementDAO.findByCode(code);
        String errorMessage = checkRemovalValidation(orderElement);
        if (errorMessage != null) {
            return Response.status(Status.FORBIDDEN).entity(new ErrorDTO(errorMessage)).build();
        }
        if (orderElement.isOrder()) {
            orderModel.remove((Order) orderElement);
        } else {
            Order order = orderDAO.loadOrderAvoidingProxyFor(orderElement);
            orderModel.initEdit(order, null);
            order = orderModel.getOrder();
            orderElement = findOrderElement(order, orderElement.getId());
            OrderLineGroup parent = orderElement.getParent();
            parent.remove(orderElement);
            orderElement.detachFromParent();
            if (!parent.isOrder() && parent.getChildren().isEmpty()) {
                OrderElement newElement = parent.toLeaf();
                if (!order.isCodeAutogenerated()) {
                    newElement.setCode(UUID.randomUUID().toString());
                }
                parent.getParent().replace(parent, newElement);
                parent.detachFromParent();
            }
            orderModel.save();
        }
        return Response.ok().build();
    } catch (InstanceNotFoundException e) {
        return Response.status(Status.NOT_FOUND).build();
    }
}
Example 14
Project: keywhiz-master  File: SecretResource.java View source code
/**
   * Delete a secret series
   *
   * @excludeParams automationClient
   * @param name Secret series name
   *
   * @responseMessage 204 Secret series deleted
   * @responseMessage 404 Secret series not found
   */
@Timed
@ExceptionMetered
@DELETE
@Path("{name}")
public Response deleteSecretSeries(@Auth AutomationClient automationClient, @PathParam("name") String name) {
    secretDAO.getSecretByName(name).orElseThrow(NotFoundException::new);
    secretDAO.deleteSecretsByName(name);
    auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_DELETE, automationClient.getName(), name));
    return Response.noContent().build();
}
Example 15
Project: abiquo-master  File: VirtualMachineResource.java View source code
/**
     * Deletes the virtual machine.<br>
     * A [email protected] VirtualMachine} can only be deleted if is in one allowed are NOT_ALLOCATED and
     * UNKNOWN. allowed
     * <ul>
     * <li><b>NOT_ALLOCATED</b></li>
     * <li><b>UNKNOWN</b></li>
     * </ul>
     * 
     * @title Delete a virtual machine
     * @wiki If the virtual machine exists in the hypervisor it will be removed from the hypervisor
     *       as well.
     * @param vdcId VirtualDatacenter id
     * @param vappId VirtualAppliance id
     * @param vmId VirtualMachine id
     * @param restBuilder injected restbuilder context parameter
     * @throws Exception
     */
@DELETE
public void deleteVirtualMachine(@PathParam(VirtualDatacenterResource.VIRTUAL_DATACENTER) final Integer vdcId, @PathParam(VirtualApplianceResource.VIRTUAL_APPLIANCE) final Integer vappId, @PathParam(VirtualMachineResource.VIRTUAL_MACHINE) final Integer vmId, @Context final IRESTBuilder restBuilder) throws Exception {
    // Check virtual machine state and lock it before starting
    VirtualMachineState originalState = vmLock.lockVirtualMachineBeforeDeleting(vdcId, vappId, vmId);
    try {
        vmService.deleteVirtualMachine(vmId, vappId, vdcId, originalState);
    // If everything goes fine, there is no need to unlock the VM since it will be deleted
    // by the handler or here if it was not deployed
    } catch (Exception ex) {
        vmLock.unlockVirtualMachine(vmId, originalState);
        throw ex;
    }
}
Example 16
Project: kaleido-repository-master  File: ConfigurationController.java View source code
/**
    * remove the property from the configuration
    * 
    * @param config configuration name identifier
    * @param property
    * @throws ConfigurationNotFoundException if configuration can't be found in registry or in database model
    * @throws PropertyNotFoundException if property can't be found in configuration
    * @throws ConfigurationException if configuration is not yet loaded
    */
@DELETE
@Path("/{config}/property/{property}")
public void removeProperty(@PathParam("config") final String config, @PathParam("property") final String property) {
    boolean foundConfiguration = false;
    boolean foundConfigurationProperty = false;
    if (em != null) {
        ConfigurationModel configurationModel = findConfigurationModelByName(config, false);
        if (configurationModel != null) {
            foundConfiguration = true;
            ConfigurationProperty configurationProperty = configurationModel.getPropertiesByName().get(property);
            if (configurationProperty != null) {
                foundConfigurationProperty = true;
                // remove it from meta data database
                configurationModel.getProperties().remove(configurationProperty);
                em.merge(configurationModel);
                em.remove(em.merge(configurationProperty));
                em.flush();
            }
        }
    }
    try {
        Configuration configuration = getRegisteredConfiguration(config);
        // check if property exists
        if (!foundConfigurationProperty && !configuration.containsKey(property)) {
            throw new PropertyNotFoundException(config, property);
        }
        // remove it from registered configuration
        configuration.removeProperty(property);
    } catch (ConfigurationNotFoundException cnfe) {
        if (!foundConfiguration) {
            throw cnfe;
        }
        if (!foundConfigurationProperty) {
            throw new PropertyNotFoundException(config, property);
        }
    }
}
Example 17
Project: visuwall-master  File: ZNodeResource.java View source code
@DELETE
@Produces({ MediaType.APPLICATION_JSON, "application/javascript", MediaType.APPLICATION_XML, MediaType.APPLICATION_OCTET_STREAM })
public void deleteZNode(@PathParam("path") String path, @DefaultValue("-1") @QueryParam("version") String versionParam, @Context UriInfo ui) throws InterruptedException, KeeperException {
    ensurePathNotNull(path);
    int version;
    try {
        version = Integer.parseInt(versionParam);
    } catch (NumberFormatException e) {
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(new ZError(ui.getRequestUri().toString(), path + " bad version " + versionParam)).build());
    }
    zk.delete(path, version);
}
Example 18
Project: thermospy-master  File: LogSessionResource.java View source code
@DELETE
@Timed
@UnitOfWork
@Path("/{id}")
public Response delete(@PathParam("id") IntParam id) {
    LogSession s = controller.getLogSession();
    if (s != null && s.getId() == id.get()) {
        controller.setLogSession(null);
    }
    temperatureEntryDao.deleteAllBySessionId(id.get());
    boolean result = sessionDao.delete(id.get());
    if (result)
        return Response.ok(id.get()).build();
    else
        return Response.serverError().build();
}
Example 19
Project: linshare-core-master  File: DocumentRestServiceImpl.java View source code
@DELETE
@Path("/{uuid}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Delete a document.", response = DocumentDto.class)
@ApiResponses({ @ApiResponse(code = 403, message = "Current logged in account does not have the delegation role."), @ApiResponse(code = 404, message = "Document not found."), @ApiResponse(code = 400, message = "Bad request : missing required fields."), @ApiResponse(code = 500, message = "Internal server error.") })
@Override
public DocumentDto delete(@ApiParam(value = "The document uuid.", required = true) @PathParam("uuid") String uuid) throws BusinessException {
    return documentFacade.delete(uuid);
}
Example 20
Project: stickypunch-master  File: SafariPushResource.java View source code
@DELETE
@Path("/devices/{deviceToken}/registrations/{websitePushId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response disableRegistration(@Context HttpHeaders headers, @PathParam("deviceToken") String deviceToken, @PathParam("websitePushId") String websitePushId) throws Exception {
    Optional<String> userIdOptional = extractandUserId(headers);
    if (!auth(userIdOptional, Optional.of(deviceToken))) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }
    updateUserId(userIdOptional, false, websitePushId, deviceToken);
    return Response.ok().build();
}
Example 21
Project: iaf-master  File: Init.java View source code
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllResources() {
    List<Object> resources = new ArrayList<Object>();
    ResourceMethodRegistry registry = (ResourceMethodRegistry) dispatcher.getRegistry();
    for (Map.Entry<String, List<ResourceInvoker>> entry : registry.getBounded().entrySet()) {
        for (ResourceInvoker invoker : entry.getValue()) {
            Method method = invoker.getMethod();
            if (method.getDeclaringClass() == getClass()) {
                continue;
            }
            Map<String, Object> resource = new HashMap<String, Object>(3);
            if (method.isAnnotationPresent(GET.class))
                resource.put("method", "GET");
            else if (method.isAnnotationPresent(POST.class))
                resource.put("method", "POST");
            else if (method.isAnnotationPresent(PUT.class))
                resource.put("method", "PUT");
            else if (method.isAnnotationPresent(DELETE.class))
                resource.put("method", "DELETE");
            Path path = method.getAnnotation(Path.class);
            if (path != null) {
                resource.put("path", path.value());
            }
            RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
            if (rolesAllowed != null) {
                resource.put("allowed", rolesAllowed.value());
            }
            resources.add(resource);
        }
    }
    return Response.status(Response.Status.CREATED).entity(resources).build();
}
Example 22
Project: dcache-master  File: FileResources.java View source code
@DELETE
@Path("{value : .*}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteFileEntry(@PathParam("value") String value) throws CacheException {
    PnfsHandler handler = ServletContextHandlerAttributes.getPnfsHandler(ctx);
    PathMapper pathMapper = ServletContextHandlerAttributes.getPathMapper(ctx);
    FsPath path = pathMapper.asDcachePath(request, value);
    try {
        handler.deletePnfsEntry(path.toString(), EnumSet.of(FileType.REGULAR));
    } catch (FileNotFoundCacheException e) {
        throw new NotFoundException(e);
    } catch (PermissionDeniedCacheException e) {
        if (Subjects.isNobody(ServletContextHandlerAttributes.getSubject())) {
            throw new NotAuthorizedException(e);
        } else {
            throw new ForbiddenException(e);
        }
    } catch (JSONExceptionIllegalArgumentException | CacheException |  e) {
        throw new BadRequestException(e);
    } catch (Exception e) {
        throw new InternalServerErrorException(e);
    }
    return successfulResponse(Response.Status.OK);
}
Example 23
Project: usergrid-master  File: CollectionResource.java View source code
/**
     * Delete settings for a collection.
     */
@DELETE
@Path("{itemName}/_settings")
@Produces({ MediaType.APPLICATION_JSON, "application/javascript" })
@RequireApplicationAccess
@JSONP
public ApiResponse executeDeleteOnSettingsWithCollectionName(@Context UriInfo ui, @PathParam("itemName") PathSegment itemName, String body, @QueryParam("callback") @DefaultValue("callback") String callback) throws Exception {
    if (logger.isTraceEnabled()) {
        logger.trace("CollectionResource.executeDeleteOnSettingsWithCollectionName");
    }
    addItemToServiceContext(ui, itemName);
    ApiResponse response = createApiResponse();
    response.setAction("delete");
    response.setApplication(services.getApplication());
    response.setParams(ui.getQueryParameters());
    emf.getEntityManager(services.getApplicationId()).deleteCollectionSettings(itemName.getPath().toLowerCase());
    return response;
}
Example 24
Project: fiware-rss-master  File: RSSModelService.java View source code
/**
     * Delete Rss Models.
     * 
     * @param aggregatorId
     * @param appProvider
     * @param productClass
     * @return
     * @throws Exception
     */
@WebMethod
@DELETE
@Path("/")
@Consumes("application/json")
public Response deleteRSSModel(@QueryParam("aggregatorId") String aggregatorId, @QueryParam("appProviderId") String appProvider, @QueryParam("productClass") String productClass) throws Exception {
    RSSModelService.logger.debug("Into deleteRSSModel method");
    // check security
    RSUser user = userManager.getCurrentUser();
    String effectiveAggregator;
    if (userManager.isAdmin()) {
        effectiveAggregator = aggregatorId;
    } else if (null == aggregatorId || aggregatorId.equals(user.getEmail())) {
        effectiveAggregator = user.getEmail();
    } else {
        String[] args = { "You are not allowed to remove RS Models for the given aggregator" };
        throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
    }
    // Call service
    rssModelsManager.deleteRssModel(effectiveAggregator, appProvider, productClass);
    // Building response
    ResponseBuilder rb = Response.status(Response.Status.OK.getStatusCode());
    return rb.build();
}
Example 25
Project: proarc-master  File: DigitalObjectResource.java View source code
/**
     * @see PurgeFedoraObject
     */
@DELETE
@Produces({ MediaType.APPLICATION_JSON })
public SmartGwtResponse<DigitalObject> deleteObject(@QueryParam(DigitalObjectResourceApi.DELETE_PID_PARAM) List<String> pids, @QueryParam(DigitalObjectResourceApi.DELETE_HIERARCHY_PARAM) @DefaultValue("true") boolean hierarchy, @QueryParam(DigitalObjectResourceApi.DELETE_PURGE_PARAM) @DefaultValue("false") boolean purge) throws IOException, PurgeException {
    RemoteStorage fedora = RemoteStorage.getInstance(appConfig);
    ArrayList<DigitalObject> result = new ArrayList<DigitalObject>(pids.size());
    PurgeFedoraObject service = new PurgeFedoraObject(fedora);
    if (purge) {
        session.requirePermission(Permissions.ADMIN);
        service.purge(pids, hierarchy, session.asFedoraLog());
    } else {
        service.delete(pids, hierarchy, session.asFedoraLog());
    }
    for (String pid : pids) {
        result.add(new DigitalObject(pid, null));
    }
    return new SmartGwtResponse<DigitalObject>(result);
}
Example 26
Project: iot-server-appliances-master  File: FireAlarmManagerService.java View source code
@Path("/device/remove/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) {
    DeviceManagement deviceManagement = new DeviceManagement();
    DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
    deviceIdentifier.setId(deviceId);
    deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE);
    try {
        boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(deviceIdentifier);
        if (removed) {
            response.setStatus(HttpStatus.SC_OK);
        } else {
            response.setStatus(HttpStatus.SC_EXPECTATION_FAILED);
        }
    } catch (DeviceManagementException e) {
        log.error(e.getErrorMessage());
    }
}
Example 27
Project: magnificent-mileage-master  File: Routers.java View source code
/** De-register all registered routerIds, evicting them from memory. */
@Secured({ "ROLE_ROUTERS" })
@DELETE
@Produces({ MediaType.TEXT_PLAIN })
public Response deleteAll() {
    int nEvicted = graphService.evictAll();
    String message = String.format("%d graphs evicted.", nEvicted);
    return Response.status(200).entity(message).build();
}
Example 28
Project: org.openntf.domino-master  File: FramedResource.java View source code
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@SuppressWarnings("rawtypes")
public Response deleteFramedObject(String requestEntity, @Context final UriInfo uriInfo, @PathParam(Routes.NAMESPACE) final String namespace) {
    DFramedTransactionalGraph graph = this.getGraph(namespace);
    String jsonEntity = null;
    ResponseBuilder builder = Response.ok();
    ParamMap pm = Parameters.toParamMap(uriInfo);
    StringWriter sw = new StringWriter();
    JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true);
    JsonGraphFactory factory = JsonGraphFactory.instance;
    Map<String, String> report = new HashMap<String, String>();
    List<String> ids = pm.get(Parameters.ID);
    if (ids.size() == 0) {
    // TODO no id
    } else {
        for (String id : ids) {
            try {
                NoteCoordinate nc = NoteCoordinate.Utils.getNoteCoordinate(id);
                Object element = graph.getElement(nc, null);
                if (element instanceof Element) {
                    ((Element) element).remove();
                } else if (element instanceof VertexFrame) {
                    ((VertexFrame) element).asVertex().remove();
                } else if (element instanceof EdgeFrame) {
                    ((EdgeFrame) element).asEdge().remove();
                }
                report.put(id, "deleted");
            } catch (Throwable t) {
                DominoUtils.handleException(t);
            }
        }
        graph.commit();
    }
    try {
        writer.outObject(report);
    } catch (JsonException e) {
        DominoUtils.handleException(e);
    } catch (IOException e) {
        DominoUtils.handleException(e);
    }
    builder.type(MediaType.APPLICATION_JSON_TYPE).entity(sw.toString());
    Response response = builder.build();
    return response;
}
Example 29
Project: platform-api-master  File: AccountService.java View source code
/**
     * Removes attribute with given name from certain account.
     *
     * @param accountId
     *         account identifier
     * @param attributeName
     *         attribute name to remove attribute
     * @throws ConflictException
     *         if attribute name is not valid
     * @throws NotFoundException
     *         if account with given identifier doesn't exist
     * @throws ServerException
     *         when some error occurred while getting/updating account
     */
@ApiOperation(value = "Delete account attribute", notes = "Remove attribute from an account. Attribute name is used as a quary parameter. For this API request account/owner, system/admin or system/manager role is required", position = 4)
@ApiResponses(value = { @ApiResponse(code = 204, message = "OK"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 409, message = "Invalid attribute name"), @ApiResponse(code = 500, message = "Internal Server Error") })
@DELETE
@Path("/{id}/attribute")
@RolesAllowed({ "account/owner", "system/admin", "system/manager" })
public void removeAttribute(@ApiParam(value = "Account ID", required = true) @PathParam("id") String accountId, @ApiParam(value = "Attribute name to be removed", required = true) @QueryParam("name") String attributeName) throws ConflictException, NotFoundException, ServerException {
    validateAttributeName(attributeName);
    final Account account = accountDao.getById(accountId);
    account.getAttributes().remove(attributeName);
    accountDao.update(account);
}
Example 30
Project: HDP-2.2-Patched-master  File: HttpFSServer.java View source code
/**
   * Binding to handle DELETE requests.
   *
   * @param user the principal of the user making the request.
   * @param path the path for operation.
   * @param op the HttpFS operation of the request.
   * @param params the HttpFS parameters of the request.
   *
   * @return the request response.
   *
   * @throws IOException thrown if an IO error occurred. Thrown exceptions are
   * handled by [email protected] HttpFSExceptionProvider}.
   * @throws FileSystemAccessException thrown if a FileSystemAccess releated
   * error occurred. Thrown exceptions are handled by
   * [email protected] HttpFSExceptionProvider}.
   */
@DELETE
@Path("{path:.*}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(@Context Principal user, @PathParam("path") String path, @QueryParam(OperationParam.NAME) OperationParam op, @Context Parameters params) throws IOException, FileSystemAccessException {
    Response response;
    path = makeAbsolute(path);
    MDC.put(HttpFSFileSystem.OP_PARAM, op.value().name());
    String doAs = params.get(DoAsParam.NAME, DoAsParam.class);
    switch(op.value()) {
        case DELETE:
            {
                Boolean recursive = params.get(RecursiveParam.NAME, RecursiveParam.class);
                AUDIT_LOG.info("[{}] recursive [{}]", path, recursive);
                FSOperations.FSDelete command = new FSOperations.FSDelete(path, recursive);
                JSONObject json = fsExecute(user, doAs, command);
                response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
                break;
            }
        default:
            {
                throw new IOException(MessageFormat.format("Invalid HTTP DELETE operation [{0}]", op.value()));
            }
    }
    return response;
}
Example 31
Project: dswarm-graph-neo4j-master  File: MaintainResource.java View source code
/**
	 * note utilise this endpoint with care, because it cleans your complete db!
	 *
	 * @param database the graph database
	 */
@DELETE
@Path("/delete")
@Produces("application/json")
public Response cleanGraph(@Context final GraphDatabaseService database) throws IOException, DMPGraphException {
    MaintainResource.LOG.debug("start cleaning up the db");
    final long deleted = deleteSomeStatements(database);
    MaintainResource.LOG.debug("finished delete-all-entities TXs");
    MaintainResource.LOG.debug("start legacy indices clean-up");
    // TODO: maybe separate index clean-up + observe index clean-up
    // => maybe we also need to do a label + relationship types clean-up ... => this is not supported right now ...
    deleteSomeLegacyIndices(database);
    MaintainResource.LOG.debug("finished legacy indices clean-up");
    MaintainResource.LOG.debug("start schema indices clean-up");
    deleteSomeSchemaIndices(database);
    MaintainResource.LOG.debug("finished schema indices clean-up");
    MaintainResource.LOG.debug("finished cleaning up the db");
    final StringWriter out = new StringWriter();
    final JsonGenerator generator = simpleObjectMapper.getFactory().createGenerator(out);
    generator.writeStartObject();
    generator.writeNumberField("deleted", deleted);
    generator.writeEndObject();
    generator.flush();
    generator.close();
    final String result = out.toString();
    out.flush();
    out.close();
    return Response.ok(result, MediaType.APPLICATION_JSON_TYPE).build();
}
Example 32
Project: yarn-comment-master  File: NamenodeWebHdfsMethods.java View source code
/** Handle HTTP DELETE request for the root. */
@DELETE
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteRoot(@Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT) final DeleteOpParam op, @QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT) final RecursiveParam recursive) throws IOException, InterruptedException {
    return delete(ugi, delegation, username, doAsUser, ROOT, op, recursive);
}
Example 33
Project: REST-OCD-Services-master  File: ServiceClass.java View source code
/**
     * Deletes a graph.
     * All covers based on the graph are removed as well.
     * If a benchmark is currently calculating the graph the execution is terminated.
     * If an algorithm is currently calculating a cover based on the graph it is terminated.
     * If a metric is currently running on a cover based on the grap it is terminated.
     * @param graphIdStr The graph id.
     * @return A confirmation xml.
     * Or an error xml.
     */
@DELETE
@Path("graphs/{graphId}")
@Produces(MediaType.TEXT_XML)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 401, message = "Unauthorized") })
@ApiOperation(value = "", notes = "Deletes a graph.")
public String deleteGraph(@PathParam("graphId") String graphIdStr) {
    try {
        long graphId;
        String username = ((UserAgent) getActiveAgent()).getLoginName();
        try {
            graphId = Long.parseLong(graphIdStr);
        } catch (Exception e) {
            requestHandler.log(Level.WARNING, "user: " + username, e);
            return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph id is not valid.");
        }
        EntityManager em = requestHandler.getEntityManager();
        CustomGraphId id = new CustomGraphId(graphId, username);
        CustomGraph graph;
        synchronized (threadHandler) {
            EntityTransaction tx = em.getTransaction();
            try {
                tx.begin();
                graph = em.find(CustomGraph.class, id);
                if (graph == null) {
                    requestHandler.log(Level.WARNING, "user: " + username + ", " + "Graph does not exist: graph id " + graphId);
                    return requestHandler.writeError(Error.PARAMETER_INVALID, "Graph does not exist: graph id " + graphId);
                }
                tx.commit();
            } catch (RuntimeException e) {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
                throw e;
            }
            threadHandler.interruptBenchmark(id);
            List<Cover> queryResults;
            String queryStr = "SELECT c from Cover c" + " JOIN c." + Cover.GRAPH_FIELD_NAME + " g" + " WHERE g." + CustomGraph.USER_NAME_FIELD_NAME + " = :username" + " AND g." + CustomGraph.ID_FIELD_NAME + " = " + graphId;
            TypedQuery<Cover> query = em.createQuery(queryStr, Cover.class);
            query.setParameter("username", username);
            queryResults = query.getResultList();
            for (Cover cover : queryResults) {
                threadHandler.interruptAll(cover);
                tx = em.getTransaction();
                try {
                    tx.begin();
                    em.remove(cover);
                    tx.commit();
                } catch (RuntimeException e) {
                    if (tx != null && tx.isActive()) {
                        tx.rollback();
                    }
                    throw e;
                }
            }
            try {
                tx = em.getTransaction();
                tx.begin();
                em.remove(graph);
                tx.commit();
            } catch (RuntimeException e) {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
                throw e;
            }
        }
        return requestHandler.writeConfirmationXml();
    } catch (Exception e) {
        requestHandler.log(Level.SEVERE, "", e);
        return requestHandler.writeError(Error.INTERNAL, "Internal system error.");
    }
}
Example 34
Project: modeshape-master  File: ModeShapeRestService.java View source code
/**
     * Deletes the item at [email protected] path}.
     *
     * @param request the servlet request; may not be null or unauthenticated
     * @param rawRepositoryName the URL-encoded repository name
     * @param rawWorkspaceName the URL-encoded workspace name
     * @param path the path to the item
     * @return a [email protected] non-null} [email protected] Response} instance.
     * @throws RepositoryException if any other error occurs
     */
@DELETE
@Path("{repositoryName}/{workspaceName}/" + RestHelper.ITEMS_METHOD_NAME + "{path:.+}")
public Response deleteItem(@Context HttpServletRequest request, @PathParam("repositoryName") String rawRepositoryName, @PathParam("workspaceName") String rawWorkspaceName, @PathParam("path") String path) throws RepositoryException {
    itemHandler.deleteItem(request, rawRepositoryName, rawWorkspaceName, path);
    return Response.noContent().build();
}