List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java
/** * //w w w . j a v a 2s.c o m * @param dataId * @param group * @param timeout * @param skipContentCache * ?cachegetcheck?get?cache * @return */ String getConfigureInfomation(String dataId, String group, long timeout, boolean skipContentCache) { start(); if (!isRun) { throw new RuntimeException("DiamondSubscriber????ConfigureInfomation"); } if (null == group) { group = Constants.DEFAULT_GROUP; } // =======================?======================= if (MockServer.isTestMode()) { return MockServer.getConfigInfo(dataId, group); } // ========================================================== /** * TTLcache */ if (!skipContentCache) { String key = makeCacheKey(dataId, group); String content = contentCache.get(key); if (content != null) { return content; } } long waitTime = 0; String uri = getUriString(dataId, group); if (log.isInfoEnabled()) { log.info(uri); } CacheData cacheData = getCacheData(dataId, group); // ? int retryTimes = this.getDiamondConfigure().getRetrieveDataRetryTimes(); log.info("????" + retryTimes); // ?? int tryCount = 0; while (0 == timeout || timeout > waitTime) { // ?1 tryCount++; if (tryCount > retryTimes + 1) { log.warn("??"); break; } log.info("???" + tryCount + "?, waitTime:" + waitTime); // long onceTimeOut = getOnceTimeOut(waitTime, timeout); waitTime += onceTimeOut; HttpMethod httpMethod = new GetMethod(uri); configureHttpMethod(skipContentCache, cacheData, onceTimeOut, httpMethod); try { int httpStatus = httpClient.executeMethod(httpMethod); switch (httpStatus) { case SC_OK: { String result = getSuccess(dataId, group, cacheData, httpMethod); return result; } case SC_NOT_MODIFIED: { String result = getNotModified(dataId, cacheData, httpMethod); return result; } case SC_NOT_FOUND: { log.warn("DataID:" + dataId + "??"); cacheData.setMd5(Constants.NULL); this.snapshotConfigInfoProcessor.removeSnapshot(dataId, group); return null; } case SC_SERVICE_UNAVAILABLE: { rotateToNextDomain(); } break; default: { log.warn("HTTP State: " + httpStatus + ":" + httpClient.getState()); rotateToNextDomain(); } } } catch (HttpException e) { log.error("???Http", e); rotateToNextDomain(); } catch (IOException e) { log.error("???IO", e); rotateToNextDomain(); } catch (Exception e) { log.error("", e); rotateToNextDomain(); } finally { httpMethod.releaseConnection(); } } throw new RuntimeException("?ConfigureInfomation, DataID" + dataId + ", Group" + group + "," + timeout); }
From source file:com.mengka.diamond.client.impl.DefaultDiamondSubscriber.java
/** * /*from ww w. j a v a2 s . c o m*/ * @param dataId * @param group * @param timeout * @param skipContentCache * ?cachegetcheck?get?cache * @return */ String getConfigureInfomation(String dataId, String group, long timeout, boolean skipContentCache) { start(); if (!isRun) { throw new RuntimeException("DiamondSubscriber????ConfigureInfomation"); } if (null == group) { group = Constants.DEFAULT_GROUP; } // =======================?======================= if (MockServer.isTestMode()) { return MockServer.getConfigInfo(dataId, group); } // ========================================================== /** * TTLcache */ if (!skipContentCache) { String key = makeCacheKey(dataId, group); String content = contentCache.get(key); if (content != null) { return content; } } long waitTime = 0; String uri = getUriString(dataId, group); if (log.isInfoEnabled()) { log.info(diamondConfigure.currentDiamondServerIp(this.domainNamePos.get()) + uri); } CacheData cacheData = getCacheData(dataId, group); // ? int retryTimes = this.getDiamondConfigure().getRetrieveDataRetryTimes(); log.info("????" + retryTimes); // ?? int tryCount = 0; while (0 == timeout || timeout > waitTime) { // ?1 tryCount++; if (tryCount > retryTimes + 1) { log.warn("??"); break; } log.info("???" + tryCount + "?, waitTime:" + waitTime); // long onceTimeOut = getOnceTimeOut(waitTime, timeout); waitTime += onceTimeOut; HttpMethod httpMethod = new GetMethod(uri); configureHttpMethod(skipContentCache, cacheData, onceTimeOut, httpMethod); try { int httpStatus = httpClient.executeMethod(httpMethod); switch (httpStatus) { case SC_OK: { String result = getSuccess(dataId, group, cacheData, httpMethod); return result; } case SC_NOT_MODIFIED: { String result = getNotModified(dataId, cacheData, httpMethod); return result; } case SC_NOT_FOUND: { log.warn("DataID:" + dataId + "??"); cacheData.setMd5(Constants.NULL); this.snapshotConfigInfoProcessor.removeSnapshot(dataId, group); return null; } case SC_SERVICE_UNAVAILABLE: { rotateToNextDomain(); } break; default: { log.warn("HTTP State: " + httpStatus + ":" + httpClient.getState()); rotateToNextDomain(); } } } catch (HttpException e) { log.error("???Http", e); rotateToNextDomain(); } catch (IOException e) { log.error("???IO", e); rotateToNextDomain(); } catch (Exception e) { log.error("", e); rotateToNextDomain(); } finally { httpMethod.releaseConnection(); } } throw new RuntimeException("?ConfigureInfomation, DataID" + dataId + ", Group" + group + "," + timeout); }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public LearningObjectInstance getLearningObjectInstance(int instanceId, int learningObjectId) throws Exception { String uri = String.format(_baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s", learningObjectId, instanceId); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); LearningObjectInstance loi = null;/*from w w w. ja v a2s . c o m*/ try { int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { loi = deserializeXMLToLearningObjectInstance(method.getResponseBodyAsStream()); } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return loi; }
From source file:com.cloud.test.regression.ApiCommand.java
public void sendCommand(HttpClient client, Connection conn) { if (TestCaseEngine._printUrl == true) { s_logger.info("url is " + this.command); }/* w w w. j a v a 2 s.com*/ if (this.getCommandType() == CommandType.SCRIPT) { try { s_logger.info("Executing command " + this.command); Runtime rtime = Runtime.getRuntime(); Process child = rtime.exec(this.command); Thread.sleep(10000); int retCode = child.waitFor(); if (retCode != 0) { this.responseCode = retCode; } else { this.responseCode = 200; } } catch (Exception ex) { s_logger.error("Unable to execute a command " + this.command, ex); } } else if (this.getCommandType() == CommandType.MYSQL) { try { Statement stmt = conn.createStatement(); this.result = stmt.executeQuery(this.command); this.responseCode = 200; } catch (Exception ex) { this.responseCode = 400; s_logger.error("Unable to execute mysql query " + this.command, ex); } } else { HttpMethod method = new GetMethod(this.command); try { this.responseCode = client.executeMethod(method); if (this.responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); doc.getDocumentElement().normalize(); if (!(this.isAsync)) { this.responseBody = doc.getDocumentElement(); } else { // get async job result Element jobTag = (Element) doc.getDocumentElement().getElementsByTagName("jobid").item(0); String jobId = jobTag.getTextContent(); Element responseBodyAsyncEl = queryAsyncJobResult(jobId); if (responseBodyAsyncEl == null) { s_logger.error("Can't get a async result"); } else { this.responseBody = responseBodyAsyncEl; // get status of the job Element jobStatusTag = (Element) responseBodyAsyncEl.getElementsByTagName("jobstatus") .item(0); String jobStatus = jobStatusTag.getTextContent(); if (!jobStatus.equals("1")) { // Need to modify with different error codes for jobAsync // results // set fake response code by now this.responseCode = 400; } } } } if (TestCaseEngine._printUrl == true) { s_logger.info("Response code is " + this.responseCode); } } catch (Exception ex) { s_logger.error("Command " + command + " failed with exception " + ex.getMessage()); } finally { method.releaseConnection(); } } }
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 . j av a 2 s. c om 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:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public List<Assessment> getPossibleAssessments(int instanceId, int learningObjectId) throws Exception { String uri = String.format( _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/PossibleAssessments", learningObjectId, instanceId); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); List<Assessment> assessments = new ArrayList<Assessment>(); try {//from w w w . ja v a2s. co m int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { assessments = deserializeXMLToListOfAssessments(method.getResponseBodyAsStream()); } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return assessments; }
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 {/* w w w. j a v a 2s .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; }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public List<AssessmentItem> getAssessmentItems(int instanceId, int learningObjectId) throws Exception { String uri = String.format( _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/AssessmentItems", learningObjectId, instanceId); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); List<AssessmentItem> assessmentItems = new ArrayList<AssessmentItem>(); try {/*from www.jav a2 s .co m*/ int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { assessmentItems = deserializeXMLToListOfAssessmentItems(method.getResponseBodyAsStream()); } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return assessmentItems; }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public List<LearningObjectInstanceUser> getLearningObjectInstanceUsers(int instanceId, int learningObjectId, int[] userIds, boolean includeTeachers, int pageIndex, int pageSize, LearningObjectInstanceUser.OrderBy orderBy, OrderDirection orderDirection) throws Exception { String uri = String.format(_baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Users", learningObjectId, instanceId); uri = appendLearningObjectInstanceUsersExtraParameters(uri, userIds, includeTeachers); uri = AppendPagingParams(uri, pageIndex, pageSize, orderBy, orderDirection); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); List<LearningObjectInstanceUser> users = new ArrayList<LearningObjectInstanceUser>(); try {//from ww w .j a va2 s . c om int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { users = deserializeXMLToListOfLearningObjectInstanceUser(method.getResponseBodyAsStream()); } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return users; }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public List<AppLicense> getAppLicensesForCurrentUser() throws Exception { List<AppLicense> appLicenses = new ArrayList<AppLicense>(); String uri = String.format(_baseUri + "/LearningObjectService.svc/AppLicensesForCurrentUser"); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); try {/*ww w . j av a 2 s .c o m*/ int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) { appLicenses = deserializeXMLToAppLicenses(method.getResponseBodyAsStream()); } } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return appLicenses; }