NOAA Web Site Link Tides and Currents Home Page Transparent placeholder image
CO-OPS         IOOS Data Portal         Take Our Survey
banner graphic

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MetObservationsGetter {

    public static void main(String[] args) {
        //CO-OPS Sensor Observation Service (SOS) URL
        String sosUrl = "https://opendap.co-ops.nos.noaa.gov/ioos-dif-sos/SOS";
        String baseUrl = sosUrl + "?service=SOS&request=GetObservation&version=1.0.0&observedProperty=";

        /*
         * The user can modify the local directory where the downloaded data files can be stored, the observed property, 
         * the stations IDs, the date range, and the preferred format of those data files.
         *
         */
        //Local directory that data files will be stored to
        String saveToYourLocalDir = "C:\\temp\\sosdata\\";
        //Observed property options: air_temperature, air_pressure, sea_water_electrical_conductivity, sea_water_salinity, 
        //sea_water_temperature, winds, rain_fall, relative_humidity
        String products[] = {"air_temperature", "winds", "rain_fall"};
        //Station Ids
        String stationsIds[] = {"8454049", "8637689", "9754228", "9759394"};
        //Begin date and end date for requested data
        String dates[] = {"2011-12-01", "2012-03-21"};
        //Response format options: csv, tsv, xml, kml 
        String responseFormat = "csv";

        String dateTimeStr;
        String url;
        URL dataUrl;
        String fileName;

        try {
            List dtList = getDateTimeList(dates);
            String responseMIMEType = getResponseMIMEType(responseFormat);

            for (int i = 0; i < products.length; i++) {
                if (!isValidObservedProperty(products[i])) {
                    throw new IOException(" Wrong Observed Property: " + products[i] + ", please enter a valid observed property.");
                }

                for (int j = 0; j < stationsIds.length; j++) {
                    if (!isValidNwlonStationId(stationsIds[j])) {
                        throw new IOException(" Wrong Station ID: " + stationsIds[j] + ", please enter a valid station ID.");
                    }

                    for (int k = 0, size = dtList.size(); k < size; k++) {
                        dateTimeStr = (String) dtList.get(k);
                        url = baseUrl + products[i] + "&offering=urn:ioos:station:NOAA.NOS.CO-OPS:"
                                + stationsIds[j] + "&responseFormat=" + urlEncode(responseMIMEType) + "&eventTime=" + dateTimeStr;
                        /*
                         * The end result of that URL should look like this;
                         * https://opendap.co-ops.nos.noaa.gov/ioos-dif-sos/SOS?service=SOS&request=GetObservation&version=1.0.0
                         * &observedProperty=air_temperature&offering=urn:ioos:station:NOAA.NOS.CO-OPS:8454000
                         * &responseFormat=text%2Fcsv&eventTime=2005-01-01T00:00:00Z/2005-02-01T00:00:00Z
                         */

                        dataUrl = new URL(url);
                        fileName = getFileName(products[i], stationsIds[j], dateTimeStr, responseFormat, saveToYourLocalDir);
                        getResource(dataUrl, fileName);
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("ERROR: ******* " + e.getMessage());
        }
    }

    /**
     * Check if string is a valid NWLON station ID (consist of 7 digits).
     *
     * @param stationId string to check
     * @return boolean if consists only of numbers
     */
    public static boolean isValidNwlonStationId(String stationId) {
        Pattern regexWL = Pattern.compile("^[1-9][0-9]{6}$");

        if (stationId == null) {
            return false;
        } else {
            stationId = stationId.trim();
            Matcher mWL = regexWL.matcher(stationId);

            if (mWL.matches()) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * Get the list of date/timestamp in IOOS-DIF format yyyy-mm-ddThh:mm:ssZ
     * and in GMT.
     *
     * @param dates[] date to fetch data
     * @return a list of date/timestamp in yyyy-mm-ddThh:mm:ssZ format, e.g.
     * 2005-01-01T00:00:00Z/2005-02-01T00:00:00Z
     */
    public static List getDateTimeList(String dates[]) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        String startTime = "00:00:00";
        String endTime = "23:59:00";
        int MAX_RETRIEVAL_DAYS = 31; // This maximum allowed time period is enforced by the server and can not be changed
        long difference;
        double diffDays;
        Date start;
        Date end;
        Date tempStart;
        Date tempEnd;
        String dateTimeStr;
        List dateTimeList = new ArrayList();

        try {
            start = sdf.parse(dates[0] + " " + startTime);
            end = sdf.parse(dates[1] + " " + endTime);
            if (end.before(start)) {
                throw new java.text.ParseException(" Wrong dates order, end date must be later than begin date.", -1);
            }
            difference = end.getTime() - start.getTime();
            diffDays = difference / (1000 * 60 * 60 * 24);

            if (diffDays > MAX_RETRIEVAL_DAYS) {
                tempStart = start;
                for (int d = 0; d <= diffDays; d += MAX_RETRIEVAL_DAYS) {
                    tempEnd = sdf.parse(addDays(MAX_RETRIEVAL_DAYS - 1, tempStart) + " " + endTime);
                    if (tempEnd.after(end)) {
                        tempEnd = end;
                    }
                    dateTimeStr = sdf.format(tempStart).replace(" ", "T") + "Z" + "/" + sdf.format(tempEnd).replace(" ", "T") + "Z";
                    dateTimeList.add(dateTimeStr);
                    tempStart = sdf.parse(addDays(1, tempEnd) + " " + startTime);
                }
            } else {
                dateTimeStr = sdf.format(start).replace(" ", "T") + "Z" + "/" + sdf.format(end).replace(" ", "T") + "Z";
                dateTimeList.add(dateTimeStr);
            }
        } catch (ParseException ex) {
            System.err.println("ERROR: ******* " + ex.toString());
        }
        return dateTimeList;
    }

    /**
     * Add days to a Date.
     *
     * @param dayOffset number of days to add
     * @param dateTime a date
     * @return a date as string in yyyy-MM-dd format
     */
    public static String addDays(int dayOffset, Date dateTime) {
        Calendar calender = new GregorianCalendar();
        calender.setTime(dateTime);
        calender.add(Calendar.DATE, dayOffset);

        int month = calender.get(Calendar.MONTH) + 1;
        int day = calender.get(Calendar.DAY_OF_MONTH);
        int year = calender.get(Calendar.YEAR);

        StringBuilder buffer = new StringBuilder(15);
        buffer.append(year);
        buffer.append('-');

        if (month < 10) {
            buffer.append('0');
        }
        buffer.append(month);
        buffer.append('-');

        if (day < 10) {
            buffer.append('0');
        }
        buffer.append(day);

        return buffer.toString();
    }

    /**
     * Get the MIME type of response format.
     *
     * @param formatOption response format
     * @return MIME Type of response format
     */
    private static String getResponseMIMEType(String formatOption) throws IOException {
        String responseMIMEType = "text/csv";
        if (formatOption.equalsIgnoreCase("csv")) {
            responseMIMEType = "text/csv";
        } else if (formatOption.equalsIgnoreCase("tsv")) {
            responseMIMEType = "text/tab-separated-values";
        } else if (formatOption.equalsIgnoreCase("kml")) {
            responseMIMEType = "application/vnd.google-earth.kml+xml";
        } else if (formatOption.equalsIgnoreCase("xml")) {
            responseMIMEType = "text/xml;schema=\"ioos/0.6.1\"";
        } else {
            throw new IOException(" Wrong Response Format: please enter a valid response format string.");
        }
        return responseMIMEType;
    }

    /**
     * Check if string is a valid observed property (case insensitive match).
     *
     * @param input string to check
     * @return boolean if string is a valid observed property
     */
    public static boolean isValidObservedProperty(String input) {
        boolean isMatch = false;
        List acceptObservedProperties = new ArrayList();
        acceptObservedProperties.add("air_temperature");
        acceptObservedProperties.add("air_pressure");
        acceptObservedProperties.add("sea_water_electrical_conductivity");
        acceptObservedProperties.add("sea_water_salinity");
        acceptObservedProperties.add("sea_water_temperature");
        acceptObservedProperties.add("winds");
        acceptObservedProperties.add("rain_fall");
        acceptObservedProperties.add("relative_humidity");

        if (input != null) {
            if (input.length() == 0) {
                isMatch = false;
            } else {
                String s = input.toLowerCase();
                for (int i = 0, size = acceptObservedProperties.size(); i < size; i++) {
                    if (acceptObservedProperties.get(i).toString().equals(s)) {
                        isMatch = true;
                        break;
                    }
                }
            }
        }
        return isMatch;
    }

    /**
     * Encode a URL string.
     *
     * @param inString string to encode
     * @return encoded string
     */
    private static String urlEncode(String inString) {
        if (inString != null) {
            inString = inString.replace("/", "%2F");
            inString = inString.replace("+", "%2B");
        }
        return inString;
    }

    /**
     * Get the name of data file that will be saved to local hard disk.
     *
     * @param product product name
     * @param stationId station ID
     * @param dateTime time event
     * @param responseFormat response format
     * @param saveToYourLocalDir local directory that data files will be stored
     * to
     * @return new file name to be created on local hard disk
     */
    public static String getFileName(String product, String stationId, String dateTime, String responseFormat, String saveToYourLocalDir) {
        String dateTimeStr = dateTime.replace(":", "-").replace("/", "_");
        String fileName = saveToYourLocalDir + product + "_" + stationId + "_" + dateTimeStr + "." + responseFormat.toLowerCase();
        return fileName;
    }

    /**
     * Fetch the files from the http connection and write it to a local file.
     *
     * @param url URL to fetch data
     * @param fileName new file to be created on local hard disk
     */
    public static void getResource(URL url, String fileName) {
        HttpURLConnection huc = null;
        BufferedInputStream in = null;
        FileOutputStream file;
        BufferedOutputStream out = null;

        try {
            huc = (HttpURLConnection) url.openConnection();
            huc.setAllowUserInteraction(false);
            huc.setDoInput(true);
            huc.setDoOutput(false);
            huc.setUseCaches(false);
            huc.setReadTimeout(30000);
            huc.connect();

            in = new BufferedInputStream(huc.getInputStream());
            file = new FileOutputStream(fileName);
            out = new BufferedOutputStream(file);

            int len;
            byte[] data = new byte[1024];
            while ((len = in.read(data, 0, 1024)) >= 0) {
                out.write(data, 0, len);
            }

            out.flush();
            out.close();
            in.close();
            huc.disconnect();
            Thread.sleep(4000);
        } catch (InterruptedException iex) {
            System.err.println("ERROR: ******* " + iex.toString());
        } catch (IOException ex) {
            System.err.println("ERROR: ******* " + ex.toString());
        } finally {
            try {
                in.close();
                out.close();
                huc.disconnect();
            } catch (IOException ex) {
                System.err.println("ERROR: ******* " + ex.toString());
            }
        }
    }
}

 
Web site owner: Center for Operational Oceanographic Products and Services (CO-OPS)          Privacy Policy         Take Our Survey