List of usage examples for org.apache.commons.httpclient HttpMethod setRequestHeader
public abstract void setRequestHeader(String paramString1, String paramString2);
From source file:org.jahia.test.services.logout.LogoutTest.java
protected String logout(String url) throws Exception { String returnUrl = null;/*from w ww.ja v a2 s .c om*/ String baseurl = getBaseServerURL() + Jahia.getContextPath(); HttpMethod method = new GetMethod(baseurl + "/cms/logout"); try { method.setRequestHeader("Referer", baseurl + url); getHttpClient().executeMethod(method); returnUrl = StringUtils.isEmpty(Jahia.getContextPath()) || !(method.getPath().startsWith(Jahia.getContextPath())) ? method.getPath() : StringUtils.substringAfter(method.getPath(), Jahia.getContextPath()); } finally { method.releaseConnection(); } return returnUrl; }
From source file:org.jboss.web.loadbalancer.Loadbalancer.java
protected HttpClient prepareServerRequest(HttpServletRequest request, HttpServletResponse response, HttpMethod method) { // clear state HttpClient client = new HttpClient(connectionManager); client.setStrictMode(false);//from ww w. jav a 2 s . c o m client.setTimeout(connectionTimeout); method.setFollowRedirects(false); method.setDoAuthentication(false); client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); Enumeration reqHeaders = request.getHeaderNames(); while (reqHeaders.hasMoreElements()) { String headerName = (String) reqHeaders.nextElement(); String headerValue = request.getHeader(headerName); if (!ignorableHeader.contains(headerName.toLowerCase())) { method.setRequestHeader(headerName, headerValue); } } //Cookies Cookie[] cookies = request.getCookies(); HttpState state = client.getState(); for (int i = 0; cookies != null && i < cookies.length; ++i) { Cookie cookie = cookies[i]; org.apache.commons.httpclient.Cookie reqCookie = new org.apache.commons.httpclient.Cookie(); reqCookie.setName(cookie.getName()); reqCookie.setValue(cookie.getValue()); if (cookie.getPath() != null) { reqCookie.setPath(cookie.getPath()); } else { reqCookie.setPath("/"); } reqCookie.setSecure(cookie.getSecure()); reqCookie.setDomain(method.getHostConfiguration().getHost()); state.addCookie(reqCookie); } return client; }
From source file:org.jivesoftware.openfire.clearspace.ClearspaceManager.java
/** * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the * form /userService/users.//from w w w. j a v a2 s . co m * If CS throws an exception it handled and transalated to a Openfire exception if possible. * This is done using the check fault method that tries to throw the best maching exception. * * @param type Must be GET or DELETE * @param urlSuffix The url suffix of the rest request * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only * @return The response as a xml doc. * @throws ConnectionException Thrown if there are issues perfoming the request. * @throws Exception Thrown if the response from Clearspace contains an exception. */ public Element executeRequest(HttpType type, String urlSuffix, String xmlParams) throws ConnectionException, Exception { if (Log.isDebugEnabled()) { Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams); } String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix; String secret = getSharedSecret(); HttpClient client = new HttpClient(); HttpMethod method; // Configures the authentication client.getParams().setAuthenticationPreemptive(true); Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret); AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM); client.getState().setCredentials(scope, credentials); // Creates the method switch (type) { case GET: method = new GetMethod(wsUrl); break; case POST: PostMethod pm = new PostMethod(wsUrl); StringRequestEntity requestEntity = new StringRequestEntity(xmlParams); pm.setRequestEntity(requestEntity); method = pm; break; case PUT: PutMethod pm1 = new PutMethod(wsUrl); StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams); pm1.setRequestEntity(requestEntity1); method = pm1; break; case DELETE: method = new DeleteMethod(wsUrl); break; default: throw new IllegalArgumentException(); } method.setRequestHeader("Accept", "text/xml"); method.setDoAuthentication(true); try { // Executes the request client.executeMethod(method); // Parses the result String body = method.getResponseBodyAsString(); if (Log.isDebugEnabled()) { Log.debug("Outgoing REST call results: " + body); } // Checks the http status if (method.getStatusCode() != 200) { if (method.getStatusCode() == 401) { throw new ConnectionException("Invalid password to connect to Clearspace.", ConnectionException.ErrorType.AUTHENTICATION); } else if (method.getStatusCode() == 404) { throw new ConnectionException("Web service not found in Clearspace.", ConnectionException.ErrorType.PAGE_NOT_FOUND); } else if (method.getStatusCode() == 503) { throw new ConnectionException("Web service not avaible in Clearspace.", ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE); } else { throw new ConnectionException( "Error connecting to Clearspace, http status code: " + method.getStatusCode(), new HTTPConnectionException(method.getStatusCode()), ConnectionException.ErrorType.OTHER); } } else if (body.contains("Clearspace Upgrade Console")) { //TODO Change CS to send a more standard error message throw new ConnectionException("Clearspace is in an update state.", ConnectionException.ErrorType.UPDATE_STATE); } Element response = localParser.get().parseDocument(body).getRootElement(); // Check for exceptions checkFault(response); // Since there is no exception, returns the response return response; } catch (DocumentException e) { throw new ConnectionException("Error parsing the response of Clearspace.", e, ConnectionException.ErrorType.OTHER); } catch (HttpException e) { throw new ConnectionException("Error performing http request to Clearspace", e, ConnectionException.ErrorType.OTHER); } catch (UnknownHostException e) { throw new ConnectionException("Unknown Host " + getConnectionURI() + " trying to connect to Clearspace", e, ConnectionException.ErrorType.UNKNOWN_HOST); } catch (IOException e) { throw new ConnectionException("Error peforming http request to Clearspace.", e, ConnectionException.ErrorType.OTHER); } finally { method.releaseConnection(); } }
From source file:org.jivesoftware.util.HttpClientWithTimeoutFeedFetcher.java
/** * @see com.sun.syndication.fetcher.FeedFetcher#retrieveFeed(java.net.URL) *//* ww w .j a v a 2 s . c o m*/ public SyndFeed retrieveFeed(URL feedUrl) throws IllegalArgumentException, IOException, FeedException, FetcherException { if (feedUrl == null) { throw new IllegalArgumentException("null is not a valid URL"); } // TODO Fix this //System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); HttpClient client = new HttpClient(); HttpConnectionManager conManager = client.getHttpConnectionManager(); conManager.getParams().setParameter("http.connection.timeout", 3000); conManager.getParams().setParameter("http.socket.timeout", 3000); if (getCredentialSupplier() != null) { client.getState().setAuthenticationPreemptive(true); // TODO what should realm be here? Credentials credentials = getCredentialSupplier().getCredentials(null, feedUrl.getHost()); if (credentials != null) { client.getState().setCredentials(null, feedUrl.getHost(), credentials); } } System.setProperty("httpclient.useragent", "Openfire Admin Console: v" + XMPPServer.getInstance().getServerInfo().getVersion().getVersionString()); String urlStr = feedUrl.toString(); FeedFetcherCache cache = getFeedInfoCache(); if (cache != null) { // retrieve feed HttpMethod method = new GetMethod(urlStr); method.addRequestHeader("Accept-Encoding", "gzip"); try { if (isUsingDeltaEncoding()) { method.setRequestHeader("A-IM", "feed"); } // get the feed info from the cache // Note that syndFeedInfo will be null if it is not in the cache SyndFeedInfo syndFeedInfo = cache.getFeedInfo(feedUrl); if (syndFeedInfo != null) { method.setRequestHeader("If-None-Match", syndFeedInfo.getETag()); if (syndFeedInfo.getLastModified() instanceof String) { method.setRequestHeader("If-Modified-Since", (String) syndFeedInfo.getLastModified()); } } method.setFollowRedirects(true); int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); SyndFeed feed = getFeed(syndFeedInfo, urlStr, method, statusCode); syndFeedInfo = buildSyndFeedInfo(feedUrl, urlStr, method, feed, statusCode); cache.setFeedInfo(new URL(urlStr), syndFeedInfo); // the feed may have been modified to pick up cached values // (eg - for delta encoding) feed = syndFeedInfo.getSyndFeed(); return feed; } finally { method.releaseConnection(); } } else { // cache is not in use HttpMethod method = new GetMethod(urlStr); try { method.setFollowRedirects(true); int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); return getFeed(null, urlStr, method, statusCode); } finally { method.releaseConnection(); } } }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.capture.CaptureImage.java
/*********************************************************************************************** * doCaptureImage()./*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 doCaptureImage(final ObservatoryInstrumentDAOInterface dao, final CommandMessageInterface commandmessage) { final String SOURCE = "CaptureImage.doCaptureImage()"; final CommandType cmdCapture; String strResponseValue; final ResponseMessageInterface responseMessage; // Initialise dao.clearEventLogFragment(); // Get the latest Resources dao.readResources(); // Don't affect the CommandType of the incoming Command cmdCapture = (CommandType) commandmessage.getCommandType().copy(); // Ensure we are dealing with an Ethernet-based instrument if ((commandmessage.getInstrument() != null) && (commandmessage.getInstrument().getController() != null) && (commandmessage.getInstrument().getController().getIPAddress() != null) && (dao.getRemoteDataConnection() != null)) { final HttpClient client; final HttpMethod method; final String strURL; // Set up the HttpClient client = new HttpClient(); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); // Beware filename part (e.g. IMAGE.JPG) *must* be uppercase! // Assume that we are dealing with a valid Ethernet Controller strURL = ControlPanelInterface.PREFIX_HTTP + IPVersion.stripTrailingPaddingFromIPAddressAndPort( commandmessage.getInstrument().getController().getIPAddress()); // The DAO Hostname contains the Value of Property KEY_DAO_IMAGE_FILENAME method = new GetMethod(strURL + "/" + dao.getRemoteDataConnection().getHostname()); // See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html // The User-Agent request-header field contains information about the user agent originating the request method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)"); // The Referer[sic] request-header field allows the client to specify, for the server's benefit, // the address (URI) of the resource from which the Request-URI was obtained // (the "referrer", although the header field is misspelled.) method.setRequestHeader("Referer", strURL + "/Jview.htm"); SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.INFO, METADATA_TARGET_IMAGE + METADATA_ACTION_CAPTURE + METADATA_ADDRESS + strURL + "/" + dao.getRemoteDataConnection().getHostname() + TERMINATOR, SOURCE, dao.getObservatoryClock()); // Establish the identity of this Instrument using Metadata // from the Framework, Observatory and Observer dao.establishDAOIdentityForCapture(DAOCommandHelper.getCommandCategory(cmdCapture), 0, false, null, null); try { final int intStatus; final InputStream inputStream; // Now try to get the Image intStatus = client.executeMethod(method); // Check the server status if (intStatus != HttpStatus.SC_OK) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + method.getStatusLine(), SOURCE, dao.getObservatoryClock()); } // It is vital that the response body is always read, // regardless of the status returned by the server. inputStream = method.getResponseBodyAsStream(); if (inputStream != null) { final BufferedImage image; image = ImageIO.read(inputStream); // If we get here, it must have succeeded... // Pass the Image to the DAO, and then to the Instrument and InstrumentPanel dao.setImageData(image); dao.setUnsavedData(true); inputStream.close(); strResponseValue = ResponseMessageStatus.SUCCESS.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.SUCCESS); } else { // No data are available SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_PARSE_DATA, SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.PREMATURE_TERMINATION.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.PREMATURE_TERMINATION); } } catch (NumberFormatException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (HttpException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE); } catch (IOException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_IO + exception.getMessage(), SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE); } finally { // It is important to always release the connection, // regardless of whether the server returned an error or not method.releaseConnection(); } } else { // Incorrectly configured XML strResponseValue = ResponseMessageStatus.INVALID_XML.getResponseValue(); dao.getResponseMessageStatusList().add( DAOCommandHelper.logInvalidXML(dao, SOURCE, METADATA_TARGET_IMAGE, METADATA_ACTION_CAPTURE)); } responseMessage = ResponseMessageHelper.createResponseMessage(dao, commandmessage, cmdCapture, null, null, strResponseValue); return (responseMessage); }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.capture.CaptureImageRealtime.java
/*********************************************************************************************** * captureImageRealtime()./* w w w. ja v a 2s .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().// ww w.ja v a2 s. c om * * @param dao * @param commandmessage * * @return ResponseMessageInterface */ public static ResponseMessageInterface doImportGOESRealtime(final ObservatoryInstrumentDAOInterface dao, final CommandMessageInterface commandmessage) { final String SOURCE = "ImportGOESRealtime.doImportGOESRealtime()"; final int PARAMETER_COUNT = 5; final int INDEX_URL = 0; final int INDEX_PATHNAME = 1; final int INDEX_INTERVAL = 2; final int INDEX_PERIOD = 3; final int INDEX_UPDATE = 4; final CommandType cmdImport; final List<ParameterType> listParameters; String strResponseValue; final ResponseMessageInterface responseMessage; final List<String> errors; final boolean boolDebug; boolDebug = (LOADER_PROPERTIES.isTimingDebug() || LOADER_PROPERTIES.isMetadataDebug() || LOADER_PROPERTIES.isStaribusDebug() || LOADER_PROPERTIES.isStarinetDebug()); // Initialise errors = new ArrayList<String>(10); dao.clearEventLogFragment(); // Get the latest Resources dao.readResources(); // Don't affect the CommandType of the incoming Command cmdImport = (CommandType) commandmessage.getCommandType().copy(); // We expect five parameters: the url, the pathname, the capture interval, the capture period and the update flag listParameters = cmdImport.getParameterList(); if ((dao.getHostInstrument() != null) && (dao.getHostInstrument().getInstrument() != null) && (dao.getHostInstrument().getInstrument().getController() != null) && (dao.getHostInstrument().getInstrument().getController().getVirtualAddress() != null) && (listParameters != null) && (listParameters.size() == PARAMETER_COUNT) && (listParameters.get(INDEX_URL) != null) && (SchemaDataType.STRING .equals(listParameters.get(INDEX_URL).getInputDataType().getDataTypeName())) && (listParameters.get(INDEX_PATHNAME) != null) && (SchemaDataType.PATH_NAME .equals(listParameters.get(INDEX_PATHNAME).getInputDataType().getDataTypeName())) && (listParameters.get(INDEX_INTERVAL) != null) && (SchemaDataType.DECIMAL_INTEGER .equals(listParameters.get(INDEX_INTERVAL).getInputDataType().getDataTypeName())) && (listParameters.get(INDEX_PERIOD) != null) && (SchemaDataType.DECIMAL_INTEGER .equals(listParameters.get(INDEX_PERIOD).getInputDataType().getDataTypeName())) && (listParameters.get(INDEX_UPDATE) != null) && (SchemaDataType.BOOLEAN .equals(listParameters.get(INDEX_UPDATE).getInputDataType().getDataTypeName()))) { try { final String strURL; final String strPathname; final String strCaptureInterval; final String strCapturePeriod; final boolean boolRealtimeUpdate; final int intCaptureIntervalSec; int intCapturePeriodSec; final HttpClient client; final HttpMethod method; strURL = listParameters.get(INDEX_URL).getValue(); strPathname = listParameters.get(INDEX_PATHNAME).getValue(); strCaptureInterval = listParameters.get(INDEX_INTERVAL).getValue(); strCapturePeriod = listParameters.get(INDEX_PERIOD).getValue(); boolRealtimeUpdate = Boolean.parseBoolean(listParameters.get(INDEX_UPDATE).getValue()); intCaptureIntervalSec = Integer.parseInt(strCaptureInterval); intCapturePeriodSec = Integer.parseInt(strCapturePeriod); // Check for silly parameter settings // CapturePeriod = 0 means run continuously if ((strURL != null) && (!EMPTY_STRING.equals(strURL.trim())) && (intCaptureIntervalSec > 0) && (intCapturePeriodSec >= 0)) { final String strPeriod; final int intCaptureCountMax; final ResponseMessageStatusList listStatusInCaptureLoop; boolean boolSuccess; if (intCapturePeriodSec == 0) { strPeriod = CaptureCommandHelper.MSG_PERIOD_CONTINUOUS; } else { strPeriod = Integer.toString(intCapturePeriodSec); } // We have all the Parameters, now prepare the HTTP client client = new HttpClient(); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); method = new GetMethod(strURL); // See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html // The User-Agent request-header field contains information about the user agent originating the request method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)"); // The Referer[sic] request-header field allows the client to specify, for the server's benefit, // the address (URI) of the resource from which the Request-URI was obtained // (the "referrer", although the header field is misspelled.) method.setRequestHeader("Referer", strURL + "/Jview.htm"); // Log everything we have so far SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.INFO, METADATA_TARGET_IMAGE + METADATA_ACTION_IMPORT + METADATA_URL_REQUEST + strURL + TERMINATOR_SPACE + METADATA_PATHNAME + strPathname + TERMINATOR_SPACE + METADATA_INTERVAL + intCaptureIntervalSec + TERMINATOR_SPACE + METADATA_PERIOD + strPeriod + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); // Correct the CapturePeriod for continuous operation if (intCapturePeriodSec == 0) { // Allow about 10 days of operation! (Could be Integer.MAX_VALUE?) intCapturePeriodSec = 1000000; } intCaptureCountMax = intCapturePeriodSec / intCaptureIntervalSec; boolSuccess = true; // Adjust the Timeout for the number of commands expected // TODO REVIEW TimeoutHelper.restartDAOTimeoutTimer(dao, intCounter, 0, 0); listStatusInCaptureLoop = ResponseMessageStatus.createResponseMessageStatusList(); for (int intCaptureIndex = 0; ((intCaptureIndex < intCaptureCountMax) && (boolSuccess) && Utilities.executeWorkerCanProceed(dao)); intCaptureIndex++) { final long longTimeStart; final long longTimeFinish; final long longTimeToWait; longTimeStart = dao.getObservatoryClock().getSystemTimeMillis(); listStatusInCaptureLoop.clear(); try { final int intStatus; final InputStream inputStream; // Now try to get the Image intStatus = client.executeMethod(method); // Check the server status if (intStatus != HttpStatus.SC_OK) { SimpleEventLogUIComponent .logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + SPACE + method.getStatusLine(), SOURCE, dao.getObservatoryClock()); } // It is vital that the response body is always read, // regardless of the status returned by the server. inputStream = method.getResponseBodyAsStream(); if (inputStream != null) { final BufferedImage image; image = ImageIO.read(inputStream); // If we get here, it must have succeeded... (otherwise IOException, ImageFormatException) // Save the image as a timestamped PNG file every time boolSuccess = DataExporter.exportImage(image, strPathname + "/GOES", true, FileUtilities.png, dao.getEventLogFragment(), dao.getObservatoryClock()); // Pass the Image to the DAO, and then to the Instrument and InstrumentPanel if (boolRealtimeUpdate) { dao.setImageData(image); dao.setUnsavedData(true); REGISTRY.getFramework().notifyFrameworkChangedEvent(dao.getHostInstrument()); InstrumentHelper.notifyInstrumentChanged(dao.getHostInstrument()); } inputStream.close(); listStatusInCaptureLoop.add(ResponseMessageStatus.SUCCESS); } else { // No data are available SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_PARSE_DATA, SOURCE, dao.getObservatoryClock()); } } catch (NumberFormatException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } catch (HttpException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_HTTP + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } catch (IOException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, ObservatoryInstrumentDAOInterface.ERROR_IO + exception.getMessage(), SOURCE, dao.getObservatoryClock()); } // Take account of the time elapsed so far... longTimeFinish = dao.getObservatoryClock().getSystemTimeMillis(); longTimeToWait = (intCaptureIntervalSec * ChronosHelper.SECOND_MILLISECONDS) - (longTimeFinish - longTimeStart); if (longTimeToWait > 0) { // Wait for the required time, checking to see if we have been stopped by the User Utilities.safeSleepPollExecuteWorker(longTimeToWait, dao); } else { LOGGER.error(SOURCE + " Invalid capture interval [time_to_wait=" + longTimeToWait + " msec]"); } } // Always release the HttpClient connection method.releaseConnection(); //----------------------------------------------------------------------------- // Capture the final Status and ResponseValue (these may show a failure) dao.getResponseMessageStatusList().addAll(listStatusInCaptureLoop); if (dao.getResponseMessageStatusList().contains(ResponseMessageStatus.SUCCESS)) { strResponseValue = ResponseMessageStatus.SUCCESS.getResponseValue(); } else { SimpleEventLogUIComponent.logErrors(dao.getEventLogFragment(), EventStatus.FATAL, errors, SOURCE, dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.PREMATURE_TERMINATION.getResponseValue(); } } else { throw new IllegalArgumentException(EXCEPTION_PARAMETER_INVALID); } } catch (NumberFormatException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, METADATA_EXCEPTION + ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage() + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.FATAL, METADATA_EXCEPTION + ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + exception.getMessage() + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_PARAMETER.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_PARAMETER); } catch (Exception exception) { exception.printStackTrace(); SimpleEventLogUIComponent.logEvent(dao.getEventLogFragment(), EventStatus.WARNING, METADATA_EXCEPTION + dao.getInstrumentName() + " Generic Exception [exception=" + exception.getMessage() + "]" + TERMINATOR, dao.getLocalHostname(), dao.getObservatoryClock()); strResponseValue = ResponseMessageStatus.INVALID_MESSAGE.getResponseValue(); dao.getResponseMessageStatusList().add(ResponseMessageStatus.INVALID_MESSAGE); } } else { // Incorrectly configured XML strResponseValue = ResponseMessageStatus.INVALID_XML.getResponseValue(); dao.getResponseMessageStatusList().add( DAOCommandHelper.logInvalidXML(dao, SOURCE, METADATA_TARGET_IMAGE, METADATA_ACTION_CAPTURE)); } ObservatoryInstrumentHelper.runGarbageCollector(); responseMessage = ResponseMessageHelper.createResponseMessage(dao, commandmessage, cmdImport, null, null, strResponseValue); return (responseMessage); }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.importers.ImportImageRemote.java
/*********************************************************************************************** * doImportImageRemote().// w w w . jav 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().// ww w . j a va2s . com * 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.methodize.nntprss.feed.Channel.java
/** * Retrieves the latest RSS doc from the remote site *//*from ww w.j ava 2 s . c o m*/ public synchronized void poll() { // Use method-level variable // Guard against change in history mid-poll polling = true; // boolean keepHistory = historical; long keepExpiration = expiration; lastPolled = new Date(); int statusCode = -1; HttpMethod method = null; String urlString = url.toString(); try { HttpClient httpClient = getHttpClient(); channelManager.configureHttpClient(httpClient); HttpResult result = null; try { connected = true; boolean redirected = false; int count = 0; do { URL currentUrl = new URL(urlString); method = new GetMethod(urlString); method.setRequestHeader("User-agent", AppConstants.getUserAgent()); method.setRequestHeader("Accept-Encoding", "gzip"); method.setFollowRedirects(false); method.setDoAuthentication(true); // ETag if (lastETag != null) { method.setRequestHeader("If-None-Match", lastETag); } // Last Modified if (lastModified != 0) { final String NAME = "If-Modified-Since"; //defend against such fun like net.freeroller.rickard got If-Modified-Since "Thu, 24 Aug 2028 12:29:54 GMT" if (lastModified < System.currentTimeMillis()) { final String DATE = httpDate.format(new Date(lastModified)); method.setRequestHeader(NAME, DATE); log.debug("channel " + this.name + " using " + NAME + " " + DATE); //ALEK } } method.setFollowRedirects(false); method.setDoAuthentication(true); HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost(currentUrl.getHost(), currentUrl.getPort(), currentUrl.getProtocol()); result = executeHttpRequest(httpClient, hostConfig, method); statusCode = result.getStatusCode(); if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) { redirected = true; // Resolve against current URI - may be a relative URI try { urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString(); } catch (URISyntaxException use) { // Fall back to just using location from result urlString = result.getLocation(); } if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY && channelManager.isObserveHttp301()) { try { url = new URL(urlString); if (log.isInfoEnabled()) { log.info("Channel = " + this.name + ", updated URL from HTTP Permanent Redirect"); } } catch (MalformedURLException mue) { // Ignore URL permanent redirect for now... } } } else { redirected = false; } // method.getResponseBody(); // method.releaseConnection(); count++; } while (count < 5 && redirected); } catch (HttpRecoverableException hre) { if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - Temporary Http Problem - " + hre.getMessage()); } status = STATUS_CONNECTION_TIMEOUT; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } catch (ConnectException ce) { // @TODO Might also be a connection refused - not only a timeout... if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - Connection Timeout, skipping - " + ce.getMessage()); } status = STATUS_CONNECTION_TIMEOUT; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } catch (UnknownHostException ue) { if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - Unknown Host Exception, skipping"); } status = STATUS_UNKNOWN_HOST; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } catch (NoRouteToHostException re) { if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - No Route To Host Exception, skipping"); } status = STATUS_NO_ROUTE_TO_HOST; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } catch (SocketException se) { // e.g. Network is unreachable if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - Socket Exception, skipping"); } status = STATUS_SOCKET_EXCEPTION; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } // Only process if ok - if not ok (e.g. not modified), don't do anything if (connected && statusCode == HttpStatus.SC_OK) { PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()), PUSHBACK_BUFFER_SIZE); skipBOM(pbis); BufferedInputStream bis = new BufferedInputStream(pbis); DocumentBuilder db = AppConstants.newDocumentBuilder(); try { Document rssDoc = null; if (!parseAtAllCost) { try { rssDoc = db.parse(bis); } catch (InternalError ie) { // Crimson library throws InternalErrors if (log.isDebugEnabled()) { log.debug("InternalError thrown by Crimson", ie); } throw new SAXException("InternalError thrown by Crimson: " + ie.getMessage()); } } else { // Parse-at-all-costs selected // Read in document to local array - may need to parse twice ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int bytesRead = bis.read(buf); while (bytesRead > -1) { if (bytesRead > 0) { bos.write(buf, 0, bytesRead); } bytesRead = bis.read(buf); } bos.flush(); bos.close(); byte[] rssDocBytes = bos.toByteArray(); try { // Try the XML document parser first - just in case // the doc is well-formed rssDoc = db.parse(new ByteArrayInputStream(rssDocBytes)); } catch (SAXParseException spe) { if (log.isDebugEnabled()) { log.debug("XML parse failed, trying tidy"); } // Fallback to parse-at-all-costs parser rssDoc = LooseParser.parse(new ByteArrayInputStream(rssDocBytes)); } } processChannelDocument(expiration, rssDoc); // Update last modified / etag from headers // lastETag = httpCon.getHeaderField("ETag"); // lastModified = httpCon.getHeaderFieldDate("Last-Modified", 0); Header hdrETag = method.getResponseHeader("ETag"); lastETag = hdrETag != null ? hdrETag.getValue() : null; Header hdrLastModified = method.getResponseHeader("Last-Modified"); lastModified = hdrLastModified != null ? parseHttpDate(hdrLastModified.getValue()) : 0; log.debug("channel " + this.name + " parsed Last-Modifed " + hdrLastModified + " to " + (lastModified != 0 ? "" + (new Date(lastModified)) : "" + lastModified)); //ALEK status = STATUS_OK; } catch (SAXParseException spe) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - Error parsing RSS document - check feed"); } status = STATUS_INVALID_CONTENT; } bis.close(); // end if response code == HTTP_OK } else if (connected && statusCode == HttpStatus.SC_NOT_MODIFIED) { if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - HTTP_NOT_MODIFIED, skipping"); } status = STATUS_OK; } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - Proxy authentication required"); } status = STATUS_PROXY_AUTHENTICATION_REQUIRED; } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - Authentication required"); } status = STATUS_USER_AUTHENTICATION_REQUIRED; } // Update channel in database... channelDAO.updateChannel(this); } catch (FileNotFoundException fnfe) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - File not found returned by web server - check feed"); } status = STATUS_NOT_FOUND; } catch (Exception e) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - Exception while polling channel", e); } } catch (NoClassDefFoundError ncdf) { // Throw if SSL / redirection to HTTPS if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - NoClassDefFound", ncdf); } } finally { connected = false; polling = false; } }