|
import java.io.*;
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;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class CurrentsPointObservationsGetter {
public static void main(String[] args) {
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=currents";
String saveToYourLocalDir = "C:\\temp\\sosdata\\";
String stationsIds[] = {"cb0102", "gp0101", "t02010"};
String dates[] = {"2012-02-01", "2012-03-21"};
String responseFormat = "csv";
String describeStationURL;
URL describeSensorURL;
String procedureURN;
String dateTimeStr;
String url;
URL dataUrl;
String filename;
try {
List dtList = getDateTimeList(dates);
String responseMIMEType = getResponseMIMEType(responseFormat);
for (int i = 0; i < stationsIds.length; i++) {
describeStationURL = sosUrl + "?service=SOS&request=DescribeSensor&version=1.0.0&"
+ "outputFormat=text/xml;subtype=\"sensorML/1.0.1\"&procedure=urn:ioos:station:NOAA.NOS.CO-OPS:" + stationsIds[i];
describeSensorURL = new URL(describeStationURL);
procedureURN = getProcedureURN(describeSensorURL);
if (!isValidRealTimeCurrentStationId(stationsIds[i])) {
throw new IOException(" Wrong Station ID: " + stationsIds[i] + ", please enter a valid station ID.");
}
for (int j = 0, size = dtList.size(); j < size; j++) {
dateTimeStr = (String) dtList.get(j);
url = baseUrl + "&offering=urn:ioos:station:NOAA.NOS.CO-OPS:" + stationsIds[i]
+ "&procedure=" + procedureURN + "&responseFormat=" + urlEncode(responseMIMEType) + "&eventTime=" + dateTimeStr;
dataUrl = new URL(url);
filename = getFileName(stationsIds[i], dateTimeStr, responseFormat, saveToYourLocalDir);
getResource(dataUrl, filename);
}
}
} catch (Exception e) {
System.err.println("ERROR: ******* " + e.getMessage());
}
}
public static boolean isValidRealTimeCurrentStationId(String stationId) {
Pattern regexCUrealtime = Pattern.compile("^[a-z]{2}[0-9]{4}$");
Pattern regexCUrealtimeOld = Pattern.compile("^[a-z][0-9]{5}$");
if (stationId == null) {
return false;
} else {
stationId = stationId.trim();
Matcher mCUrealtime = regexCUrealtime.matcher(stationId);
Matcher mCUrealtimeOld = regexCUrealtimeOld.matcher(stationId);
if (mCUrealtime.matches()) { return true;
} else if (mCUrealtimeOld.matches()) { return true;
} else {
return false;
}
}
}
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; 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;
}
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();
}
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;
}
private static String urlEncode(String inString) {
if (inString != null) {
inString = inString.replace("/", "%2F");
inString = inString.replace("+", "%2B");
}
return inString;
}
public static String getFileName(String stationId, String dateTime, String responseFormat, String saveToYourLocalDir) {
String dateTimeStr = dateTime.replace(":", "-").replace("/", "_");
String fileName = saveToYourLocalDir + "currentsPoint_" + stationId + "_" + dateTimeStr + "." + responseFormat.toLowerCase();
return fileName;
}
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());
}
}
}
private static String getProcedureURN(URL url) {
String procedureURN = null;
HttpURLConnection huc;
InputStream in;
try {
huc = (HttpURLConnection) url.openConnection();
huc.setAllowUserInteraction(false);
huc.setDoInput(true);
huc.setDoOutput(false);
huc.setUseCaches(false);
huc.connect();
in = huc.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(in);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("sml:identification");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
NamedNodeMap attributes = nNode.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Attr attribute = (Attr) attributes.item(j);
if (attribute.getNodeName().equals("xlink:href")) {
procedureURN = nNode.getAttributes().getNamedItem("xlink:href").getNodeValue() + ":rtb";
}
}
}
}
in.close();
} catch (SAXException sex) {
System.err.println("ERROR: ******* " + sex.toString());
} catch (ParserConfigurationException pex) {
System.err.println("ERROR: ******* " + pex.toString());
} catch (IOException ex) {
System.err.println("ERROR: ******* " + ex.toString());
}
return procedureURN;
}
}
|