Java Code Examples for javax.ws.rs.GET

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

  16 
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 /jaxrs/src/test/java/io/airlift/jaxrs/.

Source file: TestOverrideMethodFilterInHttpServer.java

  15 
vote

@Test public void testNonOverridableMethodsWithHeader() throws IOException, ExecutionException, InterruptedException {
  assertNonOverridableMethod(buildRequestWithHeader(GET,POST));
  assertNonOverridableMethod(buildRequestWithHeader(GET,DELETE));
  assertNonOverridableMethod(buildRequestWithHeader(GET,PUT));
  assertNonOverridableMethod(buildRequestWithHeader(DELETE,POST));
  assertNonOverridableMethod(buildRequestWithHeader(DELETE,GET));
  assertNonOverridableMethod(buildRequestWithHeader(DELETE,PUT));
  assertNonOverridableMethod(buildRequestWithHeader(PUT,POST));
  assertNonOverridableMethod(buildRequestWithHeader(PUT,DELETE));
  assertNonOverridableMethod(buildRequestWithHeader(PUT,GET));
}
 

Example 3

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

Source file: AuthzEndpoint.java

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

From project ANNIS, under directory /annis-service/src/main/java/annis/service/internal/.

Source file: AnnisWebService.java

  15 
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

  15 
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 /extensions/resteasy/src/test/java/org/jboss/arquillian/extension/rest/.

Source file: RestClientTestCase.java

  15 
vote

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

Example 7

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

Source file: FieldResource.java

  15 
vote

@GET @Path("{id}") public Object get(@PathParam("id") String id) throws Exception {
  PropField propField=propFieldManager.getPropField(id);
  if (propField == null) {
    throw new NotFoundException("Field with id [" + id + "] was not found");
  }
 else {
    return propField;
  }
}
 

Example 8

From project bam, under directory /release/jbossas/performance/app/src/main/java/org/overlord/bam/performance/jee/app/.

Source file: JEEApp.java

  15 
vote

/** 
 * This method returns the duration.
 * @return The duration
 */
@GET @Path("/duration") @Produces("application/json") public long getDuration(){
  if (LOG.isLoggable(Level.FINE)) {
    LOG.fine("Duration=" + (_lastTxn - _firstTxn));
  }
  return (_lastTxn - _firstTxn);
}
 

Example 9

From project blog_1, under directory /miniprojects/generic-pojo-mappers/src/main/java/net/jakubholy/blog/genericmappers/rest/.

Source file: GenericCollectionResource.java

  15 
vote

@GET @Path("/{collectionName}") public Response listStoredCollection(@PathParam("collectionName") String collectionName){
  try {
    Iterable<Map<String,Object>> collectionElements=storage.getDocumentsAsMap(collectionName);
    return Response.ok().entity(collectionElements).expires(getDefaultCachePeriod()).build();
  }
 catch (  Exception e) {
    log.log(Level.SEVERE,"Failed to list the collection " + collectionName,e);
    return Response.serverError().entity("Failure: " + e).build();
  }
}
 

Example 10

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

Source file: InfoFacade.java

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

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

Source file: ActivationKeyResource.java

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

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

Source file: StaticDataWebServiceImpl.java

  15 
vote

@Override @GET @Path("/errorkeys/") @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) public Set<String> getErrorKeys() throws Exception {
  Set<String> errorKeys=new HashSet<String>();
  for (  DomainException.DomainErrorMessage m : DomainException.DomainErrorMessage.values()) {
    errorKeys.add(m.getMessageKey());
  }
  return errorKeys;
}
 

Example 13

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

Source file: CustomerResource.java

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

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

Source file: MetricsController.java

  15 
vote

@GET @Path("series/{table}/{family}/{column}/rowkey/{rkey}") @Produces("application/json") public String getSeries(@Context HttpServletRequest request,@PathParam("table") String table,@PathParam("family") String family,@PathParam("column") String column,@PathParam("rkey") String rkey,@QueryParam("start") String start,@QueryParam("end") String end){
  SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
  String buffer="";
  Series series;
  long startTime=0;
  long endTime=0;
  TimeHandler time=new TimeHandler(request);
  try {
    if (start != null) {
      startTime=sdf.parse(start).getTime();
    }
 else {
      startTime=time.getStartTime();
    }
    if (end != null) {
      endTime=sdf.parse(end).getTime();
    }
 else {
      endTime=time.getEndTime();
    }
    if (rkey != null) {
      series=ChukwaHBaseStore.getSeries(table,rkey,family,column,startTime,endTime,true);
      buffer=series.toString();
    }
 else {
      throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("No row key defined.").build());
    }
  }
 catch (  ParseException e) {
    throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Start/End date parse error.  Format: yyyyMMddHHmmss.").build());
  }
  return buffer;
}
 

Example 15

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

Source file: AdminChainREST.java

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

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

Source file: InstanceResource.java

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

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

Source file: AsyncEventResource.java

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

From project components-ness-httpserver_1, under directory /src/main/java/com/nesscomputing/httpserver/selftest/.

Source file: SelftestResource.java

  15 
vote

/** 
 * On success, does nothing interesting. On failure, returns a 5xx response
 */
@GET public Response doSelftest() throws Exception {
  for (  Selftest test : tests) {
    test.doSelftest();
  }
  return Response.ok().build();
}
 

Example 19

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

Source file: RetryHandlersStub.java

  15 
vote

@GET @Path("retry") public Response retry(@QueryParam("value") String value){
  if (++count != failFor) {
    return Response.status(418).build();
  }
 else {
    return Response.ok(value).build();
  }
}
 

Example 20

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

Source file: DiscoveryResource.java

  15 
vote

@GET @Path("{name}/{id}") @Produces(MediaType.APPLICATION_JSON) public Response get(@PathParam("name") String name,@PathParam("id") String id){
  try {
    ServiceInstance<T> instance=context.getServiceDiscovery().queryForInstance(name,id);
    if (instance == null) {
      return Response.status(Response.Status.NOT_FOUND).build();
    }
    return Response.ok(instance).build();
  }
 catch (  Exception e) {
    log.error(String.format("Trying to get instance (%s) from service (%s)",id,name),e);
    return Response.serverError().build();
  }
}
 

Example 21

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

Source file: DatasourceResource.java

  15 
vote

@GET @Path("/analysis/ids") @Produces({APPLICATION_XML,APPLICATION_JSON}) public JaxbList<String> getAnalysisDatasourceIds(){
  List<String> analysisIds=new ArrayList<String>();
  for (  MondrianCatalog mondrianCatalog : mondrianCatalogService.listCatalogs(PentahoSessionHolder.getSession(),true)) {
    String domainId=mondrianCatalog.getName() + METADATA_EXT;
    Domain domain=metadataDomainRepository.getDomain(domainId);
    if (domain == null) {
      analysisIds.add(mondrianCatalog.getName());
    }
  }
  return new JaxbList<String>(analysisIds);
}
 

Example 22

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-api-frascati/src/main/java/org/easysoa/proxy/core/api/records/replay/.

Source file: ExchangeReplayServiceImpl.java

  15 
vote

/** 
 * Returns use informations
 */
@Override @GET @Path("/") public String returnInformations(){
  logger.debug("Returning help informations");
  StringBuffer help=new StringBuffer();
  help.append("<HTML><HEAD><TITLE>");
  help.append("Exchange replay service commands");
  help.append("</TITLE></HEAD><BODY>");
  help.append("<P><H1>Exchange replay service</H1></P>");
  help.append("<P><H2>How to use :</H2></P>");
  help.append("<P><UL>");
  help.append("<LI>To get the record store list (GET operation) : /getExchangeRecordStorelist</LI>");
  help.append("<LI>To get a record list (GET operation) : /getExchangeRecordList/{storeName}</LI>");
  help.append("<LI>To get a specific record (GET operation) : /getExchangeRecord/{storeName}/{exchangeID}</LI>");
  help.append("<LI>To start a replay session : /startReplaySession/{replaySessionName}</LI>");
  help.append("<LI>To replay an exchange record directly without any modifications (GET operation) : /replay/{exchangeRecordStoreName}/{exchangeRecordId}</LI>");
  help.append("<LI>To stop the current replaySession : /stopReplaySession</LI>");
  help.append("<LI>To generate a form template form with the default values : /templates/getTemplate/{storeName}/{templateName}");
  help.append("</UL></P></BODY></HTML>");
  return help.toString();
}
 

Example 23

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

Source file: ApiRestStatusServer.java

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

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

Source file: BlogCommentsResource.java

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

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

Source file: AnnotationBasedRoutingDefinition.java

  15 
vote

private void setupRoutes(){
  for (  Method m : underlyingObject.getClass().getMethods()) {
    if (m.isAnnotationPresent(GET.class)) {
      addRoute(m,InvocationVerb.GET);
    }
    if (m.isAnnotationPresent(PUT.class)) {
      addRoute(m,InvocationVerb.PUT);
    }
    if (m.isAnnotationPresent(POST.class)) {
      addRoute(m,InvocationVerb.POST);
    }
    if (m.isAnnotationPresent(DELETE.class)) {
      addRoute(m,InvocationVerb.DELETE);
    }
    if (m.isAnnotationPresent(HEAD.class)) {
      addRoute(m,InvocationVerb.HEAD);
    }
  }
}
 

Example 26

From project fed4j, under directory /src/main/java/com/jute/fed4j/example/resource/.

Source file: BackendResource.java

  15 
vote

@GET @Path("/yst") public String YST(){
  try {
    Thread.sleep(200);
  }
 catch (  InterruptedException e) {
    e.printStackTrace();
  }
  return "<xml><yst>result 1</yst></xml>\n";
}
 

Example 27

From project flume_1, under directory /flume-config-web/src/main/java/com/cloudera/flume/master/.

Source file: CommandManagerResource.java

  15 
vote

@GET @Produces("application/json") public JSONObject getLogs(){
  JSONObject o=new JSONObject();
  try {
    for (    Entry<Long,CommandStatus> e : commands.getStatuses().entrySet()) {
      o.put(e.getKey().toString(),toJSONObject(e.getValue()));
    }
  }
 catch (  JSONException e) {
    LOG.warn("Problem encoding JSON",e);
    return new JSONObject();
  }
  return o;
}
 

Example 28

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

Source file: RestController.java

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

From project gatein-sso, under directory /auth-callback/src/main/java/org/gatein/sso/authentication/callback/.

Source file: AuthenticationHandler.java

  15 
vote

@GET @Path("/auth/{1}/{2}") @Produces({MediaType.TEXT_PLAIN}) public String authenticate(@PathParam("1") String username,@PathParam("2") String password){
  try {
    log.debug("---------------------------------------");
    log.debug("Username: " + username);
    log.debug("Password: XXXXXXXXXXXXXXXX");
    Authenticator authenticator=(Authenticator)getContainer().getComponentInstanceOfType(Authenticator.class);
    Credential[] credentials=new Credential[]{new UsernameCredential(username),new PasswordCredential(password)};
    try {
      authenticator.validateUser(credentials);
      return "" + Boolean.TRUE;
    }
 catch (    LoginException le) {
      return "" + Boolean.FALSE;
    }
  }
 catch (  Exception e) {
    log.error(this,e);
    throw new RuntimeException(e);
  }
}
 

Example 30

From project gatein-toolbox, under directory /CoreOrganizationInitializer/src/main/java/org/exoplatform/core/component/organization/initializer/.

Source file: RestOrganizationInitializer.java

  15 
vote

@GET @Path("launchUserListeners/{userName}/{checkFolders}") public String launchUserListeners(@PathParam("userName") String userName,@PathParam("checkFolders") Boolean checkFolders){
  UserHandler userHandler=orgService_.getUserHandler();
  User user;
  try {
    user=userHandler.findUserByName(userName);
    boolean ok=initializerService.treatUser(user,checkFolders);
    String responseString=ok ? "User listeners executed successfuly." : "Error occured during execution of user listeners.";
    return responseString;
  }
 catch (  Exception e) {
    log.warn("Error with user " + userName,e);
    return "Error occured during execution of user listeners: " + e.getMessage();
  }
}
 

Example 31

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

Source file: ClustersResource.java

  15 
vote

@GET @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) public ClusterNameListResponse getClusters(){
  List<ClusterInfo> clusters=clusterService.getAllClusters();
  List<String> clusterList=new ArrayList<String>();
  for (  ClusterInfo cluster : clusters) {
    clusterList.add(cluster.getName());
  }
  return new ClusterNameListResponse(clusterList);
}
 

Example 32

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

Source file: Server.java

  15 
vote

/** 
 * List all the tables in an hcat database.
 */
@GET @Path("ddl/database/{db}/table") @Produces(MediaType.APPLICATION_JSON) public Response listTables(@PathParam("db") String db,@QueryParam("like") String tablePattern) throws HcatException, NotAuthorizedException, BusyException, BadParam, ExecuteException, IOException {
  verifyUser();
  verifyDdlParam(db,":db");
  HcatDelegator d=new HcatDelegator(appConf,execService);
  if (!TempletonUtils.isset(tablePattern))   tablePattern="*";
  return d.listTables(getUser(),db,tablePattern);
}