Java Code Examples for javax.ws.rs.core.Context

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 airlift, under directory /sample-server/src/main/java/io/airlift/sample/.

Source file: PersonResource.java

  21 
vote

@GET @Produces(MediaType.APPLICATION_JSON) public Response get(@PathParam("id") String id,@Context UriInfo uriInfo){
  Preconditions.checkNotNull(id,"id must not be null");
  Person person=store.get(id);
  if (person == null) {
    return Response.status(Response.Status.NOT_FOUND).entity("[" + id + "]").build();
  }
  return Response.ok(from(person,uriInfo.getRequestUri())).build();
}
 

Example 2

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

Source file: AuthzEndpoint.java

  20 
vote

@GET public Response authorize(@Context HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
  OAuthAuthzRequest oauthRequest=null;
  OAuthIssuerImpl oauthIssuerImpl=new OAuthIssuerImpl(new MD5Generator());
  try {
    oauthRequest=new OAuthAuthzRequest(request);
    String responseType=oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
    OAuthASResponse.OAuthAuthorizationResponseBuilder builder=OAuthASResponse.authorizationResponse(request,HttpServletResponse.SC_FOUND);
    if (responseType.equals(ResponseType.CODE.toString())) {
      builder.setCode(oauthIssuerImpl.authorizationCode());
    }
    if (responseType.equals(ResponseType.TOKEN.toString())) {
      builder.setAccessToken(oauthIssuerImpl.accessToken());
      builder.setExpiresIn(3600l);
    }
    String redirectURI=oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
    final OAuthResponse response=builder.location(redirectURI).buildQueryMessage();
    URI url=new URI(response.getLocationUri());
    return Response.status(response.getResponseStatus()).location(url).build();
  }
 catch (  OAuthProblemException e) {
    final Response.ResponseBuilder responseBuilder=Response.status(HttpServletResponse.SC_FOUND);
    String redirectUri=e.getRedirectUri();
    if (OAuthUtils.isEmpty(redirectUri)) {
      throw new WebApplicationException(responseBuilder.entity("OAuth callback url needs to be provided by client!!!").build());
    }
    final OAuthResponse response=OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e).location(redirectUri).buildQueryMessage();
    final URI location=new URI(response.getLocationUri());
    return responseBuilder.location(location).build();
  }
}
 

Example 3

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/rest/.

Source file: EventStreamEndPoint.java

  20 
vote

@Path("/event/stream/{stream}") @GET @Produces({MediaType.TEXT_PLAIN,"text/plain+epstmts"}) public Response getStream(String stream,@Context UriInfo uriInfo){
  EPStatement ep=registry.getStatement(stream);
  if (ep != null) {
    return Response.ok(new EPStatementQuery(ep,uriInfo.getQueryParameters())).type(MediaType.TEXT_PLAIN).build();
  }
 else {
    return Response.ok(registry.getStatementNames()).type("text/plain+epstmts").build();
  }
}
 

Example 4

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

Source file: RecordResource.java

  19 
vote

/** 
 * Return records of type {childType} who have a field in the format {parentType}Id and where the value of that field is {id} For example, to get all notes attached to a record of type ticket tickets/30/notes This method is shorthand for this search: /notes?ticketId={id}
 * @param id
 * @return
 * @throws NotFoundException
 */
@GET @Path("{parentType}/{id}/{childType}") public Object search(@PathParam("parentType") String parentType,@PathParam("id") String id,@PathParam("childType") String childType,@Context UriInfo ui) throws NotFoundException {
  MultivaluedMap<String,String> queryParams=ui.getQueryParameters();
  parentType=Inflector.getInstance().singularize(parentType);
  childType=Inflector.getInstance().singularize(childType);
  try {
    return recordManager.findSubResources(parentType,id,childType,queryParams);
  }
 catch (  InvalidFieldException ife) {
    throw new NotFoundException();
  }
}
 

Example 5

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

Source file: FormProcessingFacade.java

  19 
vote

@POST @Path("task/{id}/complete") @Produces("text/html") @Consumes("multipart/form-data") public Response closeTaskWithUI(@Context HttpServletRequest request,@PathParam("id") String taskId,MultipartFormDataInput payload){
  FieldMapping mapping=createFieldMapping(payload);
  String username=request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : null;
  String outcomeDirective=mapping.directives.get("outcome");
  if (outcomeDirective != null) {
    getTaskManagement().completeTask(Long.valueOf(taskId),outcomeDirective,mapping.processVars,username);
  }
 else {
    getTaskManagement().completeTask(Long.valueOf(taskId),mapping.processVars,username);
  }
  return Response.ok(SUCCESSFULLY_PROCESSED_INPUT).build();
}
 

Example 6

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

Source file: ConsumerResource.java

  19 
vote

/** 
 * delete the consumer.
 * @param uuid uuid of the consumer to delete.
 * @httpcode 403
 * @httpcode 404
 * @httpcode 200
 */
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("{consumer_uuid}") @Transactional public void deleteConsumer(@PathParam("consumer_uuid") @Verify(Consumer.class) String uuid,@Context Principal principal){
  if (log.isDebugEnabled()) {
    log.debug("deleting  consumer_uuid" + uuid);
  }
  Consumer toDelete=verifyAndLookupConsumer(uuid);
  try {
    this.poolManager.revokeAllEntitlements(toDelete);
  }
 catch (  ForbiddenException e) {
    String msg=e.message().getDisplayMessage();
    throw new ForbiddenException(i18n.tr("Cannot unregister {0} consumer {1} because: {2}",toDelete.getType().getLabel(),toDelete.getName(),msg),e);
  }
  consumerRules.onConsumerDelete(consumerDeleteHelper,toDelete);
  Event event=eventFactory.consumerDeleted(toDelete);
  consumerCurator.delete(toDelete);
  identityCertService.deleteIdentityCert(toDelete);
  sink.sendEvent(event);
}
 

Example 7

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 8

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 9

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

Source file: InstanceResource.java

  19 
vote

@GET @Produces(MediaType.APPLICATION_JSON) public Response getInstance(@PathParam("id") String instanceId,@Context UriInfo uriInfo){
  checkNotNull(instanceId);
  checkNotNull(uriInfo);
  for (  Map.Entry<String,InstanceConnector> instanceConnectorEntry : instanceConnectorMap.entrySet()) {
    Instance instance=instanceConnectorEntry.getValue().getInstance(instanceId);
    if (instance != null) {
      return Response.ok(InstanceRepresentation.fromInstance(instance.toBuilder().setProvider(instanceConnectorEntry.getKey()).setHostname(dnsManager.getFullyQualifiedDomainName(instance)).setTags(tagManager.getTags(instance)).build(),constructSelfUri(uriInfo,instanceId))).build();
    }
  }
  return Response.status(Status.NOT_FOUND).build();
}
 

Example 10

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/webapp/.

Source file: DragonWebServices.java

  19 
vote

@GET @Path("/jobs") @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) public JobsInfo getJobs(@Context HttpServletRequest hsr){
  JobsInfo allJobs=new JobsInfo();
  for (  Job job : appCtx.getAllJobs().values()) {
    Job fullJob=appCtx.getJob(job.getID());
    if (fullJob == null) {
      continue;
    }
    allJobs.add(new JobInfo(fullJob,hasAccess(fullJob,hsr)));
  }
  return allJobs;
}
 

Example 11

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

Source file: DashboardRest.java

  19 
vote

@GET @Path("/service/{serviceid}") @Produces(MediaType.APPLICATION_JSON) public Object getServiceById(@Context HttpServletRequest request,@PathParam("serviceid") String serviceid) throws Exception {
  CoreSession session=SessionFactory.getSession(request);
  DocumentModel worskspaceServiceModel=session.getDocument(new IdRef(serviceid));
  String referencePath=(String)worskspaceServiceModel.getProperty(Service.SCHEMA,Service.PROP_REFERENCESERVICE);
  DocumentModel referencedServiceModel=(referencePath != null) ? session.getDocument(new PathRef(referencePath)) : null;
  return getServiceEntry(session.getDocument(new IdRef(serviceid)),referencedServiceModel).toString();
}
 

Example 12

From project entando-core-engine, under directory /src/main/java/org/entando/entando/aps/system/services/api/server/.

Source file: ApiRestStatusServer.java

  19 
vote

@GET @Produces({"application/json","application/xml"}) @Path("/{namespace}/{resourceName}/{httpMethod}") public Object getApiStatus(@PathParam("httpMethod") String httpMethodString,@PathParam("namespace") String namespace,@PathParam("resourceName") String resourceName,@Context HttpServletRequest request){
  StringApiResponse response=new StringApiResponse();
  ApiMethod.HttpMethod httpMethod=Enum.valueOf(ApiMethod.HttpMethod.class,httpMethodString.toUpperCase());
  try {
    IResponseBuilder responseBuilder=(IResponseBuilder)ApsWebApplicationUtils.getBean(SystemConstants.API_RESPONSE_BUILDER,request);
    ApiMethod apiMethod=responseBuilder.extractApiMethod(httpMethod,namespace,resourceName);
    if (null != apiMethod.getRequiredPermission()) {
      response.setResult(ApiStatus.AUTHORIZATION_REQUIRED.toString(),null);
    }
 else     if (apiMethod.getRequiredAuth()) {
      response.setResult(ApiStatus.AUTHENTICATION_REQUIRED.toString(),null);
    }
 else {
      response.setResult(ApiStatus.FREE.toString(),null);
    }
  }
 catch (  ApiException ae) {
    response.addErrors(((ApiException)ae).getErrors());
    response.setResult(ApiStatus.INACTIVE.toString(),null);
  }
catch (  Throwable t) {
    return this.buildErrorResponse(httpMethod,namespace,resourceName,t);
  }
  return response;
}
 

Example 13

From project gadget-server, under directory /gadget-web/src/main/java/org/overlord/gadgets/web/server/.

Source file: UserController.java

  19 
vote

@POST @Path("authentication") @Consumes("application/json") @Produces("application/json") public UserModel getUser(User user,@Context HttpServletRequest request){
  User theUser=userManager.getUser(user.getName(),user.getPassword());
  UserModel userModel=new UserModel();
  if (theUser != null) {
    userModel.setUserId(theUser.getId());
    userModel.setUserName(theUser.getName());
    List<Page> pages=userManager.getPages(theUser.getId());
    if (pages != null && pages.size() > 0) {
      userModel.setCurrentPageId(pages.get(0).getId());
    }
    userModel.setDisplayName(theUser.getDisplayName());
    request.getSession().setAttribute("user",userModel);
  }
  return userModel;
}
 

Example 14

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 15

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

Source file: ViewResource.java

  19 
vote

@GET @Path("vid/{vid}") public ViewBean getView(@Context HttpServletRequest request,@PathParam("vid") String vid){
  ViewStore view;
  ViewBean vr;
  String uid=request.getRemoteUser();
  try {
    view=new ViewStore(uid,vid);
    vr=view.get();
    if (request.getRemoteUser().intern() != vr.getOwner().intern() && vr.getPermissionType().intern() != "public".intern()) {
      throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity("permission denied.").build());
    }
  }
 catch (  IllegalAccessException e) {
    throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("View does not exist.").build());
  }
  return vr;
}
 

Example 16

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 17

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

Source file: Hoop.java

  19 
vote

/** 
 * Binding to handle all DELETE requests.
 * @param user principal making the request.
 * @param path path for the DELETE request.
 * @param recursive indicates if the delete is recursive, default is <code>false</code>
 * @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}.
 */
@DELETE @Path("{path:.*}") @Produces(MediaType.APPLICATION_JSON) public Response delete(@Context Principal user,@PathParam("path") FsPathParam path,@QueryParam(DeleteRecursiveParam.NAME) @DefaultValue(DeleteRecursiveParam.DEFAULT) DeleteRecursiveParam recursive,@QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) DoAsParam doAs) throws IOException, HadoopException {
  path.makeAbsolute();
  MDC.put("op","DELETE");
  AUDIT_LOG.info("[{}] recursive [{}]",path,recursive);
  FSDelete command=new FSDelete(path.value(),recursive.value());
  JSONObject json=fsExecute(user,doAs.value(),command);
  return Response.ok(json).type(MediaType.APPLICATION_JSON).build();
}
 

Example 18

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

Source file: AccessTokenResource.java

  19 
vote

@GET @Produces(MediaType.TEXT_PLAIN) public Response generateAccessToken(@Context HttpContext hc) throws OAuthSignatureException, NoSuchAlgorithmException {
  OAuthServerRequest request=new OAuthServerRequest(hc.getRequest());
  OAuthParameters params=new OAuthParameters();
  params.readRequest(request);
  OAuthSecrets secrets=new OAuthSecrets();
  Consumer consumer=keyManager.findConsumer(params.getConsumerKey());
  if (consumer != null && consumer.getConsumerKey() != null && consumer.getConsumerSecret() != null) {
    secrets.setConsumerSecret(consumer.getConsumerSecret());
  }
 else {
    return Response.status(Status.BAD_REQUEST).entity("Consumer is not registered: " + params.getConsumerKey()).build();
  }
  RequestToken requestToken=keyManager.findRequestToken(params.getToken());
  secrets.setTokenSecret(requestToken.getTokenSecret());
  boolean verified=OAuthSignature.verify(request,params,secrets);
  if (verified == false) {
    return Response.status(Status.BAD_REQUEST).entity("signature_invalid").build();
  }
  String[] accessToken=KeyGenerator.generateAccessToken(consumer.getConsumerKey());
  if (requestToken.getGrantedBy() == null) {
    return Response.status(Status.BAD_REQUEST).entity("unauthorized request token: " + requestToken.getTokenKey()).build();
  }
  keyManager.saveAccessToken(accessToken[0],accessToken[1],requestToken,requestToken.getGrantedBy().toString());
  return Response.ok().entity("oauth_token=" + accessToken[0] + "&oauth_token_secret="+ accessToken[1]).build();
}
 

Example 19

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

Source file: AbstractSchedulableEntityManager.java

  19 
vote

/** 
 * Schedules an submitted entity immediately
 * @param type
 * @param entity
 * @return APIResult
 */
public APIResult schedule(@Context HttpServletRequest request,@Dimension("entityType") @PathParam("type") String type,@Dimension("entityName") @PathParam("entity") String entity,@Dimension("colo") @PathParam("colo") String colo){
  checkColo(colo);
  try {
    audit(request,entity,type,"SCHEDULED");
    scheduleInternal(type,entity);
    return new APIResult(APIResult.Status.SUCCEEDED,entity + "(" + type+ ") scheduled successfully");
  }
 catch (  Throwable e) {
    LOG.error("Unable to schedule workflow",e);
    throw IvoryWebException.newException(e,Response.Status.BAD_REQUEST);
  }
}
 

Example 20

From project jboss-as-quickstart, under directory /tasks-rs/src/main/java/org/jboss/as/quickstarts/tasksrs/service/.

Source file: TaskResource.java

  19 
vote

@POST @Path("tasks/{title}") public Response createTask(@Context UriInfo info,@Context SecurityContext context,@PathParam("title") @DefaultValue("task") String taskTitle){
  User user=getUser(context);
  Task task=new Task(taskTitle);
  taskDao.createTask(user,task);
  String rawPath=info.getAbsolutePath().getRawPath().replace(task.getTitle(),task.getId().toString());
  UriBuilder uriBuilder=info.getAbsolutePathBuilder().replacePath(rawPath);
  URI uri=uriBuilder.build();
  return Response.created(uri).build();
}
 

Example 21

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 22

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

Source file: AuthTest.java

  19 
vote

@GET public String get(@Context HttpHeaders h){
  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 "GET";
}
 

Example 23

From project koshinuke.java, under directory /src/java/org/koshinuke/jersey/.

Source file: KoshinukePrincipalProvider.java

  19 
vote

@Override public Injectable<KoshinukePrincipal> getInjectable(ComponentContext ic,Context a,Type t){
  if (KoshinukePrincipal.class.equals(t) == false) {
    return null;
  }
  return new Injectable<KoshinukePrincipal>(){
    @Override public KoshinukePrincipal getValue(){
      HttpServletRequest request=KoshinukePrincipalProvider.this.requestInvoker.get();
      return AuthenticationFilterFactory.getUserPrincipal(request);
    }
  }
;
}
 

Example 24

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 25

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 26

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 27

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

Source file: ChangeRequestCompactService.java

  19 
vote

@GET public StreamingOutput doGet(@QueryParam("uri") String uri,@QueryParam("projectId") String projectId,@QueryParam("id") String id,@Context UriInfo uriInfo){
  String baseUrl=uriInfo.getBaseUri().toString() + IConstants.SERVICE_SERVICES;
  ResourceAdapter adapter=AdapterRegistry.getAdapter(baseUrl);
  String query="PREFIX dcterms:<http://purl.org/dc/elements/1.1/>\n" + "SELECT ?uri ?title ?identifier ?created\n" + "WHERE {\n"+ "  ?uri dcterms:title ?title.\n"+ "  ?uri dcterms:identifier ?identifier.\n"+ "  ?uri dcterms:created ?created.\n"+ "  ?uri dcterms:identifier \"" + id + "\"\n"+ "}\n";
  ResultSet resultSet=adapter.executeSparql(projectId,query);
  final String html=buildHtml(resultSet);
  return new StreamingOutput(){
    public void write(    OutputStream output) throws IOException, WebApplicationException {
      byte[] out=html.getBytes();
      output.write(out);
    }
  }
;
}
 

Example 28

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

Source file: MonitorsResource.java

  19 
vote

@GET @Produces(MediaType.APPLICATION_JSON) public Iterable<MonitorRepresentation> getAll(@Context final UriInfo uriInfo){
  return Iterables.transform(monitors.values(),new Function<Monitor,MonitorRepresentation>(){
    @Override public MonitorRepresentation apply(    @Nullable Monitor monitor){
      return MonitorRepresentation.of(monitor,uriInfo);
    }
  }
);
}
 

Example 29

From project nuxeo-filesystem-connectors, under directory /nuxeo-webdav/src/main/java/org/nuxeo/ecm/webdav/resource/.

Source file: ExistingResource.java

  19 
vote

@PROPPATCH public Response proppatch(@Context UriInfo uriInfo) throws Exception {
  if (backend.isLocked(doc.getRef()) && !backend.canUnlock(doc.getRef())) {
    return Response.status(423).build();
  }
  @SuppressWarnings("deprecation") final net.java.dev.webdav.jaxrs.xml.elements.Response response=new net.java.dev.webdav.jaxrs.xml.elements.Response(new HRef(uriInfo.getRequestUri()),null,null,null,new PropStat(new Prop(new Win32CreationTime()),new Status(OK)),new PropStat(new Prop(new Win32FileAttributes()),new Status(OK)),new PropStat(new Prop(new Win32LastAccessTime()),new Status(OK)),new PropStat(new Prop(new Win32LastModifiedTime()),new Status(OK)));
  return Response.status(207).entity(new MultiStatus(response)).build();
}