Java Code Examples for javax.ws.rs.Consumes

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Ivory, under directory /prism/src/main/java/org/apache/ivory/resource/channel/.

Source file: HTTPChannel.java

  22 
vote

private String getConsumes(Method method){
  Consumes consumes=method.getAnnotation(Consumes.class);
  if (consumes == null || consumes.value() == null) {
    return MediaType.TEXT_PLAIN;
  }
  return consumes.value()[0];
}
 

Example 2

From project airlift, under directory /sample-server/src/main/java/io/airlift/sample/.

Source file: PersonResource.java

  19 
vote

@PUT @Consumes(MediaType.APPLICATION_JSON) public Response put(@PathParam("id") String id,PersonRepresentation person){
  Preconditions.checkNotNull(id,"id must not be null");
  Preconditions.checkNotNull(person,"person must not be null");
  boolean added=store.put(id,person.toPerson());
  if (added) {
    UriBuilder uri=UriBuilder.fromResource(PersonResource.class);
    return Response.created(uri.build(id)).build();
  }
  return Response.noContent().build();
}
 

Example 3

From project amber, under directory /oauth-2.0/integration-tests/src/test/java/org/apache/amber/oauth2/integration/endpoints/.

Source file: RegistrationEndpoint.java

  19 
vote

@POST @Consumes("application/json") @Produces("application/json") public Response register(@Context HttpServletRequest request) throws OAuthSystemException {
  OAuthServerRegistrationRequest oauthRequest=null;
  try {
    oauthRequest=new OAuthServerRegistrationRequest(new JSONHttpServletRequestWrapper(request));
    oauthRequest.discover();
    oauthRequest.getClientName();
    oauthRequest.getClientUrl();
    oauthRequest.getClientDescription();
    oauthRequest.getRedirectURI();
    OAuthResponse response=OAuthServerRegistrationResponse.status(HttpServletResponse.SC_OK).setClientId(CommonExt.CLIENT_ID).setClientSecret(CommonExt.CLIENT_SECRET).setIssuedAt(CommonExt.ISSUED_AT).setExpiresIn(CommonExt.EXPIRES_IN).buildJSONMessage();
    return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
  }
 catch (  OAuthProblemException e) {
    OAuthResponse response=OAuthServerRegistrationResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e).buildJSONMessage();
    return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
  }
}
 

Example 4

From project Arecibo, under directory /alertmanager/src/main/java/com/ning/arecibo/alertmanager/resources/.

Source file: AlertingConfigurationsResource.java

  19 
vote

@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @TimedResource public Response createAlertingConfiguration(@FormParam("config_name") final String alertingConfigName,@FormParam("is_config_enabled") final String enabled,@FormParam("notify_on_recovery") final String notifyOnRecovery,@FormParam("repeat_mode") final String repeatMode,@FormParam("notification_groups") final List<Integer> notificationGroups){
  boolean repeatUntilCleared=false;
  if (repeatMode != null && repeatMode.equals("UNTIL_CLEARED")) {
    repeatUntilCleared=true;
  }
  final int alertingConfigId=client.createAlertingConfig(alertingConfigName,repeatUntilCleared,notifyOnRecovery != null,enabled != null,notificationGroups);
  log.info("Created alerting config %s (id=%d)",alertingConfigName,alertingConfigId);
  return Response.seeOther(URI.create("/ui/alerting")).build();
}
 

Example 5

From project arquillian-showcase, under directory /extensions/resteasy/src/test/java/org/jboss/arquillian/extension/rest/.

Source file: RestClientTestCase.java

  19 
vote

@Test @GET @Path("rest/customer") @Consumes(MediaType.APPLICATION_XML) public void shouldBeAbleToListAllCustomers(ClientResponse<List<Customer>> response){
  Assert.assertEquals(Status.OK.getStatusCode(),response.getStatus());
  List<Customer> customers=response.getEntity(new GenericType<List<Customer>>(){
  }
);
  Assert.assertEquals(2,customers.size());
}
 

Example 6

From project bpm-console, under directory /server/war/src/main/java/org/jboss/bpm/console/server/util/.

Source file: RsDocBuilder.java

  19 
vote

private StringBuffer build(Class root){
  Path rootPath=(Path)root.getAnnotation(Path.class);
  RsComment rootComment=(RsComment)root.getAnnotation(RsComment.class);
  List<Representation> representations=new ArrayList<Representation>();
  for (  Method m : root.getDeclaredMethods()) {
    Path resPath=m.getAnnotation(Path.class);
    if (resPath != null) {
      Representation r=new Representation();
      r.path=resPath.value();
      r.httpMethod=m.getAnnotation(GET.class) != null ? "GET" : "POST";
      r.consume=(m.getAnnotation(Consumes.class) != null) ? arrayToString(m.getAnnotation(Consumes.class).value()) : "*/*";
      r.produce=(m.getAnnotation(Produces.class) != null) ? arrayToString(m.getAnnotation(Produces.class).value()) : "*/*";
      representations.add(r);
    }
  }
  StringBuffer sb=new StringBuffer();
  if (rootComment != null) {
    sb.append("<tr>");
    sb.append("<td colspan=5 style='border-bottom:1px solid black;'>");
    sb.append("<b>").append(rootComment.title()).append("</b>").append("<br>");
    sb.append("<i>").append(rootComment.description()).append("</i>");
    sb.append("</td>");
    sb.append("</tr>");
  }
  for (  Representation r : representations) {
    sb.append("<tr>");
    sb.append("<td>").append(r.httpMethod.toUpperCase()).append("</td>");
    sb.append("<td>").append(buildPath(rootPath.value(),r.path)).append("</td>");
    sb.append("<td>").append("").append("</td>");
    sb.append("<td>").append(r.consume).append("</td>");
    sb.append("<td>").append(r.produce).append("</td>");
    sb.append("</tr>");
  }
  sb.append("<tr><td colspan=5>&nbsp;</td></tr>");
  return sb;
}
 

Example 7

From project candlepin, under directory /src/main/java/org/candlepin/resource/.

Source file: ConsumerResource.java

  19 
vote

/** 
 * Request a list of pools and quantities that would result in an actual auto-bind. This is a dry run of an autobind. It allows the client to see what would be the result of an autobind without executing it. It can only do this for the prevously established list of installed products for the consumer If a service level is included in the request, then that level will override the one stored on the consumer. If no service level is included then the existing one will be used.
 * @param consumerUuid Consumer identifier to be entitled
 * @param serviceLevel String service level override to be used for run
 * @return Response with a list of PoolQuantities containing the pool and number.
 * @httpcode 400
 * @httpcode 403
 * @httpcode 404
 * @httpcode 200
 */
@GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{consumer_uuid}/entitlements/dry-run") public List<PoolQuantity> dryBind(@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid,@QueryParam("service_level") String serviceLevel){
  Consumer consumer=verifyAndLookupConsumer(consumerUuid);
  List<PoolQuantity> dryRunPools=new ArrayList<PoolQuantity>();
  try {
    checkServiceLevel(consumer.getOwner(),serviceLevel);
    dryRunPools=entitler.getDryRun(consumer,serviceLevel);
  }
 catch (  ForbiddenException fe) {
    return dryRunPools;
  }
catch (  BadRequestException bre) {
    throw bre;
  }
catch (  RuntimeException re) {
    return dryRunPools;
  }
  return dryRunPools;
}
 

Example 8

From project caseconductor-platform, under directory /utest-webservice/utest-webservice-impl/src/main/java/com/utest/webservice/impl/v2/.

Source file: ProductWebServiceImpl.java

  19 
vote

@PUT @Path("/{id}/undo_delete/") @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Override @Secured({Permission.PRODUCT_EDIT,Permission.DELETED_ENTITY_UNDO}) public Boolean undeleteProduct(@Context final UriInfo ui_,@PathParam("id") final Integer productId,@FormParam("originalVersionId") final Integer originalVersionId_) throws Exception {
  UtestSearch search=new UtestSearch();
  search.addFilterEqual("productId",productId);
  productService.undoAllDeletedEntities(ProductComponent.class,search);
  return productService.undoDeletedEntity(Product.class,productId);
}
 

Example 9

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/agent/rest/.

Source file: AdaptorController.java

  19 
vote

/** 
 * Adds an adaptor to the agent and returns the adaptor info.
 * @param context servletContext
 * @param viewType type of view to return (text|xml)
 * @param postBody JSON post body
 * @return Response object
 */
@POST @Consumes("application/json") @Produces({"text/xml","text/plain"}) public Response addAdaptor(@Context ServletContext context,@QueryParam("viewType") String viewType,String postBody){
  ChukwaAgent agent=(ChukwaAgent)context.getAttribute("ChukwaAgent");
  if (postBody == null)   return badRequestResponse("Empty POST body.");
  StringBuilder addCommand=new StringBuilder("add ");
  try {
    JSONObject reqJson=new JSONObject(postBody);
    String dataType=reqJson.getString("DataType");
    String adaptorClass=reqJson.getString("AdaptorClass");
    String adaptorParams=fetchOptionalString(reqJson,"AdaptorParams");
    long offset=fetchOptionalLong(reqJson,"Offset",0);
    addCommand.append(adaptorClass).append(' ');
    addCommand.append(dataType);
    if (adaptorParams != null)     addCommand.append(' ').append(adaptorParams);
    addCommand.append(' ').append(offset);
  }
 catch (  JSONException e) {
    return badRequestResponse("Invalid JSON passed: '" + postBody + "', error: "+ e.getMessage());
  }
  try {
    String adaptorId=agent.processAddCommandE(addCommand.toString());
    return doGetAdaptor(agent,adaptorId,viewType);
  }
 catch (  AdaptorException e) {
    return badRequestResponse("Could not add adaptor for postBody: '" + postBody + "', error: "+ e.getMessage());
  }
}
 

Example 10

From project cloud-management, under directory /src/main/java/com/proofpoint/cloudmanagement/service/.

Source file: InstancesResource.java

  19 
vote

@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createInstance(final InstanceCreationRequest request,@Context UriInfo uriInfo){
  checkNotNull(request);
  checkNotNull(uriInfo);
  if (!instanceConnectorMap.containsKey(request.getProvider())) {
    return Response.status(Status.BAD_REQUEST).entity(new InstanceCreationFailedResponse(request,PROVIDER_UNAVAILABLE)).build();
  }
  if (instanceConnectorMap.get(request.getProvider()).getLocation(request.getLocation()) == null) {
    return Response.status(Status.BAD_REQUEST).entity(new InstanceCreationFailedResponse(request,LOCATION_UNAVAILABLE)).build();
  }
  if (!Iterables.any(instanceConnectorMap.get(request.getProvider()).getLocation(request.getLocation()).getAvailableSizes(),new Predicate<Size>(){
    @Override public boolean apply(    @Nullable Size size){
      return size.getSize().equals(request.getSize());
    }
  }
)) {
    return Response.status(Status.BAD_REQUEST).entity(new InstanceCreationFailedResponse(request,SIZE_UNAVAILABLE)).build();
  }
  String instanceId=instanceConnectorMap.get(request.getProvider()).createInstance(request.getSize(),request.getNamePrefix(),request.getLocation());
  for (  InstanceCreationNotifier instanceCreationNotifier : instanceCreationNotifiers) {
    instanceCreationNotifier.notifyInstanceCreated(instanceId);
  }
  return Response.created(InstanceResource.constructSelfUri(uriInfo,instanceId)).build();
}
 

Example 11

From project components-ness-jersey, under directory /testing/src/test/java/com/nesscomputing/jersey/exceptions/.

Source file: TestArgumentExceptionMapping.java

  19 
vote

@Consumes("application/json") @Produces("application/json") @POST public String doSomething(MessageHolder something) throws Exception {
  if ("die".equals(something.getMessage())) {
    mapper.readTree("{\"messa");
  }
  return something.getMessage();
}
 

Example 12

From project curator, under directory /curator-x-discovery-server/src/main/java/com/netflix/curator/x/discovery/server/rest/.

Source file: DiscoveryResource.java

  19 
vote

@PUT @Path("v1/service/{name}/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response putService(ServiceInstance<T> instance,@PathParam("name") String name,@PathParam("id") String id){
  if (!instance.getId().equals(id) || !instance.getName().equals(name)) {
    log.info("Request where path id and/or name doesn't match entity");
    return Response.status(Response.Status.BAD_REQUEST).build();
  }
  if (instance.getServiceType() == ServiceType.DYNAMIC) {
    log.info("Service type cannot be dynamic");
    return Response.status(Response.Status.BAD_REQUEST).build();
  }
  try {
    context.getServiceDiscovery().registerService(instance);
  }
 catch (  Exception e) {
    log.error("Trying to register service",e);
    return Response.serverError().build();
  }
  return Response.status(Response.Status.CREATED).build();
}
 

Example 13

From project data-access, under directory /src/org/pentaho/platform/dataaccess/datasource/wizard/service/impl/.

Source file: AnalysisDatasourceService.java

  19 
vote

/** 
 * This is used by PUC to use a Jersey put to import a Mondrian Schema XML into PUR
 * @author : tband  date: 7/10/12
 * @param dataInputStream
 * @param schemaFileInfo
 * @param catalogName
 * @param datasourceName
 * @param overwrite
 * @param xmlaEnabledFlag
 * @param parameters
 * @return this method returns a response of "3" for success, 8 if exists, etc.
 * @throws PentahoAccessControlException
 */
@PUT @Path("/putSchema") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("text/plain") public Response putMondrianSchema(@FormDataParam(UPLOAD_ANALYSIS) InputStream dataInputStream,@FormDataParam(UPLOAD_ANALYSIS) FormDataContentDisposition schemaFileInfo,@FormDataParam(CATALOG_NAME) String catalogName,@FormDataParam(DATASOURCE_NAME) String datasourceName,@FormDataParam(OVERWRITE_IN_REPOS) String overwrite,@FormDataParam(XMLA_ENABLED_FLAG) String xmlaEnabledFlag,@FormDataParam(PARAMETERS) String parameters) throws PentahoAccessControlException {
  Response response=null;
  String statusCode=String.valueOf(PlatformImportException.PUBLISH_GENERAL_ERROR);
  try {
    validateAccess();
    String fileName=schemaFileInfo.getFileName();
    processMondrianImport(dataInputStream,catalogName,overwrite,xmlaEnabledFlag,parameters,fileName);
    statusCode=SUCCESS;
  }
 catch (  PentahoAccessControlException pac) {
    logger.error(pac.getMessage());
    statusCode=String.valueOf(PlatformImportException.PUBLISH_USERNAME_PASSWORD_FAIL);
  }
catch (  PlatformImportException pe) {
    logger.error("Error putMondrianSchema " + pe.getMessage() + " status = "+ pe.getErrorStatus());
    statusCode=String.valueOf(pe.getErrorStatus());
  }
catch (  Exception e) {
    logger.error("Error putMondrianSchema " + e.getMessage());
    statusCode=String.valueOf(PlatformImportException.PUBLISH_GENERAL_ERROR);
  }
  response=Response.ok().status(new Integer(statusCode)).type(MediaType.TEXT_PLAIN).build();
  logger.debug("putMondrianSchema Response " + response);
  return response;
}
 

Example 14

From project EasySOA, under directory /easysoa-registry/easysoa-registry-rest/src/main/java/org/easysoa/rest/.

Source file: DiscoveryRest.java

  19 
vote

@POST @Path("/appliimpl") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Object doPostAppliImpl(@Context HttpContext httpContext,@Context HttpServletRequest request) throws Exception {
  EasySOAApiSession api=EasySOALocalApiFactory.createLocalApi(SessionFactory.getSession(request));
  Map<String,String> params=getFirstValues(request.getParameterMap());
  try {
    EasySOADocument doc=api.notifyAppliImpl(params);
    result.put("documentId",doc.getId());
  }
 catch (  Exception e) {
    appendError(e.getMessage());
  }
  return getFormattedResult();
}
 

Example 15

From project event-collector, under directory /event-collector/src/main/java/com/proofpoint/event/collector/.

Source file: EventResource.java

  19 
vote

@POST @Consumes(MediaType.APPLICATION_JSON) public Response post(List<Event> events) throws IOException {
  Set<String> badEvents=Sets.newHashSet();
  for (  Event event : events) {
    if (acceptedEventType(event.getType())) {
      for (      EventWriter writer : writers) {
        writer.write(event);
      }
    }
 else {
      badEvents.add(event.getType());
    }
  }
  if (!badEvents.isEmpty()) {
    String errorMessage="Invalid event type(s): " + Joiner.on(", ").join(badEvents);
    return Response.status(Status.BAD_REQUEST).entity(errorMessage).build();
  }
  return Response.status(Response.Status.ACCEPTED).build();
}
 

Example 16

From project examples_1, under directory /datanucleus/com.paremus.example.datanucleus.service/src/com/paremus/example/datanucleus/service/rest/.

Source file: BlogCommentsResource.java

  19 
vote

@POST @Consumes(MediaType.TEXT_PLAIN) public Response create(String data) throws Exception {
  Comment comment=new Comment(UUID.randomUUID().toString(),data);
  blog.saveComment(comment);
  URI commentUri=uriInfo.getAbsolutePathBuilder().path(comment.id).build();
  return Response.created(commentUri).build();
}
 

Example 17

From project gmc, under directory /src/org.gluster.storage.management.gateway/src/org/gluster/storage/management/gateway/resources/v1_0/.

Source file: KeysResource.java

  19 
vote

@POST @Consumes(MediaType.MULTIPART_FORM_DATA) public Response importSshKeys(@FormDataParam("file") InputStream uploadedInputStream){
  File uploadedFile=new File(System.getProperty("java.io.tmpdir") + File.separator + "keys.tar");
  String timestamp=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
  writeToFile(uploadedInputStream,uploadedFile.getAbsolutePath());
  if (SshUtil.PRIVATE_KEY_FILE.isFile()) {
    if (!SshUtil.PRIVATE_KEY_FILE.renameTo(new File(SshUtil.PRIVATE_KEY_FILE.getAbsolutePath() + "-" + timestamp))) {
      throw new GlusterRuntimeException("Unable to backup private key!");
    }
  }
  if (SshUtil.PUBLIC_KEY_FILE.isFile()) {
    if (!SshUtil.PUBLIC_KEY_FILE.renameTo(new File(SshUtil.PUBLIC_KEY_FILE.getAbsolutePath() + "-" + timestamp))) {
      throw new GlusterRuntimeException("Unable to backup public key!");
    }
  }
  ProcessResult output=ProcessUtil.executeCommand("tar","xvf",uploadedFile.getAbsolutePath(),"-C",SshUtil.SSH_AUTHORIZED_KEYS_DIR_LOCAL);
  uploadedFile.delete();
  if (!output.isSuccess()) {
    String errMsg="Error in importing SSH keys: [" + output.toString() + "]";
    logger.error(errMsg);
    throw new GlusterRuntimeException(errMsg);
  }
  return createdResponse("SSH Key imported successfully");
}
 

Example 18

From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/rest/resource/.

Source file: UserResource.java

  19 
vote

@PUT @Consumes("application/json") public ReturnCodeBean setProfile(UserBean user){
  try {
    UserStore us=new UserStore(user.getId());
    us.set(user);
  }
 catch (  Exception e) {
    log.error(ExceptionUtil.getStackTrace(e));
    throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("User does not exist.").build());
  }
  return new ReturnCodeBean(ReturnCodeBean.SUCCESS,"Saved.");
}
 

Example 19

From project HMS, under directory /controller/src/main/java/org/apache/hms/controller/rest/.

Source file: ControllerManager.java

  19 
vote

@POST @Consumes(MediaType.APPLICATION_JSON) @Path("create/cluster") public Response createCluster(CreateClusterCommand cmd){
  try {
    Controller ci=Controller.getInstance();
    ClientHandler ch=ci.getClientHandler();
    if (ch == null) {
      LOG.error("ClientHandler is empty");
    }
    String path=ch.queueCmd(cmd);
    Response r=new Response();
    r.setOutput(path);
    return r;
  }
 catch (  Exception e) {
    LOG.error(ExceptionUtil.getStackTrace(e));
    throw new WebApplicationException(e);
  }
}
 

Example 20

From project hoop, under directory /hoop-server/src/main/java/com/cloudera/hoop/.

Source file: Hoop.java

  19 
vote

/** 
 * Binding to handle all OPST requests, supported operations are {@link PostOpParam.Values}.
 * @param is request input stream, used only for{@link PostOpParam.Values#CREATE} operations.
 * @param user principal making the request.
 * @param path path for the POST request.
 * @param op POST operation, default is {@link PostOpParam.Values#CREATE}.
 * @param override, default is true. Used only for{@link PostOpParam.Values#CREATE} operations.
 * @param replication replication factor to set, used only by{@link PostOpParam.Values#CREATE} operations.
 * @param blockSize block size to set, used only by{@link PostOpParam.Values#CREATE} operations.
 * @param permission permission to set.
 * @param doAs user being impersonated, defualt value is none. It can be usedonly if the current user is a Hoop proxyuser.
 * @return the request response.
 * @throws IOException thrown if an IO error occurred. Thrown exceptions arehandled by  {@link HoopExceptionProvider}.
 * @throws HadoopException thrwon if a Hadoop releated error occurred. Thrownexceptions are handled by  {@link HoopExceptionProvider}.
 */
@POST @Path("{path:.*}") @Consumes({"*/*"}) @Produces({MediaType.APPLICATION_JSON}) public Response post(InputStream is,@Context Principal user,@PathParam("path") FsPathParam path,@QueryParam(PostOpParam.NAME) @DefaultValue(PostOpParam.DEFAULT) PostOpParam op,@QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT) OverwriteParam override,@QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT) ReplicationParam replication,@QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT) BlockSizeParam blockSize,@QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT) PermissionParam permission,@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) DoAsParam doAs) throws IOException, HadoopException {
  Response response=null;
  path.makeAbsolute();
  MDC.put("op",op.value().name());
switch (op.value()) {
case CREATE:
{
      FSCreate command=new FSCreate(is,path.value(),permission.value(),override.value(),replication.value(),blockSize.value());
      URI uri=fsExecute(user,doAs.value(),command);
      AUDIT_LOG.info("[{}] permission [{}] override [{}] replication [{}] blockSize [{}]",new Object[]{path,permission,override,replication,blockSize});
      response=Response.created(uri).type(MediaType.APPLICATION_JSON).build();
      break;
    }
case MKDIRS:
{
    FSMkdirs command=new FSMkdirs(path.value(),permission.value());
    JSONObject json=fsExecute(user,doAs.value(),command);
    AUDIT_LOG.info("[{}] permission [{}]",path,permission.value());
    response=Response.ok(json).type(MediaType.APPLICATION_JSON).build();
    break;
  }
}
return response;
}
 

Example 21

From project iserve, under directory /iserve-parent/iserve-sal-rest/src/main/java/uk/ac/open/kmi/iserve/sal/rest/resource/.

Source file: DocumentResource.java

  19 
vote

@POST @Consumes({MediaType.TEXT_HTML,MediaType.TEXT_XML,MediaType.APPLICATION_XML,"application/rdf+xml","text/turtle","text/n3","text/rdf+n3",MediaType.TEXT_PLAIN}) @Produces({MediaType.TEXT_HTML}) public Response addDocument(String serviceDescription,@HeaderParam("Content-Location") String locationUri,@HeaderParam("Content-Type") String contentType) throws DocumentException, URISyntaxException, LogException {
  if (security.getUserPrincipal() == null) {
    throw new MappableContainerException(new AuthenticationException("Authentication credentials are required\r\n","iServe SAL RESTful API"));
  }
  String userFoafId=security.getUserPrincipal().getName();
  String fileName=null;
  if ((locationUri != null) && ("".equalsIgnoreCase(locationUri) == false)) {
    fileName=URIUtil.getLocalName(locationUri);
  }
  if (fileName == null) {
    if ((contentType != null) && ("".equalsIgnoreCase(contentType) == false)) {
      if (contentType.equalsIgnoreCase(MediaType.TEXT_HTML)) {
        fileName="service.html";
      }
 else       if (contentType.equalsIgnoreCase(MediaType.TEXT_XML) && contentType.equalsIgnoreCase(MediaType.APPLICATION_XML)) {
        fileName="service.xml";
      }
 else       if (contentType.equalsIgnoreCase("application/rdf+xml")) {
        fileName="service.rdf.xml";
      }
 else       if (contentType.equalsIgnoreCase("text/turtle")) {
        fileName="service.ttl";
      }
 else       if (contentType.equalsIgnoreCase("text/rdf+n3") && contentType.equalsIgnoreCase("text/n3")) {
        fileName="service.n3";
      }
 else {
        fileName="service.txt";
      }
    }
  }
  String uriString=documentManager.addDocument(fileName,serviceDescription);
  logManager.log(userFoafId,LOG.ITEM_CREATION,uriString,new Date(),"REST");
  String htmlString="<html>\n  <head>\n    <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n  </head>\n" + "  <body>\nA document is created at <a href='" + uriString + "'>"+ uriString+ "</a>\n  </body>\n</html>";
  return Response.status(Status.CREATED).contentLocation(new URI(uriString)).entity(htmlString).build();
}
 

Example 22

From project jboss-as-quickstart, under directory /kitchensink/src/main/java/org/jboss/as/quickstarts/kitchensink/rest/.

Source file: MemberResourceRESTService.java

  19 
vote

/** 
 * Creates a new member from the values provided. Performs validation, and will return a JAX-RS response with either 200 ok, or with a map of fields, and related errors.
 */
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createMember(Member member){
  Response.ResponseBuilder builder=null;
  try {
    validateMember(member);
    registration.register(member);
    builder=Response.ok();
  }
 catch (  ConstraintViolationException ce) {
    builder=createViolationResponse(ce.getConstraintViolations());
  }
catch (  ValidationException e) {
    Map<String,String> responseObj=new HashMap<String,String>();
    responseObj.put("email","Email taken");
    builder=Response.status(Response.Status.CONFLICT).entity(responseObj);
  }
catch (  Exception e) {
    Map<String,String> responseObj=new HashMap<String,String>();
    responseObj.put("error",e.getMessage());
    builder=Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
  }
  return builder.build();
}
 

Example 23

From project jbpm-form-builder, under directory /jbpm-gwt-form-builder/src/main/java/org/jbpm/formbuilder/server/.

Source file: RESTFileService.java

  19 
vote

@POST @Path("/package/{pkgName}") @Consumes(MediaType.MULTIPART_FORM_DATA) @DoNotUseJAXBProvider public Response saveFile(@PathParam("pkgName") String packageName,@Context HttpServletRequest request){
  setContext(request.getSession().getServletContext());
  if (isMultipart(request)) {
    ServletFileUpload upload=createFileUpload();
    try {
      List<?> files=parseFiles(request,upload);
      if (files == null || files.isEmpty()) {
        return error("there should be one file at least",null);
      }
      FileItem item=(FileItem)files.iterator().next();
      byte[] content=readItem(item);
      String fileName=item.getName();
      String expositionUrl=fileService.storeFile(packageName,fileName,content);
      return Response.ok(expositionUrl,MediaType.TEXT_PLAIN).build();
    }
 catch (    FileException e) {
      return error("Problem storing file to guvnor",e);
    }
catch (    IOException e) {
      return error("Problem reading input of file",e);
    }
catch (    FileUploadException e) {
      return error("Problem reading upload of file",e);
    }
  }
 else {
    return error("Must be a multipart form data post",null);
  }
}
 

Example 24

From project koshinuke.java, under directory /src/java/org/koshinuke/jgit/server/.

Source file: GitHttpdService.java

  19 
vote

@POST @Path(UPLOAD_PACK) @Consumes(CT_UPD + "-request") public Response uploadPack(final @Context HttpContext context,@PathParam("project") String project,@PathParam("repository") String repository){
  return GitUtil.handleLocal(this.config.getRepositoryRootDir(),project,repository,new Function<Repository,Response>(){
    @Override public Response apply(    Repository input){
      if (GitHttpdService.this.isEnabledUploadPack(input)) {
        UploadPack pack=GitHttpdService.this.makeUploadPack(input);
        try {
          HttpResponseContext response=context.getResponse();
          response.setResponse(noCache(null).type(CT_UPD + "-result").build());
          OutputStream out=response.getOutputStream();
          InputStream in=context.getRequest().getEntity(InputStream.class);
          pack.upload(in,out,null);
          out.flush();
        }
 catch (        IOException e) {
          throw new WebApplicationException(e);
        }
 finally {
          GitUtil.clearCache();
        }
        return null;
      }
      return Response.status(Status.FORBIDDEN).build();
    }
  }
);
}
 

Example 25

From project Lily, under directory /cr/process/server/rest-module/src/main/java/org/lilyproject/rest/.

Source file: BlobCollectionResource.java

  19 
vote

@POST @Consumes("*/*") @Produces("application/json") public Response post(@Context HttpHeaders headers,InputStream is){
  String lengthHeader=headers.getRequestHeaders().getFirst(HttpHeaders.CONTENT_LENGTH);
  if (lengthHeader == null) {
    throw new ResourceException("Content-Length header is required for uploading blobs.",BAD_REQUEST.getStatusCode());
  }
  String mediaType=headers.getMediaType().getType() + "/" + headers.getMediaType().getSubtype();
  long length=Long.parseLong(lengthHeader);
  Blob blob=new Blob(mediaType,length,null);
  OutputStream os=null;
  try {
    os=repository.getOutputStream(blob);
    IOUtils.copyLarge(is,os);
  }
 catch (  Exception e) {
    throw new ResourceException("Error writing blob.",e,INTERNAL_SERVER_ERROR.getStatusCode());
  }
 finally {
    Closer.close(os);
  }
  String value=BlobConverter.valueToString(blob.getValue());
  URI uri=UriBuilder.fromUri("/blob/" + value).build();
  return Response.created(uri).entity(blob).build();
}
 

Example 26

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/logbrowser/src/main/java/demo/service/.

Source file: CustomerService.java

  19 
vote

@POST @Consumes("application/json") public Response updateCustomer(final Customer customer){
  Validate.notNull(customer);
  LOGGER.log(Level.FINE,"Invoking updateCustomer, customer={0}",customer);
  if (isCustomerExists(customer)) {
    LOGGER.log(Level.FINE,"Specified customer exists, update data, customer={0}",customer);
  }
 else {
    LOGGER.log(Level.WARNING,"Specified customer does not exist, add data, customer={0}",customer);
  }
  customers.put(customer.getId(),customer);
  LOGGER.log(Level.INFO,"Customer was updated successful, customer={0}",customer);
  return Response.ok().build();
}
 

Example 27

From project lyo.core, under directory /OSLC4JStockQuote/src/org/eclipse/lyo/oslc4j/stockquote/resources/.

Source file: StockQuoteResource.java

  19 
vote

@OslcCreationFactory(title="Stock Quote Creation Factory",label="Stock Quote Creation",resourceShapes={OslcConstants.PATH_RESOURCE_SHAPES + "/" + Constants.PATH_STOCK_QUOTE},resourceTypes={Constants.TYPE_STOCK_QUOTE},usages={OslcConstants.OSLC_USAGE_DEFAULT}) @POST @Consumes({OslcMediaType.APPLICATION_RDF_XML,OslcMediaType.APPLICATION_XML,OslcMediaType.TEXT_XML,OslcMediaType.APPLICATION_JSON}) @Produces({OslcMediaType.APPLICATION_RDF_XML,OslcMediaType.APPLICATION_XML,OslcMediaType.TEXT_XML,OslcMediaType.APPLICATION_JSON}) public Response addStockQuote(@Context final HttpServletRequest httpServletRequest,final StockQuote stockQuote) throws URISyntaxException {
  final String identifier=Utilities.createStockQuoteIdentifier(stockQuote);
  final URI about=new URI(httpServletRequest.getScheme(),null,httpServletRequest.getServerName(),httpServletRequest.getServerPort(),httpServletRequest.getContextPath() + "/stockQuotes/" + identifier,null,null);
  stockQuote.setAbout(about);
  stockQuote.setIdentifier(identifier);
  stockQuote.setServiceProvider(ServiceProviderSingleton.getServiceProviderURI());
  Persistence.addStockQuote(stockQuote);
  return Response.created(about).entity(stockQuote).build();
}
 

Example 28

From project lyo.rio, under directory /OSLC4JAutomation/src/org/eclipse/lyo/oslc4j/automation/resources/.

Source file: AutomationRequestResource.java

  19 
vote

@PUT @Consumes({OslcMediaType.APPLICATION_RDF_XML,OslcMediaType.APPLICATION_XML,OslcMediaType.APPLICATION_JSON}) @Path("{resourceId}") public Response updateResource(@Context final HttpServletResponse httpServletResponse,@HeaderParam("If-Match") final String eTagHeader,@PathParam("resourceId") final String resourceId,final AutomationRequest resource){
  if (resource.getDesiredState() != null) {
    resource.setStates(new URI[]{resource.getDesiredState()});
  }
  return super.updateResource(httpServletResponse,eTagHeader,resourceId,resource);
}
 

Example 29

From project lyo.server, under directory /org.eclipse.lyo.server.oauth.webapp/src/main/java/org/eclipse/lyo/server/oauth/webapp/services/.

Source file: ConsumersService.java

  19 
vote

/** 
 * Updates an OAuth consumer.
 * @param key the consumer key
 * @param name the new name or null
 * @param trusted "true" the consumer is trusted. Can be null.
 * @param provisional "true" if the consumer is provisional or "false" if the consumer is authorized. Can be null.
 * @return the HTTP response
 */
@POST @Path("/{key}") @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) public Response updateConsumer(@PathParam("key") String key,@FormParam("name") String name,@FormParam("trusted") String trusted,@FormParam("provisional") String provisional){
  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();
    }
    ConsumerStore store=OAuthConfiguration.getInstance().getConsumerStore();
    LyoOAuthConsumer consumer=store.getConsumer(key);
    if (consumer == null) {
      return Response.status(Status.NOT_FOUND).build();
    }
    if (name != null) {
      consumer.setName(name);
    }
    if (trusted != null) {
      consumer.setTrusted("true".equals(trusted));
    }
    if (provisional != null) {
      consumer.setProvisional("true".equals(provisional));
    }
    store.updateConsumer(consumer);
    return Response.noContent().build();
  }
 catch (  ConsumerStoreException e) {
    return handleConsumerStoreException(e);
  }
catch (  OAuthProblemException e) {
    return Response.status(Status.SERVICE_UNAVAILABLE).build();
  }
}
 

Example 30

From project meteo, under directory /core/src/main/java/com/ning/metrics/meteo/server/resources/.

Source file: StreamResource.java

  19 
vote

/** 
 * Add a new stream
 * @param streamConfig the new stream configuration
 * @return 201 Created on success, 500 on error (exception in the 199 Warning header)
 */
@POST @Consumes(MediaType.APPLICATION_JSON) public Response addStream(final StreamConfig streamConfig){
  if (compiler.getPublisherInstances().get(streamConfig.getName()) != null) {
    return Response.status(Response.Status.CONFLICT).header("Warning","199 Stream already exists").build();
  }
  try {
    compiler.addStream(streamConfig);
  }
 catch (  Exception e) {
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).header("Warning","199 " + e.toString()).build();
  }
  return Response.status(Response.Status.CREATED).build();
}
 

Example 31

From project ogm-kitchensink, under directory /src/main/java/org/jboss/as/quickstarts/kitchensink/rest/.

Source file: MemberResourceRESTService.java

  19 
vote

/** 
 * Creates a new member from the values provided.  Performs validation, and will return a JAX-RS response with either 200 ok, or with a map of fields, and related errors.
 */
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createMember(Member member){
  Response.ResponseBuilder builder=null;
  try {
    validateMember(member);
    registration.register(member);
    builder=Response.ok();
  }
 catch (  ConstraintViolationException ce) {
    builder=createViolationResponse(ce.getConstraintViolations());
  }
catch (  ValidationException e) {
    Map<String,String> responseObj=new HashMap<String,String>();
    responseObj.put("email","Email taken");
    builder=Response.status(Response.Status.CONFLICT).entity(responseObj);
  }
catch (  Exception e) {
    Map<String,String> responseObj=new HashMap<String,String>();
    responseObj.put("error",e.getMessage());
    builder=Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
  }
  return builder.build();
}
 

Example 32

From project onebusaway-nyc, under directory /onebusaway-nyc-transit-data-manager/onebusaway-nyc-tdm-webapp/src/main/java/org/onebusaway/nyc/transit_data_manager/api/config/.

Source file: ConfigResource.java

  19 
vote

@Path("/{component}/{key}/set") @POST @Consumes("application/json") @Produces("application/json") public String setConfigVal(String configStr,@PathParam("component") String component,@PathParam("key") String key) throws JsonParseException, JsonMappingException, IOException {
  _log.info("Starting setConfigVal for component " + component + " and key "+ key);
  boolean giveUnsupportedValueTypeWarning=false;
  boolean giveNoValueError=false;
  SingleConfigItem configItem=mapper.readValue(configStr,SingleConfigItem.class);
  ConfigItem inputConfigItem=configItem.getConfig();
  if (!"string".equalsIgnoreCase(inputConfigItem.getValueType())) {
    giveUnsupportedValueTypeWarning=true;
  }
  if (inputConfigItem.getValue() == null) {
    giveNoValueError=true;
  }
  ConfigItem configToSet=new ConfigItem();
  configToSet.setComponent(component);
  configToSet.setKey(key);
  configToSet.setUpdated(new DateTime());
  configToSet.setDescription(inputConfigItem.getDescription());
  configToSet.setValue(inputConfigItem.getValue());
  configToSet.setUnits(inputConfigItem.getUnits());
  configToSet.setValueType("String");
  if (!giveNoValueError)   datastore.setConfigItemByComponentKey(component,key,configToSet);
  Message statusMessage=new Message();
  if (giveNoValueError) {
    statusMessage.setStatus("ERROR");
    statusMessage.setMessageText("No Value entered. Nothing saved.");
  }
 else   if (giveUnsupportedValueTypeWarning) {
    statusMessage.setStatus("WARNING");
    statusMessage.setMessageText("valueTypes other than string are unsupported at this time. Value will be stored as a string.");
  }
 else {
    statusMessage=new Message();
    statusMessage.setStatus("OK");
  }
  _log.info("Returning result in setConfigVal.");
  return mapper.writeValueAsString(statusMessage);
}
 

Example 33

From project Openbravo-POS-iPhone-App, under directory /OpenbravoPOS_PDA/src-pda/com/openbravo/pos/pda/restresources/.

Source file: TicketResource.java

  19 
vote

@POST @Path("deleteTicketProducts") @Consumes("application/json") public void deleteTicketProducts(TicketAddition ticketAdd){
  TicketInfo ticket=manager.findTicket(ticketAdd.getTicketId());
  List<TicketLineInfo> linesToRemove=new ArrayList<TicketLineInfo>();
  for (  TicketLineInfo ticketInfo : ticket.getLines()) {
    if (ticketAdd.getProductIds().contains(ticketInfo.getProductid())) {
      linesToRemove.add(ticketInfo);
      ticketAdd.getProductIds().remove(ticketInfo.getProductid());
    }
  }
  for (  TicketLineInfo line : linesToRemove) {
    ticket.getLines().remove(line);
  }
  int i=0;
  for (  TicketLineInfo line : ticket.getLines()) {
    line.setM_iLine(i++);
  }
  TicketDAO dao=new TicketDAO();
  dao.updateTicket(ticketAdd.getTicketId(),ticket);
}
 

Example 34

From project OpenTripPlanner, under directory /opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/.

Source file: Patcher.java

  19 
vote

@RolesAllowed("user") @POST @Path("/patch") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML,MediaType.TEXT_XML}) @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML,MediaType.TEXT_XML}) public PatchCreationResponse createPatches(PatchSet patches) throws JSONException {
  PatchCreationResponse response=new PatchCreationResponse();
  for (  Patch patch : patches.patches) {
    if (patch.getId() == null) {
      response.status="Every patch must have an id";
      return response;
    }
    if (patch instanceof AlertPatch) {
      AlertPatch alertPatch=(AlertPatch)patch;
      final AgencyAndId route=alertPatch.getRoute();
      if (route != null && route.getId().equals("")) {
        response.status="Every route patch must have a route id";
        return response;
      }
    }
  }
  for (  Patch patch : patches.patches) {
    patchservice.apply(patch);
  }
  response.status="OK";
  return response;
}
 

Example 35

From project platform_3, under directory /sample-server/src/main/java/com/proofpoint/platform/sample/.

Source file: PersonResource.java

  19 
vote

@PUT @Consumes(MediaType.APPLICATION_JSON) public Response put(@PathParam("id") String id,PersonRepresentation person){
  Preconditions.checkNotNull(id,"id must not be null");
  Preconditions.checkNotNull(person,"person must not be null");
  boolean added=store.put(id,person.toPerson());
  if (added) {
    UriBuilder uri=UriBuilder.fromResource(PersonResource.class);
    return Response.created(uri.build(id)).build();
  }
  return Response.noContent().build();
}
 

Example 36

From project rest-support, under directory /hudson-rest-api/src/main/java/org/hudsonci/rest/api/project/.

Source file: ProjectsResource.java

  19 
vote

@POST @Consumes(TEXT_XML) @Path("{projectName}") public ProjectDTO createProject(@PathParam("projectName") String projectName,final InputStream configXml) throws IOException {
  checkNotNull(projectName);
  checkNotNull(configXml);
  projectName=support.decodeProjectName(projectName);
  log.debug("Creating project: {}",projectName);
  if (projectService.projectExists(projectName)) {
    throw new WebApplicationException(CONFLICT);
  }
  InputStream input=new BufferedInputStream(configXml);
  try {
    projectService.createProjectFromXML(projectName,input);
  }
  finally {
    Closer.close(input);
  }
  AbstractProject<?,?> project=projectService.getProject(projectName);
  return projectx.convert(project);
}
 

Example 37

From project RSB, under directory /src/main/java/eu/openanalytics/rsb/component/.

Source file: AdminResource.java

  19 
vote

@Path("/" + SYSTEM_SUBPATH + "/configuration") @PUT @Consumes(Constants.JSON_CONTENT_TYPE) public Response putSystemConfiguration(final InputStream in) throws IOException, URISyntaxException {
  Validate.notNull(getConfiguration().getConfigurationUrl(),"Transient configuration can't be PUT over the API");
  final Configuration newConfiguration=ConfigurationFactory.loadJsonConfiguration(in);
  final String reformattedNewConfiguration=Util.toJson(new PersistedConfiguration(newConfiguration));
  final File newConfigurationFile=new File(getConfiguration().getConfigurationUrl().toURI());
  final FileWriter fw=new FileWriter(newConfigurationFile);
  IOUtils.copy(new StringReader(reformattedNewConfiguration),fw);
  IOUtils.closeQuietly(fw);
  getLogger().warn("Configuration stored in: " + newConfigurationFile + ". System needs restart in order to activate this new configuration!");
  return Response.noContent().build();
}
 

Example 38

From project s-ramp, under directory /s-ramp-atom/src/main/java/org/overlord/sramp/atom/services/.

Source file: ArtifactResource.java

  19 
vote

@POST @Path("{model}/{type}") @Consumes(MultipartConstants.MULTIPART_RELATED) @Produces(MediaType.APPLICATION_ATOM_XML_ENTRY) public Entry createMultiPart(@HeaderParam("Content-Type") String contentType,@PathParam("model") String model,@PathParam("type") String type,MultipartRelatedInput input){
  Entry atomEntry=new Entry();
  try {
    ArtifactType artifactType=ArtifactType.valueOf(model,type);
    if (artifactType.getArtifactType().isDerived()) {
      throw new Exception("Failed to create artifact because '" + artifactType.getArtifactType() + "' is a derived type.");
    }
    List<InputPart> list=input.getParts();
    if (list.size() != 2)     ;
    InputPart firstPart=list.get(0);
    InputPart secondpart=list.get(1);
    atomEntry=firstPart.getBody(new GenericType<Entry>(){
    }
);
    BaseArtifactType baseArtifactType=SrampAtomUtils.unwrapSrampArtifact(artifactType,atomEntry);
    String fileName=null;
    if (baseArtifactType.getName() != null)     fileName=baseArtifactType.getName();
    String mimeType=MimeTypes.determineMimeType(contentType,fileName,artifactType);
    artifactType.setMimeType(mimeType);
    InputStream is=secondpart.getBody(new GenericType<InputStream>(){
    }
);
    PersistenceManager persistenceManager=PersistenceFactory.newInstance();
    BaseArtifactType intermediate=persistenceManager.persistArtifact(baseArtifactType,is);
    Collection<DerivedArtifactType> dartifacts=DerivedArtifactsFactory.newInstance().deriveArtifacts(intermediate);
    persistenceManager.persistDerivedArtifacts(intermediate,dartifacts);
    intermediate.setDescription(baseArtifactType.getDescription());
    intermediate.setCreatedBy(baseArtifactType.getCreatedBy());
    persistenceManager.updateArtifact(baseArtifactType,artifactType);
    ArtifactToFullAtomEntryVisitor visitor=new ArtifactToFullAtomEntryVisitor();
    ArtifactVisitorHelper.visitArtifact(visitor,intermediate);
    atomEntry=visitor.getAtomEntry();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return atomEntry;
}
 

Example 39

From project saiku, under directory /saiku-core/saiku-web/src/main/java/org/saiku/web/rest/resources/.

Source file: QueryResource.java

  19 
vote

@DELETE @Consumes("application/x-www-form-urlencoded") @Path("/{queryname}/axis/{axis}/dimension/{dimension}/member/") public Status removeMembers(@PathParam("queryname") String queryName,@PathParam("axis") String axisName,@PathParam("dimension") String dimensionName,MultivaluedMap<String,String> formParams){
  if (log.isDebugEnabled()) {
    log.debug("TRACK\t" + "\t/query/" + queryName + "/axis/"+ axisName+ "/dimension/"+ dimensionName+ "\tPUT");
  }
  try {
    if (formParams.containsKey("selections")) {
      LinkedList<String> sels=(LinkedList<String>)formParams.get("selections");
      String selectionJSON=(String)sels.getFirst();
      ObjectMapper mapper=new ObjectMapper();
      List<SelectionRestObject> selections=mapper.readValue(selectionJSON,TypeFactory.collectionType(ArrayList.class,SelectionRestObject.class));
      for (      SelectionRestObject member : selections) {
        removeMember("MEMBER",queryName,axisName,dimensionName,member.getUniquename());
      }
      return Status.OK;
    }
  }
 catch (  Exception e) {
    log.error("Cannot updates selections for query (" + queryName + ")",e);
  }
  return Status.INTERNAL_SERVER_ERROR;
}
 

Example 40

From project saiku-adhoc, under directory /saiku-adhoc-core/src/main/java/org/saiku/adhoc/rest/.

Source file: QueryResource.java

  19 
vote

@POST @Consumes({"application/json"}) @Path("/{queryname}") public Status createQuery(MetadataModelInfo modelInfo,@PathParam("queryname") String sessionId){
  if (log.isDebugEnabled()) {
    log.debug("REST:POST " + sessionId + " createQuery");
  }
  try {
    if (log.isDebugEnabled()) {
      log.debug("REST:POST " + sessionId + " createQuery");
    }
    editorService.createNewModel(sessionId,modelInfo);
    return Status.OK;
  }
 catch (  Exception e) {
    e.printStackTrace();
    return Status.INTERNAL_SERVER_ERROR;
  }
}
 

Example 41

From project smart-cms, under directory /webservice-modules/webservice-resources/src/main/java/com/smartitengineering/cms/ws/resources/content/.

Source file: ContentResource.java

  19 
vote

@POST @Consumes(MediaType.MULTIPART_FORM_DATA) public Response post(FormDataMultiPart multiPart){
  LOGGER.info("Received POST for content as multipart/form-data");
  com.smartitengineering.cms.ws.common.domains.Content contentImpl=parseMultipartFormData(multiPart,getInjectables());
  if (LOGGER.isDebugEnabled()) {
    try {
      ObjectMapper mapper=new ObjectMapper();
      LOGGER.debug("Serialized content impl is " + mapper.writeValueAsString(contentImpl));
    }
 catch (    Exception ex) {
      LOGGER.warn("Could not output info log ",ex);
    }
  }
  return put(contentImpl,this.content == null ? null : new EntityTag("*"));
}
 

Example 42

From project social, under directory /component/service/src/main/java/org/exoplatform/social/service/rest/.

Source file: ActivitiesRestService.java

  19 
vote

/** 
 * Update like by the JSON/XML format.
 * @param uriInfo
 * @param activityId
 * @param format
 * @param like
 * @return response
 * @throws Exception
 */
@POST @Path("{activityId}/likes/update.{format}") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) public Response updateLike(@Context UriInfo uriInfo,@PathParam("portalName") String portalName,@PathParam("activityId") String activityId,@PathParam("format") String format,Like like) throws Exception {
  MediaType mediaType=Util.getMediaType(format);
  portalName_=portalName;
  LikeList likeList=updateLike(activityId,like);
  return Util.getResponse(likeList,uriInfo,mediaType,Response.Status.OK);
}
 

Example 43

From project SOCIETIES-SCE-Services, under directory /3rdPartyServices/StudentServices/CollaborativeQuiz/RestServer/src/laura/rest/server/.

Source file: StudentResource.java

  19 
vote

@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String registerStudent(@FormParam("jid") String id,@FormParam("name") String name){
  try {
    Class.forName("com.mysql.jdbc.Driver");
    String url="jdbc:mysql://localhost:3306/sociallearninggame";
    conn=DriverManager.getConnection(url,"root","123qwe");
    statement=conn.createStatement();
    String query="SELECT * FROM Students";
    resultSet=statement.executeQuery(query);
    while (resultSet.next()) {
      if (resultSet.getString("jid").equals(id)) {
        return "Student already registered";
      }
    }
    resultSet.close();
    if (!id.equals("") && !name.equals("")) {
      preparedStatement=conn.prepareStatement("INSERT INTO Students (jid,name,first) VALUES (?,?,1)");
      preparedStatement.setString(1,id);
      preparedStatement.setString(2,name);
      preparedStatement.executeUpdate();
    }
 else {
      return "missing id and/or name";
    }
    resultSet.close();
    conn.close();
  }
 catch (  Exception e) {
    System.out.println("an error occurred while trying to connect to the database");
    return "an error occurred while trying to connect to the database";
  }
  return "registration complete";
}
 

Example 44

From project tesb-rt-se, under directory /examples/cxf/jaxrs-advanced/common/src/main/java/common/advanced/.

Source file: Person.java

  19 
vote

@PUT @Consumes("text/plain") @Path("age") public void updateAge(int newAge) throws PersonUpdateException {
  if (age > newAge) {
    throw new PersonUpdateException();
  }
  setAge(newAge);
}
 

Example 45

From project usergrid-stack, under directory /rest/src/main/java/org/usergrid/rest/applications/.

Source file: ApplicationResource.java

  19 
vote

@POST @Path("token") @Consumes(APPLICATION_JSON) public Response getAccessTokenPostJson(@Context UriInfo ui,Map<String,Object> json,@QueryParam("callback") @DefaultValue("") String callback) throws Exception {
  String grant_type=(String)json.get("grant_type");
  String username=(String)json.get("username");
  String password=(String)json.get("password");
  String client_id=(String)json.get("client_id");
  String client_secret=(String)json.get("client_secret");
  String pin=(String)json.get("pin");
  String code=(String)json.get("code");
  String redirect_uri=(String)json.get("redirect_uri");
  long ttl=0;
  if (json.get("ttl") != null) {
    try {
      ttl=Long.parseLong(json.get("ttl").toString());
    }
 catch (    NumberFormatException nfe) {
      throw new IllegalArgumentException("ttl must be a number >= 0");
    }
  }
  return getAccessToken(ui,null,grant_type,username,password,pin,client_id,client_secret,code,ttl,redirect_uri,callback);
}
 

Example 46

From project wissl, under directory /src/main/java/fr/msch/wissl/server/.

Source file: REST.java

  19 
vote

@POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Path("edit/artwork/{album_id}") public void editArtwork(@PathParam("album_id") int album_id,MultipartFormDataInput multipart) throws SQLException, SecurityError {
  long l1=System.nanoTime();
  String sid=(sessionIdHeader == null ? sessionIdGet : sessionIdHeader);
  Session s=Session.check(sid,request.getRemoteAddr(),true);
  String path=null;
  try {
    InputPart part=multipart.getFormDataMap().get("file").get(0);
    InputStream is=part.getBody(new GenericType<InputStream>(){
    }
);
    File file=File.createTempFile("image.",".tmp");
    FileUtils.copyInputStreamToFile(is,file);
    path=Library.resizeArtwork(file.getAbsolutePath());
    file.delete();
  }
 catch (  IOException e) {
    Logger.error("Failed to create image file",e);
    throw new IllegalArgumentException("Failed to create new artwork image");
  }
  int[] ids=new int[]{album_id};
  List<String> files=DB.get().getAlbumSongPaths(ids);
  Library.editArtwork(files,path);
  DB.get().editAlbumArtwork(ids,path);
  log(s,l1);
}
 

Example 47

From project ws, under directory /exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/header/.

Source file: MediaTypeHelper.java

  19 
vote

/** 
 * Create a list of media type for given Consumes annotation. If parameter mime is null then list with single element {@link MediaTypeHelper#DEFAULT_TYPE} will be returned.
 * @param mime the Consumes annotation.
 * @return ordered list of media types.
 */
public static List<MediaType> createConsumesList(Consumes mime){
  if (mime == null) {
    return DEFAULT_TYPE_LIST;
  }
  return createMediaTypesList(mime.value());
}
 

Example 48

From project zanata, under directory /zanata-war/src/main/java/org/zanata/rest/service/.

Source file: AccountService.java

  19 
vote

/** 
 * Creates or updates a user account. If an account with the given user name already exists, said account will be overwritten with the provided data. Otherwise, a new account will  be created.
 * @param account The account information to create/update.
 * @return The following response status codes will be returned from this operation:<br>OK(200) - If a new account was created.<br> CREATED(201) - If an existing account was modified.<br> UNAUTHORIZED(401) - If the user does not have the proper permissions to perform this operation.<br> INTERNAL SERVER ERROR(500) - If there is an unexpected error in the server while performing this operation. 
 */
@Override @PUT @Consumes({MediaTypes.APPLICATION_ZANATA_ACCOUNT_XML,MediaTypes.APPLICATION_ZANATA_ACCOUNT_JSON}) public Response put(Account account){
  log.debug("HTTP PUT {0} : \n{1}",request.getRequestURL(),account);
  HAccount hAccount=accountDAO.getByUsername(username);
  ResponseBuilder response;
  String operation;
  if (hAccount == null) {
    operation="insert";
    response=Response.created(uri.getAbsolutePath());
    hAccount=new HAccount();
    HPerson person=new HPerson();
    person.setAccount(hAccount);
    hAccount.setPerson(person);
  }
 else {
    operation="update";
    response=Response.ok();
  }
  transfer(account,hAccount);
  identity.checkPermission(hAccount,operation);
  session.save(hAccount);
  session.flush();
  return response.build();
}
 

Example 49

From project zen-project, under directory /zen-webservice/src/main/java/com/nominanuda/hyperapi/.

Source file: AnnotatedType.java

  19 
vote

public @Nullable String mediaType(){
  for (  Annotation a : annotations) {
    Class<? extends Annotation> t=a.annotationType();
    if (Consumes.class.equals(t)) {
      String[] vals=((Consumes)a).value();
      return vals == null ? null : vals[0];
    }
 else     if (Produces.class.equals(t)) {
      String[] vals=((Produces)a).value();
      return vals == null ? null : vals[0];
    }
  }
  return null;
}
 

Example 50

From project zk-service-registry-server, under directory /lib/zk-service-registry-server/zookeeper-3.3.3/src/contrib/rest/src/java/org/apache/zookeeper/server/jersey/resources/.

Source file: ZNodeResource.java

  19 
vote

@PUT @Produces({MediaType.APPLICATION_JSON,"application/javascript",MediaType.APPLICATION_XML}) @Consumes(MediaType.APPLICATION_OCTET_STREAM) public Response setZNode(@PathParam("path") String path,@QueryParam("callback") String callback,@DefaultValue("-1") @QueryParam("version") String versionParam,@DefaultValue("base64") @QueryParam("dataformat") String dataformat,@DefaultValue("false") @QueryParam("null") String setNull,@Context UriInfo ui,byte[] data) 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());
  }
  if (setNull.equals("true")) {
    data=null;
  }
  Stat stat=zk.setData(path,data,version);
  ZStat zstat=new ZStat(path,ui.getAbsolutePath().toString(),null,null,stat.getCzxid(),stat.getMzxid(),stat.getCtime(),stat.getMtime(),stat.getVersion(),stat.getCversion(),stat.getAversion(),stat.getEphemeralOwner(),stat.getDataLength(),stat.getNumChildren(),stat.getPzxid());
  return Response.status(Response.Status.OK).entity(new JSONWithPadding(zstat,callback)).build();
}