public void testFileItemPersistence() throws Exception { // TODO: write a synchronous connector? byte[] testData = new byte[1024]; for (int i = 0; i < testData.length; i++) testData[i] = (byte) i; Server server = new Server(); SocketConnector connector = new SocketConnector(); server.addConnector(connector); ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(new ServletHolder(new FileItemPersistenceTestServlet()), "/"); server.addHandler(handler); server.start(); localPort = connector.getLocalPort(); try { WebClient wc = new WebClient(); HtmlPage p = (HtmlPage) wc.getPage("http://localhost:" + localPort + '/'); HtmlForm f = p.getFormByName("main"); HtmlFileInput input = (HtmlFileInput) f.getInputByName("test"); input.setData(testData); f.submit(); } finally { server.stop(); } }
/** @throws Exception on failure */ @Test public void unicode() throws Exception { startWebServer("./"); final WebClient client = getWebClient(); client.getPage( "http://localhost:" + PORT + "/src/test/resources/event_coordinates.html?param=\u00F6"); }
public static void sayit(int tc, String msg) { String tmsg[] = msg.split("<4;2>0:"); String player = tmsg[0]; player = player.toLowerCase().trim(); String u1 = props("muser1").toLowerCase(); String u2 = props("muser2").toLowerCase(); String u3 = props("muser3").toLowerCase(); String sname = props("server" + tc + "name"); if (TC1.ghost == 1 || TC2 != null && TC2.ghost == 1 || TC3 != null && TC3.ghost == 1) { tmsg[1] = tmsg[1] + "\n"; } if (!player.equals(u1) && !player.equals(u2) && !player.equals(u3)) { for (Entry<Integer, TelnetService> t : TNH.entrySet()) { if (tc != t.getValue().mynum) { TNH.get(t.getKey()) .write( "gos " + sname.substring(0, 1) + ": " + tmsg[0].trim() + ": " + tmsg[1].trim()); } } for (WebClient value : WebSocket.channels) { if (value != null) { value.send(sname + ": " + tmsg[0].trim() + ": " + tmsg[1].trim()); } } log = shift(log, tmsg[0].trim() + " gossips: " + tmsg[1].trim()); } }
public static WebClient buildWebClient(CookieManager manager) { WebClient webClient = buildWebClient(); webClient.setCookieManager(manager); return webClient; }
private void testTransfer() throws Exception { Server server = new Server(); server.setOut(new PrintStream(new ByteArrayOutputStream())); server.runTool("-web", "-webPort", "8182", "-properties", "null"); File transfer = new File("transfer"); transfer.mkdirs(); try { FileOutputStream f = new FileOutputStream("transfer/test.txt"); f.write("Hello World".getBytes()); f.close(); WebClient client = new WebClient(); String url = "http://localhost:8182"; String result = client.get(url); client.readSessionId(result); String test = client.get(url, "transfer/test.txt"); assertEquals("Hello World", test); new File("transfer/testUpload.txt").delete(); client.upload( url + "/transfer/testUpload.txt", "testUpload.txt", new ByteArrayInputStream("Hallo Welt".getBytes())); byte[] d = IOUtils.readBytesAndClose(new FileInputStream("transfer/testUpload.txt"), -1); assertEquals("Hallo Welt", new String(d)); new File("transfer/testUpload.txt").delete(); } finally { server.shutdown(); FileUtils.deleteRecursive("transfer", true); } }
public void testDoConfigure() throws Exception { UpdateSite target = new UpdateSite("test1", "http://example.com/test/update-center.json"); // Multiple update site. Jenkins.getInstance().getUpdateCenter().getSites().clear(); Jenkins.getInstance().getUpdateCenter().getSites().add(target); String originalId = target.getId(); WebClient wc = new WebClient(); HtmlPage editSitePage = wc.goTo(String.format("%s/%s", UpdateSitesManager.URL, target.getId())); HtmlForm editSiteForm = editSitePage.getFormByName("editSiteForm"); assertNotNull("There must be editSiteForm", editSiteForm); String newId = "newId"; String newUrl = "http://localhost/update-center.json"; editSiteForm.getInputByName("_.id").setValueAttribute(newId); editSiteForm.getInputByName("_.url").setValueAttribute(newUrl); submit(editSiteForm); UpdateSite site = null; for (UpdateSite s : Jenkins.getInstance().getUpdateCenter().getSites()) { if (newId.equals(s.getId())) { site = s; } assertFalse("id must be updated(old one must not remain)", originalId.equals(s.getId())); } assertNotNull("id must be updated", site); assertEquals("url must be updated", newUrl, site.getUrl()); }
public void testDoDelete() throws Exception { UpdateSite target = new UpdateSite("test1", "http://example.com/test/update-center.json"); Jenkins.getInstance().getUpdateCenter().getSites().clear(); Jenkins.getInstance().getUpdateCenter().getSites().add(target); int initialSize = Jenkins.getInstance().getUpdateCenter().getSites().size(); WebClient wc = new WebClient(); HtmlPage deleteSitePage = wc.goTo(String.format("%s/%s/delete", UpdateSitesManager.URL, target.getId())); assertEquals( "UpdateSite must not be deleted yet.", initialSize, Jenkins.getInstance().getUpdateCenter().getSites().size()); HtmlForm deleteSiteForm = deleteSitePage.getFormByName("deleteSiteForm"); assertNotNull("There must be deleteSiteForm", deleteSiteForm); submit(deleteSiteForm); assertEquals( "UpdateSite must be deleted.", initialSize - 1, Jenkins.getInstance().getUpdateCenter().getSites().size()); }
@LocalData public void testMatrixBuildSummary() throws Exception { Hudson hudson = Hudson.getInstance(); List<MatrixProject> projects = hudson.getAllItems(MatrixProject.class); MatrixProject testProject = null; for (MatrixProject project : projects) { System.out.println(project.getName()); if (project.getName().equals("matrix-robot")) testProject = project; } if (testProject == null) fail("Couldn't find example project"); Future<MatrixBuild> run = testProject.scheduleBuild2(0); while (!run.isDone()) { Thread.sleep(5); } Run lastBuild = testProject.getLastBuild(); assertTrue("Build wasn't a success", lastBuild.getResult() == Result.SUCCESS); WebClient wc = getWebClient(); HtmlPage page = wc.goTo("job/matrix-robot"); WebAssert.assertElementPresentByXPath( page, "//div[@id='navigation']//a[@href='/job/matrix-robot/robot']"); WebAssert.assertElementPresentByXPath(page, "//td[@id='main-panel']//img[@src='robot/graph']"); page = wc.goTo("job/matrix-robot/3"); WebAssert.assertElementPresentByXPath( page, "//div[@id='navigation']//a[@href='/job/matrix-robot/3/robot']"); WebAssert.assertElementPresentByXPath( page, "//td[@id='main-panel']//h4[contains(.,'Robot Test Summary:')]"); WebAssert.assertElementPresentByXPath( page, "//td[@id='main-panel']//a[@href='/job/matrix-robot/3/robot' and contains(text(),'Browse results')]"); }
private WebClient getWebClientWithWrongSocksProxy() { final WebClient client = getWebClient(); client .getOptions() .setProxyConfig(new ProxyConfig(SOCKS_PROXY_HOST, SOCKS_PROXY_PORT + 1, true)); return client; }
public void testLogInWithOpenIDAndSignUp() throws Exception { openid = createServer(); realm = new HudsonPrivateSecurityRealm(true); hudson.setSecurityRealm(realm); WebClient wc = new WebClient(); // Workaround failing ajax requests to build queue wc.setThrowExceptionOnFailingAjax(false); // Login with OpenID as an unregistered user HtmlPage login = wc.goTo("federatedLoginService/openid/login?from=/"); login .getDocumentElement() .getOneHtmlElementByAttribute("a", "title", "log in with OpenID") .click(); HtmlForm loginForm = getFormById(login, "openid_form"); loginForm.getInputByName("openid").setValueAttribute(openid.url); HtmlPage signUp = (HtmlPage) loginForm.submit(); // Sign up user HtmlForm signUpForm = getFormByAction(signUp, "/securityRealm/createAccountWithFederatedIdentity"); signUpForm.getInputByName("password1").setValueAttribute("x"); signUpForm.getInputByName("password2").setValueAttribute("x"); HtmlPage loggedIn = submit(signUpForm); assertNotNull(loggedIn.getAnchorByHref("/logout")); assertNotNull(loggedIn.getAnchorByHref("/user/aliceW")); wc.goTo("logout"); // Re-login login(wc); }
// Implementation methods // ------------------------------------------------------------------------- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { WebClient client = WebClient.getWebClient(request); Session session = client.getSession(); Queue queue = getQueue(request, session); if (queue == null) { throw new ServletException("No queue URI specified"); } String msgId = request.getParameter("msgId"); if (msgId == null) { MessageRenderer renderer = getMessageRenderer(request); configureRenderer(request, renderer); String selector = getSelector(request); QueueBrowser browser = session.createBrowser(queue, selector); renderer.renderMessages(request, response, browser); } else { XmlMessageRenderer renderer = new XmlMessageRenderer(); QueueBrowser browser = session.createBrowser(queue, "JMSMessageID='" + msgId + "'"); if (!browser.getEnumeration().hasMoreElements()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Message message = (Message) browser.getEnumeration().nextElement(); PrintWriter writer = response.getWriter(); renderer.renderMessage(writer, request, response, browser, message); writer.flush(); } } catch (JMSException e) { throw new ServletException(e); } }
private void doHttpsTest(final WebClient webClient) throws Exception { localServer_ = new InsecureHttpsServer(SocksProxyTestServlet.HTML); localServer_.start(); webClient.getOptions().setUseInsecureSSL(true); final String url = "https://" + localServer_.getHostName() + ":" + localServer_.getPort(); final HtmlPage page = webClient.getPage(url); assertEquals("hello", page.getTitleText()); }
/** {@inheritDoc} */ public void setEnclosedPage(final Page page) { if (page == enclosedPage_) { return; } destroyChildren(); enclosedPage_ = page; if (isJavaScriptInitializationNeeded()) { webClient_.initialize(this); } webClient_.initialize(page); }
@LocalData public void testMatrixBuildReportLinks() throws Exception { WebClient wc = getWebClient(); HtmlPage page = wc.goTo("job/matrix-robot/FOO=bar/2"); WebAssert.assertElementPresentByXPath( page, "//td[@id='main-panel']//a[@href='/job/matrix-robot/FOO=bar/2/robot' and contains(.,'Browse results')]"); WebAssert.assertElementPresentByXPath( page, "//td[@id='main-panel']//a[@href='/job/matrix-robot/FOO=bar/2/robot/report/report.html' and contains(.,'Open report.html')]"); }
/** Associates the OpenID identity of the user with {@link #realm}. */ private void associateUserWithOpenId(User u) throws Exception { WebClient wc = new WebClient().login(u.getId(), u.getId() /*assumes password==name*/); // Associate an OpenID with an existing user HtmlPage associated = wc.goTo("federatedLoginService/openid/startAssociate?openid=" + openid.url); assertTrue( associated.getDocumentURI().endsWith("federatedLoginService/openid/onAssociationSuccess")); OpenIdUserProperty p = u.getProperty(OpenIdUserProperty.class); assertEquals(1, p.getIdentifiers().size()); assertEquals(openid.getUserIdentity(), p.getIdentifiers().iterator().next()); }
/** * Tests Jetty. * * @throws Exception on failure */ @Test public void jettyProofOfConcept() throws Exception { startWebServer("./"); final WebClient client = getWebClient(); final Page page = client.getPage("http://localhost:" + PORT + "/src/test/resources/event_coordinates.html"); final WebConnection defaultConnection = client.getWebConnection(); Assert.assertTrue( "HttpWebConnection should be the default", HttpWebConnection.class.isInstance(defaultConnection)); Assert.assertTrue("Response should be valid HTML", HtmlPage.class.isInstance(page)); }
/** This test unit is for testing a commit hook using the UUID */ @Bug(399165) @Test public void testPrebuiltCommitTrigger() throws Exception { hudson.setCrumbIssuer(null); // First create repository with 1 file and commit information SVNCommitInfo info = createSVNRepository(); assertNull(info.getErrorMessage()); assertEquals("Failed to create 1 revision.", 1, info.getNewRevision()); // Create freestyle project with SVN SCM. FreeStyleProject project = createFreeStyleProject(); project.setScm(new SubversionSCM("file:///tmp/399165")); SCMTrigger trigger = new SCMTrigger("0 */6 * * *"); project.addTrigger(trigger); trigger.start(project, true); // Execute build (This is critical for fixing eclipse bug: 399165) assertBuildStatusSuccess(project.scheduleBuild2(0)); // Commit a file again. info = createSecondCommit(); assertNull(info.getErrorMessage()); assertEquals("Failed to create second commit.", 2, info.getNewRevision()); // Create post-commit hook WebClient wc = new WebClient(); WebRequestSettings wr = new WebRequestSettings( new URL( getURL() + "subversion/" + repository.getRepositoryUUID(false) + "/notifyCommit"), HttpMethod.POST); wr.setRequestBody("A dirB/file2.txt"); wr.setAdditionalHeader("Content-Type", "text/plain;charset=UTF-8"); wr.setAdditionalHeader("X-Hudson-Subversion-Revision", "2"); WebConnection conn = wc.getWebConnection(); System.out.println(wr); WebResponse resp = conn.getResponse(wr); assertTrue(isGoodHttpStatus(resp.getStatusCode())); waitUntilNoActivity(); FreeStyleBuild b = project.getLastBuild(); assertNotNull(b); assertBuildStatus(Result.SUCCESS, b); assertEquals("Failed to execute a buid.", 2, b.getNumber()); }
/** @see wicket.RequestCycle#onBeginRequest() */ @SuppressWarnings("nls") @Override protected void onBeginRequest() { WebClientSession webClientSession = (WebClientSession) getSession(); WebClient webClient = webClientSession.getWebClient(); if (webClient != null) { if (webClient.getSolution() != null) { MDC.put("clientid", webClient.getClientID()); MDC.put("solution", webClient.getSolution().getName()); } J2DBGlobals.setServiceProvider(webClient); webClient.onBeginRequest(webClientSession); } }
@LocalData public void testActionViewsWithNoRuns() throws Exception { WebClient wc = getWebClient(); HtmlPage page = wc.goTo("job/robot/"); WebAssert.assertElementPresentByXPath( page, "//div[@id='navigation']//a[@href='/job/robot/robot']"); WebAssert.assertElementPresentByXPath( page, "//td[@id='main-panel']//p[contains(.,'No results available yet.')]"); WebAssert.assertElementNotPresentByXPath( page, "//td[@id='main-panel']//img[@src='robot/graph']"); page = wc.goTo("job/robot/robot/"); WebAssert.assertTextPresent(page, "No robot results available yet!"); }
/** @see wicket.RequestCycle#onEndRequest() */ @SuppressWarnings("nls") @Override protected void onEndRequest() { J2DBGlobals.setServiceProvider(null); WebClientSession webClientSession = (WebClientSession) getSession(); WebClient webClient = webClientSession.getWebClient(); if (webClient != null) { try { webClient.onEndRequest(webClientSession); } finally { MDC.remove("clientid"); MDC.remove("solution"); } } }
/** @throws Exception if an error occurs */ @Test public void emptyPut() throws Exception { final Map<String, Class<? extends Servlet>> servlets = new HashMap<String, Class<? extends Servlet>>(); servlets.put("/test", EmptyPutServlet.class); startWebServer("./", null, servlets); final String[] expectedAlerts = {"1"}; final WebClient client = getWebClient(); client.setAjaxController(new NicelyResynchronizingAjaxController()); final List<String> collectedAlerts = new ArrayList<String>(); client.setAlertHandler(new CollectingAlertHandler(collectedAlerts)); client.getPage("http://localhost:" + PORT + "/test"); assertEquals(expectedAlerts, collectedAlerts); }
boolean needToAuthenticate() { if (getAuthenticationType() == null) return false; if (getCredentialsForRealm() != null) return true; if (!_client.getExceptionsThrownOnErrorStatus()) return false; throw createAuthorizationRequiredException(); }
@LocalData public void testNoConfigAccessWithPermissionEnabled() throws Exception { setPermissionEnabled(true); AuthorizationStrategy as = jenkins.getAuthorizationStrategy(); assertTrue( "Expecting GlobalMatrixAuthorizationStrategy", (as instanceof GlobalMatrixAuthorizationStrategy)); GlobalMatrixAuthorizationStrategy gas = (GlobalMatrixAuthorizationStrategy) as; assertFalse( "Bob should not have extended read for this test", gas.hasExplicitPermission("bob", Item.EXTENDED_READ)); WebClient wc = new WebClient().login("bob", "bob"); wc.assertFails("job/a/configure", HttpURLConnection.HTTP_FORBIDDEN); }
public AppAnnieCrawlerJava(String application, String store, String rankType, AuthObject auth) throws ParsingException { url = "http://www.appannie.com/app/" + (store.equals("appstore") ? "ios" : store) + "/" + application.replaceAll(" ", "-").toLowerCase() + "/ranking/#view=" + rankType + "&date="; WebClient webClient = buildWebClient(); HtmlPage page = null; try { page = webClient.getPage("https://www.appannie.com/account/login/"); } catch (IOException e) { e.printStackTrace(); // todo: throw exception } HtmlForm form = page.getFormByName(""); // authentication try { form.getInputByName("username").setValueAttribute(auth.username()); } catch (Throwable t) { throw new ParsingException( "Login form incorrect! Please check " + getClass().getName() + " for errors."); } try { form.getInputByName("password").setValueAttribute(auth.password()); } catch (Throwable t) { throw new ParsingException( "Login form incorrect! Please check " + getClass().getName() + " for errors."); } try { form.getButtonByName("").click(); } catch (IOException e) { throw new ParsingException( "Login form incorrect! Please check " + getClass().getName() + " for errors."); } cookieManager = webClient.getCookieManager(); }
protected void sendMessage(WebClient client, String[] stocks) throws JMSException { Session session = client.getSession(); int idx = 0; while (true) { idx = (int) Math.round(stocks.length * Math.random()); if (idx < stocks.length) { break; } } String stock = stocks[idx]; Destination destination = session.createTopic("STOCKS." + stock); String stockText = createStockText(stock); log("Sending: " + stockText + " on destination: " + destination); Message message = session.createTextMessage(stockText); client.send(destination, message); }
private void doHttpTest(final WebClient client) throws Exception, IOException, MalformedURLException { final Map<String, Class<? extends Servlet>> servlets = new HashMap<>(); servlets.put("/test", SocksProxyTestServlet.class); startWebServer("./", new String[0], servlets); final HtmlPage page = client.getPage("http://localhost:" + PORT + "/test"); assertEquals("hello", page.getTitleText()); }
@LocalData public void testReadOnlyConfigAccessWithPermissionEnabled() throws Exception { setPermissionEnabled(true); AuthorizationStrategy as = jenkins.getAuthorizationStrategy(); assertTrue( "Expecting GlobalMatrixAuthorizationStrategy", (as instanceof GlobalMatrixAuthorizationStrategy)); GlobalMatrixAuthorizationStrategy gas = (GlobalMatrixAuthorizationStrategy) as; assertTrue( "Charlie should have extended read for this test", gas.hasExplicitPermission("charlie", Item.EXTENDED_READ)); WebClient wc = new WebClient().login("charlie", "charlie"); HtmlPage page = wc.goTo("job/a/configure"); HtmlForm form = page.getFormByName("config"); HtmlButton saveButton = getButtonByCaption(form, "Save"); assertNull(saveButton); }
/** * Test for feature request 1438216: HttpWebConnection should allow extension to create the * HttpClient. * * @throws Exception if the test fails */ @Test public void designedForExtension() throws Exception { startWebServer("./"); final WebClient webClient = getWebClient(); final boolean[] tabCalled = {false}; final WebConnection myWebConnection = new HttpWebConnection(webClient) { @Override protected AbstractHttpClient createHttpClient() { tabCalled[0] = true; return new DefaultHttpClient(); } }; webClient.setWebConnection(myWebConnection); webClient.getPage("http://localhost:" + PORT + "/LICENSE.txt"); Assert.assertTrue("createHttpClient has not been called", tabCalled[0]); }
public void testFormRoundTrip() throws Exception { MavenInstallation.DescriptorImpl mavenDescriptor = jenkins.getDescriptorByType(MavenInstallation.DescriptorImpl.class); mavenDescriptor.setInstallations(new MavenInstallation("maven", "XXX", NO_PROPERTIES)); AntInstallation.DescriptorImpl antDescriptor = jenkins.getDescriptorByType(AntInstallation.DescriptorImpl.class); antDescriptor.setInstallations(new AntInstallation("ant", "XXX", NO_PROPERTIES)); JDK.DescriptorImpl jdkDescriptor = jenkins.getDescriptorByType(JDK.DescriptorImpl.class); jdkDescriptor.setInstallations(new JDK("jdk", "XXX")); ToolLocationNodeProperty property = new ToolLocationNodeProperty( new ToolLocationNodeProperty.ToolLocation(jdkDescriptor, "jdk", "foobar"), new ToolLocationNodeProperty.ToolLocation(mavenDescriptor, "maven", "barzot"), new ToolLocationNodeProperty.ToolLocation(antDescriptor, "ant", "zotfoo")); slave.getNodeProperties().add(property); WebClient webClient = new WebClient(); HtmlPage page = webClient.getPage(slave, "configure"); HtmlForm form = page.getFormByName("config"); submit(form); Assert.assertEquals(1, slave.getNodeProperties().toList().size()); ToolLocationNodeProperty prop = slave.getNodeProperties().get(ToolLocationNodeProperty.class); Assert.assertEquals(3, prop.getLocations().size()); ToolLocationNodeProperty.ToolLocation location = prop.getLocations().get(0); Assert.assertEquals(jdkDescriptor, location.getType()); Assert.assertEquals("jdk", location.getName()); Assert.assertEquals("foobar", location.getHome()); location = prop.getLocations().get(1); Assert.assertEquals(mavenDescriptor, location.getType()); Assert.assertEquals("maven", location.getName()); Assert.assertEquals("barzot", location.getHome()); location = prop.getLocations().get(2); Assert.assertEquals(antDescriptor, location.getType()); Assert.assertEquals("ant", location.getName()); Assert.assertEquals("zotfoo", location.getHome()); }
@Test public void testPostCommitTrigger() throws Exception { // Disable crumbs because HTMLUnit refuses to mix request bodies with // request parameters hudson.setCrumbIssuer(null); FreeStyleProject p = createFreeStyleProject(); String url = "https://tsethudsonsvn.googlecode.com/svn/trunk"; SCMTrigger trigger = new SCMTrigger("0 */6 * * *"); p.setScm(new SubversionSCM(url)); p.addTrigger(trigger); trigger.start(p, true); String repoUUID = "b703df53-fdd9-0691-3d8c-58db40123d9f"; WebClient wc = new WebClient(); WebRequestSettings wr = new WebRequestSettings( new URL(getURL() + "subversion/" + repoUUID + "/notifyCommit"), HttpMethod.POST); wr.setRequestBody("A trunk/testcommit.txt"); wr.setAdditionalHeader("Content-Type", "text/plain;charset=UTF-8"); wr.setAdditionalHeader("X-Hudson-Subversion-Revision", "16"); WebConnection conn = wc.getWebConnection(); WebResponse resp = conn.getResponse(wr); assertTrue(isGoodHttpStatus(resp.getStatusCode())); waitUntilNoActivity(); FreeStyleBuild b = p.getLastBuild(); assertNotNull(b); assertBuildStatus(Result.SUCCESS, b); SVNRevisionState revisionState = b.getAction(SVNRevisionState.class); assertNotNull("Failed to find revision", revisionState); assertNotNull("Failed to find revision", revisionState.revisions.get(url)); assertEquals(16, revisionState.revisions.get(url).longValue()); }