List of usage examples for org.apache.commons.httpclient.methods HeadMethod HeadMethod
public HeadMethod(String paramString)
From source file:org.dataconservancy.dcs.access.http.DatastreamServletTest.java
public void testHead() throws Exception { // ServletTester has internal errors processing head requests so use http client String baseurl = servletContainer.createSocketConnector(true); HttpClient client = new HttpClient(); HeadMethod head = new HeadMethod(baseurl + "/access/datastream/" + ds_entity.getId()); int status = client.executeMethod(head); assertEquals(200, status);/* w w w . j a va 2 s .c om*/ assertEquals(ds_entity.getSizeBytes(), head.getResponseContentLength()); assertNotNull(head.getResponseHeader("ETag")); assertNotNull(head.getResponseHeader("Content-Type")); assertEquals("application/xbox", head.getResponseHeader("Content-Type").getValue()); head = new HeadMethod(baseurl + "/access/datastream/doesnotexist"); status = client.executeMethod(head); assertEquals(404, status); }
From source file:org.dataconservancy.dcs.access.http.EntityServletTest.java
public void testHead() throws Exception { HttpClient client = new HttpClient(); for (DcsEntity entity : entities) { HeadMethod head = new HeadMethod(entity.getId()); int status = client.executeMethod(head); assertEquals(200, status);// w w w.j a va2 s.c om assertEquals("application/xml", head.getResponseHeader("Content-Type").getValue()); assertTrue(head.getResponseContentLength() > 0); assertNotNull(head.getResponseHeader("ETag")); } HeadMethod head = new HeadMethod(entities.get(0).getId() + "blah"); int status = client.executeMethod(head); assertEquals(404, status); }
From source file:org.dataconservancy.dcs.access.http.GQMQueryServletTest.java
public void testHEAD() throws Exception { String baseurl = servletContainer.createSocketConnector(true); HttpClient client = new HttpClient(); HeadMethod head = new HeadMethod( baseurl + "/qf/query/" + ServletUtil.encodeURLPath("intersects([line 'EPSG:4326' 4 -1, 4 1])")); int status = client.executeMethod(head); Assert.assertEquals(200, status);/* ww w. ja v a 2 s. c om*/ Assert.assertEquals("application/xml", head.getResponseHeader("Content-Type").getValue()); Assert.assertEquals("" + gqms.getGQMs().size(), head.getResponseHeader("X-TOTAL-MATCHES").getValue()); head = new HeadMethod(baseurl + "/qf/query/badfield:"); status = client.executeMethod(head); Assert.assertEquals(404, status); }
From source file:org.dataconservancy.dcs.access.http.QueryServletTest.java
public void testHEAD() throws Exception { Collection<DcsFile> files = dcp.getFiles(); // ServletTester has internal errors processing head requests so use http client // request.setMethod("GET"); String baseurl = servletContainer.createSocketConnector(true); HttpClient client = new HttpClient(); HeadMethod head = new HeadMethod(baseurl + "/access/query/" + ServletUtil.encodeURLPath("entityType:File")); int status = client.executeMethod(head); assertEquals(200, status);//from ww w . j a v a 2 s. co m assertEquals("application/xml", head.getResponseHeader("Content-Type").getValue()); assertEquals("" + files.size(), head.getResponseHeader("X-TOTAL-MATCHES").getValue()); head = new HeadMethod(baseurl + "/access/query/badfield:"); status = client.executeMethod(head); assertEquals(404, status); }
From source file:org.dataconservancy.dcs.query.endpoint.dcpsolr.QueryServletTest.java
public void testHEAD() throws Exception { // ServletTester has internal errors processing head requests so use http client // request.setMethod("GET"); String baseurl = servletContainer.createSocketConnector(true); HttpClient client = new HttpClient(); HeadMethod head = new HeadMethod(baseurl + "/qf/query/" + ServletUtil.encodeURLPath("entityType:File")); int status = client.executeMethod(head); assertEquals(200, status);/*ww w .ja v a2 s .co m*/ assertEquals("application/xml", head.getResponseHeader("Content-Type").getValue()); assertEquals("" + dcp.getFiles().size(), head.getResponseHeader("X-TOTAL-MATCHES").getValue()); head = new HeadMethod(baseurl + "/qf/query/badfield:"); status = client.executeMethod(head); assertEquals(404, status); }
From source file:org.deegree.framework.util.HttpUtils.java
/** * validates passed URL. If it is not a valid URL or a client can not connect to it an exception will be thrown * //from ww w . ja va 2 s . co m * @param url * @param user * @param password * @throws IOException */ public static int validateURL(String url, String user, String password) throws IOException { if (url.startsWith("http:")) { URL tmp = new URL(url); HeadMethod hm = new HeadMethod(url); setHTTPCredentials(hm, user, password); InetAddress.getByName(tmp.getHost()); HttpClient client = new HttpClient(); client.executeMethod(hm); if (hm.getStatusCode() != HttpURLConnection.HTTP_OK) { if (hm.getStatusCode() != HttpURLConnection.HTTP_UNAUTHORIZED && hm.getStatusCode() != 401) { // this method just evaluates if a URL/host is valid; it does not takes care // if authorization is available/valid throw new IOException("Host " + tmp.getHost() + " of URL + " + url + " does not exists"); } } return hm.getStatusCode(); } else if (url.startsWith("file:")) { URL tmp = new URL(url); InputStream is = tmp.openStream(); is.close(); return 200; } return HttpURLConnection.HTTP_UNAVAILABLE; }
From source file:org.deri.pipes.utils.HttpResponseCache.java
/** * @param client/*from www. j a v a 2 s . com*/ * @param location * @param location2 * @return */ public static HttpResponseData getResponseData(HttpClient client, String location, Map<String, String> requestHeaders) throws Exception { synchronized (client) { if (MINIMUM_CACHE_TIME_MILLIS <= 0) { logger.debug("caching disabled."); return getDataFromRequest(client, location, requestHeaders); } String cacheKey = makeCacheKey(location, requestHeaders); if (requestHeaders == null) { requestHeaders = new HashMap<String, String>(); } if (requestHeaders.get(HEADER_USER_AGENT) == null) { requestHeaders.put(HEADER_USER_AGENT, getDefaultUserAgent()); } JCS jcs = null; try { jcs = JCS.getInstance("httpResponseCache"); } catch (Exception e) { logger.warn("Problem getting JCS cache" + e, e); } if (jcs != null) { try { HttpResponseData data = (HttpResponseData) jcs.get(cacheKey); if (data != null) { if (data.getExpires() > System.currentTimeMillis()) { logger.info("Retrieved from cache (not timed out):" + location); return data; } if (location.length() < 2000) { HeadMethod headMethod = new HeadMethod(location); headMethod.setFollowRedirects(true); addRequestHeaders(headMethod, requestHeaders); try { int response = client.executeMethod(headMethod); Header lastModifiedHeader = headMethod.getResponseHeader(HEADER_LAST_MODIFIED); if (response == data.getResponse()) { if (lastModifiedHeader == null) { logger.debug("Not using cache (No last modified header available) for " + location); } else if (lastModifiedHeader != null && data.getLastModified().equals(lastModifiedHeader.getValue())) { setExpires(data, headMethod); jcs.put(cacheKey, data); logger.info("Retrieved from cache (used HTTP HEAD request to check " + HEADER_LAST_MODIFIED + ") :" + location); return data; } else { logger.debug("Not using cache (last modified changed) for " + location); } } } finally { headMethod.releaseConnection(); } } } } catch (Exception e) { logger.warn("Problem retrieving from cache for " + location, e); } } HttpResponseData data = getDataFromRequest(client, location, requestHeaders); if (jcs != null) { try { jcs.put(cacheKey, data); logger.debug("cached " + location); } catch (Exception e) { logger.warn("Could not store response for " + location + " in cache", e); } } return data; } }
From source file:org.drools.guvnor.server.files.PackageDeploymentServletTest.java
@Test @Ignore// w w w . j a v a 2 s.co m public void testLoadingRules() throws Exception { RulesRepository repo = new RulesRepository(TestEnvironmentSessionHelper.getSession(true)); ServiceImplementation impl = new ServiceImplementation(); impl.repository = repo; PackageItem pkg = repo.createPackage("testPDSGetPackage", ""); AssetItem header = pkg.addAsset("drools", ""); header.updateFormat("package"); header.updateContent("import org.drools.SampleFact\n global org.drools.SampleFact sf"); header.checkin(""); AssetItem asset = pkg.addAsset("someRule", ""); asset.updateContent("when \n SampleFact() \n then \n System.err.println(42);"); asset.updateFormat(AssetFormats.DRL); asset.checkin(""); assertNull(impl.buildPackage(pkg.getUUID(), true)); //check source PackageDeploymentServlet serv = new PackageDeploymentServlet(); MockHTTPRequest req = new MockHTTPRequest("/package/testPDSGetPackage/LATEST.drl", null); MockHTTPResponse res = new MockHTTPResponse(); serv.doGet(req, res); assertNotNull(res.extractContentBytes()); String drl = res.extractContent(); assertTrue(drl.indexOf("rule") > -1); //now binary serv = new PackageDeploymentServlet(); req = new MockHTTPRequest("/package/testPDSGetPackage/LATEST", null); res = new MockHTTPResponse(); serv.doGet(req, res); assertNotNull(res.extractContentBytes()); byte[] bin = res.extractContentBytes(); byte[] bin_ = pkg.getCompiledPackageBytes(); org.drools.rule.Package o = (org.drools.rule.Package) DroolsStreamUtils .streamIn(new ByteArrayInputStream(bin)); assertNotNull(o); assertEquals(1, o.getRules().length); assertEquals(1, o.getGlobals().size()); assertEquals(bin_.length, bin.length); assertSameArray(bin_, bin); //now some snapshots impl.createPackageSnapshot("testPDSGetPackage", "SNAP1", false, "hey"); serv = new PackageDeploymentServlet(); req = new MockHTTPRequest("/package/testPDSGetPackage/SNAP1.drl", null); res = new MockHTTPResponse(); serv.doGet(req, res); assertNotNull(res.extractContentBytes()); drl = new String(res.extractContentBytes()); assertTrue(drl.indexOf("rule") > -1); //now binary serv = new PackageDeploymentServlet(); req = new MockHTTPRequest("/package/testPDSGetPackage/SNAP1", null); res = new MockHTTPResponse(); serv.doGet(req, res); assertNotNull(res.extractContentBytes()); bin = res.extractContentBytes(); bin_ = pkg.getCompiledPackageBytes(); assertEquals(bin_.length, bin.length); //now get an individual asset source serv = new PackageDeploymentServlet(); req = new MockHTTPRequest("/package/testPDSGetPackage/SNAP1/someRule.drl", null); res = new MockHTTPResponse(); serv.doGet(req, res); assertNotNull(res.extractContentBytes()); drl = res.extractContent(); System.err.println(drl); assertTrue(drl.indexOf("rule") > -1); assertEquals(-1, drl.indexOf("package")); //now test HEAD serv = new PackageDeploymentServlet(); req = new MockHTTPRequest("/package/testPDSGetPackage/LATEST", null); req.method = "HEAD"; res = new MockHTTPResponse(); serv.doHead(req, res); assertTrue(res.headers.size() > 0); String lm = res.headers.get("Last-Modified"); assertNotNull(lm); serv = new PackageDeploymentServlet(); req = new MockHTTPRequest("/package/testPDSGetPackage/LATEST", null); req.method = "HEAD"; res = new MockHTTPResponse(); serv.doHead(req, res); assertTrue(res.headers.size() > 0); assertEquals(lm, res.headers.get("Last-Modified")); serv = new PackageDeploymentServlet(); req = new MockHTTPRequest("/package/testPDSGetPackage/LATEST.drl", null); req.method = "HEAD"; res = new MockHTTPResponse(); serv.doHead(req, res); assertTrue(res.headers.size() > 0); assertEquals(lm, res.headers.get("Last-Modified")); System.out.println(lm); // //now lets run it in a real server ! // Server server = new Server(9000); Context ctx = new Context(server, "/", Context.SESSIONS); ctx.addServlet(new ServletHolder(new PackageDeploymentServlet()), "/package/*"); server.setStopAtShutdown(true); server.start(); ResourceFactory.getResourceChangeNotifierService().start(); ResourceFactory.getResourceChangeScannerService().start(); ResourceChangeScannerConfiguration sconf = ResourceFactory.getResourceChangeScannerService() .newResourceChangeScannerConfiguration(); sconf.setProperty("drools.resource.scanner.interval", "1"); ResourceFactory.getResourceChangeScannerService().configure(sconf); String xml = ""; xml += "<change-set xmlns='http://drools.org/drools-5.0/change-set'"; xml += " xmlns:xs='http://www.w3.org/2001/XMLSchema-instance'"; xml += " xs:schemaLocation='http://drools.org/drools-5.0/change-set http://anonsvn.jboss.org/repos/labs/labs/jbossrules/trunk/drools-api/src/main/resources/change-set-1.0.0.xsd' >"; xml += " <add> "; xml += " <resource source='http://localhost:9000/package/testPDSGetPackage/LATEST.drl' type='DRL' />"; xml += " </add> "; xml += "</change-set>"; FileManager fileManager = new FileManager(); fileManager.setUp(); File fxml = fileManager.newFile("changeset.xml"); Writer output = new BufferedWriter(new FileWriter(fxml)); output.write(xml); output.close(); KnowledgeAgent ag = KnowledgeAgentFactory.newKnowledgeAgent("fii", KnowledgeAgentFactory.newKnowledgeAgentConfiguration()); ag.applyChangeSet(ResourceFactory.newUrlResource(fxml.toURI().toURL())); KnowledgeBase kb = ag.getKnowledgeBase(); assertEquals(1, kb.getKnowledgePackages().size()); KnowledgePackage kp = kb.getKnowledgePackages().iterator().next(); assertTrue(kb.getKnowledgePackages().size() > 0); assertEquals(1, kp.getRules().size()); //check the HEAD method HttpClient client = new HttpClient(); HeadMethod hm = new HeadMethod("http://localhost:9000/package/testPDSGetPackage/LATEST.drl"); client.executeMethod(hm); Header lastMod = hm.getResponseHeader("lastModified"); Thread.sleep(50); long now = System.currentTimeMillis(); long before = Long.parseLong(lastMod.getValue()); assertTrue(before < now); //now lets add a rule asset = pkg.addAsset("someRule2", ""); asset.updateContent("when \n SampleFact() \n then \n System.err.println(43);"); asset.updateFormat(AssetFormats.DRL); asset.checkin(""); assertNull(impl.buildPackage(pkg.getUUID(), true)); Thread.sleep(3000); kb = ag.getKnowledgeBase(); assertEquals(1, kb.getKnowledgePackages().size()); kp = kb.getKnowledgePackages().iterator().next(); if (kp.getRules().size() != 2) { Thread.sleep(2000); kb = ag.getKnowledgeBase(); assertEquals(1, kb.getKnowledgePackages().size()); kp = kb.getKnowledgePackages().iterator().next(); } if (kp.getRules().size() != 2) { Thread.sleep(2000); kb = ag.getKnowledgeBase(); assertEquals(1, kb.getKnowledgePackages().size()); kp = kb.getKnowledgePackages().iterator().next(); } assertEquals(2, kp.getRules().size()); server.stop(); repo.logout(); }
From source file:org.dspace.app.util.AbstractDSpaceWebapp.java
/** Return the list of running applications. */ static public List<AbstractDSpaceWebapp> getApps() { ArrayList<AbstractDSpaceWebapp> apps = new ArrayList<AbstractDSpaceWebapp>(); TableRowIterator tri;/*from ww w . ja va 2 s. c o m*/ Context context = null; HttpMethod request = null; try { context = new Context(); tri = DatabaseManager.queryTable(context, "Webapp", "SELECT * FROM Webapp"); for (TableRow row : tri.toList()) { DSpaceWebapp app = new DSpaceWebapp(); app.kind = row.getStringColumn("AppName"); app.url = row.getStringColumn("URL"); app.started = row.getDateColumn("Started"); app.uiQ = row.getBooleanColumn("isUI"); HttpClient client = new HttpClient(); request = new HeadMethod(app.url); int status = client.executeMethod(request); request.getResponseBody(); if (status != HttpStatus.SC_OK) { DatabaseManager.delete(context, row); context.commit(); continue; } apps.add(app); } } catch (SQLException e) { log.error("Unable to list running applications", e); } catch (HttpException e) { log.error("Failure checking for a running webapp", e); } catch (IOException e) { log.error("Failure checking for a running webapp", e); } finally { if (null != request) { request.releaseConnection(); } if (null != context) { context.abort(); } } return apps; }
From source file:org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientFileSystemBrowser.java
protected void runRequest() throws Exception { Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "runRequest"); //$NON-NLS-1$ setupProxies();/*ww w .ja va 2s . c o m*/ // set timeout initHttpClientConnectionManager(); String urlString = directoryOrFile.toString(); CredentialsProvider credProvider = new HttpClientProxyCredentialProvider() { protected Proxy getECFProxy() { return getProxy(); } protected Credentials getNTLMCredentials(Proxy lp) { if (hasForceNTLMProxyOption()) return HttpClientRetrieveFileTransfer.createNTLMCredentials(lp); return null; } }; // setup authentication setupAuthentication(urlString); // setup https host and port setupHostAndPort(credProvider, urlString); headMethod = new HeadMethod(hostConfigHelper.getTargetRelativePath()); headMethod.setFollowRedirects(true); // Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod) // Seems to be another way to select the credentials. headMethod.getParams().setParameter(CredentialsProvider.PROVIDER, credProvider); // set max-age for cache control to 0 for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=249990 headMethod.addRequestHeader("Cache-Control", "max-age=0"); //$NON-NLS-1$//$NON-NLS-2$ headMethod.addRequestHeader("Connection", "Keep-Alive"); //$NON-NLS-1$ //$NON-NLS-2$ long lastModified = 0; long fileLength = -1; connectingSockets.clear(); int code = -1; try { Trace.trace(Activator.PLUGIN_ID, "browse=" + urlString); //$NON-NLS-1$ code = httpClient.executeMethod(getHostConfiguration(), headMethod); Trace.trace(Activator.PLUGIN_ID, "browse resp=" + code); //$NON-NLS-1$ // Check for NTLM proxy in response headers // This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002 boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(headMethod); if (ntlmProxyFound && !hasForceNTLMProxyOption()) throw new BrowseFileTransferException( "HttpClient Provider is not configured to support NTLM proxy authentication.", //$NON-NLS-1$ HttpClientOptions.NTLM_PROXY_RESPONSE_CODE); if (code == HttpURLConnection.HTTP_OK) { fileLength = headMethod.getResponseContentLength(); lastModified = getLastModifiedTimeFromHeader(); } else if (code == HttpURLConnection.HTTP_NOT_FOUND) { throw new BrowseFileTransferException(NLS.bind("File not found: {0}", urlString), code); //$NON-NLS-1$ } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code); } else if (code == HttpURLConnection.HTTP_FORBIDDEN) { throw new BrowseFileTransferException("Forbidden", code); //$NON-NLS-1$ } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) { throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required, code); } else { throw new BrowseFileTransferException( NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE, new Integer(code)), code); } remoteFiles = new IRemoteFile[1]; remoteFiles[0] = new URLRemoteFile(lastModified, fileLength, fileID); } catch (Exception e) { Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "runRequest", e); //$NON-NLS-1$ BrowseFileTransferException ex = (BrowseFileTransferException) ((e instanceof BrowseFileTransferException) ? e : new BrowseFileTransferException(NLS .bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT, urlString), e, code)); throw ex; } finally { headMethod.releaseConnection(); } }