Example usage for org.apache.commons.httpclient HttpMethod releaseConnection

List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod releaseConnection.

Prototype

public abstract void releaseConnection();

Source Link

Usage

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.capture.CaptureImage.java

/***********************************************************************************************
 * doCaptureImage()./*  w w w  .  j a  v a  2 s .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().//  www.j av  a2  s  . 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);
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.importers.ImportGOESRealtime.java

/***********************************************************************************************
 * doImportGOESRealtime().//  w  w  w  . j  ava 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.  j  a  v  a  2  s  . c o 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 a2 s .c om*/
 * 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.melati.admin.Admin.java

private String proxy(Melati melati, ServletTemplateContext context) {
    if (melati.getSession().getAttribute("generatedByMelatiClass") == null)
        throw new AnticipatedException("Only available from within an Admin generated page");
    String method = melati.getRequest().getMethod();
    String url = melati.getRequest().getQueryString();
    HttpServletResponse response = melati.getResponse();
    HttpMethod httpMethod = null;
    try {//from  w  w w. j  av  a  2  s.c o m

        HttpClient client = new HttpClient();
        if (method.equals("GET"))
            httpMethod = new GetMethod(url);
        else if (method.equals("POST"))
            httpMethod = new PostMethod(url);
        else if (method.equals("PUT"))
            httpMethod = new PutMethod(url);
        else if (method.equals("HEAD"))
            httpMethod = new HeadMethod(url);
        else
            throw new RuntimeException("Unexpected method '" + method + "'");
        try {
            httpMethod.setFollowRedirects(true);
            client.executeMethod(httpMethod);
            for (Header h : httpMethod.getResponseHeaders()) {
                response.setHeader(h.getName(), h.getValue());
            }
            response.setStatus(httpMethod.getStatusCode());
            response.setHeader("Cache-Control", "no-cache");
            byte[] outputBytes = httpMethod.getResponseBody();
            if (outputBytes != null) {
                response.setBufferSize(outputBytes.length);
                response.getWriter().write(new String(outputBytes));
                response.getWriter().flush();
            }
        } catch (Exception e) {
            throw new MelatiIOException(e);
        }
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
    }
    return null;
}

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Executes HTTP request//  www  .j  a  v  a  2s  .  co  m
 * @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.mozilla.zest.impl.ZestBasicRunner.java

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;
    URI uri = new URI(req.getUrl().toString(), false);

    switch (req.getMethod()) {
    case "GET":
        method = new GetMethod(uri.toString());
        // Can only redirect on GETs
        method.setFollowRedirects(req.isFollowRedirects());
        break;/*from   w  w w . j a v  a2 s  .  co m*/
    case "POST":
        method = new PostMethod(uri.toString());
        break;
    case "OPTIONS":
        method = new OptionsMethod(uri.toString());
        break;
    case "HEAD":
        method = new HeadMethod(uri.toString());
        break;
    case "PUT":
        method = new PutMethod(uri.toString());
        break;
    case "DELETE":
        method = new DeleteMethod(uri.toString());
        break;
    case "TRACE":
        method = new TraceMethod(uri.toString());
        break;
    default:
        throw new IllegalArgumentException("Method not supported: " + req.getMethod());
    }

    setHeaders(method, req.getHeaders());

    for (Cookie cookie : req.getCookies()) {
        // Replace any Zest variables in the value
        cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false));
        httpclient.getState().addCookie(cookie);
    }

    if (req.getMethod().equals("POST")) {
        // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after
        Header contentType = method.getRequestHeader("Content-Type");
        RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null);

        ((PostMethod) method).setRequestEntity(requestEntity);

        if (contentType != null) {
            method.setRequestHeader(contentType);
        }
    }

    int code = 0;
    String responseHeader = null;
    String responseBody = null;
    Date start = new Date();
    try {
        this.debug(req.getMethod() + " : " + req.getUrl());
        code = httpclient.executeMethod(method);

        responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders());
        responseBody = method.getResponseBodyAsString();

    } finally {
        method.releaseConnection();
    }
    // Update the headers with the ones actually sent
    req.setHeaders(arrayToStr(method.getRequestHeaders()));

    if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) {
        // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests
        method = new GetMethod(method.getResponseHeader("Location").getValue());
        // Just in case there are multiple redirects
        method.setFollowRedirects(req.isFollowRedirects());

        try {
            this.debug(req.getMethod() + " : " + req.getUrl());
            code = httpclient.executeMethod(method);

            responseHeader = method.getStatusLine().toString() + "\r\n"
                    + arrayToStr(method.getResponseHeaders());
            responseBody = method.getResponseBodyAsString();

        } finally {
            method.releaseConnection();
        }
    }

    return new ZestResponse(req.getUrl(), responseHeader, responseBody, code,
            new Date().getTime() - start.getTime());
}

From source file:org.mskcc.pathdb.schemas.externalDb.ExternalDbLinkTester.java

/**
 * Given an External Database Record object, this class connects
 * to the specificed url pattern with a sample id, and returns the
 * HTTP status code.  This provides a simple sanity check to verify that
 * the live links to an external database are still functioning correctly.
 * Verifying that the links actually return the "correct" data is much more
 * difficult, and beyond the scope of what this method can do.
 *
 * @param dbRecord ExternalDatabaseRecord Object.
 * @return HTTP Status Code.//from   w  ww.  j  a  va 2s .  com
 * @throws HttpException HTTP Error.
 * @throws IOException   I/O Error.
 */
public static int checkSampleLink(ExternalDatabaseRecord dbRecord) throws HttpException, IOException {
    if (dbRecord.getUrlPattern() == null) {
        throw new IllegalArgumentException("External Database Url " + "attribute is null");
    }
    if (dbRecord.getSampleId() == null) {
        throw new IllegalArgumentException("External Database " + "sample ID attribute is null");
    }
    HttpClient client = new HttpClient();
    client.setConnectionTimeout(5000);
    String url = dbRecord.getUrlWithId(dbRecord.getSampleId());
    HttpMethod method = new GetMethod(url);
    method.setFollowRedirects(true);
    int statusCode = client.executeMethod(method);
    method.releaseConnection();
    return statusCode;
}

From source file:org.mule.ibeans.module.http.HttpClientMessageRequester2.java

/**
 * Make a specific request to the underlying transport
 *
 * @param timeout the maximum time the operation should block before returning.
 *                The call should return immediately if there is data available. If
 *                no data becomes available before the timeout elapses, null will be
 *                returned//from w  ww.  j a va2  s .  c o  m
 * @return the result of the request wrapped in a MuleMessage object. Null will be
 *         returned if no data was avaialable
 * @throws Exception if the call to the underlying protocal cuases an exception
 */
protected MuleMessage doRequest(long timeout) throws Exception {
    HttpMethod httpMethod = new GetMethod(endpoint.getEndpointURI().getAddress());

    if (endpoint.getProperties().containsKey(HttpConstants.HEADER_AUTHORIZATION)) {
        httpMethod.setDoAuthentication(true);
        client.getParams().setAuthenticationPreemptive(true);
        httpMethod.setRequestHeader(HttpConstants.HEADER_AUTHORIZATION,
                (String) endpoint.getProperty(HttpConstants.HEADER_AUTHORIZATION));
    }

    boolean releaseConn = false;
    try {
        HttpClient client = new HttpClient();

        if (etag != null && checkEtag) {
            httpMethod.setRequestHeader(HttpConstants.HEADER_IF_NONE_MATCH, etag);
        }
        client.executeMethod(httpMethod);

        if (httpMethod.getStatusCode() < 400) {
            MuleMessage message = new HttpMuleMessageFactory(connector.getMuleContext()).create(httpMethod,
                    null /* encoding */);
            etag = message.getInboundProperty(HttpConstants.HEADER_ETAG, null);

            if (httpMethod.getStatusCode() == HttpStatus.SC_OK
                    || (httpMethod.getStatusCode() != HttpStatus.SC_NOT_MODIFIED || !checkEtag)) {
                if (StringUtils.EMPTY.equals(message.getPayload())) {
                    releaseConn = true;
                }
                return message;
            } else {
                //Not modified, we should really cache the whole message and return it
                return new DefaultMuleMessage(NullPayload.getInstance(), getConnector().getMuleContext());
            }
        } else {
            releaseConn = true;
            throw new ReceiveException(
                    HttpMessages.requestFailedWithStatus(httpMethod.getStatusLine().toString()), endpoint,
                    timeout);
        }

    } catch (ReceiveException e) {
        releaseConn = true;
        throw e;
    } catch (Exception e) {
        releaseConn = true;
        throw new ReceiveException(endpoint, timeout, e);
    } finally {
        if (releaseConn) {
            httpMethod.releaseConnection();
        }
    }
}