List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter
public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException
From source file:org.apache.cloudstack.network.element.SspClient.java
public boolean login() { PostMethod method = postMethod; method.setPath("/ws.v1/login"); // NOTE: /ws.v1/login is correct method.addParameter("username", username); method.addParameter("password", password); try {/*from www . ja v a 2 s . c om*/ client.executeMethod(method); } catch (HttpException e) { s_logger.info("Login " + username + " to " + apiUrl + " failed", e); return false; } catch (IOException e) { s_logger.info("Login " + username + " to " + apiUrl + " failed", e); return false; } finally { method.releaseConnection(); } String apiCallPath = null; try { apiCallPath = method.getName() + " " + method.getURI().toString(); } catch (URIException e) { s_logger.error("method getURI failed", e); } s_logger.info("ssp api call:" + apiCallPath + " user=" + username + " status=" + method.getStatusLine()); if (method.getStatusCode() == HttpStatus.SC_OK) { return true; } return false; }
From source file:org.apache.cocoon.transformation.SparqlTransformer.java
private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters) throws ProcessingException, IOException, SAXException { HttpClient httpclient = new HttpClient(); if (System.getProperty("http.proxyHost") != null) { // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost")); String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", ""); if (nonProxyHostsRE.length() > 0) { String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|"); nonProxyHostsRE = ""; for (String pHost : pHosts) { nonProxyHostsRE += "|(^https?://" + pHost + ".*$)"; }// w ww. j a v a2 s. c o m nonProxyHostsRE = nonProxyHostsRE.substring(1); } if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) { try { HostConfiguration hostConfiguration = httpclient.getHostConfiguration(); hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort", "80"))); httpclient.setHostConfiguration(hostConfiguration); } catch (Exception e) { throw new ProcessingException("Cannot set proxy!", e); } } } // Make the HttpMethod. HttpMethod httpMethod = null; // Do not use empty query parameter. if (requestParameters.getParameter(parameterName).trim().equals("")) { requestParameters.removeParameter(parameterName); } // Instantiate different HTTP methods. if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(url); if (requestParameters.getEncodedQueryString() != null) { httpMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpMethod.setQueryString(""); } } else if ("POST".equalsIgnoreCase(method)) { PostMethod httpPostMethod = new PostMethod(url); if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE)) .startsWith("application/x-www-form-urlencoded")) { // Encode parameters in POST body. Iterator parNames = requestParameters.getParameterNames(); while (parNames.hasNext()) { String parName = (String) parNames.next(); httpPostMethod.addParameter(parName, requestParameters.getParameter(parName)); } } else { // Use query parameter as POST body httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName)); // Add other parameters to query string requestParameters.removeParameter(parameterName); if (requestParameters.getEncodedQueryString() != null) { httpPostMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpPostMethod.setQueryString(""); } } httpMethod = httpPostMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod httpPutMethod = new PutMethod(url); httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName)); requestParameters.removeParameter(parameterName); httpPutMethod.setQueryString(requestParameters.getEncodedQueryString()); httpMethod = httpPutMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(url); httpMethod.setQueryString(requestParameters.getEncodedQueryString()); } else { throw new ProcessingException("Unsupported method: " + method); } // Authentication (optional). if (credentials != null && credentials.length() > 0) { String[] unpw = credentials.split("\t"); httpclient.getParams().setAuthenticationPreemptive(true); httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(), httpMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(unpw[0], unpw[1])); } // Add request headers. Iterator headers = httpHeaders.entrySet().iterator(); while (headers.hasNext()) { Map.Entry header = (Map.Entry) headers.next(); httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue()); } // Declare some variables before the try-block. XMLizer xmlizer = null; try { // Execute the request. int responseCode; responseCode = httpclient.executeMethod(httpMethod); // Handle errors, if any. if (responseCode < 200 || responseCode >= 300) { if (showErrors) { AttributesImpl attrs = new AttributesImpl(); attrs.addCDATAAttribute("status", "" + responseCode); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs); String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error"); return; // Not a nice, but quick and dirty way to end. } else { throw new ProcessingException("Received HTTP status code " + responseCode + " " + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString()); } } // Parse the response if (responseCode == 204) { // No content. String statusLine = httpMethod.getStatusLine().toString(); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else if (parse.equalsIgnoreCase("xml")) { InputStream responseBodyStream = httpMethod.getResponseBodyAsStream(); xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE); xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(), new IncludeXMLConsumer(xmlConsumer)); responseBodyStream.close(); } else if (parse.equalsIgnoreCase("text")) { xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); String responseBody = httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else { throw new ProcessingException("Unknown parse type: " + parse); } } catch (ServiceException e) { throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e); } finally { if (xmlizer != null) manager.release((Component) xmlizer); httpMethod.releaseConnection(); } }
From source file:org.apache.geronimo.daytrader.javaee6.web.TradeAppServlet.java
/** * Main service method for TradeAppServlet * /*from w ww . j ava 2s . co m*/ * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ @SuppressWarnings("deprecation") public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = null; String userID = null; // String to create full dispatch path to TradeAppServlet w/ request // Parameters String dispPath = null; // Dispatch Path to TradeAppServlet resp.setContentType("text/html"); TradeServletAction tsAction = new TradeServletAction(); // Dyna - need status string - prepended to output action = req.getParameter("action"); ServletContext ctx = getServletConfig().getServletContext(); if (action == null) { tsAction.doWelcome(ctx, req, resp, ""); return; } else if (action.equals("login")) { userID = req.getParameter("uid"); String passwd = req.getParameter("passwd"); String inScenario = req.getParameter("inScenario"); try { tsAction.doLogin(ctx, req, resp, userID, passwd); } catch (ServletException se) { tsAction.doWelcome(ctx, req, resp, se.getMessage()); } return; } else if (action.equals("register")) { userID = req.getParameter("user id"); String passwd = req.getParameter("passwd"); String cpasswd = req.getParameter("confirm passwd"); String fullname = req.getParameter("Full Name"); String ccn = req.getParameter("Credit Card Number"); String money = req.getParameter("money"); String email = req.getParameter("email"); String smail = req.getParameter("snail mail"); tsAction.doRegister(ctx, req, resp, userID, passwd, cpasswd, fullname, ccn, money, email, smail); return; } else if (action.equals("registerproxy")) { String code = req.getParameter("code"); String state = req.getParameter("state"); String foros = "code=" + code + "&client_id=" + CLIENT_ID + // "&client_secret=" +CLIENT_SECRET + "&grant_type=authorization_code&redirect_uri=http://localhost:8080/daytrader/app?action=registerproxy"; "&client_secret=" + CLIENT_SECRET + "&grant_type=authorization_code&redirect_uri=" + HOST_URL + "daytrader/app?action=registerproxy"; String url = "https://accounts.google.com/o/oauth2/token"; System.out.println("Url:" + url); HttpClient client = new HttpClient(); PostMethod httppost = new PostMethod(url); //httppost httppost.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //ByteArrayRequestEntity entity = new ByteArrayRequestEntity(foros.getBytes("UTF-8")); //httppost.set System.out.println("Foros :" + foros); httppost.addParameter("grant_type", "authorization_code"); httppost.addParameter("code", code); httppost.addParameter("client_id", CLIENT_ID); httppost.addParameter("client_secret", CLIENT_SECRET); //httppost.addParameter("redirect_uri","http://localhost:8080/daytrader/app?action=registerproxy" ); // httppost.setRequestBody(foros); // httppost.setEntity(entity); httppost.addParameter("redirect_uri", HOST_URL + "daytrader/app?action=registerproxy"); // httppost.setRequestBody(foros); // httppost.setEntity(entity); String accessToken = null; try { // client.set int responseCode = client.executeMethod(httppost); String jsonResponse = httppost.getResponseBodyAsString(); System.out.println("jsonResponse:" + jsonResponse); JSONObject jsonParser = new JSONObject(jsonResponse); accessToken = (String) jsonParser.getString("access_token"); System.out.println("Access Token:" + accessToken); GetMethod userInfoGet = new GetMethod(GOOGLE_SSO_URL + accessToken); String googleId = null; String email = null; String name = null; String firstName = null; String lastName = null; try { responseCode = client.executeMethod(userInfoGet); String userInfo = userInfoGet.getResponseBodyAsString(); JSONObject userInfoParser = new JSONObject(userInfo); googleId = (String) userInfoParser.getString("id"); email = (String) userInfoParser.getString("email"); name = (String) userInfoParser.getString("name"); firstName = (String) userInfoParser.getString("given_name"); lastName = (String) userInfoParser.getString("family_name"); userID = email; try {//tsAction. String results = ""; try { tsAction.doCheck(ctx, req, resp, userID, results); tsAction.doLogin(ctx, req, resp, userID); } catch (Exception ex) { results = "NOT_FOUND"; tsAction.doRegister(ctx, req, resp, email, "password", "password", firstName + " " + lastName, "CCN", "500", email, "Please update Address"); req.getRequestDispatcher("/app?action=login&uid=" + email + "&passwd=password") .forward(req, resp); } /*Log.error("Looking for request status: "+ results); if (results.equals("FOUND")) else */ } catch (Exception ex) { //tsAction.doLogin(ctx, req, resp, userID, passwd); } } catch (IOException e) { throw new RuntimeException(e); } } catch (Exception e) { throw new RuntimeException(e); } } // The rest of the operations require the user to be logged in - // Get the Session and validate the user. HttpSession session = req.getSession(); userID = (String) session.getAttribute("uidBean"); if (userID == null) { System.out.println("TradeAppServlet service error: User Not Logged in"); tsAction.doWelcome(ctx, req, resp, "User Not Logged in"); return; } if (action.equals("quotes")) { String symbols = req.getParameter("symbols"); tsAction.doQuotes(ctx, req, resp, userID, symbols); } else if (action.equals("buy")) { String symbol = req.getParameter("symbol"); String quantity = req.getParameter("quantity"); tsAction.doBuy(ctx, req, resp, userID, symbol, quantity); } else if (action.equals("sell")) { int holdingID = Integer.parseInt(req.getParameter("holdingID")); tsAction.doSell(ctx, req, resp, userID, new Integer(holdingID)); } else if (action.equals("portfolio") || action.equals("portfolioNoEdge")) { tsAction.doPortfolio(ctx, req, resp, userID, "Portfolio as of " + new java.util.Date()); } else if (action.equals("logout")) { tsAction.doLogout(ctx, req, resp, userID); } else if (action.equals("home")) { tsAction.doHome(ctx, req, resp, userID, "Ready to Trade"); } else if (action.equals("account")) { tsAction.doAccount(ctx, req, resp, userID, ""); } else if (action.equals("update_profile")) { String password = req.getParameter("password"); String cpassword = req.getParameter("cpassword"); String fullName = req.getParameter("fullname"); String address = req.getParameter("address"); String creditcard = req.getParameter("creditcard"); String email = req.getParameter("email"); tsAction.doAccountUpdate(ctx, req, resp, userID, password == null ? "" : password.trim(), cpassword == null ? "" : cpassword.trim(), fullName == null ? "" : fullName.trim(), address == null ? "" : address.trim(), creditcard == null ? "" : creditcard.trim(), email == null ? "" : email.trim()); } else { System.out.println("TradeAppServlet: Invalid Action=" + action); tsAction.doWelcome(ctx, req, resp, "TradeAppServlet: Invalid Action" + action); } }
From source file:org.apache.geronimo.testsuite.security.TestConsoleSecurity.java
private PostMethod login(HttpClient httpClient, String username, String password) throws Exception { String response = doGet(httpClient, "http://localhost:8080/console"); assertTrue("Expected login form", response.contains("Console Login")); PostMethod postMethod = new PostMethod("http://localhost:8080/console/j_security_check"); if (username != null) { postMethod.addParameter("j_username", username); }// w ww. j a v a 2s.co m if (password != null) { postMethod.addParameter("j_password", password); } return postMethod; }
From source file:org.apache.geronimo.testsuite.security.TestSecurity.java
private PostMethod login(HttpClient httpClient, String username, String password) throws Exception { String response = doGet(httpClient, "http://localhost:8080/demo/protect/hello.html"); assertTrue("Expected authentication form", response.contains("FORM Authentication demo")); PostMethod postMethod = new PostMethod("http://localhost:8080/demo/j_security_check"); if (username != null) { postMethod.addParameter("j_username", username); }/*from ww w . j a v a 2 s .co m*/ if (password != null) { postMethod.addParameter("j_password", password); } return postMethod; }
From source file:org.apache.gobblin.kafka.schemareg.LiKafkaSchemaRegistry.java
/** * Register a schema to the Kafka schema registry under the provided input name. This method will change the name * of the schema to the provided name if configured to do so. This is useful because certain services (like Gobblin kafka adaptor and * Camus) get the schema for a topic by querying for the latest schema with the topic name, requiring the topic * name and schema name to match for all topics. If it is not configured to switch names, this is useful for the case * where the Kafka topic and Avro schema names do not match. This method registers the schema to the schema registry in such a * way that any schema can be written to any topic. * * @param schema {@link org.apache.avro.Schema} to register. * @param name Name of the schema when registerd to the schema registry. This name should match the name * of the topic where instances will be published. * @return schema ID of the registered schema. * @throws SchemaRegistryException if registration failed *//*w w w. ja v a 2 s . co m*/ @Override public MD5Digest register(String name, Schema schema) throws SchemaRegistryException { PostMethod post = new PostMethod(url); if (this.switchTopicNames) { return register(AvroUtils.switchName(schema, name), post); } else { post.addParameter("name", name); return register(schema, post); } }
From source file:org.apache.gobblin.kafka.schemareg.LiKafkaSchemaRegistry.java
/** * Register a schema to the Kafka schema registry * * @param schema// ww w . j a v a2s . c o m * @param post * @return schema ID of the registered schema * @throws SchemaRegistryException if registration failed */ public synchronized MD5Digest register(Schema schema, PostMethod post) throws SchemaRegistryException { // Change namespace if override specified if (this.namespaceOverride.isPresent()) { schema = AvroUtils.switchNamespace(schema, this.namespaceOverride.get()); } LOG.info("Registering schema " + schema.toString()); post.addParameter("schema", schema.toString()); HttpClient httpClient = this.borrowClient(); try { LOG.debug("Loading: " + post.getURI()); int statusCode = httpClient.executeMethod(post); if (statusCode != HttpStatus.SC_CREATED) { throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode); } String response; response = post.getResponseBodyAsString(); if (response != null) { LOG.info("Received response " + response); } String schemaKey; Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME); if (headers.length != 1) { throw new SchemaRegistryException( "Error reading schema id returned by registerSchema call: headers.length = " + headers.length); } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) { throw new SchemaRegistryException( "Error parsing schema id returned by registerSchema call: header = " + headers[0].getValue()); } else { LOG.info("Registered schema successfully"); schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length()); } MD5Digest schemaId = MD5Digest.fromString(schemaKey); return schemaId; } catch (Throwable t) { throw new SchemaRegistryException(t); } finally { post.releaseConnection(); this.httpClientPool.returnObject(httpClient); } }
From source file:org.apache.gobblin.metrics.kafka.KafkaAvroSchemaRegistry.java
/** * Register a schema to the Kafka schema registry * * @param schema// w ww . j a v a 2 s . com * @return schema ID of the registered schema * @throws SchemaRegistryException if registration failed */ @Override public synchronized String register(Schema schema) throws SchemaRegistryException { // Change namespace if override specified if (this.namespaceOverride.isPresent()) { schema = AvroUtils.switchNamespace(schema, this.namespaceOverride.get()); } LOG.info("Registering schema " + schema.toString()); PostMethod post = new PostMethod(url); post.addParameter("schema", schema.toString()); HttpClient httpClient = this.borrowClient(); try { LOG.debug("Loading: " + post.getURI()); int statusCode = httpClient.executeMethod(post); if (statusCode != HttpStatus.SC_CREATED) { throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode); } String response; response = post.getResponseBodyAsString(); if (response != null) { LOG.info("Received response " + response); } String schemaKey; Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME); if (headers.length != 1) { throw new SchemaRegistryException( "Error reading schema id returned by registerSchema call: headers.length = " + headers.length); } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) { throw new SchemaRegistryException( "Error parsing schema id returned by registerSchema call: header = " + headers[0].getValue()); } else { LOG.info("Registered schema successfully"); schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length()); } return schemaKey; } catch (Throwable t) { throw new SchemaRegistryException(t); } finally { post.releaseConnection(); this.httpClientPool.returnObject(httpClient); } }
From source file:org.apache.jackrabbit.spi2davex.RepositoryServiceImpl.java
public void copy(SessionInfo sessionInfo, String srcWorkspaceName, NodeId srcNodeId, NodeId destParentNodeId, Name destName) throws RepositoryException { if (srcWorkspaceName.equals(sessionInfo.getWorkspaceName())) { super.copy(sessionInfo, srcWorkspaceName, srcNodeId, destParentNodeId, destName); return;//from www.j a v a 2 s. com } PostMethod method = null; try { method = new PostMethod(getWorkspaceURI(sessionInfo)); NamePathResolver resolver = getNamePathResolver(sessionInfo); StringBuffer args = new StringBuffer(); args.append(srcWorkspaceName); args.append(","); args.append(resolver.getJCRPath(getPath(srcNodeId, sessionInfo))); args.append(","); String destParentPath = resolver.getJCRPath(getPath(destParentNodeId, sessionInfo)); String destPath = (destParentPath.endsWith("/") ? destParentPath + resolver.getJCRName(destName) : destParentPath + "/" + resolver.getJCRName(destName)); args.append(destPath); method.addParameter(PARAM_COPY, args.toString()); addIfHeader(sessionInfo, method); getClient(sessionInfo).executeMethod(method); method.checkSuccess(); } catch (IOException e) { throw new RepositoryException(e); } catch (DavException e) { throw ExceptionConverter.generate(e); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:org.apache.jackrabbit.spi2davex.RepositoryServiceImpl.java
public void clone(SessionInfo sessionInfo, String srcWorkspaceName, NodeId srcNodeId, NodeId destParentNodeId, Name destName, boolean removeExisting) throws RepositoryException { PostMethod method = null; try {/* w ww . j a va 2 s . c om*/ method = new PostMethod(getWorkspaceURI(sessionInfo)); NamePathResolver resolver = getNamePathResolver(sessionInfo); StringBuffer args = new StringBuffer(); args.append(srcWorkspaceName); args.append(","); args.append(resolver.getJCRPath(getPath(srcNodeId, sessionInfo))); args.append(","); String destParentPath = resolver.getJCRPath(getPath(destParentNodeId, sessionInfo)); String destPath = (destParentPath.endsWith("/") ? destParentPath + resolver.getJCRName(destName) : destParentPath + "/" + resolver.getJCRName(destName)); args.append(destPath); args.append(","); args.append(Boolean.toString(removeExisting)); method.addParameter(PARAM_CLONE, args.toString()); addIfHeader(sessionInfo, method); getClient(sessionInfo).executeMethod(method); method.checkSuccess(); } catch (IOException e) { throw new RepositoryException(e); } catch (DavException e) { throw ExceptionConverter.generate(e); } finally { if (method != null) { method.releaseConnection(); } } }