Ejemplo n.º 1
0
  protected ClientResponse impl() {
    Preconditions.checkNotNull(repository, "Repository was not specified");

    if (StringUtils.countMatches(repository, ":") == 1) {
      String repositoryTag[] = StringUtils.split(repository, ':');
      repository = repositoryTag[0];
      tag = repositoryTag[1];
    }

    MultivaluedMap<String, String> params = new MultivaluedMapImpl();
    params.add("tag", tag);
    params.add("fromImage", repository);
    params.add("registry", registry);

    WebResource webResource = baseResource.path("/images/create").queryParams(params);

    try {
      LOGGER.trace("POST: {}", webResource);
      return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class);
    } catch (UniformInterfaceException exception) {
      if (exception.getResponse().getStatus() == 500) {
        throw new DockerException("Server error.", exception);
      } else {
        throw new DockerException(exception);
      }
    }
  }
Ejemplo n.º 2
0
 // Registra un MR para su gestion
 // curl -d "ip=192.168.119.35&port=10001&domain=broadcaster&type=Webservices"
 // http://192.168.119.35:9999/mbs/register
 @POST
 @Path("/register")
 @Produces(MediaType.TEXT_PLAIN)
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 public String register(
     @FormParam("ip") String ip,
     @FormParam("port") String port,
     @FormParam("domain") String domain,
     @FormParam("type") String type) {
   if (domain.equals("SNMPInstrumentingServer")) {
     Client client = Client.create();
     WebResource webResource =
         client.resource(
             "http://"
                 + MBeanServerMaster.INSTRUMENTING_SERVER_IP
                 + ":"
                 + MBeanServerMaster.INSTRUMENTING_SERVER_WS_PORT
                 + "/snmp_mbs/register");
     MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
     queryParams.add("domain", "SNMPInstrumentingServer");
     queryParams.add("type", type);
     ClientResponse s =
         webResource.queryParams(queryParams).post(ClientResponse.class, queryParams);
     if (s.getEntity(String.class).equals("ok"))
       DynamicMBeanMirrorFactory.register(ip, port, domain, type);
   } else DynamicMBeanMirrorFactory.register(ip, port, domain, type);
   return "";
 }
  private static WebResource.Builder getBuilder(
      String url, String authorization, Map<String, String> key, Boolean overwrite) {
    Client client = Client.create();
    WebResource wr = client.resource(url);

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();

    if (key != null && !key.isEmpty()) {
      for (String k : key.keySet()) {
        queryParams.add(k, key.get(k));
      }
    }

    if (overwrite != null && overwrite) {
      queryParams.add(CLOUDHUB_OVERRITE_REST_PARAMETER, overwrite.toString());
    }

    if (queryParams.isEmpty()) {
      return wr.header(HTTP_AUTH_HEADER_NAME, authorization).type(MediaType.APPLICATION_JSON);
    } else {
      return wr.queryParams(queryParams)
          .header(HTTP_AUTH_HEADER_NAME, authorization)
          .type(MediaType.APPLICATION_JSON);
    }
  }
Ejemplo n.º 4
0
 private void handleCookies(
     Method m,
     Object[] params,
     MultivaluedMap<String, String> headers,
     List<Parameter> beanParams,
     MultivaluedMap<ParameterType, Parameter> map) {
   List<Parameter> cs = getParameters(map, ParameterType.COOKIE);
   for (Parameter p : cs) {
     if (params[p.getIndex()] != null) {
       headers.add(
           HttpHeaders.COOKIE,
           p.getName()
               + '='
               + convertParamValue(params[p.getIndex()].toString(), getParamAnnotations(m, p)));
     }
   }
   for (Parameter p : beanParams) {
     Map<String, BeanPair> values =
         getValuesFromBeanParam(params[p.getIndex()], CookieParam.class);
     for (Map.Entry<String, BeanPair> entry : values.entrySet()) {
       if (entry.getValue() != null) {
         headers.add(
             HttpHeaders.COOKIE,
             entry.getKey()
                 + "="
                 + convertParamValue(entry.getValue().getValue(), entry.getValue().getAnns()));
       }
     }
   }
 }
Ejemplo n.º 5
0
 private void handleHeaders(
     Method m,
     Object[] params,
     MultivaluedMap<String, String> headers,
     List<Parameter> beanParams,
     MultivaluedMap<ParameterType, Parameter> map) {
   List<Parameter> hs = getParameters(map, ParameterType.HEADER);
   for (Parameter p : hs) {
     if (params[p.getIndex()] != null) {
       headers.add(
           p.getName(), convertParamValue(params[p.getIndex()], getParamAnnotations(m, p)));
     }
   }
   for (Parameter p : beanParams) {
     Map<String, BeanPair> values =
         getValuesFromBeanParam(params[p.getIndex()], HeaderParam.class);
     for (Map.Entry<String, BeanPair> entry : values.entrySet()) {
       if (entry.getValue() != null) {
         headers.add(
             entry.getKey(),
             convertParamValue(entry.getValue().getValue(), entry.getValue().getAnns()));
       }
     }
   }
 }
Ejemplo n.º 6
0
  /** Test checks that POST on the '/form' resource gives a response page with the entered data. */
  @Test
  public void testPostOnForm() {
    MultivaluedMap<String, String> formData = new MultivaluedStringMap();
    formData.add("name", "testName");
    formData.add("colour", "red");
    formData.add("hint", "re");

    Response response =
        target()
            .path("form")
            .request()
            .post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
    assertEquals(Response.Status.OK, response.getStatusInfo());

    // check that the generated response is the expected one
    InputStream responseInputStream = response.readEntity(InputStream.class);
    try {
      byte[] responseData = new byte[responseInputStream.available()];
      final int read = responseInputStream.read(responseData);

      assertTrue(read > 0);
      assertTrue(new String(responseData).contains("Hello, you entered"));
    } catch (IOException ex) {
      Logger.getLogger(MainTest.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 7
0
  public List<Offer> getOffers(String latitude, String longitude) {
    // Request JSON data from the API for offers
    MultivaluedMap<String, String> QueryParams = new MultivaluedMapImpl();
    QueryParams.add("lat", latitude);
    QueryParams.add("long", longitude);
    String json =
        service
            .path("offers")
            .queryParams(QueryParams)
            .accept(MediaType.APPLICATION_JSON)
            .get(String.class);

    List<Offer> offers = null;

    try {
      // Transform this to a list of POJOs
      offers = mapper.readValue(json, new TypeReference<List<Offer>>() {});

      for (Offer offer : offers) {
        Log.d(TAG, "Offer: " + offer.getId() + " decription: " + offer.getDescription());
      }
    } catch (JsonParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JsonMappingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return offers;
  }
  @Test
  public void testCreateAndGetApplication()
      throws ParseException, IllegalArgumentException, ClientProtocolException, IOException {
    // Define application attributes
    String friendlyName, voiceCallerIdLookup, rcmlUrl, kind;

    // Test create application via POST
    MultivaluedMap<String, String> applicationParams = new MultivaluedMapImpl();
    applicationParams.add("FriendlyName", friendlyName = "APPCreateGet");
    applicationParams.add("VoiceCallerIdLookup", voiceCallerIdLookup = "true");
    applicationParams.add("RcmlUrl", rcmlUrl = "/restcomm/rcmlurl/test");
    applicationParams.add("Kind", kind = "voice");
    JsonObject applicationJson =
        RestcommApplicationsTool.getInstance()
            .createApplication(
                deploymentUrl.toString(),
                adminAccountSid,
                adminUsername,
                adminAuthToken,
                applicationParams);
    Sid applicationSid = new Sid(applicationJson.get("sid").getAsString());

    // Test asserts via GET to a single application
    applicationJson =
        RestcommApplicationsTool.getInstance()
            .getApplication(
                deploymentUrl.toString(),
                adminUsername,
                adminAuthToken,
                adminAccountSid,
                applicationSid.toString());

    SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
    assertTrue(df.parse(applicationJson.get("date_created").getAsString()) != null);
    assertTrue(df.parse(applicationJson.get("date_updated").getAsString()) != null);
    assertTrue(applicationJson.get("friendly_name").getAsString().equals(friendlyName));
    assertTrue(applicationJson.get("account_sid").getAsString().equals(adminAccountSid));
    assertTrue(applicationJson.get("api_version").getAsString().equals("2012-04-24"));
    assertTrue(
        applicationJson.get("voice_caller_id_lookup").getAsString().equals(voiceCallerIdLookup));
    assertTrue(applicationJson.get("rcml_url").getAsString().equals(rcmlUrl));
    assertTrue(applicationJson.get("kind").getAsString().equals(kind));

    // Test asserts via GET to a application list
    JsonArray applicationsListJson =
        RestcommApplicationsTool.getInstance()
            .getApplications(
                deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid);
    applicationJson = applicationsListJson.get(0).getAsJsonObject();
    assertTrue(df.parse(applicationJson.get("date_created").getAsString()) != null);
    assertTrue(df.parse(applicationJson.get("date_updated").getAsString()) != null);
    assertTrue(applicationJson.get("friendly_name").getAsString().equals(friendlyName));
    assertTrue(applicationJson.get("account_sid").getAsString().equals(adminAccountSid));
    assertTrue(applicationJson.get("api_version").getAsString().equals("2012-04-24"));
    assertTrue(
        applicationJson.get("voice_caller_id_lookup").getAsString().equals(voiceCallerIdLookup));
    assertTrue(applicationJson.get("rcml_url").getAsString().equals(rcmlUrl));
    assertTrue(applicationJson.get("kind").getAsString().equals(kind));
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle
  * (com.sun.jersey.api.client.ClientRequest)
  */
 @Override
 public ClientResponse doHandle(ClientRequest cr) {
   MultivaluedMap<String, Object> headers = cr.getHeaders();
   headers.add("DataServiceVersion", "3.0");
   headers.add("MaxDataServiceVersion", "3.0");
   headers.add("x-ms-version", "2.5");
   return getNext().handle(cr);
 }
Ejemplo n.º 10
0
  @Test
  public void testFormMultivaluedMapRepresentation() {
    MultivaluedMap<String, String> map = new MultivaluedHashMap<String, String>();

    map.add("name", "\u00A9 CONTENT \u00FF \u2200 \u22FF");
    map.add("name", "� � �");
    _test(map, FormMultivaluedMapResource.class, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
  }
 Attachment createDocumentAttachment(File pdfFile) {
   String filename = pdfFile.getName();
   MultivaluedMap<String, String> headers = new MetadataMap<String, String>();
   headers.add("Content-Disposition", "attachment;filename=" + filename);
   headers.add("Content-Type", "application/x-www-form-urlencoded");
   FileDataSource fileDataSource = new FileDataSource(pdfFile);
   return new Attachment("dokument", fileDataSource, headers);
 }
 @Override
 public void filter(
     ContainerRequestContext requestContext, ContainerResponseContext responseContext)
     throws IOException {
   MultivaluedMap<String, Object> headers = responseContext.getHeaders();
   headers.add("Cache-Control", "private, no-cache, no-store, must-revalidate");
   headers.add("Expires", "-1");
   headers.add("Pragma", "no-cache");
 }
Ejemplo n.º 13
0
 @GET
 @Path("MultivaluedMap")
 @Produces("application/x-www-form-urlencoded")
 public MultivaluedMap<String, String> mMapGet() {
   final MultivaluedMap<String, String> mmap = new MultivaluedMapImpl<String, String>();
   mmap.add("firstname", "Angela");
   mmap.add("lastname", "Merkel");
   return mmap;
 }
 Attachment createForsendelsesAttachment(Forsendelse forsendelse) throws Exception {
   JAXBContext jaxbContext = JAXBContext.newInstance(new Class[] {Forsendelse.class});
   Marshaller marshaller = jaxbContext.createMarshaller();
   File tmpFile = File.createTempFile("fors-", ".xml");
   marshaller.marshal(forsendelse, tmpFile);
   FileDataSource fileDataSource = new FileDataSource(tmpFile);
   MultivaluedMap<String, String> headers = new MetadataMap<String, String>();
   headers.add("Content-Disposition", "attachment;filename=" + tmpFile.getName());
   headers.add("Content-Type", " text/xml; charset=utf-8");
   return new Attachment("forsendelse", fileDataSource, headers);
 }
  public void close(String description, Location location) {
    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("locationId", location.getId());
    queryParams.add("description", description);

    resource
        .path(RESOURCE)
        .queryParams(queryParams)
        .header("X-Authorization", apiKey)
        .delete(String.class);
  }
Ejemplo n.º 16
0
  @Override
  public void filter(
      ContainerRequestContext requestContext, ContainerResponseContext responseContext)
      throws IOException {

    MultivaluedMap<String, Object> headers = responseContext.getHeaders();

    headers.add("Access-Control-Allow-Origin", "*");
    headers.add("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE, PUT");
    headers.add(
        "Access-Control-Allow-Headers",
        "X-Requested-With, Content-Type, X-Codingpedia, uname, pass");
  }
Ejemplo n.º 17
0
 public List<SystemElement> getSystemElements(List<String> inKeys, boolean summarize)
     throws ClientException {
   if (inKeys == null) {
     throw new IllegalArgumentException("inKeys cannot be null");
   }
   MultivaluedMap<String, String> formParams = new MultivaluedMapImpl();
   for (String key : inKeys) {
     formParams.add("key", key);
   }
   formParams.add("summarize", Boolean.toString(summarize));
   String path = UriBuilder.fromPath("/api/protected/systemelement/").build().toString();
   return doPost(path, SystemElementList, formParams);
 }
  public static List<PatientSearchResult> getDynamicSearch(
      List<DynamicSearchCriteria> criteria, String stateRelation, String userToken) {
    // Use a form because there are an unknown number of values
    MultivaluedMap form = new MultivaluedMapImpl();
    // stateRelation is how the criteria are logically related "AND", "OR"
    form.add("stateRelation", stateRelation);
    int i = 0;
    // Step through all criteria given, the form fields are appended with an integer
    // to maintain grouping in REST call (dataGroup0, dataGroup1...)
    for (DynamicSearchCriteria dcriteria : criteria) {
      form.add("sourceName" + i, dcriteria.getDataGroup());
      form.add("itemName" + i, dcriteria.getField());
      form.add("operator" + i, dcriteria.getOperator().getValue());
      form.add("value" + i, dcriteria.getValue());
      i++;
    }

    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create();
    WebResource resource =
        client.resource(APIURLHolder.getUrl() + "/nbia-api/services/getDynamicSearch");
    ClientResponse response =
        resource
            .accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .header("Authorization", "Bearer " + userToken)
            .post(ClientResponse.class, form);
    // check response status code
    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    // display response
    String output = response.getEntity(String.class);
    List<PatientSearchResultImpl> myObjects;
    try {
      //	Object json = mapper.readValue(output, Object.class);
      //   String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
      //   logger.info("Returned JSON\n"+indented);
      myObjects = mapper.readValue(output, new TypeReference<List<PatientSearchResultImpl>>() {});
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    List<PatientSearchResult> returnValue = new ArrayList<PatientSearchResult>();
    for (PatientSearchResultImpl result : myObjects) {
      returnValue.add(result);
    }
    return returnValue;
  }
Ejemplo n.º 19
0
 /** Queries GeoNames API for a given geonameId and return the JSON string */
 private String fetchJsonFromGeoNames(String geoNameId) {
   String result = null;
   if (cache.containsKey("geoname_json_" + geoNameId)) {
     return cache.get("geoname_json_" + geoNameId);
   } else {
     Client c = Client.create();
     WebResource r = c.resource(geonamesApiUrl);
     MultivaluedMap<String, String> params = new MultivaluedMapImpl();
     params.add("geonameId", geoNameId);
     params.add("username", apiUser);
     result = r.queryParams(params).get(String.class);
     cache.put("geoname_json_" + geoNameId, result);
   }
   return result;
 }
Ejemplo n.º 20
0
 public void filter(ClientRequestContext requestContext) throws IOException {
   MultivaluedMap<String, Object> headers = requestContext.getHeaders();
   String authenticationHeader = getAuthenticationHeader();
   if (Strings.isNotBlank(authenticationHeader)) {
     headers.add("Authorization", authenticationHeader);
   }
 }
Ejemplo n.º 21
0
 /**
  * Process any {@link InjectLink} annotations on the supplied entity.
  *
  * @param entity the entity object returned by the resource method
  * @param uriInfo the uriInfo for the request
  * @param headers the map into which the headers will be added
  */
 public void processLinkHeaders(
     T entity, UriInfo uriInfo, MultivaluedMap<String, Object> headers) {
   List<String> headerValues = getLinkHeaderValues(entity, uriInfo);
   for (String headerValue : headerValues) {
     headers.add("Link", headerValue);
   }
 }
Ejemplo n.º 22
0
  private static MultivaluedMap<ParameterType, Parameter> getParametersInfo(
      Method m, Object[] params, OperationResourceInfo ori) {
    MultivaluedMap<ParameterType, Parameter> map = new MetadataMap<ParameterType, Parameter>();

    List<Parameter> parameters = ori.getParameters();
    if (parameters.size() == 0) {
      return map;
    }
    int requestBodyParam = 0;
    int multipartParam = 0;
    for (Parameter p : parameters) {
      if (isIgnorableParameter(m, p)) {
        continue;
      }
      if (p.getType() == ParameterType.REQUEST_BODY) {
        requestBodyParam++;
        if (getMultipart(ori, p.getIndex()) != null) {
          multipartParam++;
        }
      }
      map.add(p.getType(), p);
    }

    if (map.containsKey(ParameterType.REQUEST_BODY)) {
      if (requestBodyParam > 1 && requestBodyParam != multipartParam) {
        reportInvalidResourceMethod(ori.getMethodToInvoke(), "SINGLE_BODY_ONLY");
      }
      if (map.containsKey(ParameterType.FORM)) {
        reportInvalidResourceMethod(ori.getMethodToInvoke(), "ONLY_FORM_ALLOWED");
      }
    }
    return map;
  }
Ejemplo n.º 23
0
  @Override
  public UriBuilder queryParam(String name, Object... values) {
    checkSsp();
    if (name == null) throw new IllegalArgumentException("Name parameter is null");
    if (values == null) throw new IllegalArgumentException("Value parameter is null");
    if (values.length == 0) return this;

    name = encode(name, UriComponent.Type.QUERY_PARAM);
    if (queryParams == null) {
      for (Object value : values) {
        if (query.length() > 0) query.append('&');
        query.append(name);

        if (value == null)
          throw new IllegalArgumentException("One or more of query value parameters are null");

        final String stringValue = value.toString();
        if (stringValue.length() > 0)
          query.append('=').append(encode(stringValue, UriComponent.Type.QUERY_PARAM));
      }
    } else {
      for (Object value : values) {
        if (value == null)
          throw new IllegalArgumentException("One or more of query value parameters are null");

        queryParams.add(name, encode(value.toString(), UriComponent.Type.QUERY_PARAM));
      }
    }
    return this;
  }
Ejemplo n.º 24
0
  /** Executes an authentication request via HTTP POST */
  private <T> T executeAuthenticationPost(WebResource webResource, Class<T> returnClass)
      throws CIWiseRESTConnectorTokenExpiredException, CIWiseRESTConnectorException {

    // Map query params for POST operation MultivaluedMap, MultivaluedMapImpl

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("username", getConnector().getConfig().getUsername());
    queryParams.add("password", getConnector().getConfig().getPassword());

    /** Call HTTP POST */
    ClientResponse clientResponse =
        webResource
            .queryParams(queryParams)
            .accept(MediaType.APPLICATION_JSON)
            .post(ClientResponse.class);

    if (clientResponse.getStatus() == 200) {
      return clientResponse.getEntity(returnClass);
    } else if (clientResponse.getStatus() == 401) {
      throw new CIWiseRESTConnectorTokenExpiredException(
          "The access token has expired; " + clientResponse.getEntity(String.class));
    } else {
      throw new CIWiseRESTConnectorException(
          String.format(
              "ERROR - statusCode: %d - message: %s",
              clientResponse.getStatus(), clientResponse.getEntity(String.class)));
    }
  }
  private FileMetaData getFileContentInfo(File file) {
    try {
      MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
      queryParams.add("redirect", "meta");
      ClientResponse resp =
          getRootApiWebResource()
              .path("files")
              .path(String.valueOf(file.getId()))
              .path("content")
              .queryParams(queryParams)
              .accept(MediaType.APPLICATION_OCTET_STREAM)
              .accept(MediaType.TEXT_HTML)
              .accept(MediaType.APPLICATION_XHTML_XML)
              .get(ClientResponse.class);

      String sResp = resp.getEntity(String.class);
      FileMetaData fileInfo =
          mapper.readValue(
              mapper.readValue(sResp, JsonNode.class).findPath(RESPONSE).toString(),
              FileMetaData.class);
      logger.info(fileInfo.toString());
      return fileInfo;
    } catch (BaseSpaceException bs) {
      throw bs;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
  @Override
  public UriBuilder replaceMatrixParam(String name, Object... values) {
    checkSsp();

    if (name == null) {
      throw new IllegalArgumentException("Name parameter is null");
    }

    if (matrixParams == null) {
      int i = path.lastIndexOf("/");
      if (i != -1) {
        i = 0;
      }
      matrixParams = UriComponent.decodeMatrix((i != -1) ? path.substring(i) : "", false);
      i = path.indexOf(";", i);
      if (i != -1) {
        path.setLength(i);
      }
    }

    name = encode(name, UriComponent.Type.MATRIX_PARAM);
    matrixParams.remove(name);
    if (values != null) {
      for (Object value : values) {
        if (value == null) {
          throw new IllegalArgumentException("One or more of matrix value parameters are null");
        }

        matrixParams.add(name, encode(value.toString(), UriComponent.Type.MATRIX_PARAM));
      }
    }
    return this;
  }
  @Override
  public UriBuilder replaceQueryParam(String name, Object... values) {
    checkSsp();

    if (queryParams == null) {
      queryParams = UriComponent.decodeQuery(query.toString(), false);
      query.setLength(0);
    }

    name = encode(name, UriComponent.Type.QUERY_PARAM);
    queryParams.remove(name);

    if (values == null) {
      return this;
    }

    for (Object value : values) {
      if (value == null) {
        throw new IllegalArgumentException("One or more of query value parameters are null");
      }

      queryParams.add(name, encode(value.toString(), UriComponent.Type.QUERY_PARAM));
    }
    return this;
  }
  @Test
  public void putAddToOrganizationFail() throws Exception {

    Map<String, String> originalProperties = getRemoteTestProperties();

    try {
      setTestProperty(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "false");
      setTestProperty(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false");
      setTestProperty(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "false");
      setTestProperty(PROPERTIES_SYSADMIN_EMAIL, "*****@*****.**");

      String t = adminToken();
      MultivaluedMap formData = new MultivaluedMapImpl();
      formData.add("foo", "bar");
      try {
        resource()
            .path(
                "/management/organizations/test-organization/users/[email protected]")
            .queryParam("access_token", t)
            .accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .put(JsonNode.class, formData);
      } catch (UniformInterfaceException e) {
        assertEquals("Should receive a 400 Not Found", 400, e.getResponse().getStatus());
      }
    } finally {
      setTestProperties(originalProperties);
    }
  }
Ejemplo n.º 29
0
  public static void testUpdateDb() {
    Client client = Client.create();

    WebResource webResource = client.resource("http://localhost:8080/TrainingDiaryPortal");

    MultivaluedMap<String, String> params = new MultivaluedMapImpl();
    params.add("id", "1");
    params.add("channel", "mobile");

    ClientResponse response =
        webResource
            .path("/updateDb")
            .queryParams(params)
            .type("application/json")
            .post(ClientResponse.class);
  }
Ejemplo n.º 30
0
  @Test
  public void shouldFilterLogEntriesOnEventCategories() throws Exception {
    DocumentModel doc = RestServerInit.getFile(1, session);

    List<LogEntry> logEntries = new ArrayList<>();
    LogEntry logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("firstEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("secondEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("Two");
    logEntry.setEventId("firstEvent");
    logEntries.add(logEntry);
    auditLogger.addLogEntries(logEntries);

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("category", "One");
    queryParams.add("category", "Two");
    ClientResponse response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    JsonNode node = mapper.readTree(response.getEntityInputStream());
    List<JsonNode> nodes = getLogEntries(node);
    assertEquals(3, nodes.size());

    queryParams = new MultivaluedMapImpl();
    queryParams.add("category", "Two");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    nodes = getLogEntries(node);
    assertEquals(1, nodes.size());
  }