/**
   * Login to the PAScoresDwnld site. This method has not been modified from the original published
   * by CollegeBoard.
   *
   * <p>For more information, please see: <a href=
   * "https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-portal-help#features">
   * https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-
   * portal-help#features</a>
   *
   * <p>Original code can be accessed at: <a href=
   * "https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip">
   * https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip </a>
   *
   * @author CollegeBoard
   * @param username Username to login with
   * @param password Password to login with
   * @return Authentication token
   */
  private String login(String username, String password) {
    Client client = getClient();
    WebResource webResource = client.resource(scoredwnldUrlRoot + "/pascoredwnld/login");

    String input = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"};";

    ClientResponse response =
        webResource
            .accept("application/json")
            .type("application/json")
            .post(ClientResponse.class, input);

    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    try {
      JSONObject json = new JSONObject(response.getEntity(String.class));
      return String.valueOf(json.get("token"));
    } catch (Exception e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    }
    return "";
  }
示例#2
0
  public void bootFromServer(String clientName, Database db1)
      throws JSONException, ClassNotFoundException {

    Client client = Client.create();

    WebResource webResource =
        client.resource("http://localhost:8080/com.youtube.rest/api/bootstrap/get/" + clientName);
    ;

    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

    if (response.getStatus() != 200 && response.getStatus() != 204) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    String output = response.getEntity(String.class);
    System.out.println("Server Bootstrap information: ");
    System.out.println(output);
    String query = db1.parseData(output);
    System.out.println("QUERY");
    System.out.println(query);
    db1.delete("client1");
    //	db1.insert(query);
    System.out.println("Information saved in Mysql!");
    System.out.println("Server boot done!");
  }
  @Test(dependsOnMethods = "testSubmit")
  public void testGetTypeNames() throws Exception {
    WebResource resource = service.path("api/atlas/types");

    ClientResponse clientResponse =
        resource
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.GET, ClientResponse.class);
    assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode());

    String responseAsString = clientResponse.getEntity(String.class);
    Assert.assertNotNull(responseAsString);

    JSONObject response = new JSONObject(responseAsString);
    Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));

    final JSONArray list = response.getJSONArray(AtlasClient.RESULTS);
    Assert.assertNotNull(list);

    // Verify that primitive and core types are not returned
    String typesString = list.join(" ");
    Assert.assertFalse(typesString.contains(" \"__IdType\" "));
    Assert.assertFalse(typesString.contains(" \"string\" "));
  }
  @Test
  public void testGetDependencies() throws Exception {
    ClientResponse response;
    response =
        this.service
            .path("api/entities/list/process/")
            .header("Remote-User", REMOTE_USER)
            .type(MediaType.TEXT_XML)
            .accept(MediaType.TEXT_XML)
            .get(ClientResponse.class);
    Assert.assertEquals(response.getStatus(), 200);

    Map<String, String> overlay = getUniqueOverlay();

    response = submitToIvory(CLUSTER_FILE_TEMPLATE, overlay, EntityType.CLUSTER);
    assertSuccessful(response);

    response =
        this.service
            .path("api/entities/list/cluster/")
            .header("Remote-User", REMOTE_USER)
            .type(MediaType.TEXT_XML)
            .accept(MediaType.TEXT_XML)
            .get(ClientResponse.class);
    Assert.assertEquals(response.getStatus(), 200);
  }
  @Test(dependsOnMethods = {"testDeployApplication", "testLocatedLocation"})
  public void testDeployApplicationFromBuilder() throws Exception {
    ApplicationSpec spec =
        ApplicationSpec.builder()
            .type(RestMockAppBuilder.class.getCanonicalName())
            .name("simple-app-builder")
            .locations(ImmutableSet.of("localhost"))
            .build();

    ClientResponse response = clientDeploy(spec);
    assertTrue(response.getStatus() / 100 == 2, "response is " + response);

    // Expect app to be running
    URI appUri = response.getLocation();
    waitForApplicationToBeRunning(response.getLocation(), Duration.TEN_SECONDS);
    assertEquals(
        client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(),
        "simple-app-builder");

    // Expect app to have the child-entity
    Set<EntitySummary> entities =
        client()
            .resource(appUri.toString() + "/entities")
            .get(new GenericType<Set<EntitySummary>>() {});
    assertEquals(entities.size(), 1);
    assertEquals(Iterables.getOnlyElement(entities).getName(), "child1");
    assertEquals(
        Iterables.getOnlyElement(entities).getType(),
        RestMockSimpleEntity.class.getCanonicalName());
  }
示例#6
0
  @Test
  public void testMember() throws InterruptedException, JSONException {
    // The member must be unlocked to begin the test
    String accessToken =
        getAccessTokenWithScopePath(
            ScopePathType.READ_LIMITED,
            lockedClientId,
            lockedClientSecret,
            lockedClientRedirectUri);
    ClientResponse getAllResponse = memberV2ApiClient.getEmails(user1OrcidId, accessToken);
    assertNotNull(getAllResponse);
    Emails emails = getAllResponse.getEntity(Emails.class);
    assertNotNull(emails);
    assertNotNull(emails.getEmails());
    assertFalse(emails.getEmails().isEmpty());

    // Lock and try to get authorization code
    adminLockAccount(adminUserName, adminPassword, memberId);
    lookForErrorsOnAuthorizationCodePage(
        lockedClientId, ScopePathType.READ_LIMITED.value(), lockedClientRedirectUri);

    // Try to use access token while the client is locked
    getAllResponse = memberV2ApiClient.getEmails(user1OrcidId, accessToken);
    assertNotNull(getAllResponse);

    // unlock to finish
    adminUnlockAccount(adminUserName, adminPassword, memberId);
  }
  @Test
  public void testProcessEndtimeUpdate() throws Exception {
    scheduleProcess();
    waitForBundleStart(Job.Status.RUNNING);

    ClientResponse response =
        this.service
            .path("api/entities/definition/process/" + processName)
            .header("Remote-User", REMOTE_USER)
            .accept(MediaType.TEXT_XML)
            .get(ClientResponse.class);
    Process process =
        (Process)
            EntityType.PROCESS
                .getUnmarshaller()
                .unmarshal(new StringReader(response.getEntity(String.class)));

    Validity processValidity = process.getClusters().getClusters().get(0).getValidity();
    processValidity.setEnd(new Date(new Date().getTime() + 60 * 60 * 1000));
    File tmpFile = getTempFile();
    EntityType.PROCESS.getMarshaller().marshal(process, tmpFile);
    response =
        this.service
            .path("api/entities/update/process/" + processName)
            .header("Remote-User", REMOTE_USER)
            .accept(MediaType.TEXT_XML)
            .post(ClientResponse.class, getServletInputStream(tmpFile.getAbsolutePath()));
    assertSuccessful(response);

    // Assert that update does not create new bundle
    List<BundleJob> bundles = getBundles();
    Assert.assertEquals(bundles.size(), 1);
  }
示例#8
0
  public String contactNumberClient(Business input) {

    String contactNumber = "";

    try {

      Client client = Client.create();
      WebResource webResource = client.resource("http://localhost:9280/NICUtil/rest/contact/post");

      ObjectMapper mapper = new ObjectMapper();
      ClientResponse response =
          webResource
              .type("application/json")
              .post(ClientResponse.class, mapper.writeValueAsString(input));

      if (response.getStatus() != 201) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
      }

      System.out.println("**Web Service Successful in helper**\n\n");
      contactNumber = response.getEntity(String.class);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return contactNumber;
  }
示例#9
0
  protected AccessTokenResponse getAccessToken(
      Client client, PartnerConfiguration partnerConfiguration)
      throws UnsupportedEncodingException {
    String tokenParams =
        String.format(
            "grant_type=client_credentials&scope=all&client_id=%s&client_secret=%s",
            partnerConfiguration.userName, partnerConfiguration.password);

    ClientResponse postResponse =
        client
            .resource(TOKEN_URL)
            .entity(tokenParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE)
            .header(
                "Authorization",
                basic(partnerConfiguration.userName, partnerConfiguration.password))
            .post(ClientResponse.class);

    String json = postResponse.getEntity(String.class);
    JSONObject accessToken = (JSONObject) JSONSerializer.toJSON(json);

    AccessTokenResponse response = new AccessTokenResponse();
    response.setAccessToken(accessToken.getString("access_token"));
    response.setExpiresIn(accessToken.getLong("expires_in"));
    response.setRefreshToken(accessToken.getString("refresh_token"));
    response.setTokenType(accessToken.getString("token_type"));

    return response;
  }
 @ApiOperation(value = "to insert employee records", response = EmpOrderController.class)
 @RequestMapping(value = "/empinsert", method = RequestMethod.GET)
 public ModelAndView empController(
     HttpServletRequest request,
     HttpServletResponse responses,
     @RequestParam("name") String name,
     @RequestParam("age") int age,
     @RequestParam("gender") String gender) {
   /*String name= request.getParameter("name");
   int age =Integer.parseInt(request.getParameter("age"));
   String gender= request.getParameter("gender");*/
   ModelAndView mav = new ModelAndView();
   JSONObject json = new JSONObject();
   json.put("name", name);
   json.put("age", age);
   json.put("gender", gender);
   String msg = null;
   try {
     Client client = Client.create();
     WebResource webResource = client.resource("http://localhost:8080/EmpOrderRest/api/insertEmp");
     ClientResponse response =
         webResource.type("application/json").post(ClientResponse.class, json.toString());
     if (response.getStatus() == 200) {
       msg = "Employee entry inserted Successfully";
     } else {
       msg = "Cannot insert the records";
       throw new RuntimeException("Why Failed : HTTP error code : " + response.getStatus());
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   mav.setViewName("welcome.jsp");
   mav.addObject("msg", msg);
   return mav;
 }
示例#11
0
  public String fileUploadClient(MultipartFile mpf) {

    String filePath = "";
    Client client = Client.create();
    WebResource webResource = client.resource("http://localhost:9280/NICUtil/rest/contact/upload");
    byte[] logo = null;

    try {
      // logo = FileUtils.readFileToByteArray(file);
      logo = mpf.getBytes();
    } catch (IOException e1) {

      e1.printStackTrace();
    }

    // Construct a MultiPart with two body parts
    MultiPart multiPart =
        new MultiPart().bodyPart(new BodyPart(logo, MediaType.APPLICATION_OCTET_STREAM_TYPE));

    // POST the request
    try {
      ClientResponse response =
          webResource.type("multipart/mixed").post(ClientResponse.class, multiPart);
      filePath = response.getEntity(String.class);

      System.out.println("id is " + filePath);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return filePath;
  }
  @ApiOperation("To fetch and display records")
  @RequestMapping("/display")
  public ModelAndView display(HttpServletRequest request, HttpServletResponse responses) {
    String table = request.getParameter("table");
    String name = request.getParameter("name");
    ModelAndView mav = new ModelAndView();
    String msg = null;
    try {
      Client client = Client.create();
      String names = URLEncoder.encode(name, "UTF-8").replace("+", "%20");
      WebResource webResource =
          client.resource("http://localhost:8080/EmpOrderRest/api/display/" + table + "/" + names);
      ClientResponse response = webResource.head();
      if (response.getStatus() == 200) {

        JSONObject json =
            readJsonFromUrl(
                "http://localhost:8080/EmpOrderRest/api/display/" + table + "/" + names);
        msg = json.toString();
      } else {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    mav.setViewName("welcome.jsp");
    mav.addObject("msg", msg);
    return mav;
  }
 @ApiOperation("to insert order records")
 @RequestMapping(value = "/orderinsert", method = RequestMethod.GET)
 public ModelAndView ordersController(
     HttpServletRequest request,
     HttpServletResponse responses,
     @RequestParam("name") String name,
     @RequestParam("description") String desc) {
   ModelAndView mav = new ModelAndView();
   JSONObject json = new JSONObject();
   json.put("name", name);
   json.put("description", desc);
   String msg = null;
   try {
     Client client = Client.create();
     WebResource webResource =
         client.resource("http://localhost:8080/EmpOrderRest/api/insertOrder");
     ClientResponse response =
         webResource.type("application/json").post(ClientResponse.class, json.toString());
     if (response.getStatus() == 200) {
       msg = "Order entry inserted Successfully";
     } else {
       throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   mav.setViewName("welcome.jsp");
   mav.addObject("msg", msg);
   return mav;
 }
示例#14
0
    private static JSONObject exec(String method, String uri, Object data, String contentType)
        throws JSONException {
      ClientResponse apiResult;
      JSONObject response = new JSONObject();

      try {
        apiResult =
            buildRequest(API_BASE_URL + uri, contentType)
                .method(method, ClientResponse.class, data);
        int apiHttpCode = apiResult.getStatus();

        response.put("status", apiHttpCode);

        String responseBody = apiResult.getEntity(String.class);

        response.put(
            "response",
            responseBody.indexOf("[") == 0
                ? new JSONArray(responseBody)
                : new JSONObject(responseBody));
      } catch (Exception e) {
        response.put("status", 500);
        response.put("error", e.getMessage());
      }

      return response;
    }
示例#15
0
  /**
   * TODO
   *
   * @param serviceName
   * @param pageSize
   * @return
   */
  public List<IEntity> getEntities(final String serviceName, final int pageSize) {

    int startIndex = 1;
    int resultCount = -1;
    final LinkedList<IEntity> result = new LinkedList<IEntity>();

    do {
      final String url =
          ALM_REST_SERVICE_URL
              + serviceName
              + "?page-size="
              + pageSize
              + "&start-index="
              + startIndex;
      final ClientResponse response = request(url);
      if (response == null) {
        // TODO log warn
        return result;
      }
      final Entities entities = response.getEntity(Entities.class);
      resultCount = entities.getTotalResults();
      result.addAll(entities);
      startIndex = startIndex + pageSize;

    } while (resultCount == pageSize);
    return result;
  }
示例#16
0
  @Test
  public void updateTopologyConfigWhileAuthenticated() {
    final Topology mockedTopology = RandomGenerator.randomObject(Topology.class);
    final TopologyConfig requestTopologyConfig = RandomGenerator.randomObject(TopologyConfig.class);

    doReturn(mockedTopology)
        .when(topologyServiceMock)
        .getTopology(mockedTopology.getId(), TEST_SUBJECT_ID);
    doNothing()
        .when(topologyServiceMock)
        .updateTopology(mockedTopology.getId(), mockedTopology, TEST_SUBJECT_ID);

    mockAuthenticatedSubject();

    ClientResponse clientResponse =
        resource()
            .path("/api/topologies/" + mockedTopology.getId() + "/config")
            .type(MediaType.APPLICATION_JSON)
            .put(ClientResponse.class, requestTopologyConfig);

    assertEquals("Response HTTP status code should be 200 (OK)", clientResponse.getStatus(), 200);

    verify(topologyServiceMock).getTopology(mockedTopology.getId(), TEST_SUBJECT_ID);
    verify(topologyServiceMock)
        .updateTopology(mockedTopology.getId(), mockedTopology, TEST_SUBJECT_ID);
  }
  @Test
  public void testWriteBinaryFile() throws InterruptedException {
    final String str = "some binary text";
    final String fileName = "file.bn";

    // set object in PentahoSystem
    mp.defineInstance(IUnifiedRepository.class, repo);

    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});

    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1,
        "admin",
        "password",
        "",
        new String[] {adminAuthorityName, authenticatedAuthorityName});
    try {
      login(sysAdminUserName, systemTenant, new String[] {adminAuthorityName});
      login("admin", mainTenant_1, new String[] {adminAuthorityName, authenticatedAuthorityName});

      WebResource webResource = resource();
      final byte[] blob = str.getBytes();
      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFileBinary(publicFolderPath.replaceAll("/", ":") + ":" + fileName, blob);

      // the file might not actually be ready.. wait a second
      Thread.sleep(20000);

      ClientResponse response =
          webResource
              .path("repo/files/:public:file.bn")
              .accept(APPLICATION_OCTET_STREAM)
              .get(ClientResponse.class);
      assertResponse(response, Status.OK, APPLICATION_OCTET_STREAM);

      byte[] data = response.getEntity(byte[].class);
      assertEquals("contents of file incorrect/missing", str, new String(data));
    } catch (Exception ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  public void testNodeHelper(String path, String media) throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    HashMap<String, String> hash = addAppContainers(app);
    Application app2 = new MockApp(2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    HashMap<String, String> hash2 = addAppContainers(app2);

    ClientResponse response =
        r.path("ws").path("v1").path("node").path(path).accept(media).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    JSONObject info = json.getJSONObject("apps");
    assertEquals("incorrect number of elements", 1, info.length());
    JSONArray appInfo = info.getJSONArray("app");
    assertEquals("incorrect number of elements", 2, appInfo.length());
    String id = appInfo.getJSONObject(0).getString("id");
    if (id.matches(app.getAppId().toString())) {
      verifyNodeAppInfo(appInfo.getJSONObject(0), app, hash);
      verifyNodeAppInfo(appInfo.getJSONObject(1), app2, hash2);
    } else {
      verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);
      verifyNodeAppInfo(appInfo.getJSONObject(1), app, hash);
    }
  }
  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);
    }
  }
  @Test
  public void testNodeAppsState() throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    addAppContainers(app);
    MockApp app2 = new MockApp("foo", 1234, 2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    HashMap<String, String> hash2 = addAppContainers(app2);
    app2.setState(ApplicationState.RUNNING);

    ClientResponse response =
        r.path("ws")
            .path("v1")
            .path("node")
            .path("apps")
            .queryParam("state", ApplicationState.RUNNING.toString())
            .accept(MediaType.APPLICATION_JSON)
            .get(ClientResponse.class);

    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    JSONObject info = json.getJSONObject("apps");
    assertEquals("incorrect number of elements", 1, info.length());
    JSONArray appInfo = info.getJSONArray("app");
    assertEquals("incorrect number of elements", 1, appInfo.length());
    verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);
  }
示例#21
0
  @Test
  public void testGetEntityDefinition() throws Exception {
    ClientResponse response;
    Map<String, String> overlay = getUniqueOverlay();

    response = submitToIvory(CLUSTER_FILE_TEMPLATE, overlay, EntityType.CLUSTER);
    assertSuccessful(response);

    response = submitToIvory(FEED_TEMPLATE1, overlay, EntityType.FEED);
    assertSuccessful(response);

    response =
        this.service
            .path("api/entities/definition/feed/" + overlay.get("inputFeedName"))
            .header("Remote-User", REMOTE_USER)
            .accept(MediaType.TEXT_XML)
            .get(ClientResponse.class);

    String feedXML = response.getEntity(String.class);
    try {
      Feed result = (Feed) unmarshaller.unmarshal(new StringReader(feedXML));
      Assert.assertEquals(result.getName(), overlay.get("inputFeedName"));
    } catch (JAXBException e) {
      Assert.fail("Reponse " + feedXML + " is not valid", e);
    }
  }
  // verify the exception object default format is JSON
  @Test
  public void testNodeAppsStateInvalidDefault() throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    addAppContainers(app);
    Application app2 = new MockApp("foo", 1234, 2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    addAppContainers(app2);

    try {
      r.path("ws")
          .path("v1")
          .path("node")
          .path("apps")
          .queryParam("state", "FOO_STATE")
          .get(JSONObject.class);
      fail("should have thrown exception on invalid user query");
    } catch (UniformInterfaceException ue) {
      ClientResponse response = ue.getResponse();

      assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
      assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
      JSONObject msg = response.getEntity(JSONObject.class);
      JSONObject exception = msg.getJSONObject("RemoteException");
      assertEquals("incorrect number of elements", 3, exception.length());
      String message = exception.getString("message");
      String type = exception.getString("exception");
      String classname = exception.getString("javaClassName");
      verifyStateInvalidException(message, type, classname);
    }
  }
 public static void main(String[] args) {
   Client c = Client.create();
   String v1 = "http://www.diachron-fp7.eu/resource/recordset/efo/2.34";
   String v2 = "http://www.diachron-fp7.eu/resource/recordset/efo/2.35";
   boolean ingest = true;
   String ip = "139.91.183.48";
   ip = "localhost";
   WebResource r = c.resource("http://" + ip + ":8181/ForthMaven-1.0/diachron/change_detection");
   String input =
       "{ \"Old_Version\" : \""
           + v1
           + "\", "
           + "\"New_Version\" : \""
           + v2
           + "\", "
           + "\"Ingest\" : "
           + ingest
           + ", "
           + "\"Complex_Changes\" : [ ] }";
   ClientResponse response =
       r.type(MediaType.APPLICATION_JSON)
           .accept(MediaType.APPLICATION_JSON)
           .post(ClientResponse.class, input);
   System.out.println(response.getEntity(String.class));
   System.out.println(response.getStatus());
 }
  @Test
  public void testNodeSingleAppsXML() throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    HashMap<String, String> hash = addAppContainers(app);
    Application app2 = new MockApp(2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    addAppContainers(app2);

    ClientResponse response =
        r.path("ws")
            .path("v1")
            .path("node")
            .path("apps")
            .path(app.getAppId().toString() + "/")
            .accept(MediaType.APPLICATION_XML)
            .get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList nodes = dom.getElementsByTagName("app");
    assertEquals("incorrect number of elements", 1, nodes.getLength());
    verifyNodeAppInfoXML(nodes, app, hash);
  }
  @Test(
      dependsOnMethods = {
        "testListEffectors",
        "testFetchApplicationsAndEntity",
        "testTriggerSampleEffector",
        "testListApplications",
        "testReadEachSensor",
        "testPolicyWhichCapitalizes",
        "testLocatedLocation"
      })
  public void testDeleteApplication() throws TimeoutException, InterruptedException {
    waitForPageFoundResponse("/v1/applications/simple-app", ApplicationSummary.class);
    Collection<Application> apps = getManagementContext().getApplications();
    log.info("Deleting simple-app from " + apps);
    int size = apps.size();

    ClientResponse response =
        client().resource("/v1/applications/simple-app").delete(ClientResponse.class);

    assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
    TaskSummary task = response.getEntity(TaskSummary.class);
    assertTrue(task.getDescription().toLowerCase().contains("destroy"), task.getDescription());
    assertTrue(task.getDescription().toLowerCase().contains("simple-app"), task.getDescription());

    waitForPageNotFoundResponse("/v1/applications/simple-app", ApplicationSummary.class);

    log.info("App appears gone, apps are: " + getManagementContext().getApplications());
    // more logging above, for failure in the check below

    Asserts.eventually(
        EntityFunctions.applications(getManagementContext()),
        Predicates.compose(Predicates.equalTo(size - 1), CollectionFunctionals.sizeFunction()));
  }
  /**
   * @param path
   * @param expectedValue
   */
  private void shouldRetrieveResourceWithValue(final String path, final String expectedValue) {
    final ClientResponse res =
        root().path(path).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);

    assertEquals(ClientResponse.Status.OK, res.getClientResponseStatus());
    assertEquals(expectedValue, res.getEntity(String.class));
  }
  @Test(dependsOnMethods = "testSubmit")
  public void testGetDefinition() throws Exception {
    for (HierarchicalTypeDefinition typeDefinition : typeDefinitions) {
      System.out.println("typeName = " + typeDefinition.typeName);

      WebResource resource = service.path("api/atlas/types").path(typeDefinition.typeName);

      ClientResponse clientResponse =
          resource
              .accept(Servlets.JSON_MEDIA_TYPE)
              .type(Servlets.JSON_MEDIA_TYPE)
              .method(HttpMethod.GET, ClientResponse.class);
      assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode());

      String responseAsString = clientResponse.getEntity(String.class);
      Assert.assertNotNull(responseAsString);
      JSONObject response = new JSONObject(responseAsString);
      Assert.assertNotNull(response.get(AtlasClient.DEFINITION));
      Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));

      String typesJson = response.getString(AtlasClient.DEFINITION);
      final TypesDef typesDef = TypesSerialization.fromJson(typesJson);
      List<HierarchicalTypeDefinition<ClassType>> hierarchicalTypeDefinitions =
          typesDef.classTypesAsJavaList();
      for (HierarchicalTypeDefinition<ClassType> classType : hierarchicalTypeDefinitions) {
        for (AttributeDefinition attrDef : classType.attributeDefinitions) {
          if ("name".equals(attrDef.name)) {
            assertEquals(attrDef.isIndexable, true);
            assertEquals(attrDef.isUnique, true);
          }
        }
      }
    }
  }
示例#28
0
  @Test
  public void shouldFilterLogEntriesOnEventId() throws Exception {
    DocumentModel doc = RestServerInit.getFile(1, session);

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("eventId", "documentModified");
    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(1, nodes.size());
    assertEquals("documentModified", nodes.get(0).get("eventId").getValueAsText());

    queryParams.putSingle("principalName", "bender");
    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(0, nodes.size());
  }
  @Test
  public void testSubmit() throws Exception {
    for (HierarchicalTypeDefinition typeDefinition : typeDefinitions) {
      String typesAsJSON = TypesSerialization.toJson(typeDefinition);
      System.out.println("typesAsJSON = " + typesAsJSON);

      WebResource resource = service.path("api/atlas/types");

      ClientResponse clientResponse =
          resource
              .accept(Servlets.JSON_MEDIA_TYPE)
              .type(Servlets.JSON_MEDIA_TYPE)
              .method(HttpMethod.POST, ClientResponse.class, typesAsJSON);
      assertEquals(clientResponse.getStatus(), Response.Status.CREATED.getStatusCode());

      String responseAsString = clientResponse.getEntity(String.class);
      Assert.assertNotNull(responseAsString);

      JSONObject response = new JSONObject(responseAsString);
      JSONArray typesAdded = response.getJSONArray(AtlasClient.TYPES);
      assertEquals(typesAdded.length(), 1);
      assertEquals(typesAdded.getJSONObject(0).getString("name"), typeDefinition.typeName);
      Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));
    }
  }
  /**
   * Get the URL of the file to download. This has not been modified from the original version.
   *
   * <p>For more information, please see: <a href=
   * "https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-portal-help#features">
   * https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-
   * portal-help#features</a>
   *
   * <p>Original code can be accessed at: <a href=
   * "https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip">
   * https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip </a>
   *
   * @see #login(String, String)
   * @see org.collegeboard.scoredwnld.client.FileInfo
   * @author CollegeBoard
   * @param accessToken Access token obtained from {@link #login(String, String)}
   * @param filePath File to download
   * @return FileInfo descriptor of file to download
   */
  private FileInfo getFileUrlByToken(String accessToken, String filePath) {

    Client client = getClient();
    WebResource webResource =
        client.resource(
            scoredwnldUrlRoot + "/pascoredwnld/file?tok=" + accessToken + "&filename=" + filePath);
    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    try {
      JSONObject json = new JSONObject(response.getEntity(String.class));
      FileInfo fileInfo = new FileInfo();
      fileInfo.setFileName(filePath);
      fileInfo.setFileUrl(String.valueOf(json.get("fileUrl")));
      return fileInfo;
    } catch (ClientHandlerException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    } catch (UniformInterfaceException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    } catch (JSONException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    }

    return null;
  }