List of usage examples for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER
String RETRY_HANDLER
To view the source code for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER.
Click Source Link
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.importers.ImportGOESRealtime.java
/*********************************************************************************************** * doImportGOESRealtime().//w w w .ja v a 2s .c o m * * @param dao * @param commandmessage * * @return ResponseMessageInterface */ public static ResponseMessageInterface doImportGOESRealtime(final ObservatoryInstrumentDAOInterface dao, final CommandMessageInterface commandmessage) { final String SOURCE = "ImportGOESRealtime.doImportGOESRealtime()"; final int PARAMETER_COUNT = 5; final int INDEX_URL = 0; final int INDEX_PATHNAME = 1; final int INDEX_INTERVAL = 2; final int INDEX_PERIOD = 3; final int INDEX_UPDATE = 4; final CommandType cmdImport; final List<ParameterType> listParameters; String strResponseValue; final ResponseMessageInterface responseMessage; final List<String> errors; final boolean boolDebug; boolDebug = (LOADER_PROPERTIES.isTimingDebug() || LOADER_PROPERTIES.isMetadataDebug() || LOADER_PROPERTIES.isStaribusDebug() || LOADER_PROPERTIES.isStarinetDebug()); // Initialise errors = new ArrayList<String>(10); dao.clearEventLogFragment(); // Get the latest Resources dao.readResources(); // Don't affect the CommandType of the incoming Command cmdImport = (CommandType) commandmessage.getCommandType().copy(); // We expect five parameters: the url, the pathname, the capture interval, the capture period and the update flag listParameters = cmdImport.getParameterList(); if ((dao.getHostInstrument() != null) && (dao.getHostInstrument().getInstrument() != null) && (dao.getHostInstrument().getInstrument().getController() != null) && (dao.getHostInstrument().getInstrument().getController().getVirtualAddress() != null) && (listParameters != null) && (listParameters.size() == PARAMETER_COUNT) && (listParameters.get(INDEX_URL) != null) && (SchemaDataType.STRING .equals(listParameters.get(INDEX_URL).getInputDataType().getDataTypeName())) && (listParameters.get(INDEX_PATHNAME) != null) && (SchemaDataType.PATH_NAME .equals(listParameters.get(INDEX_PATHNAME).getInputDataType().getDataTypeName())) && (listParameters.get(INDEX_INTERVAL) != null) && (SchemaDataType.DECIMAL_INTEGER .equals(listParameters.get(INDEX_INTERVAL).getInputDataType().getDataTypeName())) && (listParameters.get(INDEX_PERIOD) != null) && (SchemaDataType.DECIMAL_INTEGER .equals(listParameters.get(INDEX_PERIOD).getInputDataType().getDataTypeName())) && (listParameters.get(INDEX_UPDATE) != null) && (SchemaDataType.BOOLEAN .equals(listParameters.get(INDEX_UPDATE).getInputDataType().getDataTypeName()))) { try { final String strURL; final String strPathname; final String strCaptureInterval; final String strCapturePeriod; final boolean boolRealtimeUpdate; final int intCaptureIntervalSec; int intCapturePeriodSec; final HttpClient client; final HttpMethod method; strURL = listParameters.get(INDEX_URL).getValue(); strPathname = listParameters.get(INDEX_PATHNAME).getValue(); strCaptureInterval = listParameters.get(INDEX_INTERVAL).getValue(); strCapturePeriod = listParameters.get(INDEX_PERIOD).getValue(); boolRealtimeUpdate = Boolean.parseBoolean(listParameters.get(INDEX_UPDATE).getValue()); intCaptureIntervalSec = Integer.parseInt(strCaptureInterval); intCapturePeriodSec = Integer.parseInt(strCapturePeriod); // Check for silly parameter settings // CapturePeriod = 0 means run continuously if ((strURL != null) && (!EMPTY_STRING.equals(strURL.trim())) && (intCaptureIntervalSec > 0) && (intCapturePeriodSec >= 0)) { final String strPeriod; final int intCaptureCountMax; final ResponseMessageStatusList listStatusInCaptureLoop; boolean boolSuccess; if (intCapturePeriodSec == 0) { strPeriod = CaptureCommandHelper.MSG_PERIOD_CONTINUOUS; } else { strPeriod = Integer.toString(intCapturePeriodSec); } // We have all the Parameters, now prepare the HTTP client client = new HttpClient(); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); method = new GetMethod(strURL); // See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html // The User-Agent request-header field contains information about the user agent originating the request method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)"); // The Referer[sic] request-header field allows the client to specify, for the server's benefit, // the address (URI) of the resource from which the Request-URI was obtained // (the "referrer", although the header field is misspelled.) method.setRequestHeader("Referer", strURL + "/Jview.htm"); // Log everything we have so far SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.INFO, METADATA_TARGET_IMAGE + METADATA_ACTION_IMPORT + METADATA_URL_REQUEST + strURL + TERMINATOR_SPACE + METADATA_PATHNAME + strPathname + TERMINATOR_SPACE + METADATA_INTERVAL + intCaptureIntervalSec + TERMINATOR_SPACE + METADATA_PERIOD + strPeriod + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); // Correct the CapturePeriod for continuous operation if (intCapturePeriodSec == 0) { // Allow about 10 days of operation! (Could be Integer.MAX_VALUE?) intCapturePeriodSec = 1000000; } intCaptureCountMax = intCapturePeriodSec / intCaptureIntervalSec; boolSuccess = true; // Adjust the Timeout for the number of commands expected // TODO REVIEW TimeoutHelper.restartDAOTimeoutTimer(dao, intCounter, 0, 0); listStatusInCaptureLoop = ResponseMessageStatus.createResponseMessageStatusList(); for (int intCaptureIndex = 0; ((intCaptureIndex < intCaptureCountMax) && (boolSuccess) && Utilities.executeWorkerCanProceed(dao)); intCaptureIndex++) { final long longTimeStart; final long longTimeFinish; final long longTimeToWait; longTimeStart = dao.getObservatoryClock().getSystemTimeMillis(); listStatusInCaptureLoop.clear(); try { final int intStatus; final InputStream inputStream; // Now try to get the Image intStatus = client.executeMethod(method); // Check the server status if (intStatus != HttpStatus.SC_OK) { SimpleEventLogUIComponent .logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + SPACE + method.getStatusLine(), SOURCE, dao.getObservatoryClock()); } // It is vital that the response body is always read, // regardless of the status returned by the server. inputStream = method.getResponseBodyAsStream(); if (inputStream != null) { final BufferedImage image; image = ImageIO.read(inputStream); // If we get here, it must have succeeded... (otherwise IOException, ImageFormatException) // Save the image as a timestamped PNG file every time boolSuccess = DataExporter.exportImage(image, strPathname + "/GOES", true, FileUtilities.png, dao.getEventLogFragment(), dao.getObservatoryClock()); // Pass the Image to the DAO, and then to the Instrument and InstrumentPanel if (boolRealtimeUpdate) { dao.setImageData(image); dao.setUnsavedData(true); REGISTRY.getFramework().notifyFrameworkChangedEvent(dao.getHostInstrument()); InstrumentHelper.notifyInstrumentChanged(dao.getHostInstrument()); } inputStream.close(); listStatusInCaptureLoop.add(ResponseMessageStatus.SUCCESS); } else { // No data are available SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_PARSE_DATA, SOURCE, dao.getObservatoryClock()); } } catch (NumberFormatException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } catch (HttpException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } catch (IOException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_IO + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } // Take account of the time elapsed so far... longTimeFinish = dao.getObservatoryClock().getSystemTimeMillis(); longTimeToWait = (intCaptureIntervalSec * ChronosHelper.SECOND_MILLISECONDS) - (longTimeFinish - longTimeStart); if (longTimeToWait > 0) { // Wait for the required time, checking to see if we have been stopped by the User Utilities.safeSleepPollExecuteWorker(longTimeToWait, dao); } else { LOGGER.error(SOURCE + " Invalid capture interval [time_to_wait=" + longTimeToWait + " msec]"); } } // Always release the HttpClient connection method.releaseConnection(); //----------------------------------------------------------------------------- // Capture the final Status and ResponseValue (these may show a failure) dao.getResponseMessageStatusList().addAll(listStatusInCaptureLoop); if (dao.getResponseMessageStatusList().contains(ResponseMessageStatus.SUCCESS)) { strResponseValue = ResponseMessageStatus.SUCCESS.getResponseValue(); } else { SimpleEventLogUIComponent.logErrors(dao.getEventLogFragment(), EventStatus.FATAL, errors, SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.PREMATURE_TERMINATION.getResponseValue(); } } else { throw new IllegalArgumentException(EXCEPTION_PARAMETER_INVALID); } } catch (NumberFormatException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, METADATA_EXCEPTION + ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage() + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, METADATA_EXCEPTION + ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage() + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (Exception exception) { exception.printStackTrace(); SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, METADATA_EXCEPTION + dao.getInstrumentName() + " Generic Exception [exception=" + exception.getMessage() + "]" + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE); } } else { // Incorrectly configured XML strResponseValue = ResponseMessageStatus.INVALID_XML.getResponseValue(); dao.getResponseMessageStatusList().add( DAOCommandHelper.logInvalidXML(dao, SOURCE, METADATA_TARGET_IMAGE, METADATA_ACTION_CAPTURE)); } ObservatoryInstrumentHelper.runGarbageCollector(); responseMessage = ResponseMessageHelper.createResponseMessage(dao, commandmessage, cmdImport, null, null, strResponseValue); return (responseMessage); }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.importers.ImportImageRemote.java
/*********************************************************************************************** * doImportImageRemote()./*from w ww . ja va2 s.co m*/ * http://hc.apache.org/httpclient-3.x/tutorial.html * http://www.eboga.org/java/open-source/httpclient-demo.html * * @param dao * @param commandmessage * * @return ResponseMessageInterface */ public static ResponseMessageInterface doImportImageRemote(final ObservatoryInstrumentDAOInterface dao, final CommandMessageInterface commandmessage) { final String SOURCE = "ImportImageRemote.doImportImageRemote()"; final int PARAMETER_COUNT = 1; final int INDEX_URL = 0; final CommandType commandType; final List<ParameterType> listParameters; ResponseMessageInterface responseMessage; LOGGER.debugTimedEvent(LOADER_PROPERTIES.isTimingDebug(), SOURCE); // Get the latest Resources dao.readResources(); // Don't affect the CommandType of the incoming Command commandType = (CommandType) commandmessage.getCommandType().copy(); // We expect one parameter, the filename listParameters = commandType.getParameterList(); responseMessage = null; // TODO REVIEW Initialise all DAO data containers if possible // dao.clearData(); // Check the Command parameters before continuing to retrieve the data file // Note that a FileChooser is not provided for remote file retrieval! if ((commandmessage.getInstrument() != null) && (commandmessage.getInstrument().getController() != null) && (commandmessage.getInstrument().getController().getVirtualAddress() != null) && (listParameters != null) && (listParameters.size() == PARAMETER_COUNT) && (listParameters.get(INDEX_URL) != null) && (SchemaDataType.STRING .equals(listParameters.get(INDEX_URL).getInputDataType().getDataTypeName()))) { final String strURL; strURL = listParameters.get(INDEX_URL).getValue(); LOGGER.debugTimedEvent(LOADER_PROPERTIES.isTimingDebug(), "ImportImageRemote.importImageRemote() [url=" + strURL + "]"); if ((strURL != null) && (!EMPTY_STRING.equals(strURL.trim()))) { final HttpClient client; final HttpMethod method; // Set up the HttpClient client = new HttpClient(); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); method = new GetMethod(strURL); // See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html // The User-Agent request-header field contains information about the user agent originating the request method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)"); // The Referer[sic] request-header field allows the client to specify, for the server's benefit, // the address (URI) of the resource from which the Request-URI was obtained // (the "referrer", although the header field is misspelled.) method.setRequestHeader("Referer", strURL + "/Jview.htm"); try { final int intStatus; final InputStream inputStream; // Now try to get the Image intStatus = client.executeMethod(method); // Check the server status if (intStatus != HttpStatus.SC_OK) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + SPACE + method.getStatusLine(), SOURCE, dao.getObservatoryClock()); } // It is vital that the response body is always read, // regardless of the status returned by the server. inputStream = method.getResponseBodyAsStream(); if (inputStream != null) { BufferedImage image; image = null; if ((strURL.endsWith(FileUtilities.jpg)) || (strURL.endsWith(FileUtilities.jpeg))) { image = ImageIO.read(inputStream); } else if (strURL.endsWith(FileUtilities.png)) { final PngImage pngImage; // http://code.google.com/p/javapng/ pngImage = new PngImage(); image = pngImage.read(inputStream, true); } //-------------------------------------------------------------------------- // If we get here, it must have succeeded... if (image != null) { // Pass the Image to the DAO, and then to the Instrument and InstrumentPanel dao.setImageData(image); // Don't force the user to export imported data, but don't change the state of SavedData // Do not affect RawData, because Images have different containers // So don't change the ChannelCount or Temperature flag // If we get here, we have the image... SimpleEventLogUIComponent.logEvent( dao.getEventLogFragment(), EventStatus.INFO, METADATA_TARGET_IMAGE + METADATA_ACTION_IMPORT + METADATA_URL_REQUEST + strURL + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); REGISTRY.getFramework().notifyFrameworkChangedEvent(dao.getHostInstrument()); InstrumentHelper.notifyInstrumentChanged(dao.getHostInstrument()); // Create the ResponseMessage // The captureImage() operation normally just requires an Ack, i.e. no ResponseValue commandType.getResponse().setValue(ResponseMessageStatus.SUCCESS.getResponseValue()); responseMessage = ResponseMessageHelper.constructSuccessfulResponse(dao, commandmessage, commandType); } } else { // No data are available SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_PARSE_DATA, SOURCE, dao.getObservatoryClock()); } } catch (NumberFormatException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } catch (HttpException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } catch (IOException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_IO + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } finally { method.releaseConnection(); } } else { SimpleEventLogUIComponent.logEvent( dao.getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_IMAGE + METADATA_ACTION_IMPORT + METADATA_RESULT + "Image URL is not valid" + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); } } REGISTRY.getFramework().notifyFrameworkChangedEvent(dao.getHostInstrument()); InstrumentHelper.notifyInstrumentChanged(dao.getHostInstrument()); // If the Command failed, do not change any DAO data containers! // Our valuable data must remain available for export later... // Construct INVALID_PARAMETER responseMessage = ResponseMessageHelper.constructFailedResponseIfNull(dao, commandmessage, commandType, responseMessage); return (responseMessage); }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.impl.starinettester.dao.StarinetTesterDAO.java
/*********************************************************************************************** * sendHttpRequest().//from w ww .j a v a 2s. co m * http://hc.apache.org/httpclient-3.x/tutorial.html * http://www.eboga.org/java/open-source/httpclient-demo.html * * @param commandmessage * * @return ResponseMessageInterface */ public ResponseMessageInterface sendHttpRequest(final CommandMessageInterface commandmessage) { final String SOURCE = "StarinetTesterDAO.sendHttpRequest()"; final int PARAMETER_COUNT = 1; final int CHANNEL_COUNT = 1; final CommandType commandType; ResponseMessageInterface responseMessage; final HttpClient client; HttpMethod method; LOGGER.debugTimedEvent(LOADER_PROPERTIES.isTimingDebug(), SOURCE); // Get the latest Resources readResources(); // Don't affect the CommandType of the incoming Command commandType = (CommandType) commandmessage.getCommandType().copy(); responseMessage = null; // Do not change any DAO data containers! clearEventLogFragment(); // Set up the HttpClient client = new HttpClient(); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); // Initialise the Method with a default URL method = new GetMethod(DEFAULT_URL); try { final List<ParameterType> listParameters; // We expect one Parameter, the URL listParameters = commandType.getParameterList(); if ((listParameters != null) && (listParameters.size() == PARAMETER_COUNT) && (SchemaDataType.STRING.equals(listParameters.get(0).getInputDataType().getDataTypeName()))) { final String strURLInput; final int intStatus; final String strResponseBody; strURLInput = listParameters.get(0).getValue(); // Use the default URL if the Parameter was blank if ((strURLInput != null) && (!EMPTY_STRING.equals(strURLInput.trim()))) { method = new GetMethod(strURLInput); } // See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html // The User-Agent request-header field contains information about the user agent originating the request method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)"); // The Referer[sic] request-header field allows the client to specify, for the server's benefit, // the address (URI) of the resource from which the Request-URI was obtained // (the "referrer", although the header field is misspelled.) method.setRequestHeader("Referer", strReferrerURL); SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.INFO, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_URL_REQUEST + strURLInput + TERMINATOR + SPACE + METADATA_URL_REFERRER + strReferrerURL + TERMINATOR, SOURCE, getObservatoryClock()); // Now try to send the Request intStatus = client.executeMethod(method); // Check the server status if (intStatus != HttpStatus.SC_OK) { SimpleEventLogUIComponent .logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_MESSAGE + ERROR_HTTP + method.getStatusLine() + TERMINATOR, SOURCE, getObservatoryClock()); } // It is vital that the response body is *always* read, // regardless of the status returned by the server. strResponseBody = method.getResponseBodyAsString(); if ((strResponseBody != null) && (getRawData() != null)) { final Vector vecResponseBody; // If we get here, it must have succeeded... // Add one channel of data, the Response // There must be one Calendar and ChannelCount samples in the Vector... vecResponseBody = new Vector(2); vecResponseBody.add(getObservatoryClock().getCalendarDateNow()); vecResponseBody.add(strResponseBody); getRawData().add(vecResponseBody); setRawDataChannelCount(CHANNEL_COUNT); setTemperatureChannel(false); // Create the ResponseMessage // The ResponseValue is just 'Ok' commandType.getResponse().setValue(ResponseMessageStatus.SUCCESS.getResponseValue()); responseMessage = ResponseMessageHelper.constructSuccessfulResponse(this, commandmessage, commandType); } else { // No data are available SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_MESSAGE + ERROR_PARSE_DATA + TERMINATOR, SOURCE, getObservatoryClock()); } } else { throw new NumberFormatException(ResponseMessageStatus.INVALID_PARAMETER.getName()); } } catch (NumberFormatException exception) { // Invalid Parameters SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.FATAL, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_EXCEPTION + ERROR_PARSE_INPUT + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.FATAL, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_EXCEPTION + ERROR_PARSE_INPUT + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (HttpException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_EXCEPTION + ERROR_HTTP + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (IOException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_HTTP + METADATA_EXCEPTION + ERROR_IO + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } finally { method.releaseConnection(); } // If the Command failed, do not change any DAO data containers! // Our valuable data must remain available for export later... responseMessage = ResponseMessageHelper.constructFailedResponseIfNull(this, commandmessage, commandType, responseMessage); return (responseMessage); }
From source file:org.manalang.monkeygrease.Config.java
public synchronized void load() { InputStream is = null;/*from w w w .j a v a2 s . c om*/ GetMethod method = null; if (MonkeygreaseFilter.remoteConfigURL != "" && MonkeygreaseFilter.remoteConfigURL != null) { method = new GetMethod(MonkeygreaseFilter.remoteConfigURL); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = MonkeygreaseFilter.client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { MonkeygreaseFilter.log.severe("Method failed: " + method.getStatusLine()); } is = method.getResponseBodyAsStream(); } catch (HttpException e) { MonkeygreaseFilter.log.severe("Fatal protocol violation: " + e.getMessage()); } catch (IOException e) { MonkeygreaseFilter.log.severe("Fatal transport error: " + e.getMessage()); } } else { is = context.getResourceAsStream(DEFAULT_WEB_CONF_FILE); if (is == null) { System.out.println("unable to find monkeygrease conf file " + DEFAULT_WEB_CONF_FILE); } } DocumentBuilder parser; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // factory.setValidating(true); // factory.setNamespaceAware(true); // factory.setIgnoringComments(true); // factory.setIgnoringElementContentWhitespace(true); try { parser = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { MonkeygreaseFilter.log.severe("Unable to setup XML parser for reading conf " + e.toString()); return; } // parser.setErrorHandler(handler); // parser.setEntityResolver(handler); try { Document doc = parser.parse(is); if (MonkeygreaseFilter.remoteConfigURL != "" && MonkeygreaseFilter.remoteConfigURL != null) method.releaseConnection(); NodeList rulesConf = doc.getElementsByTagName("rule"); rules = new Rules(); for (int i = 0; i < rulesConf.getLength(); i++) { Node ruleNode = rulesConf.item(i); Rule rule = new Rule(ruleNode); if (rule.isEnabled()) rules.add(rule); } // processConfDoc(doc); } catch (SAXParseException e) { MonkeygreaseFilter.log.severe("Parse error on line " + e.getLineNumber() + " " + e.toString()); } catch (Exception e) { MonkeygreaseFilter.log.severe("Exception loading conf " + " " + e.toString()); } }
From source file:org.manalang.monkeygrease.utils.HttpClient.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getParameter("u"); String method = request.getParameter("m"); String params = request.getParameter("p"); InputStream is = null;/* w w w . j a v a2s . c o m*/ if (url == null || url == "") return; if (method != null && method.toLowerCase().equals("post")) { // Create a method instance. PostMethod postMethod = new PostMethod(url); // If params avail, set post data if (params != null && params != "") { String[] paramArray = params.split("&"); NameValuePair[] postData = new NameValuePair[paramArray.length]; for (int i = 0; i < paramArray.length; i++) { String[] nameVal = paramArray[i].split("="); String name = nameVal[0]; String value = nameVal[1]; postData[i] = new NameValuePair(name, value); } postMethod.setRequestBody(postData); } // Provide custom retry handler is necessary postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(2, false)); try { // Execute the method. int statusCode = client.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); } // Read the response body. is = postMethod.getResponseBodyAsStream(); Header[] headers = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; response.setHeader(header.getName(), header.getValue()); } PrintWriter out = response.getWriter(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String line; while ((line = in.readLine()) != null) { out.println(line); } out.close(); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. postMethod.releaseConnection(); } } else { if (params != null) { if (url.indexOf("?") == -1) { url = url + "?" + params; } else { url = url + "&" + params; } } // Create a method instance. GetMethod getMethod = new GetMethod(url); // Provide custom retry handler is necessary getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(2, false)); try { // Execute the method. int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } // Read the response body. is = getMethod.getResponseBodyAsStream(); Header[] headers = getMethod.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; response.setHeader(header.getName(), header.getValue()); } PrintWriter out = response.getWriter(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String line; while ((line = in.readLine()) != null) { out.println(line); } out.close(); // Deal with the response. // Use caution: ensure correct character encoding and is not // binary data } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. getMethod.releaseConnection(); } } }
From source file:org.mitre.mat.engineclient.MATCgiClient.java
protected JsonNode postHTTP(ArrayList<NameValuePair> pArrayList, HashMap<String, String> data) throws MATEngineClientException { // Serialize the document, send it to HTTP, deserialize. if (data != null) { int mapsize = data.size(); Iterator keyValuePairs1 = data.entrySet().iterator(); for (int i = 0; i < mapsize; i++) { Map.Entry entry = (Map.Entry) keyValuePairs1.next(); Object key = entry.getKey(); Object value = entry.getValue(); pArrayList.add(new NameValuePair((String) key, (String) value)); }// w ww. j a v a 2 s. c om } NameValuePair[] pArray = (NameValuePair[]) pArrayList.toArray(new NameValuePair[1]); HttpClientParams params = new HttpClientParams(); params.setContentCharset("utf-8"); HttpClient client = new HttpClient(params); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); method.setRequestBody(pArray); String resString = null; try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new MATEngineClientException("HTTP method failed: " + method.getStatusLine()); } BufferedReader b = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "utf-8")); StringBuffer buf = new StringBuffer(); int READ_LEN = 2048; char[] cbuf = new char[READ_LEN]; while (true) { int chars = b.read(cbuf, 0, READ_LEN); if (chars < 0) { break; } // You may not read READ_LEN chars, but // that doesn't mean you're done. buf.append(cbuf, 0, chars); } resString = new String(buf); } catch (HttpException e) { throw new MATEngineClientException("Fatal protocol violation: " + e.getMessage()); } catch (IOException e) { throw new MATEngineClientException("Fatal transport error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } JsonNode responseObj = null; JsonFactory jsonFact = new JsonFactory(); JsonNode jsonValues; JsonParser parser; try { parser = jsonFact.createJsonParser(new StringReader(resString)); return new ObjectMapper().readTree(parser); } catch (org.codehaus.jackson.JsonParseException ex) { Logger.getLogger(MATCgiClient.class.getName()).log(Level.SEVERE, null, ex); throw new MATEngineClientException("Couldn't digest the following string as JSON: " + resString); } catch (IOException ex) { Logger.getLogger(MATCgiClient.class.getName()).log(Level.SEVERE, null, ex); throw new MATEngineClientException("Couldn't interpret response document: " + ex.getMessage()); } }
From source file:org.mule.transport.http.HttpClientMessageDispatcher.java
@Override protected MuleMessage doSend(MuleEvent event) throws Exception { HttpMethod httpMethod = getMethod(event); httpConnector.setupClientAuthorization(event, httpMethod, client, endpoint); httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new MuleHttpMethodRetryHandler()); boolean releaseConn = false; try {/*from w ww. j a v a 2s . c o m*/ httpMethod = execute(event, httpMethod); DefaultExceptionPayload ep = null; if (returnException(event, httpMethod)) { ep = new DefaultExceptionPayload(new DispatchException(event, getEndpoint(), new HttpResponseException(httpMethod.getStatusText(), httpMethod.getStatusCode()))); } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) { try { return handleRedirect(httpMethod, event); } catch (Exception e) { ep = new DefaultExceptionPayload(new DispatchException(event, getEndpoint(), e)); return getResponseFromMethod(httpMethod, ep); } } releaseConn = httpMethod.getResponseBodyAsStream() == null; return getResponseFromMethod(httpMethod, ep); } catch (Exception e) { releaseConn = true; if (e instanceof DispatchException) { throw (DispatchException) e; } throw new DispatchException(event, getEndpoint(), e); } finally { if (releaseConn) { httpMethod.releaseConnection(); } } }
From source file:org.openadaptor.auxil.connector.http.HttpReadConnector.java
/** * HTTP does not require a permanent connection. * /*from w w w . j a v a 2 s. c om*/ * @see IReadConnector#connect() */ public void connect() { setHostConfiguration(); method = new GetMethod(url); /* Provide custom retry handler */ method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); isDry = false; }
From source file:org.openflamingo.engine.handler.MavenArtifactLoader.java
/** * Artifact ./*from ww w . j ava 2s .c o m*/ * * @param groupId Maven Group Id * @param artifactId Maven Artifact Id * @param version Artifact Version * @param url Maven Repository URL * @param workingDirectory Local Working Directory * @param retry Retry * @return Artifact? Local FileSystem Path */ public static String downloadArtifactFromRepository(String groupId, String artifactId, String version, String url, String workingDirectory, String retry) { boolean isCaching = ConfigurationManagerHelper.getConfigurationManagerHelper().getConfigurationManager() .getBoolean("artifact.caching", true); String filename = workingDirectory + "/" + artifactId + "-" + version + ".jar"; String cachePath = ConfigurationManagerHelper.getConfigurationManagerHelper().getConfigurationManager() .get("artifact.cache.path", "/temp/cache"); String cachedFilename = cachePath + "/" + artifactId + "-" + version + ".jar"; String artifactPath = null; if (isCaching) { artifactPath = cachedFilename; } else { artifactPath = filename; } if (url == null || workingDirectory == null) { String message = ExceptionUtils.getMessage( "Maven Repository? ? . Maven Repository URL '{}' Working Directory '{}'", url, workingDirectory); throw new IllegalArgumentException(message); } if (!new File(artifactPath).exists()) { String artifactUrl = url + getArtifactPath(groupId.trim(), artifactId.trim(), version.trim()); HttpClient httpClient = new HttpClient(); GetMethod method = new GetMethod(artifactUrl); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(Integer.valueOf(retry), false)); int statusCode = 0; try { logger.debug("Artifact [{}]? .", artifactUrl); statusCode = httpClient.executeMethod(method); } catch (IOException e) { throw new WorkflowException(ExceptionUtils .getMessage("Artifact '{}'? .", artifactUrl), e); } if (statusCode != HttpStatus.SC_OK) { throw new WorkflowException(ExceptionUtils.getMessage( "Artifact '{}'? ?? . HTTP ? '{}' ? '{}'", artifactUrl, statusCode, HttpStatusCodeResolver.resolve(statusCode))); } // ?? fully qualified file name? . FileSystemUtils.testCreateDir(new Path(FileSystemUtils.correctPath(cachePath))); try { InputStream is = method.getResponseBodyAsStream(); File outputFile = new File(artifactPath); FileOutputStream fos = new FileOutputStream(outputFile); org.springframework.util.FileCopyUtils.copy(is, fos); logger.info("Artifact [{}]? [{}] ? .", artifactUrl, artifactPath); return artifactPath; } catch (IOException e) { throw new WorkflowException(ExceptionUtils.getMessage( " Artifact '{}' ? .", artifactPath), e); } } else { logger.info("?? Artifact [{}]? .", artifactPath); return artifactPath; } }
From source file:org.openhab.action.telegram.internal.Telegram.java
@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message") static public boolean sendTelegram(@ParamDoc(name = "group") String group, @ParamDoc(name = "message") String message) { if (groupTokens.get(group) == null) { logger.error("Bot '{}' not defined, action skipped", group); return false; }//from w w w . j av a 2 s.c o m String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken()); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.getParams().setSoTimeout(HTTP_TIMEOUT); postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()), new NameValuePair("text", message) }; postMethod.setRequestBody(data); try { int statusCode = client.executeMethod(postMethod); if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) { return true; } if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: {}", postMethod.getStatusLine()); return false; } InputStream tmpResponseStream = postMethod.getResponseBodyAsStream(); Header encodingHeader = postMethod.getResponseHeader("Content-Encoding"); if (encodingHeader != null) { for (HeaderElement ehElem : encodingHeader.getElements()) { if (ehElem.toString().matches(".*gzip.*")) { tmpResponseStream = new GZIPInputStream(tmpResponseStream); logger.debug("GZipped InputStream from {}", url); } else if (ehElem.toString().matches(".*deflate.*")) { tmpResponseStream = new InflaterInputStream(tmpResponseStream); logger.debug("Deflated InputStream from {}", url); } } } String responseBody = IOUtils.toString(tmpResponseStream); if (!responseBody.isEmpty()) { logger.debug(responseBody); } } catch (HttpException e) { logger.error("Fatal protocol violation: {}", e.toString()); } catch (IOException e) { logger.error("Fatal transport error: {}", e.toString()); } finally { postMethod.releaseConnection(); } return true; }