Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
pigdog
Apr 23, 2004

by Smythe

TRex EaterofCars posted:

No one smart uses struts any more. Ugh.

I am a huge fan of Grails, which is basically lipstick on Spring + Hibernate with a bunch of other cool features.

Could you explain what's wrong with Struts? (Just curious)

Adbot
ADBOT LOVES YOU

Max Facetime
Apr 18, 2009

pigdog posted:

Could you explain what's wrong with Struts? (Just curious)

For one, it uses Object-Graph Navigation Language (OGNL), which makes it easy to parse input to Java objects and get values from Java objects using strings like "session.user.name.firstName". OGNL can also parse and execute arbitrary Java code.

Yep, nothing can go wrong with that.

ComptimusPrime
Jan 23, 2006
Computer Transformer

Doctor w-rw-rw- posted:

Play framework is a really cool non-Servlet app framework. Klout and some other companies use it in production and its Scala support was good enough for Typesafe to anoint it officially as...something. I forgot. But its Java bindings are great, and I find it a lot of fun.

Agreed, the Play framework is easily the best framework I have worked with. It is so good that it makes me sad when I have to go to work and use ASP.

ComptimusPrime
Jan 23, 2006
Computer Transformer

I am in posted:

For one, it uses Object-Graph Navigation Language (OGNL), which makes it easy to parse input to Java objects and get values from Java objects using strings like "session.user.name.firstName". OGNL can also parse and execute arbitrary Java code.

Yep, nothing can go wrong with that.

I think it is worth adding that there is no point picking up something like Struts right now if you are starting from scratch. The world of web development has largely moved on.

Struts can be used to create a great website that is secure and full featured, but there is no point to using it. It isn't higher performing that other frameworks, it isn't more inherently secure, and most importantly, it is not as easy to create things with as one of the more modern frameworks.

Volguus
Mar 3, 2009
Spring MVC is good.
Tapestry is very nice as well.
The Play! framework...i personally wasn't too impressed with their 1.2.x versions, I'll wait to see what 2.0 will bring to the table.
Grails is awesome for a lot of reasons, awful for others (slow, huge memory usage, etc.). 2.0 promised to fix a lot of things (including speed improvements), didn't have a chance yet to try it out.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

rhag posted:

Spring MVC is good.
Tapestry is very nice as well.
The Play! framework...i personally wasn't too impressed with their 1.2.x versions, I'll wait to see what 2.0 will bring to the table.
Grails is awesome for a lot of reasons, awful for others (slow, huge memory usage, etc.). 2.0 promised to fix a lot of things (including speed improvements), didn't have a chance yet to try it out.

Tapestry is nice, and so is Wicket for that matter (as far as a view technology).

If you need speed, Spring MVC + JSTL is the best on the block as far as I'm concerned.

Grails definitely requires you to learn how to use -XX:PermGenSize and -Xmx but I think for the increase in productivity it's worth it.

Max Facetime
Apr 18, 2009

Just saw this one:

quote:

Unsigned Integer Arithmetic API now in JDK 8

By darcy on Jan 20, 2012

At long last, after due discussion and review, I've just pushed initial API support for unsigned integer arithmetic into JDK 8! The support is implemented via static methods, primarily on java.lang.Integer and java.lang.Long, that:
•Provide bidirectional conversion between strings and unsigned integers
•Compare values as unsigned
•Compute unsigned divide and remainder

At long last indeed!

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

quote:

I've just pushed initial API support for unsigned integer arithmetic into JDK 8! The support is implemented via static methods
you fuckers, how about something actually useful

Scaevolus
Apr 16, 2007

Having one line methods that are return (int)x & 0xff; is great, especially since invoking Byte.toUnsignedInt is longer than just doing it directly.

Doc Faustus
Sep 6, 2005

Philippe is such an angry eater
I'm using a Scanner to read in and parse a text file. I'm not sure if I'm just doing this wrong, or if I'm missing something, but here's the issue.

I've created the Scanner object in my main(), with it taking input from a File object. I pass the Scanner into a method, where it reads through every line of a file. I then pass the Scanner to a second method, but by this point Scanner is at the end of the file, so there's no more lines to read.

So, as I see it, either I need a new Scanner object for each method, OR I need some way to tell the Scanner to start over.

Help?

ComptimusPrime
Jan 23, 2006
Computer Transformer
Creating a new Scanner will likely work.

I would really recommend that you take a look at InputStreamReader or FileReader.

Each of these will do what you need them to do, and you can call reset() to go back to the beginning of the file. Not as friendly as Scanner, but it is the more correct way of handling the problem.

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
Scanner is really friendly and easy to use, but it's really slow performance-wise and not as versatile. Use FileReader or BufferedReader.

Doc Faustus
Sep 6, 2005

Philippe is such an angry eater
Each file being parsed isn't very long (~55 lines), but it needs to process 52,000 documents, so efficiency is certainly a concern. BufferedReader looks like the best alternative so far, though I'll admit I've become fairly reliant on Scanner's .hasNext() method.

Thom Yorke raps
Nov 2, 2004


How worried do I have to be about permgen space? I'm working on a large (700,000 lines of code probably?) application. I'm trying to make use of functional programming, so I'm using a number of Function classes to imitate true closures.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
The only time I've run into permgen space problems is when using a lot of Spring/CGLib stuff in a web container. Redeploy the application(s) several times, and the JVM starts puking, because it has some problems cleaning up after proxy classes or something.

Blacknose
Jul 28, 2006

Meet frustration face to face
A point of view creates more waves
So lose some sleep and say you tried
Pretty much the same as that, I've only seen it when redeploying big Spring apps.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Going to chime in with I've only seen it when redeploying a project with a lot of Web Services in GlassFish. After many redeploys it will barf on that and require a restart. I think it's because the GC doesn't reclaim stuff in the permgenspace.

edit: I've also seen it when compiling a project in Netbeans a bunch of times. LOL

DholmbladRU
May 4, 2006
I am attempting to create a java/jsp web page which will read from an xml file and allow users to interact with the data. What I am thinking is pulling the data from the xml file and putting it into a java object, this object could then be passed through using a session. Temporary object could be pointed to origonal one if they wanted to add or remove elements.

Well I am having some trouble getting started, I am a little confused as to which xml parser I should be using. I got brief overviews of SAX and DOM however I am still unsure. Or is there an easier way than this? I havnt done any work with java in awhile.

I found some code online that I was able to alter to read in xml and parse into list then to an array. Is there an easy way to remove the tags from a string. So for a given string I have 'tag=value', how can I return everything after it? Can this be accomplished with regex?

DholmbladRU fucked around with this message at 03:02 on Jan 25, 2012

pigdog
Apr 23, 2004

by Smythe
See something like this: http://totheriver.com/learn/xml/xmltutorial.html . DOM is easier to use but takes up more memory and CPU (gets important if the XMLs are in megabytes of size), SAX is a bit of a bitch to use but is faster and doesn't blow up if the XML files are huge, StAX is sort of middle ground but haven't used it much yet. Don't use a regexp to parse XML, especially other peoples' XML, it will bite you in the rear end. That's what XML parsers are there for. There's a bunch of boilerplate code, but once you have that DOM object you can do cool stuff with it like search it with XPath, modify the elements, transform it with XSLT, et cetera.

edit: If the XML in question corresponds to a concrete XML schema, then see this: http://xmlbeans.apache.org/

pigdog fucked around with this message at 10:13 on Jan 25, 2012

DholmbladRU
May 4, 2006

pigdog posted:

See something like this: http://totheriver.com/learn/xml/xmltutorial.html . DOM is easier to use but takes up more memory and CPU (gets important if the XMLs are in megabytes of size), SAX is a bit of a bitch to use but is faster and doesn't blow up if the XML files are huge, StAX is sort of middle ground but haven't used it much yet. Don't use a regexp to parse XML, especially other peoples' XML, it will bite you in the rear end. That's what XML parsers are there for. There's a bunch of boilerplate code, but once you have that DOM object you can do cool stuff with it like search it with XPath, modify the elements, transform it with XSLT, et cetera.

edit: If the XML in question corresponds to a concrete XML schema, then see this: http://xmlbeans.apache.org/

Thanks for the information. I was able to use dom for the moment to bring in an xml file and put it into java obj. What I was talking abuot regex for was to remove part of a string that I do not want.

code:
if (event.isStartElement()) {
					if (event.asStartElement().getName().getLocalPart()
							.equals(location)) {
						event = eventReader.nextEvent();
						//System.out.println(event.asCharacters().getData());
						homeObject.setLocation(event.asCharacters().getData().trim() );
					//	System.out.println(event.asCharacters().getData());
						continue;
					}
				}
Here I am reading in a xml tag and adding it to a java object field. However the tag name 'location=' comes along with it. How can I remove this from the incoming string without taking up alot of resources?

DholmbladRU fucked around with this message at 14:05 on Jan 25, 2012

Sereri
Sep 30, 2008

awwwrigami

DholmbladRU posted:

Here I am reading in a xml tag and adding it to a java object field. However the tag name 'location=' comes along with it. How can I remove this from the incoming string without taking up alot of resources?

So you have <abc location='xyz'> and want to remove the location='xyz' ? Why not simply remove the attribute from the object?

Max Facetime
Apr 18, 2009

DholmbladRU posted:

Here I am reading in a xml tag and adding it to a java object field. However the tag name 'location=' comes along with it. How can I remove this from the incoming string without taking up alot of resources?

This line is a suspect one:

code:
	event = eventReader.nextEvent();
You're not checking what sort of event you get back, so it's likely not what you anticipated. Next, the method call to asCharacters() "[r]eturns this event as Characters, may result in a class cast exception if this event is not Characters." Yikes.

So if the event was an isAttribute() event that was helpfully converted to a content event that could explain the "location=" part.

Instead, you should put the StartElement that asStartElement() returns in a variable and read the attribute using getAttributeByName().

DholmbladRU
May 4, 2006

I am in posted:

This line is a suspect one:

code:
	event = eventReader.nextEvent();
You're not checking what sort of event you get back, so it's likely not what you anticipated. Next, the method call to asCharacters() "[r]eturns this event as Characters, may result in a class cast exception if this event is not Characters." Yikes.

So if the event was an isAttribute() event that was helpfully converted to a content event that could explain the "location=" part.

Instead, you should put the StartElement that asStartElement() returns in a variable and read the attribute using getAttributeByName().

Didnt think about non character input, user input will be validated so hopfully that wont happen. And this is a small project that I am puttingn togetther

This should work right?
code:
if (event.isStartElement()) {
					if (event.asStartElement().getName().getLocalPart()
							.equals(location)) {
						event = eventReader.nextEvent();
						homeObject.setLocation(event.getAttributeByName.trim() );
						continue;
					}
				}

Max Facetime
Apr 18, 2009

No, that doesn't even compile. Try this to see what's going on:

code:
  private static final QName TAG = new QName("location");
  private static final QName ATTRIBUTE = new QName("location");
  private static final String XML = "<root><location location=\"earf\"/>"
    + "<location location=\"moon\">base alpha</location>" + "</root>";
  private static int count;

  public static void main(String[] args) {
    try {
      XMLEventReader eventReader =
        XMLInputFactory.newFactory()
          .createXMLEventReader(new StringReader(XML));
      while(eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        print(event);
        if(event.isStartElement()) {
          StartElement startElement = event.asStartElement();
          QName elementName = startElement.getName();
          if(elementName.equals(TAG)) {
            Attribute attribute = startElement.getAttributeByName(ATTRIBUTE);
            String location = attribute.getValue();
            System.out.println("got location " + location);
          }
        }
      }
    } catch(XMLStreamException | FactoryConfigurationError e) {
      e.printStackTrace();
    }
  }

  public static void print(XMLEvent event) {
    count++;
    System.out.println("event " + count + ": " + event + " "
      + (event.isAttribute() ? "Attribute " : "")
      + (event.isCharacters() ? "Characters " : "")
      + (event.isEndDocument() ? "EndDocument " : "")
      + (event.isEndElement() ? "EndElement " : "")
      + (event.isEntityReference() ? "EntityReference " : "")
      + (event.isNamespace() ? "Namespace " : "")
      + (event.isProcessingInstruction() ? "PI " : "")
      + (event.isStartDocument() ? "StartDocument " : "")
      + (event.isStartElement() ? "StartElement " : ""));
  }

DholmbladRU
May 4, 2006
code:
		while (eventReader.hasNext()) {
			
			XMLEvent event = eventReader.nextEvent();

			if (event.isStartElement()) {
				StartElement startElement = event.asStartElement();
				
				// If we have a item element we create a new item
				if (startElement.getName().getLocalPart() == (home)) {
					homeObject = new homeObj();
					// We read the attributes from this tag and add the date
					// attribute to our object
					Iterator<Attribute> attributes = startElement.getAttributes();
					
					//writes ID for the home tag to the obj
					if (event.isStartElement()) {
						Attribute attribute = attributes.next();
						if (attribute.getName().toString().equals("id")) {
							homeObject.setHome(attribute.getValue());
							String s= attribute.getValue();
							continue;
						}

					}
				}
				
				if (event.isStartElement()) {
				//	StartElement start = event.asStartElement();
			          QName elementName = startElement.getName();

					if (elementName.equals(locationTag)) {			
						Attribute attribute = startElement.getAttributeByName(locationAtt);	
						System.out.println(attribute.getName());
						homeObject.setLocation(attribute.getValue().replaceAll("\\s","") );
						
						continue;
					}
				}
xml example
code:
<h>
 <home id="1">
  <location>
  virginia
  </location
 </home>
</h>
My prior implementation was creating the homeObject.field with 'tagName=value'.

I am still really confused by your example, I dont see how I would do .getCharacters. I am getting the Id in, and stored properly. But after that everything is wrong

Max Facetime
Apr 18, 2009

DholmbladRU posted:

xml example
code:
<h>
 <home id="1">
  <location>
  virginia
  </location
 </home>
</h>
My prior implementation was creating the homeObject.field with 'tagName=value'.

I am still really confused by your example, I dont see how I would do .getCharacters. I am getting the Id in, and stored properly. But after that everything is wrong

Running that exact XML using this output loop

code:
  private static final String XML = "<h>\n" + " <home id=\"1\">\n"
    + "  <location>\n" + "  virginia\n" + "  </location\n" + " </home>\n"
    + "</h>";

// ...

  while(eventReader.hasNext()) {
    XMLEvent event = eventReader.nextEvent();
    print(event);
  }
outputs for me

code:
event 1: <?xml version="1.0" encoding='null' standalone='no'?> StartDocument 
event 2: <h> StartElement 
event 3: 
  Characters 
event 4: <home id='1'> StartElement 
event 5: 
   Characters 
event 6: <location> StartElement 
event 7: 
  virginia
   Characters 
javax.xml.stream.XMLStreamException: ParseError at [row,col]:[6,2]
Message: The end-tag for element type "location" must end with a '>' delimiter.
	at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source)
	at com.sun.xml.internal.stream.XMLEventReaderImpl.nextEvent(Unknown Source)
	at xmlevent.EventStuff.main(EventStuff.java:32)
Note 3rd and 5th events, they are for character content that's entirely whitespace.

7th event is the Character event you're looking for.

And the invalid closing tag and its error message follows next.

Tracking an XML stream is tricky enough on its own, doubly so if you're learning the language at the same time. Plus it's overkill unless your XML files are 100+MBs or you have a concrete performance target.

May I suggest DOM instead? Here's a DOM version of the previous parsing debugger:

code:
  static final String XML = "<h>\n" + " <home id=\"1\">\n" + "  <location>\n"
    + "  virginia\n" + "  </location>\n" + " </home>\n" + "</h>";

  public static void main(String[] args) {
    try {
      Document document =
        DocumentBuilderFactory.newInstance().newDocumentBuilder()
          .parse(new InputSource(new StringReader(XML)));
      print(document);
    } catch(SAXException | IOException | ParserConfigurationException
        | TransformerFactoryConfigurationError | TransformerException e) {
      e.printStackTrace();
    }
  }

  private static int indent;

  private static void print(Node node)
      throws TransformerFactoryConfigurationError, TransformerException,
      IOException {
    indent++;
    char[] indentChars = new char[indent];
    Arrays.fill(indentChars, ' ');

    try (StringWriter sw = new StringWriter()) {
      Transformer trans = TransformerFactory.newInstance().newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      trans.transform(new DOMSource(node), new StreamResult(sw));

      System.out.println(new String(indentChars)
        + (node + " " + sw.toString()).replaceAll("\\s+", " "));
    }
    NodeList childNodes = node.getChildNodes();
    for(int i = 0, n = childNodes.getLength(); i < n; i++) {
      print(childNodes.item(i));
    }
    indent--;
  }
This outputs the lot more structured

code:
 [#document: null] <h> <home id="1"> <location> virginia </location> </home> </h>
  [h: null] <h> <home id="1"> <location> virginia </location> </home> </h>
   [#text: ] 
   [home: null] <home id="1"> <location> virginia </location> </home>
    [#text: ] 
    [location: null] <location> virginia </location>
     [#text: virginia ] virginia 
    [#text: ] 
   [#text: ]

DholmbladRU
May 4, 2006
I am in: Thank you for providing me with these methods. It is really helping me understand this better. Eventually I will be pulling in an xml file with more than just the location tag.

code:
3 nodeType
null firstChild
#text nodeName
virginia sw.ToString()
If i try to get the sw.ToString() by the nodeType, if there are any spaces in the xml document I will get incorrect data. Could I mitigate this safly by checking if nodetype=3 and sw.toString!=null. Or am I approching this the wrong way

like this
code:
   if(node.getNodeType()==3 && node.getNodeName()=="#text"){
	    //  System.out.println(node.getNodeType());
	     // System.out.println(node.getFirstChild());
	      //System.out.println(node.getNodeName());
	      System.out.println(sw.toString());
	    }
returns me

code:
virginia
$1000000
1/24/2010
for
code:
<h><home id=\"1\"><location>virginia</location><price>$1000000</price><dateOnMarket>1/24/2010</dateOnMarket></home></h>";
Whic is closer to what I am looking for.

DholmbladRU fucked around with this message at 19:22 on Jan 26, 2012

Max Facetime
Apr 18, 2009

DholmbladRU posted:

like this
code:
   if(node.getNodeType()==3 && node.getNodeName()=="#text"){
	    //  System.out.println(node.getNodeType());
	     // System.out.println(node.getFirstChild());
	      //System.out.println(node.getNodeName());
	      System.out.println(sw.toString());
	    }

Yes, this is more like it.

The Node API docs here summarizes different element types and how they are matched to Java interfaces. It doesn't show an example, but the intended way to use the Node API is like this:

code:
if(node.getNodeType() == Node.TEXT_NODE) {
  Text textNode = (Text) node;
  System.out.println(textNode.getData());
}
but in this case a simpler version is just fine:

code:
if(node.getNodeType() == Node.TEXT_NODE) {
  System.out.println(node.getNodeValue());
}

DholmbladRU
May 4, 2006
Yeah seems like this should work, thanks for all the help. Is there a way to grab the 1, or the "home id='1'"? When that is added as a node it only contains 'home: null'. The ID doesnt seem to be read anywhere.

Max Facetime
Apr 18, 2009

DholmbladRU posted:

Yeah seems like this should work, thanks for all the help. Is there a way to grab the 1, or the "home id='1'"? When that is added as a node it only contains 'home: null'. The ID doesnt seem to be read anywhere.

You can read all the attributes from a NamedNodeMap object by calling node.getAttributes() when the node's type is Node.ELEMENT_NODE.

DholmbladRU
May 4, 2006
I am getting a bunch of lines where getNodeName()="" and getNodeValue()=""

code:
3
null
#text


3
null
#text



thas from

System.out.println(node.getNodeType());
System.out.println(node.getFirstChild());
System.out.println(node.getNodeName());
System.out.println(node.getNodeValue());


There are no trailing spaces in my xml document, I even ruined the tabing to make sure..

code:
<homes>
<home id="1">
<location>Rock Creek Chuch, DC</location>
<price>$1000000</price>
<dateOnMarket>1/24/2010</dateOnMarket>
<numDaysOnMarket>1</numDaysOnMarket>
<sold>no</sold>
<dateSold>n/a</dateSold>
<shortDescription>Beautiful, spacious Petworth rowhouse</shortDescription>
<imageURL>C:/Documents and Settings/dholmblad/workspace/SDK/images/h1.jpg</imageURL>
</home>
</homes>

DholmbladRU fucked around with this message at 23:59 on Jan 26, 2012

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

DholmbladRU posted:

There are no trailing spaces in my xml document, I even ruined the tabing to make sure..

code:
<homes>
<home id="1">
<location>Rock Creek Chuch, DC</location>
<price>$1000000</price>
<dateOnMarket>1/24/2010</dateOnMarket>
<numDaysOnMarket>1</numDaysOnMarket>
<sold>no</sold>
<dateSold>n/a</dateSold>
<shortDescription>Beautiful, spacious Petworth rowhouse</shortDescription>
<imageURL>C:/Documents and Settings/dholmblad/workspace/SDK/images/h1.jpg</imageURL>
</home>
</homes>

It sure looks like there are some newlines in there...

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
If you really want to work with xml, I recommend using a library like XOM (my favorite) or JDOM (the most well-known).

It will make your life a billion times easier.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
Or you can just use groovy. It makes xml super simple.

Doctor w-rw-rw-
Jun 24, 2008

TRex EaterofCars posted:

Or you can just use groovy. It makes xml super simple.

Because adding a whole language to a project for a single feature is no problem for anyone...what advantages and features specifically addressing XML does Groovy have?

Seconding XOM. It's straightforward in its usage.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Doctor w-rw-rw- posted:

Because adding a whole language to a project for a single feature is no problem for anyone...what advantages and features specifically addressing XML does Groovy have?

Seconding XOM. It's straightforward in its usage.

No need to be a dick; XML in Java is so hairy that writing a small class in Groovy is vastly preferable. Java's going polyglot anyhow, might as well jump on board.

To answer your question, XML is basically a first class citizen in Groovy. Both reading and writing are super simple. I make judicious use of MarkupBuilder and XMLParser myself.

http://groovy.codehaus.org/Processing+XML

Volguus
Mar 3, 2009

TRex EaterofCars posted:

No need to be a dick; XML in Java is so hairy that writing a small class in Groovy is vastly preferable. Java's going polyglot anyhow, might as well jump on board.

To answer your question, XML is basically a first class citizen in Groovy. Both reading and writing are super simple. I make judicious use of MarkupBuilder and XMLParser myself.

http://groovy.codehaus.org/Processing+XML

While your statement is true, that XML is a first citizen in groovy and its parsing is trivial, I still don't get what's so difficult in Java either (with the standard DOM or SAX parsers).
Sure, some libraries may come and make it even easier, but...holy moly, you can say anything about it except that it's hard.
Their only requirement is to read the documentation, then is a breeze.
I personally favor SAX for the simple reason that is faster and can parse relatively big XML files (where DOM would choke for example: OutOfMemoryError).
Writing a SAX handler is quite straight-forward as well.

for small XMLs though, DOM is good enough for every day use.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

rhag posted:

While your statement is true, that XML is a first citizen in groovy and its parsing is trivial, I still don't get what's so difficult in Java either (with the standard DOM or SAX parsers).
Sure, some libraries may come and make it even easier, but...holy moly, you can say anything about it except that it's hard.
Their only requirement is to read the documentation, then is a breeze.
I personally favor SAX for the simple reason that is faster and can parse relatively big XML files (where DOM would choke for example: OutOfMemoryError).
Writing a SAX handler is quite straight-forward as well.

for small XMLs though, DOM is good enough for every day use.

It's obviously subjective but I seriously hate working with XML in Java. It's long winded and error prone, and the less I type the better. Groovy's is much easier to read and understand later as well.

There are streaming parsers and builders for Groovy as well.

Doctor w-rw-rw-
Jun 24, 2008

TRex EaterofCars posted:

No need to be a dick; XML in Java is so hairy that writing a small class in Groovy is vastly preferable. Java's going polyglot anyhow, might as well jump on board.

To answer your question, XML is basically a first class citizen in Groovy. Both reading and writing are super simple. I make judicious use of MarkupBuilder and XMLParser myself.

http://groovy.codehaus.org/Processing+XML

Sorry, wasn't trying to be a dick. I don't really favor the trend towards JVM languages that aren't statically typed. If I want to go for something interpreted or much looser in general than Java, I'm happy to make use of Objective-C and Python. And for many projects, usage of Groovy or even Scala is a pretty hard sell, so someone working on a project might not necessarily have the option to add a whole new language, particularly not if there's - for example - established practices for testing and a test scaffolding that expects things to be one way, and metrics that evaluate said testing. That is to say, for some, process might get in the way of progress.

I only took a very brief look, but it seems that Groovy has a concise format for parsing, but as someone who writes in Java, verbosity can sometimes be tolerated for other features. In the case of XOM, it can clean up the DOM of HTML files, which is what I like it for.

Adbot
ADBOT LOVES YOU

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Doctor w-rw-rw- posted:

Sorry, wasn't trying to be a dick. I don't really favor the trend towards JVM languages that aren't statically typed. If I want to go for something interpreted or much looser in general than Java, I'm happy to make use of Objective-C and Python. And for many projects, usage of Groovy or even Scala is a pretty hard sell, so someone working on a project might not necessarily have the option to add a whole new language, particularly not if there's - for example - established practices for testing and a test scaffolding that expects things to be one way, and metrics that evaluate said testing. That is to say, for some, process might get in the way of progress.

I only took a very brief look, but it seems that Groovy has a concise format for parsing, but as someone who writes in Java, verbosity can sometimes be tolerated for other features. In the case of XOM, it can clean up the DOM of HTML files, which is what I like it for.

I hear ya. Chaining NekoHTML to Groovy's XML processor to get markup repair isn't too bad (
code:
new XmlParser(new org.cyberneko.html.parsers.SAXParser())
) but that's yet ANOTHER set of jars to add. In an environment that doesn't allow developers the flexibility to do that I guess that's not really feasible.

In regards to losing the static typing, one nice thing about Groovy is that type declarations are supported. You can write near-Java (up to a few subtleties) and Groovy will gobble it down.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply