List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream
public abstract InputStream getResponseBodyAsStream() throws IOException;
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.capture.CaptureImage.java
/*********************************************************************************************** * doCaptureImage()./* w ww. j a v a 2 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 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().// w w w .j a v a 2 s. c om * * @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); }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.importers.ImportGOESRealtime.java
/*********************************************************************************************** * doImportGOESRealtime().//from ww w. jav a 2s. c om * * @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 w w. j av a 2 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.methodize.nntprss.feed.Channel.java
/** * Executes HTTP request/* www . jav a 2s .c om*/ * @param client * @param config * @param method */ private static HttpResult executeHttpRequest(HttpClient client, HostConfiguration config, HttpMethod method) throws HttpException, IOException { HttpResult result; int statusCode = -1; try { statusCode = client.executeMethod(config, method); // while (statusCode == -1 && attempt < 3) { // try { // // execute the method. // statusCode = client.executeMethod(config, method); // } catch (HttpRecoverableException e) { // log.( // "A recoverable exception occurred, retrying." // + e.getMessage()); // method.releaseConnection(); // method.recycle(); // try { // Thread.sleep(250); // } catch(InterruptedException ie) { // } // } // } result = new HttpResult(statusCode); Header locationHeader = method.getResponseHeader("location"); if (locationHeader != null) { result.setLocation(locationHeader.getValue()); } if (statusCode == HttpStatus.SC_OK) { Header contentEncoding = method.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equals("gzip")) { InputStream is = method.getResponseBodyAsStream(); is = new GZIPInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = is.read(buf)) > -1) { if (bytesRead > 0) { baos.write(buf, 0, bytesRead); } } baos.flush(); baos.close(); is.close(); result.setResponse(baos.toByteArray()); } else { result.setResponse(method.getResponseBody()); } } else { // Process response InputStream is = method.getResponseBodyAsStream(); if (is != null) { byte[] buf = new byte[1024]; while (is.read(buf) != -1) ; is.close(); } // result.setResponse(method.getResponseBody()); } return result; } finally { method.releaseConnection(); } }
From source file:org.mule.transport.as2.As2MessageDispatcher.java
@Override protected void doDispatch(MuleEvent event) throws Exception { logger.debug("DBG: inside " + getClass() + ".doDispatch()"); HttpMethod httpMethod = getMethod(event); as2Connector.setupClientAuthorizationLocal(event, httpMethod, client, endpoint); try {// w w w . j a v a 2s . c o m execute(event, httpMethod); if (returnException(event, httpMethod)) { logger.error(httpMethod.getResponseBodyAsString()); Exception cause = new Exception(String.format("Http call returned a status of: %1d %1s", httpMethod.getStatusCode(), httpMethod.getStatusText())); throw new DispatchException(event, getEndpoint(), cause); } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) { if (logger.isInfoEnabled()) { logger.info("Received a redirect response code: " + httpMethod.getStatusCode() + " " + httpMethod.getStatusText()); } } else { logger.debug("DBG: response Body is: " + httpMethod.getResponseBodyAsString()); /* Check the incoming synch MDN */ MimeMultipart mdn = MDNBuilder.createMDNFromResponse(httpMethod.getResponseBodyAsStream(), "multipart/report"); if (MDNBuilder.identifyMdnType(mdn) != MdnType.PROCESSED) { throw new Exception("MDN is not of type PROCESSED"); } } } finally { httpMethod.releaseConnection(); } }
From source file:org.mule.transport.as2.As2MuleMessageFactory.java
protected Object extractPayloadFromHttpMethod(HttpMethod httpMethod) throws IOException { InputStream body = httpMethod.getResponseBodyAsStream(); if (body != null) { return new ReleasingInputStream(body, httpMethod); } else {//from w w w . j a va2 s . com return StringUtils.EMPTY; } }
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 w w. j a v a 2 s.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.mule.transport.http.HttpMuleMessageFactoryTestCase.java
private HttpMethod createMockHttpMethod(String method, InputStream body, String uri, Header[] headers) throws Exception { HttpMethod httpMethod = mock(HttpMethod.class); when(httpMethod.getName()).thenReturn(method); when(httpMethod.getStatusLine()).thenReturn(new StatusLine("HTTP/1.1 200 OK")); when(httpMethod.getStatusCode()).thenReturn(HttpConstants.SC_OK); when(httpMethod.getURI()).thenReturn(new URI(uri, false)); when(httpMethod.getResponseHeaders()).thenReturn(headers); when(httpMethod.getResponseBodyAsStream()).thenReturn(body); return httpMethod; }
From source file:org.mule.transport.http.transformers.HttpClientMethodResponseToObject.java
@Override public Object doTransform(Object src, String encoding) throws TransformerException { Object msg;// w w w. j a v a2 s. c om HttpMethod httpMethod = (HttpMethod) src; InputStream is; try { is = httpMethod.getResponseBodyAsStream(); } catch (IOException e) { throw new TransformerException(this, e); } if (is == null) { msg = NullPayload.getInstance(); } else { msg = new ReleasingInputStream(is, httpMethod); } // Standard headers Map headerProps = new HashMap(); Header[] headers = httpMethod.getResponseHeaders(); String name; for (int i = 0; i < headers.length; i++) { name = headers[i].getName(); if (name.startsWith(HttpConstants.X_PROPERTY_PREFIX)) { name = name.substring(2); } headerProps.put(name, headers[i].getValue()); } // Set Mule Properties return new DefaultMuleMessage(msg, headerProps, muleContext); }