/**
   * Assigns representation into data set.
   *
   * <p>If specific version is assigned, and then other version of the same representation name
   * assigned again, the old version is overridden. You can also assign the representation without
   * version in this case the old version will also be overridden. Note that the version number will
   * be then set to null in Cassandra, but {@link #getDataSetRepresentations(java.lang.String,
   * java.lang.String)} method will return the last persistent version with {@link
   * Representation#version} filled.
   *
   * @param providerId provider identifier (required)
   * @param dataSetId data set identifier (required)
   * @param cloudId cloudId of the record (required)
   * @param representationName name of the representation (required)
   * @param versionId version of representation; if not provided, latest persistent version will be
   *     assigned to data set
   * @throws DataSetNotExistsException if data set does not exist
   * @throws RepresentationNotExistsException if no such representation exists
   * @throws MCSException on unexpected situations
   */
  public void assignRepresentationToDataSet(
      String providerId,
      String dataSetId,
      String cloudId,
      String representationName,
      String versionId)
      throws DataSetNotExistsException, RepresentationNotExistsException, MCSException {

    WebTarget target =
        client
            .target(this.baseUrl)
            .path(assignmentsPath)
            .resolveTemplate(ParamConstants.P_PROVIDER, providerId)
            .resolveTemplate(ParamConstants.P_DATASET, dataSetId);

    Form form = new Form();
    form.param(ParamConstants.F_CLOUDID, cloudId);
    form.param(ParamConstants.F_REPRESENTATIONNAME, representationName);
    form.param(ParamConstants.F_VER, versionId);

    Response response =
        target.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));

    if (response.getStatus() != Status.NO_CONTENT.getStatusCode()) {
      ErrorInfo errorInfo = response.readEntity(ErrorInfo.class);
      throw MCSExceptionProvider.generateException(errorInfo);
    }
  }
 @Override
 public Set<ParentNode> createNodes(String collection, List<Map<String, Object>> records)
     throws IOException {
   InputNodeList list = new InputNodeList();
   List<InputNode> inList = new ArrayList<InputNode>();
   for (Map<String, Object> map : records) {
     InputNode node = InputNodeCreator.createInputNodeFromMap(map);
     if (node != null) {
       inList.add(node);
     }
   }
   WebTarget target = client.target("/nodes/nodes/generate");
   Form form = new Form();
   list.setInputNodeList(inList);
   form.param("recordValues", objectMapper.writeValueAsString(list));
   Set<ParentNode> parentNodeSet =
       target
           .path("")
           .request()
           .post(Entity.form(form))
           .readEntity(ParentNodeList.class)
           .getParentNodeList();
   Set<String> ids = new HashSet<String>();
   for (ParentNode parentNode : parentNodeSet) {
     ids.add(parentNode.getId());
   }
   cacheDAO.addParentsToSet(collection, ids);
   return parentNodeSet;
 }
  /**
   * Updates an existing merge request. You can change branches, title, or even close the MR.
   *
   * <p>PUT /projects/:id/merge_request/:merge_request_id
   *
   * @param projectId
   * @param mergeRequestId
   * @param sourceBranch
   * @param targetBranch
   * @param title
   * @param description
   * @param assigneeId
   * @return the updated merge request
   * @throws GitLabApiException
   */
  public MergeRequest updateMergeRequest(
      Integer projectId,
      Integer mergeRequestId,
      String sourceBranch,
      String targetBranch,
      String title,
      String description,
      Integer assigneeId)
      throws GitLabApiException {

    if (projectId == null) {
      throw new RuntimeException("mergeRequestId cannot be null");
    }

    if (mergeRequestId == null) {
      throw new RuntimeException("projectId cannot be null");
    }

    Form formData = new Form();
    addFormParam(formData, "source_branch", sourceBranch, false);
    addFormParam(formData, "target_branch", targetBranch, false);
    addFormParam(formData, "title", title, false);
    addFormParam(formData, "description", description, false);
    addFormParam(formData, "assignee_id", assigneeId, false);

    Response response =
        put(
            Response.Status.OK,
            formData.asMap(),
            "projects",
            projectId,
            "merge_request",
            mergeRequestId);
    return (response.readEntity(MergeRequest.class));
  }
  /**
   * Creates a new data set.
   *
   * @param providerId provider identifier (required)
   * @param dataSetId data set identifier (required)
   * @param description data set description (not required)
   * @return URI to created data set
   * @throws DataSetAlreadyExistsException when data set with given id (for given provider) already
   *     exists
   * @throws ProviderNotExistsException when provider with given id does not exist
   * @throws MCSException on unexpected situations
   */
  public URI createDataSet(String providerId, String dataSetId, String description)
      throws ProviderNotExistsException, DataSetAlreadyExistsException, MCSException {

    WebTarget target =
        client
            .target(this.baseUrl)
            .path(dataSetsPath)
            .resolveTemplate(ParamConstants.P_PROVIDER, providerId);

    Form form = new Form();
    form.param(ParamConstants.F_DATASET, dataSetId);
    form.param(ParamConstants.F_DESCRIPTION, description);

    Response response =
        target.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));

    if (response.getStatus() == Status.CREATED.getStatusCode()) {
      return response.getLocation();
    }

    // TODO this does not function correctly,
    // details are filled with "MessageBodyReader not found for media type=text/html;
    // charset=utf-8, type=class eu.europeana.cloud.common.response.ErrorInfo,
    // genericType=class eu.europeana.cloud.common.response.ErrorInfo."
    // simple strings like 'adsfd' get entitised correctly
    ErrorInfo errorInfo = response.readEntity(ErrorInfo.class);
    throw MCSExceptionProvider.generateException(errorInfo);
  }
Example #5
0
  @Test
  public void testRepresentation() {
    Form form = new Form();

    form.param("name", "\u00A9 CONTENT \u00FF \u2200 \u22FF");
    form.param("name", "� � �");
    _test(form, FormResource.class, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
  }
 private Form getQueryOrFormParams(String[] paramNames, String[] paramValues) {
   Form form = new javax.ws.rs.core.Form();
   for (int i = 0; i < paramNames.length; i++) {
     if (paramValues[i] != null) {
       form = form.param(paramNames[i], paramValues[i]);
     }
   }
   return form;
 }
Example #7
0
  public static ClientAccessToken getAccessTokenWithAuthorizationCode(
      WebClient client, String code) {
    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "authorization_code");
    form.param("code", code);
    form.param("client_id", "consumer-id");
    Response response = client.post(form);

    return response.readEntity(ClientAccessToken.class);
  }
 public boolean login(String userid, String password) {
   String loginUri = getLink(root.getLinks(), "login").getUri().toString();
   WebTarget target = client.target(loginUri);
   Form form = new Form();
   form.param("login", "spongebob");
   form.param("password", "1234");
   String json =
       target
           .request()
           .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
   authToken = (new Gson()).fromJson(json, AuthToken.class);
   Log.d(TAG, json);
   return true;
 }
 @Override
 public ParentNode createNode(String collection, Map<String, Object> params) throws IOException {
   InputNode node = InputNodeCreator.createInputNodeFromMap(params);
   if (node != null) {
     WebTarget target = client.target("/nodes/node/generate");
     Form form = new Form();
     form.param("recordValues", objectMapper.writeValueAsString(node));
     ParentNode pNode =
         target.path("").request().post(Entity.form(form)).readEntity(ParentNode.class);
     cacheDAO.addParentToSet(collection, pNode.getId());
     return pNode;
   }
   return null;
 }
 /**
  * @param responseType Class representing the response
  * @param idRol query parameter
  * @param nombre query parameter
  * @return response object (instance of responseType class)
  */
 public <T> T editarRol(Class<T> responseType, String idRol, String nombre)
     throws ClientErrorException {
   String[] queryParamNames = new String[] {"idRol", "nombre"};
   String[] queryParamValues = new String[] {idRol, nombre};
   ;
   javax.ws.rs.core.Form form = getQueryOrFormParams(queryParamNames, queryParamValues);
   javax.ws.rs.core.MultivaluedMap<String, String> map = form.asMap();
   for (java.util.Map.Entry<String, java.util.List<String>> entry : map.entrySet()) {
     java.util.List<String> list = entry.getValue();
     String[] values = list.toArray(new String[list.size()]);
     webTarget = webTarget.queryParam(entry.getKey(), (Object[]) values);
   }
   return webTarget.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
 }
 @Test
 @InSequence(1)
 public void shouldCreateCompetition(@ArquillianResource URL base) throws Exception {
   URL url = new URL(base, "rest/competition");
   WebTarget target = ClientBuilder.newClient().target(url.toExternalForm());
   Form newCompetitionForm = new Form();
   newCompetitionForm.param("name", COMPETITION_NAME);
   newCompetitionForm.param("description", COMPETITION_DESCRIPTION);
   Response response =
       target
           .request(MediaType.APPLICATION_JSON_TYPE)
           .post(Entity.entity(newCompetitionForm, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
   assertEquals(201, response.getStatus());
   competitionId = getIdFromLocationHeader(response);
 }
  @Test
  public void loginTest_WrongPassword() {

    Form form = new Form();
    form.param("email", BBSADMIN_EMAIL);
    form.param("password", "wrong");

    Response response =
        mockClient
            .target(DemoClientConstants.BACKEND_BO_PORTAL_URL)
            .path(DemoClientConstants.BO_LOGIN_PATH)
            .request()
            .post(Entity.form(form));
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.readEntity(String.class).contains("Invalid Password"));
  }
Example #13
0
  private String isValidToken(String token, String useragent, String ip) {
    Form form = new Form();
    form.param("token", token);
    form.param("user_agent", useragent);
    form.param("ip", ip);

    Client client = ClientBuilder.newClient();
    String url = "http://localhost:8080/IdentityService/Auth";

    String valid =
        client
            .target(url)
            .request(MediaType.TEXT_PLAIN)
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED), String.class);
    return valid;
  }
  /**
   * Adds a comment to a merge request.
   *
   * <p>POST /projects/:id/merge_request/:merge_request_id/comments
   *
   * @param projectId
   * @param mergeRequestId
   * @param comments
   * @return the added merge request comment
   * @throws GitLabApiException
   */
  public MergeRequestComment addMergeRequestComment(
      Integer projectId, Integer mergeRequestId, String comments) throws GitLabApiException {

    Form formData = new Form();
    formData.param("note", comments);
    Response response =
        post(
            Response.Status.OK,
            formData,
            "projects",
            projectId,
            "merge_request",
            mergeRequestId,
            "comments");
    return (response.readEntity(MergeRequestComment.class));
  }
Example #15
0
 @Test
 public void testPost2() {
   final Form form = new Form();
   form.param(FormResource.PW, "北京");
   form.param(FormResource.NPW, "上海");
   form.param(FormResource.VNPW, "上海");
   final String result =
       target("form-resource")
           .request()
           .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
   FormTest.LOGGER.debug(result);
   Assert.assertEquals(
       "encoded should let it to disable decoding",
       "feuyeux:%E5%8C%97%E4%BA%AC:%E4%B8%8A%E6%B5%B7:上海",
       result);
 }
 @Override
 protected ClientInvocationBuilder apply(ClientInvocationBuilder target, Object object) {
   Form form = null;
   Object entity = target.getInvocation().getEntity();
   if (entity != null) {
     if (entity instanceof Form) {
       form = (Form) entity;
     } else {
       throw new RuntimeException("Cannot set a form parameter if entity body already set");
     }
   } else {
     form = new Form();
     target.getInvocation().setEntity(Entity.form(form));
   }
   String value = target.getInvocation().getClientConfiguration().toString(object);
   form.param(paramName, value);
   return target;
 }
Example #17
0
  // Test: Update User of id 1
  // Test: Check if result is success XML.
  private void testUpdateUser() {
    Form form = new Form();
    form.param("id", "1");
    form.param("name", "Mahesh");
    form.param("address", "Christchurch");
    form.param("contactNumber", "+9198855117733");

    String callResult =
        client
            .target(REST_SERVICE_URL)
            .request(MediaType.APPLICATION_XML)
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
    String result = PASS;
    if (!SUCCESS_RESULT.equals(callResult)) {
      result = FAIL;
    }

    System.out.println("Test case name: testUpdateUser, Result: " + result);
  }
  /**
   * Implementation of a CKAN Datahub Page Creation REST service client application. POST
   * /ckan-datahub/jobs/
   *
   * @param jobid the job identifier.
   * @since 2.0
   */
  public void newJob(final int jobid) {
    // Convert integer to string
    final String s_jobid = "" + jobid;
    final Client client = ClientBuilder.newClient();
    final WebTarget webTarget = client.target(ALIADA_CKANCREATION_URL);

    // Data to be sent via HTTP POST
    final Form form = new Form();
    form.param("jobid", s_jobid);

    // POST (Response in XML format)
    final String acceptType = MediaType.APPLICATION_XML; // If we want the response in XML format
    final Response postResponse =
        webTarget
            .path("/jobs")
            .request(acceptType)
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
    LOGGER.info("status =" + postResponse.getStatus());
    LOGGER.info("response data=" + postResponse.readEntity(String.class));
  }
  /**
   * Updates description of data set.
   *
   * @param providerId provider identifier (required)
   * @param dataSetId data set identifier (required)
   * @param description new description of data set (if <code>""</code> will be set to <code>""
   *     </code>, if <code>null</code> will be set to <code>null</code>)
   * @throws DataSetNotExistsException if data set does not exist
   * @throws MCSException on unexpected situations
   */
  public void updateDescriptionOfDataSet(String providerId, String dataSetId, String description)
      throws DataSetNotExistsException, MCSException {
    WebTarget target =
        client
            .target(this.baseUrl)
            .path(dataSetPath)
            .resolveTemplate(ParamConstants.P_PROVIDER, providerId)
            .resolveTemplate(ParamConstants.P_DATASET, dataSetId);

    Form form = new Form();
    form.param(ParamConstants.F_DESCRIPTION, description);

    Response response =
        target.request().put(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));

    if (response.getStatus() != Status.NO_CONTENT.getStatusCode()) {

      ErrorInfo errorInfo = response.readEntity(ErrorInfo.class);
      throw MCSExceptionProvider.generateException(errorInfo);
    }
  }
Example #20
0
  public static String getAuthorizationCode(WebClient client, String scope) {
    // Make initial authorization request
    client.type("application/json").accept("application/json");
    client.query("client_id", "consumer-id");
    client.query("redirect_uri", "http://www.blah.apache.org");
    client.query("response_type", "code");
    if (scope != null) {
      client.query("scope", scope);
    }
    client.path("authorize/");
    Response response = client.get();

    OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);

    // Now call "decision" to get the authorization code grant
    client.path("decision");
    client.type("application/x-www-form-urlencoded");

    Form form = new Form();
    form.param("session_authenticity_token", authzData.getAuthenticityToken());
    form.param("client_id", authzData.getClientId());
    form.param("redirect_uri", authzData.getRedirectUri());
    if (authzData.getProposedScope() != null) {
      form.param("scope", authzData.getProposedScope());
    }
    form.param("oauthDecision", "allow");

    response = client.post(form);
    String location = response.getHeaderString("Location");
    return getSubstring(location, "code");
  }
Example #21
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    String clientId = request.getParameter("txtClientId");
    String username = request.getParameter("txtUsername");
    String password = request.getParameter("txtPassword");

    Client client = ClientBuilder.newClient();

    WebTarget target = client.target(HOST_URL + request.getContextPath() + LOGIN_SERVICE_URL);
    Form form = new Form();
    form.param("username", username);
    form.param("password", password);

    Response serviceResponse =
        target
            .request()
            .header("client_id", clientId)
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));

    int statusCode = serviceResponse.getStatus();
    if (statusCode == Response.Status.OK.getStatusCode()) {
      JSONObject jsonOutput =
          (JSONObject) JSONSerializer.toJSON(serviceResponse.readEntity(String.class));
      // out.println("token received: " + jsonOutput.getString("auth_token"));
      RequestDispatcher rs = request.getRequestDispatcher("/secured/search.jsp");
      request.setAttribute("auth_token", jsonOutput.getString("auth_token"));
      request.setAttribute("client_id", clientId);
      rs.include(request, response);
    } else {
      out.println("Username or Password incorrect");
      // out.println(HOST_URL + request.getContextPath() + LOGIN_SERVICE_URL);
      RequestDispatcher rs = request.getRequestDispatcher("index.jsp");
      rs.include(request, response);
    }
  }
  public void testSavedPostRequest() throws Exception {
    // test login to customer-portal which does a bearer request to customer-db
    driver.navigate().to(APP_SERVER_BASE_URL + "/input-portal");
    System.err.println("*********** Current url: " + driver.getCurrentUrl());
    Assert.assertTrue(driver.getCurrentUrl().startsWith(APP_SERVER_BASE_URL + "/input-portal"));
    inputPage.execute("hello");

    assertAtLoginPagePostBinding();
    loginPage.login("*****@*****.**", "password");
    System.out.println("Current url: " + driver.getCurrentUrl());
    Assert.assertEquals(driver.getCurrentUrl(), APP_SERVER_BASE_URL + "/input-portal/secured/post");
    String pageSource = driver.getPageSource();
    System.out.println(pageSource);
    Assert.assertTrue(pageSource.contains("parameter=hello"));
    // test that user principal and KeycloakSecurityContext available
    driver.navigate().to(APP_SERVER_BASE_URL + "/input-portal/insecure");
    System.out.println("insecure: ");
    System.out.println(driver.getPageSource());
    Assert.assertTrue(driver.getPageSource().contains("Insecure Page"));
    if (System.getProperty("insecure.user.principal.unsupported") == null)
      Assert.assertTrue(driver.getPageSource().contains("UserPrincipal"));

    // test logout

    driver.navigate().to(APP_SERVER_BASE_URL + "/input-portal?GLO=true");

    // test unsecured POST KEYCLOAK-901

    Client client = ClientBuilder.newClient();
    Form form = new Form();
    form.param("parameter", "hello");
    String text =
        client
            .target(APP_SERVER_BASE_URL + "/input-portal/unsecured")
            .request()
            .post(Entity.form(form), String.class);
    Assert.assertTrue(text.contains("parameter=hello"));
    client.close();
  }
Example #23
0
  // Test: Add User of id 3
  // Test: Check if result is success XML.
  private void testAddUser() {
    Form form = new Form();
    form.param("id", "3");
    form.param("name", "Bomms");
    form.param("address", "jurasic park");
    form.param("contactNumber", "+5444432432");

    String callResult =
        client
            .target(REST_SERVICE_URL)
            .request(MediaType.APPLICATION_XML)
            .put(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);

    GenericType<List<User>> list = new GenericType<List<User>>() {};
    List<User> users = client.target(REST_SERVICE_URL).request(MediaType.APPLICATION_XML).get(list);

    String result = PASS;
    // Verify add is successful and getallusers is giving 3
    if (!SUCCESS_RESULT.equals(callResult) && users.size() != 3) {
      result = FAIL;
    }

    System.out.println("Test case name: testAddUser, Result: " + result);
  }
    @Override
    public Object provide() {
      ContainerRequest request = getContainerRequest();

      Form form = getCachedForm(request, decode);

      if (form == null) {
        Form otherForm = getCachedForm(request, !decode);
        if (otherForm != null) {
          form = switchUrlEncoding(request, otherForm);
          cacheForm(request, form);
        } else {
          form = getForm(request);
          cacheForm(request, form);
        }
      }

      try {
        return extractor.extract(form.asMap());
      } catch (ExtractorException e) {
        throw new ParamException.FormParamException(
            e.getCause(), extractor.getName(), extractor.getDefaultValueString());
      }
    }
    private Form switchUrlEncoding(final ContainerRequest request, final Form otherForm) {
      final Set<Map.Entry<String, List<String>>> entries = otherForm.asMap().entrySet();

      MultivaluedMap<String, String> formMap = new NullableMultivaluedHashMap<>();
      for (Map.Entry<String, List<String>> entry : entries) {
        final String charsetName =
            ReaderWriter.getCharset(
                    MediaType.valueOf(request.getHeaderString(HttpHeaders.CONTENT_TYPE)))
                .name();

        String key;
        try {
          key =
              decode
                  ? URLDecoder.decode(entry.getKey(), charsetName)
                  : URLEncoder.encode(entry.getKey(), charsetName);

          for (String value : entry.getValue()) {
            if (value != null) {
              formMap.add(
                  key,
                  decode
                      ? URLDecoder.decode(value, charsetName)
                      : URLEncoder.encode(value, charsetName));
            } else {
              formMap.add(key, null);
            }
          }

        } catch (UnsupportedEncodingException uee) {
          throw new ProcessingException(
              LocalizationMessages.ERROR_UNSUPPORTED_ENCODING(charsetName, extractor.getName()),
              uee);
        }
      }
      return new Form(formMap);
    }
  @Test
  public void testResteasy734() throws Exception {
    ResteasyWebTarget target = null;
    Response response = null;

    target = client.target("http://localhost:8081/encoded/pathparam/bee bop");
    response = target.request().get();
    String entity = response.readEntity(String.class);
    System.out.println("Received encoded path param: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee%20bop", entity);
    response.close();

    target = client.target("http://localhost:8081/decoded/pathparam/bee bop");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received decoded path param: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee bop", entity);
    response.close();

    target = client.target("http://localhost:8081/encoded/matrix;m=bee bop");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received encoded matrix param: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee%20bop", entity);
    response.close();

    target = client.target("http://localhost:8081/decoded/matrix;m=bee bop");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received decoded matrix param: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee bop", entity);
    response.close();

    target = client.target("http://localhost:8081/encoded/query?m=bee bop");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received encoded query param: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee%20bop", entity);
    response.close();

    target = client.target("http://localhost:8081/decoded/query?m=bee bop");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received decoded query param: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee bop", entity);
    response.close();

    target = client.target("http://localhost:8081/encoded/form");
    Form form = new Form();
    form.param("f", "bee bop");
    response = target.request().post(Entity.form(form));
    entity = response.readEntity(String.class);
    System.out.println("Received encoded form param: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee+bop", entity);
    response.close();

    target = client.target("http://localhost:8081/decoded/form");
    form = new Form();
    form.param("f", "bee bop");
    response = target.request().post(Entity.form(form));
    entity = response.readEntity(String.class);
    System.out.println("Received decoded form param: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee bop", entity);
    response.close();

    target = client.target("http://localhost:8081/encoded/segment/bee bop");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received encoded path param from segment: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee%20bop", entity);
    response.close();

    target = client.target("http://localhost:8081/decoded/segment/bee bop");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received decoded path param from segment: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee bop", entity);
    response.close();

    target = client.target("http://localhost:8081/encoded/segment/matrix/params;m=bee bop");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received encoded matrix param from segment: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee%20bop", entity);
    response.close();

    target = client.target("http://localhost:8081/decoded/segment/matrix/params;m=bee bop");
    response = target.request().get();
    entity = response.readEntity(String.class);
    System.out.println("Received decoded matrix param from segment: " + entity);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("bee bop", entity);
    response.close();
  }
Example #27
0
  @Override
  @SuppressWarnings("unchecked")
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // get the interface describing the resource
    Class<?> proxyIfc = proxy.getClass().getInterfaces()[0];

    // response type
    Class<?> responseType = method.getReturnType();

    // determine method name
    String httpMethod = getHttpMethodName(method);
    if (httpMethod == null) {
      for (Annotation ann : method.getAnnotations()) {
        httpMethod = getHttpMethodName(ann.annotationType());
        if (httpMethod != null) {
          break;
        }
      }
    }

    // create a new UriBuilder appending the @Path attached to the method
    WebTarget newTarget = addPathFromAnnotation(method, target);

    if (httpMethod == null) {
      if (newTarget == target) {
        // no path annotation on the method -> fail
        throw new UnsupportedOperationException("Not a resource method.");
      } else if (!responseType.isInterface()) {
        // the method is a subresource locator, but returns class,
        // not interface - can't help here
        throw new UnsupportedOperationException("Return type not an interface");
      }
    }

    // process method params (build maps of (Path|Form|Cookie|Matrix|Header..)Params
    // and extract entity type
    MultivaluedHashMap<String, Object> headers =
        new MultivaluedHashMap<String, Object>(this.headers);
    LinkedList<Cookie> cookies = new LinkedList<Cookie>(this.cookies);
    Form form = new Form();
    form.asMap().putAll(this.form.asMap());
    Annotation[][] paramAnns = method.getParameterAnnotations();
    Object entity = null;
    Type entityType = null;
    for (int i = 0; i < paramAnns.length; i++) {
      Map<Class, Annotation> anns = new HashMap<Class, Annotation>();
      for (Annotation ann : paramAnns[i]) {
        anns.put(ann.annotationType(), ann);
      }
      Annotation ann;
      Object value = args[i];
      if (anns.isEmpty()) {
        entityType = method.getGenericParameterTypes()[i];
        entity = value;
      } else {
        if (value == null && (ann = anns.get(DefaultValue.class)) != null) {
          value = ((DefaultValue) ann).value();
        }

        if (value != null) {
          if ((ann = anns.get(PathParam.class)) != null) {
            newTarget = newTarget.resolveTemplate(((PathParam) ann).value(), value);
          } else if ((ann = anns.get((QueryParam.class))) != null) {
            if (value instanceof Collection) {
              newTarget =
                  newTarget.queryParam(((QueryParam) ann).value(), convert((Collection) value));
            } else {
              newTarget = newTarget.queryParam(((QueryParam) ann).value(), value);
            }
          } else if ((ann = anns.get((HeaderParam.class))) != null) {
            if (value instanceof Collection) {
              headers.addAll(((HeaderParam) ann).value(), convert((Collection) value));
            } else {
              headers.addAll(((HeaderParam) ann).value(), value);
            }

          } else if ((ann = anns.get((CookieParam.class))) != null) {
            String name = ((CookieParam) ann).value();
            Cookie c;
            if (value instanceof Collection) {
              for (Object v : ((Collection) value)) {
                if (!(v instanceof Cookie)) {
                  c = new Cookie(name, v.toString());
                } else {
                  c = (Cookie) v;
                  if (!name.equals(((Cookie) v).getName())) {
                    // is this the right thing to do? or should I fail? or ignore the difference?
                    c = new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion());
                  }
                }
                cookies.add(c);
              }
            } else {
              if (!(value instanceof Cookie)) {
                cookies.add(new Cookie(name, value.toString()));
              } else {
                c = (Cookie) value;
                if (!name.equals(((Cookie) value).getName())) {
                  // is this the right thing to do? or should I fail? or ignore the difference?
                  cookies.add(
                      new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion()));
                }
              }
            }
          } else if ((ann = anns.get((MatrixParam.class))) != null) {
            if (value instanceof Collection) {
              newTarget =
                  newTarget.matrixParam(((MatrixParam) ann).value(), convert((Collection) value));
            } else {
              newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), value);
            }
          } else if ((ann = anns.get((FormParam.class))) != null) {
            if (value instanceof Collection) {
              for (Object v : ((Collection) value)) {
                form.param(((FormParam) ann).value(), v.toString());
              }
            } else {
              form.param(((FormParam) ann).value(), value.toString());
            }
          }
        }
      }
    }

    if (httpMethod == null) {
      // the method is a subresource locator
      return WebResourceFactory.newResource(responseType, newTarget, true, headers, cookies, form);
    }

    // accepted media types
    Produces produces = method.getAnnotation(Produces.class);
    if (produces == null) {
      produces = proxyIfc.getAnnotation(Produces.class);
    }
    String[] accepts = produces == null ? null : produces.value();

    // determine content type
    String contentType = null;
    if (entity != null) {
      Consumes consumes = method.getAnnotation(Consumes.class);
      if (consumes == null) {
        consumes = proxyIfc.getAnnotation(Consumes.class);
      }
      if (consumes != null && consumes.value().length > 0) {
        // TODO: should consider q/qs instead of picking the first one
        contentType = consumes.value()[0];
      }
    }

    Invocation.Builder builder;
    if (accepts != null) {
      builder = newTarget.request(accepts);
    } else {
      builder = newTarget.request();
    }

    // apply header params and cookies
    builder.headers(headers);

    for (Cookie c : cookies) {
      builder = builder.cookie(c);
    }

    Object result;

    if (entity == null && !form.asMap().isEmpty()) {
      entity = form;
      contentType = MediaType.APPLICATION_FORM_URLENCODED;
    } else {
      if (contentType == null) {
        contentType = MediaType.APPLICATION_OCTET_STREAM;
      }
      if (!form.asMap().isEmpty()) {
        if (entity instanceof Form) {
          ((Form) entity).asMap().putAll(form.asMap());
        } else {
          // TODO: should at least log some warning here
        }
      }
    }

    GenericType responseGenericType = new GenericType(method.getGenericReturnType());
    if (entity != null) {
      if (entityType instanceof ParameterizedType) {
        entity = new GenericEntity(entity, entityType);
      }
      result = builder.method(httpMethod, Entity.entity(entity, contentType), responseGenericType);
    } else {
      result = builder.method(httpMethod, responseGenericType);
    }

    return result;
  }