List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK
int SC_OK
To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.
Click Source Link
From source file:com.mdt.rtm.Invoker.java
public Element invoke(Param... params) throws ServiceException { Element result;//from www . ja v a2 s . com long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation; if (timeSinceLastInvocation < INVOCATION_INTERVAL) { // In order not to invoke the RTM service too often try { Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation); } catch (InterruptedException e) { throw new ServiceInternalException( "Unexpected interruption while attempting to pause for some time before invoking the RTM service back", e); } } log.debug("Invoker running at " + new Date()); HttpClient client = new HttpClient(); if (proxyHostName != null) { // Sets an HTTP proxy and the credentials for authentication client.getHostConfiguration().setProxy(proxyHostName, proxyPortNumber); if (proxyLogin != null) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyLogin, proxyPassword)); } } GetMethod method = new GetMethod(serviceBaseUrl + REST_SERVICE_URL_POSTFIX); method.setRequestHeader(HttpMethodParams.HTTP_URI_CHARSET, "UTF-8"); NameValuePair[] pairs = new NameValuePair[params.length + 1]; int i = 0; for (Param param : params) { log.debug(" setting " + param.getName() + "=" + param.getValue()); pairs[i++] = param.toNameValuePair(); } pairs[i++] = new NameValuePair(API_SIG_PARAM, calcApiSig(params)); method.setQueryString(pairs); try { URI methodUri; try { methodUri = method.getURI(); log.info("Executing the method:" + methodUri); } catch (URIException exception) { String message = "Cannot determine the URI of the web method"; log.error(message); throw new ServiceInternalException(message, exception); } int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { log.error("Method failed: " + method.getStatusLine()); throw new ServiceInternalException("method failed: " + method.getStatusLine()); } // THINK: this method is deprecated, but the only way to get the body as a string, without consuming // the body input stream: the HttpMethodBase issues a warning but does not let you call the "setResponseStream()" method! String responseBodyAsString = method.getResponseBodyAsString(); log.info(" Invocation response:\r\n" + responseBodyAsString); Document responseDoc = builder.parse(method.getResponseBodyAsStream()); Element wrapperElt = responseDoc.getDocumentElement(); if (!wrapperElt.getNodeName().equals("rsp")) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + responseBodyAsString); } else { String stat = wrapperElt.getAttribute("stat"); if (stat.equals("fail")) { Node errElt = wrapperElt.getFirstChild(); while (errElt != null && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) { errElt = errElt.getNextSibling(); } if (errElt == null) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + responseBodyAsString); } else { throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")), ((Element) errElt).getAttribute("msg")); } } else { Node dataElt = wrapperElt.getFirstChild(); while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE || dataElt.getNodeName().equals("transaction") == true)) { try { Node nextSibling = dataElt.getNextSibling(); if (nextSibling == null) { break; } else { dataElt = nextSibling; } } catch (IndexOutOfBoundsException exception) { // Some implementation may throw this exception, instead of returning a null sibling break; } } if (dataElt == null) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + responseBodyAsString); } else { result = (Element) dataElt; } } } } catch (HttpException e) { throw new ServiceInternalException("", e); } catch (IOException e) { throw new ServiceInternalException("", e); } catch (SAXException e) { throw new ServiceInternalException("", e); } finally { // Release the connection. method.releaseConnection(); } lastInvocation = System.currentTimeMillis(); return result; }
From source file:de.sub.goobi.helper.tasks.CreatePdfFromServletThread.java
/** * Aufruf als Thread./* ww w . ja v a 2s . c o m*/ */ @Override public void run() { setStatusProgress(30); if ((this.getProcess() == null) || (this.targetFolder == null) || (this.internalServletPath == null)) { setStatusMessage("parameters for temporary and final folder and internal servlet path not defined"); setStatusProgress(-1); return; } GetMethod method = null; try { /* * define path for mets and pdfs */ URL kitodoContentServerUrl = null; String contentServerUrl = ConfigCore.getParameter("kitodoContentServerUrl"); new File(""); URI tempPdf = fileService.createResource(this.getProcess().getTitle() + ".pdf"); URI finalPdf = fileService.createResource(this.targetFolder, this.getProcess().getTitle() + ".pdf"); Integer contentServerTimeOut = ConfigCore.getIntParameter("kitodoContentServerTimeOut", 60000); /* * using mets file */ if (new MetadatenVerifizierung().validate(this.getProcess()) && (this.metsURL != null)) { /* * if no contentserverurl defined use internal * goobiContentServerServlet */ if ((contentServerUrl == null) || (contentServerUrl.length() == 0)) { contentServerUrl = this.internalServletPath + "/gcs/gcs?action=pdf&metsFile="; } kitodoContentServerUrl = new URL(contentServerUrl + this.metsURL); /* * mets data does not exist or is invalid */ } else { if ((contentServerUrl == null) || (contentServerUrl.length() == 0)) { contentServerUrl = this.internalServletPath + "/cs/cs?action=pdf&images="; } StringBuilder url = new StringBuilder(); FilenameFilter filter = Helper.imageNameFilter; URI imagesDir = serviceManager.getProcessService().getImagesTifDirectory(true, this.getProcess()); ArrayList<URI> meta = fileService.getSubUris(filter, imagesDir); ArrayList<String> filenames = new ArrayList<>(); for (URI data : meta) { String file = ""; file += data.toURL(); filenames.add(file); } Collections.sort(filenames, new MetadatenHelper(null, null)); for (String f : filenames) { url.append(f); url.append("$"); } String imageString = url.substring(0, url.length() - 1); String targetFileName = "&targetFileName=" + this.getProcess().getTitle() + ".pdf"; kitodoContentServerUrl = new URL(contentServerUrl + imageString + targetFileName); } /* * get pdf from servlet and forward response to file */ HttpClient httpclient = new HttpClient(); if (logger.isDebugEnabled()) { logger.debug("Retrieving: " + kitodoContentServerUrl.toString()); } method = new GetMethod(kitodoContentServerUrl.toString()); try { method.getParams().setParameter("http.socket.timeout", contentServerTimeOut); int statusCode = httpclient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.error("HttpStatus not ok"); if (logger.isDebugEnabled()) { logger.debug("Response is:\n" + method.getResponseBodyAsString()); } return; } InputStream inStream = method.getResponseBodyAsStream(); try (BufferedInputStream bis = new BufferedInputStream(inStream); FileOutputStream fos = (FileOutputStream) fileService.write(tempPdf)) { byte[] bytes = new byte[8192]; int count = bis.read(bytes); while ((count != -1) && (count <= 8192)) { fos.write(bytes, 0, count); count = bis.read(bytes); } if (count != -1) { fos.write(bytes, 0, count); } } setStatusProgress(80); } finally { method.releaseConnection(); } /* * copy pdf from temp to final destination */ if (logger.isDebugEnabled()) { logger.debug("pdf file created: " + tempPdf + "; now copy it to " + finalPdf); } fileService.copyFile(tempPdf, finalPdf); if (logger.isDebugEnabled()) { logger.debug("pdf copied to " + finalPdf + "; now start cleaning up"); } fileService.delete(tempPdf); if (this.metsURL != null) { File tempMets = new File(this.metsURL.toString()); tempMets.delete(); } } catch (Exception e) { logger.error("Error while creating pdf for " + this.getProcess().getTitle(), e); setStatusMessage("error " + e.getClass().getSimpleName() + " while pdf creation: " + e.getMessage()); setStatusProgress(-1); /* * report Error to User as Error-Log */ String text = "error while pdf creation: " + e.getMessage(); URI uri = null; try { uri = fileService.createResource(this.targetFolder, this.getProcess().getTitle() + ".PDF-ERROR.log"); } catch (MalformedURLException e1) { logger.error( "URI " + this.targetFolder + this.getProcess().getTitle() + ".PDF-ERROR.log is malformed", e1); } catch (IOException e1) { logger.error("Ressource " + uri + " could not be created", e); } try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(fileService.write(uri)))) { output.write(text); } catch (IOException e1) { logger.error("Error while reporting error to user in file " + uri, e); } return; } finally { if (method != null) { method.releaseConnection(); } } setStatusMessage("done"); setStatusProgress(100); }
From source file:com.cognifide.maven.plugins.crx.CrxPackageAbstractMojo.java
/** * Performs post request to given URL with given parameters provided as a part lists. * //from w w w .j a va 2 s . c o m * @param targetURL Place where post action should be submitted * @param partList Parameters of post action * @return Response body * @throws MojoExecutionException */ protected String post(String targetURL, List<Part> partList) throws MojoExecutionException { PostMethod postMethod = new PostMethod(targetURL); try { Part[] parts = partList.toArray(new Part[partList.size()]); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); int status = getHttpClient().executeMethod(postMethod); if (status == HttpStatus.SC_OK) { return IOUtils.toString(postMethod.getResponseBodyAsStream()); } else { getLog().warn(postMethod.getResponseBodyAsString()); throw new MojoExecutionException("Request to the repository failed, cause: " + HttpStatus.getStatusText(status) + " (check URL, user and password)"); } } catch (IOException ex) { throw new MojoExecutionException("Request to the repository failed, cause: " + ex.getMessage(), ex); } finally { postMethod.releaseConnection(); } }
From source file:com.interaction.example.odata.multicompany.ODataMulticompanyITCase.java
/** * GET item, check id of entity//from www . j av a2s .co m */ @Test public void getFlightCheckId() throws Exception { org.apache.abdera.model.Entry entry = null; GetMethod method = new GetMethod(baseUri + "Flights(2)"); try { client.executeMethod(method); assertEquals(200, method.getStatusCode()); if (method.getStatusCode() == HttpStatus.SC_OK) { // read as string for debugging String response = method.getResponseBodyAsString(); System.out.println("Response = " + response); Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); Document<org.apache.abdera.model.Entry> doc = parser.parse(new StringReader(response)); entry = doc.getRoot(); } } catch (IOException e) { fail(e.getMessage()); } finally { method.releaseConnection(); } assertNotNull(entry); assertEquals("http://localhost:8080/example/interaction-odata-multicompany.svc/MockCompany001/Flights(2)", entry.getId().toString()); }
From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java
/** * Check if a file exists in the OC server * // w ww .j a v a 2 s . co m * @deprecated Use ExistenceCheckOperation instead * * @return 'true' if the file exists; 'false' it doesn't exist * @throws Exception When the existence could not be determined */ @Deprecated public boolean existsFile(String path) throws IOException, HttpException { HeadMethod head = new HeadMethod(getWebdavUri() + WebdavUtils.encodePath(path)); try { int status = executeMethod(head); Log_OC.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK) ? "(FAIL)" : "")); exhaustResponse(head.getResponseBodyAsStream()); return (status == HttpStatus.SC_OK); } finally { head.releaseConnection(); // let the connection available for other methods } }
From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchIndex.java
private void initializeIndex() { if (haveMappingInfo) { return;// w w w .j a v a 2s . c o m } if (!refreshIndexIfNecessary()) { try { ElasticSearchConnector connector = new ElasticSearchConnector(); JSONObject mappingInfo = createMappingInfo(); PutMethod putMethod = new PutMethod(ElasticSearchConnector.actualUrl(indexUrl)); putMethod.setRequestEntity(new StringRequestEntity(mappingInfo.toString(), MimeConstants.CT_APPLICATION_JSON, MimeConstants.P_CHARSET_UTF8)); int statusCode = connector.executeMethod(putMethod); if (statusCode == HttpStatus.SC_OK) { haveMappingInfo = true; refreshIndexIfNecessary(); // Sometimes searches don't seem to honor mapping info. Try to force it } else { ZimbraLog.index.error("Problem Setting mapping information for index with key=%s httpstatus=%d", key, statusCode); } } catch (HttpException e) { ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e); } catch (IOException e) { ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e); } catch (JSONException e) { ZimbraLog.index.error("Problem Setting mapping information for index with key=" + key, e); } } }
From source file:fitnesse.wikitext.widgets.Downloader.java
private void downloadFile(String pomUrl, File res) throws DownloadException { try {/*from w ww. ja v a2 s . c om*/ HttpClient httpClient = new HttpClient(); GetMethod method = new GetMethod(pomUrl); int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new DownloadException("Impossible to retrieve " + pomUrl + ", error code: " + statusCode); } else { ensureParentFileExist(res); FileUtils.fileWrite(res.getAbsolutePath(), method.getResponseBodyAsString(100000)); } } catch (HttpException e) { throw new DownloadException("Impossible to retrieve " + pomUrl, e); } catch (IOException e) { throw new DownloadException("Impossible to retrieve " + pomUrl, e); } }
From source file:com.zimbra.qa.unittest.TestCookieReuse.java
/** * Verify that we can RE-use the cookie for REST session if the session is valid *//* www . j a va 2s . c o m*/ @Test public void testValidSessionCookieReuse() throws ServiceException, IOException { //establish legitimate connection ZMailbox mbox = TestUtil.getZMailbox(USER_NAME); URI uri = mbox.getRestURI("Inbox?fmt=rss"); HttpClient alice = mbox.getHttpClient(uri); //create evesdropper's connection HttpClient eve = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); Cookie[] cookies = alice.getState().getCookies(); HttpState state = new HttpState(); for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; state.addCookie(new Cookie(uri.getHost(), cookie.getName(), cookie.getValue(), "/", null, false)); } eve.setState(state); GetMethod get = new GetMethod(uri.toString()); int statusCode = HttpClientUtil.executeMethod(eve, get); Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode); }
From source file:com.thoughtworks.go.server.service.ScheduleServiceSecurityTest.java
@Test public void shouldNotThrowExceptionIfUserHasOperatePermission() throws Exception { configHelper.addSecurityWithAdminConfig(); Username user = UserHelper.getUserName(); configHelper.setOperatePermissionForGroup("defaultGroup", user.getUsername().toString()); Pipeline pipeline = fixture.createPipelineWithFirstStagePassedAndSecondStageRunning(); HttpLocalizedOperationResult operationResult = new HttpLocalizedOperationResult(); Stage stageForCancellation = pipeline.getStages().byName(fixture.ftStage); Stage resultStage = scheduleService.cancelAndTriggerRelevantStages(stageForCancellation.getId(), user, operationResult);//from w w w . ja va 2 s . c o m assertThat(resultStage, is(not(nullValue()))); assertThat(operationResult.isSuccessful(), is(true)); assertThat(operationResult.httpCode(), is(HttpStatus.SC_OK)); //TODO: Check why stage result is not persisted after stage is cancelled // Stage mostRecent = stageDao.mostRecentStage(new StageConfigIdentifier(fixture.pipelineName, fixture.ftStage)); // assertThat(mostRecent.getResult(), is(StageResult.Cancelled)); }
From source file:com.microfocus.application.automation.tools.octane.actions.Webhooks.java
@RequirePOST public void doNotify(StaplerRequest req, StaplerResponse res) throws IOException { logger.info("Received POST from " + req.getRemoteHost()); // legal user, handle request JSONObject inputNotification = (JSONObject) JSONValue.parse(req.getInputStream()); Object properties = inputNotification.get("properties"); // without build context, could not send octane relevant data if (!req.getHeader(PROJECT_KEY_HEADER).isEmpty() && properties instanceof Map) { // get relevant parameters Map sonarAttachedProperties = (Map) properties; // filter notifications from sonar projects, who haven't configured listener parameters if (sonarAttachedProperties.containsKey(BUILD_NUMBER_PARAM_NAME) && sonarAttachedProperties.containsKey(JOB_NAME_PARAM_NAME)) { String buildId = (String) (sonarAttachedProperties.get(BUILD_NUMBER_PARAM_NAME)); String jobName = (String) sonarAttachedProperties.get(JOB_NAME_PARAM_NAME); // get sonar details from job configuration TopLevelItem jenkinsJob = Jenkins.getInstance().getItem(jobName); if (isValidJenkinsJob(jenkinsJob)) { AbstractProject jenkinsProject = ((AbstractProject) jenkinsJob); Integer buildNumber = Integer.valueOf(buildId, 10); if (isValidJenkinsBuildNumber(jenkinsProject, buildNumber)) { AbstractBuild build = getBuild(jenkinsProject, buildNumber); if (build != null && isBuildExpectingToGetWebhookCall(build) && !isBuildAlreadyGotWebhookCall(build)) { WebhookExpectationAction action = build.getAction(WebhookExpectationAction.class); ExtensionList<GlobalConfiguration> allConfigurations = GlobalConfiguration.all(); GlobalConfiguration sonarConfiguration = allConfigurations .getDynamic(SonarHelper.SONAR_GLOBAL_CONFIG); if (sonarConfiguration != null) { String sonarToken = SonarHelper.getSonarInstallationTokenByUrl(sonarConfiguration, action.getServerUrl()); HashMap project = (HashMap) inputNotification.get(PROJECT); String sonarProjectKey = (String) project.get(SONAR_PROJECT_KEY_NAME); // use SDK to fetch and push data OctaneSDK.getClients() .forEach(octaneClient -> octaneClient.getSonarService() .enqueueFetchAndPushSonarCoverage(jobName, buildId, sonarProjectKey, action.getServerUrl(), sonarToken)); markBuildAsRecievedWebhookCall(build); res.setStatus(HttpStatus.SC_OK); // sonar should get positive feedback for webhook }//from w w w . ja v a2 s . c o m } else { logger.warn("Got request from sonarqube webhook listener for build ," + buildId + " which is not expecting to get sonarqube data"); res.setStatus(HttpStatus.SC_EXPECTATION_FAILED); } } else { logger.warn("Got request from sonarqube webhook listener, but build " + buildId + " context could not be resolved"); res.setStatus(HttpStatus.SC_NOT_ACCEPTABLE); } } } } }