'분류 전체보기'에 해당되는 글 2491건
- 2010.02.19 Get HTML code
- 2010.02.19 Change the font weight and color of all Italic text
- 2010.02.19 Filter by ID
- 2010.02.19 Check key code
- 2010.02.19 Anchor click event
- 2010.02.19 Change background color
- 2010.02.19 Change submit button background and border
- 2010.02.19 Change color for DIV
- 2010.02.19 Create and append text node
- 2010.02.19 Add Text node created by document
- 2010.02.19 Append HTML to
- 2010.02.19 Append HTML to
- 2010.02.19 Add and remove text paragraph
- 2010.02.19 Add click listener to links in unordered list
- 2010.02.19 Stop click event
- 2010.02.19 Find all children of the clicked element.
- 2010.02.19 Jar File Download
- 2010.02.19 Properties To XML
- 2010.02.19 Parse Properties Files
- 2010.02.19 XML Databases and Tools 1: read from clob
- 2010.02.19 XML Databases and Tools 2: read from blob
- 2010.02.19 XML Databases DOM
- 2010.02.19 Get character data (CDATA) from xml document
- 2010.02.19 Velocity Output XML
- 2010.02.19 Show basic XML handling in a template
- 2010.02.19 Custom log for Velocity
- 2010.02.19 Velocity input encoding
- 2010.02.19 Event Handler: Exceptions
- 2010.02.19 Velocity Variable Noise Reference
- 2010.02.19 Resource Loader Demo
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:42
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:41
반응형
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<style type="text/css">
a.test { font-weight: bold; color:red;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("input.buttonA").click(function(){ $("div.contentToChange").find("em").css({color:"#993300", fontWeight:"bold"}); });
});
</script>
</head>
<body>
<input type="button" value="Change" class="buttonA" />
<div style="background:#eee;" class="contentToChange">
<h2>Header 2</h2>
<p class="firstparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
<p class="fifthparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
</div>
</body>
</html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<style type="text/css">
a.test { font-weight: bold; color:red;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("input.buttonA").click(function(){ $("div.contentToChange").find("em").css({color:"#993300", fontWeight:"bold"}); });
});
</script>
</head>
<body>
<input type="button" value="Change" class="buttonA" />
<div style="background:#eee;" class="contentToChange">
<h2>Header 2</h2>
<p class="firstparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
<p class="fifthparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
</div>
</body>
</html>
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:40
반응형
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").css("background", "blue")
.filter(function (index) {
return $(this).attr("id") == "fourth" ;
})
.css("border", "1px solid red");
});
</script>
<style>
div { border:2px white solid;}
</style>
</head>
<body>
<body>
<div id="first">asdf</div>
<div id="second">asdf</div>
<div id="third">asdf</div>
<div id="fourth">asdf</div>
<div id="fifth">asdf</div>
<div id="sixth">asdf</div>
</body>
</html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").css("background", "blue")
.filter(function (index) {
return $(this).attr("id") == "fourth" ;
})
.css("border", "1px solid red");
});
</script>
<style>
div { border:2px white solid;}
</style>
</head>
<body>
<body>
<div id="first">asdf</div>
<div id="second">asdf</div>
<div id="third">asdf</div>
<div id="fourth">asdf</div>
<div id="fifth">asdf</div>
<div id="sixth">asdf</div>
</body>
</html>
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:39
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:38
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:36
반응형
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).ready(function(){
$("*").css("background","red");
});
});
</script>
</head>
<body>
<div class="notMe">div </div>
<div class="myClass">div</div>
<span class="myClass myOtherClass">span</span>
</body>
</html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).ready(function(){
$("*").css("background","red");
});
});
</script>
</head>
<body>
<div class="notMe">div </div>
<div class="myClass">div</div>
<span class="myClass myOtherClass">span</span>
</body>
</html>
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:36
반응형
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var input = $(":submit").css({background:"yellow", border:"3px red solid"});
$('#result').text('jQuery matched ' + input.length + ' elements.');
});
</script>
</head>
<body>
<form><input type="submit" /></form>
<div id="result"></div>
</body>
</html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var input = $(":submit").css({background:"yellow", border:"3px red solid"});
$('#result').text('jQuery matched ' + input.length + ' elements.');
});
</script>
</head>
<body>
<form><input type="submit" /></form>
<div id="result"></div>
</body>
</html>
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:35
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:34
반응형
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").html("<b>bold</b> not bold");
$("div b").append(document.createTextNode("!!!")).css("color", "red");
});
</script>
</head>
<body>
<body>
<DIV></DIV>
</body>
</html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").html("<b>bold</b> not bold");
$("div b").append(document.createTextNode("!!!")).css("color", "red");
});
</script>
</head>
<body>
<body>
<DIV></DIV>
</body>
</html>
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:34
반응형
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").html("<b>bold</b>");
$("p b").append(document.createTextNode("added")).css("color", "red");
});
</script>
</head>
<body>
<body>
<p>asdf</p>
</body>
</html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").html("<b>bold</b>");
$("p b").append(document.createTextNode("added")).css("color", "red");
});
</script>
</head>
<body>
<body>
<p>asdf</p>
</body>
</html>
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:33
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:33
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:33
반응형
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<style type="text/css">
a.test { font-weight: bold; color:red;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("input.buttonA").click(function(){$("div.contentToChange").find("p").not(".alert").append("<strong> Appended</strong>")});
$("input.buttonB").click(function(){$("strong").remove()});
});
</script>
</head>
<body>
<input type="button" value="Add" class="buttonA" />
<input type="button" value="Remove" class="buttonB" />
<div style="background:#eee;" class="contentToChange">
<h2>Header 2</h2>
<p class="firstparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
<p class="secondparagraph">Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse <strong>molestie</strong> consequat, vel illum <strong>dolore</strong> eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer <strong>adipiscing</strong> elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p class="thirdparagraph">Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea <em>commodo</em> consequat. Duis autem vel eum iriure dolor in hendrerit in <em>vulputate</em> velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te <strong>feugait</strong> nulla facilisi.</p>
<p class="fourthparagraph">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, <strong>quis</strong> nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
<p class="fifthparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
<p class="sixthparagraph">Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse <strong>molestie</strong> consequat, vel illum <strong>dolore</strong> eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer <strong>adipiscing</strong> elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</div>
</body>
</html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<style type="text/css">
a.test { font-weight: bold; color:red;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("input.buttonA").click(function(){$("div.contentToChange").find("p").not(".alert").append("<strong> Appended</strong>")});
$("input.buttonB").click(function(){$("strong").remove()});
});
</script>
</head>
<body>
<input type="button" value="Add" class="buttonA" />
<input type="button" value="Remove" class="buttonB" />
<div style="background:#eee;" class="contentToChange">
<h2>Header 2</h2>
<p class="firstparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
<p class="secondparagraph">Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse <strong>molestie</strong> consequat, vel illum <strong>dolore</strong> eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer <strong>adipiscing</strong> elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p class="thirdparagraph">Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea <em>commodo</em> consequat. Duis autem vel eum iriure dolor in hendrerit in <em>vulputate</em> velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te <strong>feugait</strong> nulla facilisi.</p>
<p class="fourthparagraph">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, <strong>quis</strong> nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
<p class="fifthparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
<p class="sixthparagraph">Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse <strong>molestie</strong> consequat, vel illum <strong>dolore</strong> eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer <strong>adipiscing</strong> elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</div>
</body>
</html>
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:31
반응형
<html>
<head>
<script type='text/javascript' src='js/jquery-1.3.2.js'></script>
<script type='text/javascript'>
var tmpExample = {
ready : function() {
$('ul#myStyle li a').click(
function($e) {
$e.preventDefault();
window.open(this.href, 'FavoriteLink', '');
}
);
}
};
$(document).ready(tmpExample.ready);
</script>
<style type='text/css'>
ul {
list-stlye: none;
margin: 0;
padding: 0;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<ul id='myStyle'>
<li><a href='http://www.java2s.com'>java2s</a></li>
<li><a href='http://www.apple.com'>Apple</a></li>
<li><a href='http://www.jquery.com'>jQuery</a></li>
</ul>
</body>
</html>
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:31
반응형
<html>
<head>
<script type='text/javascript' src='js/jquery-1.3.2.js'></script>
<script type='text/javascript'>
var tmpExample = {
ready : function() {
$('ul#myStyle li a').click(
function($e) {
$e.preventDefault();
window.open(this.href, 'FavoriteLink', '');
}
);
}
};
$(document).ready(tmpExample.ready);
</script>
<style type='text/css'>
ul {
list-stlye: none;
margin: 0;
padding: 0;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<ul id='myStyle'>
<li><a href='http://www.java2s.com'>java2s</a></li>
<li><a href='http://www.apple.com'>Apple</a></li>
<li><a href='http://www.jquery.com'>jQuery</a></li>
</ul>
</body>
</html>
<head>
<script type='text/javascript' src='js/jquery-1.3.2.js'></script>
<script type='text/javascript'>
var tmpExample = {
ready : function() {
$('ul#myStyle li a').click(
function($e) {
$e.preventDefault();
window.open(this.href, 'FavoriteLink', '');
}
);
}
};
$(document).ready(tmpExample.ready);
</script>
<style type='text/css'>
ul {
list-stlye: none;
margin: 0;
padding: 0;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<ul id='myStyle'>
<li><a href='http://www.java2s.com'>java2s</a></li>
<li><a href='http://www.apple.com'>Apple</a></li>
<li><a href='http://www.jquery.com'>jQuery</a></li>
</ul>
</body>
</html>
07.JavaScript, jQuery, ExtJS.../jQuery2010. 2. 19. 18:30
반응형
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#container").click(function (e) {
var $kids = $(e.target).children();
alert($kids.length);
e.preventDefault();
return false;
});
});
</script>
</head>
<body>
<body>
<div id="container">
<div>
asdf
</div>
</div>
</body>
</html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#container").click(function (e) {
var $kids = $(e.target).children();
alert($kids.length);
e.preventDefault();
return false;
});
});
</script>
</head>
<body>
<body>
<div id="container">
<div>
asdf
</div>
</div>
</body>
</html>
01.JAVA/Java2010. 2. 19. 18:28
반응형
|
ABC |
|
DEF |
|
GHI |
|
JKL |
|
MNOPQR |
|
STUVWXYZ |
03.HTML 4.X, HTML5, XML.../XML2010. 2. 19. 18:26
반응형
/*--
Copyright (C) 2001 Brett McLaughlin.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the disclaimer that follows
these conditions in the documentation and/or other materials
provided with the distribution.
3. The name "Java and XML" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact brett@newInstance.com.
In addition, we request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
"This product includes software developed for the
'Java and XML' book, by Brett McLaughlin (O'Reilly & Associates)."
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.jdom.output.XMLOutputter;
/**
* <b><code>PropsToXML</code></b> takes a standard Java properties
* file, and converts it into an XML format. This makes properties
* like <code>enhydra.classpath.separator</code> "groupbable" by
* "enhydra", "classpath", and by the key name, "separator", which
* the standard Java <code>java.util.Properties</code> class does
* not allow.
*/
public class PropsToXML {
/**
* <p> This will take the supplied properties file, and
* convert that file to an XML representation, which is
* then output to the supplied XML document filename. </p>
*
* @param propertiesFilename file to read in as Java properties.
* @param xmlFilename file to output XML representation to.
* @throws <code>IOException</code> - when errors occur.
*/
public void convert(String propertiesFilename, String xmlFilename)
throws IOException {
// Get Java Properties object
FileInputStream input = new FileInputStream(propertiesFilename);
Properties props = new Properties();
props.load(input);
// Convert to XML
convertToXML(props, xmlFilename);
}
/**
* <p> This will handle the detail of conversion from a Java
* <code>Properties</code> object to an XML document. </p>
*
* @param props <code>Properties</code> object to use as input.
* @param xmlFilename file to output XML to.
* @throws <code>IOException</code> - when errors occur.
*/
private void convertToXML(Properties props, String xmlFilename)
throws IOException {
// Create a new JDOM Document with a root element "properties"
Element root = new Element("properties");
Document doc = new Document(root);
// Get the property names
Enumeration propertyNames = props.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String)propertyNames.nextElement();
String propertyValue = props.getProperty(propertyName);
createXMLRepresentation(root, propertyName, propertyValue);
}
// Output document to supplied filename
XMLOutputter outputter = new XMLOutputter(" ", true);
FileOutputStream output = new FileOutputStream(xmlFilename);
outputter.output(doc, output);
}
/**
* <p> This will convert a single property and its value to
* an XML element and textual value. </p>
*
* @param root JDOM root <code>Element</code> to add children to.
* @param propertyName name to base element creation on.
* @param propertyValue value to use for property.
*/
private void createXMLRepresentation(Element root,
String propertyName,
String propertyValue) {
/*
Element element = new Element(propertyName);
element.setText(propertyValue);
root.addContent(element);
*/
int split;
String name = propertyName;
Element current = root;
Element test = null;
while ((split = name.indexOf(".")) != -1) {
String subName = name.substring(0, split);
name = name.substring(split+1);
// Check for existing element
if ((test = current.getChild(subName)) == null) {
Element subElement = new Element(subName);
current.addContent(subElement);
current = subElement;
} else {
current = test;
}
}
// When out of loop, what's left is the final element's name
Element last = new Element(name);
// last.setText(propertyValue);
last.setAttribute("value", propertyValue);
current.addContent(last);
}
/**
* <p> Provide a static entry point for running. </p>
*/
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java PropsToXML " +
"[properties file] [XML file for output]");
System.exit(0);
}
try {
PropsToXML propsToXML = new PropsToXML();
propsToXML.convert(args[0], args[1]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*--
Copyright (C) 2001 Brett McLaughlin.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the disclaimer that follows
these conditions in the documentation and/or other materials
provided with the distribution.
3. The name "Java and XML" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact brett@newInstance.com.
In addition, we request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
"This product includes software developed for the
'Java and XML' book, by Brett McLaughlin (O'Reilly & Associates)."
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
/**
* <b><code>XMLProperties</code></b> extends Java's
* <code>java.util.Properties</code> class, and provides
* behavior similar to properties but that use XML as the
* input and output format.
*/
class XMLProperties extends Properties {
/**
* <p> This overrides the default <code>load()</code>
* behavior to read from an XML document. </p>
*
* @param reader the reader to read XML from
* @throws <code>IOException</code> - when errors occur reading.
*/
public void load(Reader reader)
throws IOException {
try {
// Load XML into JDOM Document
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(reader);
// Turn into properties objects
loadFromElements(doc.getRootElement().getChildren(),
new StringBuffer(""));
} catch (JDOMException e) {
throw new IOException(e.getMessage());
}
}
/**
* <p> This overrides the default <code>load()</code>
* behavior to read from an XML document. </p>
*
* @param inputStream the input stream
* @throws <code>IOException</code> - when errors occur reading.
*/
public void load(InputStream inputStream)
throws IOException {
load(new InputStreamReader(inputStream));
}
/**
* <p> This overrides the default <code>load()</code>
* behavior to read from an XML document. </p>
*
* @param xmlDocument the XML document to read
* @throws <code>IOException</code> - when errors occur reading.
*/
public void load(File xmlDocument)
throws IOException {
load(new FileReader(xmlDocument));
}
/**
* <p>This helper method loads the XML properties from a specific
* XML element, or set of elements.</p>
*
* @param elements <code>List</code> of elements to load from.
* @param baseName the base name of this property.
*/
private void loadFromElements(List elements, StringBuffer baseName) {
// Iterate through each element
for (Iterator i = elements.iterator(); i.hasNext(); ) {
Element current = (Element)i.next();
String name = current.getName();
String text = current.getTextTrim();
// String text = current.getAttributeValue("value");
// Don't add "." if no baseName
if (baseName.length() > 0) {
baseName.append(".");
}
baseName.append(name);
// See if we have an element value
if ((text == null) || (text.equals(""))) {
// If no text, recurse on children
loadFromElements(current.getChildren(),
baseName);
} else {
// If text, this is a property
setProperty(baseName.toString(),
text);
}
// On unwind from recursion, remove last name
if (baseName.length() == name.length()) {
baseName.setLength(0);
} else {
baseName.setLength(baseName.length() -
(name.length() + 1));
}
}
}
/**
* @deprecated This method does not throw an IOException
* if an I/O error occurs while saving the property list.
* As of the Java 2 platform v1.2, the preferred way to save
* a properties list is via the
* <code>{@link store(OutputStream out, String header}</code>
* method.
*/
public void save(OutputStream out, String header) {
try {
store(out, header);
} catch (IOException ignored) {
// Deprecated version doesn't pass errors
}
}
/**
* <p> This will output the properties in this object
* as XML to the supplied output writer. </p>
*
* @param writer the writer to output XML to.
* @param header comment to add at top of file
* @throws <code>IOException</code> - when writing errors occur.
*/
public void store(Writer writer, String header)
throws IOException {
// Create a new JDOM Document with a root element "properties"
Element root = new Element("properties");
Document doc = new Document(root);
// Add in header information
Comment comment = new Comment(header);
doc.getContent().add(0, comment);
// Get the property names
Enumeration propertyNames = propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String)propertyNames.nextElement();
String propertyValue = getProperty(propertyName);
createXMLRepresentation(root, propertyName, propertyValue);
}
// Output document to supplied filename
XMLOutputter outputter = new XMLOutputter(" ", true);
outputter.output(doc, writer);
writer.flush();
}
/**
* <p> This will output the properties in this object
* as XML to the supplied output stream. </p>
*
* @param out the output stream.
* @param header comment to add at top of file
* @throws <code>IOException</code> - when writing errors occur.
*/
public void store(OutputStream out, String header)
throws IOException {
store(new OutputStreamWriter(out), header);
}
/**
* <p> This will output the properties in this object
* as XML to the supplied output file. </p>
*
* @param xmlDocument XML file to output to.
* @param header comment to add at top of file
* @throws <code>IOException</code> - when writing errors occur.
*/
public void store(File xmlDocument, String header)
throws IOException {
store(new FileWriter(xmlDocument), header);
}
/**
* <p> This will convert a single property and its value to
* an XML element and textual value. </p>
*
* @param root JDOM root <code>Element</code> to add children to.
* @param propertyName name to base element creation on.
* @param propertyValue value to use for property.
*/
private void createXMLRepresentation(Element root,
String propertyName,
String propertyValue) {
int split;
String name = propertyName;
Element current = root;
Element test = null;
while ((split = name.indexOf(".")) != -1) {
String subName = name.substring(0, split);
name = name.substring(split+1);
// Check for existing element
if ((test = current.getChild(subName)) == null) {
Element subElement = new Element(subName);
current.addContent(subElement);
current = subElement;
} else {
current = test;
}
}
// When out of loop, what's left is the final element's name
Element last = new Element(name);
last.setText(propertyValue);
/** Uncomment this for Attribute usage */
/*
last.setAttribute("value", propertyValue);
*/
current.addContent(last);
}
}
/*--
Copyright (C) 2001 Brett McLaughlin.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the disclaimer that follows
these conditions in the documentation and/or other materials
provided with the distribution.
3. The name "Java and XML" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact brett@newInstance.com.
In addition, we request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
"This product includes software developed for the
'Java and XML' book, by Brett McLaughlin (O'Reilly & Associates)."
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
/**
* <b><code>TestXMLProperties</code></b> is a simple class that tests
* usage of the <code>{@link XMLProperties}</code> class for reading
* XML property files.
*/
class TestXMLProperties {
/**
* <p>Provide a static entry point for testing.</p>
*/
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java TestXMLProperties " +
"[XML input document] [XML output document]");
System.exit(0);
}
try {
// Create and load properties
System.out.println("Reading XML properties from " + args[0]);
XMLProperties props = new XMLProperties();
props.load(new FileInputStream(args[0]));
// Print out properties and values
System.out.println("\n\n---- Property Values ----");
Enumeration names = props.propertyNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
String value = props.getProperty(name);
System.out.println("Property Name: " + name +
" has value " + value);
}
// Store properties
System.out.println("\n\nWriting XML properies to " + args[1]);
props.store(new FileOutputStream(args[1]),
"Testing XMLProperties class");
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Demo file: enhydra.properties
/*
#
# This file has several Enhydra-specific properties
# to make available to Java programs running with
# knowledge of this properties file.
#
# sax parser implementing class
org.xml.sax.parser="org.apache.xerces.parsers.SAXParser"
# Class used to start the server
org.enhydra.initialclass=org.enhydra.multiServer.bootstrap.Bootstrap
# initial arguments passed to the server
org.enhydra.initialargs="./bootstrap.conf"
# Classpath for the parent top enhydra classloader
org.enhydra.classpath="."
# separator for the classpath above
org.enhydra.classpath.separator=":"
*/
03.HTML 4.X, HTML5, XML.../XML2010. 2. 19. 18:25
반응형
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.Properties;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.Properties;
import java.util.Enumeration;
import org.apache.xerces.parsers.*;
public class ParseNonXML extends DefaultHandler {
public static void main(String args[]) throws SAXException {
PropertyFileParser pfp = new PropertyFileParser();
pfp.setContentHandler(new ParseNonXML());
pfp.parse(buildProperties());
}
public static Properties buildProperties() {
Properties props = new Properties();
for (int i = 0; i < 10; i++)
props.setProperty("key" + i, "value" + i);
return props;
}
public void startDocument() {
System.out.println("<keys>");
}
public void endDocument() {
System.out.println("</keys>");
}
public void characters(char[] data, int start, int end) {
String str = new String(data, start, end);
System.out.print(str);
}
public void startElement(String uri, String qName, String lName, Attributes atts) {
System.out.print("<" + lName + ">");
}
public void endElement(String uri, String qName, String lName) {
System.out.println("</" + lName + ">");
}
}
class PropertyFileParser extends SAXParser {
private Properties props = null;
private ContentHandler handler = null;
public void parse(Properties props) throws SAXException {
handler = getContentHandler();
handler.startDocument();
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String val = (String) props.getProperty(key);
handler.startElement("", key, key, new AttributesImpl());
char[] chars = getChars(val);
handler.characters(chars, 0, chars.length);
handler.endElement("", key, key);
}
handler.endDocument();
}
private char[] getChars(String value) {
char[] chars = new char[value.length()];
value.getChars(0, value.length(), chars, 0);
return chars;
}
}
import org.xml.sax.helpers.*;
import java.util.Properties;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.Properties;
import java.util.Enumeration;
import org.apache.xerces.parsers.*;
public class ParseNonXML extends DefaultHandler {
public static void main(String args[]) throws SAXException {
PropertyFileParser pfp = new PropertyFileParser();
pfp.setContentHandler(new ParseNonXML());
pfp.parse(buildProperties());
}
public static Properties buildProperties() {
Properties props = new Properties();
for (int i = 0; i < 10; i++)
props.setProperty("key" + i, "value" + i);
return props;
}
public void startDocument() {
System.out.println("<keys>");
}
public void endDocument() {
System.out.println("</keys>");
}
public void characters(char[] data, int start, int end) {
String str = new String(data, start, end);
System.out.print(str);
}
public void startElement(String uri, String qName, String lName, Attributes atts) {
System.out.print("<" + lName + ">");
}
public void endElement(String uri, String qName, String lName) {
System.out.println("</" + lName + ">");
}
}
class PropertyFileParser extends SAXParser {
private Properties props = null;
private ContentHandler handler = null;
public void parse(Properties props) throws SAXException {
handler = getContentHandler();
handler.startDocument();
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String val = (String) props.getProperty(key);
handler.startElement("", key, key, new AttributesImpl());
char[] chars = getChars(val);
handler.characters(chars, 0, chars.length);
handler.endElement("", key, key);
}
handler.endDocument();
}
private char[] getChars(String value) {
char[] chars = new char[value.length()];
value.getChars(0, value.length(), chars, 0);
return chars;
}
}
03.HTML 4.X, HTML5, XML.../XML2010. 2. 19. 18:24
반응형
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainClass {
public static void main(String[] args) {
try {
Class.forName("COM.cloudscape.core.JDBCDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:cloudscape:GAMETRADER");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM tableName");
while (rs.next()) {
int id = rs.getInt("ID");
InputStream bis = rs.getAsciiStream("MANUAL");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int ch = 0;
while ((ch = bis.read()) != -1)
bos.write(ch);
System.out.println("GAMEID: " + id + "\n" + "MANUAL: " + new String(bos.toByteArray()));
}
} catch (Throwable e) {
System.out.println("exception thrown");
System.out.println(e);
}
}
}
03.HTML 4.X, HTML5, XML.../XML2010. 2. 19. 18:23
반응형
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class MainClass {
public static void main(String[] args) throws Exception{
Class.forName("COM.cloudscape.core.JDBCDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:cloudscape:GAMETRADER");
conn.setAutoCommit(false);
Statement s = conn.createStatement();
s.executeUpdate("CREATE TABLE MANUALS(GAMEID INT, MANUAL LONG VARCHAR)");
conn.commit();
File file = new File("manuals.xml");
InputStream is = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("INSERT INTO MANUALS VALUES(?,?)");
ps.setInt(1, 1285757);
ps.setAsciiStream(2, is, (int) file.length());
ps.execute();
conn.commit();
}
}
03.HTML 4.X, HTML5, XML.../XML2010. 2. 19. 18:23
반응형
import java.sql.*;
import java.io.*;
import org.apache.xerces.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class XMLDBDOM {
public static void main(String[] args) throws Exception{
Class.forName("COM.cloudscape.core.JDBCDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:cloudscape:GAMETRADER");
conn.setAutoCommit(false);
Statement s = conn.createStatement();
s.executeUpdate("CREATE TABLE XMLData(GAMEID INT, MANUAL SERIALIZE(org.w3c.dom.Document))");
conn.commit();
File file = new File("XMLData.xml");
InputStream is = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("INSERT INTO XMLData VALUES(?,?)");
ps.setInt(1, 1285757);
DOMParser parser = new DOMParser();
parser.parse("XMLData.xml");
Document manual = parser.getDocument();
ps.setObject(2, manual);
ps.execute();
conn.commit();
}
}
import java.io.*;
import org.apache.xerces.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class XMLDBDOM {
public static void main(String[] args) throws Exception{
Class.forName("COM.cloudscape.core.JDBCDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:cloudscape:GAMETRADER");
conn.setAutoCommit(false);
Statement s = conn.createStatement();
s.executeUpdate("CREATE TABLE XMLData(GAMEID INT, MANUAL SERIALIZE(org.w3c.dom.Document))");
conn.commit();
File file = new File("XMLData.xml");
InputStream is = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("INSERT INTO XMLData VALUES(?,?)");
ps.setInt(1, 1285757);
DOMParser parser = new DOMParser();
parser.parse("XMLData.xml");
Document manual = parser.getDocument();
ps.setObject(2, manual);
ps.execute();
conn.commit();
}
}
01.JAVA/Java2010. 2. 19. 18:20
반응형
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("data.xml");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nodes = doc.getElementsByTagName("topic");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("title");
Element line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("data.xml");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nodes = doc.getElementsByTagName("topic");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("title");
Element line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}
98..Etc/velocity2010. 2. 19. 18:19
반응형
import java.io.StringWriter;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class EmailDemo
{
public static void main( String[] args )
throws Exception
{
/*
* first, get and initialize an engine
*/
VelocityEngine ve = new VelocityEngine();
ve.init();
/*
* organize our data
*/
ArrayList list = new ArrayList();
Map map = new HashMap();
map.put("name", "Cow");
map.put("price", "$100.00");
list.add( map );
map = new HashMap();
map.put("name", "Eagle");
map.put("price", "$59.99");
list.add( map );
map = new HashMap();
map.put("name", "Shark");
map.put("price", "$3.99");
list.add( map );
/*
* add that list to a VelocityContext
*/
VelocityContext context = new VelocityContext();
context.put("petList", list);
/*
* get the Template
*/
Template t = ve.getTemplate( "./src/email_xml.vm" );
/*
* now render the template into a Writer, here
* a StringWriter
*/
StringWriter writer = new StringWriter();
t.merge( context, writer );
/*
* use the output in the body of your emails
*/
System.out.println( writer.toString() );
}
}
-------------------------------------------------------------------------------------
<?xml version="1.0"?>
<salelist>
#foreach( $pet in $petList )
<pet>
<name>$pet.name</name>
<price>$pet.price</price>
</pet>
#end
</salelist>
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class EmailDemo
{
public static void main( String[] args )
throws Exception
{
/*
* first, get and initialize an engine
*/
VelocityEngine ve = new VelocityEngine();
ve.init();
/*
* organize our data
*/
ArrayList list = new ArrayList();
Map map = new HashMap();
map.put("name", "Cow");
map.put("price", "$100.00");
list.add( map );
map = new HashMap();
map.put("name", "Eagle");
map.put("price", "$59.99");
list.add( map );
map = new HashMap();
map.put("name", "Shark");
map.put("price", "$3.99");
list.add( map );
/*
* add that list to a VelocityContext
*/
VelocityContext context = new VelocityContext();
context.put("petList", list);
/*
* get the Template
*/
Template t = ve.getTemplate( "./src/email_xml.vm" );
/*
* now render the template into a Writer, here
* a StringWriter
*/
StringWriter writer = new StringWriter();
t.merge( context, writer );
/*
* use the output in the body of your emails
*/
System.out.println( writer.toString() );
}
}
-------------------------------------------------------------------------------------
<?xml version="1.0"?>
<salelist>
#foreach( $pet in $petList )
<pet>
<name>$pet.name</name>
<price>$pet.price</price>
</pet>
#end
</salelist>
98..Etc/velocity2010. 2. 19. 18:18
반응형
/*
* Copyright 2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
/**
* Example to show basic XML handling in a template.
*
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: XMLTest.java,v 1.2.12.1 2004/03/04 00:18:30 geirm Exp $
*/
public class XMLTest
{
public XMLTest( String templateFile)
{
Writer writer = null;
try
{
/*
* and now call init
*/
Velocity.init();
/*
* build a Document from our xml
*/
SAXBuilder builder;
Document root = null;
try
{
builder = new SAXBuilder( "org.apache.xerces.parsers.SAXParser" );
root = builder.build("./src/test.xml");
}
catch( Exception ee)
{
System.out.println("Exception building Document : " + ee);
return;
}
/*
* now, make a Context object and populate it.
*/
VelocityContext context = new VelocityContext();
context.put("root", root);
/*
* make a writer, and merge the template 'against' the context
*/
Template template = Velocity.getTemplate(templateFile);
writer = new BufferedWriter(new OutputStreamWriter(System.out));
template.merge( context , writer);
}
catch( Exception e )
{
System.out.println("Exception : " + e);
}
finally
{
if ( writer != null)
{
try
{
writer.flush();
writer.close();
}
catch( Exception ee )
{
System.out.println("Exception : " + ee );
}
}
}
}
public static void main(String[] args)
{
XMLTest t;
t = new XMLTest("./src/xml.vm");
}
}
-------------------------------------------------------------------------------------
//File: test.xml
<?xml version="1.0" encoding="UTF-8"?>
<document>
<properties>
<author>
<email>velocity-user@jakarta.apache.org</email>
<name>
<last>
<full>Team</full>
<firstinitial>T</firstinitial>
</last>
<first>
Velocity
</first>
</name>
</author>
<title>
The Jakarta Project
</title>
</properties>
<body>
I am the body
</body>
</document>
-------------------------------------------------------------------------------------
//File: xml.vm
#macro ( recursive $e $indent )
#if( $e.getChildren().size() > 0 )
$indent <$e.getName()>
#foreach ($child in $e.getChildren() )
#recursive( $child "$indent " )
#end
$indent </$e.getName()>
#else
$indent <$e.getName()>
$indent $e.getTextTrim()
$indent </$e.getName()>
#end
#end
#set($i = " ")
First, we print out the document tree with a
recursive Velocimacro :
#recursive( $root.getRootElement() $i )
Next, we access pieces of data directly :
email : $root.getRootElement().getChild("properties").getChild("author").getChild("email").getText()
last name : $root.getRootElement().getChild("properties").getChild("author").getChild("name").getChild("last").getChild("full").getText()
* Copyright 2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
/**
* Example to show basic XML handling in a template.
*
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: XMLTest.java,v 1.2.12.1 2004/03/04 00:18:30 geirm Exp $
*/
public class XMLTest
{
public XMLTest( String templateFile)
{
Writer writer = null;
try
{
/*
* and now call init
*/
Velocity.init();
/*
* build a Document from our xml
*/
SAXBuilder builder;
Document root = null;
try
{
builder = new SAXBuilder( "org.apache.xerces.parsers.SAXParser" );
root = builder.build("./src/test.xml");
}
catch( Exception ee)
{
System.out.println("Exception building Document : " + ee);
return;
}
/*
* now, make a Context object and populate it.
*/
VelocityContext context = new VelocityContext();
context.put("root", root);
/*
* make a writer, and merge the template 'against' the context
*/
Template template = Velocity.getTemplate(templateFile);
writer = new BufferedWriter(new OutputStreamWriter(System.out));
template.merge( context , writer);
}
catch( Exception e )
{
System.out.println("Exception : " + e);
}
finally
{
if ( writer != null)
{
try
{
writer.flush();
writer.close();
}
catch( Exception ee )
{
System.out.println("Exception : " + ee );
}
}
}
}
public static void main(String[] args)
{
XMLTest t;
t = new XMLTest("./src/xml.vm");
}
}
-------------------------------------------------------------------------------------
//File: test.xml
<?xml version="1.0" encoding="UTF-8"?>
<document>
<properties>
<author>
<email>velocity-user@jakarta.apache.org</email>
<name>
<last>
<full>Team</full>
<firstinitial>T</firstinitial>
</last>
<first>
Velocity
</first>
</name>
</author>
<title>
The Jakarta Project
</title>
</properties>
<body>
I am the body
</body>
</document>
-------------------------------------------------------------------------------------
//File: xml.vm
#macro ( recursive $e $indent )
#if( $e.getChildren().size() > 0 )
$indent <$e.getName()>
#foreach ($child in $e.getChildren() )
#recursive( $child "$indent " )
#end
$indent </$e.getName()>
#else
$indent <$e.getName()>
$indent $e.getTextTrim()
$indent </$e.getName()>
#end
#end
#set($i = " ")
First, we print out the document tree with a
recursive Velocimacro :
#recursive( $root.getRootElement() $i )
Next, we access pieces of data directly :
email : $root.getRootElement().getChild("properties").getChild("author").getChild("email").getText()
last name : $root.getRootElement().getChild("properties").getChild("author").getChild("name").getChild("last").getChild("full").getText()
98..Etc/velocity2010. 2. 19. 18:17
반응형
|
98..Etc/velocity2010. 2. 19. 18:15
반응형
import java.io.StringWriter;
import java.io.Writer;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class HelloWorldProperties {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("input.encoding", "utf-8");
Velocity.init(props);
Template template = Velocity.getTemplate("./src/HelloWorld.vm");
VelocityContext context = new VelocityContext();
Writer writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
}
-------------------------------------------------------------------------------------
Hello World!
import java.io.Writer;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class HelloWorldProperties {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("input.encoding", "utf-8");
Velocity.init(props);
Template template = Velocity.getTemplate("./src/HelloWorld.vm");
VelocityContext context = new VelocityContext();
Writer writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
}
-------------------------------------------------------------------------------------
Hello World!
98..Etc/velocity2010. 2. 19. 18:14
반응형
import java.io.StringWriter;
import java.io.Writer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.MethodExceptionEventHandler;
import org.apache.velocity.app.event.NullSetEventHandler;
import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
import org.apache.velocity.context.Context;
public class EventHandler implements ReferenceInsertionEventHandler,
NullSetEventHandler, MethodExceptionEventHandler {
public EventHandler(Context ctx) {
EventCartridge ec = new EventCartridge();
ec.addEventHandler(this);
ec.attachToContext(ctx);
}
public Object referenceInsert(String reference, Object data) {
System.out.println("referenceInsert: " + reference + " data: " + data);
return data;
}
public boolean shouldLogOnNullSet(String lhs, String rhs) {
System.out.println("shouldLogOnNullSet");
System.out.println("lhs:" + lhs + " rhs:" + rhs);
return true;
}
public Object methodException(Class cls, String method, Exception e)
throws Exception {
return "An " + e.getClass().getName() + " was thrown by the " + method
+ " method of the " + cls.getName() + " class [" + e.getMessage() + "]";
}
public static void main(String[] args) throws Exception {
Velocity.init();
Template t = Velocity.getTemplate("./src/eventHandler.vm");
Context ctx = new VelocityContext();
ctx.put("person", "Joe");
ctx.put("exception", new ExceptionGenerator());
EventHandler hdl = new EventHandler(ctx);
Writer writer = new StringWriter();
t.merge(ctx, writer);
System.out.println(writer);
}
}
import java.util.Random;
public class ExceptionGenerator {
public String generate() throws Exception {
Random rnd = new Random();
int x = rnd.nextInt(5);
if (x == 2) {
throw new Exception("Unlucky!");
} else {
return "No Exception";
}
}
}
-------------------------------------------------------------------------------------
#set($myNull1 = $validNull)
#set($myNull2 = $invalidNull)
This is $person
$exception.generate()
$exception.generate()
$exception.generate()
$exception.generate()
import java.io.Writer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.MethodExceptionEventHandler;
import org.apache.velocity.app.event.NullSetEventHandler;
import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
import org.apache.velocity.context.Context;
public class EventHandler implements ReferenceInsertionEventHandler,
NullSetEventHandler, MethodExceptionEventHandler {
public EventHandler(Context ctx) {
EventCartridge ec = new EventCartridge();
ec.addEventHandler(this);
ec.attachToContext(ctx);
}
public Object referenceInsert(String reference, Object data) {
System.out.println("referenceInsert: " + reference + " data: " + data);
return data;
}
public boolean shouldLogOnNullSet(String lhs, String rhs) {
System.out.println("shouldLogOnNullSet");
System.out.println("lhs:" + lhs + " rhs:" + rhs);
return true;
}
public Object methodException(Class cls, String method, Exception e)
throws Exception {
return "An " + e.getClass().getName() + " was thrown by the " + method
+ " method of the " + cls.getName() + " class [" + e.getMessage() + "]";
}
public static void main(String[] args) throws Exception {
Velocity.init();
Template t = Velocity.getTemplate("./src/eventHandler.vm");
Context ctx = new VelocityContext();
ctx.put("person", "Joe");
ctx.put("exception", new ExceptionGenerator());
EventHandler hdl = new EventHandler(ctx);
Writer writer = new StringWriter();
t.merge(ctx, writer);
System.out.println(writer);
}
}
import java.util.Random;
public class ExceptionGenerator {
public String generate() throws Exception {
Random rnd = new Random();
int x = rnd.nextInt(5);
if (x == 2) {
throw new Exception("Unlucky!");
} else {
return "No Exception";
}
}
}
-------------------------------------------------------------------------------------
#set($myNull1 = $validNull)
#set($myNull2 = $invalidNull)
This is $person
$exception.generate()
$exception.generate()
$exception.generate()
$exception.generate()
98..Etc/velocity2010. 2. 19. 18:13
반응형
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class VMDemo {
public static void main(String[] args) throws Exception {
Velocity.init();
Template t = Velocity.getTemplate("./src/VMDemo.vm");
VelocityContext ctx = new VelocityContext();
ctx.put("aDate",new Date());
Writer writer = new StringWriter();
t.merge(ctx, writer);
System.out.println(writer);
}
}
-------------------------------------------------------------------------------------
Hello $aaDate.getDate()
import java.io.Writer;
import java.util.Date;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class VMDemo {
public static void main(String[] args) throws Exception {
Velocity.init();
Template t = Velocity.getTemplate("./src/VMDemo.vm");
VelocityContext ctx = new VelocityContext();
ctx.put("aDate",new Date());
Writer writer = new StringWriter();
t.merge(ctx, writer);
System.out.println(writer);
}
}
-------------------------------------------------------------------------------------
Hello $aaDate.getDate()
98..Etc/velocity2010. 2. 19. 18:11
반응형
import java.io.StringWriter;
import java.io.Writer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class ResourceLoaders {
private static final String FILE_RESOURCE_LOADER_TEMPLATE = "./src/ResourceLoader1.vm";
private static final String JAR_RESOURCE_LOADER_TEMPLATE = "./src/ResourceLoader2.vm";
private static final String CLASSPATH_RESOURCE_LOADER_TEMPLATE = "./src/ResourceLoader3.vm";
public static void main(String[] args) throws Exception {
processTemplate(FILE_RESOURCE_LOADER_TEMPLATE);
processTemplate(FILE_RESOURCE_LOADER_TEMPLATE);
processTemplate(JAR_RESOURCE_LOADER_TEMPLATE);
processTemplate(JAR_RESOURCE_LOADER_TEMPLATE);
processTemplate(CLASSPATH_RESOURCE_LOADER_TEMPLATE);
processTemplate(CLASSPATH_RESOURCE_LOADER_TEMPLATE);
}
private static void processTemplate(String templateName) throws Exception {
Velocity.init();
Template template = Velocity.getTemplate(templateName);
VelocityContext context = new VelocityContext();
Writer writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
}
-------------------------------------------------------------------------------------
//File: ResourceLoader1.vm
ResourceLoader1 Template!
//File: ResourceLoader2.vm
ResourceLoader2 Template Modified!
//File: ResourceLoader3.vm
ResourceLoader3 Template 3
import java.io.Writer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class ResourceLoaders {
private static final String FILE_RESOURCE_LOADER_TEMPLATE = "./src/ResourceLoader1.vm";
private static final String JAR_RESOURCE_LOADER_TEMPLATE = "./src/ResourceLoader2.vm";
private static final String CLASSPATH_RESOURCE_LOADER_TEMPLATE = "./src/ResourceLoader3.vm";
public static void main(String[] args) throws Exception {
processTemplate(FILE_RESOURCE_LOADER_TEMPLATE);
processTemplate(FILE_RESOURCE_LOADER_TEMPLATE);
processTemplate(JAR_RESOURCE_LOADER_TEMPLATE);
processTemplate(JAR_RESOURCE_LOADER_TEMPLATE);
processTemplate(CLASSPATH_RESOURCE_LOADER_TEMPLATE);
processTemplate(CLASSPATH_RESOURCE_LOADER_TEMPLATE);
}
private static void processTemplate(String templateName) throws Exception {
Velocity.init();
Template template = Velocity.getTemplate(templateName);
VelocityContext context = new VelocityContext();
Writer writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
}
-------------------------------------------------------------------------------------
//File: ResourceLoader1.vm
ResourceLoader1 Template!
//File: ResourceLoader2.vm
ResourceLoader2 Template Modified!
//File: ResourceLoader3.vm
ResourceLoader3 Template 3