List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream
public abstract InputStream getResponseBodyAsStream() throws IOException;
From source file:com.hp.alm.ali.rest.client.AliRestClient.java
private void writeResponse(ResultInfo result, HttpMethod method, boolean writeBodyAndHeaders) { OutputStream bodyStream = result.getBodyStream(); StatusLine statusLine = method.getStatusLine(); if (statusLine != null) { result.setReasonPhrase(statusLine.getReasonPhrase()); }/*from ww w . j a va2s. co m*/ try { result.setLocation(method.getURI().toString()); } catch (URIException e) { throw new RuntimeException(e); } if (writeBodyAndHeaders) { Map<String, String> headersMap = result.getHeaders(); Header[] headers = method.getResponseHeaders(); for (Header header : headers) { headersMap.put(header.getName(), header.getValue()); } } result.setHttpStatus(method.getStatusCode()); Filter filter = new IdentityFilter(result); for (ResponseFilter responseFilter : responseFilters) { filter = responseFilter.applyFilter(filter, method, result); } if (writeBodyAndHeaders && bodyStream != null && method.getStatusCode() != 204) { try { InputStream responseBody = method.getResponseBodyAsStream(); if (responseBody != null) { IOUtils.copy(responseBody, filter.getOutputStream()); bodyStream.flush(); bodyStream.close(); } } catch (IOException e) { throw new RuntimeException(e); } } }
From source file:net.sf.taverna.raven.plugins.PluginManager.java
/** * Returns all the <code>Plugin</code>s available from the * <code>PluginSite</code>./*www . j av a 2 s . c o m*/ * * @param pluginSite * @return all the <code>Plugin</code>s available from the * <code>PluginSite</code> */ @SuppressWarnings("unchecked") public List<Plugin> getPluginsFromSite(PluginSite pluginSite) { List<Plugin> plugins = new ArrayList<Plugin>(); HttpClient client = new HttpClient(); client.setConnectionTimeout(TIMEOUT); client.setTimeout(TIMEOUT); setProxy(client); if (pluginSite.getUrl() == null) { logger.error("No plugin site URL" + pluginSite); return plugins; } URI pluginSiteURI; try { pluginSiteURI = pluginSite.getUrl().toURI(); } catch (URISyntaxException e) { logger.error("Invalid plugin site URL" + pluginSite); return plugins; } URI pluginsXML = pluginSiteURI.resolve("pluginlist.xml"); HttpMethod getPlugins = new GetMethod(pluginsXML.toString()); int statusCode; try { statusCode = client.executeMethod(getPlugins); } catch (UnknownHostException e) { logger.warn("Could not fetch plugins from non-existing host", e); return plugins; } catch (IOException e) { logger.warn("Could not fetch plugins " + pluginsXML, e); return plugins; } if (statusCode != HttpStatus.SC_OK) { logger.warn("HTTP status " + statusCode + " while getting plugins " + pluginsXML); return plugins; } Document pluginsDocument; try { pluginsDocument = new SAXBuilder().build(getPlugins.getResponseBodyAsStream()); } catch (JDOMException e) { logger.warn("Could not parse plugins " + pluginsXML, e); return plugins; } catch (IOException e) { logger.warn("Could not read plugins " + pluginsXML, e); return plugins; } List<Element> pluginList = pluginsDocument.getRootElement().getChildren("plugin"); for (Element pluginElement : pluginList) { URI pluginUri; try { pluginUri = pluginSiteURI.resolve(pluginElement.getTextTrim()); } catch (IllegalArgumentException ex) { logger.warn("Invalid plugin URI " + pluginElement.getTextTrim()); continue; } HttpMethod getPlugin = new GetMethod(pluginUri.toString()); try { statusCode = client.executeMethod(getPlugin); } catch (IOException e) { logger.warn("Could not fetch plugin " + pluginUri, e); continue; } if (statusCode != HttpStatus.SC_OK) { logger.warn("HTTP status " + statusCode + " while getting plugin " + pluginUri); continue; } Plugin plugin; try { XmlOptions xmlOptions = makeXMLOptions(); xmlOptions.setLoadReplaceDocumentElement(new QName(PLUGINS_NS, "plugin")); PluginDocument pluginDoc = PluginDocument.Factory.parse(getPlugin.getResponseBodyAsStream(), xmlOptions); plugin = Plugin.fromXmlBean(pluginDoc.getPlugin()); } catch (XmlException e1) { logger.warn("Could not parse plugin " + pluginUri, e1); continue; } catch (IOException e1) { logger.warn("Could not read plugin " + pluginUri, e1); continue; } if (checkPluginCompatibility(plugin)) { plugins.add(plugin); logger.debug("Added plugin from " + pluginUri); } else { logger.debug("Plugin deemed incompatible so not added to available plugin list"); } } logger.info("Added plugins from " + pluginSiteURI); return plugins; }
From source file:mitm.common.security.crl.HTTPCRLDownloadHandler.java
private Collection<? extends CRL> downloadCRLs(URI uri, TaskScheduler watchdog) throws IOException, HttpException, CRLException, FileNotFoundException { Collection<? extends CRL> crls = null; HttpClient httpClient = new HttpClient(); HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams(); params.setConnectionTimeout((int) downloadParameters.getConnectTimeout()); params.setSoTimeout((int) downloadParameters.getReadTimeout()); if (proxyInjector != null) { try {/*from w w w . jav a2 s . c o m*/ proxyInjector.setProxy(httpClient); } catch (ProxyException e) { throw new IOException(e); } } HttpMethod getMethod = new GetMethod(uri.toString()); getMethod.setFollowRedirects(true); getMethod.setRequestHeader("User-Agent", NetUtils.HTTP_USER_AGENT); /* * Add watchdog that will interrupt the thread on timeout. we want the abort to fire first so add 50% */ Task threadWatchdogTask = new ThreadInterruptTimeoutTask(Thread.currentThread(), watchdog.getName()); watchdog.addTask(threadWatchdogTask, (long) (downloadParameters.getTotalTimeout() * 1.5)); /* * Add watchdog that will abort the HTTPMethod on timeout. we want to close the input first so add 20% */ Task httpMethodAbortTimeoutTask = new HTTPMethodAbortTimeoutTask(getMethod, watchdog.getName()); watchdog.addTask(httpMethodAbortTimeoutTask, (long) (downloadParameters.getTotalTimeout() * 1.2)); try { logger.debug("Setting up a connection to: " + uri); int statusCode = 0; try { statusCode = httpClient.executeMethod(getMethod); } catch (IllegalArgumentException e) { /* * HttpClient can throw IllegalArgumentException when the host is not set */ throw new CRLException(e); } if (statusCode != HttpStatus.SC_OK) { throw new IOException("Error getting CRL. Message: " + getMethod.getStatusLine()); } InputStream urlStream = getMethod.getResponseBodyAsStream(); if (urlStream == null) { throw new IOException("Response body is null."); } /* * add a timeout watchdog on the input */ Task inputWatchdogTask = new InputStreamTimeoutTask(urlStream, watchdog.getName()); watchdog.addTask(inputWatchdogTask, downloadParameters.getTotalTimeout()); /* * we want to set a max on the number of bytes to download. We do not want * a rogue server to provide us with a 1 TB CRL. */ InputStream limitInputStream = new SizeLimitedInputStream(urlStream, downloadParameters.getMaxBytes()); ReadableOutputStreamBuffer output = new ReadableOutputStreamBuffer(memThreshold); try { IOUtils.copy(limitInputStream, output); if (threadWatchdogTask.hasRun() || httpMethodAbortTimeoutTask.hasRun() || inputWatchdogTask.hasRun()) { /* a timeout has occurred */ throw new IOException(TIMEOUT_ERROR + uri); } try { InputStream input = output.getInputStream(); try { crls = CRLUtils.readCRLs(input); } finally { IOUtils.closeQuietly(input); } if (crls == null || crls.size() == 0) { logger.debug("No CRLs found in the downloaded stream."); } } catch (CertificateException e) { throw new CRLException(e); } catch (NoSuchProviderException e) { throw new CRLException(e); } catch (SecurityFactoryFactoryException e) { throw new CRLException(e); } } finally { /* * we need to close ReadableOutputStreamBuffer to prevent temp file leak */ IOUtils.closeQuietly(output); } } finally { getMethod.releaseConnection(); } return crls; }
From source file:edu.unc.lib.dl.admin.controller.RESTProxyController.java
@RequestMapping(value = { "/services/rest", "/services/rest/*", "/services/rest/**/*" }) public final void proxyAjaxCall(HttpServletRequest request, HttpServletResponse response) throws IOException { log.debug("Prepending service url " + this.servicesUrl + " to " + request.getRequestURI()); String url = request.getRequestURI().replaceFirst(".*/services/rest/?", this.servicesUrl); if (request.getQueryString() != null) url = url + "?" + request.getQueryString(); OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream()); HttpClient client = new HttpClient(); HttpMethod method = null; try {/*w ww. java2s .c o m*/ log.debug("Proxying ajax request to services REST api via " + request.getMethod()); // Split this according to the type of request if (request.getMethod().equals("GET")) { method = new GetMethod(url); } else if (request.getMethod().equals("POST")) { method = new PostMethod(url); // Set any eventual parameters that came with our original // request (POST params, for instance) Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); ((PostMethod) method).setParameter(paramName, request.getParameter(paramName)); } } else { throw new NotImplementedException("This proxy only supports GET and POST methods."); } // Forward the user's groups along with the request method.addRequestHeader(HttpClientUtil.SHIBBOLETH_GROUPS_HEADER, GroupsThreadStore.getGroupString()); method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername()); // Execute the method client.executeMethod(method); // Set the content type, as it comes from the server Header[] headers = method.getResponseHeaders(); for (Header header : headers) { if ("Content-Type".equalsIgnoreCase(header.getName())) { response.setContentType(header.getValue()); } } try (InputStream responseStream = method.getResponseBodyAsStream()) { int b; while ((b = responseStream.read()) != -1) { response.getOutputStream().write(b); } } response.getOutputStream().flush(); } catch (HttpException e) { writer.write(e.toString()); throw e; } catch (IOException e) { e.printStackTrace(); writer.write(e.toString()); throw e; } finally { if (method != null) method.releaseConnection(); } }
From source file:com.adobe.share.api.ShareAPI.java
/** * Parses the response from the Share service. * * @param method the method//from w w w . j a v a2 s. co m * * @return the jSON object * * @throws HttpException the http exception * @throws IOException Signals that an I/O exception has occurred. * @throws ShareAPIException the share api exception */ protected final JSONObject parseResponse(final HttpMethod method) throws HttpException, IOException, ShareAPIException { JSONObject json = null; String content = null; if (LOGGER.isDebugEnabled()) { LOGGER.debug("URL: " + method.getURI().toString()); LOGGER.debug("Proxy: " + httpClient.getHostConfiguration().getProxyHost()); LOGGER.debug("Proxy Port: " + httpClient.getHostConfiguration().getProxyPort()); } try { int status = httpClient.executeMethod(method); final int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; OutputStream outputStream = new ByteArrayOutputStream(); InputStream inputStream = method.getResponseBodyAsStream(); while (true) { int read = inputStream.read(buffer); if (read == -1) { break; } outputStream.write(buffer, 0, read); } outputStream.close(); inputStream.close(); content = outputStream.toString(); if (method.getResponseHeader("Content-Type") != null) { String contentType = method.getResponseHeader("Content-Type").getValue(); if (method.getStatusCode() == STATUS_OK) { if (contentType.contains("application/xml")) { json = XML.toJSONObject(content); } } } if (status >= STATUS_BAD_REQUEST) { if (json != null) { throw new ShareAPIException(method.getStatusCode(), json.getJSONObject("response").getString("message")); } else { throw new ShareAPIException(method.getStatusCode(), content); } } } catch (JSONException e) { e.printStackTrace(); throw new ShareAPIException(method.getStatusCode(), content); } return json; }
From source file:com.cloud.test.stress.TestClientWithAPI.java
private static int executeCleanup(String server, String developerServer, String username) throws HttpException, IOException { // test steps: // - get user // - delete user // ----------------------------- // GET USER/*from w w w.j a v a2s . co m*/ // ----------------------------- String userId = _userId.get().toString(); String encodedUserId = URLEncoder.encode(userId, "UTF-8"); String url = server + "?command=listUsers&id=" + encodedUserId; s_logger.info("Cleaning up resources for user: " + userId + " with url " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); s_logger.info("get user response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> userInfo = getSingleValueFromXML(is, new String[] { "username", "id", "account" }); if (!username.equals(userInfo.get("username"))) { s_logger.error("get user failed to retrieve requested user, aborting cleanup test" + ". Following URL was sent: " + url); return -1; } } else { s_logger.error("get user failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ----------------------------- // UPDATE USER // ----------------------------- { url = server + "?command=updateUser&id=" + userId + "&firstname=delete&lastname=me"; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("update user response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> success = getSingleValueFromXML(is, new String[] { "success" }); s_logger.info("update user..success? " + success.get("success")); } else { s_logger.error( "update user failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // ----------------------------- // Detach existin dataVolume, create a new volume, attach it to the vm // ----------------------------- { url = server + "?command=listVolumes&virtualMachineId=" + _linuxVmId.get() + "&type=dataDisk"; s_logger.info("Getting dataDisk id of Centos vm"); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("List volumes response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> success = getSingleValueFromXML(is, new String[] { "id" }); s_logger.info("Got dataDiskVolume with id " + success.get("id")); _dataVolume.set(success.get("id")); } else { s_logger.error("List volumes failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // Detach volume { url = server + "?command=detachVolume&id=" + _dataVolume.get(); s_logger.info("Detaching volume with id " + _dataVolume.get()); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Detach data volume response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); s_logger.info("The volume was detached successfully"); } else { s_logger.error("Detach data disk failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // Delete a volume { url = server + "?command=deleteVolume&id=" + _dataVolume.get(); s_logger.info("Deleting volume with id " + _dataVolume.get()); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Delete data volume response code: " + responseCode); if (responseCode == 200) { s_logger.info("The volume was deleted successfully"); } else { s_logger.error("Delete volume failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // Create a new volume { url = server + "?command=createVolume&diskofferingid=" + diskOfferingId + "&zoneid=" + zoneId + "&name=newvolume&account=" + _account.get() + "&domainid=1"; s_logger.info("Creating volume...."); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" }); if (values.get("id") == null) { s_logger.info("create volume response code: 401"); return 401; } else { s_logger.info("create volume response code: " + responseCode); long volumeId = Long.parseLong(values.get("id")); s_logger.info("got volume id: " + volumeId); _newVolume.set(values.get("id")); } } else { s_logger.error("create volume failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // attach a new volume to the vm { url = server + "?command=attachVolume&id=" + _newVolume.get() + "&virtualmachineid=" + _linuxVmId.get(); s_logger.info("Attaching volume with id " + _newVolume.get() + " to the vm " + _linuxVmId.get()); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Attach data volume response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); s_logger.info("The volume was attached successfully"); } else { s_logger.error("Attach volume failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // Create a snapshot // list volumes { url = server + "?command=listVolumes&virtualMachineId=" + _linuxVmId.get() + "&type=root"; s_logger.info("Getting rootDisk id of Centos vm"); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("List volumes response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> success = getSingleValueFromXML(is, new String[] { "id" }); if (success.get("id") == null) { s_logger.error("Unable to get root volume. Followin url was sent: " + url); } s_logger.info("Got rootVolume with id " + success.get("id")); _rootVolume.set(success.get("id")); } else { s_logger.error("List volumes failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // //Create snapshot from root disk volume String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); String requestToSign = "apikey=" + encodedApiKey + "&command=createSnapshot&volumeid=" + _rootVolume.get(); requestToSign = requestToSign.toLowerCase(); String signature = signRequest(requestToSign, _secretKey.get()); String encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=createSnapshot&volumeid=" + _rootVolume.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Create snapshot response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" }); if (values.get("id") == null) { s_logger.info("create snapshot response code: 401"); return 401; } else { s_logger.info("create snapshot response code: " + responseCode + ". Got snapshot with id " + values.get("id")); _snapshot.set(values.get("id")); } } else { s_logger.error( "create snapshot failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // Create volume from the snapshot created on the previous step and attach it to the running vm /* encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); requestToSign = "apikey=" + encodedApiKey + "&command=createVolume&name=" + _account.get() + "&snapshotid=" + _snapshot.get(); requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=createVolume&name=" + _account.get() + "&snapshotid=" + _snapshot.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Create volume from snapshot response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" }); if (values.get("id") == null) { s_logger.info("create volume from snapshot response code: 401"); return 401; } else { s_logger.info("create volume from snapshot response code: " + responseCode + ". Got volume with id " + values.get("id") + ". The command was sent with url " + url); _volumeFromSnapshot.set(values.get("id")); } } else { s_logger.error("create volume from snapshot failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } { url = server + "?command=attachVolume&id=" + _volumeFromSnapshot.get() + "&virtualmachineid=" + _linuxVmId.get(); s_logger.info("Attaching volume with id " + _volumeFromSnapshot.get() + " to the vm " + _linuxVmId.get()); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Attach volume from snapshot to linux vm response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); s_logger.info("The volume created from snapshot was attached successfully to linux vm"); } else { s_logger.error("Attach volume created from snapshot failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } */ // ----------------------------- // Execute reboot/stop/start commands for the VMs before deleting the account - made to exercise xen // ----------------------------- // Reboot windows VM requestToSign = "apikey=" + encodedApiKey + "&command=rebootVirtualMachine&id=" + _windowsVmId.get(); requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=rebootVirtualMachine&id=" + _windowsVmId.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Reboot windows Vm response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> success = getSingleValueFromXML(el, new String[] { "success" }); s_logger.info("Windows VM was rebooted with the status: " + success.get("success")); } else { s_logger.error("Reboot windows VM test failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // Stop centos VM requestToSign = "apikey=" + encodedApiKey + "&command=stopVirtualMachine&id=" + _linuxVmId.get(); requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=stopVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Stop linux Vm response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> success = getSingleValueFromXML(el, new String[] { "success" }); s_logger.info("Linux VM was stopped with the status: " + success.get("success")); } else { s_logger.error("Stop linux VM test failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // Create private template from root disk volume requestToSign = "apikey=" + encodedApiKey + "&command=createTemplate" + "&displaytext=" + _account.get() + "&name=" + _account.get() + "&ostypeid=11" + "&snapshotid=" + _snapshot.get(); requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=createTemplate" + "&displaytext=" + _account.get() + "&name=" + _account.get() + "&ostypeid=11" + "&snapshotid=" + _snapshot.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Create private template response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" }); if (values.get("id") == null) { s_logger.info("create private template response code: 401"); return 401; } else { s_logger.info("create private template response code: " + responseCode); } } else { s_logger.error("create private template failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // Start centos VM requestToSign = "apikey=" + encodedApiKey + "&command=startVirtualMachine&id=" + _windowsVmId.get(); requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=startVirtualMachine&id=" + _windowsVmId.get() + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Start linux Vm response code: " + responseCode); if (responseCode != 200) { s_logger.error("Start linux VM test failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // get domainRouter id { url = server + "?command=listRouters&zoneid=" + zoneId + "&account=" + _account.get() + "&domainid=1"; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("List domain routers response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> success = getSingleValueFromXML(is, new String[] { "id" }); s_logger.info("Got the domR with id " + success.get("id")); _domainRouterId.set(success.get("id")); } else { s_logger.error("List domain routers failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // reboot the domain router { url = server + "?command=rebootRouter&id=" + _domainRouterId.get(); s_logger.info("Rebooting domR with id " + _domainRouterId.get()); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Reboot domain router response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); s_logger.info("Domain router was rebooted successfully"); } else { s_logger.error("Reboot domain routers failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // ----------------------------- // DELETE ACCOUNT // ----------------------------- { url = server + "?command=deleteAccount&id=" + _accountId.get(); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("delete account response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); s_logger.info("Deleted account successfully"); } else { s_logger.error("delete account failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } return responseCode; }
From source file:com.intuit.tank.httpclient3.TankHttpClient3.java
private void sendRequest(BaseRequest request, @Nonnull HttpMethod method, String requestBody) { String uri = null;//from w w w . ja v a 2 s. c o m long waitTime = 0L; try { uri = method.getURI().toString(); logger.debug(request.getLogUtil().getLogMessage( "About to " + method.getName() + " request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); List<String> cookies = new ArrayList<String>(); if (httpclient != null && httpclient.getState() != null && httpclient.getState().getCookies() != null) { for (Cookie cookie : httpclient.getState().getCookies()) { cookies.add("REQUEST COOKIE: " + cookie.toExternalForm() + " (domain=" + cookie.getDomain() + " : path=" + cookie.getPath() + ")"); } } request.logRequest(uri, requestBody, method.getName(), request.getHeaderInformation(), cookies, false); setHeaders(request, method, request.getHeaderInformation()); long startTime = System.currentTimeMillis(); request.setTimestamp(new Date(startTime)); httpclient.executeMethod(method); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (method.getStatusCode() != 203 && method.getStatusCode() != 202 && method.getStatusCode() != 204) { try { InputStream httpInputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int curByte = httpInputStream.read(); while (curByte >= 0) { out.write(curByte); curByte = httpInputStream.read(); } responseBody = out.toByteArray(); } catch (Exception e) { logger.warn("could not get response body: " + e); } } long endTime = System.currentTimeMillis(); processResponse(responseBody, startTime, endTime, request, method.getStatusText(), method.getStatusCode(), method.getResponseHeaders(), httpclient.getState()); waitTime = endTime - startTime; } catch (Exception ex) { logger.error(request.getLogUtil().getLogMessage( "Could not do " + method.getName() + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { try { method.releaseConnection(); } catch (Exception e) { logger.warn("Could not release connection: " + e, e); } if (method.getName().equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) { logger.info(request.getLogUtil() .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code " + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody() + " }", LogEventType.Informational)); } } if (waitTime != 0) { doWaitDueToLongResponse(request, waitTime, uri); } }
From source file:com.cloud.test.stress.TestClientWithAPI.java
private static Integer executeDeployment(String server, String developerServer, String username, String snapshot_test) throws HttpException, IOException { // test steps: // - create user // - deploy Windows VM // - deploy Linux VM // - associate IP address // - create two IP forwarding rules // - create load balancer rule // - list IP forwarding rules // - list load balancer rules // ----------------------------- // CREATE ACCOUNT // ----------------------------- String encodedUsername = URLEncoder.encode(username, "UTF-8"); String encryptedPassword = createMD5Password(username); String encodedPassword = URLEncoder.encode(encryptedPassword, "UTF-8"); String url = server + "?command=createAccount&username=" + encodedUsername + "&account=" + encodedUsername + "&password=" + encodedPassword + "&firstname=Test&lastname=Test&email=test@vmops.com&domainId=1&accounttype=0"; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); long accountId = -1; if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> accountValues = getSingleValueFromXML(is, new String[] { "id", "name" }); String accountIdStr = accountValues.get("id"); s_logger.info("created account " + username + " with id " + accountIdStr); if (accountIdStr != null) { accountId = Long.parseLong(accountIdStr); _accountId.set(accountId);/*from w w w . j av a2 s. com*/ _account.set(accountValues.get("name")); if (accountId == -1) { s_logger.error("create account (" + username + ") failed to retrieve a valid user id, aborting depolyment test"); return -1; } } } else { s_logger.error("create account test failed for account " + username + " with error code :" + responseCode + ", aborting deployment test. The command was sent with url " + url); return -1; } // LIST JUST CREATED USER TO GET THE USER ID url = server + "?command=listUsers&username=" + encodedUsername + "&account=" + encodedUsername + "&domainId=1"; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); long userId = -1; if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> userIdValues = getSingleValueFromXML(is, new String[] { "id" }); String userIdStr = userIdValues.get("id"); s_logger.info("listed user " + username + " with id " + userIdStr); if (userIdStr != null) { userId = Long.parseLong(userIdStr); _userId.set(userId); if (userId == -1) { s_logger.error("list user by username " + username + ") failed to retrieve a valid user id, aborting depolyment test"); return -1; } } } else { s_logger.error("list user test failed for account " + username + " with error code :" + responseCode + ", aborting deployment test. The command was sent with url " + url); return -1; } _secretKey.set(executeRegistration(server, username, username)); if (_secretKey.get() == null) { s_logger.error("FAILED to retrieve secret key during registration, skipping user: " + username); return -1; } else { s_logger.info("got secret key: " + _secretKey.get()); s_logger.info("got api key: " + _apiKey.get()); } // --------------------------------- // CREATE VIRTUAL NETWORK // --------------------------------- url = server + "?command=createNetwork&networkofferingid=" + networkOfferingId + "&account=" + encodedUsername + "&domainId=1" + "&zoneId=" + zoneId + "&name=virtualnetwork-" + encodedUsername + "&displaytext=virtualnetwork-" + encodedUsername; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> networkValues = getSingleValueFromXML(is, new String[] { "id" }); String networkIdStr = networkValues.get("id"); s_logger.info("Created virtual network with name virtualnetwork-" + encodedUsername + " and id " + networkIdStr); if (networkIdStr != null) { _networkId.set(networkIdStr); } } else { s_logger.error("Create virtual network failed for account " + username + " with error code :" + responseCode + ", aborting deployment test. The command was sent with url " + url); return -1; } /* // --------------------------------- // CREATE DIRECT NETWORK // --------------------------------- url = server + "?command=createNetwork&networkofferingid=" + networkOfferingId_dir + "&account=" + encodedUsername + "&domainId=1" + "&zoneId=" + zoneId + "&name=directnetwork-" + encodedUsername + "&displaytext=directnetwork-" + encodedUsername; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> networkValues = getSingleValueFromXML(is, new String[] { "id" }); String networkIdStr = networkValues.get("id"); s_logger.info("Created direct network with name directnetwork-" + encodedUsername + " and id " + networkIdStr); if (networkIdStr != null) { _networkId_dir.set(networkIdStr); } } else { s_logger.error("Create direct network failed for account " + username + " with error code :" + responseCode + ", aborting deployment test. The command was sent with url " + url); return -1; } */ // --------------------------------- // DEPLOY LINUX VM // --------------------------------- String linuxVMPrivateIP = null; { // long templateId = 3; long templateId = 4; String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); String encodedServiceOfferingId = URLEncoder.encode("" + serviceOfferingId, "UTF-8"); String encodedTemplateId = URLEncoder.encode("" + templateId, "UTF-8"); String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); String encodedNetworkIds = URLEncoder.encode(_networkId.get() + ",206", "UTF-8"); String requestToSign = "apikey=" + encodedApiKey + "&command=deployVirtualMachine&diskofferingid=" + diskOfferingId + "&networkids=" + encodedNetworkIds + "&serviceofferingid=" + encodedServiceOfferingId + "&templateid=" + encodedTemplateId + "&zoneid=" + encodedZoneId; requestToSign = requestToSign.toLowerCase(); String signature = signRequest(requestToSign, _secretKey.get()); String encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=deployVirtualMachine" + "&zoneid=" + encodedZoneId + "&serviceofferingid=" + encodedServiceOfferingId + "&diskofferingid=" + diskOfferingId + "&networkids=" + encodedNetworkIds + "&templateid=" + encodedTemplateId + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature; method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> values = getSingleValueFromXML(el, new String[] { "id", "ipaddress" }); if ((values.get("ipaddress") == null) || (values.get("id") == null)) { s_logger.info("deploy linux vm response code: 401, the command was sent with url " + url); return 401; } else { s_logger.info("deploy linux vm response code: " + responseCode); long linuxVMId = Long.parseLong(values.get("id")); s_logger.info("got linux virtual machine id: " + linuxVMId); _linuxVmId.set(values.get("id")); linuxVMPrivateIP = values.get("ipaddress"); // _linuxPassword.set(values.get("password")); _linuxPassword.set(vmPassword); s_logger.info("got linux virtual machine password: " + _linuxPassword.get()); } } else { s_logger.error("deploy linux vm failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } { // --------------------------------- // ASSOCIATE IP for windows // --------------------------------- String ipAddr = null; String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); String requestToSign = "apikey=" + encodedApiKey + "&command=associateIpAddress" + "&zoneid=" + zoneId; requestToSign = requestToSign.toLowerCase(); String signature = signRequest(requestToSign, _secretKey.get()); String encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=associateIpAddress" + "&apikey=" + encodedApiKey + "&zoneid=" + zoneId + "&signature=" + encodedSignature; method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); /*Asynchronous Job - Corresponding Changes Made*/ Element associpel = queryAsyncJobResult(server, is); Map<String, String> values = getSingleValueFromXML(associpel, new String[] { "id", "ipaddress" }); if ((values.get("ipaddress") == null) || (values.get("id") == null)) { s_logger.info( "associate ip for Windows response code: 401, the command was sent with url " + url); return 401; } else { s_logger.info("Associate IP Address response code: " + responseCode); long publicIpId = Long.parseLong(values.get("id")); s_logger.info("Associate IP's Id: " + publicIpId); _publicIpId.set(values.get("id")); } } else { s_logger.error("associate ip address for windows vm failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } String encodedPublicIpId = URLEncoder.encode(_publicIpId.get(), "UTF-8"); requestToSign = "apikey=" + encodedApiKey + "&command=listPublicIpAddresses" + "&id=" + encodedPublicIpId; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=listPublicIpAddresses&apikey=" + encodedApiKey + "&id=" + encodedPublicIpId + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("url is " + url); s_logger.info("list ip addresses for user " + userId + " response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); // InputStream ips = method.getResponseBodyAsStream(); List<String> ipAddressValues = getIPs(is, false); // List<String> ipAddressVals = getIPs(is, false, true); if ((ipAddressValues != null) && !ipAddressValues.isEmpty()) { _windowsIpId.set(ipAddressValues.get(0)); _windowsIP.set(ipAddressValues.get(1)); s_logger.info("For Windows, using non-sourceNat IP address ID: " + ipAddressValues.get(0)); s_logger.info("For Windows, using non-sourceNat IP address: " + ipAddressValues.get(1)); } } else { s_logger.error("list ip addresses failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // --------------------------------- // Use the SourceNat IP for linux // --------------------------------- { requestToSign = "apikey=" + encodedApiKey + "&command=listPublicIpAddresses"; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=listPublicIpAddresses&apikey=" + encodedApiKey + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("url is " + url); s_logger.info("list ip addresses for user " + userId + " response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); // InputStream ips = method.getResponseBodyAsStream(); List<String> ipAddressValues = getIPs(is, true); // is = method.getResponseBodyAsStream(); // List<String> ipAddressVals = getIPs(is, true, true); if ((ipAddressValues != null) && !ipAddressValues.isEmpty()) { _linuxIpId.set(ipAddressValues.get(0)); _linuxIP.set(ipAddressValues.get(1)); s_logger.info("For linux, using sourceNat IP address ID: " + ipAddressValues.get(0)); s_logger.info("For linux, using sourceNat IP address: " + ipAddressValues.get(1)); } } else { s_logger.error("list ip addresses failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } //-------------------------------------------- // Enable Static NAT for the Source NAT Ip //-------------------------------------------- String encodedSourceNatPublicIpId = URLEncoder.encode(_linuxIpId.get(), "UTF-8"); /* requestToSign = "apikey=" + encodedApiKey + "&command=enableStaticNat"+"&id=" + encodedSourceNatPublicIpId + "&virtualMachineId=" + encodedVmId;; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=enableStaticNat&apikey=" + encodedApiKey + "&signature=" + encodedSignature + "&id=" + encodedSourceNatPublicIpId + "&virtualMachineId=" + encodedVmId; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("url is " + url); s_logger.info("list ip addresses for user " + userId + " response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> success = getSingleValueFromXML(is, new String[] { "success" }); s_logger.info("Enable Static NAT..success? " + success.get("success")); } else { s_logger.error("Enable Static NAT failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } */ // ------------------------------------------------------------- // CREATE IP FORWARDING RULE -- Linux VM // ------------------------------------------------------------- String encodedVmId = URLEncoder.encode(_linuxVmId.get(), "UTF-8"); String encodedIpAddress = URLEncoder.encode(_linuxIpId.get(), "UTF-8"); requestToSign = "apikey=" + encodedApiKey + "&command=createPortForwardingRule&ipaddressid=" + encodedIpAddress + "&privateport=22&protocol=TCP&publicport=22" + "&virtualmachineid=" + encodedVmId; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=createPortForwardingRule&apikey=" + encodedApiKey + "&ipaddressid=" + encodedIpAddress + "&privateport=22&protocol=TCP&publicport=22&virtualmachineid=" + encodedVmId + "&signature=" + encodedSignature; s_logger.info("Created port forwarding rule with " + url); method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" }); s_logger.info("Port forwarding rule was assigned successfully to Linux VM"); long ipfwdid = Long.parseLong(values.get("id")); s_logger.info("got Port Forwarding Rule's Id:" + ipfwdid); _linipfwdid.set(values.get("id")); } else { s_logger.error("Port forwarding rule creation failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // Create snapshot recurring policy if needed; otherwise create windows vm if (snapshot_test.equals("yes")) { // list volumes for linux vm { url = server + "?command=listVolumes&virtualMachineId=" + _linuxVmId.get() + "&type=root"; s_logger.info("Getting rootDisk id of Centos vm"); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("List volumes response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> success = getSingleValueFromXML(is, new String[] { "id" }); if (success.get("id") == null) { s_logger.error("Unable to get root volume for linux vm. Followin url was sent: " + url); } s_logger.info("Got rootVolume for linux vm with id " + success.get("id")); _rootVolume.set(success.get("id")); } else { s_logger.error("List volumes for linux vm failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } // Create recurring snapshot policy for linux vm { String encodedTimeZone = URLEncoder.encode("America/Los Angeles", "UTF-8"); url = server + "?command=createSnapshotPolicy&intervaltype=hourly&schedule=10&maxsnaps=4&volumeid=" + _rootVolume.get() + "&timezone=" + encodedTimeZone; s_logger.info("Creating recurring snapshot policy for linux vm ROOT disk"); client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("Create recurring snapshot policy for linux vm ROOT disk: " + responseCode); if (responseCode != 200) { s_logger.error( "Create recurring snapshot policy for linux vm ROOT disk failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } } else { // --------------------------------- // DEPLOY WINDOWS VM // --------------------------------- String windowsVMPrivateIP = null; { // long templateId = 6; long templateId = 4; String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); String encodedServiceOfferingId = URLEncoder.encode("" + serviceOfferingId, "UTF-8"); String encodedTemplateId = URLEncoder.encode("" + templateId, "UTF-8"); encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); String encodedNetworkIds = URLEncoder.encode(_networkId.get() + ",206", "UTF-8"); requestToSign = "apikey=" + encodedApiKey + "&command=deployVirtualMachine&diskofferingid=" + diskOfferingId + "&networkids=" + encodedNetworkIds + "&serviceofferingid=" + encodedServiceOfferingId + "&templateid=" + encodedTemplateId + "&zoneid=" + encodedZoneId; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=deployVirtualMachine" + "&zoneid=" + encodedZoneId + "&serviceofferingid=" + encodedServiceOfferingId + "&diskofferingid=" + diskOfferingId + "&networkids=" + encodedNetworkIds + "&templateid=" + encodedTemplateId + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature; method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> values = getSingleValueFromXML(el, new String[] { "id", "ipaddress" }); if ((values.get("ipaddress") == null) || (values.get("id") == null)) { s_logger.info( "deploy windows vm response code: 401, the command was sent with url " + url); return 401; } else { s_logger.info("deploy windows vm response code: " + responseCode); windowsVMPrivateIP = values.get("ipaddress"); long windowsVMId = Long.parseLong(values.get("id")); s_logger.info("got windows virtual machine id: " + windowsVMId); _windowsVmId.set(values.get("id")); } } else { s_logger.error("deploy windows vm failes with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } //-------------------------------------------- // Enable Static NAT for the Non Source NAT Ip //-------------------------------------------- encodedVmId = URLEncoder.encode(_windowsVmId.get(), "UTF-8"); encodedPublicIpId = URLEncoder.encode(_publicIpId.get(), "UTF-8"); requestToSign = "apikey=" + encodedApiKey + "&command=enableStaticNat" + "&ipaddressid=" + encodedPublicIpId + "&virtualMachineId=" + encodedVmId; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=enableStaticNat&apikey=" + encodedApiKey + "&ipaddressid=" + encodedPublicIpId + "&signature=" + encodedSignature + "&virtualMachineId=" + encodedVmId; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("url is " + url); s_logger.info("list ip addresses for user " + userId + " response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> success = getSingleValueFromXML(is, new String[] { "success" }); s_logger.info("Enable Static NAT..success? " + success.get("success")); } else { s_logger.error("Enable Static NAT failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ------------------------------------------------------------- // CREATE IP FORWARDING RULE -- Windows VM // ------------------------------------------------------------- // create port forwarding rule for window vm encodedIpAddress = URLEncoder.encode(_windowsIpId.get(), "UTF-8"); //encodedVmId = URLEncoder.encode(_windowsVmId.get(), "UTF-8"); requestToSign = "apikey=" + encodedApiKey + "&command=createIpForwardingRule&endPort=22&ipaddressid=" + encodedIpAddress + "&protocol=TCP&startPort=22"; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=createIpForwardingRule&apikey=" + encodedApiKey + "&endPort=22&ipaddressid=" + encodedIpAddress + "&protocol=TCP&signature=" + encodedSignature + "&startPort=22"; s_logger.info("Created Ip forwarding rule with " + url); method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> values = getSingleValueFromXML(el, new String[] { "id" }); s_logger.info("Port forwarding rule was assigned successfully to Windows VM"); long ipfwdid = Long.parseLong(values.get("id")); s_logger.info("got Ip Forwarding Rule's Id:" + ipfwdid); _winipfwdid.set(values.get("id")); } else { s_logger.error("Port forwarding rule creation failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } } return responseCode; }
From source file:com.cloud.test.stress.TestClientWithAPI.java
private static int executeStop(String server, String developerServer, String username, boolean destroy) throws HttpException, IOException { // test steps: // - get userId for the given username // - list virtual machines for the user // - stop all virtual machines // - get ip addresses for the user // - release ip addresses // ----------------------------- // GET USER/*from w ww. j av a2s .com*/ // ----------------------------- String userId = _userId.get().toString(); String encodedUserId = URLEncoder.encode(userId, "UTF-8"); String url = server + "?command=listUsers&id=" + encodedUserId; s_logger.info("Stopping resources for user: " + username); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); s_logger.info("get user response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> userIdValues = getSingleValueFromXML(is, new String[] { "id" }); String userIdStr = userIdValues.get("id"); if (userIdStr != null) { userId = userIdStr; } else { s_logger.error("get user failed to retrieve a valid user id, aborting depolyment test" + ". Following URL was sent: " + url); return -1; } } else { s_logger.error("get user failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } { // ---------------------------------- // LIST VIRTUAL MACHINES // ---------------------------------- String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); String requestToSign = "apikey=" + encodedApiKey + "&command=listVirtualMachines"; requestToSign = requestToSign.toLowerCase(); String signature = signRequest(requestToSign, _secretKey.get()); String encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=listVirtualMachines&apikey=" + encodedApiKey + "&signature=" + encodedSignature; s_logger.info("Listing all virtual machines for the user with url " + url); String[] vmIds = null; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("list virtual machines response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, List<String>> vmIdValues = getMultipleValuesFromXML(is, new String[] { "id" }); if (vmIdValues.containsKey("id")) { List<String> vmIdList = vmIdValues.get("id"); if (vmIdList != null) { vmIds = new String[vmIdList.size()]; vmIdList.toArray(vmIds); String vmIdLogStr = ""; if ((vmIds != null) && (vmIds.length > 0)) { vmIdLogStr = vmIds[0]; for (int i = 1; i < vmIds.length; i++) { vmIdLogStr = vmIdLogStr + "," + vmIds[i]; } } s_logger.info("got virtual machine ids: " + vmIdLogStr); } } } else { s_logger.error("list virtual machines test failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ---------------------------------- // LIST USER IP ADDRESSES // ---------------------------------- requestToSign = "apikey=" + encodedApiKey + "&command=listPublicIpAddresses"; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=listPublicIpAddresses&apikey=" + encodedApiKey + "&signature=" + encodedSignature; String[] ipAddresses = null; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("list ip addresses for user " + userId + " response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, List<String>> ipAddressValues = getMultipleValuesFromXML(is, new String[] { "ipaddress" }); if (ipAddressValues.containsKey("ipaddress")) { List<String> ipAddressList = ipAddressValues.get("ipaddress"); if (ipAddressList != null) { ipAddresses = new String[ipAddressList.size()]; ipAddressList.toArray(ipAddresses); String ipAddressLogStr = ""; if ((ipAddresses != null) && (ipAddresses.length > 0)) { ipAddressLogStr = ipAddresses[0]; for (int i = 1; i < ipAddresses.length; i++) { ipAddressLogStr = ipAddressLogStr + "," + ipAddresses[i]; } } s_logger.info("got IP addresses: " + ipAddressLogStr); } } } else { s_logger.error("list user ip addresses failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ---------------------------------- // LIST ZONES // ---------------------------------- requestToSign = "apikey=" + encodedApiKey + "&command=listZones"; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=listZones&apikey=" + encodedApiKey + "&signature=" + encodedSignature; String[] zoneNames = null; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("list zones response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, List<String>> zoneNameValues = getMultipleValuesFromXML(is, new String[] { "name" }); if (zoneNameValues.containsKey("name")) { List<String> zoneNameList = zoneNameValues.get("name"); if (zoneNameList != null) { zoneNames = new String[zoneNameList.size()]; zoneNameList.toArray(zoneNames); String zoneNameLogStr = "\n\n"; if ((zoneNames != null) && (zoneNames.length > 0)) { zoneNameLogStr += zoneNames[0]; for (int i = 1; i < zoneNames.length; i++) { zoneNameLogStr = zoneNameLogStr + "\n" + zoneNames[i]; } } zoneNameLogStr += "\n\n"; s_logger.info("got zones names: " + zoneNameLogStr); } } } else { s_logger.error( "list zones failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ---------------------------------- // LIST ACCOUNT STATISTICS // ---------------------------------- requestToSign = "apikey=" + encodedApiKey + "&command=listAccounts"; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=listAccounts&apikey=" + encodedApiKey + "&signature=" + encodedSignature; String[] statNames = null; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("listAccountStatistics response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, List<String>> statValues = getMultipleValuesFromXML(is, new String[] { "receivedbytes" }); if (statValues.containsKey("receivedbytes")) { List<String> statList = statValues.get("receivedbytes"); if (statList != null) { statNames = new String[statList.size()]; statList.toArray(statNames); String statLogStr = "\n\n"; if ((statNames != null) && (zoneNames.length > 0)) { statLogStr += statNames[0]; for (int i = 1; i < statNames.length; i++) { statLogStr = statLogStr + "\n" + zoneNames[i]; } } statLogStr += "\n\n"; s_logger.info("got accountstatistics: " + statLogStr); } } } else { s_logger.error("listAccountStatistics failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ---------------------------------- // LIST TEMPLATES // ---------------------------------- requestToSign = "apikey=" + encodedApiKey + "&command=listTemplates@templatefilter=self"; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=listTemplates&apikey=" + encodedApiKey + "&templatefilter=self&signature=" + encodedSignature; String[] templateNames = null; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("list templates response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, List<String>> templateNameValues = getMultipleValuesFromXML(is, new String[] { "name" }); if (templateNameValues.containsKey("name")) { List<String> templateNameList = templateNameValues.get("name"); if (templateNameList != null) { templateNames = new String[templateNameList.size()]; templateNameList.toArray(templateNames); String templateNameLogStr = "\n\n"; if ((templateNames != null) && (templateNames.length > 0)) { templateNameLogStr += templateNames[0]; for (int i = 1; i < templateNames.length; i++) { templateNameLogStr = templateNameLogStr + "\n" + templateNames[i]; } } templateNameLogStr += "\n\n"; s_logger.info("got template names: " + templateNameLogStr); } } } else { s_logger.error("list templates failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ---------------------------------- // LIST SERVICE OFFERINGS // ---------------------------------- requestToSign = "apikey=" + encodedApiKey + "&command=listServiceOfferings"; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=listServiceOfferings&apikey=" + encodedApiKey + "&signature=" + encodedSignature; String[] serviceOfferingNames = null; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("list service offerings response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, List<String>> serviceOfferingNameValues = getMultipleValuesFromXML(is, new String[] { "name" }); if (serviceOfferingNameValues.containsKey("name")) { List<String> serviceOfferingNameList = serviceOfferingNameValues.get("name"); if (serviceOfferingNameList != null) { serviceOfferingNames = new String[serviceOfferingNameList.size()]; serviceOfferingNameList.toArray(serviceOfferingNames); String serviceOfferingNameLogStr = ""; if ((serviceOfferingNames != null) && (serviceOfferingNames.length > 0)) { serviceOfferingNameLogStr = serviceOfferingNames[0]; for (int i = 1; i < serviceOfferingNames.length; i++) { serviceOfferingNameLogStr = serviceOfferingNameLogStr + ", " + serviceOfferingNames[i]; } } s_logger.info("got service offering names: " + serviceOfferingNameLogStr); } } } else { s_logger.error("list service offerings failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ---------------------------------- // LIST EVENTS // --------------------------------- url = server + "?command=listEvents&page=1&pagesize=100&&account=" + _account.get(); String[] eventDescriptions = null; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("list events response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, List<String>> eventNameValues = getMultipleValuesFromXML(is, new String[] { "description" }); if (eventNameValues.containsKey("description")) { List<String> eventNameList = eventNameValues.get("description"); if (eventNameList != null) { eventDescriptions = new String[eventNameList.size()]; eventNameList.toArray(eventDescriptions); String eventNameLogStr = "\n\n"; if ((eventDescriptions != null) && (eventDescriptions.length > 0)) { eventNameLogStr += eventDescriptions[0]; for (int i = 1; i < eventDescriptions.length; i++) { eventNameLogStr = eventNameLogStr + "\n" + eventDescriptions[i]; } } eventNameLogStr += "\n\n"; s_logger.info("got event descriptions: " + eventNameLogStr); } } } else { s_logger.error( "list events failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ---------------------------------- // STOP/DESTROY VIRTUAL MACHINES // ---------------------------------- if (vmIds != null) { String cmdName = (destroy ? "destroyVirtualMachine" : "stopVirtualMachine"); for (String vmId : vmIds) { requestToSign = "apikey=" + encodedApiKey + "&command=" + cmdName + "&id=" + vmId; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=" + cmdName + "&id=" + vmId + "&apikey=" + encodedApiKey + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info(cmdName + " [" + vmId + "] response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); Map<String, String> success = getSingleValueFromXML(el, new String[] { "success" }); s_logger.info(cmdName + "..success? " + success.get("success")); } else { s_logger.error(cmdName + "test failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } } } { String[] ipAddresses = null; // ----------------------------------------- // LIST NAT IP ADDRESSES // ----------------------------------------- String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); String requestToSign = "apikey=" + encodedApiKey + "&command=listPublicIpAddresses"; requestToSign = requestToSign.toLowerCase(); String signature = signRequest(requestToSign, _secretKey.get()); String encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=listPublicIpAddresses&apikey=" + encodedApiKey + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("list ip addresses for user " + userId + " response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); List<String> ipAddressList = getNonSourceNatIPs(is); ipAddresses = new String[ipAddressList.size()]; ipAddressList.toArray(ipAddresses); String ipAddrLogStr = ""; if ((ipAddresses != null) && (ipAddresses.length > 0)) { ipAddrLogStr = ipAddresses[0]; for (int i = 1; i < ipAddresses.length; i++) { ipAddrLogStr = ipAddrLogStr + "," + ipAddresses[i]; } } s_logger.info("got ip addresses: " + ipAddrLogStr); } else { s_logger.error("list nat ip addresses failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ------------------------------------------------------------- // Delete IP FORWARDING RULE -- Windows VM // ------------------------------------------------------------- String encodedIpFwdId = URLEncoder.encode(_winipfwdid.get(), "UTF-8"); requestToSign = "apikey=" + encodedApiKey + "&command=deleteIpForwardingRule&id=" + encodedIpFwdId; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=deleteIpForwardingRule&apikey=" + encodedApiKey + "&id=" + encodedIpFwdId + "&signature=" + encodedSignature; s_logger.info("Delete Ip forwarding rule with " + url); method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element el = queryAsyncJobResult(server, input); s_logger.info("IP forwarding rule was successfully deleted"); } else { s_logger.error("IP forwarding rule creation failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } //-------------------------------------------- // Disable Static NAT for the Source NAT Ip //-------------------------------------------- encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); String encodedPublicIpId = URLEncoder.encode(_publicIpId.get(), "UTF-8"); requestToSign = "apikey=" + encodedApiKey + "&command=disableStaticNat" + "&id=" + encodedPublicIpId; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=disableStaticNat&apikey=" + encodedApiKey + "&id=" + encodedPublicIpId + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("url is " + url); s_logger.info("list ip addresses for user " + userId + " response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> success = getSingleValueFromXML(is, new String[] { "success" }); s_logger.info("Disable Static NAT..success? " + success.get("success")); } else { s_logger.error("Disable Static NAT failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } // ----------------------------------------- // DISASSOCIATE IP ADDRESSES // ----------------------------------------- if (ipAddresses != null) { for (String ipAddress : ipAddresses) { requestToSign = "apikey=" + encodedApiKey + "&command=disassociateIpAddress&id=" + ipAddress; requestToSign = requestToSign.toLowerCase(); signature = signRequest(requestToSign, _secretKey.get()); encodedSignature = URLEncoder.encode(signature, "UTF-8"); url = developerServer + "?command=disassociateIpAddress&apikey=" + encodedApiKey + "&id=" + ipAddress + "&signature=" + encodedSignature; client = new HttpClient(); method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("disassociate ip address [" + userId + "/" + ipAddress + "] response code: " + responseCode); if (responseCode == 200) { InputStream input = method.getResponseBodyAsStream(); Element disassocipel = queryAsyncJobResult(server, input); Map<String, String> success = getSingleValueFromXML(disassocipel, new String[] { "success" }); // Map<String, String> success = getSingleValueFromXML(input, new String[] { "success" }); s_logger.info("disassociate ip address..success? " + success.get("success")); } else { s_logger.error("disassociate ip address failed with error code: " + responseCode + ". Following URL was sent: " + url); return responseCode; } } } } _linuxIP.set(""); _linuxIpId.set(""); _linuxVmId.set(""); _linuxPassword.set(""); _windowsIP.set(""); _windowsIpId.set(""); _windowsVmId.set(""); _secretKey.set(""); _apiKey.set(""); _userId.set(Long.parseLong("0")); _account.set(""); _domainRouterId.set(""); return responseCode; }
From source file:com.zimbra.cs.fb.RemoteFreeBusyProvider.java
@Override public List<FreeBusy> getResults() { ArrayList<FreeBusy> fbList = new ArrayList<FreeBusy>(); for (Request req : mRequestList) { HttpMethod method = null; Account acct = (Account) req.data; try {//from ww w . j a va 2 s.c o m StringBuilder targetUrl = new StringBuilder(); targetUrl.append(UserServlet.getRestUrl(acct)); targetUrl.append("/Calendar?fmt=ifb"); targetUrl.append("&start=").append(mStart); targetUrl.append("&end=").append(mEnd); if (req.folder != FreeBusyQuery.CALENDAR_FOLDER_ALL) targetUrl.append("&").append(UserServlet.QP_FREEBUSY_CALENDAR).append("=").append(req.folder); try { if (mExApptUid != null) targetUrl.append("&").append(UserServlet.QP_EXUID).append("=") .append(URLEncoder.encode(mExApptUid, "UTF-8")); } catch (UnsupportedEncodingException e) { } String authToken = null; try { if (mSoapCtxt != null) authToken = mSoapCtxt.getAuthToken().getEncoded(); } catch (AuthTokenException e) { } if (authToken != null) { targetUrl.append("&").append(ZimbraServlet.QP_ZAUTHTOKEN).append("="); try { targetUrl.append(URLEncoder.encode(authToken, "UTF-8")); } catch (UnsupportedEncodingException e) { } } HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); HttpProxyUtil.configureProxy(client); method = new GetMethod(targetUrl.toString()); String fbMsg; try { HttpClientUtil.executeMethod(client, method); byte[] buf = ByteUtil.getContent(method.getResponseBodyAsStream(), 0); fbMsg = new String(buf, "UTF-8"); } catch (IOException ex) { // ignore this recipient and go on fbMsg = null; } if (fbMsg != null) { ZVCalendar cal = ZCalendarBuilder.build(fbMsg); for (Iterator<ZComponent> compIter = cal.getComponentIterator(); compIter.hasNext();) { ZComponent comp = compIter.next(); if (ICalTok.VFREEBUSY.equals(comp.getTok())) { FreeBusy fb = FreeBusy.parse(comp); fbList.add(fb); } } } } catch (ServiceException e) { ZimbraLog.fb.warn("can't get free/busy information for " + req.email, e); } finally { if (method != null) method.releaseConnection(); } } return fbList; }