from javax.xml.parsers import ParserConfigurationException
from javax.xml.parsers import DocumentBuilderFactory
from javax.xml.xpath import XPath
from javax.xml.xpath import XPathExpressionException
from javax.xml.xpath import XPathFactory
from javax.xml.xpath import XPathConstants
from org.xml.sax import InputSource
from org.das2.qds import DDataSet

from java.io import File
from java.io import FileInputStream
import java.lang.Integer

for j in xrange(4): 
  
  ss= 'https://autoplot.org/data/xml/weather.gov/forecast_201205%02d.xml' % (j+27)  # from http://forecast.weather.gov/
  
  try:
      file= getFile( URI(ss), monitor.getSubtaskMonitor( j,j+1,ss) )
  except:
      continue  # jump back to next in loop
      
  print ss
  myin= FileInputStream( file )

  builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
  source = InputSource( myin )
  initialDocument = builder.parse(source)

  factory= XPathFactory.newInstance()
  xpath= factory.newXPath()

 # // is anywhere, / is root.
  temps= xpath.evaluate( '/dwml/data/parameters/temperature[@type="hourly"]/value', initialDocument, XPathConstants.NODESET )
  ttemps= DDataSet.createRank1( temps.getLength() )
  for i in range( temps.getLength() ):
   value = xpath.evaluate('text()', temps.item(i), XPathConstants.STRING)
   if value:
      ttemps.putValue( i, java.lang.Integer.parseInt( value ) )
   else:
      ttemps.putValue( i, -1e31 )
  ttemps.putProperty( QDataSet.FILL_VALUE, -1e31 )

  times= xpath.evaluate( '/dwml/data/time-layout/start-valid-time/text()', initialDocument, XPathConstants.NODESET )

  ttimes= DDataSet.createRank1( times.getLength() )

  tp= TimeParser.create( TimeParser.iso8601String( times.item(0).nodeValue[0:19]) )
  tp.parse( times.item(0).nodeValue[0:19] ).getTime( Units.us2000 )

  for i in range( times.getLength() ):
     ttimes.putValue( i, tp.parse( times.item(i).nodeValue[0:19] ).getTime( Units.us2000 ) )
  ttimes.putProperty( QDataSet.UNITS, Units.us2000 )

  ttemps.putProperty( QDataSet.DEPEND_0, ttimes )

  plot( j, ttemps )

