List of usage examples for org.apache.commons.httpclient HttpException printStackTrace
public void printStackTrace()
From source file:eu.impact_project.iif.t2.client.WorkflowUploader.java
/** * Gets the groups and workflow infos from myExperiment *///from w w w .java2 s . co m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // to find out own userID String urlStringWhoami = "http://www.myexperiment.org/whoami.xml"; if (request.getParameter("myexp_user") != null && request.getParameter("myexp_password") != null) { HttpSession session = request.getSession(true); String user = request.getParameter("myexp_user"); String password = request.getParameter("myexp_password"); // WorkflowParser also needs the credentials session.setAttribute("user", user); session.setAttribute("password", password); // session.setAttribute("selectedGroupName", null); // the client will be used to query myexperiment's REST api HttpClient client = Helper.createAuthenticatingClient("www.myexperiment.org", user, password); // GET method for retrieving the xml with the userID GetMethod get = new GetMethod(urlStringWhoami); // api needs basic authentication get.setDoAuthentication(true); try { int status = client.executeMethod(get); if (status == 200) { session.setAttribute("logged_in", "true"); request.setAttribute("login_error", null); InputStream xmlResponse = get.getResponseBodyAsStream(); // get the user uri which contains the userID, // userID does not need to be extracted, // the uri can be used directly to query the api for infos // about the user Attribute attr = (Attribute) Helper.applyXPathSingleNode(xmlResponse, "//user/@uri"); String userUri = attr.getValue(); // GET method to retrieve all groups of the user get = new GetMethod(userUri + "&elements=groups"); client.executeMethod(get); xmlResponse = get.getResponseBodyAsStream(); // get all groups from received xml List<Element> groupElements = Helper.applyXPathSeveralNodes(xmlResponse, "//group"); // will be used in the jsp to construct selection lists Map<String, List<WorkflowInfo>> allWfInfos = new LinkedHashMap<String, List<WorkflowInfo>>(); // if the user is in the impact group, then it will be the // default selection in the jsp, or else it will be the // first group boolean isFirstGroup = true; for (Element group : groupElements) { String groupUri = group.getAttributeValue("uri"); String groupName = group.getTextTrim(); // set the default selection if (isFirstGroup || groupName.startsWith("IMPACT")) { session.setAttribute("selectedGroupName0", groupName); session.setAttribute("selectedGroupName1", groupName); isFirstGroup = false; } // GET method for retrieving all workflow infos of a // group get = new GetMethod(groupUri + "&elements=shared-items"); client.executeMethod(get); xmlResponse = get.getResponseBodyAsStream(); // extract the necessary information from received xml List<WorkflowInfo> wfInfos = createWfInfos(xmlResponse); // map for jsp allWfInfos.put(groupName, wfInfos); } // GET method for retrieving all workflow infos of the user get = new GetMethod(userUri + "&elements=workflows"); client.executeMethod(get); xmlResponse = get.getResponseBodyAsStream(); // extract the necessary information from received xml List<WorkflowInfo> wfInfosUser = createWfInfos(xmlResponse); if (wfInfosUser != null && wfInfosUser.size() > 0) { // the select will show this under the other groups allWfInfos.put("Own workflows", wfInfosUser); } session.setAttribute("allWfInfos", allWfInfos); session.setAttribute("currentTab0", "remote"); session.setAttribute("currentTab1", "remote"); } else { session.setAttribute("logged_in", "false"); request.setAttribute("login_error", "Login error"); session.setAttribute("currentTab0", "local"); session.setAttribute("currentTab1", "local"); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } finally { // release any connection resources used by the method get.releaseConnection(); } } RequestDispatcher rd = getServletContext().getRequestDispatcher(redirect); rd.forward(request, response); }
From source file:MemoryController.java
@RequestMapping("/memory") public @ResponseBody Memory memory( @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication, @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid, @RequestParam(value = "metricType", required = false, defaultValue = "") String name) throws FileNotFoundException, UnsupportedEncodingException, IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream("properties.xml"); //loading properites from properties file props.loadFromXML(fis);// w w w. ja v a2 s .c om String server_ip = props.getProperty("server_ip"); String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip JSONParser parser = new JSONParser(); HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(ZABBIX_API_URL); putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj = new JSONObject(); jsonObj.put("jsonrpc", "2.0"); jsonObj.put("method", "item.get"); JSONObject params = new JSONObject(); params.put("output", "extend"); params.put("hostid", hostid); JSONObject search = new JSONObject(); search.put("key_", "memory"); params.put("search", search); params.put("sortfield", "name"); jsonObj.put("params", params); jsonObj.put("auth", authentication);// todo jsonObj.put("id", new Integer(1)); putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body PutMethod putMethod2 = new PutMethod(ZABBIX_API_URL); putMethod2.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj2 = new JSONObject(); jsonObj2.put("jsonrpc", "2.0"); jsonObj2.put("method", "item.get"); JSONObject params2 = new JSONObject(); params2.put("output", "extend"); params2.put("hostid", hostid); JSONObject search2 = new JSONObject(); search2.put("key_", "swap"); params2.put("search", search2); params2.put("sortfield", "name"); jsonObj2.put("params", params2); jsonObj2.put("auth", authentication);// todo jsonObj2.put("id", new Integer(1)); putMethod2.setRequestBody(jsonObj2.toString()); String loginResponse = ""; String loginResponse2 = ""; String memory = ""; String clock = ""; String metricType = ""; try { client.executeMethod(putMethod); // send to request to the zabbix api loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response Object obj = parser.parse(loginResponse); JSONObject obj2 = (JSONObject) obj; String jsonrpc = (String) obj2.get("jsonrpc"); JSONArray array = (JSONArray) obj2.get("result"); client.executeMethod(putMethod2); // send to request to the zabbix api loginResponse2 = putMethod2.getResponseBodyAsString(); // read the result of the response Object obj3 = parser.parse(loginResponse2); JSONObject obj4 = (JSONObject) obj3; String jsonrpc2 = (String) obj4.get("jsonrpc"); JSONArray array2 = (JSONArray) obj4.get("result"); for (int i = 0; i < array.size(); i++) { JSONObject tobj = (JSONObject) array.get(i); // lastValue = getLastValue(tobj); // lastClock = getLastClock(tobj); if (!tobj.get("hostid").equals(hostid)) continue; if (name.equals("totalMemory") && tobj.get("name").equals("Total memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Total Memeory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("cachedMemory") && tobj.get("name").equals("Cached memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Cached Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("freeMemory") && tobj.get("name").equals("Free memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Free Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("bufferedMemory") && tobj.get("name").equals("Buffers memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Buffered Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("sharedMemory") && tobj.get("name").equals("Shared memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Shared Memory"; return new Memory(hostid, metricType, memory, clock); } else { continue; } } for (int i = 0; i < array2.size(); i++) { JSONObject tobj2 = (JSONObject) array2.get(i); if (!tobj2.get("hostid").equals(hostid)) continue; if (name.equals("freeSwap") && tobj2.get("name").equals("Free swap space")) { memory = (String) tobj2.get("lastvalue"); clock = (String) tobj2.get("lastclock"); metricType = "Free Swap Space"; return new Memory(hostid, metricType, memory, clock); } else { continue; } } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException pe) { System.out.println("Error"); } return new Memory( "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:"); }
From source file:com.apatar.webdav.ui.JWebDavTreeModePanel.java
private void makeWebDavPath(String name) { if ("..".equals(name)) { try {// w w w. jav a 2s. c o m String path = currentres.getHttpURL().toString(); path = path.replaceAll("%20", " "); if (!path.equalsIgnoreCase(url)) { int ind = path.lastIndexOf(separator); path = path.substring(0, ind); currentres = new WebdavResource(getHttpUrl(path), true); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { if (null != name) { try { currentres = currentres.getChildResources().getResource(name); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } setValueToLabelPath(currentres.getHttpURL().toString().replace("%20", " ")); setDataFromWebDavToTable(); }
From source file:com.idega.slide.authentication.IWSlideAuthenticator.java
public void doAuthentication(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) arg0; HttpServletResponse response = (HttpServletResponse) arg1; HttpSession session = request.getSession(); LoginBusinessBean loginBusiness = getLoginBusiness(request); try {/*from www .ja v a 2 s . c om*/ if (loginBusiness.isLoggedOn(request)) { LoggedOnInfo lInfo = loginBusiness.getLoggedOnInfo(session); if (lInfo == null) { setAsUnauthenticatedInSlide(session); } else { request = setAsAuthenticatedInSlide(request, lInfo.getLogin(), lInfo); } } else { String[] loginAndPassword = loginBusiness .getLoginNameAndPasswordFromBasicAuthenticationRequest(request); String loggedInUser = getUserAuthenticatedBySlide(session); if (loginAndPassword != null) { String username = loginAndPassword[0]; String password = loginAndPassword[1]; LoggedOnInfo lInfo = loginBusiness.getLoggedOnInfo(session, username); if (loggedInUser == null) { if (isAuthenticated(request, lInfo, username, password)) { request = setAsAuthenticatedInSlide(request, username, lInfo); } else { setAsUnauthenticatedInSlide(session); } } else if (!username.equals(loggedInUser)) { if (isAuthenticated(request, lInfo, username, password)) { request = setAsAuthenticatedInSlide(request, username, lInfo); } else { setAsUnauthenticatedInSlide(session); } } } else if (loggedInUser != null) { setAsUnauthenticatedInSlide(session); } } } catch (HttpException e) { e.printStackTrace(); response.sendError(e.getReasonCode(), e.getReason()); return; } // the slide token is set so that business methods can get it from IWSlideSession. // The WebdavUtils#getSlideToken(request) can be expensive since it copies pointers to all attributes from session to the token. // This is used e.g. to check for permissions(i.e. to calculate permissions using the ACLSecurityImpl) IWSlideSession slideSession = IBOLookup.getSessionInstance(session, IWSlideSession.class); slideSession.setSlideToken(WebdavUtils.getSlideToken(request)); arg2.doFilter(request, response); //2005.05.27 - Gummi //Workaround to ensure that the response is fully flushed. //Needed because of troubles with jakarta-slide. //iwc.getWriter().flush(); }
From source file:it.drwolf.ridire.session.async.JobDBDataUpdater.java
public String getCrawlerEngineStatus() { HttpMethod method = null;/* w ww. j a va 2 s.c o m*/ int status = -1; try { method = new GetMethod(this.engineUri); // TODO check status status = this.httpClient.executeMethod(method); method.releaseConnection(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (method != null) { method.releaseConnection(); } } if (status == 200) { return CrawlerManager.RUNNING; } return CrawlerManager.STOPPED; }
From source file:it.drwolf.ridire.session.async.JobDBDataUpdater.java
public String getCrawlStatus(String jobName) throws HeritrixException { Job j = this.getPersistedJob(jobName); if (j != null) { try {// www . ja v a 2 s. co m return this.getJobStatus(jobName); } catch (HttpException e) { e.printStackTrace(); throw new HeritrixException(); } catch (IOException e) { e.printStackTrace(); throw new HeritrixException(); } catch (DocumentException e) { e.printStackTrace(); throw new HeritrixException(); } } return null; }
From source file:com.sun.portal.rssportlet.FeedHelper.java
/** * Get the ROME SyndFeed object for the specified feed. The object may come * from a cache; the data in the feed may not be read at the time * this method is called.//from w w w. j av a 2 s . c o m * * The <code>RssPortletBean</code> object is used to identify the feed * of interest, and the timeout value to be used when managing this * feed's cached value. * * @param bean an <code>RssPortletBean</code> object that describes * the feed of interest, and the cache timeout value for the feed. * @return a ROME <code>SyndFeed</code> object encapsulating the * feed specified by the URL. */ public SyndFeed getFeed(SettingsBean bean, String selectedFeed) throws IOException, FeedException { SyndFeed feed = null; FeedElement feedElement = (FeedElement) feeds.get(selectedFeed); if (feedElement != null && !feedElement.isExpired()) { feed = feedElement.getFeed(); } else { GetMethod httpget = null; try { SyndFeedInput input = new SyndFeedInput(); HttpClient httpclient = new HttpClient(); httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT); // SO_TIMEOUT -- timeout for blocking reads httpclient.getHttpConnectionManager().getParams().setSoTimeout(SOCKET_TIMEOUT); httpget = new GetMethod(selectedFeed); //httpget.getParams().setParameter("http.socket.timeout", new Integer(20000)); // Internally the parameter collections will be linked together // by performing the following operations: // hostconfig.getParams().setDefaults(httpclient.getParams()); // httpget.getParams().setDefaults(hostconfig.getParams()); //httpclient.executeMethod(hostconfig, httpget); // Execute the method. int statusCode = httpclient.executeMethod(httpget); if (statusCode != HttpStatus.SC_OK) { log.info("Method failed: " + httpget.getStatusLine()); } // Read the response body. InputSource src = new InputSource(httpget.getResponseBodyAsStream()); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data feed = input.build(src); // // only cache the feed if the cache timeout is not equal to 0 // a cache timeout of 0 means "don't cache" // int timeout = bean.getCacheTimeout(); if (timeout != 0) { putFeed(selectedFeed, feed, timeout); } } catch (MalformedURLException mfurlex) { log.info("MalformedURLException: " + mfurlex.getMessage()); mfurlex.printStackTrace(); throw new IOException("MalformedURLException: " + mfurlex.getMessage()); } catch (HttpException httpex) { log.info("Fatal protocol violation: " + httpex.getMessage()); httpex.printStackTrace(); throw new IOException("Fatal protocol violation: " + httpex.getMessage()); } catch (IllegalArgumentException iae) { log.info("IllegalArgumentException: " + iae.getMessage()); iae.printStackTrace(); throw new IOException("IllegalArgumentException: " + iae.getMessage()); } catch (IOException ioe) { log.info("Fatal transport error: " + ioe.getMessage()); ioe.printStackTrace(); throw new IOException("Fatal transport error: " + ioe.getMessage()); } catch (ParsingFeedException parsingfeedex) { log.info("ParsingFeedException: " + parsingfeedex.getMessage()); parsingfeedex.printStackTrace(); throw new FeedException("ParsingFeedException: " + parsingfeedex.getMessage()); } catch (FeedException feedex) { log.info("FeedException: " + feedex.getMessage()); feedex.printStackTrace(); throw new FeedException("FeedException: " + feedex.getMessage()); } catch (Exception ex) { log.info("Exception ERROR: " + ex.getMessage()); ex.printStackTrace(); } finally { // Release the connection. httpget.releaseConnection(); } } return feed; }
From source file:com.dimdim.conference.application.portal.PortalServerAdapter.java
/** * @param url/* w w w . j a v a2s.com*/ * @param arguments * @return */ protected synchronized String getURL_String(HttpClient client, String url) { GetMethod method = null; String responseBody = null; try { System.out.println("Getting URL:" + url); // System.out.println("Posting data:"+args); method = new GetMethod(url); // method.setRequestBody(args); method.setFollowRedirects(true); //execute the method client.setTimeout(2000); System.out.println("Calling url:" + url); StringBuffer buf = new StringBuffer(); client.executeMethod(method); InputStream is = method.getResponseBodyAsStream(); BufferedInputStream bis = new BufferedInputStream(is); byte[] ary = new byte[256]; int len = 0; while ((len = bis.read(ary, 0, 256)) > 0) { String str = new String(ary, 0, len); // System.out.println("Received buffer:"+str); buf.append(str); } try { bis.close(); is.close(); } catch (Exception e) { } responseBody = buf.toString(); System.out.println("Called ----:" + url); } catch (HttpException he) { he.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } //clean up the connection resources try { method.releaseConnection(); } catch (Exception ee) { // Ignore the exceptions in cleanup. } return responseBody; }
From source file:eu.eco2clouds.scheduler.em.EMClientHC.java
private String postMethod(String url, String payload, String contentType, Boolean exception) { // Create an instance of HttpClient. HttpClient client = getHttpClient(); logger.debug("Connecting to: " + url); // Create a method instance. PostMethod method = new PostMethod(url); //setHeaders(method, contentType); setHeaders(method, Configuration.bonfireApiGroup); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); String response = ""; try {/*from w w w . ja va 2 s.c om*/ RequestEntity requestEntity = new StringRequestEntity(payload, contentType, null); method.setRequestEntity(requestEntity); // Execute the method. int statusCode = client.executeMethod(method); if (statusCode >= 200 && statusCode > 300) { //TODO test for this case... logger.warn( "post managed experiments information... : " + url + " failed: " + method.getStatusLine()); } else { // Read the response body. byte[] responseBody = method.getResponseBody(); response = new String(responseBody); } } catch (HttpException e) { logger.warn("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); exception = true; } catch (IOException e) { logger.warn("Fatal transport error: " + e.getMessage()); e.printStackTrace(); exception = true; } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java
public void logout() { // create client and configure it HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); // instantiating a new method and configuring it GetMethod method = new GetMethod(restCommandUrlPrefix + "logout"); method.setFollowRedirects(true); // ? // Provide custom retry handler is necessary (?) method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); NameValuePair[] params = new NameValuePair[] { new NameValuePair("ticket", ticket) }; // TODO always provide ticket method.setQueryString(params);/* w w w .j av a2 s .c o m*/ try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data System.out.println(new String(responseBody)); } catch (HttpException e) { // TODO e.printStackTrace(); } catch (IOException e) { // TODO e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }