Java Code Examples for javax.ws.rs.Produces

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 action-core, under directory /src/main/java/com/ning/metrics/action/endpoint/.

Source file: HdfsBrowser.java

  30 
vote

/** 
 * Build a Viewable to browse HDFS.
 * @param path      path in HDFS to render (directory listing or file), defaults to /
 * @param raw       optional, whether to try to deserialize
 * @param recursive optional, whether to crawl all files under a directory
 * @return Viewable to render the jsp
 * @throws IOException HDFS crawling error
 */
@GET @Path("/hdfs") @Produces({"text/html","text/plain"}) @Timed public Viewable getListing(@QueryParam("path") String path,@QueryParam("raw") final boolean raw,@QueryParam("recursive") final boolean recursive) throws IOException {
  log.debug(String.format("Got request for path=[%s], raw=[%s] and recursive=[%s]",path,raw,recursive));
  if (path == null) {
    path="/";
  }
  if (hdfsReader.isDir(path) && !recursive) {
    return new Viewable("/rest/listing.jsp",hdfsReader.getListing(path));
  }
 else {
    if (raw) {
      return new Viewable("/rest/contentRaw.jsp",hdfsReader.getListing(path,raw,recursive));
    }
 else {
      return new Viewable("/rest/content.jsp",hdfsReader.getListing(path,raw,recursive));
    }
  }
}
 

Example 2

From project airlift, under directory /jmx-http/src/main/java/io/airlift/jmx/.

Source file: MBeanResource.java

  30 
vote

@GET @Produces(MediaType.APPLICATION_JSON) public List<MBeanRepresentation> getMBeans() throws JMException {
  ImmutableList.Builder<MBeanRepresentation> mbeans=ImmutableList.builder();
  for (  ObjectName objectName : mbeanServer.queryNames(new ObjectName("*:*"),null)) {
    mbeans.add(new MBeanRepresentation(mbeanServer,objectName,objectMapper));
  }
  return mbeans.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

  29 
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 ANNIS, under directory /annis-service/src/main/java/annis/service/internal/.

Source file: AnnisWebService.java

  29 
vote

@GET @Path("search/count") @Produces("plain/text") public Response count(@QueryParam("q") String query,@QueryParam("corpora") String rawCorpusNames){
  requiredParameter(query,"q","AnnisQL query");
  requiredParameter(rawCorpusNames,"corpora","comma separated list of corpus names");
  QueryData data=queryDataFromParameters(query,rawCorpusNames);
  long start=new Date().getTime();
  int count=annisDao.count(data);
  long end=new Date().getTime();
  logQuery("COUNT",query,splitCorpusNamesFromRaw(rawCorpusNames),end - start);
  return Response.ok("" + count).type(MediaType.TEXT_PLAIN).build();
}
 

Example 5

From project Arecibo, under directory /agent/src/main/java/com/ning/arecibo/agent/status/.

Source file: StatusPageHandler.java

  29 
vote

@Path("/") @GET @Produces("text/html") public StreamingOutput getSummary(){
  return new StreamingOutput(){
    @Override public void write(    OutputStream output) throws IOException, WebApplicationException {
      PrintWriter pw=new PrintWriter(output,true);
      List<Status> statusList=dataCollector.getStatus();
      if (statusList != null && statusList.size() > 0) {
        pw.println("<h4>[Click on column headers to sort]</h4>");
        pw.println("<table class=\"sortable\">");
        pw.println("<tr>");
        pw.println("<th>Host</th>");
        pw.println("<th>JMX/SNMP</th>");
        pw.println("<th>Attribute</th>");
        pw.println("<th>Status</th>");
        pw.println("<th>Last update</th>");
        pw.println("<th>Message</th>");
        pw.println("<th>Last Collected Value</th>");
        pw.println("</tr>");
        for (        Status status : statusList) {
          long lastUpdateTime=status.getLastUpdateTime();
          String lastUpdateString=(lastUpdateTime != 0) ? formatter.print(lastUpdateTime) : "--";
          pw.println("<tr>");
          pw.printf("<td>%s</td>\n",status.getHost());
          pw.printf("<td>%s</td>\n",status.getEventName());
          pw.printf("<td>%s</td>\n",status.getValueName());
          pw.printf("<td>%s</td>\n",status.getLastStatus());
          pw.printf("<td>%s</td>\n",lastUpdateString);
          pw.printf("<td>%s</td>\n",status.getLastStatusMessage());
          pw.printf("<td>%s</td>\n",status.getLastValue());
          pw.println("</tr>");
        }
        pw.println("</table>");
      }
 else {
        pw.println("[no status available.]");
      }
    }
  }
;
}
 

Example 6

From project arquillian-showcase, under directory /jaxrs/src/main/java/com/acme/jaxrs/resource/.

Source file: CustomerResource.java

  29 
vote

@GET @Path("/{id:[1-9][0-9]*}") @Produces("text/html") public String getCustomerHtml(@PathParam("id") long id){
  Customer c=findCustomerById(id);
  if (c != null) {
    StringBuilder html=new StringBuilder();
    html.append("<html><head><title>");
    html.append(c.getName());
    html.append("</title></head><body><h1>");
    html.append(c.getName());
    html.append("</h1><dl><dt>Id</dt><dd>");
    html.append(c.getId());
    html.append("</dd><dt>Name</dt><dd>");
    html.append(c.getName());
    html.append("</dd></dl></body>");
    return html.toString();
  }
  return null;
}
 

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

  29 
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 bpm-console, under directory /server/war/src/main/java/org/jboss/bpm/console/server/.

Source file: InfoFacade.java

  29 
vote

@GET @Path("resources") @Produces("text/html") public Response getPublishedUrls(@Context HttpServletRequest request){
  final Class[] rootResources=new Class[]{InfoFacade.class,ProcessMgmtFacade.class,TaskListFacade.class,TaskMgmtFacade.class,UserMgmtFacade.class,EngineFacade.class,FormProcessingFacade.class};
  String rsServer=request.getContextPath();
  if (request.getServletPath() != null && !"".equals(request.getServletPath())) {
    rsServer=request.getContextPath() + request.getServletPath();
  }
  RsDocBuilder rsDocBuilder=new RsDocBuilder(rsServer,rootResources);
  StringBuffer sb=rsDocBuilder.build();
  return Response.ok(sb.toString()).build();
}
 

Example 9

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

Source file: ActivationKeyResource.java

  29 
vote

/** 
 * @return a list of Pool objects
 * @httpcode 400
 * @httpcode 200
 */
@GET @Path("{activation_key_id}/pools") @Produces(MediaType.APPLICATION_JSON) public List<Pool> getActivationKeyPools(@PathParam("activation_key_id") String activationKeyId){
  ActivationKey key=findKey(activationKeyId);
  List<Pool> pools=new ArrayList<Pool>();
  for (  ActivationKeyPool akp : key.getPools()) {
    pools.add(akp.getPool());
  }
  return pools;
}
 

Example 10

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

Source file: ProductWebServiceImpl.java

  29 
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 11

From project cdi-arq-workshop, under directory /arquillian-showcase/jaxrs/src/main/java/com/acme/jaxrs/resource/.

Source file: CustomerResource.java

  29 
vote

@GET @Path("/{id:[1-9][0-9]*}") @Produces("text/html") public String getCustomerHtml(@PathParam("id") long id){
  Customer c=findCustomerById(id);
  if (c != null) {
    StringBuilder html=new StringBuilder();
    html.append("<html><head><title>");
    html.append(c.getName());
    html.append("</title></head><body><h1>");
    html.append(c.getName());
    html.append("</h1><dl><dt>Id</dt><dd>");
    html.append(c.getId());
    html.append("</dd><dt>Name</dt><dd>");
    html.append(c.getName());
    html.append("</dd></dl></body>");
    return html.toString();
  }
  return null;
}
 

Example 12

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

Source file: AdaptorController.java

  29 
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 13

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

Source file: AdminChainREST.java

  29 
vote

/** 
 * Retrieve a mediation chain.
 * @param id The ID of the chain  to retrieve 
 * @return The required Chain, return <code>null<code> if chain does not exist.
 * @throws ParseException 
 */
@GET @Produces("application/json") public String chain(@PathParam("chainid") String chainid){
  if (chainid == null || chainid.length() < 1 || chainid.compareToIgnoreCase("cilia") == 0) {
    return getChainNames();
  }
  Chain chain=admin.getChain(chainid);
  StringBuilder result=new StringBuilder();
  if (chain == null) {
    result.append("{").append(chainid).append(": Does not exist}");
  }
 else {
    result.append(chain);
  }
  return result.toString();
}
 

Example 14

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

Source file: InstanceResource.java

  29 
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 15

From project collector, under directory /src/main/java/com/ning/metrics/collector/jaxrs/.

Source file: AsyncEventResource.java

  29 
vote

@Path("/event") @GET @Produces({APPLICATION_JSON,APPLICATION_JSONP}) public SuspendResponse subscribe(@PathParam("type") @DefaultValue(EventListenerDispatcher.NO_FILTER_KEY) final Broadcaster feed,@QueryParam("type") @DefaultValue(EventListenerDispatcher.NO_FILTER_KEY) final String eventType){
  Broadcaster broadcaster=feed;
  if (feed == null || feed.getAtmosphereResources().size() == 0) {
    broadcaster=BroadcasterFactory.getDefault().lookup(JerseySimpleBroadcaster.class,eventType);
    if (broadcaster == null) {
      broadcaster=BroadcasterFactory.getDefault().lookup(JerseySimpleBroadcaster.class,eventType,true);
      final NewEventListener listener=new NewEventListener(config,broadcaster);
      dispatcher.addListener(eventType,listener);
    }
  }
  return new SuspendResponse.SuspendResponseBuilder<String>().broadcaster(broadcaster).resumeOnBroadcast(false).outputComments(true).build();
}
 

Example 16

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

Source file: TestArgumentExceptionMapping.java

  29 
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 17

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

Source file: DiscoveryResource.java

  29 
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 18

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

Source file: AnalysisDatasourceService.java

  29 
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 19

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

Source file: DashboardRest.java

  29 
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();
}