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

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

Introduction

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

Prototype

public abstract StatusLine getStatusLine();

Source Link

Usage

From source file:org.jaggeryjs.hostobjects.ws.WSRequestHostObject.java

private static Scriptable setOptionsOpenWSDL(WSRequestHostObject wsRequest, Object[] args)
        throws ScriptException {
    Scriptable object = null;/*from w w  w .  j  a  va 2s  . com*/
    String wsdlURL;
    QName serviceQName = null;
    String endpointName = null;
    switch (args.length) {
    case 0:
        throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
    case 1:
        throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
    case 2:
        if (args[0] instanceof String) {
            wsdlURL = (String) args[0];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[1] instanceof Boolean) {
            wsRequest.async = (Boolean) args[1];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        break;
    case 3:
        if (args[0] instanceof String) {
            wsdlURL = (String) args[0];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[1] instanceof Boolean) {
            wsRequest.async = (Boolean) args[1];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[2] instanceof Scriptable) {
            object = (Scriptable) args[2];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        break;
    case 5:
        if (args[0] instanceof String) {
            wsdlURL = (String) args[0];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[1] instanceof Boolean) {
            wsRequest.async = (Boolean) args[1];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[2] instanceof Scriptable) {
            object = (Scriptable) args[2];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[3] instanceof QName) {
            QName qName = (QName) args[3];
            String uri = qName.getNamespaceURI();
            String localName = qName.getLocalPart();
            serviceQName = new QName(uri, localName);
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[4] instanceof String) {
            endpointName = (String) args[4];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }

        wsRequest.wsdlMode = true;
        break;
    default:
        throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
    }

    HttpMethod method = new GetMethod(wsdlURL);
    try {
        int statusCode = HostObjectUtil.getURL(wsdlURL, null, null);
        if (statusCode != HttpStatus.SC_OK) {
            throw new ScriptException("An error occured while getting the resource at " + wsdlURL + ". Reason :"
                    + method.getStatusLine());
        }
        Document doc = XMLUtils.newDocument(method.getResponseBodyAsStream());
        WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
        reader.setFeature("javax.wsdl.importDocuments", true);
        Definition definition = reader.readWSDL(getBaseURI(wsdlURL), doc);
        wsRequest.targetNamespace = definition.getTargetNamespace();
        Service service;
        Port returnPort;
        if (serviceQName == null) {
            Map services = definition.getServices();
            service = null;
            for (Object o : services.values()) {
                service = (Service) o;
                if (service.getPorts().size() > 0) {
                    //i.e we have found a service with ports
                    break;
                }
            }
            if (service == null) {
                throw Context
                        .reportRuntimeError("The WSDL given does not contain any services " + "that has ports");
            }
            Map ports = service.getPorts();
            Port port;
            returnPort = null;
            for (Iterator portsIterator = ports.values().iterator(); (portsIterator.hasNext()
                    && returnPort == null);) {
                port = (Port) portsIterator.next();
                List extensibilityElements = port.getExtensibilityElements();
                for (Object extElement : extensibilityElements) {
                    if (extElement instanceof SOAPAddress) {
                        // SOAP 1.1 address found - keep this and loop until http address is found
                        returnPort = port;
                        String location = ((SOAPAddress) extElement).getLocationURI().trim();
                        if ((location != null) && location.startsWith("http:")) {
                            // i.e we have found an http port so return from here
                            break;
                        }
                    }
                }
            }

            if (returnPort == null) {
                for (Object o : ports.values()) {
                    port = (Port) o;
                    List extensibilityElements = port.getExtensibilityElements();
                    for (Object extElement : extensibilityElements) {
                        if (extElement instanceof SOAP12Address) {
                            // SOAP 1.2 address found - keep this and loop until http address is found
                            returnPort = port;
                            String location = ((SOAP12Address) extElement).getLocationURI().trim();
                            if ((location != null) && location.startsWith("http:")) {
                                // i.e we have found an http port so return from here
                                break;
                            }
                        }
                    }
                }

                if (returnPort == null) {
                    for (Object o : ports.values()) {
                        port = (Port) o;
                        List extensibilityElements = port.getExtensibilityElements();
                        for (Object extElement : extensibilityElements) {
                            if (extElement instanceof HTTPAddress) {
                                // HTTP address found - keep this and loop until http address is found
                                returnPort = port;
                                String location = ((HTTPAddress) extElement).getLocationURI().trim();
                                if ((location != null) && location.startsWith("http:")) {
                                    // i.e we have found an http port so return from here
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (returnPort == null) {
                throw Context.reportRuntimeError(
                        "The WSDL given does not contain any ports " + "that use the http transport");
            } else {
                serviceQName = service.getQName();
                endpointName = returnPort.getName();

            }
        }
        wsRequest.sender = new ServiceClient(null, definition, serviceQName, endpointName);
    } catch (MalformedURLException e) {
        String message = "Malformed URL : " + wsdlURL;
        log.error(message, e);
        throw new ScriptException(message, e);
    } catch (Exception e) {
        String message = "Error occurred while reading the WSDL content from the URL : " + wsdlURL;
        log.error(message, e);
        throw new ScriptException(message, e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return object;
}

From source file:org.jboss.test.faces.jetty.JettyServerTestCase.java

@Test
public void testHelloPage() throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(
            new URL("http", "localhost", PORT, "/hello-jetty.jsf?name=JettyServer").toExternalForm());

    try {//from  w  w w  .j  a v  a 2s.  c  o m
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            fail("Method failed: " + method.getStatusLine());
        }

        String responseBodyAsString = method.getResponseBodyAsString();
        assertTrue(responseBodyAsString.contains("Hello, JettyServer!"));

    } finally {
        method.releaseConnection();
    }
}

From source file:org.kalypso.util.net.URLGetter.java

/**
 * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor)
 *//*w  ww. ja  va  2  s .  c  o  m*/
@Override
public IStatus execute(final IProgressMonitor monitor) {
    final String urlAsString = m_url.toString();
    final HttpMethod method = new GetMethod(urlAsString);
    // do not forget the next line!
    method.setDoAuthentication(true);

    final Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                final HttpClient httpClient = getHttpClient();
                httpClient.executeMethod(method);
                setResult(method.getResponseBodyAsStream());
            } catch (final IOException e) {
                final IStatus status;

                String responseBodyAsString = Messages.getString("org.kalypso.util.net.URLGetter.1"); //$NON-NLS-1$
                try {
                    responseBodyAsString = method.getResponseBodyAsString();
                } catch (final IOException e1) {
                    final IStatus status2 = StatusUtilities.statusFromThrowable(e1);
                    KalypsoGisPlugin.getDefault().getLog().log(status2);
                }

                String message = Messages.getString("org.kalypso.util.net.URLGetter.2") + urlAsString; //$NON-NLS-1$
                if (responseBodyAsString != null && !responseBodyAsString.isEmpty())
                    message += "\n" + responseBodyAsString; //$NON-NLS-1$

                status = new Status(IStatus.ERROR, KalypsoGisPlugin.getId(), 0, message, e);
                setStatus(status);
            }
        }
    };

    monitor.beginTask(urlAsString, IProgressMonitor.UNKNOWN);
    monitor.subTask(Messages.getString("org.kalypso.util.net.URLGetter.4")); //$NON-NLS-1$
    thread.start();
    while (thread.isAlive()) {
        try {
            Thread.sleep(100);
        } catch (final InterruptedException e1) {
            // should never happen, ignore
            e1.printStackTrace();
        }

        final String statusText;
        final StatusLine statusLine = method.getStatusLine();
        if (statusLine == null)
            statusText = Messages.getString("org.kalypso.util.net.URLGetter.5"); //$NON-NLS-1$
        else
            statusText = method.getStatusText();

        monitor.subTask(statusText);
        monitor.worked(1);
        if (monitor.isCanceled()) {
            // TODO: this does not stop the thread!
            thread.interrupt();

            monitor.done();
            return Status.CANCEL_STATUS;
        }
    }

    monitor.done();
    return m_status;
}

From source file:org.krakenapps.pkg.HttpWagon.java

public static InputStream openDownloadStream(URL url, boolean useAuth, String username, String password)
        throws IOException {
    Logger logger = LoggerFactory.getLogger(HttpWagon.class.getName());
    logger.trace("http wagon: downloading {}", url);

    HttpClient client = new HttpClient();
    if (useAuth) {
        client.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
                defaultcreds);//from  www  .j  a  v  a  2  s . c o m
    }

    HttpMethod method = new GetMethod(url.toString());

    int socketTimeout = getSocketTimeout();
    int connectionTimeout = getConnectTimeout();

    client.getParams().setParameter("http.socket.timeout", socketTimeout);
    client.getParams().setParameter("http.connection.timeout", connectionTimeout);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, null);

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("method failed: " + method.getStatusLine());
    }

    return method.getResponseBodyAsStream();
}

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

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