Example #1
0
  @GET
  @Path("/{sitemapname: [a-zA-Z_0-9]*}/{pageid: [a-zA-Z_0-9]*}")
  @Produces(MediaType.APPLICATION_JSON)
  @ApiOperation(value = "Polls the data for a sitemap.", response = PageDTO.class)
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(
            code = 404,
            message =
                "Sitemap with requested name does not exist or page does not exist, or page refers to a non-linkable widget")
      })
  public Response getPageData(
      @Context HttpHeaders headers,
      @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language,
      @PathParam("sitemapname") @ApiParam(value = "sitemap name") String sitemapname,
      @PathParam("pageid") @ApiParam(value = "page id") String pageId) {
    final Locale locale = LocaleUtil.getLocale(language);
    logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath());

    if (headers.getRequestHeader("X-Atmosphere-Transport") != null) {
      // Make the REST-API pseudo-compatible with openHAB 1.x
      // The client asks Atmosphere for server push functionality,
      // so we do a simply listening for changes on the appropriate items
      blockUnlessChangeOccurs(sitemapname, pageId);
    }
    Object responseObject =
        getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build(), locale);
    return Response.ok(responseObject).build();
  }
  @Test
  public void testContextUriInfoUtil2nd2ndPassPathParamsQueryParams() throws URISyntaxException {

    String dasBaseUri = "http://localhost:port/";

    Map<String, String> pathParams = new HashMap<String, String>();
    pathParams.put("aa", "2.16.840.1.113883.4.349");
    pathParams.put("pid", "1012581676V377802");
    pathParams.put("profile", "benefits");
    pathParams.put("domain", "integratedCare");
    pathParams.put("speciality", "careCoordinatorProfiles");
    pathParams.put("homeCommunityId", "2.16.840.1.113883.4.349.3");
    pathParams.put("remoteRepositoryId", "3.33.333.3.333333.3.333");
    pathParams.put("documentUniqueId", "1001");
    pathParams.put("fileExtension", "xml");

    Map<String, String> queryParams = new HashMap<String, String>();
    queryParams.put("queryParamName1", "queryParamValue1");
    queryParams.put("queryParamName2", "queryParamValue2");
    queryParams.put("queryParamName3", "queryParamValue3");

    javax.ws.rs.core.UriInfo contextUriInfo =
        ContextUriInfoUtil.createUriInfo(dasBaseUri, pathParams, queryParams);

    System.out.println("baseUri: " + contextUriInfo.getBaseUri());
    System.out.println("path: " + contextUriInfo.getPath());
    System.out.println("absolutePath: " + contextUriInfo.getAbsolutePath());
    System.out.println("requestUri: " + contextUriInfo.getRequestUri());
    System.out.println("");
  }
  @Test
  public void testContextUriInfoUtil1stPassPathParamsQueryP() throws URISyntaxException {

    String dasBaseUri = "http://localhost:port/";

    Map<String, String> pathParams = new HashMap<String, String>();
    pathParams.put("aa", "2.16.840.1.113883.4.349");
    pathParams.put("pid", "1012581676V377802");
    pathParams.put("profile", "benefits");
    pathParams.put("domain", "integratedCare");
    pathParams.put("speciality", "careCoordinatorProfiles");

    String queryP = "?zzzzzz=3333333&xxxxx=111111&yyyy=22222";

    Map<String, String> queryParams = new HashMap<String, String>();
    queryParams.put("zzzzzz", "3333333");
    queryParams.put("xxxxx", "111111");
    queryParams.put("yyyy", "22222");

    javax.ws.rs.core.UriInfo contextUriInfo =
        ContextUriInfoUtil.createUriInfo(dasBaseUri, null, pathParams, queryP, queryParams);

    System.out.println("baseUri: " + contextUriInfo.getBaseUri());
    System.out.println("path: " + contextUriInfo.getPath());
    System.out.println("absolutePath: " + contextUriInfo.getAbsolutePath());
    System.out.println("requestUri: " + contextUriInfo.getRequestUri());
    System.out.println("");
  }
    @GET
    @Produces("text/plain")
    public String getInstance() {
      assertEquals("test/singleton-scope", ui.getPath());
      assertEquals("singleton", param);

      return someObject.toString();
    }
  @Path("auto-ack/{consumer-id}")
  @GET
  public Response getAutoAckSubscription(
      @PathParam("consumer-id") String consumerId, @Context UriInfo uriInfo) throws Exception {
    ActiveMQRestLogger.LOGGER.debug("Handling GET request for \"" + uriInfo.getPath() + "\"");

    return internalHeadAutoAckSubscription(uriInfo, consumerId);
  }
  @Path("acknowledged/{consumer-id}")
  @HEAD
  public Response headAcknowledgedConsumer(
      @PathParam("consumer-id") String consumerId, @Context UriInfo uriInfo) throws Exception {
    ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\"");

    return internalHeadAcknowledgedConsumer(uriInfo, consumerId);
  }
  @Path("auto-ack/{subscription-id}")
  @DELETE
  public void deleteSubscription(
      @Context UriInfo uriInfo, @PathParam("subscription-id") String consumerId) {
    ActiveMQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\"");

    internalDeleteSubscription(consumerId);
  }
 @GET
 @Path("list")
 @Produces(MediaType.TEXT_HTML)
 public Viewable getJSP() {
   List<String> messages = new ArrayList<>();
   messages.add("message1");
   messages.add("message2");
   messages.add("message3");
   System.out.println(context.getPath());
   return new Viewable("/list.jsp", messages);
 }
Example #9
0
 public SitemapBean getSitemapBean(String sitemapname, URI uri) {
   Sitemap sitemap = getSitemap(sitemapname);
   if (sitemap != null) {
     return createSitemapBean(sitemapname, sitemap, uri);
   } else {
     logger.info(
         "Received HTTP GET request at '{}' for the unknown sitemap '{}'.",
         uriInfo.getPath(),
         sitemapname);
     throw new WebApplicationException(404);
   }
 }
Example #10
0
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 @ApiOperation(
     value = "Get all available sitemaps.",
     response = SitemapDTO.class,
     responseContainer = "Collection")
 @ApiResponses(value = {@ApiResponse(code = 200, message = "OK")})
 public Response getSitemaps() {
   logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath());
   Object responseObject = getSitemapBeans(uriInfo.getAbsolutePathBuilder().build());
   return Response.ok(responseObject).build();
 }
  /**
   * @param uriInfo
   * @param links
   * @return
   */
  private String getAbsoluteId(UriInfo uriInfo, Collection<Link> links) {
    String absoluteId = "";

    for (Link link : links) {
      if ("self".equals(link.getRel())) {
        absoluteId = link.getHref();
        break;
      }
    }

    if (absoluteId.isEmpty()) {
      absoluteId = uriInfo.getBaseUri() + uriInfo.getPath();
    }

    return absoluteId;
  }
Example #12
0
 @GET
 @Path("/{sitemapname: [a-zA-Z_0-9]*}")
 @Produces(MediaType.APPLICATION_JSON)
 @ApiOperation(value = "Get sitemap by name.", response = SitemapDTO.class)
 @ApiResponses(value = {@ApiResponse(code = 200, message = "OK")})
 public Response getSitemapData(
     @Context HttpHeaders headers,
     @PathParam("sitemapname") @ApiParam(value = "sitemap name") String sitemapname,
     @QueryParam("type") String type,
     @QueryParam("jsoncallback") @DefaultValue("callback") String callback) {
   logger.debug(
       "Received HTTP GET request at '{}' for media type '{}'.",
       new Object[] {uriInfo.getPath(), type});
   Object responseObject = getSitemapBean(sitemapname, uriInfo.getBaseUriBuilder().build());
   return Response.ok(responseObject).build();
 }
  protected Templates createTemplates(
      Templates templates, Map<String, Object> configuredParams, Map<String, String> outProps) {
    if (templates == null) {
      if (supportJaxbOnly) {
        return null;
      } else {
        LOG.severe("No template is available");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
      }
    }

    TemplatesImpl templ = new TemplatesImpl(templates, uriResolver);
    MessageContext mc = getContext();
    if (mc != null) {
      UriInfo ui = mc.getUriInfo();
      MultivaluedMap<String, String> params = ui.getPathParameters();
      for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        String value = entry.getValue().get(0);
        int ind = value.indexOf(";");
        if (ind > 0) {
          value = value.substring(0, ind);
        }
        templ.setTransformerParameter(entry.getKey(), value);
      }

      List<PathSegment> segments = ui.getPathSegments();
      if (segments.size() > 0) {
        setTransformParameters(templ, segments.get(segments.size() - 1).getMatrixParameters());
      }
      setTransformParameters(templ, ui.getQueryParameters());
      templ.setTransformerParameter(ABSOLUTE_PATH_PARAMETER, ui.getAbsolutePath().toString());
      templ.setTransformerParameter(RELATIVE_PATH_PARAMETER, ui.getPath());
      templ.setTransformerParameter(BASE_PATH_PARAMETER, ui.getBaseUri().toString());
      if (configuredParams != null) {
        for (Map.Entry<String, Object> entry : configuredParams.entrySet()) {
          templ.setTransformerParameter(entry.getKey(), entry.getValue());
        }
      }
    }
    if (outProps != null) {
      templ.setOutProperties(outProps);
    }

    return templ;
  }
Example #14
0
  @GET
  @Path("{domain: .+}")
  @Produces({MediaType.APPLICATION_JSON})
  public Response getConfig(@Context HttpHeaders headers, @PathParam("domain") String domain) {
    logger.trace("Received HTTP GET request at '{}'.", uriInfo.getPath());

    OpenHABConfigurationService cfg = getConfigurationServices().get("ZWave");

    if (cfg == null) {
      return Response.notAcceptable(null).build();
    }

    ConfigServiceListBean cfgList = new ConfigServiceListBean();
    cfgList.records = cfg.getConfiguration(domain);

    Object responseObject = cfgList;
    return Response.ok(responseObject).build();
  }
  @GET
  @Produces({MediaType.WILDCARD})
  public Response getItems(
      @Context HttpHeaders headers,
      @QueryParam("type") String type,
      @QueryParam("jsoncallback") @DefaultValue("callback") String callback) {
    logger.debug("Received HTTP GET request at '{}' for media type '{}'.", uriInfo.getPath(), type);

    String responseType =
        MediaTypeHelper.getResponseMediaType(headers.getAcceptableMediaTypes(), type);
    if (responseType != null) {
      Object responseObject =
          responseType.equals(MediaTypeHelper.APPLICATION_X_JAVASCRIPT)
              ? new JSONWithPadding(new ItemConfigListBean(getItemConfigBeanList()), callback)
              : new ItemConfigListBean(getItemConfigBeanList());
      return Response.ok(responseObject, responseType).build();
    } else {
      return Response.notAcceptable(null).build();
    }
  }
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public Map<String, Object> get() {
   Map<String, Object> m = new HashMap<>();
   m.put("message", "Hello " + greeting + "!!!");
   List<Item> items = new ArrayList<>(2);
   items.add(new Item("who I love", "Sun Cai"));
   items.add(new Item("Test title", "happy everyday"));
   m.put("content", items);
   m.put("boolean", Boolean.TRUE);
   m.put("integer", 123);
   m.put("double", 123.4);
   Map<String, Object> m2 = new HashMap<>();
   m2.put("Path", uriInfo.getPath());
   m2.put("Absolute Path", uriInfo.getAbsolutePath());
   m2.put("Base Uri", uriInfo.getBaseUri());
   m2.put("Matched Uris", String.join(",", uriInfo.getMatchedURIs()));
   m2.put("Request Uri", uriInfo.getRequestUri());
   m.put("Additional Info", m2);
   return m;
 }
Example #17
0
 @GET
 @Path("/{sitemapname: [a-zA-Z_0-9]*}/{pageid: [a-zA-Z_0-9]*}")
 @Produces({MediaType.WILDCARD})
 public SuspendResponse<Response> getPageData(
     @Context HttpHeaders headers,
     @PathParam("sitemapname") String sitemapname,
     @PathParam("pageid") String pageId,
     @QueryParam("type") String type,
     @QueryParam("jsoncallback") @DefaultValue("callback") String callback,
     @HeaderParam(HeaderConfig.X_ATMOSPHERE_TRANSPORT) String atmosphereTransport,
     @Context AtmosphereResource resource) {
   logger.debug(
       "Received HTTP GET request at '{}' for media type '{}'.",
       new String[] {uriInfo.getPath(), type});
   if (atmosphereTransport == null || atmosphereTransport.isEmpty()) {
     String responseType =
         MediaTypeHelper.getResponseMediaType(headers.getAcceptableMediaTypes(), type);
     if (responseType != null) {
       Object responseObject =
           responseType.equals(MediaTypeHelper.APPLICATION_X_JAVASCRIPT)
               ? new JSONWithPadding(
                   getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build()), callback)
               : getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build());
       throw new WebApplicationException(Response.ok(responseObject, responseType).build());
     } else {
       throw new WebApplicationException(Response.notAcceptable(null).build());
     }
   }
   GeneralBroadcaster sitemapBroadcaster =
       (GeneralBroadcaster)
           BroadcasterFactory.getDefault()
               .lookup(GeneralBroadcaster.class, resource.getRequest().getPathInfo(), true);
   sitemapBroadcaster.addStateChangeListener(new SitemapStateChangeListener());
   return new SuspendResponse.SuspendResponseBuilder<Response>()
       .scope(SCOPE.REQUEST)
       .resumeOnBroadcast(!ResponseTypeHelper.isStreamingTransport(resource.getRequest()))
       .broadcaster(sitemapBroadcaster)
       .outputComments(true)
       .build();
 }
  @PUT
  @Path("/{itemname: [a-zA-Z_0-9]*}")
  @Produces({MediaType.WILDCARD})
  public Response putItem(
      @Context HttpHeaders headers,
      @QueryParam("type") String type,
      @PathParam("itemname") String itemname,
      @QueryParam("jsoncallback") @DefaultValue("callback") String callback,
      ItemConfigBean item) {
    logger.debug("Received HTTP PUT request at '{}' for media type '{}'.", uriInfo.getPath(), type);

    String responseType =
        MediaTypeHelper.getResponseMediaType(headers.getAcceptableMediaTypes(), type);
    if (responseType != null) {
      Object responseObject =
          responseType.equals(MediaTypeHelper.APPLICATION_X_JAVASCRIPT)
              ? new JSONWithPadding(updateItemConfigBean(itemname, item, false), callback)
              : updateItemConfigBean(itemname, item, false);
      return Response.ok(responseObject, responseType).build();
    } else {
      return Response.notAcceptable(null).build();
    }
  }
Example #19
0
 @GET
 @Path("/{sitemapname: [a-zA-Z_0-9]*}")
 @Produces({MediaType.WILDCARD})
 public Response getSitemapData(
     @Context HttpHeaders headers,
     @PathParam("sitemapname") String sitemapname,
     @QueryParam("type") String type,
     @QueryParam("jsoncallback") @DefaultValue("callback") String callback) {
   logger.debug(
       "Received HTTP GET request at '{}' for media type '{}'.",
       new String[] {uriInfo.getPath(), type});
   String responseType =
       MediaTypeHelper.getResponseMediaType(headers.getAcceptableMediaTypes(), type);
   if (responseType != null) {
     Object responseObject =
         responseType.equals(MediaTypeHelper.APPLICATION_X_JAVASCRIPT)
             ? new JSONWithPadding(
                 getSitemapBean(sitemapname, uriInfo.getBaseUriBuilder().build()), callback)
             : getSitemapBean(sitemapname, uriInfo.getBaseUriBuilder().build());
     return Response.ok(responseObject, responseType).build();
   } else {
     return Response.notAcceptable(null).build();
   }
 }
  @Test
  public void testContextUriInfoUtil1stPassPathparamsPathPOnly() throws URISyntaxException {

    String dasBaseUri = "http://localhost:port/";

    String pathP =
        "/2.16.840.1.113883.4.349/1012581676V377802/benefits/integratedCare/careCoordinatorProfiles/";

    Map<String, String> pathParams = new HashMap<String, String>();
    pathParams.put("aa", "2.16.840.1.113883.4.349");
    pathParams.put("pid", "1012581676V377802");
    pathParams.put("profile", "benefits");
    pathParams.put("domain", "integratedCare");
    pathParams.put("speciality", "careCoordinatorProfiles");

    javax.ws.rs.core.UriInfo contextUriInfo =
        ContextUriInfoUtil.createUriInfo(dasBaseUri, pathP, pathParams);

    System.out.println("baseUri: " + contextUriInfo.getBaseUri());
    System.out.println("path: " + contextUriInfo.getPath());
    System.out.println("absolutePath: " + contextUriInfo.getAbsolutePath());
    System.out.println("requestUri: " + contextUriInfo.getRequestUri());
    System.out.println("");
  }
Example #21
0
  @Override
  public final ResourceDocument generateResourceDocument(
      UriInfo uriInfo, Class<?> classOfResource) {
    final ResourceDocument document = new ResourceDocument();

    // Read the path.
    final Path path = this.findAnnotationInClass(Path.class, classOfResource);
    if (null == path)
      throw new IllegalStateException(
          "Couldn't find any class/superclass/interface annotated with @Path for "
              + classOfResource);
    document.setPath(uriInfo.getPath() + path.value());

    this.doWithResourceDocument(document, classOfResource);

    // Process its methods
    for (Method method : classOfResource.getDeclaredMethods()) {
      // Skip methods that are not annotated with @HttpGet
      if (!isHttpMethod(method)) {
        LOG.debug("Skipping method {}, it is not annotated with @HttpMethod", method.getName());
        continue;
      }

      // IllegalStateException is thrown if the method iterated is not
      // annotated with any of the @HttpMethod annotations. This can happen
      // for utility/helper methods found within classOfResource.
      try {
        document.addMethodDocument(this.generateMethodDocument(uriInfo, method));
      } catch (IllegalStateException e) {
        // Ignoring specific methods, as they aren't annotated with @HttpMethod.
        LOG.debug("Skipping method {}, it isn't annotated with any @HttpMethod", method.getName());
      }
    }

    return document;
  }
  @Override
  public ContainerRequest filter(ContainerRequest request) {
    // validate session still active
    AuthUtils.validateSession(this.request, uriInfo, response);
    boolean authenticated = authorizationService.isAuthenticated();
    boolean anonAccessEnabled = authorizationService.isAnonAccessEnabled();
    if (!authenticated) {
      if (anonAccessEnabled || uriInfo.getPath().indexOf("auth") != -1) {
        // If anon access is allowed and we didn't bother authenticating try to perform the action
        // as a user
        request.setSecurityContext(
            new RoleAuthenticator(UserInfo.ANONYMOUS, AuthorizationService.ROLE_USER));
      } else {
        throw new AuthorizationRestException();
      }
    } else {
      // Block all the REST calls that pass trough 'mc' entry point and are not authenticated by the
      // MS token authentication,
      // except the FIRST and only the FIRST call to the setupMC that can be authenticated by the
      // basic authentication,
      if (isMissionControlAccesPoint(request)) {
        boolean firstCallToSetupMC = isFirstCallToSetupMC(request);
        boolean tokenAuthentication = isTokenAuthentication(request);
        if (!firstCallToSetupMC && !tokenAuthentication) {
          // Block all the REST calls that pass trough 'mc' entry point and are not authenticated by
          // the MS token authentication,
          throw new AuthorizationRestException(
              "The access trough the 'mc' entry point is allowed only with token authentication");
        } else if ((firstCallToSetupMC && tokenAuthentication)) {
          // Block the setupMC REST calls that pass trough 'mc' entry point and are authenticated by
          // basic authentication except the first time.
          throw new AuthorizationRestException(
              "To initialize mission control chanel for the first time use user name and password ");
        } else {
          String username = authorizationService.currentUsername();
          request.setSecurityContext(
              new RoleAuthenticator(username, AuthorizationService.ROLE_ADMIN));
          return request;
        }
      }

      // Set the authenticated user and role
      String username = authorizationService.currentUsername();
      boolean admin = authorizationService.isAdmin();

      boolean ha =
          SecurityContextHolder.getContext().getAuthentication()
              instanceof HaSystemAuthenticationToken;
      if (ha) {
        request.setSecurityContext(new RoleAuthenticator(username, HaRestConstants.ROLE_HA));
        return request;
      }

      if (admin) {
        request.setSecurityContext(
            new RoleAuthenticator(username, AuthorizationService.ROLE_ADMIN));
      } else {
        request.setSecurityContext(new RoleAuthenticator(username, AuthorizationService.ROLE_USER));
      }
    }
    return request;
  }
 /** @return {@link UriInfo#getPath()} */
 @GET
 @Path("example")
 @Produces("text/plain")
 public String getPath(@Context UriInfo uriInfo) {
   return uriInfo.getPath();
 }
  @GET
  @Produces({MediaType.APPLICATION_JSON})
  public Response getChartSeries(
      @Context HttpHeaders headers,
      @QueryParam("rrd") String itemName,
      @QueryParam("ds") String consFunction,
      @QueryParam("start") String start,
      @QueryParam("end") String end,
      @QueryParam("res") long resolution) {
    if (logger.isDebugEnabled()) {
      logger.debug("Received GET request at '{}' for rrd '{}'.", uriInfo.getPath(), itemName);
    }
    String responseType = MediaType.APPLICATION_JSON;

    // RRD specific: no equivalent in PersistenceService known
    ConsolFun consilidationFunction = ConsolFun.valueOf(consFunction);

    // read the start/end time as they are provided in the RRD-way, we use
    // the RRD4j to read them
    long[] times = Util.getTimestamps(start, end);
    Date startTime = new Date();
    startTime.setTime(times[0] * 1000L);
    Date endTime = new Date();
    endTime.setTime(times[1] * 1000L);

    if (itemName.endsWith(".rrd")) {
      itemName = itemName.substring(0, itemName.length() - 4);
    }
    String[] parts = itemName.split(":");
    String service = "rrd4j";

    if (parts.length == 2) {
      itemName = parts[1];
      service = parts[0];
    }

    Item item;
    try {
      item = itemRegistry.getItem(itemName);
      logger.debug("item '{}' found ", item);

      // Prefer RRD-Service
      QueryablePersistenceService persistenceService = getPersistenceServices().get(service);
      // Fallback to first persistenceService from list
      if (persistenceService == null) {
        Iterator<Entry<String, QueryablePersistenceService>> pit =
            getPersistenceServices().entrySet().iterator();
        if (pit.hasNext()) {
          persistenceService = pit.next().getValue();
        } else {
          throw new IllegalArgumentException("No Persistence service found.");
        }
      }
      Object data = null;
      if (persistenceService.getId().equals("rrd4j")) {
        data =
            getRrdSeries(
                persistenceService, item, consilidationFunction, startTime, endTime, resolution);
      } else {
        data = getPersistenceSeries(persistenceService, item, startTime, endTime, resolution);
      }
      return Response.ok(data, responseType).build();
    } catch (ItemNotFoundException e1) {
      logger.error("Item '{}' not found error while requesting series data.", itemName);
    }
    return Response.serverError().build();
  }
 private String getPath(UriInfo uriInfo) {
   return combine(uriInfo.getBaseUri().getPath(), uriInfo.getPath());
 }
  @POST
  public Response createSubscription(
      @FormParam("durable") @DefaultValue("false") boolean durable,
      @FormParam("autoAck") @DefaultValue("true") boolean autoAck,
      @FormParam("name") String subscriptionName,
      @FormParam("selector") String selector,
      @FormParam("delete-when-idle") Boolean destroyWhenIdle,
      @FormParam("idle-timeout") Long timeout,
      @Context UriInfo uriInfo) {
    ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\"");

    if (timeout == null) timeout = Long.valueOf(consumerTimeoutSeconds * 1000);
    boolean deleteWhenIdle = !durable; // default is true if non-durable
    if (destroyWhenIdle != null) deleteWhenIdle = destroyWhenIdle.booleanValue();

    if (subscriptionName != null) {
      // see if this is a reconnect
      QueueConsumer consumer = queueConsumers.get(subscriptionName);
      if (consumer != null) {
        boolean acked = consumer instanceof AcknowledgedSubscriptionResource;
        acked = !acked;
        if (acked != autoAck) {
          throw new WebApplicationException(
              Response.status(412)
                  .entity("Consumer already exists and ack-modes don't match.")
                  .type("text/plain")
                  .build());
        }
        Subscription sub = (Subscription) consumer;
        if (sub.isDurable() != durable) {
          throw new WebApplicationException(
              Response.status(412)
                  .entity("Consumer already exists and durability doesn't match.")
                  .type("text/plain")
                  .build());
        }
        Response.ResponseBuilder builder = Response.noContent();
        String pathToPullSubscriptions = uriInfo.getMatchedURIs().get(0);
        if (autoAck) {
          headAutoAckSubscriptionResponse(uriInfo, consumer, builder, pathToPullSubscriptions);
          consumer.setSessionLink(
              builder, uriInfo, pathToPullSubscriptions + "/auto-ack/" + consumer.getId());
        } else {
          headAcknowledgedConsumerResponse(uriInfo, (AcknowledgedQueueConsumer) consumer, builder);
          consumer.setSessionLink(
              builder, uriInfo, pathToPullSubscriptions + "/acknowledged/" + consumer.getId());
        }
        return builder.build();
      }
    } else {
      subscriptionName = generateSubscriptionName();
    }
    ClientSession session = null;
    try {
      // if this is not a reconnect, create the subscription queue
      if (!subscriptionExists(subscriptionName)) {
        session = sessionFactory.createSession();

        if (durable) {
          session.createQueue(destination, subscriptionName, true);
        } else {
          session.createTemporaryQueue(destination, subscriptionName);
        }
      }
      QueueConsumer consumer =
          createConsumer(durable, autoAck, subscriptionName, selector, timeout, deleteWhenIdle);
      queueConsumers.put(consumer.getId(), consumer);
      serviceManager.getTimeoutTask().add(this, consumer.getId());

      UriBuilder location = uriInfo.getAbsolutePathBuilder();
      if (autoAck) location.path("auto-ack");
      else location.path("acknowledged");
      location.path(consumer.getId());
      Response.ResponseBuilder builder = Response.created(location.build());
      if (autoAck) {
        QueueConsumer.setConsumeNextLink(
            serviceManager.getLinkStrategy(),
            builder,
            uriInfo,
            uriInfo.getMatchedURIs().get(0) + "/auto-ack/" + consumer.getId(),
            "-1");
      } else {
        AcknowledgedQueueConsumer.setAcknowledgeNextLink(
            serviceManager.getLinkStrategy(),
            builder,
            uriInfo,
            uriInfo.getMatchedURIs().get(0) + "/acknowledged/" + consumer.getId(),
            "-1");
      }
      return builder.build();

    } catch (ActiveMQException e) {
      throw new RuntimeException(e);
    } finally {
      if (session != null) {
        try {
          session.close();
        } catch (ActiveMQException e) {
        }
      }
    }
  }
  protected String getFormattedException(String message) {

    return String.format(formatMessage, uriInfo.getPath(), message);
  }
Example #28
0
 public static String getAbsolutePath(UriInfo uriInfo) {
   return uriInfo.getBaseUri() + uriInfo.getPath();
 }
  /* This function produces hypermedia links to be sent to the client so as it will be able to forward the application state in a valid way.*/
  public JavapurchaseModelManager createHypermedia(JavaaccountModel oJavaaccountModel) {
    JavapurchaseModelManager oJavapurchaseModelManager = new JavapurchaseModelManager();

    /* Create hypermedia links towards this specific purchase resource. These must be GET and POST as it is prescribed in the meta-models.*/
    oJavapurchaseModelManager
        .getlinklist()
        .add(
            new HypermediaLink(
                String.format("%s%s", oApplicationUri.getBaseUri(), oApplicationUri.getPath()),
                "Get all purchases of this account",
                "GET",
                "Sibling"));
    oJavapurchaseModelManager
        .getlinklist()
        .add(
            new HypermediaLink(
                String.format("%s%s", oApplicationUri.getBaseUri(), oApplicationUri.getPath()),
                "Create a new purchase",
                "POST",
                "Sibling"));

    /* Then calculate the relative path to any related resource of this one and add for each one a hypermedia link to the Linklist.*/
    String oRelativePath;
    oRelativePath = oApplicationUri.getPath();
    Iterator<JavapurchaseModel> setIterator =
        oJavaaccountModel.getSetOfJavapurchaseModel().iterator();
    while (setIterator.hasNext()) {
      JavapurchaseModel oNextJavapurchaseModel = new JavapurchaseModel();
      oNextJavapurchaseModel = setIterator.next();
      oJavapurchaseModelManager
          .getlinklist()
          .add(
              new HypermediaLink(
                  String.format(
                      "%s%s/%d",
                      oApplicationUri.getBaseUri(),
                      oRelativePath,
                      oNextJavapurchaseModel.getpurchaseId()),
                  String.format("%s", oNextJavapurchaseModel.getsku()),
                  "GET",
                  "Child",
                  oNextJavapurchaseModel.getpurchaseId()));
    }

    /* Finally calculate the relative path towards the resources of which this one is related and add one hypermedia link for each one of them in the Linklist.*/
    oRelativePath = oApplicationUri.getPath();
    int iLastSlashIndex =
        String.format("%s%s", oApplicationUri.getBaseUri(), oRelativePath).lastIndexOf("/");
    oJavapurchaseModelManager
        .getlinklist()
        .add(
            new HypermediaLink(
                String.format("%s%s", oApplicationUri.getBaseUri(), oRelativePath)
                    .substring(0, iLastSlashIndex),
                "Delete the parent JavaaccountModel",
                "DELETE",
                "Parent"));
    oJavapurchaseModelManager
        .getlinklist()
        .add(
            new HypermediaLink(
                String.format("%s%s", oApplicationUri.getBaseUri(), oRelativePath)
                    .substring(0, iLastSlashIndex),
                "Get the parent JavaaccountModel",
                "GET",
                "Parent"));
    oJavapurchaseModelManager
        .getlinklist()
        .add(
            new HypermediaLink(
                String.format("%s%s", oApplicationUri.getBaseUri(), oRelativePath)
                    .substring(0, iLastSlashIndex),
                "Update the JavaaccountModel",
                "PUT",
                "Parent"));
    return oJavapurchaseModelManager;
  }
Example #30
-1
  private StringBuilder aggregatePaths(UriInfo uriInfo, Collection<String> pathsAsString) {
    StringBuilder pathBuilder = new StringBuilder();
    pathBuilder.append(uriInfo.getPath());
    boolean segmentEndedInSlash = uriInfo.getPath().endsWith("/");

    for (String onePathSegment : pathsAsString) {
      // Check if the path segment requires an additional '/'.
      if (!segmentEndedInSlash) pathBuilder.append('/');
      pathBuilder.append(onePathSegment);
      segmentEndedInSlash = onePathSegment.endsWith("/");
    }
    return pathBuilder;
  }