/**
   * 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 "";
  }
Ejemplo n.º 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\" "));
  }
Ejemplo n.º 4
0
  @RequestMapping("/getCatalog.html")
  public String getCatalog(Map<String, Object> model) {
    if (logger.isDebugEnabled()) {
      logger.debug("");
    }

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    String xml =
        service
            .path("rest")
            .path("product")
            .path("findall")
            .accept(MediaType.TEXT_XML)
            .get(String.class);
    ConvertXMLToObject convertXMLToObject = new ConvertXMLToObject(xml);
    XmlProductMsg productMsg = convertXMLToObject.xmlProductMsgToObjects();
    List<XmlProduct> lOfProducts = productMsg.getLOfProducts();
    CatalogForm catalogForm = new CatalogForm();
    catalogForm.setmOfProducts(lOfProducts);
    catalogForm.setShowLinks(false);
    catalogForm.setHeader("Full Catalogue");
    catalogForm.setCurrentPage("fullCatalogue");
    model.put("catalogForm", catalogForm);
    return "catalog";
  }
 @Test
 @SuppressWarnings("unchecked")
 public void getComponentSubscribersByAnAuthenticatedUser() throws Exception {
   WebResource resource = resource();
   UserDetailWithProfiles user = new UserDetailWithProfiles();
   user.setFirstName("Bart");
   user.setLastName("Simpson");
   user.setId("10");
   user.addProfile(COMPONENT_ID, SilverpeasRole.writer);
   user.addProfile(COMPONENT_ID, SilverpeasRole.user);
   String sessionKey = authenticate(user);
   SubscriptionService mockedSubscriptionService = mock(SubscriptionService.class);
   List<String> subscribers = Lists.newArrayList("5", "6", "7", "20");
   when(mockedSubscriptionService.getSubscribers(new ForeignPK("0", COMPONENT_ID)))
       .thenReturn(subscribers);
   getTestResources()
       .getMockableSubscriptionService()
       .setImplementation(mockedSubscriptionService);
   String[] entities =
       resource
           .path(SUBSCRIPTION_RESOURCE_PATH + "/subscribers/0")
           .header(HTTP_SESSIONKEY, sessionKey)
           .accept(MediaType.APPLICATION_JSON)
           .get(String[].class);
   assertNotNull(entities);
   assertThat(entities.length, is(4));
   assertThat(entities, is(new String[] {"5", "6", "7", "20"}));
 }
Ejemplo n.º 6
0
 @Test
 public void testJson() {
   System.out.println("::: testJson :::");
   WebResource resource = client.resource("http://localhost:20090/domain/0");
   SomeDomain domain = resource.get(SomeDomain.class);
   Assert.assertNotNull(domain);
 }
Ejemplo n.º 7
0
  public void testHead() throws Exception {
    startServer(Resource.class);

    WebResource r = Client.create().resource(getUri().path("/").build());

    ClientResponse cr = r.path("string").accept("text/plain").head();
    assertEquals(200, cr.getStatus());
    assertEquals(MediaType.TEXT_PLAIN_TYPE, cr.getType());
    assertFalse(cr.hasEntity());

    cr = r.path("byte").accept("application/octet-stream").head();
    assertEquals(200, cr.getStatus());
    String length = cr.getMetadata().getFirst("Content-Length");
    assertNotNull(length);
    assertEquals(3, Integer.parseInt(length));
    assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE, cr.getType());
    assertFalse(cr.hasEntity());

    cr = r.path("ByteArrayInputStream").accept("application/octet-stream").head();
    assertEquals(200, cr.getStatus());
    length = cr.getMetadata().getFirst("Content-Length");
    assertNotNull(length);
    assertEquals(3, Integer.parseInt(length));
    assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE, cr.getType());
    assertFalse(cr.hasEntity());
  }
 @Ignore
 public void b1_PrivateFile() {
   WebResource webResource = resource();
   ClientResponse response =
       webResource.path("repos/xjunit/private/private.txt").get(ClientResponse.class);
   assertResponse(response, ClientResponse.Status.FORBIDDEN);
 }
 @Ignore
 public void b1_PluginDNE() {
   WebResource webResource = resource();
   ClientResponse response =
       webResource.path("repos/non-existent-plugin/private/private.txt").get(ClientResponse.class);
   assertResponse(response, ClientResponse.Status.NOT_FOUND);
 }
Ejemplo n.º 10
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;
  }
Ejemplo n.º 11
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;
  }
Ejemplo n.º 12
0
 @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;
 }
Ejemplo n.º 13
0
  @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;
  }
Ejemplo n.º 14
0
 @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;
 }
 protected void createTestFolder(String pathId) {
   WebResource webResource = resource();
   // webResource.path("repo/dirs/" + pathId).put();
   ClientResponse response =
       webResource.path("repo/dirs/" + pathId).type(TEXT_PLAIN).put(ClientResponse.class);
   assertResponse(response, Status.OK);
 }
 @Ignore
 public void b1_FileDNE() {
   WebResource webResource = resource();
   ClientResponse response =
       webResource.path("repos/xjunit/public/doesnotexist.txt").get(ClientResponse.class);
   assertResponse(response, ClientResponse.Status.NOT_FOUND);
 }
  @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);
    }
  }
  @Test
  public void shouldNotRegisterUser() throws Exception {
    String email = "test.user.invalid.email.com";

    UserResult userResult;
    Client client = createClient();
    WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user");

    // Create request hash with email address
    HashMap<String, String> requestHash = new HashMap<String, String>();
    requestHash.put("email", email);

    // First email registration
    userResult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .post(UserResult.class, requestHash);

    // Should be failed with invalid email exception
    assertEquals(Status.INVALID_EMAIL, userResult.getStatus());
    assertFalse(userResult.isSuccess());

    assertNull(userResult.getUser());
  }
Ejemplo n.º 19
0
 @Test
 public void testFeedReader() {
   System.out.println("::: testFeedReader :::");
   final String rootFeedUriStr = "http://localhost:20090/feed";
   WebResource resource = client.resource(rootFeedUriStr);
   Feed feed = resource.get(Feed.class);
   FeedEntryReader<SomeDomain> reader =
       new FeedEntryReader<SomeDomain>(
           httpClient,
           Arrays.<Entry<String, String>>asList(
               new AbstractMap.SimpleEntry<String, String>(
                   Link.REL_ALTERNATE, MediaType.APPLICATION_JSON)),
           SomeDomain.class);
   Collection<EntityResource<SomeDomain>> collection = reader.readEntriesFromFeed(feed);
   Assert.assertNotNull(collection);
   Assert.assertEquals(5, collection.size());
   try {
     int newCount = 20;
     URI uri = new URI(rootFeedUriStr + "?count=" + newCount);
     feed = ClientUtil.readEntity(uri, httpClient, MediaType.APPLICATION_ATOM_XML, Feed.class);
     collection = reader.readEntriesFromFeed(feed);
     Assert.assertNotNull(collection);
     Assert.assertEquals(newCount, collection.size());
   } catch (Exception ex) {
     ex.printStackTrace();
     Assert.fail(ex.getMessage());
   }
 }
Ejemplo n.º 20
0
  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);
    }
  }
 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());
 }
Ejemplo n.º 22
0
  @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);
  }
Ejemplo n.º 23
0
  @RequestMapping("/myCatalog.html")
  public Object myCatalog(Map<String, Object> model) {
    if (logger.isDebugEnabled()) {
      logger.debug("");
    }
    XmlLogin login = (XmlLogin) model.get("loggedin");
    if (login == null || login.getUserId() == null) {
      return new ModelAndView("redirect:homepage.html");
    }
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());

    String xml =
        service
            .path("rest")
            .path("userproduct")
            .path("finduserproducts")
            .path(login.getUserId())
            .accept(MediaType.TEXT_XML)
            .get(String.class);
    ConvertXMLToObject convertXMLToObject = new ConvertXMLToObject(xml);
    XmlProductMsg productMsg = convertXMLToObject.xmlProductMsgToObjects();
    List<XmlProduct> lOfProducts = productMsg.getLOfProducts();
    CatalogForm catalogForm = new CatalogForm();
    catalogForm.setmOfProducts(lOfProducts);
    catalogForm.setShowLinks(true);
    catalogForm.setHeader("My Catalogue");
    catalogForm.setOrigin("");
    catalogForm.setCurrentPage("myCatalogue");
    model.put("catalogForm", catalogForm);
    return "catalog";
  }
Ejemplo n.º 24
0
  // 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);
    }
  }
 @Test
 @SuppressWarnings("unchecked")
 public void getComponentSubscriptionByAnAuthenticatedUser() throws Exception {
   WebResource resource = resource();
   UserDetailWithProfiles user = new UserDetailWithProfiles();
   user.setFirstName("Bart");
   user.setLastName("Simpson");
   user.setId("10");
   user.addProfile(COMPONENT_ID, SilverpeasRole.writer);
   user.addProfile(COMPONENT_ID, SilverpeasRole.user);
   String sessionKey = authenticate(user);
   SubscriptionService mockedSubscriptionService = mock(SubscriptionService.class);
   ComponentSubscription subscription = new ComponentSubscription("10", COMPONENT_ID);
   Collection<ComponentSubscription> subscriptions = Lists.newArrayList(subscription);
   when((Collection<ComponentSubscription>)
           mockedSubscriptionService.getUserSubscriptionsByComponent("10", COMPONENT_ID))
       .thenReturn(subscriptions);
   getTestResources()
       .getMockableSubscriptionService()
       .setImplementation(mockedSubscriptionService);
   SubscriptionEntity[] entities =
       resource
           .path(SUBSCRIPTION_RESOURCE_PATH)
           .header(HTTP_SESSIONKEY, sessionKey)
           .accept(MediaType.APPLICATION_JSON)
           .get(SubscriptionEntity[].class);
   assertNotNull(entities);
   assertThat(entities.length, is(1));
   assertThat(entities[0], SubscriptionEntityMatcher.matches((Subscription) subscription));
 }
Ejemplo n.º 26
0
  @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 = "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);
          }
        }
      }
    }
  }
  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);
    }
  }
  @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;
  }