Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Wednesday, June 12, 2013

XML StreamingMarkupBuilder

import groovy.xml.StreamingMarkupBuilder

Map props = [addressid:'1', line1:'line-1_VALUE', line2:'line-2_VALUE']

def builder = new StreamingMarkupBuilder()

def address = {
     "address"(id: props.addressid) {
         "line-1"(props.line1)
         "line-2"(props.line2)
         "city"("city_VALUE") // typing wimped out...
         "state"("State_VALUE")
         "postal-code"("postal_VALUE")
     }
}

println builder.bind(address).toString() // something XML-compatible <address id="1">
...</address>

Thursday, June 6, 2013

Scrape image src's from a web page

import java.net.URLEncoder

String url = "http://msnbc.com"

String serviceUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22${URLEncoder.encode(url)}%22%20and%20xpath%3D%22%2F%2Fimg%22"
//println serviceUrl

String resultXML = serviceUrl.toURL().text // YQL will return the HTML page as XML!
//println resultXML

def root = new XmlSlurper().parseText(resultXML)

List imgSrcs = root.results.img.@src as List
imgSrcs = imgSrcs*.toString().unique()
//println imgSrcs.join('\n')

Thursday, February 23, 2012

Swing Notification Popup

//see: http://groovy.codehaus.org/GUI+Programming+with+Groovy

import groovy.swing.*
import java.awt.*
import javax.swing.*
import javax.swing.border.*
import groovy.util.slurpersupport.NodeChild as Node
 
public class Notify { 
 def sb = new SwingBuilder()

 public static void main(String[] args) {
  // creates and displays itself
  new Notify(args)
 }

 public Notify(String[] args){
  // arg is path to xml message file, 
  // will be deleted after popup displayed
  if (args.size() != 1) return 
  
  String appTitle = ".:. Notification .:."
  String filePath = args[0]
  Color backgroundColor = Color.yellow
  Border emptyBorder = BorderFactory.createMatteBorder(5, 5, 5, 5, backgroundColor)
    
  Toolkit tk = Toolkit.getDefaultToolkit()
  Dimension screenSize = tk.getScreenSize()
  final int WIDTH = screenSize.width
  final int HEIGHT = screenSize.height
  
  int w = WIDTH / 2
  int h = HEIGHT / 2
  
  int x = (WIDTH / 2) - (w / 2)
  int y = (HEIGHT / 2) - (h / 2) - 50
  
  Font fontSubject = new Font("Serif", Font.PLAIN, 24)
  Font fontMessage = new Font("Serif", Font.PLAIN, 16)
  
  //generate frame//
  sb.dialog(id:"popupBox", title:appTitle, visible:true, alwaysOnTop:true, defaultCloseOperation:JFrame.DISPOSE_ON_CLOSE, resizable:false, location:[x, y], size:[w, h]) 
  {
   borderLayout()
   label(id:"subject", constraints:BorderLayout.NORTH, horizontalAlignment:JTextField.CENTER, font:fontSubject, "SUBJ")
   
   panel(constraints:BorderLayout.CENTER){
    gridLayout(cols:1, rows:1, hgap:1, vgap:1)
    scrollPane(border:emptyBorder) {
     textArea(id:"message", editable:false, lineWrap:true, wrapStyleWord:true, font:fontMessage, "MESG")
    }
   }
  }
  def frame = sb.popupBox
  
  //decorate frame color//
  def cp = frame.contentPane
  cp.background = backgroundColor
  sb.message.background = cp.background
  
  //populate frame data//
  File xmlFile
  Node root
  try {
   xmlFile = new File(filePath)
   root = new XmlSlurper().parse(xmlFile)
   //println root.getClass().name
  } 
  catch (Exception) {
   xmlFile = new File("")
   root = new XmlSlurper().parseText('''
    Error
    Sorry, file path or XML syntax error.
    ''')
  }
  
  sb.subject.text = root.subject.text() // if not found, subject UI label is hidden
  sb.message.text = root.message.text() ? 
   root.message.text().replaceAll('\\\\n', System.getProperty( "line.separator" )) :
   'Sorry, empty notification.'
  
  //display form//
  frame.show()
  
  try {
   xmlFile.delete()
  } catch (Exception ignore) {}
 }
}

Tuesday, March 29, 2011

XML Filter and Printer

def filename = "C:\\test.xml" // will create a file on your system here!

def example="""
<contacts>
   <campuscontact>
      <firstname>Jane</firstname>
      <lastname>Doe</lastname>
      <storenumber>123</storenumber>
   </campuscontact>
   <campuscontact>
      <firstname>Mike</firstname>
      <lastname>Jones</lastname>
      <storenumber>789</storenumber>
   </campuscontact>
   <campuscontact>
      <firstname>Joe</firstname>
      <lastname>Smith</lastname>
      <storenumber>555</storenumber>
   </campuscontact>
</contacts>"""

def nodes = new XmlParser().parseText(example)
def filterBy = ['555','123']

inList = nodes.CampusContact.grep {it.StoreNumber.text() in filterBy}
notInList = nodes.CampusContact.grep {!(it.StoreNumber.text() in filterBy)}
assert inList.size() == 2
assert notInList.size() == 1

//or

notInList = nodes.CampusContact.grep {!(it in inList)}
assert notInList.size() == 1

new PrintWriter(filename).with {
    append("<root>\n")
    p = new XmlNodePrinter(delegate)
    p.preserveWhitespace = true
    p.namespaceAware = false
    inList.each { p.print(it) }
    append("</root>").close()
}

/*
<root>
<campuscontact>
  <firstname>Jane</firstname>
  <lastname>Doe</lastname>
  <storenumber>123</storenumber>
</campuscontact>
<campuscontact>
  <firstname>Joe</firstname>
  <lastname>Smith</lastname>
  <storenumber>555</storenumber>
</campuscontact>
</root>
*/

http://groovyconsole.appspot.com/script/447002

YQL for eBates Stores

String endpoint = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.ebates.com%2Fstores%2Fall%2Findex.htm%22%20and%20xpath%3D%22%2F%2Fhtml%2Fbody%2Fdiv%2Fdiv%2Fdiv%2Fdiv%2Fdiv%2Fform%2Ftable%2Ftr%5B%40class%3D'store'%5D%2Ftd%5B%40class%3D'storeName'%5D%2Fstrong%2Fa%22"
println 'getting data...'
def xml = endpoint.toURL().text

//println 'got!\n'

//println xml.size()

List names = new XmlSlurper().parseText(xml).results.a.collect{it.@href.text() - '/stores/' - '.htm'}

println "['" + names.sort().join("','") + "']"
return names.size()

RSS Feed Parser/Reader

def rssurl = "http://feeds.digg.com/digg/news/popular.rss"  
def slurp = new XmlSlurper()  
def rssObj = slurp.parse(rssurl).declareNamespace(digg: "http://digg.com/docs/diggrss/", media: "http://search.yahoo.com/mrss/")  

rssObj.channel.item.eachWithIndex { item , num ->  
    println "-------------------------------------------"  
    println "#${num + 1}: ${item.title}"
    println item."digg:category"  
    def url = item."media:thumbnail".@url.text()  
    if ( url ) {  
        println url  
        download(num, url)  
    }  
}  

def download(num , address)  
{  
    def filename =  address.tokenize("/")[-2]  
    def tmp = address.tokenize("/")[-1]   
    def ext = tmp.tokenize(".")[-1]  
    filename = filename << "." << ext  
    println "saving image file : " << filename  
    def file = new FileOutputStream(filename.toString())  
    def out = new BufferedOutputStream(file)  
    out << new URL(address).openStream()  
    out.close()  
}

println "-------------------------------------------\ndone"

http://groovyconsole.appspot.com/script/451002