コード例 #1
0
  @Test
  public void testDeleteNonEmptyDirectory() throws CoreException, IOException, SAXException {
    String dirPath1 = "sample/directory/path/sample1" + System.currentTimeMillis();
    String dirPath2 = "sample/directory/path/sample2" + System.currentTimeMillis();
    String fileName = "subfile.txt";
    String subDirectory = "subdirectory";

    createDirectory(dirPath1);
    createFile(dirPath1 + "/" + fileName, "Sample file content");
    createDirectory(dirPath2 + "/" + subDirectory);

    WebRequest request = getDeleteFilesRequest(dirPath1);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(
        "Could not delete directory with file",
        HttpURLConnection.HTTP_OK,
        response.getResponseCode());

    assertFalse(
        "Delete directory with file request returned OK, but the file still exists",
        checkDirectoryExists(dirPath1));

    request = getDeleteFilesRequest(dirPath2);
    response = webConversation.getResponse(request);
    assertEquals(
        "Could not delete directory with subdirectory",
        HttpURLConnection.HTTP_OK,
        response.getResponseCode());

    assertFalse(
        "Delete directory with subdirectory request returned OK, but the file still exists",
        checkDirectoryExists(dirPath2));
  }
コード例 #2
0
  @Test
  public void testCopyFileOverwrite() throws Exception {
    String directoryPath = "/testCopyFile/directory/path" + System.currentTimeMillis();
    String sourcePath = directoryPath + "/source.txt";
    String destName = "destination.txt";
    String destPath = directoryPath + "/" + destName;
    createDirectory(directoryPath);
    createFile(sourcePath, "This is the contents");
    createFile(destPath, "Original file");

    // with no-overwrite, copy should fail
    JSONObject requestObject = new JSONObject();
    addSourceLocation(requestObject, sourcePath);
    WebRequest request =
        getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "copy,no-overwrite");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, response.getResponseCode());

    // now omit no-overwrite and copy should succeed and return 200 instead of 201
    request = getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "copy");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject responseObject = new JSONObject(response.getText());
    checkFileMetadata(responseObject, destName, null, null, null, null, null, null, null);
    assertTrue(checkFileExists(sourcePath));
    assertTrue(checkFileExists(destPath));
  }
コード例 #3
0
  @Test
  public void testRoom() throws Exception {
    // create room
    WebRequest request =
        new PostMethodWebRequest(
            getCreateUrl(),
            new ByteArrayInputStream(objectMapper.writeValueAsString(baseRoom).getBytes()),
            MediaType.APPLICATION_JSON_VALUE);
    WebResponse response = conversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    assertEquals(MediaType.APPLICATION_JSON_VALUE, response.getContentType());
    Room room = objectMapper.readValue(response.getText(), Room.class);
    assertNotNull(room);
    assertTrue(room.getId() != 0);
    assertTrue(compare(baseRoom, room, "id"));

    // update room
    baseRoom = room;
    baseRoom.setName("New name");
    request =
        new PutMethodWebRequest(
            getUpdateUrl(),
            new ByteArrayInputStream(objectMapper.writeValueAsString(baseRoom).getBytes()),
            MediaType.APPLICATION_JSON_VALUE);
    response = conversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals(MediaType.APPLICATION_JSON_VALUE, response.getContentType());
    room = objectMapper.readValue(response.getText(), Room.class);
    assertNotNull(room);
    assertEquals(room, baseRoom);

    // get room
    request = new GetMethodWebRequest(getViewUrl(baseRoom.getId()));
    response = conversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals(MediaType.APPLICATION_JSON_VALUE, response.getContentType());
    room = objectMapper.readValue(response.getText(), Room.class);
    assertNotNull(room);
    assertEquals(room, baseRoom);

    // remove room
    request =
        new WebRequest(getDeleteUrl(baseRoom.getId())) {

          @Override
          public String getMethod() {
            return RequestMethod.DELETE.toString();
          }
        };
    response = conversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // check removed
    URL url = new URL(getViewUrl(baseRoom.getId()));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.connect();
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, connection.getResponseCode());
  }
コード例 #4
0
ファイル: HelperClass.java プロジェクト: arpavan/LeaveApp
  public WebResponse loginForm(String username, String password) throws Exception {
    WebConversation conversation = new WebConversation();
    HttpUnitOptions.setScriptingEnabled(false);
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    WebRequest request = new GetMethodWebRequest("http://localhost:8084/LeaveApp/index.jsp");
    WebResponse response = conversation.getResponse(request);
    WebForm loginform = response.getForms()[0];
    loginform.setParameter("username", username);
    loginform.setParameter("password", password);
    request = loginform.getRequest("submitbutton");
    response = conversation.getResponse(request);

    return response;
  }
コード例 #5
0
ファイル: WebQQClient.java プロジェクト: lineageii/qq
  @SuppressWarnings("unchecked")
  public List<Group> getAllGroups() throws Exception {
    // {"vfwebqq":"3e99140e076c4dc3c8a774f1e3a37518055f3f39f94428a8eaa07c1f7c0ebfea3a18792878f2c061"}

    String url = "http://s.web2.qq.com/api/get_group_name_list_mask2";
    String content = "{\"vfwebqq\":\"" + vfwebqq + "\"}";
    PostMethodWebRequest post = new PostMethodWebRequest(url);
    post.setParameter("r", content);

    wc.setHeaderField("Referer", "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2");

    WebResponse rs = wc.getResponse(post);
    log.info("sendMsg response:" + rs.getText());

    List<Group> groups = new ArrayList<Group>();

    JSONObject retJson = new JSONObject(rs.getText());
    if (retJson.getInt("retcode") == 0) {
      JSONArray infos = retJson.getJSONObject("result").getJSONArray("gnamelist");
      for (int i = 0; i < infos.length(); i++) {
        JSONObject obj = infos.getJSONObject(i);
        Group group = new Group();
        group.setGid(obj.getString("gid"));
        group.setName(obj.getString("name"));
        group.setCode(obj.getString("code"));
        groups.add(group);
      }
    }
    return groups;
  }
コード例 #6
0
  @Test
  public void testCreateTopLevelFile()
      throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample" + System.currentTimeMillis();
    createDirectory(directoryPath);
    String fileName = "testfile.txt";

    WebRequest request =
        getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName);
    WebResponse response = webConversation.getResponse(request);

    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    assertTrue(
        "Create file response was OK, but the file does not exist",
        checkFileExists(directoryPath + "/" + fileName));
    assertEquals(
        "Response should contain file metadata in JSON, but was " + response.getText(),
        "application/json",
        response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No file information in responce", responseObject);
    checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null);

    // should be able to perform GET on location header to obtain metadata
    String location = response.getHeaderField("Location");
    request = getGetFilesRequest(location + "?parts=meta");
    response = webConversation.getResource(request);
    assertNotNull(location);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    responseObject = new JSONObject(response.getText());
    assertNotNull("No direcory information in responce", responseObject);
    checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null);
  }
コード例 #7
0
  @Test
  public void testCreateDirectory() throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);

    String dirName = "testdir";
    webConversation.setExceptionsThrownOnErrorStatus(false);

    WebRequest request =
        getPostFilesRequest(directoryPath, getNewDirJSON(dirName).toString(), dirName);
    WebResponse response = webConversation.getResponse(request);

    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    assertTrue(
        "Create directory response was OK, but the directory does not exist",
        checkDirectoryExists(directoryPath + "/" + dirName));
    assertEquals(
        "Response should contain directory metadata in JSON, but was " + response.getText(),
        "application/json",
        response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No directory information in response", responseObject);
    checkDirectoryMetadata(responseObject, dirName, null, null, null, null, null);

    // should be able to perform GET on location header to obtain metadata
    String location = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
    request = getGetFilesRequest(location);
    response = webConversation.getResource(request);
    assertNotNull(location);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    responseObject = new JSONObject(response.getText());
    assertNotNull("No direcory information in responce", responseObject);
    checkDirectoryMetadata(responseObject, dirName, null, null, null, null, null);
  }
コード例 #8
0
  @Test
  public void testReadDirectoryChildren()
      throws CoreException, IOException, SAXException, JSONException {
    String dirName = "path" + System.currentTimeMillis();
    String directoryPath = "sample/directory/" + dirName;
    createDirectory(directoryPath);

    String subDirectory = "subdirectory";
    createDirectory(directoryPath + "/" + subDirectory);

    String subFile = "subfile.txt";
    createFile(directoryPath + "/" + subFile, "Sample file");

    WebRequest request = getGetFilesRequest(directoryPath + "?depth=1");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));

    assertEquals("Wrong number of directory children", 2, children.size());

    for (JSONObject child : children) {
      if (child.getBoolean("Directory")) {
        checkDirectoryMetadata(child, subDirectory, null, null, null, null, null);
      } else {
        checkFileMetadata(child, subFile, null, null, null, null, null, null, null);
      }
    }
  }
コード例 #9
0
ファイル: TC18.java プロジェクト: Ronak20/librarymanagement
  public void testDeleteUserWithLoan() throws Exception {
    logger.info("Entered TC18 testDeleteUserWithLoan");
    User user;
    String parameterUserName = "******" + System.currentTimeMillis();
    String IsbnName = "testISBN" + System.currentTimeMillis();
    user = new User("TestFirstName", "TestLastName", parameterUserName, "password", Role.STUDENT);
    String parameterBookName = "MyBook" + System.currentTimeMillis();
    userService.saveOrUpdate(user);
    Book book = new Book(parameterBookName, IsbnName, 2);
    bookService.saveOrUpdate(book);
    session.refresh(book);
    logger.info("User added" + user.getUsername());
    // now create loan for this user
    Calendar now = Calendar.getInstance();
    now.add(Calendar.MINUTE, 5);
    logger.info("Book " + book.getBookid() + " user " + user.getUserId());

    Loan loan = new Loan(user.getUserId(), book.getBookid(), now.getTime(), 0, 10, false);
    loandao.saveOrUpdate(loan);
    loanId = loan.getLoanId();
    bookId = book.getBookid();
    userId = user.getUserId();
    logger.debug("Loan " + loan.getLoanId() + " created for user " + user.getUserId());
    logger.info("Loan created: " + loan.getLoanId());
    logger.info("trying to delete userID: " + user.getUserId());
    WebConversation conversation = new WebConversation();
    WebRequest requestDeleteUser =
        new GetMethodWebRequest(Constant.DELETE_USER_URL + user.getUserId());
    WebResponse responseGetUser = conversation.getResponse(requestDeleteUser);
    WebTable bookListUpdatedTable = responseGetUser.getTableWithID("userListTable");
    TableCell tableUpdatedCell = bookListUpdatedTable.getTableCellWithID(user.getUserId());
    assertEquals(tableUpdatedCell.getText(), user.getUserId());
    logger.info("Exited TC18 testDeleteUserWithLoan");
  }
コード例 #10
0
  /** Tests that we are not allowed to get metadata files */
  @Test
  public void testGetForbiddenFiles() throws IOException, SAXException, BackingStoreException {
    // enable global anonymous read
    IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode(ServerConstants.PREFERENCE_SCOPE);
    String oldValue = prefs.get(ServerConstants.CONFIG_FILE_ANONYMOUS_READ, null);
    prefs.put(ServerConstants.CONFIG_FILE_ANONYMOUS_READ, "true");
    prefs.flush();
    try {
      // should not be allowed to get at file root
      WebRequest request = new GetMethodWebRequest(SERVER_LOCATION + FILE_SERVLET_LOCATION);
      setAuthentication(request);
      WebResponse response = webConversation.getResponse(request);
      assertEquals(
          "Should not be able to get the root",
          HttpURLConnection.HTTP_FORBIDDEN,
          response.getResponseCode());

      // should not be allowed to access the metadata directory
      request = new GetMethodWebRequest(SERVER_LOCATION + FILE_SERVLET_LOCATION + ".metadata");
      setAuthentication(request);
      response = webConversation.getResponse(request);
      assertEquals(
          "Should not be able to get metadata",
          HttpURLConnection.HTTP_FORBIDDEN,
          response.getResponseCode());

      // should not be allowed to read specific metadata files
      request =
          new GetMethodWebRequest(
              SERVER_LOCATION
                  + FILE_SERVLET_LOCATION
                  + ".metadata/.plugins/org.eclipse.orion.server.user.securestorage/user_store");
      setAuthentication(request);
      response = webConversation.getResponse(request);
      assertEquals(
          "Should not be able to get metadata",
          HttpURLConnection.HTTP_FORBIDDEN,
          response.getResponseCode());
    } finally {
      // reset the preference we messed with for the test
      if (oldValue == null) prefs.remove(ServerConstants.CONFIG_FILE_ANONYMOUS_READ);
      else prefs.put(ServerConstants.CONFIG_FILE_ANONYMOUS_READ, oldValue);
      prefs.flush();
    }
  }
コード例 #11
0
  @Test
  public void testDirectoryWithSpaces() throws CoreException, IOException, SAXException {
    String basePath = "sampe/dir with spaces/long" + System.currentTimeMillis();
    createDirectory(basePath);

    WebRequest request = getGetFilesRequest(basePath);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
  }
コード例 #12
0
ファイル: WebQQClient.java プロジェクト: lineageii/qq
 public String getUserFriends(String url) throws Exception {
   // String url = "http://s.web2.qq.com/api/get_user_friends2";
   PostMethodWebRequest post = new PostMethodWebRequest(url);
   String r = "{\"h\":\"hello\",\"vfwebqq\":\"" + this.vfwebqq + "\"}";
   post.setParameter("r", r);
   WebResponse rs = wc.getResponse(post);
   log.info("getUserFriends2 response:" + rs.getText());
   return rs.getText();
 }
コード例 #13
0
  private void doTest(String actualJSONDataURL, String expectedXMLDataURL) throws Exception {

    WebConversation wc = new WebConversation();

    WebRequest jsonDataRequest =
        SecurityUtil.getSecuredRequest(
            wc, "http://127.0.0.1:" + AllTests.WEBAPP_PORT + actualJSONDataURL);
    WebResponse jsonDataResponse = wc.getResponse(jsonDataRequest);
    String actual = jsonDataResponse.getText();

    WebRequest xmlDataRequest =
        SecurityUtil.getSecuredRequest(
            wc, "http://127.0.0.1:" + AllTests.WEBAPP_PORT + expectedXMLDataURL);
    WebResponse xmlDataResponse = wc.getResponse(xmlDataRequest);

    String xml = xmlDataResponse.getText();
    String expected = JSONTranslator.translateXMLToJSON("application/json", null, xml);
    expected = "fun" + " && " + "fun" + "(" + expected + ")";

    Assert.assertEquals(expected, actual);
  }
コード例 #14
0
  @Test
  public void testReadDirectory() throws CoreException, IOException, SAXException, JSONException {
    String dirName = "path" + System.currentTimeMillis();
    String directoryPath = "sample/directory/" + dirName;
    createDirectory(directoryPath);

    WebRequest request = getGetFilesRequest(directoryPath);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    JSONObject dirObject = new JSONObject(response.getText());
    checkDirectoryMetadata(dirObject, dirName, null, null, null, null, null);
  }
コード例 #15
0
  @Test
  public void testDeleteEmptyDir() throws CoreException, IOException, SAXException {
    String dirPath = "sample/directory/path/sample" + System.currentTimeMillis();
    createDirectory(dirPath);

    WebRequest request = getDeleteFilesRequest(dirPath);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    assertFalse(
        "Delete request returned OK, but the directory still exists",
        checkDirectoryExists(dirPath));
  }
コード例 #16
0
ファイル: TranslatorUtil.java プロジェクト: BlueBody/Spark
  private static String useGoogleTranslator(String text, TranslationType type) {

    String response = "";
    String urlString =
        "http://translate.google.com/translate_t?text=" + text + "&langpair=" + type.getID();
    // disable scripting to avoid requiring js.jar
    HttpUnitOptions.setScriptingEnabled(false);

    // create the conversation object which will maintain state for us
    WebConversation wc = new WebConversation();

    // Obtain the google translation page
    WebRequest webRequest = new GetMethodWebRequest(urlString);
    // required to prevent a 403 forbidden error from google
    webRequest.setHeaderField("User-agent", "Mozilla/4.0");

    try {
      WebResponse webResponse = wc.getResponse(webRequest);
      // NodeList list = webResponse.getDOM().getDocumentElement().getElementsByTagName("div");
      try {
        NodeList list2 =
            XPathAPI.selectNodeList(webResponse.getDOM(), "//span[@id='result_box']/span/text()");

        for (int i = 0; i < list2.getLength(); ++i) {
          response = response + list2.item(i).getNodeValue() + " ";
        }

      } catch (TransformerException e) {
        Log.warning("Translator error", e);
      }

      //            int length = list.getLength();
      //            for (int i = 0; i < length; i++) {
      //                Element element = (Element)list.item(i);
      //                if ("result_box".equals(element.getAttribute("id"))) {
      //                    Node translation = element.getFirstChild();
      //                    if (translation != null) {
      //                        response = translation.getNodeValue();
      //                    }
      //                }
      //            }
    } catch (MalformedURLException e) {
      Log.error("Could not for url: " + e);
    } catch (IOException e) {
      Log.error("Could not get response: " + e);
    } catch (SAXException e) {
      Log.error("Could not parse response content: " + e);
    }

    return response;
  }
コード例 #17
0
  @Test
  public void testCreateFileOverwrite()
      throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);
    String fileName = "testfile.txt";

    WebRequest request =
        getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

    // creating again at the same location should succeed but return OK rather than CREATED
    request = getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // creating with no-overwrite should fail if it already exists
    request = getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName);
    request.setHeaderField("X-Create-Options", "no-overwrite");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, response.getResponseCode());
  }
コード例 #18
0
  @Test
  public void testReadFileContents() throws CoreException, IOException, SAXException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);
    String fileName = "sampleFile" + System.currentTimeMillis() + ".txt";
    String fileContent = "Sample File Cotnent " + System.currentTimeMillis();
    createFile(directoryPath + "/" + fileName, fileContent);

    WebRequest request = getGetFilesRequest(directoryPath + "/" + fileName);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    assertEquals("Invalid file content", fileContent, response.getText());
  }
コード例 #19
0
ファイル: TestClient.java プロジェクト: shaunkalley/games
 public static void doJoinGame(WebConversation client) throws Exception {
   System.out.println("Joining game...");
   WebResponse response = client.getResponse("http://127.0.0.1:8080/games/euchre?action=joinGame");
   for (String name : response.getHeaderFieldNames()) {
     System.out.println(
         "header: name=" + name + ", value=" + Arrays.toString(response.getHeaderFields(name)));
   }
   System.out.println("response code=" + response.getResponseCode());
   for (String name : response.getNewCookieNames()) {
     System.out.println(
         "new cookie: name=" + name + ", value=" + response.getNewCookieValue(name));
   }
   System.out.println("text=" + response.getText());
 }
コード例 #20
0
  @Test
  public void testCopyFileInvalidSource() throws Exception {
    String directoryPath = "/testCopyFile/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);

    JSONObject requestObject = new JSONObject();
    requestObject.put("Location", "/this/does/not/exist/at/all");
    WebRequest request =
        getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "copy");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
    JSONObject responseObject = new JSONObject(response.getText());
    assertEquals("Error", responseObject.get("Severity"));
  }
コード例 #21
0
ファイル: TestClient.java プロジェクト: shaunkalley/games
 public static void doAnonymousLogin(WebConversation client, String nickname) throws Exception {
   System.out.println("Logging in anonymously...");
   PostMethodWebRequest request =
       new PostMethodWebRequest("http://127.0.0.1:8080/games/anonLogin");
   request.setParameter("nickname", nickname);
   WebResponse response = client.getResponse(request);
   for (String name : response.getHeaderFieldNames()) {
     System.out.println(
         "header: name=" + name + ", value=" + Arrays.toString(response.getHeaderFields(name)));
   }
   System.out.println("response code=" + response.getResponseCode());
   for (String name : response.getNewCookieNames()) {
     System.out.println(
         "new cookie: name=" + name + ", value=" + response.getNewCookieValue(name));
   }
   System.out.println("text=" + response.getText());
 }
コード例 #22
0
ファイル: MyTest.java プロジェクト: bflavius/nb-soa
  public void testWSDL() throws Exception {
    WebConversation conversation = new WebConversation();
    String destination = testProps.getProperty("destination");
    if (destination != null && destination.length() > 0) {
      WebRequest request = new GetMethodWebRequest(destination + "?WSDL");

      WebResponse response = conversation.getResponse(request);

      int i = response.getContentLength();
      InputSource is = new InputSource(response.getInputStream());

      Document doc = builder.parse(is);

      doc.getDocumentElement();
      System.out.println("My test");
    }
  }
コード例 #23
0
  /**
   * @throws SAXException
   * @throws IOException
   * @throws MalformedURLException
   */
  private void postData(
      final RedmineRepositoryConfig config,
      final Project project,
      final SCMConnectorConfig scmConfig,
      final String username,
      final String password,
      final String scm) {
    LOGGER.info("Redmine add Repository: " + scmConfig.getScmUrl());

    // Check if Repository should be added
    if (!config.isAddRepositoryConfiguration()) {
      LOGGER.debug("Repository config is disabled");
      return;
    }

    List<Cookie> cookies = (List<Cookie>) _wt.getDialog().getCookies();
    for (Cookie cookie : cookies) {
      LOGGER.debug("Cookie: {}", cookie);
      _wc.putCookie(cookie.getName(), cookie.getValue());
    }

    PostMethodWebRequest form =
        new PostMethodWebRequest(
            config.getServer().getUrl() + "/projects/" + project.getName() + "/repositories");
    form.setParameter("authenticity_token", getAuthenticityToken(_wt.getPageSource()));
    form.setParameter("repository_scm", scm);
    form.setParameter("repository[url]", scmConfig.getProjectScmUrl(project.getName()));
    form.setParameter("repository[login]", username);
    form.setParameter("repository[password]", password);
    form.setParameter("commit", "Create");
    try {
      LOGGER.debug("Posting: {}", form);
      _wc.getResponse(form);
      LOGGER.debug("Posted");
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #24
0
ファイル: WebQQClient.java プロジェクト: lineageii/qq
  public void sendMsg(String to, String msgParam) throws Exception {
    String url = "http://s.web2.qq.com/channel/send_msg2";
    PostMethodWebRequest post = new PostMethodWebRequest(url);
    Message message = new Message();
    message.setTo(firendsRuid.get(to).getUin());
    message.setClientid("64768904");
    message.setPsessionid(this.psessionid);
    message.setContent(msgParam);
    String msg = new JSONObject(message).toString();
    post.setParameter("r", msg);
    WebResponse rs;

    // wc.putCookie("pgv_pvid", "6477164270");
    // wc.putCookie("pgv_flv", "10.1 r102");
    // wc.putCookie("pgv_info", "pgvReferrer=&ssid=s6494109392");

    rs = wc.getResponse(post);
    log.info("sendMsg response:" + rs.getText());
  }
コード例 #25
0
  @Test
  public void testDeleteFile() throws CoreException, IOException, SAXException {
    String dirPath = "sample/directory/path";
    String fileName = System.currentTimeMillis() + ".txt";
    String filePath = dirPath + "/" + fileName;

    createDirectory(dirPath);
    createFile(filePath, "Sample file content");

    WebRequest request = getDeleteFilesRequest(filePath);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    assertFalse("Delete request returned OK, but the file still exists", checkFileExists(filePath));

    assertTrue(
        "File was deleted but the above directory was deleted as well",
        checkDirectoryExists(dirPath));
  }
コード例 #26
0
 @Test
 public void testCopyFileNoOverwrite() throws Exception {
   String directoryPath = "/testCopyFile/directory/path" + System.currentTimeMillis();
   String sourcePath = directoryPath + "/source.txt";
   String destName = "destination.txt";
   String destPath = directoryPath + "/" + destName;
   createDirectory(directoryPath);
   createFile(sourcePath, "This is the contents");
   JSONObject requestObject = new JSONObject();
   addSourceLocation(requestObject, sourcePath);
   WebRequest request =
       getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
   request.setHeaderField("X-Create-Options", "copy");
   WebResponse response = webConversation.getResponse(request);
   assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
   JSONObject responseObject = new JSONObject(response.getText());
   checkFileMetadata(responseObject, destName, null, null, null, null, null, null, null);
   assertTrue(checkFileExists(sourcePath));
   assertTrue(checkFileExists(destPath));
 }
コード例 #27
0
ファイル: WebQQClient.java プロジェクト: lineageii/qq
  /**
   * 发送群消息
   *
   * @param to
   * @param msgParam
   * @throws Exception
   */
  public void sendGroupMsg(String to, String msgParam) throws Exception {
    String url = "http://d.web2.qq.com/channel/send_qun_msg2";
    PostMethodWebRequest post = new PostMethodWebRequest(url);
    GroupMessage message = new GroupMessage();
    message.setGroup_uin(Long.valueOf(to));
    message.setClientid("64768904");
    message.setPsessionid(this.psessionid);
    message.setContent(msgParam);
    String msg = new JSONObject(message).toString();
    log.info(msg);
    post.setParameter("r", msg);
    post.setParameter("clientid", "64768904");
    post.setParameter("psessionid", this.psessionid);
    WebResponse rs;

    // wc.putCookie("pgv_pvid", "6477164270");
    // wc.putCookie("pgv_flv", "10.1 r102");
    // wc.putCookie("pgv_info", "pgvReferrer=&ssid=s6494109392");
    wc.setHeaderField("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=2");

    rs = wc.getResponse(post);
    log.info("sendMsg response:" + rs.getText());
  }
コード例 #28
0
  @Test
  public void testReadFileMetadata() throws Exception {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);
    String fileName = "sampleFile" + System.currentTimeMillis() + ".txt";
    String fileContent = "Sample File Cotnent " + System.currentTimeMillis();
    createFile(directoryPath + "/" + fileName, fileContent);

    WebRequest request = getGetFilesRequest(directoryPath + "/" + fileName + "?parts=meta");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject result = new JSONObject(response.getText());

    assertEquals(fileName, result.optString(ProtocolConstants.KEY_NAME));

    JSONArray parents = result.optJSONArray(ProtocolConstants.KEY_PARENTS);
    assertNotNull(parents);
    assertEquals(3, parents.length());
    IPath parentPath = new Path(directoryPath);
    // immediate parent
    JSONObject parent = parents.getJSONObject(0);
    assertEquals(parentPath.segment(2), parent.getString(ProtocolConstants.KEY_NAME));
    // grandparent
    parent = parents.getJSONObject(1);
    assertEquals(parentPath.segment(1), parent.getString(ProtocolConstants.KEY_NAME));

    // ensure all parent locations end with trailing slash
    for (int i = 0; i < parents.length(); i++) {
      parent = parents.getJSONObject(i);
      String location = parent.getString(ProtocolConstants.KEY_LOCATION);
      assertTrue(location.endsWith("/"));
      location = parent.getString(ProtocolConstants.KEY_CHILDREN_LOCATION);
      URI childrenLocation = new URI(location);
      assertTrue(childrenLocation.getPath().endsWith("/"));
    }
  }
コード例 #29
0
 public void testSimpleUser() throws Exception {
   WebConversation connection = new WebConversation();
   WebResponse loginPage = connection.getResponse(buildUrl("silverpeas/"));
   assertNotNull(loginPage);
   WebForm loginForm = loginPage.getFormWithName("EDform");
   assertNotNull(loginForm);
   loginForm.setParameter("Login", "SilverAdmin");
   loginForm.setParameter("Password", "SilverAdmin");
   HttpUnitOptions.setScriptingEnabled(false);
   WebResponse welcomePage = loginForm.submit();
   assertNotNull(welcomePage);
   String[] frameNames = welcomePage.getFrameNames();
   assertEquals(5, frameNames.length);
   WebResponse navigationFrame = connection.getFrameContents("bottomFrame");
   assertNotNull(navigationFrame);
   navigationFrame = connection.getFrameContents("SpacesBar");
   assertNotNull(navigationFrame);
   WebLink mailingListLink = navigationFrame.getLinkWith("Liste de diffusion");
   assertNotNull(mailingListLink);
   HttpUnitOptions.setScriptingEnabled(false);
   WebResponse activityPage = connection.getResponse(buildUrl(mailingListLink.getURLString()));
   assertNotNull(activityPage);
   WebTable browseBar = activityPage.getTableWithID("browseBar");
   assertNotNull(browseBar);
   assertEquals("MGI Coutier > Liste de diffusion > Activité", browseBar.getCellAsText(0, 0));
   assertEquals(
       "Main", browseBar.getTableCell(0, 0).getLinkWith("Liste de diffusion").getURLString());
   WebTable tableDescription = activityPage.getTableWithID("description");
   assertNotNull(tableDescription);
   String description = tableDescription.getCellAsText(1, 0);
   assertEquals("Liste de diffusion de test", description);
   WebTable tableAddress = activityPage.getTableWithID("subscribedAddress");
   assertNotNull(tableAddress);
   String subscribedAddress = tableAddress.getCellAsText(1, 0);
   assertEquals("*****@*****.**", subscribedAddress);
   WebTable tableHistory = activityPage.getTableWithID("activities");
   assertNotNull(tableHistory);
   assertEquals("Historique des Messages", tableHistory.getCellAsText(0, 0));
   assertEquals("2007", tableHistory.getCellAsText(2, 0));
   assertEquals("", tableHistory.getCellAsText(2, 1));
   assertEquals("", tableHistory.getCellAsText(2, 2));
   assertEquals("", tableHistory.getCellAsText(2, 3));
   assertEquals("", tableHistory.getCellAsText(2, 4));
   assertEquals("", tableHistory.getCellAsText(2, 5));
   assertEquals("", tableHistory.getCellAsText(2, 6));
   assertEquals("", tableHistory.getCellAsText(2, 7));
   assertEquals("", tableHistory.getCellAsText(2, 8));
   assertEquals("", tableHistory.getCellAsText(2, 9));
   assertEquals("", tableHistory.getCellAsText(2, 10));
   assertEquals("2", tableHistory.getCellAsText(2, 11));
   assertEquals("2", tableHistory.getCellAsText(2, 12));
   assertEquals("1", tableHistory.getCellAsText(3, 1));
   assertEquals("3", tableHistory.getCellAsText(3, 2));
   assertEquals("3", tableHistory.getCellAsText(3, 3));
   assertEquals("", tableHistory.getCellAsText(3, 4));
   assertEquals("", tableHistory.getCellAsText(3, 5));
   assertEquals("", tableHistory.getCellAsText(3, 6));
   assertEquals("", tableHistory.getCellAsText(3, 7));
   assertEquals("", tableHistory.getCellAsText(3, 8));
   assertEquals("", tableHistory.getCellAsText(3, 9));
   assertEquals("", tableHistory.getCellAsText(3, 10));
   assertEquals("", tableHistory.getCellAsText(3, 11));
   assertEquals("", tableHistory.getCellAsText(3, 12));
   assertEquals(
       "list/mailinglist45/currentYear/2007/currentMonth/11",
       tableHistory.getTableCell(2, 12).getLinkWith("2").getURLString());
   assertEquals(
       "list/mailinglist45/currentYear/2008/currentMonth/2",
       tableHistory.getTableCell(3, 3).getLinkWith("3").getURLString());
   WebTable tableMessages = activityPage.getTableWithID("messages");
   assertNotNull(tableMessages);
   assertEquals("Message récents", tableMessages.getCellAsText(0, 0));
   assertEquals("Simple database message 3", tableMessages.getCellAsText(1, 0));
   assertEquals(
       MESSAGE_BASE + 3,
       tableMessages.getTableCell(1, 0).getLinkWith("Simple database message 3").getURLString());
   assertEquals(
       "[email protected] - 02/03/2008 10:34:15", tableMessages.getCellAsText(2, 0));
   assertEquals(
       "Bonjour famille Simpson, j\'espère que vous allez bien. Ici "
           + "tout se passe bien et Krusty est très sympathique. Surtout depuis que "
           + "Tahiti Bob est retourné en prison. Je dois remplacer l\'homme canon "
           + "dans ...",
       tableMessages.getCellAsText(3, 0));
   assertEquals(MESSAGE_BASE + 3, tableMessages.getTableCell(3, 0).getLinks()[0].getURLString());
   assertEquals("Simple database message 4", tableMessages.getCellAsText(4, 0));
   assertEquals(
       MESSAGE_BASE + 4,
       tableMessages.getTableCell(4, 0).getLinkWith("Simple database message 4").getURLString());
   assertEquals(
       "[email protected] - 02/03/2008 10:12:15", tableMessages.getCellAsText(5, 0));
   assertEquals(
       "Bonjour famille Simpson, j\'espère que vous allez bien. Ici "
           + "tout se passe bien et Krusty est très sympathique. Surtout depuis que "
           + "Tahiti Bob est retourné en prison. Je dois remplacer l\'homme canon "
           + "dans ...",
       tableMessages.getCellAsText(6, 0));
   assertEquals(MESSAGE_BASE + 4, tableMessages.getTableCell(6, 0).getLinks()[0].getURLString());
   assertEquals("Simple database message 1", tableMessages.getCellAsText(7, 0));
   assertEquals(
       MESSAGE_BASE + 1,
       tableMessages.getTableCell(7, 0).getLinkWith("Simple database message 1").getURLString());
   assertEquals(
       "[email protected] - 01/03/2008 10:34:15", tableMessages.getCellAsText(8, 0));
   assertEquals(
       "Bonjour famille Simpson, j\'espère que vous allez bien. Ici "
           + "tout se passe bien et Krusty est très sympathique. Surtout depuis que "
           + "Tahiti Bob est retourné en prison. Je dois remplacer l\'homme canon "
           + "dans ...",
       tableMessages.getCellAsText(9, 0));
   assertEquals(MESSAGE_BASE + 1, tableMessages.getTableCell(9, 0).getLinks()[0].getURLString());
   assertEquals("Simple database message 11", tableMessages.getCellAsText(10, 0));
   assertEquals(
       MESSAGE_BASE + 11,
       tableMessages.getTableCell(10, 0).getLinkWith("Simple database message 11").getURLString());
   assertEquals(
       "[email protected] - 21/02/2008 10:34:15", tableMessages.getCellAsText(11, 0));
   assertEquals(
       "Bonjour famille Simpson, j\'espère que vous allez bien. Ici "
           + "tout se passe bien et Krusty est très sympathique. Surtout depuis que "
           + "Tahiti Bob est retourné en prison. Je dois remplacer l\'homme canon "
           + "dans ...",
       tableMessages.getCellAsText(12, 0));
   assertEquals(MESSAGE_BASE + 11, tableMessages.getTableCell(12, 0).getLinks()[0].getURLString());
   WebTable tableTabbedPane = activityPage.getTableWithID("tabbedPane");
   assertNotNull(tableTabbedPane);
   tableTabbedPane = tableTabbedPane.getTableCell(0, 0).getTables()[0];
   assertNotNull(tableTabbedPane);
   assertEquals("Activité", tableTabbedPane.getCellAsText(0, 2));
   assertEquals("Liste des Messages", tableTabbedPane.getCellAsText(0, 5));
   assertFalse(activityPage.getText().indexOf("Modération") > 0);
   assertFalse(activityPage.getText().indexOf("Abonnés Extérieurs") > 0);
 }
コード例 #30
0
  @Test
  public void testDirectoryDepth() throws CoreException, IOException, SAXException, JSONException {
    String basePath = "sampe/directory/long" + System.currentTimeMillis();
    String longPath = basePath + "/dir1/dir2/dir3/dir4";
    createDirectory(longPath);

    WebRequest request = getGetFilesRequest(basePath);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    assertEquals(
        "Directory information with depth = 0 return children",
        0,
        getDirectoryChildren(new JSONObject(response.getText())).size());

    request = getGetFilesRequest(basePath + "?depth=1");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    List<JSONObject> depthChildren = getDirectoryChildren(new JSONObject(response.getText()));

    assertEquals(
        "Directory information with depth = 1 returned too shallow", 1, depthChildren.size());
    checkDirectoryMetadata(depthChildren.get(0), "dir1", null, null, null, null, null);

    assertEquals(
        "Directory information with depth = 1 returned too deep",
        0,
        getDirectoryChildren(depthChildren.get(0)).size());

    request = getGetFilesRequest(basePath + "?depth=2");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    depthChildren =
        getDirectoryChildren(getDirectoryChildren(new JSONObject(response.getText())).get(0));

    assertEquals(
        "Directory information with depth = 2 returned too shallow", 1, depthChildren.size());

    checkDirectoryMetadata(depthChildren.get(0), "dir2", null, null, null, null, null);

    assertEquals(
        "Directory information with depth = 2 returned too deep",
        0,
        getDirectoryChildren(depthChildren.get(0)).size());

    request = getGetFilesRequest(basePath + "?depth=3");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    depthChildren =
        getDirectoryChildren(
            getDirectoryChildren(getDirectoryChildren(new JSONObject(response.getText())).get(0))
                .get(0));

    assertEquals(
        "Directory information with depth = 3 returned too shallow", 1, depthChildren.size());

    checkDirectoryMetadata(depthChildren.get(0), "dir3", null, null, null, null, null);

    assertEquals(
        "Directory information with depth = 3 returned too deep",
        0,
        getDirectoryChildren(depthChildren.get(0)).size());
  }