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.kalypso.commons.net.ProxyUtilities.java
/** * Creates a configured http client. The configuration includes setting of proxy settings. * <p>//from www . jav a 2 s . c om * IMPORTANT: To use proxy-authentication, you must use the setDoAuthentication Method of the HttpMethod you are going * to use. * </p> * <strong>Example:</strong> * * <pre> * HttpMethod method = new GetMethod( m_url.toString() ); * method.setDoAuthentication( true ); * </pre> * * @param timeout * The socket timeout in milliseconds. * @param retries * The number of retries, the http client is going to make. Set to a value lower then 0 to leave it at the * default value. * @return The configured http client. If no proxy is set, it will be a normal http client with the given timeout and * retries. * @deprecated This method should not be used any more, because its functionality is covered completely by the method * {@link #getConfiguredHttpClient(int, URL, int)}. If you have no appropriate URL, leave it null. */ @Deprecated public static HttpClient getConfiguredHttpClient(final int timeout, final int retries) { /* Create the new http client. */ final HttpClient client = new HttpClient(); /* Client should always authenticate before making a connection. */ client.getParams().setAuthenticationPreemptive(true); client.getParams().setSoTimeout(timeout); /* If a retry count is given, set the number of retries. */ if (retries >= 0) client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retries, true)); /* Get the proxy object. */ final Proxy proxy = getProxy(); /* If the proxy should be used, configure the client with it. */ if (proxy.useProxy()) { /* Get the proxy data. */ final String proxyHost = proxy.getProxyHost(); final int proxyPort = proxy.getProxyPort(); /* Set the proxy information. */ client.getHostConfiguration().setProxy(proxyHost, proxyPort); /* Get the credentials. */ final String user = proxy.getUser(); final String password = proxy.getPassword(); /* Set them, if the credentials are complete. */ if (user != null && password != null) { final Credentials credentials = new UsernamePasswordCredentials(user, password); client.getState().setProxyCredentials(AuthScope.ANY, credentials); } } return client; }
From source file:org.kalypso.commons.net.ProxyUtilities.java
/** * Creates a configured http client. The configuration includes setting of proxy settings. * <p>// ww w . j a v a2 s.c o m * IMPORTANT: To use proxy-authentication, you must use the setDoAuthentication Method of the HttpMethod you are going * to use. * </p> * <strong>Example:</strong> * * <pre> * HttpMethod method = new GetMethod( m_url.toString() ); * method.setDoAuthentication( true ); * </pre> * * @param timeout * The socket timeout in milliseconds. * @param url * The url, for which the client is needed. Could be null. * @param retries * The number of retries, the http client is going to make. Set to a value lower then 0 to leave it at the * default value. * @return The configured http client. If no proxy is set or the host, included in the url is a non proxy host, it * will be a normal http client with the given timeout and retries. If url is null, the check for non proxy * hosts is omitted. */ public static HttpClient getConfiguredHttpClient(final int timeout, final URL url, final int retries) { /* Create the new http client. */ final HttpClient client = new HttpClient(); /* Client should always authenticate before making a connection. */ client.getParams().setAuthenticationPreemptive(true); client.getParams().setSoTimeout(timeout); /* If a retry count is given, set the number of retries. */ if (retries >= 0) client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retries, true)); /* Get the proxy object. */ final Proxy proxy = getProxy(); /* If the proxy should be used, configure the client with it. */ if (proxy.useProxy() && !isNonProxyHost(url)) { /* Get the proxy data. */ final String proxyHost = proxy.getProxyHost(); final int proxyPort = proxy.getProxyPort(); /* Set the proxy information. */ client.getHostConfiguration().setProxy(proxyHost, proxyPort); /* Get the credentials. */ final String user = proxy.getUser(); final String password = proxy.getPassword(); /* Set them, if the credentials are complete. */ if (user != null && password != null) { final Credentials credentials = new UsernamePasswordCredentials(user, password); client.getState().setProxyCredentials(AuthScope.ANY, credentials); } } return client; }
From source file:org.kei.android.phone.cellhistory.towers.request.OpenCellIdRequestEntity.java
@Override public int decode(final String url, final HttpConnection connection, final int timeout) throws Exception { int ret = OK; final GetMethod getMethod = new GetMethod(url); getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); // socket timeout (connection timeout already set in HttpClient) getMethod.getParams().setSoTimeout(timeout); final int resCode = getMethod.execute(new HttpState(), connection); final InputStream response = getMethod.getResponseBodyAsStream(); final DataInputStream dis = new DataInputStream(response); if (resCode == HttpStatus.SC_OK) { final int av = dis.available(); final byte[] json = new byte[av]; dis.readFully(json);//from w ww . j av a 2 s .c o m final String sjson = new String(json); final String ljson = sjson.toLowerCase(Locale.US); if (ljson.indexOf("err") == -1) { final JSONObject object = new JSONObject(sjson); String lat, lng; lat = object.getString("lat"); lng = object.getString("lon"); ti.setCellLatitude(Double.parseDouble(lat)); ti.setCellLongitude(Double.parseDouble(lng)); } else if (ljson.indexOf("not found") != -1) ret = NOT_FOUND; else ret = EXCEPTION; } else if (resCode == HttpStatus.SC_NOT_FOUND) ret = NOT_FOUND; else if (resCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) ret = BAD_REQUEST; else ret = EXCEPTION; getMethod.releaseConnection(); return ret; }
From source file:org.krakenapps.pkg.HttpWagon.java
public static InputStream openDownloadStream(URL url, boolean useAuth, String username, String password) throws IOException { Logger logger = LoggerFactory.getLogger(HttpWagon.class.getName()); logger.trace("http wagon: downloading {}", url); HttpClient client = new HttpClient(); if (useAuth) { client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);/*from w ww. j a v a 2 s . c o m*/ } HttpMethod method = new GetMethod(url.toString()); int socketTimeout = getSocketTimeout(); int connectionTimeout = getConnectTimeout(); client.getParams().setParameter("http.socket.timeout", socketTimeout); client.getParams().setParameter("http.connection.timeout", connectionTimeout); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, null); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new IOException("method failed: " + method.getStatusLine()); } return method.getResponseBodyAsStream(); }
From source file:org.kuali.mobility.athletics.service.AthleticsServiceImpl.java
private InputStream getInputStreamFromGetMethod(GetMethod get) throws Exception { get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(socketTimeout)); httpClient.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(connectionManagerTimeout)); httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, new Integer(connectionTimeout)); int status = httpClient.executeMethod(get); if (status == HttpStatus.SC_OK) { return get.getResponseBodyAsStream(); }//from ww w.j a v a2 s . c o m return null; }
From source file:org.kuali.mobility.maps.controllers.MapsController.java
private InputStream getInputStreamFromGetMethod(GetMethod get, int timeout) throws Exception { get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(timeout)); httpClient.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(timeout)); httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, new Integer(timeout)); int status = httpClient.executeMethod(get); if (status == HttpStatus.OK.value()) { return get.getResponseBodyAsStream(); }/*from ww w. j av a2 s .c o m*/ return null; }
From source file:org.kuali.rice.kew.config.ThinClientResourceLoader.java
protected void configureDefaultHttpClientParams(HttpParams params) { params.setParameter(HttpClientParams.CONNECTION_MANAGER_CLASS, MultiThreadedHttpConnectionManager.class); params.setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109); params.setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(DEFAULT_CONNECTION_MANAGER_TIMEOUT)); Map<HostConfiguration, Integer> maxHostConnectionsMap = new HashMap<HostConfiguration, Integer>(); maxHostConnectionsMap.put(HostConfiguration.ANY_HOST_CONFIGURATION, new Integer(DEFAULT_MAX_CONNECTIONS)); params.setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, maxHostConnectionsMap); params.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, new Integer(DEFAULT_MAX_CONNECTIONS)); params.setIntParameter(HttpConnectionManagerParams.CONNECTION_TIMEOUT, new Integer(DEFAULT_CONNECTION_TIMEOUT)); boolean retrySocketException = new Boolean( ConfigContext.getCurrentContextConfig().getProperty(RETRY_SOCKET_EXCEPTION_PROPERTY)); if (retrySocketException) { LOG.info("Installing custom HTTP retry handler to retry requests in face of SocketExceptions"); params.setParameter(HttpMethodParams.RETRY_HANDLER, new CustomHttpMethodRetryHandler()); }/*w w w . j a va2 s . c o m*/ }
From source file:org.kuali.rice.ksb.messaging.serviceconnectors.HttpInvokerConnector.java
protected void configureDefaultHttpClientParams(HttpParams params) { params.setParameter(HttpClientParams.CONNECTION_MANAGER_CLASS, MultiThreadedHttpConnectionManager.class); params.setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109); params.setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, 10000); Map<HostConfiguration, Integer> maxHostConnectionsMap = new HashMap<HostConfiguration, Integer>(); maxHostConnectionsMap.put(HostConfiguration.ANY_HOST_CONFIGURATION, new Integer(20)); params.setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, maxHostConnectionsMap); params.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 20); params.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000); params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 2 * 60 * 1000); boolean retrySocketException = new Boolean( ConfigContext.getCurrentContextConfig().getProperty(RETRY_SOCKET_EXCEPTION_PROPERTY)); if (retrySocketException) { LOG.info("Installing custom HTTP retry handler to retry requests in face of SocketExceptions"); params.setParameter(HttpMethodParams.RETRY_HANDLER, new CustomHttpMethodRetryHandler()); }/*from w w w. java 2 s. co m*/ }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.capture.CaptureImage.java
/*********************************************************************************************** * doCaptureImage()./*from w w w . j av a 2s. com*/ * 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 doCaptureImage(final ObservatoryInstrumentDAOInterface dao, final CommandMessageInterface commandmessage) { final String SOURCE = "CaptureImage.doCaptureImage()"; final CommandType cmdCapture; String strResponseValue; final ResponseMessageInterface responseMessage; // Initialise dao.clearEventLogFragment(); // Get the latest Resources dao.readResources(); // Don't affect the CommandType of the incoming Command cmdCapture = (CommandType) commandmessage.getCommandType().copy(); // Ensure we are dealing with an Ethernet-based instrument if ((commandmessage.getInstrument() != null) && (commandmessage.getInstrument().getController() != null) && (commandmessage.getInstrument().getController().getIPAddress() != null) && (dao.getRemoteDataConnection() != null)) { final HttpClient client; final HttpMethod method; final String strURL; // Set up the HttpClient client = new HttpClient(); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); // Beware filename part (e.g. IMAGE.JPG) *must* be uppercase! // Assume that we are dealing with a valid Ethernet Controller strURL = ControlPanelInterface.PREFIX_HTTP + IPVersion.stripTrailingPaddingFromIPAddressAndPort( commandmessage.getInstrument().getController().getIPAddress()); // The DAO Hostname contains the Value of Property KEY_DAO_IMAGE_FILENAME method = new GetMethod(strURL + "/" + dao.getRemoteDataConnection().getHostname()); // 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"); SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.INFO, METADATA_TARGET_IMAGE + METADATA_ACTION_CAPTURE + METADATA_ADDRESS + strURL + "/" + dao.getRemoteDataConnection().getHostname() + TERMINATOR, SOURCE, dao.getObservatoryClock()); // Establish the identity of this Instrument using Metadata // from the Framework, Observatory and Observer dao.establishDAOIdentityForCapture(DAOCommandHelper.getCommandCategory(cmdCapture), 0, false, null, null); 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 + 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... // Pass the Image to the DAO, and then to the Instrument and InstrumentPanel dao.setImageData(image); dao.setUnsavedData(true); inputStream.close(); strResponseValue = ResponseMessageStatus.SUCCESS.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.SUCCESS); } else { // No data are available SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_PARSE_DATA, SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.PREMATURE_TERMINATION.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.PREMATURE_TERMINATION); } } catch (NumberFormatException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (HttpException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE); } catch (IOException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_IO + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE); } finally { // It is important to always release the connection, // regardless of whether the server returned an error or not method.releaseConnection(); } } else { // Incorrectly configured XML strResponseValue = ResponseMessageStatus.INVALID_XML.getResponseValue(); dao.getResponseMessageStatusList().add( DAOCommandHelper.logInvalidXML(dao, SOURCE, METADATA_TARGET_IMAGE, METADATA_ACTION_CAPTURE)); } responseMessage = ResponseMessageHelper.createResponseMessage(dao, commandmessage, cmdCapture, null, null, strResponseValue); return (responseMessage); }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.capture.CaptureImageRealtime.java
/*********************************************************************************************** * captureImageRealtime()./*from w w w . j a va2s . c o m*/ * * @param dao * @param commandmessage * * @return ResponseMessageInterface */ public static ResponseMessageInterface doCaptureImageRealtime(final ObservatoryInstrumentDAOInterface dao, final CommandMessageInterface commandmessage) { final String SOURCE = "CaptureImageRealtime.captureImageRealtime()"; final int PARAMETER_COUNT = 4; final int INDEX_PATHNAME = 0; final int INDEX_INTERVAL = 1; final int INDEX_PERIOD = 2; final int INDEX_UPDATE = 3; final CommandType cmdCapture; 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 cmdCapture = (CommandType) commandmessage.getCommandType().copy(); // We expect four parameters: the pathname, the capture interval, the capture period and the update flag listParameters = cmdCapture.getParameterList(); // Ensure we are dealing with an Ethernet-based instrument if ((dao.getHostInstrument() != null) && (dao.getHostInstrument().getInstrument() != null) && (dao.getHostInstrument().getInstrument().getController() != null) && (dao.getHostInstrument().getInstrument().getController().getIPAddress() != null) && (listParameters != null) && (listParameters.size() == PARAMETER_COUNT) && (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())) && (dao.getRemoteDataConnection() != null)) { try { final String strPathname; final String strCaptureInterval; final String strCapturePeriod; final boolean boolRealtimeUpdate; final int intCaptureIntervalSec; int intCapturePeriodSec; final HttpClient client; final HttpMethod method; final String strURL; 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 ((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)); // Beware filename part (e.g. IMAGE.JPG) *must* be uppercase! // Assume that we are dealing with a valid Ethernet Controller strURL = ControlPanelInterface.PREFIX_HTTP + IPVersion.stripTrailingPaddingFromIPAddressAndPort( dao.getHostInstrument().getInstrument().getController().getIPAddress()); // The DAO HostID contains the Value of Property KEY_DAO_IMAGE_FILENAME method = new GetMethod(strURL + "/" + dao.getRemoteDataConnection().getHostname()); // 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_CAPTURE + METADATA_PATHNAME + strPathname + TERMINATOR_SPACE + METADATA_INTERVAL + intCaptureIntervalSec + TERMINATOR_SPACE + METADATA_PERIOD + strPeriod + TERMINATOR_SPACE + METADATA_ADDRESS + strURL + "/" + dao.getRemoteDataConnection().getHostname() + 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; listStatusInCaptureLoop = ResponseMessageStatus.createResponseMessageStatusList(); boolSuccess = true; // Establish the identity of this Instrument using Metadata // from the Framework, Observatory and Observer dao.establishDAOIdentityForCapture(DAOCommandHelper.getCommandCategory(cmdCapture), 0, false, null, null); 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 + "/CapturedImage", 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 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, cmdCapture, null, null, strResponseValue); return (responseMessage); }