Search in sources :

Example 51 with POST

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

the class SshService method createPair.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML)
@GenerateLink(rel = Constants.LINK_REL_CREATE_PAIR)
public Response createPair(Iterator<FileItem> formData) throws BadRequestException, ServerException, ConflictException {
    String service = null;
    String name = null;
    String privateKey = null;
    String publicKey = null;
    while (formData.hasNext()) {
        FileItem item = formData.next();
        String fieldName = item.getFieldName();
        switch(fieldName) {
            case "service":
                service = item.getString();
                break;
            case "name":
                name = item.getString();
                break;
            case "privateKey":
                privateKey = item.getString();
                break;
            case "publicKey":
                publicKey = item.getString();
                break;
            default:
        }
    }
    requiredNotNull(service, "Service name required");
    requiredNotNull(name, "Name required");
    if (privateKey == null && publicKey == null) {
        throw new BadRequestException("Key content was not provided.");
    }
    sshManager.createPair(new SshPairImpl(getCurrentUserId(), service, name, publicKey, privateKey));
    // through specific of html form that doesn't invoke complete submit handler
    return Response.ok("", MediaType.TEXT_HTML).build();
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) SshPairImpl(org.eclipse.che.api.ssh.server.model.impl.SshPairImpl) BadRequestException(org.eclipse.che.api.core.BadRequestException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GenerateLink(org.eclipse.che.api.core.rest.annotations.GenerateLink)

Example 52 with POST

use of javax.ws.rs.POST in project SimianArmy by Netflix.

the class JanitorMonkeyResource method addEvent.

/**
     * POST /api/v1/janitor will try a add a new event with the information in the url context.
     *
     * @param content
     *            the Json content passed to the http POST request
     * @return the response
     * @throws IOException
     */
@POST
public Response addEvent(String content) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    LOGGER.info(String.format("JSON content: '%s'", content));
    JsonNode input = mapper.readTree(content);
    String eventType = getStringField(input, "eventType");
    String resourceId = getStringField(input, "resourceId");
    String region = getStringField(input, "region");
    Response.Status responseStatus;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8);
    gen.writeStartObject();
    gen.writeStringField("eventType", eventType);
    gen.writeStringField("resourceId", resourceId);
    if (StringUtils.isEmpty(eventType) || StringUtils.isEmpty(resourceId)) {
        responseStatus = Response.Status.BAD_REQUEST;
        gen.writeStringField("message", "eventType and resourceId parameters are all required");
    } else {
        if (eventType.equals("OPTIN")) {
            responseStatus = optInResource(resourceId, true, region, gen);
        } else if (eventType.equals("OPTOUT")) {
            responseStatus = optInResource(resourceId, false, region, gen);
        } else {
            responseStatus = Response.Status.BAD_REQUEST;
            gen.writeStringField("message", String.format("Unrecognized event type: %s", eventType));
        }
    }
    gen.writeEndObject();
    gen.close();
    LOGGER.info("entity content is '{}'", baos.toString("UTF-8"));
    return Response.status(responseStatus).entity(baos.toString("UTF-8")).build();
}
Also used : Response(javax.ws.rs.core.Response) JsonGenerator(org.codehaus.jackson.JsonGenerator) JsonNode(org.codehaus.jackson.JsonNode) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) POST(javax.ws.rs.POST)

Example 53 with POST

use of javax.ws.rs.POST in project eureka by Netflix.

the class ApplicationResource method addInstance.

/**
     * Registers information about a particular instance for an
     * {@link com.netflix.discovery.shared.Application}.
     *
     * @param info
     *            {@link InstanceInfo} information of the instance.
     * @param isReplication
     *            a header parameter containing information whether this is
     *            replicated from other nodes.
     */
@POST
@Consumes({ "application/json", "application/xml" })
public Response addInstance(InstanceInfo info, @HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication) {
    logger.debug("Registering instance {} (replication={})", info.getId(), isReplication);
    // validate that the instanceinfo contains all the necessary required fields
    if (isBlank(info.getId())) {
        return Response.status(400).entity("Missing instanceId").build();
    } else if (isBlank(info.getHostName())) {
        return Response.status(400).entity("Missing hostname").build();
    } else if (isBlank(info.getAppName())) {
        return Response.status(400).entity("Missing appName").build();
    } else if (!appName.equals(info.getAppName())) {
        return Response.status(400).entity("Mismatched appName, expecting " + appName + " but was " + info.getAppName()).build();
    } else if (info.getDataCenterInfo() == null) {
        return Response.status(400).entity("Missing dataCenterInfo").build();
    } else if (info.getDataCenterInfo().getName() == null) {
        return Response.status(400).entity("Missing dataCenterInfo Name").build();
    }
    // handle cases where clients may be registering with bad DataCenterInfo with missing data
    DataCenterInfo dataCenterInfo = info.getDataCenterInfo();
    if (dataCenterInfo instanceof UniqueIdentifier) {
        String dataCenterInfoId = ((UniqueIdentifier) dataCenterInfo).getId();
        if (isBlank(dataCenterInfoId)) {
            boolean experimental = "true".equalsIgnoreCase(serverConfig.getExperimental("registration.validation.dataCenterInfoId"));
            if (experimental) {
                String entity = "DataCenterInfo of type " + dataCenterInfo.getClass() + " must contain a valid id";
                return Response.status(400).entity(entity).build();
            } else if (dataCenterInfo instanceof AmazonInfo) {
                AmazonInfo amazonInfo = (AmazonInfo) dataCenterInfo;
                String effectiveId = amazonInfo.get(AmazonInfo.MetaDataKey.instanceId);
                if (effectiveId == null) {
                    amazonInfo.getMetadata().put(AmazonInfo.MetaDataKey.instanceId.getName(), info.getId());
                }
            } else {
                logger.warn("Registering DataCenterInfo of type {} without an appropriate id", dataCenterInfo.getClass());
            }
        }
    }
    registry.register(info, "true".equals(isReplication));
    // 204 to be backwards compatible
    return Response.status(204).build();
}
Also used : UniqueIdentifier(com.netflix.appinfo.UniqueIdentifier) DataCenterInfo(com.netflix.appinfo.DataCenterInfo) AmazonInfo(com.netflix.appinfo.AmazonInfo) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 54 with POST

use of javax.ws.rs.POST in project OpenAttestation by OpenAttestation.

the class AbstractSimpleResource method deleteOne.

//    /**
//     * Add an item to the collection. Input Content-Type is any of
//     * application/json, application/xml, application/yaml, or text/yaml Output
//     * Content-Type is any of application/json, application/xml,
//     * application/yaml, or text/yaml
//     *
//     * The input must represent a single item NOT wrapped in a collection.
//     *
//     * @param item
//     * @return
//     */
//    @POST
//    public T createOne(@BeanParam L locator, T item, @Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse){
//        //try { log.debug("createOne: {}", mapper.writeValueAsString(locator)); } catch(JsonProcessingException e) { log.debug("createOne: cannot serialize locator: {}", e.getMessage()); }
//        try { log.debug("createOne: {}", mapper.writeValueAsString(locator)); } catch(Exception e) { log.debug("createOne: cannot serialize locator: {}", e.getMessage()); }
//        locator.copyTo(item);
//        ValidationUtil.validate(item); // throw new MWException(e, ErrorCode.AS_INPUT_VALIDATION_ERROR, input, method.getName());
//        if (item.getId() == null) {
//            item.setId(new UUID());
//        }
//        getRepository().create(item);
//        httpServletResponse.setStatus(Status.CREATED.getStatusCode());
//        return item;
//    }
// the delete method is on a specific resource id and because we don't return any content it's the same whether its simple object or json api 
// jersey automatically returns status code 204 No Content (successful) to the client because
// we have a void return type
@Path("/{id}")
@DELETE
public void deleteOne(@BeanParam L locator, @Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse) throws IOException {
    try {
        log.debug("deleteOne: {}", mapper.writeValueAsString(locator));
    } catch (JsonProcessingException e) {
        log.debug("deleteOne: cannot serialize locator: {}", e.getMessage());
    }
    // subclass is responsible for validating the id in whatever manner it needs to;  most will return null if !UUID.isValid(id)  but we don't do it here because a resource might want to allow using something other than uuid as the url key, for example uuid OR hostname for hosts
    T item = getRepository().retrieve(locator);
    if (item == null) {
        throw new WebApplicationException(Response.Status.NOT_FOUND);
    }
    getRepository().delete(locator);
    httpServletResponse.setStatus(Status.NO_CONTENT.getStatusCode());
/*
        T item = getRepository().retrieve(id); // subclass is responsible for validating the id in whatever manner it needs to;  most will return null if !UUID.isValid(id)  but we don't do it here because a resource might want to allow using something other than uuid as the url key, for example uuid OR hostname for hosts
        if (item == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND); 
        }
        getRepository().delete(id);*/
/*
//        C collection = getRepository().search(selector);
//        if( collection.getDocuments().isEmpty() ) {            
//            throw new WebApplicationException(Response.Status.NOT_FOUND); 
//        }
//        T item = collection.getDocuments().get(0);
        
//        getRepository().delete(item.getId().toString());
* */
}
Also used : GET(javax.ws.rs.GET) POST(javax.ws.rs.POST) PUT(javax.ws.rs.PUT) WebApplicationException(javax.ws.rs.WebApplicationException) JsonProcessingException(org.codehaus.jackson.JsonProcessingException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE)

Example 55 with POST

use of javax.ws.rs.POST in project OpenAttestation by OpenAttestation.

the class AbstractJsonapiResource method createJsonapiCollection.

/**
     * Add an item to the collection. Input Content-Type is
     * application/vnd.api+json Output Content-Type is application/vnd.api+json
     *
     * The input must represent a collection of items to add, even if the
     * collection only contains a single item.
     *
     *
     * @param collection
     * @return
     */
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public C createJsonapiCollection(C collection) {
    log.debug("createCollection");
    ValidationUtil.validate(collection);
    // this behavior of autmoatically generating uuids if client didn't provide could be implemented in one place and reused in all create() methods...  the utility could accept a DocumentCollection and set the ids... 
    for (T item : collection.getDocuments()) {
        if (item.getId() == null) {
            item.setId(new UUID());
        }
        getRepository().create(item);
    }
    return collection;
}
Also used : POST(javax.ws.rs.POST) GET(javax.ws.rs.GET) PUT(javax.ws.rs.PUT) UUID(com.intel.mtwilson.util.io.UUID) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

POST (javax.ws.rs.POST)513 Path (javax.ws.rs.Path)360 Consumes (javax.ws.rs.Consumes)242 Produces (javax.ws.rs.Produces)222 ApiOperation (io.swagger.annotations.ApiOperation)133 ApiResponses (io.swagger.annotations.ApiResponses)107 IOException (java.io.IOException)74 URI (java.net.URI)63 WebApplicationException (javax.ws.rs.WebApplicationException)62 Timed (com.codahale.metrics.annotation.Timed)55 Response (javax.ws.rs.core.Response)50 TimedResource (org.killbill.commons.metrics.TimedResource)36 CallContext (org.killbill.billing.util.callcontext.CallContext)35 AuditEvent (org.graylog2.audit.jersey.AuditEvent)33 HashMap (java.util.HashMap)32 BadRequestException (co.cask.cdap.common.BadRequestException)24 AuditPolicy (co.cask.cdap.common.security.AuditPolicy)24 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)23 Account (org.killbill.billing.account.api.Account)22 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)20