@GET
 @Path("encode/{string}")
 @Produces("text/plain")
 public String getTemplParamEncoded(@Context UriInfo uriInfo) {
   try {
     uriInfo.getPathParameters(false).add("jkghjk", "khlokh");
     return "The Template Parameter MultivaluedMap must be unmodifiable.";
   } catch (UnsupportedOperationException e) {
     // ok
   }
   return uriInfo.getPathParameters(false).getFirst("string");
 }
예제 #2
0
 @SuppressWarnings({"unchecked"})
 private UriInfo mockEmptyUriInfo() {
   UriInfo uriInfo = mock(UriInfo.class);
   when(uriInfo.getPathParameters(true)).thenReturn(mock(MultivaluedMap.class));
   when(uriInfo.getQueryParameters(true)).thenReturn(mock(MultivaluedMap.class));
   return uriInfo;
 }
예제 #3
0
 @Override
 public void filter(ContainerRequestContext requestContext) throws IOException {
   UriInfo uriInfo = requestContext.getUriInfo();
   MultivaluedMap<String, String> params = uriInfo.getPathParameters();
   String formationId = params.getFirst("formationId");
   String year = params.getFirst("annee");
   String semester = params.getFirst("semestre");
   try {
     if (uePromoDao
             .queryBuilder()
             .where()
             .eq("formation_id", formationId)
             .and()
             .eq("year", year)
             .and()
             .eq("semester", semester)
             .countOf()
         == 0) {
       requestContext.abortWith(Response.status(Response.Status.NOT_FOUND).build());
     }
   } catch (SQLException e) {
     e.printStackTrace();
     requestContext.abortWith(Response.serverError().build());
   }
 }
예제 #4
0
  /* Test the contract for multipart POST commands.
   * A POST command should should receive an InteractionContext that has the new resource set; enabling the
   * command to process the resource contained in the current part of the multipart request
   */
  @SuppressWarnings("unchecked")
  @Test
  public void testMultipartPostCommandReceivesResource() throws InteractionException {
    ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/test");
    initialState.addTransition(
        new Transition.Builder().method("POST").target(initialState).build());
    // create a mock command to test the context is initialised correctly
    InteractionCommand mockCommand = mock(InteractionCommand.class);
    when(mockCommand.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
    // RIM with command controller that issues commands that always return SUCCESS
    HTTPHypermediaRIM rim =
        new HTTPHypermediaRIM(
            mockCommandController(mockCommand),
            new ResourceStateMachine(initialState),
            createMockMetadata());

    UriInfo uriInfo = mock(UriInfo.class);
    when(uriInfo.getPathParameters(anyBoolean())).thenReturn(mock(MultivaluedMap.class));
    when(uriInfo.getQueryParameters(anyBoolean())).thenReturn(mock(MultivaluedMap.class));

    InMultiPart inMP = mock(InMultiPart.class);
    when(inMP.hasNext()).thenReturn(true, false);
    when(inMP.next()).thenReturn(mock(InPart.class));

    rim.post(mock(HttpHeaders.class), uriInfo, inMP);
    verify(mockCommand)
        .execute((InteractionContext) argThat(new CommandReceivesResourceArgumentMatcher()));
  }
    public Identifier getApplicationIdentifier() {
      Identifier application = null;

      MultivaluedMap<java.lang.String, java.lang.String> pathParams = uriInfo.getPathParameters();
      String applicationIdStr = pathParams.getFirst("applicationId");
      if (isNotEmpty(applicationIdStr)) {
        application = Identifier.from(applicationIdStr);
      } else {
        String applicationName = PathingUtils.assembleAppName(uriInfo.getPathParameters());
        if (logger.isDebugEnabled()) {
          logger.debug("Pulled applicationName {}", applicationName);
        }
        application = Identifier.fromName(applicationName);
      }

      return application;
    }
예제 #6
0
  @SuppressWarnings("unchecked")
  @Test
  public void testPutCommandWithIfMatchHeader() throws InteractionException {
    ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/test");
    initialState.addTransition(new Transition.Builder().method("PUT").target(initialState).build());

    // this test incorrectly supplies a resource as a result of the command.
    InteractionCommand mockCommand =
        new InteractionCommand() {
          public Result execute(InteractionContext ctx) {
            assertNotNull(ctx.getResource());
            assertNull(
                ctx.getResource().getEntityTag()); // Etag is a response header and should be null
            assertNotNull(ctx.getPreconditionIfMatch());
            assertEquals("ABCDEFG", ctx.getPreconditionIfMatch());
            return Result.SUCCESS;
          }
        };

    // RIM with command controller that issues commands that always return SUCCESS
    HTTPHypermediaRIM rim =
        new HTTPHypermediaRIM(
            mockCommandController(mockCommand),
            new ResourceStateMachine(initialState),
            createMockMetadata());

    UriInfo uriInfo = mock(UriInfo.class);
    when(uriInfo.getPathParameters(anyBoolean())).thenReturn(mock(MultivaluedMap.class));
    when(uriInfo.getQueryParameters(anyBoolean())).thenReturn(mock(MultivaluedMap.class));

    // EntityResource without Etag
    EntityResource<Object> er = new EntityResource<Object>("test resource");

    // Apply If-Match header
    HttpHeaders httpHeaders = mock(HttpHeaders.class);
    doAnswer(
            new Answer<List<String>>() {
              @SuppressWarnings("serial")
              @Override
              public List<String> answer(InvocationOnMock invocation) throws Throwable {
                String headerName = (String) invocation.getArguments()[0];
                if (headerName.equals(HttpHeaders.IF_MATCH)) {
                  return new ArrayList<String>() {
                    {
                      add("ABCDEFG");
                    }
                  };
                }
                return null;
              }
            })
        .when(httpHeaders)
        .getRequestHeader(any(String.class));

    // execute
    rim.put(httpHeaders, "id", uriInfo, er);
  }
예제 #7
0
  protected ResourceState getCurrentState(ResourceState serviceDocument, String resourcePath) {
    ResourceState state = null;
    if (resourcePath != null) {
      /*
       * add a leading '/' if it needs it (when defining resources we must use a
       * full path, but requests can be relative, i.e. without a '/'
       */
      if (!resourcePath.startsWith("/")) {
        resourcePath = "/" + resourcePath;
      }
      // add service document path to resource path
      String serviceDocumentPath = serviceDocument.getPath();
      if (serviceDocumentPath.endsWith("/")) {
        serviceDocumentPath =
            serviceDocumentPath.substring(0, serviceDocumentPath.lastIndexOf("/"));
      }
      resourcePath = serviceDocumentPath + resourcePath;
      // turn the uri back into a template uri
      MultivaluedMap<String, String> pathParameters = uriInfo.getPathParameters();
      if (pathParameters != null) {
        for (String key : pathParameters.keySet()) {
          List<String> values = pathParameters.get(key);
          for (String value : values) {
            resourcePath = resourcePath.replace(value, "{" + key + "}");
          }
        }
      }
      String httpMethod = requestContext.getMethod();
      Event event = new Event(httpMethod, httpMethod);
      state = resourceStateProvider.determineState(event, resourcePath);

      if (state == null) {
        logger.warn("No state found, dropping back to path matching " + resourcePath);
        // escape the braces in the regex
        resourcePath = Pattern.quote(resourcePath);
        Map<String, Set<String>> pathToResourceStates =
            resourceStateProvider.getResourceStatesByPath();
        for (String path : pathToResourceStates.keySet()) {
          for (String name : pathToResourceStates.get(path)) {
            ResourceState s = resourceStateProvider.getResourceState(name);
            String pattern = null;
            if (s instanceof CollectionResourceState) {
              pattern = resourcePath + "(|\\(\\))";
              Matcher matcher = Pattern.compile(pattern).matcher(path);
              if (matcher.matches()) {
                state = s;
              }
            }
          }
        }
      }
    }
    return state;
  }
  @Override
  public void filter(ContainerRequestContext requestContext) throws IOException {
    UriInfo uriInfo = requestContext.getUriInfo();
    MultivaluedMap<String, String> parameters = uriInfo.getPathParameters();
    List<String> usernames = parameters.get("username");

    if (usernames == null) return;

    if (usernames.contains("me")) {
      usernames.set(usernames.indexOf("me"), SessionCredentials.getCurrentUsername());
    }
  }
  /**
   * Places the org.osehra.integration.http.uri.UriInfo uriInfo instance's path parameter values
   * into the DAS dasextension Atom Feed at feed::dasextension::path::parameters. Notes: The feed
   * parameter must contain a constructed DAS dasextension Atom Feed. This method will remove any
   * existing feed::dasextension::path::parameters::entry elements before adding the new entries
   * from uriInfo.
   *
   * @param feed - mandatory - must contain a valid feed::dasextension Element
   * @param uriInfo - mandatory
   * @return
   */
  public Feed addPathParameters(Feed feed, final javax.ws.rs.core.UriInfo uriInfo) {
    if (NullChecker.isNotEmpty(feed)) {
      // get reference to the dasextension element in feed
      ExtensibleElement dasExt =
          feed.getExtension(new QName(this.dasextensionNamespace, "dasextension"));
      if (NullChecker.isNotEmpty(dasExt)) {
        // check for a UriInfo to input
        if (NullChecker.isNotEmpty(uriInfo) && !(uriInfo.getPathParameters().isEmpty())) {

          ExtensibleElement parameters = this.getPathParameters(dasExt);

          // discard any existing path dasextension::path::parameter::entry elements
          List<Element> pathParameterEntries = parameters.getElements();
          if (NullChecker.isNotEmpty(pathParameterEntries)) {
            for (Element curPathParameterEntry : pathParameterEntries) {
              curPathParameterEntry.discard();
            }
          }

          // add the dasextension::path::parameter::entry elements from uriInfo
          QName entryQname = new QName(this.dasextensionNamespace, "entry");
          QName keyQname = new QName(this.dasextensionNamespace, "key");
          QName valueQname = new QName(this.dasextensionNamespace, "value");

          MultivaluedMap<String, String> pathParametersExt = uriInfo.getPathParameters();
          Set<Map.Entry<String, List<String>>> pathParamsEntries = pathParametersExt.entrySet();
          for (Map.Entry<String, List<String>> pathParameterEntry : pathParamsEntries) {
            ExtensibleElement entry = parameters.addExtension(entryQname);
            ExtensibleElement key = entry.addExtension(keyQname);
            key.setText(pathParameterEntry.getKey());
            for (String entryValue : pathParameterEntry.getValue()) {
              ExtensibleElement value = entry.addExtension(valueQname);
              value.setText(entryValue);
            }
          }
        }
      }
    }
    return feed;
  }
예제 #10
0
 @GET
 @Path("/get1/{dd}")
 public void get(@Context UriInfo ui) {
   MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
   MultivaluedMap<String, String> pathParams = ui.getPathParameters();
   for (Map.Entry<String, List<String>> entry : pathParams.entrySet()) {
     System.out.println(
         "path: key-" + entry.getKey() + " value-" + Arrays.toString(entry.getValue().toArray()));
   }
   for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
     System.out.println(
         "query: key-" + entry.getKey() + " value-" + Arrays.toString(entry.getValue().toArray()));
   }
 }
    @Override
    public void filter(ContainerRequestContext request) throws IOException {

      logger.debug("Filtering {}", request.getUriInfo().getRequestUri().toString());

      if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
        logger.debug("Skipping option request");
      }

      MultivaluedMap<java.lang.String, java.lang.String> params = uriInfo.getPathParameters();
      logger.debug("Params: {}", params.keySet());

      authorize(request);
    }
    public Identifier getOrganizationIdentifier() {
      Identifier organization = null;

      MultivaluedMap<java.lang.String, java.lang.String> pathParams = uriInfo.getPathParameters();
      String organizationIdStr = pathParams.getFirst("organizationId");
      if (isNotEmpty(organizationIdStr)) {
        organization = Identifier.from(organizationIdStr);
      } else {
        String organizationName = pathParams.getFirst("organizationName");
        organization = Identifier.fromName(organizationName);
      }

      return organization;
    }
예제 #13
0
  public QueryExecutionFactory requireService() {
    MultivaluedMap<String, String> params = uriInfo.getPathParameters();
    String path = params.getFirst("path");

    SparqlService service = nameToService.get(path);
    // QueryExecutionFactory result = nameToService.get(path);
    // //sparqlServiceConfig.getServiceMap().get(path);
    if (service == null) {
      throw new RuntimeException("No service registered for " + path);
    }

    QueryExecutionFactory result = service.getSparqlService();

    return result;
  }
    public Identifier getUserIdentifier() {

      MultivaluedMap<java.lang.String, java.lang.String> pathParams = uriInfo.getPathParameters();
      String userIdStr = pathParams.getFirst("userId");
      if (isNotEmpty(userIdStr)) {
        return Identifier.from(userIdStr);
      }
      String username = pathParams.getFirst("username");
      if (username != null) {
        return Identifier.fromName(username);
      }
      String email = pathParams.getFirst("email");
      if (email != null) {
        return Identifier.fromEmail(email);
      }
      return null;
    }
예제 #15
0
  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;
  }
예제 #16
0
  /* We decode the query parameters to workaround an issue in Wink */
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Test
  public void testDecodeQueryParametersNullValue() {
    ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/test");
    // RIM with command controller that issues commands that always return FAILURE
    HTTPHypermediaRIM rim =
        new HTTPHypermediaRIM(
            mockCommandController(), new ResourceStateMachine(initialState), createMockMetadata());

    UriInfo uriInfo = mock(UriInfo.class);
    when(uriInfo.getPathParameters(true)).thenReturn(mock(MultivaluedMap.class));
    MultivaluedMap<String, String> queryMap = new MultivaluedMapImpl();
    queryMap.add(null, null);
    when(uriInfo.getQueryParameters(anyBoolean())).thenReturn(queryMap);

    // should get past here without a NullPointerException
    rim.get(mock(HttpHeaders.class), "id", uriInfo);
  }
예제 #17
0
  /* We decode the query parameters to workaround an issue in Wink */
  @SuppressWarnings({"unchecked"})
  @Test
  public void testDecodeQueryParameters() throws InteractionException {
    ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/test");
    // this test simply mocks a command to test the context query parameters is initialised properly
    InteractionCommand mockCommand = mock(InteractionCommand.class);
    when(mockCommand.execute(any(InteractionContext.class))).thenReturn(Result.FAILURE);
    // RIM with command controller that issues commands that always return SUCCESS
    HTTPHypermediaRIM rim =
        new HTTPHypermediaRIM(
            mockCommandController(mockCommand),
            new ResourceStateMachine(initialState),
            createMockMetadata());

    UriInfo uriInfo = mock(UriInfo.class);
    when(uriInfo.getPathParameters(true)).thenReturn(mock(MultivaluedMap.class));
    MultivaluedMap<String, String> queryMap = new MultivaluedMapImpl<String, String>();
    queryMap.add("$filter", "this+that");
    when(uriInfo.getQueryParameters(anyBoolean())).thenReturn(queryMap);

    rim.get(mock(HttpHeaders.class), "id", uriInfo);
    verify(mockCommand)
        .execute((InteractionContext) argThat(new InteractionContextArgumentMatcher()));
  }
예제 #18
0
  /**
   * Reads a Atom (OData) representation of {@link EntityResource} from the input stream.
   *
   * @precondition {@link InputStream} contains a valid Atom (OData) Entity enclosed in a
   *     <resource/> document
   * @postcondition {@link EntityResource} will be constructed and returned.
   * @invariant valid InputStream
   */
  @Override
  public EntityResource<OEntity> readFrom(
      Class<RESTResource> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, String> httpHeaders,
      InputStream entityStream)
      throws IOException, WebApplicationException {

    // check media type can be handled, isReadable must have been called
    assert (ResourceTypeHelper.isType(type, genericType, EntityResource.class));
    assert (mediaType.isCompatible(MediaType.APPLICATION_ATOM_XML_TYPE));

    try {
      OEntityKey entityKey = null;

      // work out the entity name using resource path from UriInfo
      String baseUri = AtomXMLProvider.getBaseUri(serviceDocument, uriInfo);
      String absoluteUri = AtomXMLProvider.getAbsolutePath(uriInfo);
      logger.info("Reading atom xml content for [" + absoluteUri + "]");
      String resourcePath = null;
      StringBuffer regex = new StringBuffer("(?<=" + baseUri + ")\\S+");
      Pattern p = Pattern.compile(regex.toString());
      Matcher m = p.matcher(absoluteUri);
      while (m.find()) {
        resourcePath = m.group();
      }
      if (resourcePath == null) throw new IllegalStateException("No resource found");
      ResourceState currentState = getCurrentState(serviceDocument, resourcePath);
      if (currentState == null) throw new IllegalStateException("No state found");
      String pathIdParameter = getPathIdParameter(currentState);
      MultivaluedMap<String, String> pathParameters = uriInfo.getPathParameters();
      if (pathParameters != null && pathParameters.getFirst(pathIdParameter) != null) {
        if (STRING_KEY_RESOURCE_PATTERN.matcher(resourcePath).find()) {
          entityKey = OEntityKey.create(pathParameters.getFirst(pathIdParameter));
        } else {
          entityKey = OEntityKey.parse(pathParameters.getFirst(pathIdParameter));
        }
      }

      if (currentState.getEntityName() == null) {
        throw new IllegalStateException("Entity name could not be determined");
      }

      /*
       *  get the entity set name using the metadata
       */
      String entitySetName = getEntitySet(currentState);

      // Check contents of the stream, if empty or null then return empty resource
      InputStream verifiedStream = verifyContentReceieved(entityStream);
      if (verifiedStream == null) {
        return new EntityResource<OEntity>();
      }

      // Lets parse the request content
      Reader reader = new InputStreamReader(verifiedStream);
      assert (entitySetName != null) : "Must have found a resource or thrown exception";
      Entry e =
          new AtomEntryFormatParserExt(metadataOData4j, entitySetName, entityKey, null)
              .parse(reader);

      return new EntityResource<OEntity>(e.getEntity());
    } catch (IllegalStateException e) {
      logger.warn("Malformed request from client", e);
      throw new WebApplicationException(Status.BAD_REQUEST);
    }
  }