Java Code Examples for javax.ws.rs.POST

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 getHttpMethod(Method method){
  PUT put=method.getAnnotation(PUT.class);
  if (put != null)   return HttpMethod.PUT;
  POST post=method.getAnnotation(POST.class);
  if (post != null)   return HttpMethod.POST;
  DELETE delete=method.getAnnotation(DELETE.class);
  if (delete != null)   return HttpMethod.DELETE;
  return HttpMethod.GET;
}
 

Example 2

From project action-core, under directory /src/main/java/com/ning/metrics/action/endpoint/.

Source file: HdfsBrowser.java

  19 
vote

@POST @Produces(MediaType.TEXT_PLAIN) @Timed public Response upload(final InputStream body,@QueryParam("path") final String outputPath,@QueryParam("overwrite") @DefaultValue("false") final boolean overwrite,@QueryParam("replication") @DefaultValue("3") final short replication,@QueryParam("blocksize") @DefaultValue("-1") long blocksize,@QueryParam("permission") @DefaultValue("u=rw,go=r") final String permission) throws IOException {
  if (outputPath == null) {
    return Response.status(Response.Status.BAD_REQUEST).header("Warning","199 " + "path cannot be null").cacheControl(cacheControl).build();
  }
  if (blocksize == -1) {
    blocksize=config.getHadoopBlockSize();
  }
  try {
    final URI path=hdfsWriter.write(body,outputPath,overwrite,replication,blocksize,permission);
    return Response.created(path).build();
  }
 catch (  IOException e) {
    final String message;
    if (e.getMessage() != null) {
      message=StringUtils.split(e.getMessage(),'\n')[0];
    }
 else {
      message=e.toString();
    }
    log.warn("Unable to create [{}]: {}",outputPath,message);
    return Response.serverError().header("Warning","199 " + message).cacheControl(cacheControl).build();
  }
}
 

Example 3

From project airlift, under directory /jaxrs/src/test/java/io/airlift/jaxrs/.

Source file: TestOverrideMethodFilterInHttpServer.java

  19 
vote

@Test public void testDeleteViaQueryParam() throws Exception {
  client.execute(buildRequestWithQueryParam(POST,DELETE),createStatusResponseHandler());
  assertFalse(resource.postCalled(),"POST");
  assertTrue(resource.deleteCalled(),"DELETE");
  assertFalse(resource.putCalled(),"PUT");
  assertFalse(resource.getCalled(),"GET");
}
 

Example 4

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 5

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 6

From project ATHENA, under directory /core/web-resources/src/main/java/org/fracturedatlas/athena/web/resource/.

Source file: FieldResource.java

  19 
vote

/** 
 * Save or update the propField contained in this JSON string Note that values cannot be updated from this endpoint.  Instead, post new values to /{fieldId}/values Clients are required to pass valueType, name, and strict strict must be wither "false" or "true" valueType must be: STRING, INTEGER, DATETIME, BOOLEAN
 */
@POST public Object saveField(String json) throws Exception {
  PropField propField=gson.fromJson(json,PropField.class);
  if (propField == null) {
    throw new AthenaException("Sent a blank or malformed request body.  Could not make a field out of it.");
  }
  propField=propFieldManager.savePropField(propField);
  return propField;
}
 

Example 7

From project bam, under directory /modules/activity-management/activity-server-rests/src/main/java/org/overlord/bam/activity/server/rest/.

Source file: RESTActivityServer.java

  19 
vote

/** 
 * This method handles queries for activity events.
 * @param qspec The query spec
 * @return The list of activity events
 * @throws Exception Failed to query activity events
 */
@POST @Path("/query") @Produces("application/json") public String query(String qspec) throws Exception {
  String ret="";
  QuerySpec qs=ActivityUtil.deserializeQuerySpec(qspec.getBytes());
  if (LOG.isLoggable(Level.FINEST)) {
    LOG.finest("Activity Server Query Spec=" + qs);
  }
  if (_activityServer == null) {
    throw new Exception("Activity Server is not available");
  }
  java.util.List<ActivityUnit> list=_activityServer.query(qs);
  if (list != null) {
    byte[] b=ActivityUtil.serializeActivityUnitList(list);
    ret=new String(b);
  }
  if (LOG.isLoggable(Level.FINEST)) {
    LOG.finest("Activity Server Query Result=" + ret);
  }
  return (ret);
}
 

Example 8

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

Source file: SecurityInterceptor.java

  19 
vote

/** 
 * Scans the method annotations for RESTEasy annotations, to determine the HTTP verbs used. We'll assume this is the required access type, but any Verify annotation which specifies an access type can override this later.
 * @param invocation method invocation object
 * @return the required minimum access type
 */
private Access getAssumedAccessType(MethodInvocation invocation){
  Access minimumLevel=Access.READ_ONLY;
  for (  Annotation annotation : invocation.getMethod().getAnnotations()) {
    if (annotation instanceof PUT || annotation instanceof POST || annotation instanceof DELETE) {
      minimumLevel=Access.ALL;
      break;
    }
  }
  return minimumLevel;
}
 

Example 9

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

@Override @Secured(Permission.TEST_CASE_EDIT) @POST @Path("/{id}/import_multistep_testcases/") public Boolean importMultiStepTestCasesFromCsv(MultipartBody body_,@PathParam("id") final Integer productId_) throws Exception {
  List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments=body_.getAllAttachments();
  javax.activation.DataHandler dataHandler=attachments.get(0).getDataHandler();
  InputStream inputStream=dataHandler.getInputStream();
  OutputStream outputStream=new ByteArrayOutputStream();
  IOUtils.copy(inputStream,outputStream);
  inputStream.close();
  outputStream.close();
  testCaseService.importMultiStepTestCasesFromCsv(outputStream.toString(),productId_);
  return Boolean.TRUE;
}
 

Example 10

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 11

From project Cilia_1, under directory /framework/remote/src/main/java/fr/liglab/adele/cilia/remote/impl/.

Source file: AdminChainREST.java

  19 
vote

/** 
 * Create a new initial empty chain chain/
 * @param id The ID of the new mediation chain.
 * @throws CiliaException if the given chain id already exist.
 */
@POST @Produces("application/json") public String emptyChain(@PathParam("chainid") String id){
  try {
    admin.createEmptyChain(id);
  }
 catch (  CiliaException e) {
    e.printStackTrace();
    return "{ return : false, " + "exception : " + e.getMessage() + "}";
  }
  return "{ return : true}";
}
 

Example 12

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 13

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 14

From project crest, under directory /integration/server/src/main/java/org/codegist/crest/server/stubs/params/multiparts/.

Source file: CollectionsStub.java

  19 
vote

@POST @Path("default") public String defaults(@FormDataParam("p1") List<FormDataBodyPart> p1,@FormDataParam("p2") List<FormDataBodyPart> p2,@FormDataParam("p3") List<FormDataBodyPart> p3,@FormDataParam("p4") List<FormDataBodyPart> p4) throws UnsupportedEncodingException {
  List<FormDataBodyPart> ps=new ArrayList<FormDataBodyPart>();
  ps.addAll(p1);
  ps.addAll(p2);
  ps.addAll(p3);
  ps.addAll(p4);
  return format("default() p1=%s p2=%s p3=%s p4=%s",ToStrings.stringMulti(p1),ToStrings.stringMulti(p2),ToStrings.stringMulti(p3),ToStrings.stringMulti(p4));
}
 

Example 15

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 form post 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 "SUCCESS" for success, 8 if exists, 2 for general error,etc.
 * @throws PentahoAccessControlException
 */
@POST @Path("/postAnalysis") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces({"text/plain","text/html"}) public Response postMondrainSchema(@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 {
  ResponseBuilder responseBuilder;
  Response response=this.putMondrianSchema(dataInputStream,schemaFileInfo,catalogName,datasourceName,overwrite,xmlaEnabledFlag,parameters);
  responseBuilder=Response.ok().status(200);
  responseBuilder.entity(String.valueOf(response.getStatus()));
  return responseBuilder.build();
}
 

Example 16

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

Source file: DashboardRest.java

  19 
vote

@POST @Path("/document/{docId}/validate") @Produces(MediaType.APPLICATION_JSON) public Object getValidators(@Context HttpServletRequest request,@PathParam("docId") String docId) throws Exception {
  CoreSession session=SessionFactory.getSession(request);
  DocumentModel doc=session.getDocument(new IdRef(docId));
  JSONObject result=new JSONObject();
  if (doc != null) {
    try {
      EventsHelper.fireDocumentEvent(session,EventsHelper.EVENTTYPE_VALIDATIONREQUEST,doc);
      result.put("result","ok");
    }
 catch (    Exception e) {
      return formatError("Couldn't run validation",e);
    }
  }
 else {
    return formatError("Document not found");
  }
  return result.toString();
}
 

Example 17

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 18

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

@GET @Produces(MediaType.APPLICATION_JSON) public Response list() throws Exception {
  StringWriter output=new StringWriter();
  List<Comment> comments=blog.listComments();
  JsonGenerator generator=jsonFactory.createJsonGenerator(output);
  generator.writeStartArray();
  for (  Comment comment : comments) {
    generateCommentJson(generator,comment,true);
  }
  generator.writeEndArray();
  generator.close();
  return Response.status(Status.OK).header(RFC2616.HEADER_ALLOW,HttpMethod.GET + "," + HttpMethod.POST).type(MediaType.APPLICATION_JSON).entity(output.toString()).build();
}
 

Example 19

From project fast-http, under directory /src/main/java/org/neo4j/smack/api/.

Source file: RelationshipService.java

  19 
vote

@POST @Transactional @Path(UrlReverseLookerUpper.PATH_NODE_RELATIONSHIPS) @DeserializeWith(RelationshipCreationDeserializationStrategy.class) @SerializeWith(RelationshipSerializationStrategy.class) public void createRelationship(Invocation invocation,Output result){
  GraphDatabaseService db=invocation.getDB();
  RelationshipCreationDescription relToCreate=invocation.getContent();
  Node from=db.getNodeById(getNodeId(invocation));
  Node to=db.getNodeById(relToCreate.getEndNodeId());
  Relationship rel=from.createRelationshipTo(to,relToCreate.getType());
  setProperties(rel,relToCreate);
  result.createdAt(url.reverse(rel),rel);
}
 

Example 20

From project gatein-management, under directory /rest/src/main/java/org/gatein/management/rest/.

Source file: RestController.java

  19 
vote

private Response validateRequest(HttpManagedRequest request){
  String operationName=request.getOperationName();
  String httpMethod=request.getHttpMethod();
  MediaType mediaType=ContentTypeUtils.getMediaType(request.getContentType());
  if (operationName.equals(OperationNames.READ_RESOURCE)) {
    if (!httpMethod.equals(HttpMethod.GET)) {
      return badRequest("Request must be a GET.",operationName,mediaType);
    }
  }
 else   if (operationName.equals(OperationNames.ADD_RESOURCE)) {
    if (!httpMethod.equals(HttpMethod.POST)) {
      return badRequest("Request must be a POST.",operationName,mediaType);
    }
  }
 else   if (operationName.equals(OperationNames.UPDATE_RESOURCE)) {
    if (!httpMethod.equals(HttpMethod.PUT)) {
      return badRequest("Request must be a POST.",operationName,mediaType);
    }
  }
 else   if (operationName.equals(OperationNames.REMOVE_RESOURCE)) {
    if (!httpMethod.equals(HttpMethod.DELETE)) {
      return badRequest("Request must be a DELETE.",operationName,mediaType);
    }
  }
  return null;
}
 

Example 21

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

Source file: ClustersResource.java

  19 
vote

@POST public Response createCluster(@FormParam(FORM_PARAM_CLUSTER_NAME) String clusterName){
  if (clusterName == null || clusterName.isEmpty()) {
    throw new GlusterValidationException("Parameter [" + FORM_PARAM_CLUSTER_NAME + "] is missing in request!");
  }
  if (clusterService.getCluster(clusterName) != null) {
    throw new GlusterValidationException("Cluster [" + clusterName + "] already exists!");
  }
  clusterService.createCluster(clusterName);
  return createdResponse(clusterName);
}
 

Example 22

From project grouperfish, under directory /service/src/main/java/com/mozilla/grouperfish/rest/jaxrs/.

Source file: RunResource.java

  19 
vote

@POST public Response runTransformsForQuery(@PathParam("namespace") final String namespace,@Context final HttpServletRequest request){
  final Scope ns=scope(namespace);
  if (!ns.allows(RunResource.class,new HttpAccess(Operation.RUN,request))) {
    return FORBIDDEN;
  }
  try {
    batchService().schedule(ns);
  }
 catch (  final Exception e) {
    log.error(String.format("Error initiating run request '%s'",request.getPathInfo()),e);
    return FAIL;
  }
  return ACCEPTED;
}
 

Example 23

From project hcatalog, under directory /webhcat/svr/src/main/java/org/apache/hcatalog/templeton/.

Source file: Server.java

  19 
vote

/** 
 * Execute an hcat ddl expression on the local box.  It is run as the authenticated user and rate limited.
 */
@POST @Path("ddl") @Produces({MediaType.APPLICATION_JSON}) public ExecBean ddl(@FormParam("exec") String exec,@FormParam("group") String group,@FormParam("permissions") String permissions) throws NotAuthorizedException, BusyException, BadParam, ExecuteException, IOException {
  verifyUser();
  verifyParam(exec,"exec");
  HcatDelegator d=new HcatDelegator(appConf,execService);
  return d.run(getUser(),exec,false,group,permissions);
}
 

Example 24

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

Source file: ViewResource.java

  19 
vote

@POST @Path("permission") public ReturnCodeBean changeViewPermission(@Context HttpServletRequest request,@FormParam("owner") String owner,@FormParam("view_vid") String vid,@FormParam("permission") String permission){
  try {
    if (owner.intern() == request.getRemoteUser().intern()) {
      ViewStore vs=new ViewStore(owner,vid);
      ViewBean view=vs.get();
      view.setPermissionType(permission);
      vs.set(view);
    }
 else {
      throw new Exception("Permission denied.");
    }
  }
 catch (  Exception e) {
    log.error(ExceptionUtil.getStackTrace(e));
    throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("View save failed.").build());
  }
  return new ReturnCodeBean(ReturnCodeBean.SUCCESS,"Saved");
}
 

Example 25

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

Source file: ConfigManager.java

  19 
vote

@POST @Path("blueprint/{name}") public Response createBlueprint(@Context UriInfo uri,@PathParam("name") String name,ConfigManifest blueprint){
  Response res;
  try {
    ZooKeeper zk=Controller.getInstance().getZKInstance();
    blueprint.setUrl(uri.getAbsolutePath().toURL());
    byte[] data=JAXBUtil.write(blueprint);
    Stat stat=zk.exists(CommonConfigurationKeys.ZOOKEEPER_CONFIG_BLUEPRINT_PATH_DEFAULT + '/' + name,false);
    if (stat == null) {
      zk.create(CommonConfigurationKeys.ZOOKEEPER_CONFIG_BLUEPRINT_PATH_DEFAULT + '/' + name,data,Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
    }
 else {
      throw new WebApplicationException(409);
    }
    res=Response.created(uri.getAbsolutePath()).build();
    return res;
  }
 catch (  WebApplicationException e) {
    throw e;
  }
catch (  Exception e) {
    LOG.error(ExceptionUtil.getStackTrace(e));
    throw new WebApplicationException(500);
  }
}
 

Example 26

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 27

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

Source file: AuthorizeResource.java

  19 
vote

@POST @Produces(MediaType.TEXT_HTML) public Response login(@FormParam("oauth_token") String oauthToken,@FormParam("OpenID") String userSuppliedString,@FormParam("allow") String allowString,@FormParam("deny") String denyString,@Context HttpServletRequest request) throws DiscoveryException, MessageException, ConsumerException, URISyntaxException {
  if (allowString != null || denyString != null) {
    if (allowString != null && allowString.endsWith("Allow")) {
      keyManager.saveAuthorization(oauthToken,userSuppliedString,null);
      return Response.ok().entity("Go to Access Token").build();
    }
 else     if (denyString != null && denyString.endsWith("Deny")) {
      return Response.status(Status.BAD_REQUEST).entity("Denied by the user").build();
    }
    return Response.status(Status.BAD_REQUEST).entity("Error occurs during authorization").build();
  }
 else {
    String returnToUrl="http://localhost:8080/iserve/oauth/authorize?oauth_token=" + oauthToken;
    List discoveries=manager.discover(userSuppliedString);
    DiscoveryInformation discovered=manager.associate(discoveries);
    request.getSession().setAttribute("openid-disc",discovered);
    AuthRequest authReq=manager.authenticate(discovered,returnToUrl);
    return Response.seeOther(new URI(authReq.getDestinationUrl(true))).build();
  }
}
 

Example 28

From project javaee-tutorial, under directory /jaxrs/server/src/main/java/org/jboss/ee/tutorial/jaxrs/server/.

Source file: Library.java

  19 
vote

@POST @Path("/book/{isbn}") public Book updateBook(@PathParam("isbn") String id,String title){
  Book book=books.get(id);
  if (book != null) {
    book.setTitle(title);
  }
  log.infof("updateBook: %s",book);
  return book;
}
 

Example 29

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 30

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 31

From project jersey-ahc-client, under directory /src/test/java/org/sonatype/spice/jersey/client/ahc/tests/tests/.

Source file: AuthTest.java

  19 
vote

@POST public String post(@Context HttpHeaders h,String e){
  requestCount++;
  String value=h.getRequestHeaders().getFirst("Authorization");
  if (value == null) {
    assertEquals(1,requestCount);
    throw new WebApplicationException(Response.status(401).header("WWW-Authenticate","Basic realm=\"WallyWorld\"").build());
  }
 else {
    assertTrue(requestCount > 1);
  }
  return e;
}
 

Example 32

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 33

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 34

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/jax_rs/basic/src/main/java/demo/jaxrs/server/.

Source file: CustomerService.java

  19 
vote

@POST @Path("/customers/") public Response addCustomer(Customer customer){
  System.out.println("----invoking addCustomer, Customer name is: " + customer.getName());
  customer.setId(++currentId);
  customers.put(customer.getId(),customer);
  return Response.ok(customer).build();
}
 

Example 35

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 36

From project lyo.rio, under directory /OSLC4JChangeManagement/src/org/eclipse/lyo/oslc4j/changemanagement/resources/.

Source file: ChangeRequestResource.java

  19 
vote

@OslcCreationFactory(title="Change Request Creation Factory",label="Change Request Creation",resourceShapes={OslcConstants.PATH_RESOURCE_SHAPES + "/" + Constants.PATH_CHANGE_REQUEST},resourceTypes={Constants.TYPE_CHANGE_REQUEST},usages={OslcConstants.OSLC_USAGE_DEFAULT}) @POST @Consumes({OslcMediaType.APPLICATION_RDF_XML,OslcMediaType.APPLICATION_XML,OslcMediaType.APPLICATION_JSON}) @Produces({OslcMediaType.APPLICATION_RDF_XML,OslcMediaType.APPLICATION_XML,OslcMediaType.APPLICATION_JSON}) public Response addChangeRequest(@Context final HttpServletRequest httpServletRequest,@Context final HttpServletResponse httpServletResponse,final ChangeRequest changeRequest) throws URISyntaxException {
  final long identifier=Persistence.getNextIdentifier();
  final URI about=new URI(httpServletRequest.getScheme(),null,httpServletRequest.getServerName(),httpServletRequest.getServerPort(),httpServletRequest.getContextPath() + "/changeRequests/" + identifier,null,null);
  changeRequest.setAbout(about);
  changeRequest.setIdentifier(String.valueOf(identifier));
  changeRequest.setServiceProvider(ServiceProviderSingleton.getServiceProviderURI());
  final Date date=new Date();
  changeRequest.setCreated(date);
  changeRequest.setModified(date);
  Persistence.addChangeRequest(changeRequest);
  setETagHeader(getETagFromChangeRequest(changeRequest),httpServletResponse);
  return Response.created(about).entity(changeRequest).build();
}
 

Example 37

From project lyo.server, under directory /org.eclipse.lyo.samples.excel/src/main/java/org/eclipse/lyo/samples/excel/changerequest/.

Source file: ChangeRequestCreatorService.java

  19 
vote

@POST public void doPost(@PathParam("projectId") String projectId,@Context UriInfo uriInfo,MultivaluedMap<String,String> formData){
  String title=formData.getFirst("title");
  String description=formData.getFirst("description");
  String status=formData.getFirst("status");
  if (description == null) {
    description="";
  }
  try {
    ChangeRequestDto dto=new ChangeRequestDto();
    dto.setTitle(title);
    dto.setDescription(description);
    dto.setStatus(status);
    String baseUrl=uriInfo.getBaseUri().toString() + IConstants.SERVICE_SERVICES;
    ResourceAdapter adapter=AdapterRegistry.getAdapter(baseUrl);
    adapter.addChangeRequest(dto);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 38

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 39

From project nuxeo-opensocial, under directory /nuxeo-opensocial-features/src/main/java/org/nuxeo/opensocial/gadgets/.

Source file: GadgetDocument.java

  19 
vote

@POST @Path("deletePicture") public Response doDelete(){
  try {
    doc.setPropertyValue("file:content",null);
    CoreSession session=getContext().getCoreSession();
    session.saveDocument(doc);
    session.save();
  }
 catch (  ClientException e) {
    doDeleteFiles(GADGET_CONTENT_FILES);
  }
  return Response.ok("File upload ok",MediaType.TEXT_PLAIN).build();
}
 

Example 40

From project nuxeo-rss-reader, under directory /nuxeo-rss-reader-ui/src/main/java/org/nuxeo/rss/reader/webengine/.

Source file: RssReaderModuleRoot.java

  19 
vote

@POST @Path("/removeFeed") public Object removeFeed(@FormParam("id") String id,@QueryParam("language") String language) throws Exception {
  CoreSession session=ctx.getCoreSession();
  session.removeDocument(new IdRef(id));
  session.save();
  return getConfigPage(language);
}
 

Example 41

From project odata4j, under directory /odata4j-core/src/main/java/org/odata4j/producer/resources/.

Source file: EntitiesRequestResource.java

  19 
vote

@POST @Produces({ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8,ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8,ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8}) public Response createEntity(@Context HttpHeaders httpHeaders,@Context UriInfo uriInfo,@Context ContextResolver<ODataProducer> producerResolver,@PathParam("entitySetName") String entitySetName,String payload) throws Exception {
  if (entitySetName.equals("mex") && httpHeaders.getMediaType() != null && httpHeaders.getMediaType().toString().startsWith("application/soap+xml"))   return Response.status(405).build();
  log("createEntity","entitySetName",entitySetName);
  ODataProducer producer=producerResolver.getContext(ODataProducer.class);
  OEntity entity=this.getRequestEntity(httpHeaders,uriInfo,payload,producer.getMetadata(),entitySetName,null);
  EntityResponse response=producer.createEntity(entitySetName,entity);
  FormatWriter<EntityResponse> writer=FormatWriterFactory.getFormatWriter(EntityResponse.class,httpHeaders.getAcceptableMediaTypes(),null,null);
  StringWriter sw=new StringWriter();
  writer.write(uriInfo,sw,response);
  String relid=InternalUtil.getEntityRelId(response.getEntity());
  String entryId=uriInfo.getBaseUri().toString() + relid;
  String responseEntity=sw.toString();
  return Response.ok(responseEntity,writer.getContentType()).status(Status.CREATED).location(URI.create(entryId)).header(ODataConstants.Headers.DATA_SERVICE_VERSION,ODataConstants.DATA_SERVICE_VERSION_HEADER).build();
}
 

Example 42

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 43

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 44

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 45

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 46

From project platform_3, under directory /jaxrs/src/test/java/com/proofpoint/jaxrs/.

Source file: TestOverrideMethodFilterInHttpServer.java

  19 
vote

@Test public void testDeleteViaQueryParam() throws Exception {
  client.execute(buildRequestWithQueryParam(POST,DELETE),createStatusResponseHandler());
  assertFalse(resource.postCalled(),"POST");
  assertTrue(resource.deleteCalled(),"DELETE");
  assertFalse(resource.putCalled(),"PUT");
  assertFalse(resource.getCalled(),"GET");
}
 

Example 47

From project remitt, under directory /src/main/java/org/remitt/server/impl/.

Source file: ServiceImpl.java

  19 
vote

@POST @Path("changepassword/{pw}") @Produces("application/json") public Boolean changePassword(String newPassword){
  Connection c=getConnection();
  String userName=getCurrentUserName();
  Boolean returnValue=false;
  PreparedStatement cStmt=null;
  try {
    cStmt=c.prepareCall("UPDATE tUser SET passhash = MD5( ? ) WHERE username = ?;");
    cStmt.setString(1,newPassword);
    cStmt.setString(2,userName);
    cStmt.execute();
    returnValue=(cStmt.getUpdateCount() == 1);
  }
 catch (  NullPointerException npe) {
    log.error("Caught NullPointerException",npe);
  }
catch (  SQLException e) {
    log.error("Caught SQLException",e);
  }
 finally {
    DbUtil.closeSafely(cStmt);
    DbUtil.closeSafely(c);
  }
  return returnValue;
}
 

Example 48

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 49

From project resty-gwt, under directory /restygwt/src/main/java/org/fusesource/restygwt/rebind/.

Source file: RestServiceClassCreator.java

  19 
vote

private String getRestMethod(JMethod method) throws UnableToCompleteException {
  String restMethod=null;
  if (method.getAnnotation(DELETE.class) != null) {
    restMethod=METHOD_DELETE;
  }
 else   if (method.getAnnotation(GET.class) != null) {
    restMethod=METHOD_GET;
  }
 else   if (method.getAnnotation(HEAD.class) != null) {
    restMethod=METHOD_HEAD;
  }
 else   if (method.getAnnotation(OPTIONS.class) != null) {
    restMethod=METHOD_OPTIONS;
  }
 else   if (method.getAnnotation(POST.class) != null) {
    restMethod=METHOD_POST;
  }
 else   if (method.getAnnotation(PUT.class) != null) {
    restMethod=METHOD_PUT;
  }
 else   if (method.getAnnotation(JSONP.class) != null) {
    restMethod=METHOD_JSONP;
  }
 else {
    restMethod=method.getName();
    if (!REST_METHODS.contains(restMethod)) {
      error("Invalid rest method. It must either have a lower case rest method name or have a javax rs method annotation: " + method.getReadableDeclaration());
    }
  }
  return restMethod;
}
 

Example 50

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

Source file: JobsResource.java

  19 
vote

/** 
 * Handles a function call job with a JSON payload.
 * @param jsonArgument Argument passed to the function called on RServi.
 * @param httpHeaders
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
@POST @Consumes(Constants.JSON_CONTENT_TYPE) public Response handleJsonFunctionCallJob(final String jsonArgument,@Context final HttpHeaders httpHeaders,@Context final UriInfo uriInfo) throws URISyntaxException, IOException {
  return handleNewRestJob(httpHeaders,uriInfo,new JobBuilder(){
    public AbstractJob build(    final String applicationName,    final UUID jobId,    final GregorianCalendar submissionTime){
      return new JsonFunctionCallJob(Source.REST,applicationName,jobId,submissionTime,jsonArgument);
    }
  }
);
}
 

Example 51

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

Source file: ArtifactResource.java

  19 
vote

/** 
 * S-RAMP atom POST to upload an artifact to the repository.  The artifact content should be POSTed raw.
 * @param fileName
 * @param model
 * @param type
 * @param content
 * @throws SrampAtomException
 */
@POST @Path("{model}/{type}") @Produces(MediaType.APPLICATION_ATOM_XML_ENTRY) public Entry create(@HeaderParam("Content-Type") String contentType,@HeaderParam("Slug") String fileName,@PathParam("model") String model,@PathParam("type") String type,InputStream is) throws SrampAtomException {
  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.");
    }
    String mimeType=MimeTypes.determineMimeType(contentType,fileName,artifactType);
    artifactType.setMimeType(mimeType);
    if (fileName == null) {
      if (artifactType.getArtifactType() == ArtifactTypeEnum.Document) {
        fileName="newartifact.bin";
      }
 else       if (artifactType.getArtifactType() == ArtifactTypeEnum.XmlDocument) {
        fileName="newartifact.xml";
      }
 else {
        fileName="newartifact." + artifactType.getArtifactType().getModel();
      }
    }
    PersistenceManager persistenceManager=PersistenceFactory.newInstance();
    BaseArtifactType baseArtifactType=ArtifactType.getArtifactInstance(artifactType);
    baseArtifactType.setName(fileName);
    BaseArtifactType artifact=persistenceManager.persistArtifact(baseArtifactType,is);
    Collection<DerivedArtifactType> derivedArtifacts=DerivedArtifactsFactory.newInstance().deriveArtifacts(artifact);
    persistenceManager.persistDerivedArtifacts(artifact,derivedArtifacts);
    ArtifactToFullAtomEntryVisitor visitor=new ArtifactToFullAtomEntryVisitor();
    ArtifactVisitorHelper.visitArtifact(visitor,artifact);
    return visitor.getAtomEntry();
  }
 catch (  Exception e) {
    throw new SrampAtomException(e);
  }
 finally {
    IOUtils.closeQuietly(is);
  }
}