List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod
public PostMethod(String paramString)
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;//from w w w .j ava2s.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.linkedin.pinot.server.realtime.ServerSegmentCompletionProtocolHandler.java
private SegmentCompletionProtocol.Response doHttp(SegmentCompletionProtocol.Request request, Part[] parts) { SegmentCompletionProtocol.Response response = new SegmentCompletionProtocol.Response( SegmentCompletionProtocol.ControllerResponseStatus.NOT_SENT, -1L); HttpClient httpClient = new HttpClient(); ControllerLeaderLocator leaderLocator = ControllerLeaderLocator.getInstance(); final String leaderAddress = leaderLocator.getControllerLeader(); if (leaderAddress == null) { LOGGER.error("No leader found {}", this.toString()); return new SegmentCompletionProtocol.Response( SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER, -1L); }//from w ww . j ava2s. c om final String url = request.getUrl(leaderAddress); HttpMethodBase method; if (parts != null) { PostMethod postMethod = new PostMethod(url); postMethod.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams())); method = postMethod; } else { method = new GetMethod(url); } LOGGER.info("Sending request {} for {}", url, this.toString()); try { int responseCode = httpClient.executeMethod(method); if (responseCode >= 300) { LOGGER.error("Bad controller response code {} for {}", responseCode, this.toString()); return response; } else { response = new SegmentCompletionProtocol.Response(method.getResponseBodyAsString()); LOGGER.info("Controller response {} for {}", response.toJsonString(), this.toString()); if (response.getStatus().equals(SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER)) { leaderLocator.refreshControllerLeader(); } return response; } } catch (IOException e) { LOGGER.error("IOException {}", this.toString(), e); leaderLocator.refreshControllerLeader(); return response; } }
From source file:eu.earthobservatory.org.StrabonEndpoint.capabilities.AutoDiscoveryCapabilities.java
@Override public RequestCapabilities getQueryCapabilities() { RequestCapabilities request = new RequestCapabilitiesImpl(); String query = "SELECT * WHERE {?s ?p ?o. FILTER(regex(str(?p), \"geometry\"))} LIMIT 1"; String[] queryParams = { "SPARQLQuery", "query" }; String[] formatValues = { "XML", "KML", "KMZ", "GeoJSON", "HTML", "TSV" }; String[] acceptValues = { "application/sparql-results+xml", "text/tab-separated-values", "application/vnd.google-earth.kml+xml", "application/vnd.google-earth.kmz", "text/html", "application/json" }; // check query parameter and format parameter for (int q = 0; q < queryParams.length; q++) { for (int v = 0; v < formatValues.length; v++) { HttpClient hc = new HttpClient(); // create a post method to execute PostMethod method = new PostMethod(getConnectionURL() + "/Query"); // set the query parameter method.setParameter(queryParams[q], query); // set the format parameter method.setParameter("format", formatValues[v]); try { // execute the method int statusCode = hc.executeMethod(method); if (statusCode == 301 || statusCode == 200) { //System.out.println(queryParams[q] + ", " + formatValues[v]); request.getParametersObject().addParameter(new Parameter(queryParams[q], null)); request.getParametersObject().addParameter(new Parameter("format", null)); request.getParametersObject().getParameter("format").addAcceptedValue(formatValues[v]); }//w w w .j a v a 2s . c o m } catch (IOException e) { e.printStackTrace(); } finally { // release the connection. method.releaseConnection(); } } } // check query parameter and accept header for (int q = 0; q < queryParams.length; q++) { for (int a = 0; a < acceptValues.length; a++) { HttpClient hc = new HttpClient(); // create a post method to execute PostMethod method = new PostMethod(getConnectionURL() + "/Query"); // set the query parameter method.setParameter(queryParams[q], query); // check for accept value as well // set the accept format method.addRequestHeader("Accept", acceptValues[a]); try { // execute the method int statusCode = hc.executeMethod(method); if (statusCode == 301 || statusCode == 200) { //System.out.println(queryParams[q] + ", " + acceptValues[a]); request.getParametersObject().addParameter(new Parameter(queryParams[q], null)); request.getParametersObject().addParameter(new Parameter("Accept", null)); request.getParametersObject().getParameter("Accept").addAcceptedValue(acceptValues[a]); } } catch (IOException e) { e.printStackTrace(); } finally { // release the connection. method.releaseConnection(); } } } return request; }
From source file:dk.dma.epd.common.prototype.communication.webservice.ShoreHttp.java
public void init() { httpClient = new HttpClient(); method = new PostMethod(url); HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams(); params.setSoTimeout(readTimeout);//from w ww. j a va2 s . com params.setConnectionTimeout(connectionTimeout); method.setRequestHeader("User-Agent", USER_AGENT); method.setRequestHeader("Connection", "close"); method.addRequestHeader("Accept", "text/*"); // TODO if compress response method.addRequestHeader("Accept-Encoding", "gzip"); }
From source file:au.org.ala.spatial.util.UploadSpatialResource.java
public static String loadCreateStyle(String url, String extra, String username, String password, String name) { System.out.println("loadCreateStyle url:" + url); System.out.println("name:" + name); String output = ""; HttpClient client = new HttpClient(); client.setConnectionTimeout(10000);//from w w w.j a va 2 s .c o m client.setTimeout(60000); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); PostMethod post = new PostMethod(url); post.setDoAuthentication(true); // Execute the request try { // Request content will be retrieved directly // from the input stream File file = File.createTempFile("sld", "xml"); FileWriter fw = new FileWriter(file); fw.append("<style><name>" + name + "</name><filename>" + name + ".sld</filename></style>"); fw.close(); RequestEntity entity = new FileRequestEntity(file, "text/xml"); post.setRequestEntity(entity); int result = client.executeMethod(post); output = result + ": " + post.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(System.out); output = "0: " + e.getMessage(); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } return output; }
From source file:com.apatar.ui.JHelpDialog.java
private void addListeners() { sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { PostMethod filePost = new PostMethod(getUrl()); // filePost.getParameters().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try { List<File> targetFiles = getAttachFiles(); Part[] parts;/*from w w w.ja v a 2 s . c om*/ if (targetFiles != null) { parts = new Part[targetFiles.size() + 1]; int i = 1; for (File targetFile : targetFiles) { parts[i++] = new FilePart("file" + i, targetFile); } ; } else parts = new Part[1]; parts[0] = new StringPart("FeatureRequest", text.getText()); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status != HttpStatus.SC_OK) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Upload failed, response=" + HttpStatus.getStatusText(status)); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }); }
From source file:com.cognifide.actions.msg.push.active.PushClientRunnable.java
private void confirm(String msgId) throws IOException { final HttpMethod method = new PostMethod(serverUrl + SERVLET_PATH + "/" + msgId); client.executeMethod(method);/*from ww w.j a va2 s . co m*/ method.releaseConnection(); }
From source file:com.google.api.ads.dfp.lib.AuthToken.java
/** * Retrieves an authentication token using the user's credentials. * * @return a {@code String} authentication token. * @throws AuthTokenException if the status from the Client Login server is * anything but {@code HttpStatus.SC_OK = 200} *//*from www.j a v a 2 s .c om*/ public String getAuthToken() throws AuthTokenException { try { PostMethod postMethod = new PostMethod(CLIENT_LOGIN_URL); int statusCode = postToClientLogin(postMethod); Properties responseProperties = generatePropertiesFromResponse(postMethod.getResponseBodyAsStream()); if (statusCode == HttpStatus.SC_OK) { if (responseProperties.containsKey(AUTH_TOKEN_KEY)) { return responseProperties.getProperty(AUTH_TOKEN_KEY).toString(); } else { throw new IllegalStateException("Unable to get auth token from Client Login server"); } } else { CaptchaInformation captchaInfo = null; String errorCode = null; if (responseProperties.containsKey(ERROR_KEY)) { errorCode = responseProperties.getProperty(ERROR_KEY); if (errorCode != null && errorCode.equals(CAPTCHA_REQUIRED_ERROR)) { captchaInfo = extractCaptchaInfoFromProperties(responseProperties); } if (responseProperties.containsKey(INFO_KEY)) { errorCode += ": " + responseProperties.getProperty(INFO_KEY); } } throw new AuthTokenException(statusCode, postMethod.getResponseBodyAsString(), errorCode, captchaInfo, null); } } catch (IOException e) { throw new AuthTokenException(null, null, null, null, e); } }
From source file:com.novell.ldap.DsmlConnection.java
/** * Used to send requests to the server and retrieve responses * @param message The Message To Send/*from ww w. j av a2s . c o m*/ * @param isSearch true if returning a DSMLSearchResult, false if LDAPMessage * @return The Server's Response */ private Object sendMessage(LDAPMessage message, boolean isSearch) throws LDAPException { try { PostMethod post = new PostMethod(serverString); //post.setDoAuthentication(true); //First load up the content headers post.setRequestHeader("Content-Type", "text/xml; charset=utf8"); if (this.useSoap) { post.setRequestHeader("SOAPAction", "#batchRequest"); } if (this.callback != null) { this.callback.manipulationPost(post, this); } StringWriter out = new StringWriter(); DSMLWriter writer = new DSMLWriter(out); PrintWriter pout = new PrintWriter(out); //First print the SOAP Envelope pout.println("<?xml version=\"1.0\" encoding=\"UTF8\"?>"); if (this.useSoap) { pout.println("<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">"); pout.println("<soap-env:Body>"); } //write out the message writer.writeMessage(message); writer.finish(); if (this.useSoap) { //Complete the SOAP Envelope pout.println("</soap-env:Body>"); pout.println("</soap-env:Envelope>"); } ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes("UTF-8")); //Set the input stream post.setRequestBody(in); //POST the request con.executeMethod(post); if (post.getStatusCode() != 200) { //we have an error, if it's an authorization error throw an invalid credentials exception. otherwise throw an unwilling to perform. if (post.getStatusCode() == 401 || post.getStatusCode() == 403) { throw new LDAPException(LDAPException.resultCodeToString(LDAPException.INVALID_CREDENTIALS), LDAPException.INVALID_CREDENTIALS, LDAPException.resultCodeToString(LDAPException.INVALID_CREDENTIALS)); } else { throw new LDAPException(LDAPException.resultCodeToString(LDAPException.UNAVAILABLE), LDAPException.UNAVAILABLE, post.getStatusText()); } } DSMLReader reader = new DSMLReader(post.getResponseBodyAsStream()); post.releaseConnection(); //Make sure it was successfull ArrayList errors = reader.getErrors(); if (errors.size() > 0) { throw ((LDAPException) errors.get(0)); } if (isSearch) { return new DSMLSearchResults(reader); } else { //return the message return reader.readMessage(); } } catch (HttpException e) { throw new LDAPLocalException("Http Error", LDAPException.CONNECT_ERROR, e); } catch (IOException e) { throw new LDAPLocalException("Communications Error", LDAPException.CONNECT_ERROR, e); } }
From source file:com.redhat.topicindex.security.FedoraAccountSystem.java
@SuppressWarnings("unchecked") private boolean authenticate() throws LoginException { if (password == null || username == null) throw new LoginException("No Username/Password found"); if (password.equals("") || username.equals("")) throw new LoginException("No Username/Password found"); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(FEDORA_JSON_URL); try {//w ww. j av a2s. c o m // Generate the data to send List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new NameValuePair("username", username)); formparams.add(new NameValuePair("user_name", username)); formparams.add(new NameValuePair("password", String.valueOf(password))); formparams.add(new NameValuePair("login", "Login")); method.addParameters(formparams.toArray(new NameValuePair[formparams.size()])); // Send the data and get the response client.executeMethod(method); // Handle the response BufferedReader br = new BufferedReader( new InputStreamReader(new ByteArrayInputStream(method.getResponseBody()))); JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; // Parse the response to check authentication success and valid groups String line; while ((line = br.readLine()) != null) { Map json = (Map) parser.parse(line, containerFactory); if (json.containsKey("success") && json.containsKey("person")) { if (json.get("person") instanceof LinkedHashMap) { LinkedHashMap person = (LinkedHashMap) json.get("person"); if (person.get("status").equals("active")) { if (person.containsKey("approved_memberships")) { if (person.get("approved_memberships") instanceof LinkedList) { if (!checkCLAAgreement(((LinkedList) person.get("approved_memberships")))) { throw new LoginException("FAS authentication failed for " + username + ". Contributor License Agreement not yet signed"); } } else if (person.get("approved_memberships") instanceof LinkedHashMap) { if (!checkCLAAgreement(((LinkedHashMap) person.get("approved_memberships")))) { throw new LoginException("FAS authentication failed for " + username + ". Contributor License Agreement not yet signed"); } } } else { throw new LoginException("FAS authentication failed for " + username + ". Contributor License Agreement not yet signed"); } } else { throw new LoginException( "FAS authentication failed for " + username + ". Account is not active"); } } } else { throw new LoginException("Error: FAS authentication failed for " + username); } } } catch (LoginException e) { throw e; } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } finally { method.releaseConnection(); } return true; }