List of usage examples for java.net ConnectException getMessage
public String getMessage()
From source file:io.logspace.agent.hq.HqAgentController.java
@Override public void update(Date nextFireTime) { try {//from www. jav a2s.c o m this.uploadCapabilities(); } catch (UnknownHostException uhex) { this.logger.error( "Could not upload capabilities because the HQ was not available: {} - Will retry at {}", uhex.getMessage(), nextFireTime); // no need to try downloading as well return; } catch (NoRouteToHostException nrthex) { this.logger.error( "Could not upload capabilities because the HQ was not available: {} - Will retry at {}", nrthex.getMessage(), nextFireTime); // no need to try downloading as well return; } catch (ConnectException cex) { this.logger.error( "Could not upload capabilities because the HQ was not available: {} - Will retry at {}", cex.getMessage(), nextFireTime); // no need to try downloading as well return; } catch (IOException ioex) { this.logger.error("Failed to upload capabilities. Will retry at " + nextFireTime, ioex); } try { this.downloadOrder(); } catch (ConnectException cex) { this.logger.error("Could not download orders because the HQ was not available: {} - Will retry at {}", cex.getMessage(), nextFireTime); } catch (HttpResponseException hrex) { if (hrex.getStatusCode() == HTTP_NOT_FOUND) { this.logger.error("There was no order available: {} - Will retry at {}", hrex.getMessage(), nextFireTime); } else if (hrex.getStatusCode() == HTTP_FORBIDDEN) { this.logger.error("Not allowed to download order: {} - Will retry at {}", hrex.getMessage(), nextFireTime); } else { this.logger.error("Failed to download order. Will retry at {}", nextFireTime, hrex); } } catch (IOException ioex) { this.logger.error("Failed to download order. Will retry at {}", nextFireTime, ioex); } }
From source file:org.duniter.core.client.service.HttpServiceImpl.java
protected boolean executeRequest(HttpClient httpClient, HttpUriRequest request) { if (log.isDebugEnabled()) { log.debug("Executing request : " + request.getRequestLine()); }// ww w.ja v a 2s. com try { HttpResponse response = httpClient.execute(request); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: { response.getEntity().consumeContent(); return true; } case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_FORBIDDEN: throw new TechnicalException(I18n.t("duniter4j.client.authentication")); default: throw new TechnicalException( I18n.t("duniter4j.client.status", response.getStatusLine().toString())); } } catch (ConnectException e) { throw new TechnicalException(I18n.t("duniter4j.client.core.connect"), e); } catch (IOException e) { throw new TechnicalException(e.getMessage(), e); } }
From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpMetricsIngestionServerShutdownIntegrationTest.java
@Test public void testHttpIngestionHappyCase() throws Exception { // given/* w w w . j av a2 s.c o m*/ HttpPost post = new HttpPost(getMetricsURI()); HttpEntity entity = new StringEntity(generateJSONMetricsData(), ContentType.APPLICATION_JSON); post.setEntity(entity); HttpResponse response = client.execute(post); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); HttpPost post2 = new HttpPost(getMetricsURI()); HttpEntity entity2 = new StringEntity(generateJSONMetricsData(), ContentType.APPLICATION_JSON); post2.setEntity(entity2); // when server.shutdownServer(); // then try { HttpResponse response2 = client.execute(post2); Assert.fail("We should have received a Connect exception"); } catch (ConnectException ex) { // NOTE: ideally, one would simply use jUnit's `ExpectedException` // rule or `expected` param to indicate that we expected a // ConnectException to be thrown. However, ConnectException can be // thrown for a number of different reasons, and the only way to // know for sure that the connection was refused (and, thus, that // the port is no longer open) is to catch the exception object and // check its message. Hence, this try/catch. Assert.assertTrue("Connection refused", ex.getMessage().contains("Connection refused")); } }
From source file:org.apache.ambari.view.capacityscheduler.ConfigurationService.java
/** * Gets node labels from RM//w ww.ja v a2 s . c o m * * @return node labels */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("/nodeLabels") public Response getNodeLabels() { Response response; try { String url = String.format(RM_GET_NODE_LABEL_URL, getRMUrl()); InputStream rmResponse = context.getURLStreamProvider().readFrom(url, "GET", (String) null, new HashMap<String, String>()); String nodeLabels = IOUtils.toString(rmResponse); response = Response.ok(nodeLabels).build(); } catch (ConnectException ex) { throw new ServiceFormattedException("Connection to Resource Manager refused", ex); } catch (WebApplicationException ex) { throw ex; } catch (Exception ex) { throw new ServiceFormattedException(ex.getMessage(), ex); } return response; }
From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java
public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException { final String methodName = IServiceCheckProcessor.CNAME + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException"; if (DEBUG) {// www. j a v a2 s .co m DEBUGGER.debug(methodName); DEBUGGER.debug("ServiceCheckRequest: {}", request); } int exitCode = -1; Socket socket = null; File sourceFile = null; CommandLine command = null; BufferedWriter writer = null; ExecuteStreamHandler streamHandler = null; ByteArrayOutputStream outputStream = null; ServiceCheckResponse response = new ServiceCheckResponse(); final DefaultExecutor executor = new DefaultExecutor(); final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { switch (request.getRequestType()) { case NETSTAT: sourceFile = scriptConfig.getScripts().get("netstat"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; case REMOTEDATE: response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData(System.currentTimeMillis()); break; case TELNET: response = new ServiceCheckResponse(); int targetPort = request.getPortNumber(); String targetServer = request.getTargetHost(); if (DEBUG) { DEBUGGER.debug("Target port: {}", targetPort); DEBUGGER.debug("Target server: {}", targetServer); } if (targetPort == 0) { throw new ServiceCheckException("Target port number was not assigned. Cannot action request."); } final String CRLF = "\r\n"; final String TERMINATE_TELNET = "^]"; synchronized (new Object()) { InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort); socket = new Socket(); socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT); socket.setSoLinger(false, 0); socket.setKeepAlive(false); try { socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + targetServer + " on port " + request.getPortNumber()); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(TERMINATE_TELNET + CRLF); pWriter.flush(); pWriter.close(); response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " successful."); } catch (ConnectException cx) { response.setRequestStatus(AgentStatus.FAILURE); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " failed with message: " + cx.getMessage()); } } break; case PROCESSLIST: sourceFile = scriptConfig.getScripts().get("processList"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; default: // unknown operation throw new ServiceCheckException("No valid operation was specified"); } } catch (UnknownHostException uhx) { ERROR_RECORDER.error(uhx.getMessage(), uhx); throw new ServiceCheckException(uhx.getMessage(), uhx); } catch (SocketException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new ServiceCheckException(sx.getMessage(), sx); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); throw new ServiceCheckException(iox.getMessage(), iox); } catch (InterruptedException ix) { ERROR_RECORDER.error(ix.getMessage(), ix); throw new ServiceCheckException(ix.getMessage(), ix); } finally { try { if (writer != null) { writer.close(); } if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } return response; }
From source file:org.jumpmind.symmetric.service.impl.PullService.java
public void execute(NodeCommunication nodeCommunication, RemoteNodeStatus status) { Node node = nodeCommunication.getNode(); if (StringUtils.isNotBlank(node.getSyncUrl()) || !parameterService.isRegistrationServer()) { int pullCount = 0; long batchesProcessedCount = 0; do {//from w w w. j a va 2s . c o m batchesProcessedCount = status.getBatchesProcessed(); pullCount++; log.debug("Pull requested for {}", node.toString()); if (pullCount > 1) { log.info("Immediate pull requested while in reload mode"); } try { dataLoaderService.loadDataFromPull(node, status); } catch (ConnectException ex) { log.warn("Failed to connect to the transport: {}", (node.getSyncUrl() == null ? parameterService.getRegistrationUrl() : node.getSyncUrl())); fireOffline(ex, node, status); } catch (OfflineException ex) { fireOffline(ex, node, status); } catch (UnknownHostException ex) { fireOffline(ex, node, status); } catch (SocketException ex) { log.warn("{}", ex.getMessage()); fireOffline(ex, node, status); } catch (IOException ex) { log.error("An IO exception happened while attempting to pull data", ex); fireOffline(ex, node, status); } if (!status.failed() && (status.getDataProcessed() > 0 || status.getBatchesProcessed() > 0)) { log.info("Pull data received from {}. {} rows and {} batches were processed", new Object[] { node.toString(), status.getDataProcessed(), status.getBatchesProcessed() }); } else if (status.failed()) { log.info( "There was a failure while pulling data from {}. {} rows and {} batches were processed", new Object[] { node.toString(), status.getDataProcessed(), status.getBatchesProcessed() }); } /* * Re-pull immediately if we are in the middle of an initial * load so that the initial load completes as quickly as * possible. */ } while (nodeService.isDataLoadStarted() && !status.failed() && status.getBatchesProcessed() > batchesProcessedCount); } else { log.warn("Cannot pull node '{}' in the group '{}'. The sync url is blank", node.getNodeId(), node.getNodeGroupId()); } }
From source file:org.openmrs.module.sana.queue.web.v1.servlet.SaveResponseServlet.java
/** * POST requests sent here will result in an email and sms message * with follow up information for sent back to the CHW *//* www. jav a 2 s .c om*/ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String encounterId = request.getParameter("encounterId"); String queueItemId = request.getParameter("queueItemId"); String doctorDiagnosis = request.getParameter("HiddenDiagnoses"); String doctorUrgency = request.getParameter("Urgency"); String doctorTreatment = request.getParameter("Treatment"); String doctorComments = request.getParameter("Comments"); PrintWriter output = response.getWriter(); QueueItemService queueService = Context.getService(QueueItemService.class); LocationService lservice = (LocationService) Context.getService(LocationService.class); ConceptService cservice = Context.getConceptService(); QueueItem q = null; if (queueItemId != null && !"".equals(queueItemId)) { q = queueService.getQueueItem(Integer.parseInt(queueItemId)); } else { Integer eid = Integer.parseInt(encounterId); for (QueueItem qi : queueService.getQueueItems()) { if (qi.getEncounterId().equals(eid)) { q = qi; } } } Encounter e = q.getEncounter(); //Extract the doctor's response from the HTML form //Parse the diagnosis list String diagnosisList = ""; if (doctorDiagnosis != null && !doctorDiagnosis.equals("")) { StringTokenizer stokenizer = new StringTokenizer(doctorDiagnosis, ","); String diagnosis = ""; String name = ""; Concept diagnosisConcept = cservice.getConcept("DOCTOR DIAGNOSIS"); while (stokenizer.hasMoreTokens()) { diagnosis = stokenizer.nextToken(); //Create a new obs with this diagnosis Obs o = new Obs(); o.setPerson(q.getPatient()); o.setLocation(lservice.getDefaultLocation()); //Get DIAGNOSIS concept if (diagnosisConcept != null) o.setConcept(diagnosisConcept); else { fail(output, "Couldn't find concept DOCTOR DIAGNOSIS. Go to" + " Concept Dictionary and add this concept."); return; } o.setDateCreated(new Date()); o.setObsDatetime(new Date()); o.setCreator(Context.getAuthenticatedUser()); o.setValueText(diagnosis); //Extract diagnosis name (without SNOMED ID) if (diagnosis.contains("|")) name = diagnosis.substring(0, diagnosis.indexOf('|') - 1).toLowerCase(); else name = diagnosis.toLowerCase(); //Add diagnosis to list if (diagnosisList.equals("")) diagnosisList += name; else diagnosisList += ", " + name; //Update and save the encounter and queue item e.addObs(o); Context.getObsService().saveObs(o, ""); } } //If null, set to empty string when sending back to phone else { doctorDiagnosis = ""; } log.error("Diagnosis " + doctorDiagnosis); if (doctorUrgency != null && !doctorUrgency.equals("")) { //Create a new obs with the doctor's response Obs o = new Obs(); o.setPerson(q.getPatient()); o.setLocation(lservice.getDefaultLocation()); //Get URGENCY LEVEL concept Concept urgencyConcept = cservice.getConceptByName("DOCTOR URGENCY LEVEL"); if (urgencyConcept != null) o.setConcept(urgencyConcept); else { fail(output, "Couldn't find concept DOCTOR URGENCY LEVEL. Go to" + " Concept Dictionary and add this concept."); return; } o.setDateCreated(new Date()); o.setObsDatetime(new Date()); o.setCreator(Context.getAuthenticatedUser()); o.setValueText(doctorUrgency); //Update and save the encounter and queue item e.addObs(o); Context.getObsService().saveObs(o, ""); } //If null, set to empty string when sending back to phone else { doctorUrgency = ""; } log.debug("doctorUrgency " + doctorUrgency); if (doctorTreatment != null && !doctorTreatment.equals("")) { //Create a new obs with the doctor's response Obs o = new Obs(); o.setDateCreated(new Date()); o.setPerson(q.getPatient()); o.setLocation(lservice.getDefaultLocation()); //Get TREATMENT RECOMMENDATION concept Concept treatmentConcept = cservice.getConceptByName("DOCTOR TREATMENT RECOMMENDATION"); if (treatmentConcept != null) o.setConcept(treatmentConcept); else { fail(output, "Couldn't find concept DOCTOR TREATMENT " + "RECOMMENDATION. Go to Concept Dictionary and add this " + "concept."); return; } o.setObsDatetime(new Date()); o.setCreator(Context.getAuthenticatedUser()); o.setValueText(doctorTreatment); //Update and save the encounter and queue item e.addObs(o); Context.getObsService().saveObs(o, ""); } //If null, set to empty string when sending back to phone else { doctorTreatment = ""; } log.debug("doctorTreatment " + doctorTreatment); if (doctorComments != null && !doctorComments.equals("")) { //Create a new obs with the doctor's response Obs o = new Obs(); o.setPerson(q.getPatient()); o.setLocation(lservice.getDefaultLocation()); //Get DOCTOR COMMENTS concept Concept commentsConcept = cservice.getConceptByName("DOCTOR COMMENTS"); if (commentsConcept != null) o.setConcept(commentsConcept); else { fail(output, "Couldn't find concept DOCTOR COMMENTS. Go to " + "Concept Dictionary and add this concept."); return; } o.setDateCreated(new Date()); o.setObsDatetime(new Date()); o.setCreator(Context.getAuthenticatedUser()); o.setValueText(doctorComments); o.setEncounter(e); //Update and save the encounter and obs e.addObs(o); Context.getObsService().saveObs(o, ""); } else { doctorComments = ""; } log.debug("doctorComments " + doctorComments); //Set plan String plan = ""; if (doctorTreatment.equals("") && doctorComments.equals("")) plan = ""; else if (doctorTreatment.equals("")) plan = doctorComments; else if (doctorComments.equals("")) plan = doctorTreatment; else plan = doctorTreatment + ", " + doctorComments; Context.getEncounterService().saveEncounter(e); q.setEncounter(e); q.setStatus(QueueItemStatus.CLOSED); q.setDateChanged(new Date()); queueService.updateQueueItem(q); //Get phone number and construct SMS message and email message String patientId = e.getPatient().getPatientIdentifier().toString(); // Get the user's preferred notification String notificationPref = e.getCreator().getUserProperty("notification"); // TODO Come up with a better way to trigger notification type //Send sms try { boolean sms = sendSMS(q, diagnosisList, plan, patientId); } catch (ConnectException err) { log.error("Couldn't connect to notification server " + Context.getAdministrationService().getGlobalProperty(Property.MDS_URI)); fail(output, "Failed to send SMS message." + err.getMessage()); } catch (Exception err) { log.error("Unable to send notification", err); fail(output, "Failed to send SMS message." + err.getMessage()); } try { //If person who uploaded the case has an email, then email the // specialist response to them if they indicated so in their user // profile if (notificationPref.equalsIgnoreCase("email")) { boolean email = sendMail(q, diagnosisList, plan, patientId, doctorUrgency); } } catch (ConnectException err) { log.error("Couldn't connect to email notification server " + Context.getAdministrationService().getGlobalProperty(Property.EMAIL_URL)); } catch (Exception err) { log.error("Email failed: " + err.getMessage()); fail(output, "Failed to send email message " + err.getMessage()); } response.sendRedirect(request.getContextPath() + "/module/sana/queue/v1/queue.form"); }
From source file:org.kepler.actor.rest.RESTService.java
/** * * @param pmPairList// www.j a v a 2 s . co m * List of the name and value parameters that user has provided * through paramInputPort. However in method this list is * combined with the user configured ports and the combined list * name value pair parameters are added to the service URL * separated by ampersand. * @param nvPairList * List of the name and value parameters that user has provided * @return the results after executing the Get service. */ public String executeGetMethod(List<NameValuePair> nvPairList, String serSiteURL) throws IllegalActionException { if (_debugging) { _debug("I AM IN GET METHOD"); } //log.debug("I AM IN GET METHOD"); HttpClient client = new HttpClient(); StringBuilder results = new StringBuilder(); results.append(serSiteURL); List<NameValuePair> fullPairList = getCombinedPairList(nvPairList); if (fullPairList.size() > 0) { results.append("?"); int pairListSize = fullPairList.size(); for (int j = 0; j < pairListSize; j++) { NameValuePair nvPair = fullPairList.get(j); results.append(nvPair.getName()).append(ServiceUtils.EQUALDELIMITER).append(nvPair.getValue()); if (j < pairListSize - 1) { results.append("&"); } } } if (_debugging) { _debug("RESULTS :" + results.toString()); } // Create a method instance. GetMethod method = new GetMethod(results.toString()); InputStream rstream = null; StringBuilder resultsForDisplay = new StringBuilder(); try { messageBldr = new StringBuilder(); messageBldr.append("In excuteGetMethod, communicating with service: ").append(serSiteURL) .append(" STATUS Code: "); int statusCode = client.executeMethod(method); messageBldr.append(statusCode); log.debug(messageBldr.toString()); if (_debugging) { _debug(messageBldr.toString()); } // if(statusCode == 201){ // System.out.println("Success -- " + statusCode + // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString()); // }else{ // System.out.println("Failure -- " + statusCode + // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString()); // } rstream = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(rstream)); String s; while ((s = br.readLine()) != null) { resultsForDisplay.append(s).append(ServiceUtils.LINESEP); } } catch (HttpException httpe) { if (_debugging) { _debug("Fatal protocol violation: " + httpe.getMessage()); } httpe.printStackTrace(); throw new IllegalActionException(this, httpe, "Fatal Protocol Violation: " + httpe.getMessage()); } catch (ConnectException conExp) { if (_debugging) { _debug("Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage()); } conExp.printStackTrace(); throw new IllegalActionException(this, conExp, "Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage()); } catch (IOException ioe) { if (_debugging) { _debug("IOException: " + ioe.getMessage()); } // System.err.println("Fatal transport error: " + e.getMessage()); ioe.printStackTrace(); throw new IllegalActionException(this, ioe, "IOException: " + ioe.getMessage()); } catch (Exception e) { if (_debugging) { _debug("Fatal transport error: " + e.getMessage()); } // System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); throw new IllegalActionException(this, e, "Error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); client = null; // close InputStream; if (rstream != null) try { rstream.close(); } catch (IOException e) { e.printStackTrace(); throw new IllegalActionException(this, e, "InputStream Close Exception: " + e.getMessage()); } } return resultsForDisplay.toString(); }
From source file:org.kepler.actor.rest.RESTService.java
/** * File & regular parameters are passed as two separate lists and they are * treated little differently. If flPairList is not null or empty then this * method uses Part Object else no.// w ww.j a va 2 s . c o m * * @param pmPairList * List of the name and value parameters that user has provided * @param flPairList * List of the name and value (full file path)of file parameters. * It is essentially a list of files that user wishes to attach. * @return the results after executing the Post service. */ public String executePostMethod(List<NameValuePair> pmPairList, List<NameValuePair> flPairList, String serSiteURL) throws IllegalActionException { if (_debugging) { _debug("I AM IN POST METHOD"); } //log.debug("I AM IN POST METHOD"); String postAddress = serSiteURL; HttpClient client = new HttpClient(); MultipartPostMethod method = new MultipartPostMethod(postAddress); List<NameValuePair> fullNameValueList = getCombinedPairList(pmPairList); if (flPairList != null && flPairList.size() > 0) { fullNameValueList.addAll(flPairList); int totalSize = fullNameValueList.size(); Part[] parts = new Part[totalSize]; try { for (int i = 0; i < parts.length; i++) { String nm = fullNameValueList.get(i).getName(); String vl = fullNameValueList.get(i).getValue(); if (i > totalSize - flPairList.size() - 1) { System.out.println("FILE NAME: " + nm); File file = getFileObject(vl); // System.out.println("FILE NAME: " + file.getName()); parts[i] = new FilePart(nm, file); method.addPart(parts[i]); System.out.println("PARTS: " + i + " " + parts[i].getName()); System.out.println("file Name: " + vl); } else { System.out.println("PARAMETER NAME: " + nm); System.out.println("PARAMETER Value: " + vl); parts[i] = new StringPart(nm, vl); method.addPart(parts[i]); } if (_debugging) { _debug("Value of i: " + i); } } } catch (FileNotFoundException fnfe) { if (_debugging) { _debug("File Not Exception: " + fnfe.getMessage()); } fnfe.printStackTrace(); throw new IllegalActionException(this, fnfe, "File Not Found: " + fnfe.getMessage()); } } else { for (NameValuePair nmPair : fullNameValueList) { method.addParameter(nmPair.getName(), nmPair.getValue()); } } InputStream rstream = null; StringBuilder results = new StringBuilder(); try { messageBldr = new StringBuilder(); messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL) .append(" STATUS Code: "); int statusCode = client.executeMethod(method); messageBldr.append(statusCode); log.debug("DEBUG: " + messageBldr.toString()); System.out.println(messageBldr.toString()); // if(statusCode == 201){ // System.out.println("Succuess -- " + statusCode + // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString()); // }else{ // System.out.println("Failure -- " + statusCode + // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString()); // } rstream = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(rstream)); log.debug("BEFORE WHILE LOOP"); String s; while ((s = br.readLine()) != null) { results.append(s).append(ServiceUtils.LINESEP); } } catch (HttpException e) { if (_debugging) { _debug("Fatal protocol violation: " + e.getMessage()); } e.printStackTrace(); return "Protocol Violation"; } catch (ConnectException conExp) { if (_debugging) { _debug("Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage()); } conExp.printStackTrace(); throw new IllegalActionException(this, conExp, "Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage()); } catch (IOException ioe) { if (_debugging) { _debug("Fatal transport error: " + ioe.getMessage()); } // System.err.println("Fatal transport error: " + e.getMessage()); ioe.printStackTrace(); throw new IllegalActionException(this, ioe, "IOException: Perhaps could not" + " connect to the service '" + serSiteURL + "'. " + ioe.getMessage()); } catch (Exception e) { if (_debugging) { _debug("Error: " + e.getMessage()); } // System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); throw new IllegalActionException(this, e, "Error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); client = null; // close InputStream; if (rstream != null) try { rstream.close(); } catch (IOException e) { e.printStackTrace(); throw new IllegalActionException(this, e, "InputStream Close Exception: " + e.getMessage()); } } return results.toString(); }
From source file:org.opennms.netmgt.rtc.DataSender.java
/** * Subscribe - Add the received URL and related info to the category->URLs map * so the sendData() can send out to appropriate URLs for each category. * Also send the latest info for the category * * @param url a {@link java.lang.String} object. * @param catlabel a {@link java.lang.String} object. * @param user a {@link java.lang.String} object. * @param passwd a {@link java.lang.String} object. *///from www . j a va 2s . c om public synchronized void subscribe(final String url, final String catlabel, final String user, final String passwd) { // send category data to the newly subscribed URL // look up info for this category final RTCCategory cat = m_dataMgr.getCategories().get(catlabel); if (cat == null) { // oops! category for which we have no info! LOG.warn("RTC: No information available for category: {}", catlabel); return; } // create new HttpPostInfo final HttpPostInfo postInfo; try { postInfo = new HttpPostInfo(url, catlabel, user, passwd); } catch (final MalformedURLException mue) { LOG.warn("ERROR subscribing: Invalid URL '{}' - Data WILL NOT be SENT to the specified url", url); return; } // Add the URL to the list for the specified category Set<HttpPostInfo> urlList = m_catUrlMap.get(catlabel); if (urlList == null) { urlList = new HashSet<HttpPostInfo>(); m_catUrlMap.put(catlabel, urlList); } if (!urlList.add(postInfo)) { LOG.debug("Already subscribed to URL: {}\tcatlabel: {}\tuser: {} - IGNORING LATEST subscribe event", url, catlabel, user); } else { LOG.debug("Subscribed to URL: {}\tcatlabel: {}\tuser:{}", url, catlabel, user); } try { m_dsrPool.execute(new Runnable() { @Override public void run() { // send data Reader inr = null; InputStream inp = null; try { LOG.debug("DataSender: posting data to: {}", url); final EuiLevel euidata = m_dataMgr.getEuiLevel(cat); inr = new PipedMarshaller(euidata).getReader(); // Connect with a fairly long timeout to allow the web UI time to register the // {@link RTCPostServlet}. Actually, this doesn't seem to work because the POST // will immediately throw a {@link ConnectException} if the web UI isn't ready // yet. Oh well. inp = HttpUtils.post(postInfo.getURL(), inr, user, passwd, 8 * HttpUtils.DEFAULT_POST_BUFFER_SIZE, 60000); final byte[] tmp = new byte[1024]; int bytesRead; while ((bytesRead = inp.read(tmp)) != -1) { if (LOG.isDebugEnabled()) { if (bytesRead > 0) { LOG.debug("DataSender: post response: {}", new String(tmp, 0, bytesRead)); } } } LOG.debug("DataSender: posted data for category: {}", catlabel); } catch (final ConnectException e) { // These exceptions will be thrown if we try to POST RTC data before the web UI is available. // Don't log a large stack trace for this because it will happen during startup before the // RTCPostServlet is ready to handle requests. LOG.warn("DataSender: Unable to send category '{}' to URL '{}': {}", catlabel, url, e.getMessage()); } catch (final Throwable t) { LOG.warn("DataSender: Unable to send category '{}' to URL '{}'", catlabel, url, t); } finally { IOUtils.closeQuietly(inp); IOUtils.closeQuietly(inr); } } }); } catch (RejectedExecutionException e) { LOG.warn("Unable to queue datasender. The task was rejected by the pool. Current queue size: {}.", m_queue.size(), e); } }