1 5 package net.sourceforge.jwebunit; 6 7 import com.meterware.httpunit.*; 8 import com.meterware.httpunit.cookies.CookieJar; 9 10 import net.sourceforge.jwebunit.util.ExceptionUtility; 11 import org.w3c.dom.*; 12 import org.xml.sax.SAXException ; 13 14 import java.io.IOException ; 15 import java.io.PrintStream ; 16 import java.util.ArrayList ; 17 import java.util.HashMap ; 18 import java.util.List ; 19 import java.util.Map ; 20 21 29 public class HttpUnitDialog { 30 private WebClient wc; 31 private WebResponse resp; 32 private TestContext context; 33 private WebForm form; 34 private Map multiselectMap = new HashMap (); 35 36 44 public HttpUnitDialog(String initialURL, TestContext context) { 45 this.context = context; 46 initWebClient(); 47 try { 48 resp = wc.getResponse(new GetMethodWebRequest(initialURL)); 49 } catch (Exception e) { 50 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 51 } 52 } 53 54 private void initWebClient() { 55 wc = (context != null) ? context.getWebClient() : new WebConversation(); 56 57 wc.addClientListener(new WebClientListener() { 58 public void requestSent(WebClient webClient, WebRequest webRequest) { 59 } 60 61 public void responseReceived(WebClient webClient, WebResponse webResponse) { 62 resp = webClient.getCurrentPage(); 63 form = null; 64 multiselectMap.clear(); 65 } 66 }); 67 } 68 73 public WebWindow getWindow(String windowName) { 74 return wc.getOpenWindow(windowName); 75 } 76 79 public WebClient getWebClient() { 80 return wc; 81 } 82 83 86 public WebResponse getResponse() { 87 return resp; 88 } 89 90 94 public String getResponseText() { 95 try { 96 return context.toEncodedString(resp.getText()); 97 } catch (IOException e) { 98 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 99 } 100 } 101 102 106 public String getResponsePageTitle() { 107 try { 108 return context.toEncodedString(resp.getTitle()); 109 } catch (SAXException e) { 110 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 111 } 112 } 113 114 117 private CookieJar getCookies() { 118 return (getResponse() != null) ? new CookieJar(getResponse()) : null; 119 } 120 121 public boolean hasCookie(String cookieName) { 122 CookieJar respJar = getCookies(); 123 String [] cookieNames = respJar.getCookieNames(); 124 125 for (int i = 0; i < cookieNames.length; i++) { 126 if (cookieNames[i].equals(cookieName)) { 127 return true; 128 } 129 } 130 return false; 131 } 132 133 public String getCookieValue(String cookieName) { 134 return getCookies().getCookieValue(cookieName); 135 } 136 137 139 162 public WebForm getForm() { 163 if (form == null && hasForm()) 164 setWorkingForm(getForm(0)); 165 return form; 166 } 167 168 private WebForm getForm(int formIndex) { 169 try { 170 return resp.getForms()[formIndex]; 171 } catch (SAXException e) { 172 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 173 } 174 } 175 176 private WebForm getForm(String nameOrID) { 177 try { 178 WebForm f = resp.getFormWithID(nameOrID); 179 return (f != null) ? f : resp.getFormWithName(nameOrID); 180 } catch (SAXException e) { 181 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 182 } 183 } 184 185 private WebForm getFormWithButton(String buttonName) { 186 if (hasForm()) { 187 for (int i = 0; i < getForms().length; i++) { 188 WebForm webForm = getForms()[i]; 189 if (webForm.getSubmitButton(buttonName) != null) 190 return webForm; 191 } 192 } 193 return null; 194 } 195 196 private WebForm getFormWithParameter(String paramName) { 197 if (hasForm()) { 198 for (int i = 0; i < getForms().length; i++) { 199 WebForm webForm = getForms()[i]; 200 String [] names = webForm.getParameterNames(); 201 for (int j = 0; j < names.length; j++) { 202 if (names[j].equals(paramName)) 203 return webForm; 204 } 205 206 } 207 } 208 return null; 209 } 210 211 private WebForm[] getForms() { 212 try { 213 return resp.getForms(); 214 } catch (SAXException e) { 215 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 216 } 217 } 218 219 private void checkFormStateWithParameter(String paramName) { 220 if (form == null) { 221 try { 222 setWorkingForm(getFormWithParameter(paramName)); 223 } catch (UnableToSetFormException e) { 224 throw new UnableToSetFormException("Unable to set form based on parameter [" + paramName + "]."); 225 } 226 } 227 } 228 229 private void checkFormStateWithButton(String buttonName) { 230 if (form == null) { 231 setWorkingForm(getFormWithButton(buttonName)); 232 } 233 } 234 235 242 public void setWorkingForm(String nameOrId) { 243 setWorkingForm(getForm(nameOrId)); 244 } 245 246 private void setWorkingForm(WebForm newForm) { 247 if (newForm == null) 248 throw new UnableToSetFormException("Attempted to set form to null."); 249 form = newForm; 250 } 251 252 255 public boolean hasForm() { 256 try { 257 return resp.getForms().length > 0; 258 } catch (SAXException e) { 259 e.printStackTrace(); 260 return false; 261 } 262 } 263 264 270 public boolean hasForm(String nameOrID) { 271 return getForm(nameOrID) != null; 272 } 273 274 280 public boolean hasFormParameterNamed(String paramName) { 281 try { 282 checkFormStateWithParameter(paramName); 283 } catch (UnableToSetFormException e) { 284 return false; 285 } 286 return getForm().hasParameterNamed(paramName); 287 } 288 289 297 public void setFormParameter(String paramName, String paramValue) { 298 checkFormStateWithParameter(paramName); 299 getForm().setParameter(paramName, paramValue); 300 } 301 302 public void updateFormParameter(String paramName, String paramValue) { 303 checkFormStateWithParameter(paramName); 304 if (!multiselectMap.containsKey(paramName)) 305 multiselectMap.put(paramName, new ArrayList ()); 306 List values = (List ) multiselectMap.get(paramName); 307 if (!values.contains(paramValue)) 308 values.add(paramValue); 309 getForm().setParameter(paramName, (String []) values.toArray(new String [0])); 310 } 311 312 318 public String getFormParameterValue(String paramName) { 319 checkFormStateWithParameter(paramName); 320 return getForm().getParameterValue(paramName); 321 } 322 323 330 public void removeFormParameter(String paramName) { 331 checkFormStateWithParameter(paramName); 332 getForm().removeParameter(paramName); 333 } 334 335 public void removeFormParameterWithValue(String paramName, String value) { 336 checkFormStateWithParameter(paramName); 337 if (multiselectMap.containsKey(paramName)) { 338 List values = (List ) multiselectMap.get(paramName); 339 values.remove(value); 340 getForm().setParameter(paramName, (String []) values.toArray(new String [0])); 341 } 342 } 343 344 350 public boolean hasFormParameterLabeled(String paramLabel) { 351 return null != getFormElementNameForLabel(paramLabel); 352 } 353 354 360 public String getFormElementNameForLabel(String formElementLabel) { 361 try { 362 Document document = getResponse().getDOM(); 363 Element root = document.getDocumentElement(); 364 NodeList forms = root.getElementsByTagName("form"); 365 366 for (int i = 0; i < forms.getLength(); i++) { 367 Element form = (Element) forms.item(i); 368 TextAndElementWalker walker = 369 new TextAndElementWalker(form, new String [] { "input", "select", "textarea" }); 370 Element formElement = walker.getElementAfterText(formElementLabel); 371 if (formElement != null) { 372 return formElement.getAttribute("name"); 373 } 374 } 375 376 return null; 377 } catch (SAXException e) { 378 e.printStackTrace(); 379 return null; 380 } 381 } 382 383 389 public SubmitButton getSubmitButton(String buttonName) { 390 checkFormStateWithButton(buttonName); 391 return getForm().getSubmitButton(buttonName); 392 } 393 394 public String getSubmitButtonValue(String buttonName) { 395 return getSubmitButton(buttonName).getValue().trim(); 396 } 397 398 public boolean hasSubmitButton(String buttonName) { 399 try { 400 return getSubmitButton(buttonName) != null; 401 } catch (UnableToSetFormException e) { 402 return false; 403 } 404 405 } 406 407 412 public Button getButton(String buttonId) { 413 return getForm().getButtonWithID(buttonId); 414 } 415 416 417 public boolean hasButton(String buttonId) { 418 try { 419 return getButton(buttonId) != null; 420 } catch (UnableToSetFormException e) { 421 return false; 422 } 423 } 424 425 431 public boolean isTextInResponse(String text) { 432 try { 433 return (context.toEncodedString(resp.getText()).indexOf(text) >= 0); 434 } catch (IOException e) { 435 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 436 } 437 } 438 439 447 public boolean isTextInTable(String tableSummaryOrId, String text) { 448 WebTable table = getWebTableBySummaryOrId(tableSummaryOrId); 449 if (table == null) { 450 throw new RuntimeException ("No table with summary or id [" + tableSummaryOrId + "] found in response."); 451 } 452 for (int row = 0; row < table.getRowCount(); row++) { 453 for (int col = 0; col < table.getColumnCount(); col++) { 454 TableCell cell = table.getTableCell(row, col); 455 if (cell != null) { 456 String cellHtml = getNodeHtml(cell.getDOM()); 457 if (cellHtml.indexOf(text) != -1) 458 return true; 459 } 460 } 461 } 462 return false; 463 } 464 465 private String getNodeHtml(Node node) { 466 String nodeHtml = ""; 467 NodeList children = node.getChildNodes(); 468 for (int i = 0; i < children.getLength(); i++) { 469 Node child = children.item(i); 470 if (child.getNodeType() == Node.ELEMENT_NODE) { 471 nodeHtml += "<" + child.getNodeName() + ">"; 472 } 473 if (child.hasChildNodes()) { 474 nodeHtml += getNodeHtml(child); 475 } else { 476 nodeHtml += child.getNodeValue(); 477 } 478 if (child.getNodeType() == Node.ELEMENT_NODE) { 479 nodeHtml += "</" + child.getNodeName() + ">"; 480 } 481 } 482 return context.toEncodedString(nodeHtml); 483 } 484 485 488 private static String getNodeText(Node node) { 489 String nodeText = ""; 490 NodeList children = node.getChildNodes(); 491 for (int i = 0; i < children.getLength(); i++) { 492 Node child = children.item(i); 493 if (child.hasChildNodes()) { 494 nodeText += getNodeText(child); 495 } else if (child.getNodeType() == Node.TEXT_NODE) { 496 nodeText += ((Text) child).getData(); 497 } 498 } 499 return nodeText; 500 } 501 502 509 public WebTable getWebTableBySummaryOrId(String tableSummaryOrId) { 510 WebTable table; 511 try { 512 table = resp.getTableWithSummary(tableSummaryOrId); 513 if (table == null) { 514 table = resp.getTableWithID(tableSummaryOrId); 515 } 516 } catch (SAXException e) { 517 e.printStackTrace(); 518 return null; 519 } 520 return table; 521 } 522 523 529 public String [][] getSparseTableBySummaryOrId(String tableSummaryOrId) { 530 WebTable table = getWebTableBySummaryOrId(tableSummaryOrId); 531 table.purgeEmptyCells(); 532 String [][] sparseTableCellValues = table.asText(); 533 return sparseTableCellValues; 534 } 535 536 540 public void submit() { 541 try { 542 resp = getForm().submit(); 543 } catch (Exception e) { 544 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 545 } 546 } 547 548 555 public void submit(String buttonName) { 556 try { 557 getForm().getSubmitButton(buttonName).click(); 558 resp = wc.getCurrentPage(); 559 } catch (Exception e) { 560 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 561 } 562 } 563 564 567 public void reset() { 568 getForm().reset(); 569 } 570 571 private void submitRequest(WebLink aLink) { 572 try { 573 aLink.click(); 574 resp = wc.getCurrentPage(); 575 } catch (Exception e) { 576 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 577 } 578 } 579 580 588 public boolean isLinkPresentWithText(String linkText) { 589 try { 590 return (resp.getLinkWith(linkText) != null); 591 } catch (SAXException e) { 592 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 593 } 594 } 595 596 606 public boolean isLinkPresentWithText(String linkText, int index) { 607 return getLinkWithText(linkText, index) != null; 608 } 609 610 617 public boolean isLinkPresentWithImage(String imageFileName) { 618 try { 619 return (resp.getFirstMatchingLink(new LinkImagePredicate(), imageFileName) != null); 620 } catch (SAXException e) { 621 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 622 } 623 } 624 625 631 public boolean isLinkPresent(String anId) { 632 try { 633 return resp.getLinkWithID(anId) != null; 634 } catch (SAXException e) { 635 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 636 } 637 } 638 639 646 public void clickLinkWithText(String linkText) { 647 WebLink link = null; 648 try { 649 link = resp.getLinkWith(linkText); 650 } catch (SAXException e) { 651 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 652 } 653 if (link == null) 654 throw new RuntimeException ("No Link found for \"" + linkText + "\""); 655 submitRequest(link); 656 } 657 658 public void clickLinkWithText(String linkText, int index) { 659 WebLink link = getLinkWithText(linkText, index); 660 if (link == null) 661 throw new RuntimeException ("No Link found for \"" + linkText + "\" with index " + index); 662 submitRequest(link); 663 } 664 665 private WebLink getLinkWithText(String linkText, int index) { 666 WebLink link = null; 667 try { 668 WebLink links[] = resp.getLinks(); 669 int count = 0; 670 for (int i = 0; i < links.length; ++i) { 671 Node node = links[i].getDOMSubtree(); 672 if (nodeContainsText(node, linkText)) { 673 if (count == index) { 674 link = links[i]; 675 break; 676 } else { 677 count++; 678 } 679 } 680 } 681 } catch (SAXException e) { 682 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 683 } 684 return link; 685 } 686 687 public static boolean nodeContainsText(Node node, String linkText) { 688 return getNodeText(node).indexOf(linkText) != -1; 689 } 690 691 public void clickLinkWithTextAfterText(String linkText, String labelText) { 692 WebLink link = getLinkWithTextAfterText(linkText, labelText); 693 if (link == null) 694 throw new RuntimeException ("No Link found for \"" + linkText + "\" with label \"" + labelText + "\""); 695 submitRequest(link); 696 } 697 698 private WebLink getLinkWithTextAfterText(String linkText, String labelText) { 699 try { 700 TextAndElementWalker walker = 701 new TextAndElementWalker(resp.getDOM().getDocumentElement(), new String [] { "a" }); 702 final Element linkElement = walker.getElementWithTextAfterText(linkText, labelText); 703 if (linkElement != null) { 704 return resp.getFirstMatchingLink(new SameLinkPredicate(), linkElement); 705 } 706 } catch (SAXException e) { 707 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 708 } 709 return null; 710 } 711 712 private static class SameLinkPredicate implements HTMLElementPredicate { 713 public boolean matchesCriteria(Object found, Object given) { 714 WebLink link = (WebLink) found; 715 Element foundElement = (Element) link.getDOMSubtree(); 716 Element givenElement = (Element) given; 717 718 NamedNodeMap foundAttributes = foundElement.getAttributes(); 719 NamedNodeMap givenAttributes = givenElement.getAttributes(); 720 721 if (foundAttributes.getLength() != givenAttributes.getLength()) { 722 return false; 723 } 724 725 for (int i = 0; i < foundAttributes.getLength(); i++) { 726 Attr foundAttribute = (Attr) foundAttributes.item(i); 727 Attr givenAttribute = (Attr) givenAttributes.getNamedItem(foundAttribute.getName()); 728 if (!foundAttribute.getValue().equals(givenAttribute.getValue())) { 729 return false; 730 } 731 } 732 733 return true; 734 } 735 } 736 737 744 public void clickLink(String anID) { 745 WebLink link = null; 746 try { 747 link = resp.getLinkWithID(anID); 748 } catch (SAXException e) { 749 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 750 } 751 if (link == null) 752 throw new RuntimeException ("No Link found with ID \"" + anID + "\""); 753 submitRequest(link); 754 755 } 756 757 765 public void clickLinkWithImage(String imageFileName) { 766 WebLink link = null; 767 try { 768 link = resp.getFirstMatchingLink(new LinkImagePredicate(), imageFileName); 769 } catch (SAXException e) { 770 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 771 } 772 if (link == null) 773 throw new RuntimeException ("No Link found with imageFileName \"" + imageFileName + "\""); 774 submitRequest(link); 775 } 776 777 782 public void clickButton(String buttonId) { 783 try { 784 getButton(buttonId).click(); 785 resp = wc.getCurrentPage(); 786 } catch (Exception e) { 787 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 788 } 789 } 790 791 799 public boolean hasRadioOption(String radioGroup, String radioOption) { 800 WebForm[] forms = getForms(); 801 for (int i = 0; i < forms.length; i++) { 802 WebForm form = forms[i]; 803 String [] opts = form.getOptionValues(radioGroup); 804 for (int j = 0; j < opts.length; j++) { 805 String opt = opts[j]; 806 if (radioOption.equals(opt)) 807 return true; 808 } 809 } 810 return false; 811 } 812 813 819 public String [] getOptionsFor(String selectName) { 820 return getForm().getOptions(selectName); 821 } 822 823 829 public String [] getOptionValuesFor(String selectName) { 830 return getForm().getOptionValues(selectName); 831 } 832 833 839 public String getSelectedOption(String selectName) { 840 String val = getFormParameterValue(selectName); 841 String [] vals = getOptionValuesFor(selectName); 842 for (int i = 0; i < vals.length; i++) { 843 if (vals[i].equals(val)) 844 return getOptionsFor(selectName)[i]; 845 } 846 return null; 847 } 848 849 857 public String getValueForOption(String selectName, String option) { 858 String [] opts = getOptionsFor(selectName); 859 for (int i = 0; i < opts.length; i++) { 860 if (opts[i].equals(option)) 861 return getOptionValuesFor(selectName)[i]; 862 } 863 throw new RuntimeException ("Unable to find option " + option + " for " + selectName); 864 } 865 866 874 public void selectOption(String selectName, String option) { 875 setFormParameter(selectName, getValueForOption(selectName, option)); 876 } 877 878 884 public Element getElement(String anID) { 885 try { 886 return walkDOM(getResponse().getDOM().getDocumentElement(), anID); 887 } catch (Exception e) { 888 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 889 } 890 } 891 892 private Element walkDOM(Element element, String anID) { 893 if (element.getAttribute("id").equals(anID) || element.getAttribute("ID").equals(anID)) 894 return element; 895 NodeList children = element.getChildNodes(); 896 for (int i = 0; i < children.getLength(); i++) { 897 Node child = children.item(i); 898 if (child.getNodeType() == Node.ELEMENT_NODE) { 899 Element el = walkDOM((Element) child, anID); 900 if (el != null) 901 return el; 902 } 903 } 904 return null; 905 } 906 907 915 public boolean isTextInElement(Element element, String text) { 916 NodeList children = element.getChildNodes(); 917 for (int i = 0; i < children.getLength(); i++) { 918 Node child = children.item(i); 919 if (child.getNodeType() == Node.TEXT_NODE) { 920 if (((Text) child).getData().indexOf(text) != -1) 921 return true; 922 } 923 924 if (child.getNodeType() == Node.ELEMENT_NODE) { 925 if (isTextInElement((Element) child, text)) 926 return true; 927 } 928 } 929 return false; 930 } 931 932 937 public void gotoWindow(String windowName) { 938 setMainWindow(getWindow(windowName)); 939 } 940 941 944 public void gotoRootWindow() { 945 setMainWindow(wc.getOpenWindows()[0]); 946 } 947 948 private void setMainWindow(WebWindow win) { 949 wc.setMainWindow(win); 950 resp = wc.getMainWindow().getCurrentPage(); 951 } 952 953 958 public void gotoFrame(String frameName) { 959 resp = getFrame(frameName); 960 form=null; 961 } 962 963 968 public WebResponse getFrame(String frameName) { 969 return wc.getMainWindow().getFrameContents(frameName); 970 } 971 972 975 public void gotoPage(String url) { 976 try { 977 resp = wc.getResponse(url); 978 } catch (Exception e) { 979 throw new RuntimeException (ExceptionUtility.stackTraceToString(e)); 980 } 981 } 982 983 988 public void dumpCookies(PrintStream stream) { 989 CookieJar respJar = getCookies(); 990 String [] cookieNames = respJar.getCookieNames(); 991 for (int i = 0; i < cookieNames.length; i++) 992 stream.print(cookieNames[i] + " : [" + respJar.getCookieValue(cookieNames[i]) + "]\n"); 993 } 994 995 1000 public void dumpResponse() { 1001 dumpResponse(System.out); 1002 } 1003 1004 1009 public void dumpResponse(PrintStream stream) { 1010 try { 1011 stream.println(getResponseText()); 1012 } catch (Exception e) { 1013 e.printStackTrace(); 1014 throw new RuntimeException (e.getMessage()); 1015 } 1016 } 1017 1018 1024 public void dumpTable(String tableNameOrId, PrintStream stream) { 1025 dumpTable(tableNameOrId, getSparseTableBySummaryOrId(tableNameOrId), stream); 1026 } 1027 1028 1034 public void dumpTable(String tableNameOrId, String [][] table) { 1035 dumpTable(tableNameOrId, table, System.out); 1036 } 1037 1038 1045 public void dumpTable(String tableNameOrId, String [][] table, PrintStream stream) { 1046 stream.print("\n" + tableNameOrId + ":"); 1047 for (int i = 0; i < table.length; i++) { 1048 String [] cell = table[i]; 1049 stream.print("\n\t"); 1050 for (int j = 0; j < cell.length; j++) { 1051 stream.print("[" + cell[j] + "]"); 1052 } 1053 } 1054 } 1055 1056} 1057 | Popular Tags |