DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Coding Topics

article thumbnail
CSS3 Optical Illusions
today i have prepared something interesting for you. this is a demonstration of several optical illusions in css3 (without using any images or javascript). enjoy the results. here are samples and downloadable package: live demo download in package ok, download the example files and let's start coding! step 1. html as usual, we start with the html. here is full html code of all 6 demos. index.html css3 optical illusions back to original tutorial on script tutorials 1 2 3 4 5 6 38 38 step 2. css here are the css styles. maybe you’ve noticed that in our html i have two css files: layout.css and illusions.css. the first file (layout.css) contain the styles of our test page. we will not publish these styles in this article, but if you wish – you can find these styles in our package. css/illusions.css span { display: none; } .contr { color: #000000; cursor: pointer; float: left; font-size: 16px; font-weight: bold; height: 30px; line-height: 30px; margin: 10px; text-align: center; text-decoration: none; width: 60px; -webkit-border-radius:10px; -moz-border-radius:10px; -ms-border-radius:10px; -o-border-radius:10px; border-radius:10px; background-color:#e3e3ff; background: -moz-linear-gradient(#ffffff, #eee); background: -ms-linear-gradient(#ffffff, #eee); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #eee)); background: -webkit-linear-gradient(#ffffff, #eee); background: -o-linear-gradient(#ffffff, #eee); filter: progid:dximagetransform.microsoft.gradient(startcolorstr='#ffffff', endcolorstr='#eee'); -ms-filter: "progid:dximagetransform.microsoft.gradient(startcolorstr='#ffffff', endcolorstr='#eee')"; background: linear-gradient(#ffffff, #eee); } .contr:hover{ background-color:#e3e3ff; box-shadow:0px 0px 4px rgba(0,0,0,0.5) inset, 0px 0px 0px 4px rgba(51,51,204,0.5); -moz-box-shadow:0px 0px 4px rgba(0,0,0,0.5) inset, 0px 0px 0px 4px rgba(51,51,204,0.5); -webkit-box-shadow:0px 0px 4px rgba(0,0,0,0.5) inset, 0px 0px 0px 4px rgba(51,51,204,0.5); } .demos { background-color: #b2b2b2; display: block; height: 640px; margin-top: 55px; overflow: hidden; position: relative; } .demos > div { display: none; } #page1:target ~ .demos #i1 { display: block; } #page2:target ~ .demos #i2 { display: block; } #page3:target ~ .demos #i3 { display: block; } #page4:target ~ .demos #i4 { display: block; } #page5:target ~ .demos #i5 { display: block; } #page6:target ~ .demos #i6 { display: block; } /* illusion 1 */ #i1 { width: 900px; } #i1 .row { background-color: #fff; border-bottom: 2px solid #888; height: 90px; -webkit-background-size: 140px 70px; -moz-background-size: 140px 70px; -ms-background-size: 140px 70px; -o-background-size: 140px 70px; background-size: 140px 70px; background-position: 0 50%; background-image: -webkit-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: -moz-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: -ms-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: -o-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: linear-gradient(0deg, #000 50%, transparent 50%, transparent); } #i1 .row:nth-child(3n+3) { background-position: 60px 50%; } #i1 .row:nth-child(2n+2) { background-position: 30px 50%; } /* illusion 2 */ #i2 { background-color: #98cb00; height: 640px; margin: 0 auto; overflow: hidden; padding: 0 150px; position: relative; width: 600px; } #i2 > div { float: left; height: 105px; padding-left: 90px; padding-top: 90px; position: relative; width: 105px; } #i2 div div { border: 1px outset #fff; height: 20px; position: absolute; width: 30px; -webkit-border-radius: 100px / 50px; -moz-border-radius: 100px / 50px; -ms-border-radius: 100px / 50px; -o-border-radius: 100px / 50px; border-radius: 100px / 50px; background: -webkit-linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); background: -moz-linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); background: -ms-linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); background: -o-linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); background: linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); } #i2 #o1 { -webkit-transform: rotate(-30deg) translatex(70px); -moz-transform: rotate(-30deg) translatex(70px); -ms-transform: rotate(-30deg) translatex(70px); -o-transform: rotate(-30deg) translatex(70px); transform: rotate(-30deg) translatex(70px); } #i2 #o2 { -webkit-transform: rotate(-60deg) translatex(70px); -moz-transform: rotate(-60deg) translatex(70px); -ms-transform: rotate(-60deg) translatex(70px); -o-transform: rotate(-60deg) translatex(70px); transform: rotate(-60deg) translatex(70px); } #i2 #o3 { -webkit-transform: rotate(-90deg) translatex(70px); -moz-transform: rotate(-90deg) translatex(70px); -ms-transform: rotate(-90deg) translatex(70px); -o-transform: rotate(-90deg) translatex(70px); transform: rotate(-90deg) translatex(70px); } #i2 #o4 { -webkit-transform: rotate(-120deg) translatex(70px); -moz-transform: rotate(-120deg) translatex(70px); -ms-transform: rotate(-120deg) translatex(70px); -o-transform: rotate(-120deg) translatex(70px); transform: rotate(-120deg) translatex(70px); } #i2 #o5 { -webkit-transform: rotate(-150deg) translatex(70px); -moz-transform: rotate(-150deg) translatex(70px); -ms-transform: rotate(-150deg) translatex(70px); -o-transform: rotate(-150deg) translatex(70px); transform: rotate(-150deg) translatex(70px); } #i2 #o6 { -webkit-transform: rotate(-180deg) translatex(70px); -moz-transform: rotate(-180deg) translatex(70px); -ms-transform: rotate(-180deg) translatex(70px); -o-transform: rotate(-180deg) translatex(70px); transform: rotate(-180deg) translatex(70px); } #i2 #o7 { -webkit-transform: rotate(-210deg) translatex(70px); -moz-transform: rotate(-210deg) translatex(70px); -ms-transform: rotate(-210deg) translatex(70px); -o-transform: rotate(-210deg) translatex(70px); transform: rotate(-210deg) translatex(70px); } #i2 #o8 { -webkit-transform: rotate(-240deg) translatex(70px); -moz-transform: rotate(-240deg) translatex(70px); -ms-transform: rotate(-240deg) translatex(70px); -o-transform: rotate(-240deg) translatex(70px); transform: rotate(-240deg) translatex(70px); } #i2 #o9 { -webkit-transform: rotate(-270deg) translatex(70px); -moz-transform: rotate(-270deg) translatex(70px); -ms-transform: rotate(-270deg) translatex(70px); -o-transform: rotate(-270deg) translatex(70px); transform: rotate(-270deg) translatex(70px); } #i2 #o10 { -webkit-transform: rotate(-300deg) translatex(70px); -moz-transform: rotate(-300deg) translatex(70px); -ms-transform: rotate(-300deg) translatex(70px); -o-transform: rotate(-300deg) translatex(70px); transform: rotate(-300deg) translatex(70px); } #i2 #o11 { -webkit-transform: rotate(-330deg) translatex(70px); -moz-transform: rotate(-330deg) translatex(70px); -ms-transform: rotate(-330deg) translatex(70px); -o-transform: rotate(-330deg) translatex(70px); transform: rotate(-330deg) translatex(70px); } #i2 #o12 { -webkit-transform: rotate(0deg) translatex(70px); -moz-transform: rotate(0deg) translatex(70px); -ms-transform: rotate(0deg) translatex(70px); -o-transform: rotate(0deg) translatex(70px); transform: rotate(0deg) translatex(70px); } /* illusion 3 */ #i3 { color: #000000; font-family: times new roman; font-size: 250px; padding-left: 300px; } #i3 .rev { text-align: right; -webkit-transform: rotate(-180deg); -moz-transform: rotate(-180deg); -ms-transform: rotate(-180deg); -o-transform: rotate(-180deg); transform: rotate(-180deg); } /* illusion 4 */ #i4 .row { background-color: #fff; border-bottom: 5px solid #fff; height: 50px; -webkit-background-size: 60px 50px; -moz-background-size: 60px 50px; -ms-background-size: 60px 50px; -o-background-size: 60px 50px; background-size: 60px 50px; background-position: 0 50%; background-image: -webkit-linear-gradient(0deg, #000 90%, transparent 10%, transparent); background-image: -moz-linear-gradient(0deg, #000 90%, transparent 10%, transparent); background-image: -ms-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: -o-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: linear-gradient(0deg, #000 50%, transparent 50%, transparent); } /* illusion 5 */ @-webkit-keyframes custom_effect { 0% {opacity: 0;} 33% {opacity: 1;} 100% {opacity: 1;} } @-moz-keyframes custom_effect { 0% {opacity: 0;} 33% {opacity: 1;} 100% {opacity: 1;} } #i5 { background-color: #b2b2b2; height: 600px; margin: 0 auto; overflow: hidden; position: relative; width: 600px; } #i5 > div { float: left; height: 200px; padding-left: 200px; padding-top: 200px; position: relative; width: 200px; } #i5 div div { height: 50px; position: absolute; width: 50px; -webkit-border-radius: 50px; -moz-border-radius: 50px; -ms-border-radius: 50px; -o-border-radius: 50px; border-radius: 50px; background-color: #b2b2b2; background-image: -webkit-radial-gradient(50% 50%, circle, #fd19fd, #b2b2b2 70%); background-image: -moz-radial-gradient(50% 50%, circle, #fd19fd, #b2b2b2 70%); background-image: -o-radial-gradient(50% 50%, circle, #fd19fd, #b2b2b2 70%); background-image: radial-gradient(50% 50%, circle, #fd19fd, #b2b2b2 70%); -moz-animation-name: custom_effect; -moz-animation-duration: 1.2s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; -webkit-animation-name: custom_effect; -webkit-animation-duration: 1.2s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; } #i5 #o1 { -moz-transform: rotate(30deg) translatex(150px); -moz-animation-delay: 0.1s; -webkit-transform: rotate(30deg) translatex(150px); -webkit-animation-delay: 0.1s; } #i5 #o2 { -moz-transform: rotate(60deg) translatex(150px); -moz-animation-delay: 0.2s; -webkit-transform: rotate(60deg) translatex(150px); -webkit-animation-delay: 0.2s; } #i5 #o3 { -moz-transform: rotate(90deg) translatex(150px); -moz-animation-delay: 0.3s; -webkit-transform: rotate(90deg) translatex(150px); -webkit-animation-delay: 0.3s; } #i5 #o4 { -moz-transform: rotate(120deg) translatex(150px); -moz-animation-delay: 0.4s; -webkit-transform: rotate(120deg) translatex(150px); -webkit-animation-delay: 0.4s; } #i5 #o5 { -moz-transform: rotate(150deg) translatex(150px); -moz-animation-delay: 0.5s; -webkit-transform: rotate(150deg) translatex(150px); -webkit-animation-delay: 0.5s; } #i5 #o6 { -moz-transform: rotate(180deg) translatex(150px); -moz-animation-delay: 0.6s; -webkit-transform: rotate(180deg) translatex(150px); -webkit-animation-delay: 0.6s; } #i5 #o7 { -moz-transform: rotate(210deg) translatex(150px); -moz-animation-delay: 0.7s; -webkit-transform: rotate(210deg) translatex(150px); -webkit-animation-delay: 0.7s; } #i5 #o8 { -moz-transform: rotate(240deg) translatex(150px); -moz-animation-delay: 0.8s; -webkit-transform: rotate(240deg) translatex(150px); -webkit-animation-delay: 0.8s; } #i5 #o9 { -moz-transform: rotate(270deg) translatex(150px); -moz-animation-delay: 0.9s; -webkit-transform: rotate(270deg) translatex(150px); -webkit-animation-delay: 0.9s; } #i5 #o10 { -moz-transform: rotate(300deg) translatex(150px); -moz-animation-delay: 1.0s; -webkit-transform: rotate(300deg) translatex(150px); -webkit-animation-delay: 1.0s; } #i5 #o11 { -moz-transform: rotate(330deg) translatex(150px); -moz-animation-delay: 1.1s; -webkit-transform: rotate(330deg) translatex(150px); -webkit-animation-delay: 1.1s; } #i5 #o12 { -moz-transform: rotate(0deg) translatex(150px); -moz-animation-delay: 1.2s; -webkit-transform: rotate(0deg) translatex(150px); -webkit-animation-delay: 1.2s; } /* illusion 5 */ #i6 { background-color: #3f023e; height: 640px; margin: 0 auto; overflow: hidden; padding-left: 120px; position: relative; width: 900px; } #i6 .yellow { background-color: #b9bd04; background-image: -webkit-radial-gradient(50% 50%, circle, #fff531 40%, #b9bd04 80%); background-image: -moz-radial-gradient(50% 50%, circle, #fff531 40%, #b9bd04 80%); background-image: -o-radial-gradient(50% 50%, circle, #fff531 40%, #b9bd04 80%); background-image: radial-gradient(50% 50%, circle, #fff531 40%, #b9bd04 80%); } #i6 .pink { background-color: #f101e8; background-image: -webkit-radial-gradient(50% 50%, circle, #0e0403 40%, #f101e8 80%); background-image: -moz-radial-gradient(50% 50%, circle, #0e0403 40%, #f101e8 80%); background-image: -o-radial-gradient(50% 50%, circle, #0e0403 40%, #f101e8 80%); background-image: radial-gradient(50% 50%, circle, #0e0403 40%, #f101e8 80%); } #i6 > div { float: left; height: 320px; position: relative; width: 320px; } #i6 .r1 { height: 320px; position: absolute; width: 320px; -webkit-border-radius: 320px; -moz-border-radius: 320px; -ms-border-radius: 320px; -o-border-radius: 320px; border-radius: 320px; } #i6 .r2 { height: 240px; left: 40px; position: absolute; top: 40px; width: 240px; -webkit-border-radius: 240px; -moz-border-radius: 240px; -ms-border-radius: 240px; -o-border-radius: 240px; border-radius: 240px; } #i6 .r3 { height: 160px; left: 40px; position: absolute; top: 40px; width: 160px; -webkit-border-radius: 160px; -moz-border-radius: 160px; -ms-border-radius: 160px; -o-border-radius: 160px; border-radius: 160px; } #i6 .r4 { height: 80px; left: 40px; position: absolute; top: 40px; width: 80px; -webkit-border-radius: 80px; -moz-border-radius: 80px; -ms-border-radius: 80px; -o-border-radius: 80px; border-radius: 80px; } this is very big pack of styles, but i hope that this is ok. i have used several different css3 techniques: and keyframe animation, and transform rotate, and sometimes – gradients. live demo download in package conclusion hope you enjoyed the new demo. don’t forget to give thanks and leave a comment good luck! source: http://www.script-tutorials.com/css3-optical-illusions/
January 5, 2012
by Andrei Prikaznov
· 8,290 Views
article thumbnail
Different SOAP encoding styles – RPC, RPC-literal, and document-literal
SOAP uses XML to marshal data that is transported to a software application. Since SOAP’s introduction, three SOAP encoding styles have become popular and are reliably implemented across software vendors and technology providers: SOAP Remote Procedure Call (RPC) encoding, also known as Section 5 encoding, which is defined by the SOAP 1.1 specification SOAP Remote Procedure Call Literal encoding (SOAP RPC-literal), which uses RPC methods to make calls but uses an XML do-it-yourself method for marshalling the data SOAP document-style encoding, which is also known as message-style or document-literal encoding. There are other encoding styles, but software developers have not widely adopted them, mostly because their promoters disagree on a standard. For example, Microsoft is promoting Direct Internet Message Exchange (DIME) to encode binary file data, while the rest of the world is promoting SOAP with Attachments. SOAP RPC encoding, RPC-literal, and document-style SOAP encoding have emerged as the encoding styles that a software developer can count on. SOAP RPC is the encoding style that offers you the most simplicity. You make a call to a remote object, passing along any necessary parameters. The SOAP stack serializes the parameters into XML, moves the data to the destination using transports such as HTTP and SMTP, receives the response, deserializes the response back into objects, and returns the results to the calling method. Whew! SOAP RPC handles all the encoding and decoding, even for very complex data types, and binds to the remote object automatically. Now, imagine that you have some data already in XML format. SOAP RPC also allows literal encoding of the XML data as a single field that is serialized and sent to the Web service host. This is what’s referred to as RPC-literal encoding. Since there is only one parameter — the XML tree — the SOAP stack only needs to serialize one value. The SOAP stack still deals with the transport issues to get the request to the remote object. The stack binds the request to the remote object and handles the response. Lastly, in a SOAP document-style call, the SOAP stack sends an entire XML document to a server without even requiring a return value. The message can contain any sort of XML data that is appropriate to the remote service. In SOAP document-style encoding, the developer handles everything, including determining the transport (e.g., HTTP, MQ, SMTP), marshaling and unmarshaling the body of the SOAP envelope, and parsing the XML in the request and response to find the needed data. The three encoding systems are compared here: SOAP RPC encoding is easiest for the software developer; however, all that ease comes with a scalability and performance penalty. In SOAP RPC-literal encoding, you are more involved with handling XML parsing, but it requires there to be overhead for the SOAP stack to deal with. SOAP document-literal encoding is most difficult for the software developer, but consequently requires little SOAP overhead. Why is SOAP RPC easier? With this encoding style, you only need to define the public object method in your code once; the SOAP stack unmarshals the request parameters into objects and passes them directly into the method call of your object. Otherwise, you are stuck with the task of parsing through the XML tree to find the data elements you need before you get to make the call to the public method. There is an argument for parsing the XML data yourself: since you know the data in the XML tree best, your code will parse that data more efficiently than generalized SOAP stack code. You will find this when measuring scalability and performance in SOAP encoding styles. References: 1. Discover SOAP encoding’s impact on Web service performance (http://www.ibm.com/developerworks/webservices/library/ws-soapenc/) From http://singztechmusings.wordpress.com/2011/12/20/different-soap-encoding-styles-rpc-rpc-literal-and-document-literal/
January 4, 2012
by Singaram Subramanian
· 49,902 Views · 2 Likes
article thumbnail
Java: How to Save / Download a File Available at a Particular URL Location on the Internet?
package singz.test; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.FileUtils; /* * @author Singaram Subramanian */ public class FileDownloadTest { public static void main(String[] args) { // Make sure that this directory exists String dirName = "C:\\FileDownload"; try { System.out.println("Downloading \'Maven, Eclipse and OSGi working together\' PDF document..."); saveFileFromUrlWithJavaIO( dirName + "\\maven_eclipse_and_osgi_working_together.pdf", "http://singztechmusings.files.wordpress.com/2011/09/maven_eclipse_and_osgi_working_together.pdf"); System.out.println("Downloaded \'Maven, Eclipse and OSGi working together\' PDF document."); System.out.println("Downloading \'InnoQ Web Services Standards Poster\' PDF document..."); saveFileFromUrlWithCommonsIO( dirName + "\\innoq_ws-standards_poster_2007-02.pdf", "http://singztechmusings.files.wordpress.com/2011/08/innoq_ws-standards_poster_2007-02.pdf"); System.out.println("Downloaded \'InnoQ Web Services Standards Poster\' PDF document."); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // Using Java IO public static void saveFileFromUrlWithJavaIO(String fileName, String fileUrl) throws MalformedURLException, IOException { BufferedInputStream in = null; FileOutputStream fout = null; try { in = new BufferedInputStream(new URL(fileUrl).openStream()); fout = new FileOutputStream(fileName); byte data[] = new byte[1024]; int count; while ((count = in.read(data, 0, 1024)) != -1) { fout.write(data, 0, count); } } finally { if (in != null) in.close(); if (fout != null) fout.close(); } } // Using Commons IO library // Available at http://commons.apache.org/io/download_io.cgi public static void saveFileFromUrlWithCommonsIO(String fileName, String fileUrl) throws MalformedURLException, IOException { FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName)); } } From http://singztechmusings.wordpress.com/2011/12/20/java-how-to-save-download-a-file-available-at-a-particular-url-location-in-internet/
January 3, 2012
by Singaram Subramanian
· 148,527 Views
article thumbnail
Styling a JavaFX Control with CSS
Change the look and feel of any JavaFX control using CSS.
January 2, 2012
by Toni Epple
· 97,054 Views · 1 Like
article thumbnail
JAXB, SAX, DOM Performance
This post investigates the performance of unmarshalling an XML document to Java objects using a number of different approaches. The XML document is very simple. It contains a collection of Person entities. person0 name0 person1 name1 ... There is a corresponding Person Java object for the Person entity in the XML ... @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "id", "name" }) public class Person { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String value) { this.name = value; } } and a PersonList object to represent a collection of Persons. @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "persons") public class PersonList { @XmlElement(name="person") private List personList = new ArrayList(); public List getPersons() { return personList; } public void setPersons(List persons) { this.personList = persons; } } The approaches investigated were: Various flavours of JAXB SAX DOM In all cases, the objective was to get the entities in the XML document to the corresponding Java objects. The JAXB annotations on the Person and PersonList POJOS are used in the JAXB tests. The same classes can be used in SAX and DOM tests (the annotations will just be ignored). Initially the reference implementations for JAXB, SAX and DOM were used. The Woodstox STAX parsing was then used. This would have been called in some of the JAXB unmarshalling tests. The tests were carried out on my Dell Laptop, a Pentium Dual-Core CPU, 2.1 GHz running Windows 7. Test 1 - Using JAXB to unmarshall a Java File. @Test public void testUnMarshallUsingJAXB() throws Exception { JAXBContext jc = JAXBContext.newInstance(PersonList.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); PersonList obj = (PersonList)unmarshaller.unmarshal(new File(filename)); } Test 1 illustrates how simple the progamming model for JAXB is. It is very easy to go from an XML file to Java objects. There is no need to get involved with the nitty gritty details of marshalling and parsing. Test 2 - Using JAXB to unmarshall a Streamsource Test 2 is similar Test 1, except this time a Streamsource object wraps around a File object. The Streamsource object gives a hint to the JAXB implementation to stream the file. @Test public void testUnMarshallUsingJAXBStreamSource() throws Exception { JAXBContext jc = JAXBContext.newInstance(PersonList.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); StreamSource source = new StreamSource(new File(filename)); PersonList obj = (PersonList)unmarshaller.unmarshal(source); } Test 3 - Using JAXB to unmarshall a StAX XMLStreamReader Again similar to Test 1, except this time an XMLStreamReader instance wraps a FileReader instance which is unmarshalled by JAXB. @Test public void testUnMarshallingWithStAX() throws Exception { FileReader fr = new FileReader(filename); JAXBContext jc = JAXBContext.newInstance(PersonList.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); XMLInputFactory xmlif = XMLInputFactory.newInstance(); XMLStreamReader xmler = xmlif.createXMLStreamReader(fr); PersonList obj = (PersonList)unmarshaller.unmarshal(xmler); } Test 4 - Just use DOM This test uses no JAXB and instead just uses the JAXP DOM approach. This means straight away more code is required than any JAXB approach. @Test public void testParsingWithDom() throws Exception { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(filename); List personsAsList = new ArrayList(); NodeList persons = doc.getElementsByTagName("person"); for (int i = 0; i persons = new ArrayList(); DefaultHandler handler = new DefaultHandler() { boolean bpersonId = false; boolean bpersonName = false; public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("id")) { bpersonId = true; Person person = new Person(); persons.add(person); } else if (qName.equalsIgnoreCase("name")) { bpersonName = true; } } public void endElement(String uri, String localName, String qName) throws SAXException { } public void characters(char ch[], int start, int length) throws SAXException { if (bpersonId) { String personID = new String(ch, start, length); bpersonId = false; Person person = persons.get(persons.size() - 1); person.setId(personID); } else if (bpersonName) { String name = new String(ch, start, length); bpersonName = false; Person person = persons.get(persons.size() - 1); person.setName(name); } } }; saxParser.parse(filename, handler); } The tests were run 5 times for 3 files which contain a collection of Person entities. The first first file contained 100 Person entities and was 5K in size. The second contained 10,000 entities and was 500K in size and the third contained 250,000 Person entities and was 15 Meg in size. In no cases was any XSD used, or any validations performed. The results are given in result tables where the times for the different runs are comma separated. TEST RESULTS The tests were first run using JDK 1.6.26, 32 bit and the reference implementation for SAX, DOM and JAXB shipped with JDK was used. Unmarshall Type 100 Persons time (ms) 10K Persons time (ms) 250K Persons time (ms) JAXB (Default) 48,13, 5,4,4 78, 52, 47,50,50 1522, 1457, 1353, 1308,1317 JAXB(Streamsource) 11, 6, 3,3,2 44, 44, 48,45,43 1191, 1364, 1144, 1142, 1136 JAXB (StAX) 18, 2,1,1,1 111, 136, 89,91,92 2693, 3058, 2495, 2472, 2481 DOM 16, 2, 2,2,2 89,50, 55,53,50 1992, 2198, 1845, 1776, 1773 SAX 4, 2, 1,1,1 29, 34, 23,26,26 704, 669, 605, 589,591 JDK 1.6.26 Test comments The first time unmarshalling happens is usually the longest. The memory usage for the JAXB and SAX is similar. It is about 2 Meg for the file with 10,000 persons and 36 - 38 Meg file with 250,000. DOM Memory usage is far higher. For the 10,000 persons file it is 6 Meg, for the 250,000 person file it is greater than 130 Meg. The performance times for pure SAX are better. Particularly, for very large files. The exact same tests were run again, using the same JDK (1.6.26) but this time the Woodstox implementation of StAX parsing was used. Unmarshall Type 100 Persons time (ms) 10K Persons time (ms) 250K Persons time (ms) JAXB (Default) 48,13, 5,4,4 78, 52, 47,50,50 1522, 1457, 1353, 1308,1317 JAXB(Streamsource) 11, 6, 3,3,2 44, 44, 48,45,43 1191, 1364, 1144, 1142, 1136 JAXB (StAX) 18, 2,1,1,1 111, 136, 89,91,92 2693, 3058, 2495, 2472, 2481 DOM 16, 2, 2,2,2 89,50, 55,53,50 1992, 2198, 1845, 1776, 1773 SAX 4, 2, 1,1,1 29, 34, 23,26,26 704, 669, 605, 589,591 JDK 1.6.26 + Woodstox test comments Again, the first time unmarshalling happens is usually proportionally longer. Again, memory usage for SAX and JAXB is very similar. Both are far better than DOM. The results are very similar to Test 1. The JAXB (StAX) approach time has improved considerably. This is due to the Woodstox implementation of StAX parsing being used. The performance times for pure SAX are still the best. Particularly for large files. The the exact same tests were run again, but this time I used JDK 1.7.02 and the Woodstox implementation of StAX parsing. Unmarshall Type 100 Persons time (ms) 10,000 Persons time (ms) 250,000 Persons time (ms) JAXB (Default) 165,5, 3, 3,5 611,23, 24, 46, 28 578, 539, 511, 511, 519 JAXB(Streamsource) 13,4, 3, 4, 3 43,24, 21, 26, 22 678, 520, 509, 504, 627 JAXB (StAX) 21,1,0, 0, 0 300,69, 20, 16, 16 637, 487, 422, 435, 458 DOM 22,2,2,2,2 420,25, 24, 23, 24 1304, 807, 867, 747, 1189 SAX 7,2,2,1,1 169,15, 15, 19, 14 366, 364, 363, 360, 358 JDK 7 + Woodstox test comments: The performance times for JDK 7 overall are much better. There are some anomolies - the first time the 100 persons and the 10,000 person file is parsed. The memory usage is slightly higher. For SAX and JAXB it is 2 - 4 Meg for the 10,000 persons file and 45 - 49 Meg for the 250,000 persons file. For DOM it is higher again. 5 - 7.5 Meg for the 10,000 person file and 136 - 143 Meg for the 250,000 persons file. Note: W.R.T. all tests No memory analysis was done for the 100 persons file. The memory usage was just too small and so it would have pointless information. The first time to initialise a JAXB context can take up to 0.5 seconds. This was not included in the test results as it only took this time the very first time. After that the JVM initialises context very quickly (consistly < 5ms). If you notice this behaviour with whatever JAXB implementation you are using, consider initialising at start up. These tests are a very simple XML file. In reality there would be more object types and more complex XML. However, these tests should still provide a guidance. Conclusions: The peformance times for pure SAX are slightly better than JAXB but only for very large files. Unless you are using very large files the performance differences are not worth worrying about. The progamming model advantages of JAXB win out over the complexitiy of the SAX programming model. Don't forget JAXB also provides random accses like DOM does. SAX does not provide this. Performance times look a lot better with Woodstox, if JAXB / StAX is being used. Performance times with 64 bit JDK 7 look a lot better. Memory usuage looks slightly higher. From http://dublintech.blogspot.com/2011/12/jaxb-sax-dom-performance.html
December 31, 2011
by Alex Staveley
· 47,468 Views · 4 Likes
article thumbnail
What are the differences between JAXB 1.0 and JAXB 2.0
What are the differences between JAXB 1.0 and JAXB 2.0? JAXB 1.0 only requires JDK 1.3 or later. JAXB 2.0 requires JDK 1.5 or later. JAXB 2.0 makes use of generics and thus provides compile time type safety checking thus reducing runtime errors. Validation is only available during marshalling in JAXB 1.0. Validation is also available during unmarshalling in JAXB 2.0. Termination occurs in JAXB 1.0 when a validation error occurs. In JAXB 2.0 custom ValidationEventHandlers can be used to deal with validation errors. JAXB 2.0 uses annotations and supports bi-directional mapping. JAXB 2.0 generates less code. JAXB 1.0 does not support key XML Schema components like anyAttribute, key, keyref, and unique. It also does not support attributes like complexType.abstract, element.abstract, element.substitutionGroup, xsi:type, complexType.block, complexType.final, element.block, element.final, schema.blockDefault, and schema.finalDefault. In version 2.0, support has been added for all of these schema constructs. References: http://javaboutique.internet.com/tutorials/jaxb/index3.html From http://dublintech.blogspot.com/2011/04/what-are-differences-between-jaxb-10.html
December 30, 2011
by Alex Staveley
· 15,413 Views
article thumbnail
XML Schema to Java - Generating XmlAdapters
In previous posts I have demonstrated how powerful JAXB's XmlAdapter can be when starting from domain objects. In this example I will demonstrate how to leverage an XmlAdapter when generating an object model from an XML schema. This post was inspired by an answer I gave to a question on Stack Overflow (feel free to up vote). XMLSchema (format.xsd) The following is the XML schema that will be used for this example. The interesting portion is a type called NumberCodeValueType. This type has a specified pattern requiring it be a seven digit number. This number can have leading zeros which would not be marshalled by JAXB's default conversion of numbers. NumberFormatter Since JAXB's default number to String algorithm will not match our schema requirements, we will need to write our own formatter. We are required to provide two static methods one that coverts our type to the desired XML format, and another that converts from the XML format. package blog.xmladapter.bindings; public class NumberFormatter { public static String printInt(Integer value) { String result = String.valueOf(value); for(int x=0, length = 7 - result.length(); x XJC Call The bindings file is referenced in the XJC call as: xjc -d out -p blog.xmladapter.bindings -b bindings.xml format.xsd Adapter1 This will cause an XmlAdapter to be created that leverages the formatter: package blog.xmladapter.bindings; import javax.xml.bind.annotation.adapters.XmlAdapter; public class Adapter1 extends XmlAdapter { public Integer unmarshal(String value) { return (blog.xmladapter.bindings.NumberFormatter.parseInt(value)); } public String marshal(Integer value) { return (blog.xmladapter.bindings.NumberFormatter.printInt(value)); } } Root The XmlAdapter will be referenced from the domain object using the @XmlJavaTypeAdapter annotation: package blog.xmladapter.bindings; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "number" }) @XmlRootElement(name = "root") public class Root { @XmlElement(required = true, type = String.class) @XmlJavaTypeAdapter(Adapter1 .class) protected Integer number; public Integer getNumber() { return number; } public void setNumber(Integer value) { this.number = value; } } Demo Now if we run the following demo code: package blog.xmladapter.bindings; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Root.class); Root root = new Root(); root.setNumber(4); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(root, System.out); } } Output We will get the desired output: 0000004 From http://blog.bdoughan.com/2011/08/xml-schema-to-java-generating.html
December 30, 2011
by Blaise Doughan
· 15,472 Views
article thumbnail
HowTo: Build a VNC Client for the Browser
VNC is just a special case of client-server, though perhaps an especially cool one. Quite a few rising web technologies do robust client-server work extra well (Node.js, WebSockets, etc.) -- and in-browser VNC is nothing new. Here are two (open-source, of course): noVNC is more ambitiously HTML5-duplexed, using WebSockets as well as Canvas. It's quite popular, and has its own 10-page Github wiki. Also supports wss:// encryption. Use this if you want a reliable, battle-tested HTML5 client. (WebSocket fallback is provided by web-socket-js.) vnc.js was written in 24 hours, during LinkedIn's first public Intern Hackday. So of course it hasn't been tested thoroughly, and probably could be written a little more cleanly. But there's something beautifully coherent about an app written in a single session. If the app really does work, then some of the decisions will make a little more sense -- it's possible to get into the developer's mind a little more easily -- and breaking down the code doesn't result in as many 'why did they do this??' moments, because the developers' minds were never far from any part of the project, at any moment during development. vnc.js doesn't use WebSockets (it uses Socket.io instead), but that's fine -- a little less HTML5, a little more slick JavaScript doesn't hurt anyone. Plus the marathoning hackers behind vnc.js put together a sweet little tutorial detailing the decisions made that 24-hour period, emphasizing the rapid thought-process behind the architecture (in clear diagrams), and a very practical abstraction for easier in-browser work with TCP (using Node.js and Socket.io) and RFB. Both packages are worth checking out; the hacking tutorial is a fun read for any web developer interested in coding a VNC client, or even just sophisticated with with different network protocols in the browser.
December 30, 2011
by John Esposito
· 19,874 Views
article thumbnail
JAXB and Joda-Time: Dates and Times
Joda-Time provides an alternative to the Date and Calendar classes currently provided in Java SE. Since they are provided in a separate library JAXB does not provide a default mapping for these classes. We can supply the necessary mapping via XmlAdapters. In this post we will cover the following Joda-Time types: DateTime, DateMidnight, LocalDate, LocalTime, LocalDateTime. Java Model The following domain model will be used for this example: package blog.jodatime; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; @XmlRootElement @XmlType(propOrder={ "dateTime", "dateMidnight", "localDate", "localTime", "localDateTime"}) public class Root { private DateTime dateTime; private DateMidnight dateMidnight; private LocalDate localDate; private LocalTime localTime; private LocalDateTime localDateTime; public DateTime getDateTime() { return dateTime; } public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } public DateMidnight getDateMidnight() { return dateMidnight; } public void setDateMidnight(DateMidnight dateMidnight) { this.dateMidnight = dateMidnight; } public LocalDate getLocalDate() { return localDate; } public void setLocalDate(LocalDate localDate) { this.localDate = localDate; } public LocalTime getLocalTime() { return localTime; } public void setLocalTime(LocalTime localTime) { this.localTime = localTime; } public LocalDateTime getLocalDateTime() { return localDateTime; } public void setLocalDateTime(LocalDateTime localDateTime) { this.localDateTime = localDateTime; } } XmlAdapters Since Joda-Time and XML Schema both represent data and time information according to ISO 8601 the implementation of the XmlAdapters is quite trivial. DateTimeAdapter package blog.jodatime; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.joda.time.DateTime; public class DateTimeAdapter extends XmlAdapter{ public DateTime unmarshal(String v) throws Exception { return new DateTime(v); } public String marshal(DateTime v) throws Exception { return v.toString(); } } DateMidnightAdapter package blog.jodatime; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.joda.time.DateMidnight; public class DateMidnightAdapter extends XmlAdapter { public DateMidnight unmarshal(String v) throws Exception { return new DateMidnight(v); } public String marshal(DateMidnight v) throws Exception { return v.toString(); } } LocalDateAdapter package blog.jodatime; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.joda.time.LocalDate; public class LocalDateAdapter extends XmlAdapter{ public LocalDate unmarshal(String v) throws Exception { return new LocalDate(v); } public String marshal(LocalDate v) throws Exception { return v.toString(); } } LocalTimeAdapter package blog.jodatime; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.joda.time.LocalTime; public class LocalTimeAdapter extends XmlAdapter { public LocalTime unmarshal(String v) throws Exception { return new LocalTime(v); } public String marshal(LocalTime v) throws Exception { return v.toString(); } } LocalDateTimeAdapter package blog.jodatime; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.joda.time.LocalDateTime; public class LocalDateTimeAdapter extends XmlAdapter{ public LocalDateTime unmarshal(String v) throws Exception { return new LocalDateTime(v); } public String marshal(LocalDateTime v) throws Exception { return v.toString(); } } Registering the XmlAdapters We will use the @XmlJavaTypeAdapters annotation to register the Joda-Time types at the package level. This means that whenever these types are found on a field/property on a class within this package the XmlAdapter will automatically be applied. @XmlJavaTypeAdapters({ @XmlJavaTypeAdapter(type=DateTime.class, value=DateTimeAdapter.class), @XmlJavaTypeAdapter(type=DateMidnight.class, value=DateMidnightAdapter.class), @XmlJavaTypeAdapter(type=LocalDate.class, value=LocalDateAdapter.class), @XmlJavaTypeAdapter(type=LocalTime.class, value=LocalTimeAdapter.class), @XmlJavaTypeAdapter(type=LocalDateTime.class, value=LocalDateTimeAdapter.class) }) package blog.jodatime; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; Demo To run the following demo you will need the Joda-Time jar on your classpath. It can be obtained here: http://sourceforge.net/projects/joda-time/files/joda-time/ package blog.jodatime; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; public class Demo { public static void main(String[] args) throws Exception { Root root = new Root(); root.setDateTime(new DateTime(2011, 5, 30, 11, 2, 30, 0)); root.setDateMidnight(new DateMidnight(2011, 5, 30)); root.setLocalDate(new LocalDate(2011, 5, 30)); root.setLocalTime(new LocalTime(11, 2, 30)); root.setLocalDateTime(new LocalDateTime(2011, 5, 30, 11, 2, 30)); JAXBContext jc = JAXBContext.newInstance(Root.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(root, System.out); } } Output The following is the output from our demo code: 2011-05-30T11:02:30.000-04:00 2011-05-30T00:00:00.000-04:00 2011-05-30 11:02:30.000 2011-05-30T11:02:30.000 From http://blog.bdoughan.com/2011/05/jaxb-and-joda-time-dates-and-times.html
December 29, 2011
by Blaise Doughan
· 15,775 Views
article thumbnail
Mapping Objects to Multiple XML Schemas - Weather Example
I have written previous posts on EclipseLink JAXB (MOXy)'s @XmlPath and external binding file extensions. In this post I will demonstrate how powerful these extensions are by mapping a single object model to two different XML schemas. To make the example more "real", the XML data will come from two different services that provide weather information: Google and Yahoo. Java Model The following domain model will be used for this post: Weather Report package blog.weather; import java.util.List; public class WeatherReport { private String location; private int currentTemperature; private String currentCondition; private List forecast; } Forecast package blog.weather; public class Forecast { private String dayOfTheWeek; private int low; private int high; private String condition; } Google Weather API First we will leverage Google's Weather API. The following URL will be used to access the weather data for Ottawa, Canada: http://www.google.com/ig/api?weather=Ottawa The following is the result of performing the above query at time I was writing this article. I have highlighted the portions of the XML document that we will map to: Java Model - Mapped to Google's XML Schema via Annotations We will map the result of the Google weather API via a combination of standard JAXB and MOXy extension annotations. Weather Report package blog.weather; import java.util.List; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.eclipse.persistence.oxm.annotations.XmlPath; @XmlRootElement(name="xml_api_reply") @XmlType(propOrder={"location", "currentCondition", "currentTemperature", "forecast"}) @XmlAccessorType(XmlAccessType.FIELD) public class WeatherReport { @XmlPath("weather/forecast_information/city/@data") private String location; @XmlPath("weather/current_conditions/temp_f/@data") private int currentTemperature; @XmlPath("weather/current_conditions/condition/@data") private String currentCondition; @XmlPath("weather/forecast_conditions") private List forecast; } Forecast package blog.weather; import org.eclipse.persistence.oxm.annotations.XmlPath; public class Forecast { @XmlPath("day_of_week/@data") private String dayOfTheWeek; @XmlPath("low/@data") private int low; @XmlPath("high/@data") private int high; @XmlPath("condition/@data") private String condition; } Specify MOXy as the JAXB Provider (jaxb.properties) To configure MOXy as your JAXB provider simply add a file named jaxb.properties in the same package as your domain model with the following entry: javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory For more information see: Specifying EclipseLink MOXy as Your JAXB Provider. Demo The following demo code will read the XML data for Google's weather service, and marshal the objects back to XML: package blog.weather; import java.net.URL; import javax.xml.bind.*; public class GoogleDemo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(WeatherReport.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); URL url = new URL("http://www.google.com/ig/api?weather=Ottawa"); WeatherReport weatherReport = (WeatherReport) unmarshaller.unmarshal(url); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(weatherReport, System.out); } } Output Below is the result of running the demo code. The output represents the portion of the XML document that we had mapped to: expand source Yahoo Weather API The following URL will be used to access the weather data for Ottawa using the Yahoo Weather API (3369 is the WOEID for Ottawa): http://weather.yahooapis.com/forecastrss?w=3369 The following is the result of performing the above query at time I was writing this article: http://us.rd.yahoo.com/dailynews/rss/weather/Ottawa__CA/*http://weather.yahoo.com/forecast/CAXX0343_f.html Yahoo! Weather for Ottawa, CA en-us Thu, 08 Sep 2011 10:58 am EDT 60 142 18 http://weather.yahoo.com http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif 45.42 -75.69 http://us.rd.yahoo.com/dailynews/rss/weather/Ottawa__CA/*http://weather.yahoo.com/forecast/CAXX0343_f.html Thu, 08 Sep 2011 10:58 am EDT Current Conditions: Mostly Cloudy, 66 F Forecast: Thu - Partly Cloudy. High: 75 Low: 57 Fri - Partly Cloudy. High: 79 Low: 53 Full Forecast at Yahoo! Weather (provided by The Weather Channel) ]]> CAXX0343_2011_09_09_7_00_EDT Java Model - Mapped to Yahoo's XML Schema via XML Metadata Since we can not supply a second set of mappings to an object model via annotations, we must supply subsequent mappings by leveraging MOXy's XML metadata. By default MOXy's mapping document is used to supplement any annotations that are specified on the model. However, if the xml-mapping-metadata-complete flag is set, then the XML metadata will completely replace the metadata provided by annotations (the annotations for the Google mapping will remain on the POJOs, but the xml-mapping-metadata-complete flag tells MOXy to ignore them). Demo The following demo code will read the XML data for Yahoo's weather service, and marshal the objects back to XML. Due to a MOXy bug regarding unmapped CDATA sections (https://bugs.eclipse.org/357145, this bug has been fixed in EclipseLink 2.3.1), a filtered XMLStreamReader was used to remove it from the XML input: package blog.weather; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.stream.StreamFilter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.stream.StreamSource; import org.eclipse.persistence.jaxb.JAXBContextFactory; public class YahooDemo { public static void main(String[] args) throws Exception { Map properties = new HashMap(1); properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "blog/weather/yahoo-binding.xml"); JAXBContext jc = JAXBContext.newInstance(new Class[] {WeatherReport.class}, properties); XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource("http://weather.yahooapis.com/forecastrss?w=3369"); XMLStreamReader xsr = xif.createXMLStreamReader(xml); xsr = xif.createFilteredReader(xsr, new CDATAFilter()); Unmarshaller unmarshaller = jc.createUnmarshaller(); WeatherReport weatherReport = (WeatherReport) unmarshaller.unmarshal(xsr); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(weatherReport, System.out); } private static class CDATAFilter implements StreamFilter { public boolean accept(XMLStreamReader xsr) { return XMLStreamReader.CDATA != xsr.getEventType(); } } } Output Below is the result of running the demo code. The output represents the portion of the XML document that we had mapped to: From http://blog.bdoughan.com/2011/09/mapping-objects-to-multiple-xml-schemas.html
December 28, 2011
by Blaise Doughan
· 10,315 Views
article thumbnail
The “4+1” View Model of Software Architecture
In November 1995, while working as Lead software architect at Hughes Aircraft Of Canada Philippe Kruchten published a paper entitled: "Architectural Blueprints—The “4+1” View Model of Software Architecture". The intent was to come up with a mechanism to separate the different aspects of a software system into different views of the system. Why? Because different stakeholders always have different interest in a software system. Some aspects of a system are relevant to the Developers; others are relevant to System administrators. The Developers want to know about things like classes; System administrators want to know about deployment, hardware and network configurations and don't care about classes. Similar points can be made for Testers, Project Managers and Customers. Kruchten thought it made sense to decompose architecture into distinct views so stakeholders could get what they wanted. In total there were 5 views in his approach but he decided to call it 4 + 1. We'll discuss why it's called 4 + 1 later! But first, let's have a look at each of the different views. The logical view This contains information about the various parts of the system. In UML the logical view is modelled using Class, Object, State machine and Interaction diagrams (e.g Sequence diagrams). It's relevance is really to developers. The process view This describes the concurrent processes within the system. It encompasses some non-functional requirements such as performance and availability. In UML, Activity diagrams - which can be used to model concurrent behaviour - are used to model the process view. The development view The development view focusses on software modules and subsystems. In UML, Package and Component diagrams are used to model the development view. The physical view The physical view describes the physical deployment of the system. For example, how many nodes are used and what is deployed on what node. Thus, the physical view concerns some non-functional requirements such as scalability and availability. In UML, Deployment diagrams are used to model the physical view. The use case view This view describes the functionality of the system from the perspective from outside world. It contains diagrams describing what the system is supposed to do from a black box perspective. This view typically contains Use Case diagrams. All other views use this view to guide them. Why is it called the 4 + 1 instead of just 5? Well this is because of the special significance the use case view has. When all other views are finished, it's effectively redundant. However, all other views would not be possible without it. It details the high levels requirements of the system. The other views detail how those requirements are realised. 4 + 1 came before UML It's important to remember the 4 + 1 approach was put forward two years before the first the introduction of UML which did not manifest in its first guise until 1997. UML is how most enterprise architectures are modelled and the 4 + 1 approach still plays a relevance to UML today. UML 2.0 has 13 different types of diagrams - each diagram type can be categorised into one of the 4 + 1 views. UML is 4 + 1 friendly! So is it important? The 4 + 1 approach isn't just about satisfying different stakeholders. It makes modelling easier to do because it makes it easier to organise. A typical project will contain numerous diagrams of the various types. For example, a project may contain a few hundred sequence diagrams and several class diagrams. Grouping diagrams of similar types and purpose means there is an emphasis in separating concerns. Sure isn't it just the same with Java? Grouping Java classes of similar purpose and related responsibilities into packages means organisation is better. Similarly, grouping different components into different jar files means organisation is better. Modelling tools will usually support the 4 + 1 approach and this means projects will have templates for how to split the various types of diagrams. In a company when projects follow industry standard templates again it means things are better organised. The 4 + 1 approach also provides a way for architects to be able to prioritise modelling concerns. It is rare that a project will have enough time to model every single diagram possible for an architecture. Architects can prioritise different views. For example, for a business domain intensive project it would make sense to prioritise the logical view. In a project with high concurrency and complex timing it would make sense to ensure the process view gets ample time. Similarly, the 4 + 1 approach makes it possible for stakeholders to get the parts of the model that are relevant to them. References: Architectural Blueprints—The “4+1” View Model of Software Architecture Paper http://www.cs.ubc.ca/~gregor/teaching/papers/4+1view-architecture.pdf Learning UML 2.0 by Russ Miles & Kim Hamilton. O'Reilly From http://dublintech.blogspot.com/2011/05/41-view-model-of-software-architecture.html
December 28, 2011
by Alex Staveley
· 53,932 Views
article thumbnail
Guava Stopwatch
Guava's Stopwatch is another Guava class new to Guava Release 10 (as is Optional, the subject of another recent post). As its name implies, this simple class provides a method to conveniently measure time elapsed between two code points. It has several advantages over use of System.currentTimeMillis() or System.nanoTime(). I don't focus on these advantages here, but the Javadoc documentation for Stopwatch does cover some of these advantages. As is true of many of Guava's classes, one of the endearing features of Stopwatch is its simplicity and appropriately named methods. The class features two constructors, one that takes no arguments (likely to be most commonly used) and one that accepts an customized extension of the Ticker class. Once an instance of Stopwatch is obtained, it's a simple matter of using methods with "obvious" names like start(), stop(), and reset() to control the stopwatch. Any given Stopwatch instance records elapsed time in a cumulative fashion. In other words, you can start and stop the stopwatch multiple times (just don't start an already started stopwatch and don't stop an already stopped stopwatch) and the elapsed time accumulates with each start and stop. If that's not what is wanted and a single instance of the stopwatch is to be used to measure independent events (but not concurrent events), then the reset() method is used between the last run's stop() and the next run's start(). I have already alluded to several caveats to keep in mind when using Guava's Stopwatch. First, two successive start() methods should not be invoked on a given instance of Stopwatch without first stopping it with stop() before making the second call to stop(). Stopwatch has an instance method isRunning() that is useful for detecting a running stopwatch before trying to start it again or even before trying to stop one that has already been stopped or was never started. Most of these issues such as starting the stopwatch twice without stopping it or stopping a stopwatch that is not running or was never started lead to IllegalStateExceptions being thrown. Guava developers make use of their own Preconditions class to ascertain these aberrant conditions and to the throwing of these exceptions. The further implication of this, which is spelled out in the Javadoc documentation, is that Stopwatch is not thread-safe and should be used in a single-thread environment. The methods covered so far handle constructing instances of Stopwatch and managing the stopwatch. However, a stopwatch is almost always useful only when the timed results are available for viewing. The Stopwatch class provides two main methods for accessing elapsed time recorded by the stopwatch instance. One method, elapsedMillis(), is similar to standard Java methods that return milliseconds since epoch time. The big difference here is that Stopwatch is returning milliseconds elapsed between given points in time (start() and stop() calls) versus since an absolute epoch time. I prefer elapsedTime(TimeUnit) for acquiring the elapsed time recorded in my stopwatch instance. This method makes use of the TimeUnit enum (see my post on TimeUnit) to specify the units that the elapsed time should be expressed in. Both of these methods for reporting elapsed time can be run while the stopwatch is running or after it has stopped. The following code listing contains a class that demonstrates the methods on Stopwatch that have been highlighted in this post. StopWatchDemo.java package dustin.examples; import static java.lang.System.out; import com.google.common.base.Stopwatch; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * Demonstrates Guava's (Release 10) Stopwatch class. * * @author Dustin */ public class StopWatchDemo { private final static Logger LOGGER = Logger.getLogger(StopWatchDemo.class.getCanonicalName()); public static void doSomethingJustToBeDoingIt(final int numberOfTimesToDoNothing) { for (int count=0; count < numberOfTimesToDoNothing; count++) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(1)); } catch (InterruptedException interruptEx) { LOGGER.log(Level.INFO, "Don't interrupt me when I'm trying to sleep!", interruptEx); } } } /** * Print statistics on Stopwatch-reported times for provided number of loops. * * @param numberLoops Number of loops executed. * @param stopwatch Stopwatch instance with time used statistics. */ public static void printElapsedTime(final int numberLoops, final Stopwatch stopwatch) { if (stopwatch.isRunning()) { out.println("WARNING! Your stopwatch is still running!"); } else // stopwatch not running { out.println(numberLoops + " loops required: "); out.println("\t" + stopwatch.toString(6)); out.println("\t" + stopwatch.elapsedMillis() + " elapsed milliseconds."); out.println("\t" + stopwatch.elapsedTime(TimeUnit.MINUTES) + " minutes"); out.println("\t" + stopwatch.elapsedTime(TimeUnit.SECONDS) + " seconds"); out.println("\t" + stopwatch.elapsedTime(TimeUnit.MILLISECONDS) + " milliseconds"); out.println("\t" + stopwatch.elapsedTime(TimeUnit.NANOSECONDS) + " nanoseconds"); } } public static void main(final String[] arguments) { final Stopwatch stopwatch = new Stopwatch(); int numberTimes = 5; stopwatch.start(); doSomethingJustToBeDoingIt(numberTimes); stopwatch.stop(); printElapsedTime(numberTimes, stopwatch); numberTimes = 45; stopwatch.reset(); stopwatch.start(); doSomethingJustToBeDoingIt(numberTimes); stopwatch.stop(); printElapsedTime(numberTimes, stopwatch); numberTimes = 125; stopwatch.reset(); stopwatch.start(); doSomethingJustToBeDoingIt(numberTimes); stopwatch.stop(); printElapsedTime(numberTimes, stopwatch); } } When the above code is executed, its output is similar to that shown in the following screen snapshot. If I comment out the lines that reset the stop watch instance, the stopwatch instance accumulates elapsed time rather than tracking it separately. This difference is shown in the next screen snapshot. The Guava Stopwatch class makes it easy to perform simple timing measurements to analyze how long certain operations take. It is easy to use and provides the flexibility to readily provide output in the desired time scale. From http://marxsoftware.blogspot.com/2011/10/guava-stopwatch.html
December 28, 2011
by Dustin Marx
· 28,480 Views · 15 Likes
article thumbnail
How to deploy a neo4j instance in Amazon EC2 in 10 minutes
Neo4j is a high-performance, NOSQL graph database with all the features of a mature and robust database. In this post I will explain how to deploy a neo4j instance in Amazon EC2 web service. For this tutorial to take you no more than 10 minutes you should be able to execute properly some bash commands like mv, tar, ssh and scp (secure copy). I also assume that you have an account in Amazon Web Services and you are familiar to the process of launching instances. If not, I strongly recommend you to follow this starting guide and complete it till you manage to connect to your instance with ssh. Start downloading the latest stable version of neo4j. Which you can find here. The “Community Edition” fits well for development purposes. Do not forget to select the Unix version of the server. This will download a tar.gz file which you will copy to your EC2 instance later. While you download the neo4j server open the AWS Management Console and launch a Basic 32-bit Amazon Linux AMI. If you want to launch an Ubuntu AMI please notice that it doesn’t ship with Java, which is required for running neo4j. If you are not familiar with key pairs, pem files or security groups I insist you to follow the EC2 starting guide I mentioned above. You can either create a new security group or use the default, but you will need to configure a new security rule for the neo4j server port. After launching the instance, create a TCP rule on port 7474 with source 0.0.0.0/0. Here you are opening port 7474 for anyone. If you are planning to use the neo4j REST API and remotely call it from another server, for example a Rails application hosted in Heroku, for security reasons, you may want to change the source field to the address of your Heroku server. Do not forget to open port 22 (SSH), this is typically the first rule normal people create after launching an instance. You are almost done! You should now install neo4j in your instance. Open a terminal in your localhost and navigate to the path where you downloaded neo4j. Copy the file to your Amazon instance by using the scp command: scp -i your_pem_file.pem neo4j-community-1.6.M01-unix.tar.gz ec2-user@YOUR_PUBLIC_INSTANCE_DNS:/home/ec2-user Please notice that you will need to change the path to your pem file, typically placed in ~/.ssh, the filename of the neo4j server you just downloaded and the plublic DNS of your instance. Now connect to your instance with SSH: ssh -i your_pem_file.pem ec2-user@YOUR_PUBLIC_INSTANCE_DNS Untar the neo4j server: tar xvfz neo4j-community-1.6.M01-unix.tar.gz.tar.gz Move it to /usr/local and rename the folder to neo4j: sudo mv neo4j-community-1.6.M01 /usr/local/neo4j Almost done!!! You should now open neo4j-server.properties under the conf directory and add the following line: org.neo4j.server.webserver.address=0.0.0.0 This lines allows anyone to connect remotely to your neo4j database server. Now run the start script. From the neo4j server folder. sudo ./bin/neo4j start Finally, open a browser and access the webadmin interface of your neo4j database by typing http://YOUR_PUBLIC_INSTANCE_DNS:7474. You should see the Neo4j Monitoring and Management Tool, pretty cool! If not, ask me You can now try using the REST API and the curl bash command to insert nodes and relationships. I hope this post helped you, good luck! Follow me on Twitter @negarnil Source: http://www.cloudtmp.com/java/how-to-deploy-a-neo4j-instance-in-amazon-ec2-in-10-minutes/
December 27, 2011
by Nicolas Garnil
· 27,438 Views · 1 Like
article thumbnail
Creating a DateChooser Control with JavaFX 2.0
I must admit I finally came to like JavaFX. The game changer was that JavaFX 2.0 offers a path of adoption for Swing developers. I especially like the fact that it's easy to style the JavaFX user interface via CSS. And, even if you create custom controls, you can make them styleable without much extra effort. Here's a little datepicker I created as an example: You can use NetBeans IDE 7.1 for development. Here's the complete example as a NetBeans Project: [download] The JavaFX controls consist of a Control and a Skin class. We'll start with the control: DateChooser.java public class DateChooser extends Control{ private static final String DEFAULT_STYLE_CLASS = "date-chooser"; private Date date; public DateChooser(Date preset) { getStyleClass().setAll(DEFAULT_STYLE_CLASS); this.date = preset; } public DateChooser() { this(new Date(System.currentTimeMillis())); } @Override protected String getUserAgentStylesheet() { return "de/eppleton/fxcontrols/datechooser/calendar.css"; } public Date getDate() { return date; } } The only important thing it does is to register the stylesheet for this Control and gives access to the date picked by the user. Next we'll define a CSS file with our default styles: calendar.css .date-chooser { -fx-skin: "de.eppleton.fxcontrols.datechooser.DateChooserSkin"; } .weekday-cell { -fx-background-color: lightgray; -fx-background-radius: 5 5 5 5; -fx-background-insets: 2 2 2 2 ; -fx-text-fill: darkgray; -fx-text-alignment: left; -fx-font: 12pt "Tahoma Bold"; } .week-of-year-cell { -fx-background-color: lightgray; -fx-background-radius: 5 5 5 5; -fx-background-insets: 2 2 2 2 ; -fx-text-fill: white; -fx-text-alignment: left; -fx-font: 12pt "Tahoma Bold"; } .calendar-cell { -fx-background-color: skyblue, derive(skyblue, 25%), derive(skyblue, 50%), derive(skyblue, 75%); -fx-background-radius: 5 5 5 5; -fx-background-insets: 2 2 2 2 ; -fx-text-fill: skyblue; -fx-text-alignment: left; -fx-font: 12pt "Tahoma Bold"; } .calendar-cell:hover { -fx-background-color: skyblue; -fx-text-fill: white; } .calendar-cell:pressed { -fx-background-color: darkblue; -fx-text-fill: green; } .calendar-cell-selected { -fx-background-radius: 5 5 5 5; -fx-background-insets: 2 2 2 2 ; -fx-text-alignment: left; -fx-font: 12pt "Tahoma Bold"; -fx-background-color: darkblue; -fx-text-fill: white; } .calendar-cell-inactive { -fx-background-color: derive(lightgray, 75%); -fx-background-radius: 5 5 5 5; -fx-background-insets: 2 2 2 2 ; -fx-text-fill: darkgray; -fx-text-alignment: left; -fx-font: 12pt "Tahoma Bold"; } .calendar-cell-today { -fx-background-color: yellow; -fx-background-radius: 5 5 5 5; -fx-background-insets: 2 2 2 2 ; -fx-text-fill: skyblue; -fx-text-alignment: left; -fx-font: 12pt "Tahoma Bold"; } The most important part here is the -fx-skin. It defines which class should be used as the Skin for our control. The third part is the Skin itself. DateChooserSkin.java public class DateChooserSkin extends SkinBase> { private final Date date; private final Label month; private final BorderPane content; final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMMM yyyy"); private static class CalendarCell extends StackPane { private final Date date; public CalendarCell(Date day, String text) { this.date = day; Label label = new Label(text); getChildren().add(label); } public Date getDate() { return date; } } public DateChooserSkin(DateChooser dateChooser) { super(dateChooser, new BehaviorBase(dateChooser)); // this date is the selected date date = dateChooser.getDate(); final DatePickerPane calendarPane = new DatePickerPane(date); month = new Label(simpleDateFormat.format(calendarPane.getShownMonth())); HBox hbox = new HBox(); // create the navigation Buttons Button yearBack = new Button("<<"); yearBack.addEventHandler(ActionEvent.ACTION, new EventHandler() { @Override public void handle(ActionEvent event) { calendarPane.forward(-12); } }); Button monthBack = new Button("<"); monthBack.addEventHandler(ActionEvent.ACTION, new EventHandler() { @Override public void handle(ActionEvent event) { calendarPane.forward(-1); } }); Button monthForward = new Button(">"); monthForward.addEventHandler(ActionEvent.ACTION, new EventHandler() { @Override public void handle(ActionEvent event) { calendarPane.forward(1); } }); Button yearForward = new Button(">>"); yearForward.addEventHandler(ActionEvent.ACTION, new EventHandler() { @Override public void handle(ActionEvent event) { calendarPane.forward(12); } }); // center the label and make it grab all free space HBox.setHgrow(month, Priority.ALWAYS); month.setMaxWidth(Double.MAX_VALUE); month.setAlignment(Pos.CENTER); hbox.getChildren().addAll(yearBack, monthBack, month, monthForward, yearForward); // use a BorderPane to Layout the view content = new BorderPane(); getChildren().add(content); content.setTop(hbox); content.setCenter(calendarPane); } /** @author eppleton */ class DatePickerPane extends Region { private final Date selectedDate; private final Calendar cal; private CalendarCell selectedDayCell; // this is used to format the day cells private final SimpleDateFormat sdf = new SimpleDateFormat("d"); // empty cell header of weak-of-year row private final CalendarCell woyCell = new CalendarCell(new Date(), ""); private int rows, columns;//default public DatePickerPane(Date date) { setPrefSize(300, 300); woyCell.getStyleClass().add("week-of-year-cell"); setPadding(new Insets(5, 0, 5, 0)); this.columns = 7; this.rows = 5; // use a copy of Date, because it's mutable // we'll helperDate it through the month cal = Calendar.getInstance(); Date helperDate = new Date(date.getTime()); cal.setTime(helperDate); // the selectedDate is the date we will change, when a date is picked selectedDate = date; refresh(); } /** Move forward the specified number of Months, move backward by using negative numbers @param i */ public void forward(int i) { cal.add(Calendar.MONTH, i); month.setText(simpleDateFormat.format(cal.getTime())); refresh(); } private void refresh() { super.getChildren().clear(); this.rows = 5; // most of the time 5 rows are ok // save a copy to reset the date after our loop Date copy = new Date(cal.getTime().getTime()); // empty cell header of weak-of-year row super.getChildren().add(woyCell); // Display a styleable row of localized weekday symbols DateFormatSymbols symbols = new DateFormatSymbols(); String[] dayNames = symbols.getShortWeekdays(); // @TODO use static constants to access weekdays, I suspect we // get problems with localization otherwise ( Day 1 = Sunday/ Monday in // different timezones for (int i = 1; i < 8; i++) { // array starts with an empty field CalendarCell calendarCell = new CalendarCell(cal.getTime(), dayNames[i]); calendarCell.getStyleClass().add("weekday-cell"); super.getChildren().add(calendarCell); } // find out which month we're displaying cal.set(Calendar.DAY_OF_MONTH, 1); final int month = cal.get(Calendar.MONTH); int weekday = cal.get(Calendar.DAY_OF_WEEK); // if the first day is a sunday we need to rewind 7 days otherwise the // code below would only start with the second week. There might be // better ways of doing this... if (weekday != Calendar.SUNDAY) { // it might be possible, that we need to add a row at the end as well... Calendar check = Calendar.getInstance(); check.setTime(new Date(cal.getTime().getTime())); int lastDate = check.getActualMaximum(Calendar.DATE); check.set(Calendar.DATE, lastDate); if ((lastDate + weekday) > 36) { rows = 6; } cal.add(Calendar.DATE, -7); } cal.set(Calendar.DAY_OF_WEEK, 1); // used to identify and style the cell with the selected date; Calendar testSelected = Calendar.getInstance(); testSelected.setTime(selectedDate); for (int i = 0; i < (rows); i++) { // first column shows the week of year CalendarCell calendarCell = new CalendarCell(cal.getTime(), "" + cal.get(Calendar.WEEK_OF_YEAR)); calendarCell.getStyleClass().add("week-of-year-cell"); super.getChildren().add(calendarCell); // loop through current week for (int j = 0; j < columns; j++) { String formatted = sdf.format(cal.getTime()); final CalendarCell dayCell = new CalendarCell(cal.getTime(), formatted); dayCell.getStyleClass().add("calendar-cell"); if (cal.get(Calendar.MONTH) != month) { dayCell.getStyleClass().add("calendar-cell-inactive"); } else { if (isSameDay(testSelected, cal)) { dayCell.getStyleClass().add("calendar-cell-selected"); selectedDayCell = dayCell; } if (isToday(cal)) { dayCell.getStyleClass().add("calendar-cell-today"); } } dayCell.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent arg0) { if (selectedDayCell != null) { selectedDayCell.getStyleClass().add("calendar-cell"); selectedDayCell.getStyleClass().remove("calendar-cell-selected"); } selectedDate.setTime(dayCell.getDate().getTime()); dayCell.getStyleClass().remove("calendar-cell"); dayCell.getStyleClass().add("calendar-cell-selected"); selectedDayCell = dayCell; Calendar checkMonth = Calendar.getInstance(); checkMonth.setTime(dayCell.getDate()); if (checkMonth.get(Calendar.MONTH) != month) { forward(checkMonth.get(Calendar.MONTH) - month); } } }); // grow the hovered cell in size dayCell.setOnMouseEntered(new EventHandler() { @Override public void handle(MouseEvent e) { dayCell.setScaleX(1.1); dayCell.setScaleY(1.1); } }); dayCell.setOnMouseExited(new EventHandler() { @Override public void handle(MouseEvent e) { dayCell.setScaleX(1); dayCell.setScaleY(1); } }); super.getChildren().add(dayCell); cal.add(Calendar.DATE, 1); // number of days to add } } cal.setTime(copy); } /** Overriden, don't add Children directly @return unmodifieable List */ @Override protected ObservableList getChildren() { return FXCollections.unmodifiableObservableList(super.getChildren()); } /** get the current month our calendar displays. Should always give you the correct one, even if some days of other mnths are also displayed @return */ public Date getShownMonth() { return cal.getTime(); } @Override protected void layoutChildren() { ObservableList children = getChildren(); double width = getWidth(); double height = getHeight(); double cellWidth = (width / (columns + 1)); double cellHeight = height / (rows + 1); for (int i = 0; i < (rows + 1); i++) { for (int j = 0; j < (columns + 1); j++) { if (children.size() <= ((i * (columns + 1)) + j)) { break; } Node get = children.get((i * (columns + 1)) + j); layoutInArea(get, j * cellWidth, i * cellHeight, cellWidth, cellHeight, 0.0d, HPos.LEFT, VPos.TOP); } } } } // utility methods private static boolean isSameDay(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The dates must not be null"); } return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); } private static boolean isToday(Calendar cal) { return isSameDay(cal, Calendar.getInstance()); } } There are a couple of inline comments explaining what the code does. Most of the visual stuff is in the DatePickerPane. DatePickerPane extends Region, which is a base class you can use for your own layout manager. You just need to override layoutChildren. I used a simple grid. The refresh method is responsible for creating the headers and the cells that represent the days and weeks. It also assigns the style to each of the fields. Since we have a fixed number of cells, we should probably add them only once and in subsequent steps only change the labels (and save us from creating tons of Eventhandlers). But let's keep it simple, it's just an example... The cool thing is that anyone interested in changing the appearance just needs to have a look at the CSS file to find out which styles we defined and can override them with a customized stylesheet to match the overall look and feel of their own application. Finally here's how to use it in your code: public class TestApplication extends Application { /** @param args the command line arguments */ public static void main(String[] args) { launch(args); } @Override public void start(final Stage primaryStage) { primaryStage.setTitle("Hello World!"); StackPane root = new StackPane(); final DateChooser dateChooser = new DateChooser(); root.getChildren().add(dateChooser); Scene scene = new Scene(root, 300, 250); primaryStage.setScene(scene); primaryStage.setOnHiding(new EventHandler() { public void handle(WindowEvent event) { System.out.println("date " + dateChooser.getDate()); } }); primaryStage.show(); } } Have fun!
December 26, 2011
by Toni Epple
· 61,797 Views
article thumbnail
HTML5 Canvas + WebSockets = Multiplayer Space Shooter In Browser
Recently I ran across Rawkets, a slick site taking two emerging web technologies -- HTML5 Canvas and WebSockets -- and combining them in the most obvious way possible: a multiplayer space shooter. Why Canvas? No plugins -- graphical Yes; and why WebSockets? Low latency -- multiplayer Yes. Sadly, every time I join the game, nobody else is there. If I wanted single-player HTML5 gaming, I could check out another project by Rawkets' creator, Rob Hawkes: straight-up Asteroids, using the HTML5 game engine Impact. But WebSockets won't help Asteroids, because Asteroids runs totally on just one client. Rawkets, on the other hand, has multiple clients running Canvas, with their own JavaScript, connecting via WebSockets, all taking through Node.js on the server, producing something like this: I can't tell whether the game is any fun, because I've never seen anyone else in there. (Also, it doesn't seem to work in Chrome). But as a tech demo it's a cool idea, and conceptually straightforward enough to inspire. (If you're impressed, Rob also links from the game site to to his HTML5 Canvas book -- though apparently the book assumes virtually no knowledge of Canvas or JavaScript, and doesn't progress all that far.) Check it out, and maybe shoot someone else's ship down -- fairly fairly, of course, because WebSockets will keep multiplex channels persistently open...
December 26, 2011
by John Esposito
· 10,420 Views
article thumbnail
Async file upload with jquery and ASP.NET
Recently before some I was in search of good asynchronous file upload control which can upload file without post back and I have don’t have to write much custom logic about this. So after searching it on internet I have found lots of options but some of the options were not working with ASP.NET and some of work options are not possible regarding context to my application just like AsyncFileUpload from Ajax toolkit.As in my application we were having old version of Ajax toolkit and if we change it than other controls stopped working. So after doing further search on internet I have found a great Juqery plugin which can easily be integrated with my application and I don’t have to write much coding to do same. So I have download that plug from the following link. This plug in created by yvind Saltvik http://www.phpletter.com/Our-Projects/AjaxFileUpload/ After downloading the plugin and going through it documentation I have found that I need to write a page or generic handler which can directly upload the file on the server. So I have decided to write a generic handler for that as generic handler is best suited with this kind of situation and we don’t have to bother about response generated by it. So let’s create example and In this example I will show how we can create async file upload without writing so much code with the help of this plugin. So I have create project called JuqeryFileUpload and our need for this example to create a generic handler. So let’s create a generic handler. You can create a new generic handler via right project-> Add –>New item->Generic handler just like following. I have created generic handler called AjaxFileuploader and following is simple code for that. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace JuqeryFileUPload { /// /// Summary description for AjaxFileUploader /// public class AjaxFileUploader : IHttpHandler { public void ProcessRequest(HttpContext context) { if (context.Request.Files.Count > 0) { string path = context.Server.MapPath("~/Temp"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); var file = context.Request.Files[0]; string fileName; if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE") { string[] files = file.FileName.Split(new char[] { '\\' }); fileName = files[files.Length - 1]; } else { fileName = file.FileName; } string strFileName=fileName ; fileName = Path.Combine(path, fileName); file.SaveAs(fileName); string msg = "{"; msg += string.Format("error:'{0}',\n", string.Empty); msg += string.Format("msg:'{0}'\n", strFileName); msg += "}"; context.Response.Write(msg); } } public bool IsReusable { get { return true; } } } } As you can see in above code.I have written a simple code to upload a file from received from file upload plugin into the temp directory on the server and if this directory is not there on the server then it will also get created by the this generic handler.At the end of the of execution I am returning the simple response which is required by plugin itself. Here in message part I am passing the name of file uploaded and in error message you can pass error if anything occurred for the time being I have not used right now. As like all jQuery plugin this plugin also does need jQuery file and there is another .js file given for plugin called ajaxfileupload.js. So I have created a test.aspx to test jQuery file and written following html for that . Upload As you can see in above code there its very simple. I have included the jQuery and ajafileupload.js given by the file upload give and there are three elements that I have used one if plain file input control you can also use the asp.net file upload control and but here I don’t need it so I have user file upload control. There is button there called which is calling a JavaScript function called “ajaxFileUpload” and here we will write a code upload that. There is an image called loading which just an animated gif which will display during the async call of generic handler. Following is code ajaxFileUpload function. As you can see in above code I have putted our generic handler url which will upload the file on server as url parameter. There is also parameter called secureURI is required to be true if you are uploading file through the secure channel and as a third parameter we have to pass a file upload control id which I have already passed and in fourth parameter we have to passed busy indicator which I have also passed. Once we passed all the parameter then it will call a method for plugin and will return response in terms of message and error. So There is two handler function written for that. That’s it. Our async file upload is ready. As you can easily integrate it and also it working fine in all the browser. Hope you like it. Stay tuned for more. Till then happy programming..
December 24, 2011
by Jalpesh Vadgama
· 66,960 Views
article thumbnail
Maven + JavaScript Unit Test: Running in a Continuous Integration Environment
So you're still interested in unit testing JavaScript (good). This post is an extension of my much more indepth first posting on how to unit test JavaScript using JS Test Driver. Please check it out here. Recap Last Posting In the last posting we successfully unit tested JavaScript using Maven and JsTest Driver. This allowes us to test JavaScript when on an environment that has a modern browser installed and can be run. Problem with typical CI environments So what happens when the test are passing on your local box, but you go to check in your code and the Continuous Integration (CI) server pukes on the new tests becasue there is no "screen" to run chrome or firefox? As of this posting, none of the top-tier browsers have a "headless" or an in-memory only browser window. There are alternatives to running JavaScript in a browser, such as rhino.js, env.js or HtmlUnit, however, these are just ports of browsers and the JavaScript and DOM representation are not 100% accurate which can lead to problems with your code when rendered in a client's browser. Approach What we need to do is to run JSTestDriver's browser in a Virtual X Framebuffer (Xvfb) which is possible on nearly all Linux based systems. The example below uses a Solaris version of Linux, however, Debian and RedHat linux distrubutions come with the simplified bash script to easily run an appliation in a virtual framebuffer. This solution was derived from one posted solution on the JS Test Driver wiki. The given example is also a full working example that is in use at my current client. Here is the quick list of what we will accomplish. Note, several of these steps are discussed in depth in the previous post and are not covered in depth here. Create a profile to run Js Unit-Tests Copy JsTestDriver library to a known location for Maven to use Copy JavaScript main and test files to known locations Use ANT to start JsTestDriver and pipe the screen into xvfb Here is a sample profile to use. You will need to adjust the properties at the top of the profile to match your system. ci-jstests /opt/swf/bin/firefox 1.3.2 /opt/X11R6/xvfb-run org.apache.maven.plugins maven-dependency-plugin 2.1 copy generate-resources copy com.google.jstestdriver jstestdriver ${js-test-driver.version} jar true jsTestDriver.jar ${project.build.directory}/jstestdriver false true maven-resources-plugin 2.4.3 copy-main-files generate-test-resources copy-resources ${project.build.directory}/test-classes/main-js src/main/webapp/scripts false copy-test-files generate-test-resources copy-resources ${project.build.directory}/test-classes/test-js src/test/webapp/scripts false org.apache.maven.plugins maven-antrun-plugin 1.6 test run Possible problems Although I cannot predict or fix all problems, I can share the one major problem I ran into with Solaris and the script used to fix that. In Solaris (and could happen to other distros) the xvfb-run script was not available and several of the other libraries did not exist. I first had to download the latest X libraries and place them in their appropriate locations on the CI server. Next, I had to re-engineer the xvfb-run script. Here is a copy of my script (NOTE: This is the solution for my server and this may not work for you) I created a script that contains: /usr/openwin/bin/Xvfb :1 screen 0 1280x1024x8 pixdepths 8 24 fbdir /tmp/.X11-vbf & From http://www.ensor.cc/2011/08/maven-javascript-unit-test-running-in.html
December 23, 2011
by Mike Ensor
· 12,313 Views
article thumbnail
Enabling JMX in Hibernate, Ehcache, Quartz, DBPC and Spring
A collection of short how-to's for enabling JMX in several popular Java technologies. Continuing our journey with JMX (see: ...JMX for human beings) we will learn how to enable JMX support (typically statistics and monitoring capabilities) in some popular frameworks. Most of this information can be found on project's home pages, but I decided to collect it with few the addition of some useful tips. Hibernate (with Spring support) Exposing Hibernate statistics with JMX is pretty simple, however some nasty workarounds are requires when JPA API is used to obtain underlying SessionFactory class JmxLocalContainerEntityManagerFactoryBean() extends LocalContainerEntityManagerFactoryBean { override def createNativeEntityManagerFactory() = { val managerFactory = super.createNativeEntityManagerFactory() registerStatisticsMBean(managerFactory) managerFactory } def registerStatisticsMBean(managerFactory: EntityManagerFactory) { managerFactory match { case impl: EntityManagerFactoryImpl => val mBean = new StatisticsService(); mBean.setStatisticsEnabled(true) mBean.setSessionFactory(impl.getSessionFactory); val name = new ObjectName("org.hibernate:type=Statistics,application=spring-pitfalls") ManagementFactory.getPlatformMBeanServer.registerMBean(mBean, name); case _ => } } } Note that I have created a subclass of Springs built-in LocalContainerEntityManagerFactoryBean. By overriding createNativeEntityManagerFactory() method I can access EntityManagerFactory and by trying to downcast it to org.hibernate.ejb.EntityManagerFactoryImpl we were able to register Hibernate Mbean. One more thing has left. Obviously we have to use our custom subclass instead of org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean. Also, in order to collect the actual statistics instead of just seeing zeroes all the way down we must set the hibernate.generate_statistics flag. @Bean def entityManagerFactoryBean() = { val entityManagerFactoryBean = new JmxLocalContainerEntityManagerFactoryBean() entityManagerFactoryBean.setDataSource(dataSource()) entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter()) entityManagerFactoryBean.setPackagesToScan("com.blogspot.nurkiewicz") entityManagerFactoryBean.setJpaPropertyMap( Map( "hibernate.hbm2ddl.auto" -> "create", "hibernate.format_sql" -> "true", "hibernate.ejb.naming_strategy" -> classOf[ImprovedNamingStrategy].getName, "hibernate.generate_statistics" -> true.toString ).asJava ) entityManagerFactoryBean } Here is a sample of what can we expect to see in JvisualVM (don't forget to install all plugins!): In addition we get a nice Hibernate logging: HQL: select generatedAlias0 from Book as generatedAlias0, time: 10ms, rows: 20 EhCache Monitoring caches is very important, especially in application where you expect values to generally be present there. I tend to query the database as often as needed to avoid unnecessary method arguments or local caching. Everything to make code as simple as possible. However this approach only works when caching on the database layer works correctly. Similar to Hibernate, enabling JMX monitoring in EhCache is a two-step process. First you need to expose provided MBean in MBeanServer: @Bean(initMethod = "init", destroyMethod = "dispose") def managementService = new ManagementService(ehCacheManager(), platformMBeanServer(), true, true, true, true, true) @Bean def platformMBeanServer() = ManagementFactory.getPlatformMBeanServer def ehCacheManager() = ehCacheManagerFactoryBean.getObject @Bean def ehCacheManagerFactoryBean = { val ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean ehCacheManagerFactoryBean.setShared(true) ehCacheManagerFactoryBean.setCacheManagerName("spring-pitfalls") ehCacheManagerFactoryBean } Note that I explicitly set CacheManager name. This is not required but this name is used as part of the Mbean name and a default one contains hashCode value, which is not very pleasant. The final touch is to enable statistics on a cache basis: Now we can happily monitor various caching characteristics of every cache separately: As we can see the percentage of cache misses increases. Never a good thing. If we don't enable cache statistics, enabling JMX is still a good idea since we get a lot of management operations for free, including flushing and clearing caches (useful during debugging and testing). Quartz scheduler In my humble opinion Quartz scheduler is very underestimated library, but I will write an article about it on its own. This time we will only learn how to monitor it via JMX. Fortunately it's as simple as adding: org.quartz.scheduler.jmx.export=true To quartz.properties file. The JMX support in Quartz could have been slightly broader, but still one can query e.g. which jobs are currently running. By the way the new major version of Quartz (2.x) brings very nice DSL-like support for scheduling: val job = newJob(classOf[MyJob]) val trigger = newTrigger(). withSchedule( repeatSecondlyForever() ). startAt( futureDate(30, SECOND) ) scheduler.scheduleJob(job.build(), trigger.build()) Apache Commons DBCP Apache Commons DBCP is the most reasonable JDBC pooling library I came across. There is also c3p0, but it doesn't seem like it's actively developed any more. Tomcat JDBC Connection Pool looked promising, but since it's bundled in Tomcat, your JDBC drivers can no longer be packaged in WAR. The only problem with DBCP is that it does not support JMX. At all (see this two and a half year old issue). Fortunately this can be easily worked around. Besides we will learn how to use Spring built-in JMX support. Looks like the standard BasicDataSource has all what we need, all we have to do is to expose existing metrics via JMX. With Spring it is dead-simple – just subclass BasicDataSource and add @ManagedAttribute annotation over desired attributes: @ManagedResource class ManagedBasicDataSource extends BasicDataSource { @ManagedAttribute override def getNumActive = super.getNumActive @ManagedAttribute override def getNumIdle = super.getNumIdle @ManagedAttribute def getNumOpen = getNumActive + getNumIdle @ManagedAttribute override def getMaxActive: Int= super.getMaxActive @ManagedAttribute override def setMaxActive(maxActive: Int) { super.setMaxActive(maxActive) } @ManagedAttribute override def getMaxIdle = super.getMaxIdle @ManagedAttribute override def setMaxIdle(maxIdle: Int) { super.setMaxIdle(maxIdle) } @ManagedAttribute override def getMinIdle = super.getMinIdle @ManagedAttribute override def setMinIdle(minIdle: Int) { super.setMinIdle(minIdle) } @ManagedAttribute override def getMaxWait = super.getMaxWait @ManagedAttribute override def setMaxWait(maxWait: Long) { super.setMaxWait(maxWait) } @ManagedAttribute override def getUrl = super.getUrl @ManagedAttribute override def getUsername = super.getUsername } Here are few data source metrics going crazy during load-test: JMX support in the Spring framework itself is pretty simple. As you have seen above exposing arbitrary attribute or operation is just a matter of adding an annotation. You only have to remember about enabling JMX support using either XML or Java (also see: SPR-8943 : Annotation equivalent to with @Configuration): or: @Bean def annotationMBeanExporter() = new AnnotationMBeanExporter() This article wasn't particularly exciting. However, the knowledge of JMX metrics will enable us to write simple yet fancy dashboards in no time. Stay tuned! From http://nurkiewicz.blogspot.com/2011/12/enabling-jmx-in-hibernate-ehcache-qurtz.html
December 22, 2011
by Tomasz Nurkiewicz
· 12,719 Views
article thumbnail
How to create offline HTML5 web apps in 5 easy steps
Among all cool new features introduced by HTML5, the possibility of caching web pages for offline use is definitely one of my favorites. Today, I’m glad to show you how you can create a page that will be available for offline browsing. Getting started View Demo Download files 1 – Add HTML5 doctype The first thing to do is create a valid HTML5 document. The HTML5 doctype is easier to remember than ones used for xhtml: ... Create a file named index.html, or get the example files from my CSS3 media queries article to use as a basis for this tutorial. In case you need it, the full HTML5 specs are available on the W3C website. 2 – Add .htaccess support The file we’re going to create to cache our web page is called a manifest file. Before creating it, we first have to add a directive to the .htaccess file (assuming your server is Apache). Open the .htaccess file, which is located on your website root, and add the following code: AddType text/cache-manifest .manifest This directive makes sure that every .manifest file is served as text/cache-manifest. If the file isn’t, then the whole manifest will have no effect and the page will not be available offline. 3 – Create the manifest file Now, things are going to be more interesting as we create a manifest file. Create a new file and save it as offline.manifest. Then, paste the following code in it. I’ll explain it later. CACHE MANIFEST #This is a comment CACHE index.html style.css image.jpg image-med.jpg image-small.jpg notre-dame.jpg Right now, you have a perfectly working manifest file. The way it works is very simple: After the CACHE declaration, you have to list each files you want to make available offline. That’s enough for caching a simple web page like the one from my example, but HTML5 caching has other interesting possibilities. For example, consider the following manifest file: CACHE MANIFEST #This is a comment CACHE index.html style.css NETWORK: search.php login.php FALLBACK: /api offline.html Like in the example manifest file, we have a CACHE declaration that caches index.html and style.css. But we also have the NETWORK declaration, which is used to specify files that shouldn’t be cached, such as a login page. The last declaration is FALLBACK. This declaration allows you to redirect the user to a particular file (in this example, offline.html) if a resource (/api) isn’t available offline. 4 – Link your manifest file to the html document Now, both your manifest file and your main html document are ready. The only thing you still have to do is to link the manifest file to the html document. Doing this is easy: simply add the manifest attribute to the html element as shown below: 5 – Test it Once done, you’re ready to go. If you visit your index.html file with Firefox 3.5+, you should see a banner like this one: Other browser I’ve tested (Chrome, Safari, Android and iPhone) do not warn about the file caching, and the file is automatically cached. Below you’ll find the browser compatibility of this technique: As usual Internet Explorer does not support it. IE: No support Firefox: 3.5+ Safari: 4.0+ Chrome: 5.0+ Opera: 10.6+ iPhone: 2.1+ Android: 2.0+ Source: http://www.catswhocode.com/blog/how-to-create-offline-html5-web-apps-in-5-easy-steps
December 22, 2011
by Jean-Baptiste Jung
· 24,143 Views
article thumbnail
A Gentle Introduction to Making HTML5 Canvas Interactive
this is an big overhaul of one of my tutorials on making and moving shapes on an html5 canvas. this new tutorial is vastly cleaner than my old one, but if you still want to see that one or are looking for the concept of a “ghost context” you can find that one here. this tutorial will show you how to create a simple data structure for shapes on an html5 canvas and how to have them be selectable. the finished canvas will look like this: this article’s code is written primarily to be easy to understand. we’ll be going over a few things that are essential to interactive apps such as games (drawing loop, hit testing), and in later tutorials i will probably turn this example into a small game of some kind. i will try to accommodate javascript beginners but this introduction does expect at least a rudimentary understanding of js. not every piece of code is explained in the text, but almost every piece of code is thoroughly commented! the html5 canvas a canvas is made by using the tag in html: this text is displayed if your browser does not support html5 canvas. a canvas isn’t smart: it’s just a place for drawing pixels. if you ask it to draw something it will execute the drawing command and then immediately forget everything about what it has just drawn. this is sometimes referred to as an immediate drawing surface, as contrasted with svg as a retained drawing surface, since svg keeps a reference to everything drawn. because we have no such references, we have to keep track ourselves of all the things we want to draw (and re-draw) each frame. canvas also has no built-in way of dealing with animation. if you want to make something you’ve drawn move, you have to clear the entire canvas and redraw all of the objects with one or more of them moved. and you have to do it often, of course, if you want a semblance of animation or motion. so we’ll need to add: code for keeping track of objects code for keeping track of canvas state code for mouse events code for drawing the objects as they are made and move around keeping track of what we draw to keep things simple for this example we will start with a shape class to represent rectangular objects. javascript doesn’t technically have classes, but that isn’t a problem because javascript programmers are very good at playing pretend. functionally (well, for our example) we are going to have a shape class and create shape instances with it. what we are really doing is defining a function named shape and adding functions to shape’s prototype. you can make new instances of the function shape and all instances will share the functions defined on shape’s prototype. if you’ve never encountered prototypes in javascript before or if the above sounds confusing to you, i highly recommend reading crockford’s javascript: the good parts . the book is an intermediate overview of javascript that gives a good understanding of why programmers choose to create objects in different ways, why certain conventions are frowned upon, and just what makes javascript so different. here’s our shape constructor and one of the two prototype methods, which are comparable to a class instance methods: // constructor for shape objects to hold data for all drawn objects. // for now they will just be defined as rectangles. function shape(x, y, w, h, fill) { // this is a very simple and unsafe constructor. // all we're doing is checking if the values exist. // "x || 0" just means "if there is a value for x, use that. otherwise use 0." this.x = x || 0; this.y = y || 0; this.w = w || 1; this.h = h || 1; this.fill = fill || '#aaaaaa'; } // draws this shape to a given context shape.prototype.draw = function(ctx) { ctx.fillstyle = this.fill; ctx.fillrect(this.x, this.y, this.w, this.h); } keeping track of canvas state we’re going to have a second class/function called canvasstate. we’re only going to make one instance of this class and it will hold all of the state in this tutorial that is not associated with shapes themselves. canvasstate is going to foremost need a reference to the canvas and a few other field for convenience. we’re also going to compute and save the border and padding (if there is any) so that we can get accurate mouse coordinates. in the canvasstate constructor we will also have a collection of state relating to the objects on the canvas and the current status of dragging. we’ll make an array of shapes, a flag “dragging” that will be true while we are dragging, a field to keep track of which object is selected and a “valid” flag that will be set to false will cause the canvas to clear everything and redraw. is going to need an array of shapes to keep track of whats been drawn so far. i’m going to add a bunch of variables for keeping track of the drawing and mouse state. i already added boxes[] to keep track of each object, but we’ll also need a var for the canvas, the canvas’ 2d context (where wall drawing is done), whether the mouse is dragging, width/height of the canvas, and so on. we’ll also want to make a second canvas, for selection purposes, but i’ll talk about that later. function canvasstate(canvas) { // ... // i removed some setup code to save space // see the full source at the end // **** keep track of state! **** this.valid = false; // when set to true, the canvas will redraw everything this.shapes = []; // the collection of things to be drawn this.dragging = false; // keep track of when we are dragging // the current selected object. // in the future we could turn this into an array for multiple selection this.selection = null; this.dragoffx = 0; // see mousedown and mousemove events for explanation this.dragoffy = 0; mouse events we’ll add events for mousedown, mouseup, and mousemove that will control when an object starts and stops dragging. we’ll also disable the selectstart event, which stops double-clicking on canvas from accidentally selecting text on the page. finally we’ll add a double-click event that will create a new shape and add it to the canvasstate’s list of shapes. the mousedown event begins by calling getmouse on our canvasstate to return the x and y position of the mouse. we then iterate through the list of shapes to see if any of them contain the mouse position. we go through them backwards because they are drawn forwards, and we want to select the one that appears topmost, so we must find the potential shape that was drawn last. if we find the shape we save the offset, save that shape as our selection, set dragging to true and set the valid flag to false. already we’ve used most of our state! finally if we didn’t find any objects we need to see if there was a selection saved from last time. if there is we should clear it. since we clicked on nothing, we obviously didn’t click on the already-selected object! clearing the selection means we will have to clear the canvas and redraw everything without the selection ring, so we set the valid flag to false. // ... // (we are still in the canvasstate constructor) // this is an example of a closure! // right here "this" means the canvasstate. but we are making events on the canvas itself, // and when the events are fired on the canvas the variable "this" is going to mean the canvas! // since we still want to use this particular canvasstate in the events we have to save a reference to it. // this is our reference! var mystate = this; //fixes a problem where double clicking causes text to get selected on the canvas canvas.addeventlistener('selectstart', function(e) { e.preventdefault(); return false; }, false); // up, down, and move are for dragging canvas.addeventlistener('mousedown', function(e) { var mouse = mystate.getmouse(e); var mx = mouse.x; var my = mouse.y; var shapes = mystate.shapes; var l = shapes.length; for (var i = l-1; i >= 0; i--) { if (shapes[i].contains(mx, my)) { var mysel = shapes[i]; // keep track of where in the object we clicked // so we can move it smoothly (see mousemove) mystate.dragoffx = mx - mysel.x; mystate.dragoffy = my - mysel.y; mystate.dragging = true; mystate.selection = mysel; mystate.valid = false; return; } } // havent returned means we have failed to select anything. // if there was an object selected, we deselect it if (mystate.selection) { mystate.selection = null; mystate.valid = false; // need to clear the old selection border } }, true); the mousemove event checks to see if we have set the dragging flag to true. if we have it gets the current mouse positon and moves the selected object to that position, remembering the offset of where we were grabbing it. if the dragging flag is false the mousemove event does nothing. canvas.addeventlistener('mousemove', function(e) { if (mystate.dragging){ var mouse = mystate.getmouse(e); // we don't want to drag the object by its top-left corner, // we want to drag from where we clicked. // thats why we saved the offset and use it here mystate.selection.x = mouse.x - mystate.dragoffx; mystate.selection.y = mouse.y - mystate.dragoffy; mystate.valid = false; // something's dragging so we must redraw } }, true); the mouseup event is simple, all it has to do is update the canvasstate so that we are no longer dragging! so once you lift the mouse, the mousemove event is back to doing nothing. canvas.addeventlistener('mouseup', function(e) { mystate.dragging = false; }, true); the double click event we’ll use to add more shapes to our canvas. it calls addshape on the canvasstate with a new instance of shape. all addshape does is add the argument to the list of shapes in the canvasstate. // double click for making new shapes canvas.addeventlistener('dblclick', function(e) { var mouse = mystate.getmouse(e); mystate.addshape(new shape(mouse.x - 10, mouse.y - 10, 20, 20, 'rgba(0,255,0,.6)')); }, true); there are a few options i implemented, what the selection ring looks like and how often we redraw. setinterval simply calls our canvasstate’s draw method. our interval of 30 means that we call the draw method every 30 milliseconds. // **** options! **** this.selectioncolor = '#cc0000'; this.selectionwidth = 2; this.interval = 30; setinterval(function() { mystate.draw(); }, mystate.interval); } drawing now we’re set up to draw every 30 milliseconds, which will allow us to continuously update the canvas so it appears like the shapes we drag are smoothly moving around. however, drawing doesn’t just mean drawing the shapes over and over; we also have to clear the canvas on every draw. if we don’t clear it, dragging will look like the shape is making a solid line because none of the old shape-positions will go away. because of this, we clear the entire canvas before each draw frame. this can get expensive, and we only want to draw if something has actually changed within our framework, which is why we have the “valid” flag in our canvasstate. after everything is drawn the draw method will set the valid flag to true. then, ocne we do something like adding a new shape or trying to drag a shape, the state will get invalidated and draw() will clear, redraw all objects, and set the valid flag again. // while draw is called as often as the interval variable demands, // it only ever does something if the canvas gets invalidated by our code canvasstate.prototype.draw = function() { // if our state is invalid, redraw and validate! if (!this.valid) { var ctx = this.ctx; var shapes = this.shapes; this.clear(); // ** add stuff you want drawn in the background all the time here ** // draw all shapes var l = shapes.length; for (var i = 0; i < l; i++) { var shape = shapes[i]; // we can skip the drawing of elements that have moved off the screen: if (shape.x > this.width || shape.y > this.height || shape.x + shape.w < 0 || shape.y + shape.h < 0) return; shapes[i].draw(ctx); } // draw selection // right now this is just a stroke along the edge of the selected shape if (this.selection != null) { ctx.strokestyle = this.selectioncolor; ctx.linewidth = this.selectionwidth; var mysel = this.selection; ctx.strokerect(mysel.x,mysel.y,mysel.w,mysel.h); } // ** add stuff you want drawn on top all the time here ** this.valid = true; } } we go through all of shapes[] and draw each one in order. this will give the nice appearance of later shapes looking as if they are on top of earlier shapes. after all the shapes are drawn, a selection handle (if there is a selection) gets drawn around the shape that this.selection references. if you wanted a background (like a city) or a foreground (like clouds), one way to add them is to put them before or after the main two drawing bits. there are often better ways though, like using multiple canvases or a css background-image, but we won’t go over that here. getting mouse coordinates on canvas getting good mouse coordinates is a little tricky on canvas. you could use offsetx/y and layerx/y, but layerx/y is deprecated in webkit (chrome and safari) and firefox does not have offsetx/y. the most bulletproof way to get the correct mouse position is shown below. you have to walk up the tree adding the offsets together. then you must add any padding or border to the offset. finally, to fix coordinate problems when you have fixed-position elements on the page (like the wordpress admin bar or a stumbleupon bar) you must add the ’s offsettop and offsetleft. then you simply subtract that offset from the e.pagex/y values and you’ll get perfect coordinates in almost every possible situation. // creates an object with x and y defined, // set to the mouse position relative to the state's canvas // if you wanna be super-correct this can be tricky, // we have to worry about padding and borders canvasstate.prototype.getmouse = function(e) { var element = this.canvas, offsetx = 0, offsety = 0, mx, my; // compute the total offset if (element.offsetparent !== undefined) { do { offsetx += element.offsetleft; offsety += element.offsettop; } while ((element = element.offsetparent)); } // add padding and border style widths to offset // also add the offsets in case there's a position:fixed bar offsetx += this.stylepaddingleft + this.styleborderleft + this.htmlleft; offsety += this.stylepaddingtop + this.stylebordertop + this.htmltop; mx = e.pagex - offsetx; my = e.pagey - offsety; // we return a simple javascript object (a hash) with x and y defined return {x: mx, y: my}; } there are a few little methods i added that are not shown, such as shape’s method to see if a point is inside its bounds. you can see and download the full demo source here . now that we have a basic structure down, it is easy to write code that handles more complex shapes, like paths or images or video. rotation and scaling these things takes a bit more work, but is quite doable with the canvas and our selection method is already set up to deal with them. if you would like to see this code enhanced in future posts (or have any fixes), let me know. source: http://simonsarris.com/blog/510-making-html5-canvas-useful
December 21, 2011
by Simon Sarris
· 11,339 Views · 1 Like
  • Previous
  • ...
  • 858
  • 859
  • 860
  • 861
  • 862
  • 863
  • 864
  • 865
  • 866
  • 867
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×