List of usage examples for org.apache.commons.httpclient Header Header
public Header(String paramString1, String paramString2)
From source file:de.kapsi.net.daap.DaapHeaderConstructor.java
/** * Creates a new Authentication Header// w w w .ja va 2 s . c o m * * @param request * @return */ public static byte[] createAuthHeader(DaapRequest request) { try { DaapConnection connection = request.getConnection(); String serverName = connection.getServer().getConfig().getServerName(); ArrayList headers = new ArrayList(); headers.add(new Header("Date", DaapUtil.now())); headers.add(new Header("DAAP-Server", serverName)); headers.add(new Header("Content-Type", "text/html")); headers.add(new Header("Content-Length", "0")); // headers.add(new Header("WWW-Authenticate", "Basic-realm=\"daap\"")); return toByteArray(HTTP_AUTH, (Header[]) headers.toArray(new Header[0])); } catch (UnsupportedEncodingException err) { // Should never happen throw new RuntimeException(err); } catch (IOException err) { // Should never happen throw new RuntimeException(err); } }
From source file:net.sf.ehcache.constructs.web.filter.PageFragmentCachingFilterTest.java
/** * Tests that a page which is not storeGzipped is not gzipped when the user agent does not accept gzip encoding *//*w w w .j a v a 2 s .c o m*/ public void testNotGzippedWhenNotAcceptEncodingPageFragment() throws Exception { HttpClient httpClient = new HttpClient(); HttpMethod httpMethod = new GetMethod(buildUrl("/include/Footer.jsp")); httpMethod.setRequestHeader(new Header("Accept-encoding", "gzip")); httpClient.executeMethod(httpMethod); byte[] responseBody = httpMethod.getResponseBody(); assertFalse(PageInfo.isGzipped(responseBody)); assertNotSame("gzip", httpMethod.getResponseHeader("Accept-encoding")); }
From source file:net.sf.ehcache.constructs.web.filter.CachingFilterTest.java
/** * Tests whether the page is gzipped using the rawer HttpClient library. * Lets us check that the responseBody is really gzipped. *//*from w w w. j av a 2 s .c om*/ public void testCachedPageIsGzippedWhenEncodingHeaderSet() throws IOException { HttpClient httpClient = new HttpClient(); HttpMethod httpMethod = new GetMethod(buildUrl(cachedPageUrl)); httpMethod.setRequestHeader(new Header("Accept-encoding", "gzip")); httpClient.executeMethod(httpMethod); byte[] responseBody = httpMethod.getResponseBody(); assertTrue(PageInfo.isGzipped(responseBody)); }
From source file:ensen.controler.DBpediaSpotlightClient.java
private JSONArray getAnnotationsFromSpotlight(Text text, String confiance, String support, String file) { if (confiance == null || confiance.trim() == "") confiance = PropertiesManager.getProperty("CONFIDENCE"); if (support == null || support.trim() == "") support = PropertiesManager.getProperty("SUPPORT"); JSONArray entities = null;// ww w. j av a 2s.c o m if (local) { double d = Math.random(); if (d > 0.5) API_URL = PropertiesManager.getProperty("DBpediaSpotlightClientLocal"); else API_URL = PropertiesManager.getProperty("DBpediaSpotlightClientLocalCopy"); } else API_URL = PropertiesManager.getProperty("DBpediaSpotlightClient"); SPOTTER = PropertiesManager.getProperty("spotter"); String spotlightResponse = null; try { //System.out.println("Querying API: " + API_URL); //System.err.println(text.text()); /** using post **/ PostMethod post = new PostMethod(API_URL + "rest/annotate/"); NameValuePair[] data = { new NameValuePair("coreferenceResolution", "false"), /**//*new NameValuePair("disambiguator", "Document"),new NameValuePair("spotter", SPOTTER),*/new NameValuePair( "confidence", confiance), new NameValuePair("support", support), new NameValuePair("text", text.text()) }; post.setRequestBody(data); post.addRequestHeader(new Header("Accept", "application/json")); post.setRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE + "; charset=UTF-8"); spotlightResponse = request(post); } catch (Exception e) { System.err.println("error in calling Spotlight."); } JSONObject resultJSON = null; try { resultJSON = new JSONObject(spotlightResponse); if (resultJSON.has("Resources")) { entities = resultJSON.getJSONArray("Resources"); } else { System.err.println("No founded resources"); System.err.println(resultJSON); } } catch (JSONException e) { System.err.println(spotlightResponse); System.err.println("Received invalid response from DBpedia Spotlight API."); e.printStackTrace(); } if (resultJSON != null) { //System.err.println("print json to" + file + ".json"); //Printer.printToFile(file + ".json", resultJSON.toString()); } //if not enough resources ==> re-do with conf 0.15 if ((entities == null || entities.length() < Integer .parseInt(PropertiesManager.getProperty("MinNofAnnotatedResourcesInDocument"))) && confiance != "0.15") { entities = getAnnotationsFromSpotlight(text, "0.15", support, file); } return entities; }
From source file:com.arjuna.qa.junit.TestAll.java
private void testCallServlet(String serverUrl, String outfile) { boolean result = true; try {/*ww w . ja va 2 s . c o m*/ // run tests by calling a servlet Header runParam = new Header("run", "run"); HttpMethodBase request = HttpUtils.accessURL(new URL(serverUrl), null, HttpURLConnection.HTTP_OK, new Header[] { runParam }, HttpUtils.POST); String response = null; int index = 0; do { System.err.println("_____________ " + (index++) + "th round"); // we have to give some time to the tests to finish Thread.sleep(timeout); // tries to get results request = HttpUtils.accessURL(new URL(serverUrl), null, HttpURLConnection.HTTP_OK, HttpUtils.GET); response = request.getResponseBodyAsString(); } while (response != null && response.indexOf("finished") == -1 && index < LOOP_RETRY_MAX); if (response != null && response.indexOf("finished") == -1) { System.err.println("======================================================"); System.err.println("==================== TIMED OUT ====================="); System.err.println("======================================================"); result = false; } else { System.err.println("======================================================"); System.err.println("==================== RESULT ====================="); System.err.println("======================================================"); System.err.println(response); // writes response to the outfile BufferedWriter writer = new BufferedWriter(new FileWriter(outfile)); writer.write(response); writer.close(); } } catch (Exception e) { System.err.println("======================================================"); System.err.println("==================== EXCEPTION ====================="); System.err.println("======================================================"); e.printStackTrace(); result = false; } assertTrue(result); }
From source file:com.dtolabs.rundeck.core.common.impl.TestURLFileUpdater.java
public void testUpdateCaching() throws Exception { File tempfile = File.createTempFile("test", ".yaml"); tempfile.deleteOnExit();//from ww w. j a v a2 s . c o m File cachemeta = File.createTempFile("test", ".properties"); cachemeta.deleteOnExit(); URLFileUpdater updater = new URLFileUpdater(new URL("http://example.com/test"), null, -1, cachemeta, tempfile, true, null, null); final test1 test1 = new test1(); test1.httpResultCode = 200; test1.httpStatusText = "OK"; test1.responseHeaders.put("Content-Type", new Header("Content-Type", "text/yaml")); //include etag, last-modified test1.responseHeaders.put("ETag", new Header("ETag", "monkey1")); test1.responseHeaders.put("Last-Modified", new Header("Last-Modified", "blahblee")); final ByteArrayInputStream stringStream = new ByteArrayInputStream(YAML_NODES_TEST.getBytes()); test1.bodyStream = stringStream; updater.setInteraction(test1); updater.updateFile(tempfile); assertTrue(tempfile.isFile()); assertTrue(tempfile.length() > 0); assertNotNull(test1.method); assertNotNull(test1.client); assertNotNull(test1.followRedirects); assertNotNull(test1.releaseConnectionCalled); //make another request. assert etag, If-modified-since are used. final test1 test2 = new test1(); test2.httpResultCode = 304; test2.httpStatusText = "Not Modified"; //include etag, last-modified test2.responseHeaders.put("ETag", new Header("ETag", "monkey1")); test2.responseHeaders.put("Last-Modified", new Header("Last-Modified", "blahblee")); test2.bodyStream = null; updater.setInteraction(test2); updater.updateFile(tempfile); assertTrue(tempfile.isFile()); assertTrue(tempfile.length() > 0); assertNotNull(test2.method); assertNotNull(test2.client); assertNotNull(test2.followRedirects); assertNotNull(test2.releaseConnectionCalled); assertEquals("monkey1", test2.requestHeaders.get("If-None-Match")); assertEquals("blahblee", test2.requestHeaders.get("If-Modified-Since")); }
From source file:com.mythesis.userbehaviouranalysis.DBpediaSpotlightClient.java
/** * Method that recognizes the entities through DBpedia spotlight the content of a given URL * @param url_check the url to be annotated *//*from ww w . j av a 2s. c o m*/ @Override public void extract(String url_check) throws AnnotationException { try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>(); entitiesString = new ArrayList<>(); typesDBspot = new ArrayList<>(); similarityScores = new ArrayList<>(); supports = new ArrayList<>(); noSecondCandidate = new ArrayList<>(); allEntities = new ArrayList<>(); double simScore = 0.0; double percOfSec = 0.0; try { LOG.info("Querying API."); String spotlightResponse; String request = API_URL + "rest/annotate?" + "confidence=" + CONFIDENCE + "&support=" + SUPPORT + "&url=" + URLEncoder.encode(url_check, "utf-8"); GetMethod getMethod = new GetMethod(request); getMethod.addRequestHeader(new Header("Accept", "application/json")); spotlightResponse = request(getMethod); assert spotlightResponse != null; JSONObject resultJSON = null; JSONArray entities = null; if (spotlightResponse.startsWith("{")) { resultJSON = new JSONObject(spotlightResponse); entities = resultJSON.getJSONArray("Resources"); for (int i = 0; i < entities.length(); i++) { try { JSONObject entity = entities.getJSONObject(i); //get the entity string by getting the last part of the URI String entityString = entity.getString("@URI").substring(28).toLowerCase() .replaceAll("[\\_,\\%28,\\%29]", " "); if (!entitiesString.contains(entityString)) { entitiesString.add(entityString);//if we have found a unique entity we include it in the list } String typesString = entity.getString("@types");//we get the semantic types/categories String[] types = typesString.split("\\,"); String delimiter = "";//the delimiter is different according to the type for (String type : types) { if (type.contains("DBpedia") || type.contains("Schema")) { //if it is DBpedia or Schema delimiter = "\\:"; } if (type.contains("Freebase")) {//if it is Freebase delimiter = "\\/"; } String[] typeStrings = type.split(delimiter); String typeString = typeStrings[typeStrings.length - 1].toLowerCase() .replaceAll("[\\_,\\%28,\\%29]", " "); if (!typesDBspot.contains(typeString)) { typesDBspot.add(typeString); } } simScore = Double.valueOf(entity.getString("@similarityScore")); percOfSec = Double.valueOf(entity.getString("@percentageOfSecondRank")); allEntities.add(entityString); similarityScores.add(simScore); supports.add(Double.valueOf(entity.getString("@support"))); if (percOfSec == -1.0) { noSecondCandidate.add(true); } else { noSecondCandidate.add(false); } } catch (JSONException e) { LOG.error("JSON exception " + e); } } } } catch (UnsupportedEncodingException | JSONException ex) { Logger.getLogger(DBpediaSpotlightClient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java
private HttpMethod createProxyRequest(String targetUrl, HttpServletRequest request) throws IOException { URI targetUri;/*from w w w . j a va 2 s. c o m*/ try { targetUri = new URI(uriEncode(targetUrl)); } catch (URISyntaxException e) { throw new RuntimeException(e); } HttpMethod commonsHttpMethod = httpMethodProvider.getMethod(request.getMethod(), targetUri.toString()); commonsHttpMethod.setFollowRedirects(false); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headerVals = request.getHeaders(headerName); while (headerVals.hasMoreElements()) { String headerValue = headerVals.nextElement(); headerValue = headerFilter.processRequestHeader(headerName, headerValue); if (headerValue != null) { commonsHttpMethod.addRequestHeader(new Header(headerName, headerValue)); } } } return commonsHttpMethod; }
From source file:edu.harvard.iq.dataverse.dataaccess.StorageIOTest.java
@Test public void testResponseHeaders() { assertArrayEquals(null, instance.getResponseHeaders()); Header[] headers = new Header[] { new Header("Test", ""), new Header() }; instance.setResponseHeaders(headers); assertArrayEquals(headers, instance.getResponseHeaders()); }
From source file:ixa.entity.linking.DBpediaSpotlightClient.java
public Document extract(Text text, int port) throws AnnotationException { LOG.info("Querying API."); String spotlightResponse = ""; Document doc = null;//from ww w .j av a 2s. c o m try { String url = "http://localhost:" + port + "/rest/disambiguate"; PostMethod method = new PostMethod(url); method.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); NameValuePair[] params = { new NameValuePair("text", text.text()), new NameValuePair("spotter", "SpotXmlParser"), new NameValuePair("confidence", Double.toString(CONFIDENCE)), new NameValuePair("support", Integer.toString(SUPPORT)) }; method.setRequestBody(params); method.setRequestHeader(new Header("Accept", "text/xml")); spotlightResponse = request(method); doc = loadXMLFromString(spotlightResponse); } catch (javax.xml.parsers.ParserConfigurationException ex) { } catch (org.xml.sax.SAXException ex) { } catch (java.io.IOException ex) { } return doc; }