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 Languages Topics

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,818 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,733 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,284 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
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,368 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,259 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,092 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,285 Views · 1 Like
article thumbnail
How to Check if a Date is More or Less Than a Month Ago with PHP
Let’s say we have the following problem: we have to check whether a date is more than a month ago or less than a month ago. Many developers go in the wrong direction by calculating the current month and then subtracting the number of months from it. Of course, this approach is slow and full of risks of allowing bugs. Since, two months before January, which is the first month of the year, is actually November, which is the eleventh month. Because of these pitfalls, this approach is entirely wrong. strtotime() is a lot more powerful than you think! The question is whether PHP cannot help us with built-in functions to perform these calculations for us. It is obvious, that from version 5.3.0 and later, there is an OOP section, which is great, but unfortunately this version is still not updated everywhere. So, how to accomplish the task? The Wrong Approach As I said, there are many ways to go in the wrong direction. One of them is to subtract 30 days from current date. This is completely wrong, because not every month has 30 days. Here, some developers will begin to predefine arrays to indicate the number of days in each month, which then will be used in their complicated calculations. Here is an example of this wrong approach. echo date('Y-m-d', strtotime(date('Y-m-d')) - 60*60*24*30); This line is full of mistakes. First of all strtotime(date(‘Y-m-d’)) can be replaced by the more elegant strtotime(‘now’), but for this later. Another big mistake is that 60*60*24*30, which is number of seconds in 30 days can be predefined as a constant. Eventually the result is wrong, because not every month has 30 days. The Correct Approach A small research of the problem and the functions in versions prior of 5.3.0 of PHP is needed. Typical case study of date formatting happen when working with dates from a database. The following code is a classical example. // 2008 05 23, 2008-05-23 is stored into the DB echo date('Y m d', strtotime('2008-05-23')); // 2008 May 23 echo date('Y F d', strtotime('2008-05-23')); The problem, perhaps, is that too often strtotime() is used like this, with exactly this type of strings. However much more interesting is that strtotime() can do much more. strtotime() Can Do Much More Let us first look at the documentation of this function. What parameters it accepts? int strtotime ( string $time [, int $now = time() ] ) The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied. In particular we are interested in the first parameter, time. time - A date/time string. Valid formats are explained in Date and Time Formats. It is especially important to note what are the valid Date and Time Formats. Here are the supported formats, but most interesting are those that are Relative. Exactly these formats are very convenient in our case, because they give us the ability to work with human readable strings, and here are some examples from the documentation of strtotime(). echo strtotime("now"), "\n"; echo strtotime("10 September 2000"), "\n"; echo strtotime("+1 day"), "\n"; echo strtotime("+1 week"), "\n"; echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n"; echo strtotime("next Thursday"), "\n"; echo strtotime("last Monday"), "\n"; Thus, a valid string would be “1 month ago”. // if current date is 2011-11-04, this will return 2011-10-04 echo date('Y-m-d', strtotime('1 month ago')) Or “-1 month”: // the same as the example above echo date('Y-m-d', strtotime('-1 month')); It’s interesting that “+1 -1 month” is also a valid string. // 2011-10-04, if today's 2011-11-04 echo date('Y-m-d', strtotime('+1 -1 month')); In fact strtotime() can do a lot more than most of the developers have ever imagined. Maybe its frequent use with string formatted dates (2010-01-13) makes it a bit unknown. Here are some interesting use cases. // 1970-01-01, Calculations in braces are bad! echo date('Y-m-d', strtotime('(60*60) minute')); // 2 months into the future echo date('Y-m-d', strtotime('-2 months ago')); For instance, do you know how to get the date of the day before yesterday? Yes 2 days before today, but here’s yet another solution. // 1 day before yesterday echo date('Y-m-d', strtotime('yesterday -1 day')); Another example is the fully human readable: // get the first monday of the current month echo date('Y-m-d', strtotime('first monday this month')); The Solution of the Task Finally, what is the solution of the original task? Well, just have to check whether a date is more or less than a month ago. // a random date $my_date = '2011-09-23'; // true if my_date is more than a month ago (strtotime($my_date) < strtotime('1 month ago')) Related posts: Thing to Know About PHP Arrays javascript get locale month with full name PHP Strings: How to Get the Extension of a File Source: http://www.stoimen.com/blog/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/
December 18, 2011
by Stoimen Popov
· 39,197 Views
article thumbnail
Estimating Java Object Sizes with Instrumentation
Most Java developers who come from a C/C++ background have probably at one time wished for a Java equivalent of sizeof(). Although Java lacks a true sizeof() equivalent, the Instrumentation interface introduced with J2SE5 can be used to get an estimate of the size of a particular object via its getObjectSize(Object) method. Although this approach only supports the object being considered itself and does not take into account the sizes of the objects it references, code can be built to traverse those references and calculate an estimated total size. The Instrumentation interface provides several methods, but the focus of this post is the getObjectSize(Object) method. This method's Javadoc documentation describes the method: Returns an implementation-specific approximation of the amount of storage consumed by the specified object. The result may include some or all of the object's overhead, and thus is useful for comparison within an implementation but not between implementations. The estimate may change during a single invocation of the JVM. This description tells us what the method does (provides an "implementation-specific approximation" of the specified object's size), its potential inclusion of overhead in the approximated size, and its potentially different values during a single JVM invocation. It's fairly obvious that one can call Instrumentation.getObjectSize(Object) on an object to get its approximate size, but how does one access an instance of Instrumentation in the first place? The package documentation for the java.lang.instrument package provides the answer (and is an example of an effective Javadoc package description). The package-level documentation for the java.lang.instrument package describes two ways an implementation might allow use JVM instrumentation. The first approach (and the one highlighted in this post) is to specify an instrumentation agent via the command-line. The second approach is to use an instrumentation agent with an already running JVM. The package documentation goes on to explain a high-level overview of using each approach. In each approach, a specific entry is required in the agent JAR's manifest file to specify the agent class: Premain-Class for the command-line approach and Agent-Class for the post-JVM startup approach. The agent class requires a specific method be implemented for either case: premain for command-line startup or agentmain forpost JVM startup. The next code listing features the Java code for the instrumentation agent. The class includes both a premain (command-line agent) method and a agentmain (post JVM startup agent) method, though only the premain will be demonstrated in this post. package dustin.examples; import static java.lang.System.out; import java.lang.instrument.Instrumentation; /** * Simple example of an Instrumentation Agent adapted from blog post * "Instrumentation: querying the memory usage of a Java object" * (http://www.javamex.com/tutorials/memory/instrumentation.shtml). */ public class InstrumentationAgent { /** Handle to instance of Instrumentation interface. */ private static volatile Instrumentation globalInstrumentation; /** * Implementation of the overloaded premain method that is first invoked by * the JVM during use of instrumentation. * * @param agentArgs Agent options provided as a single String. * @param inst Handle to instance of Instrumentation provided on command-line. */ public static void premain(final String agentArgs, final Instrumentation inst) { out.println("premain..."); globalInstrumentation = inst; } /** * Implementation of the overloaded agentmain method that is invoked for * accessing instrumentation of an already running JVM. * * @param agentArgs Agent options provided as a single String. * @param inst Handle to instance of Instrumentation provided on command-line. */ public static void agentmain(String agentArgs, Instrumentation inst) { out.println("agentmain..."); globalInstrumentation = inst; } /** * Provide the memory size of the provided object (but not it's components). * * @param object Object whose memory size is desired. * @return The size of the provided object, not counting its components * (described in Instrumentation.getObjectSize(Object)'s Javadoc as "an * implementation-specific approximation of the amount of storage consumed * by the specified object"). * @throws IllegalStateException Thrown if my Instrumentation is null. */ public static long getObjectSize(final Object object) { if (globalInstrumentation == null) { throw new IllegalStateException("Agent not initialized."); } return globalInstrumentation.getObjectSize(object); } } The agent class above exposes a statically available method for accessing Instrumentation.getObjectSize(Object). The next code listing demonstrates a simple 'application' that makes use of it. package dustin.examples; import static java.lang.System.out; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.List; /** * Build up some sample objects and throw them at the Instrumentation example. * * Might run this class as shown next: * java -javaagent:dist\agent.jar -cp dist\agent.jar dustin.examples.InstrumentSampleObjects * * @author Dustin */ public class InstrumentSampleObjects { public enum Color { RED, WHITE, YELLOW } /** * Print basic details including size of provided object to standard output. * * @param object Object whose value and size are to be printed to standard * output. */ public static void printInstrumentationSize(final Object object) { out.println( "Object of type '" + object.getClass() + "' has size of " + InstrumentationAgent.getObjectSize(object) + " bytes."); } /** * Main executable function. * * @param arguments Command-line arguments; none expected. */ public static void main(final String[] arguments) { final StringBuilder sb = new StringBuilder(1000); final boolean falseBoolean = false; final int zeroInt = 0; final double zeroDouble = 0.0; final Long zeroLong = 0L; final long zeroLongP = 0L; final Long maxLong = Long.MAX_VALUE; final Long minLong = Long.MIN_VALUE; final long maxLongP = Long.MAX_VALUE; final long minLongP = Long.MIN_VALUE; final String emptyString = ""; final String string = "ToBeOrNotToBeThatIsTheQuestion"; final String[] strings = {emptyString, string, "Dustin"}; final String[] moreStrings = new String[1000]; final List someStrings = new ArrayList(); final EmptyClass empty = new EmptyClass(); final BigDecimal bd = new BigDecimal("999999999999999999.99999999"); final Calendar calendar = Calendar.getInstance(); printInstrumentationSize(sb); printInstrumentationSize(falseBoolean); printInstrumentationSize(zeroInt); printInstrumentationSize(zeroDouble); printInstrumentationSize(zeroLong); printInstrumentationSize(zeroLongP); printInstrumentationSize(maxLong); printInstrumentationSize(maxLongP); printInstrumentationSize(minLong); printInstrumentationSize(minLongP); printInstrumentationSize(maxLong); printInstrumentationSize(maxLongP); printInstrumentationSize(emptyString); printInstrumentationSize(string); printInstrumentationSize(strings); printInstrumentationSize(moreStrings); printInstrumentationSize(someStrings); printInstrumentationSize(empty); printInstrumentationSize(bd); printInstrumentationSize(calendar); printInstrumentationSize(Color.WHITE); } } To use the instrumentation agent via the command-line start-up, I need to ensure that a simple metafile is included in the agent JAR. It might look like what follows in the next code listing for the agent class in this case (dustin.examples.InstrumentationAgent). Although I only need the Premain-class entry for the command-line startup of the agent, I have included Agent-class as an example of how to use the post JVM startup agent. It doesn't hurt anything to have both present just as it did not hurt anything to have both premain and agentmain methods defined in the object class. There are prescribed rules for which of these is first attempted based on the type of agent being used. Premain-class: dustin.examples.InstrumentationAgent Agent-class: dustin.examples.InstrumentationAgent To place this manifest file into the JAR, I could use the jar cmf with the name of the manifest file and the Java classes to be archived into the JAR. However, it's arguably easier to do with Ant and certainly is preferred for repeatedly doing this. A simple use of the Ant jar task with the manifest sub-element is shown next. With the JAR built, I can easily run it with the Java launcher and specifying the Java agent (-javaagent): java -javaagent:dist\Instrumentation.jar -cp Instrumentation.jar dustin.examples.InstrumentSampleObjects The next screen snapshot shows the output. The above output shows some of the estimated sizes of various objects such as BigDecimal, Calendar, and others. There are several useful resources related to the topic of this post. The java.sizeOf Project is "a little java agent what use the package java.lang.Instrument introduced in Java 5 and is released under GPL license." Dr. Heinz M. Kabutz's Instrumentation Memory Counter provides a significantly more sophisticated example than my post of using the Instrumentation interface to estimate object sizes. Instrumentation: querying the memory usage of a Java object provides a nice overview of this interface and provides a link to the Classmexer agent, "a simple Java instrumentation agent that provides some convenience calls for measuring the memory usage of Java objects from within an application." The posts How much memory the java objects consume? and Estimating the memory usage of a java object are also related. From http://marxsoftware.blogspot.com/2011/12/estimating-java-object-sizes-with.html
December 17, 2011
by Dustin Marx
· 33,867 Views · 1 Like
article thumbnail
Practical PHP Refactoring: Encapsulate Downcast (and Wrapping)
In statically typed languages, each variable must have a minimal type known at compile time. PHP instead, a is dynamic language where variable can contain any object, and the only enforcement of an interface can be performed on method parameters via type hinting. Statically typed languages sometimes encounter the problem of downcasting: the compiler is only able to guarantee a basic type, and the object contained instead is an instance of a richer subtype. A Java example can be a collection of Object instances where some of them are actually a String: to obtain a String instance to be able to call string.startsWith("prefix_"), the code using the collection needs a down cast: String myString = (String) myObject; This problem was really diffused in old Java code (before Generics introduction) and still today in some cases. What about PHP? You'll never need to downcast objects: variables can contain handlers to objects or even scalars without compile-time checks. Casting with (ClassName) is not even supported by the language (while casting a non-object with (object) will give you a stdClass.) Downcasting however means to promote a variable from a stricter interface to a richer one: we will apply this refactoring to scalars and their OO equivalents, Value Objects. Note that in Fowler's book downcasting is applied only to objects: the same instance just aquires a new (larger) interface. Since this casting is absent in PHP and the type coincide with the current content of the variable, we will talk about conversions of variables to different types. Scalars First of all, you may need to cast scalar variables to other types (e.g. integer to boolean). PHP rules tell us how they are evaluated in its specification for type juggling. Encapsulate Downcast is equally valid when we want to convert a type and only want to expose the right one. For example, we want to avoid this smelly code: public function isASeatAvailable() { return $this->numberOfSeats - 42; // 42 is a total of sold tickets } $result = (bool) $theater->isASeatAvailable(); The (bool) cast will be spread throughout all the client code calling $object. The logic of the refactoring is the same as for the casts on objects: encapsulating them into the method results in a cleaner API and the lack of duplication of the cast in all the client code. Value Objects Another form of casting/conversion that we need in hybrid languages like PHP is the conversion of a primitive (scalar or array) value into an object (Value Object usually). Sometimes this conversion gets duplicated like for the case of casting primitives: $topic = new Topic($object->getAllPosts()); $firstPage = new Topic($topic->getPart($offset = 0, $limit = 10)); A simple reason for why this happens in this little example is that the the Topic object, representing a collection of Posts, gets introduced into the codebase to host some new methods that make sense only on a set of Posts. However, it is not introduced in all the code, since it will take long for such a refactoring to be completed. The result is that conversions to and from the primitive structure flourish; what we want to target with this refactoring is to encapsulate the initial conversions as much as possible, an only work with a closed algebra of objects in all the rest of the code: /** @var Topic */ $topic = $object->getAllPosts(); /** @var Topic */ $firstPage = $topic->getPart(0, 10); /** @var Topic */ $filteredTopic = $topic->getSelectedPostsForQuery("refactoring"); Docblocks Docblocks applied to methods have also to be modified to reflect into the API documentation what you're returning (an object, a Traversable, an IteratorAggregate or a MyIterator). Thus this refactoring affects them. While the @return information is embodied into the code in statically typed languages, PHP gives you freedom to return whichever type you need but does not provide a formal way to document the choices. The standard however, is the @return annotation: /** * @return Traversable containing strings */ public function threadTitles() { ... } Steps The most important step in applying this refactoring is to identify the cases where it would work. There are many possible smells: new MyClass(...) statements often executed on the result of a method. Value Objects having many getters for their fields, or calculated fields, can often return another Value Object; look for duplicated logic on the client code. Ultimately (the other way around), any method returning an array or scalar value is a suspect. The second step is moving the down cast into the method. This mean modifying both the call and for objects, while you can do one step at the time in the case of scalar casting due to the (type) operation being idempotent. Finally, remember to update the docblock of the modified methods accordingly. Example In the example, we target the most useful case: a Value Object whose creation from its primitive value should be encapsulated in a method. This object models a license plate used in a Car. I just implemented the most basic case of advancement of a plate (it will overflow after 26 next() calls), to keep this code simple and to the point. We see next() is the target of our refactoring. next()); $this->assertEquals(new Plate('AB123XZ'), $newPlate); } } class Plate { private $value; public function __construct($value) { $this->value = $value; } /** * @return string */ public function next() { // we're dealing just with the basic case $lastLetter = substr($this->value, -1); $lastLetter++; $nextValue = substr_replace($this->value, $lastLetter, -1); return $nextValue; } } In a single step we can keep the test passing. We modify what is expected by the client code, now a Plate instance: next(); $this->assertEquals(new Plate('AB123XZ'), $newPlate); } } We modify the docblock, in particular @return, and we perform the instantiation inside the method. class Plate { private $value; public function __construct($value) { $this->value = $value; } /** * @return Plate */ public function next() { // we're dealing just with the basic case $lastLetter = substr($this->value, -1); $lastLetter++; $nextValue = substr_replace($this->value, $lastLetter, -1); return new self($nextValue); } }
December 14, 2011
by Giorgio Sironi
· 9,978 Views
article thumbnail
Easy Deep Cloning of Serializable and Non-Serializable Objects in Java
Frequently developers rely on 3d party libraries to avoid reinventing the wheel, particularly in the Java world, with projects like Apache and Spring so prevalent. When dealing with these frameworks, we often have little or no control of the behaviour of their classes. This can sometimes lead to problems. For instance, if you want to deep clone an object that doesn’t provide a suitable clone method, what are your options, short of writing a bunch of code? Clone through Serialization The simplest approach is to clone by taking advantage of an object being Serializable. Apache Commons provides a method to do this, but for completeness, code to do it yourself is below also. @SuppressWarnings("unchecked") public static T cloneThroughSerialize(T t) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); serializeToOutputStream(t, bos); byte[] bytes = bos.toByteArray(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); return (T)ois.readObject(); } private static void serializeToOutputStream(Serializable ser, OutputStream os) throws IOException { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(os); oos.writeObject(ser); oos.flush(); } finally { oos.close(); } } // using our custom method Object cloned = cloneThroughSerialize (someObject); // or with Apache Commons cloned = org.apache.commons.lang. SerializationUtils.clone(someObject); But what if the class we want to clone isn’t Serializable and we have no control over the source code or can’t make it Serializable? Option 1 – Java Deep Cloning Library There’s a nice little library which can deep clone virtually any Java Object – cloning. It takes advantage of Java’s excellent reflection capabilities to provide optimized deep-cloned versions of objects. Cloner cloner=new Cloner(); Object cloned = cloner.deepClone(someObject); As you can see, it’s very simple and effective, and requires minimal code. It has some more advanced abilities beyond this simple example, which you can check out here. Option 2 – JSON Cloning What about if we are not able to introduce a new library to our codebase? Some of us deal with approval processes to introduce new libraries, and it may not be worth it for a simple use case. Well, as long as we have some way to serialize and restore an object, we can make a deep copy. JSON is commonly used, so it’s a good candidate,since most of us use one JSON library or another. Most JSON libraries in Java have the ability to effectively serialize any POJO without any configuration or mapping required. This means that if you have a JSON library and cannot or will not introduce more libraries to provide deep cloning, you can leverage an existing JSON library to get the same effect. Note this method will be slower than others, but for the vast majority of applications, this won’t cause any performance problems. Below is an example using the GSON library. @SuppressWarnings("unchecked") public static T cloneThroughJson(T t) { Gson gson = new Gson(); String json = gson.toJson(t); return (T) gson.fromJson(json, t.getClass()); } // ... Object cloned = cloneThroughJson(someObject); Note that this is likely only to work if the copied object has a default no-argument constructor. In the case of GSON, you can use an instance creator to get around this. Other frameworks have similar concepts, so you can use that if you hit an issue with an unmodifiable class having not having the default constructor. Conclusion One thing I do recommend is that for any classes you need to clone, you should add some unit tests to ensure everything behaves as expected. This can prevent changes to the classes (e.g. upgrading library versions) from breaking your application without your knowledge, especially if you have a continuous integration environment set up. I’ve outlined a couple methods to clone an object outside of normal cases without any custom code. If you’ve used any other methods to get the same result, please share. From http://www.carfey.com/blog/easy-deep-cloning-of-serializable-and-non-serializable-objects-in-java/
December 13, 2011
by Carey Flichel
· 30,664 Views · 1 Like
article thumbnail
Saving Objects In Redis And Php
// A fairly generic method to store arrays and also to add them to a pool to reverse lookup their ids based on values that they contain. This method extends my own redis client but will work for the better clients out there such as predis. class storage extends redis { public function save($key, array $object, $timestamp=true){ $timestamp && $object['timestamp'] = date('Ymdhis'); $id = $this->incr('id:'.$key); foreach ($object as $k => $v) { $this->sadd(sprintf("%s:%s:%s", $key, $k, $v), $id); } $key = sprintf("%s:%s", $key, $id); $this->hmset($key, $object); } }
December 7, 2011
by Snippets Manager
· 3,450 Views
article thumbnail
Reusing Generated JAXB Classes
In this post I will demonstrate how to leverage the -episode XJC extension to reuse classes previously generated from.an XML schema. This is useful when an XML schema is imported by other XML schemas and you do not want the same classes generated each time. Imported Schema (Product.xsd) The following XML schema represents basic information about a product. Product is a common concept in this example domain so I have decided to define one representation that can be leveraged by other schemas, rather than having each schema define its own representation of product information. Since multiple XML schemas import Product.xsd we can leverage episode files so that the classes corresponding to Product.xsd are only generated once. The following XJC call demonstrates how to generate an episode file called product.episode along with the generated classes: xjc -d out -episode product.episode Product.xsd Importing Schema (ProductPurchaseRequest.xsd) Below is an example of an XML schema that imports Product.xsd: When we generate classes from this XML schema we will reference the episode file we created when we generated Java classes from Product.xsd. If we do not specify the episode file then classes will be generated for both ProductPurchaseRequest.xsd and Product.xsd: xjc -d out ProductPurchaseRequest.xsd -extension -b product.episode Another Importing Schema (ProductQuoteRequest.xsd) Below is another example of an XML schema that imports Product.xsd: Again when we generate classes from this XML schema we will reference the episode file we created when we generated Java classes from Product.xsd. xjc -d out ProductQuoteRequest.xsd -extension -b product.episode How Does it Work? (product.episode) For those of you curious how this works. The episode file generated by XJC is really just a standard JAXB bindings file that is used to customize the class generation. This generated bindings/episode file contains entries that tells XJC that a class already exists for this type. You could write this file by hand, but -episode flag to XJC does it for you. From http://blog.bdoughan.com/2011/12/reusing-generated-jaxb-classes.html
December 6, 2011
by Blaise Doughan
· 16,354 Views
article thumbnail
Handling footnotes and references in HTML5
This post examines what options one has for handling footnotes and references in HTML. It then presents a library that helps you with handling them. Requirements Handling footnotes and references comes with several requirements: On screen, one wants to show the footnote text as close as possible to the number pointing to the footnote. Whatever solution one chooses, it should also work on touch devices. Hence, a hover-only approach is not feasible. In print, footnotes should be shown, as well. Hence, a tooltip-only solution is not acceptable. Lastly, things should degrade gracefully if JavaScript is switched off. The HTML5 spec recommendations for footnotes The HTML5 specification gives several tips on how to format footnotes. Short inline annotations: title attribute. Customer: Hello! I wish to register a complaint. Hello. Miss? Shopkeeper: Watcha mean, miss? Customer: Uh, I'm sorry, I have a cold. I wish to make a complaint. Shopkeeper: Sorry, we're closing for lunch. Longer annotations: bidirectional linking via : Announcer: Number 16: The hand. Interviewer: Good evening. I have with me in the studio tonight Mr Norman St John Polevaulter, who for the past few years has been contradicting people. Mr Polevaulter, why do you contradict people? Norman: I don't. [1] Interviewer: You told me you did! ... [1] This is, naturally, a lie, but paradoxically if it were true he could not say so without contradicting the interviewer and thus making it false. Wikipedia-style highlighting of the currently active footnote The CSS pseudo-selector :target allows you to style the HTML element whose ID is the same as the page fragment identifier: li:target { background-color: #BFEFFF; } Thus, if the page URL ends with #explanation then the following list item would be highlighted: It works like this: ... Using the html_footnotes library You can download html_footnotes on GitHub and try it out online. Terminology: An annotation is either a footnote or a reference (citation). The markers in the main text referring to those annotations are called annotation pointers. A footnote pointer is a number written in parentheses. Example: (1) A reference pointer is a number written in square brackets. Example: [1] Activating the library: The library consists of CSS to style annotations and pointers and of JavaScript that post-processes the HTML so that less code has to be written. Footnotes: The library processes the HTML so that footnote pointers are formatted as superscript and become links that, when clicked on, display the text of the footnote inline. You can use an IIFE(1) to avoid the global namespace(2) being polluted. ... Footnotes IIFE is an acronym for Immediately-Invoked Function Expression.The global scope is reified as an object in JavaScript. References: Reference pointers are processed and become links. The library also adds IDs to the reference list items. Due to the appropriate CSS, a list item will be highlighted and scrolled to if one clicks on a pointer. JavaScript has many functional language constructs [1]. For example: consult [2] for an introduction to closures. ... References Functional programming. In Wikipedia. Retrieved 2011-12-03.Douglas Crockford, JavaScript: The Good Parts. O’Reilly. 2008-05-16. Source: http://www.2ality.com/2011/12/footnotes.html
December 5, 2011
by Axel Rauschmayer
· 20,269 Views
article thumbnail
MySQL vs. Neo4j on a Large-Scale Graph Traversal
this post presents an analysis of mysql (a relational database) and neo4j (a graph database) in a side-by-side comparison on a simple graph traversal. the data set that was used was an artificially generated graph with natural statistics. the graph has 1 million vertices and 4 million edges. the degree distribution of this graph on a log-log plot is provided below. a visualization of a 1,000 vertex subset of the graph is diagrammed above. loading the graph the graph data set was loaded both into mysql and neo4j. in mysql a single table was used with the following schema. create table graph ( outv int not null, inv int not null ); create index outv_index using btree on graph (outv); create index inv_index using btree on graph (inv); after loading the data, the table appears as below. the first line reads: “vertex 0 is connected to vertex 1.” mysql> select * from graph limit 10; +------+-----+ | outv | inv | +------+-----+ | 0 | 1 | | 0 | 2 | | 0 | 6 | | 0 | 7 | | 0 | 8 | | 0 | 9 | | 0 | 10 | | 0 | 12 | | 0 | 19 | | 0 | 25 | +------+-----+ 10 rows in set (0.04 sec) the 1 million vertex graph data set was also loaded into neo4j. in gremlin , the graph edges appear as below. the first line reads: “vertex 0 is connected to vertex 992915.” gremlin> g.e[1..10] ==>e[183][0-related->992915] ==>e[182][0-related->952836] ==>e[181][0-related->910150] ==>e[180][0-related->897901] ==>e[179][0-related->871349] ==>e[178][0-related->857804] ==>e[177][0-related->798969] ==>e[176][0-related->773168] ==>e[175][0-related->725516] ==>e[174][0-related->700292] warming up the caches before traversing the graph data structure in both mysql and neo4j, each database had a “ warm up ” procedure run on it. in mysql, a “select * from graph” was evaluated and all of the results were iterated through. in neo4j, every vertex in the graph was iterated through and the outgoing edges of each vertex were retrieved. finally, for both mysql and neo4j, the experiment discussed next was run twice in a row and the results of the second run were evaluated. traversing the graph the traversal that was evaluated on each database started from some root vertex and emanated n-steps out. there was no sorting, no distinct-ing, etc. the only two variables for the experiments are the length of the traversal and the root vertex to start the traversal from. in mysql, the following 5 queries denote traversals of length 1 through 5. note that the “?” is a variable parameter of the query that denotes the root vertex. select a.inv from graph as a where a.outv=? select b.inv from graph as a, graph as b where a.inv=b.outv and a.outv=? select c.inv from graph as a, graph as b, graph as c where a.inv=b.outv and b.inv=c.outv and a.outv=? select d.inv from graph as a, graph as b, graph as c, graph as d where a.inv=b.outv and b.inv=c.outv and c.inv=d.outv and a.outv=? select e.inv from graph as a, graph as b, graph as c, graph as d, graph as e where a.inv=b.outv and b.inv=c.outv and c.inv=d.outv and d.inv=e.outv and a.outv=? for neo4j, the blueprints pipes framework was used. a pipe of length n was constructed using the following static method. public static pipeline createpipeline(final integer steps) { final arraylist pipes = new arraylist(); for (int i = 0; i < steps; i++) { pipe pipe1 = new vertexedgepipe(vertexedgepipe.step.out_edges); pipe pipe2 = new edgevertexpipe(edgevertexpipe.step.in_vertex); pipes.add(pipe1); pipes.add(pipe2); } return new pipeline(pipes); } for both mysql and neo4j, the results of the query (sql and pipes) were iterated through. thus, all results were retrieved for each query. in mysql, this was done as follows. while (resultset.next()) { resultset.getint(finalcolumn); } in neo4j, this is done as follows. while (pipeline.hasnext()) { pipeline.next(); } experimental results the artificial graph dataset was constructed with a “ rich get richer “, preferential attachment model . thus, the vertices created earlier are the most dense (i.e. highest number of adjacent vertices). this property was used to limit the amount of time it would take to evaluate the tests for each traversal. only the first 250 vertices were used as roots of the traversals. before presenting timing results, note that all of these experiments were run on a macbook pro with a 2.66ghz intel core 2 duo and 4gigs of ram at 1067 mhz ddr3. the packages used were java 1.6, mysql jdbc 5.0.8, and blueprints pipes 0.1.2. java version "1.6.0_17" java(tm) se runtime environment (build 1.6.0_17-b04-248-10m3025) java hotspot(tm) 64-bit server vm (build 14.3-b01-101, mixed mode) the following java virtual machine parameters were used: -xmx1000m -xms500m below are the total running times for both mysql (red) and neo4j (blue) for traversals of length 1, 2, 3, and 4. the raw data is presented below along with the total number of vertices returned by each traversal—which, of course, is the same for both mysql and neo4j given that its the same graph data set being processed. also realize that traversals can loop and thus, many of the same vertices are returned multiple times. finally, note that only neo4j has the running time for a traversal of length 5. mysql did not finish after waiting 2 hours to complete. in comparison, neo4j took 14.37 minutes to complete a 5 step traversal. [mysql steps-1] time(ms):124 -- vertices_returned:11360 [mysql steps-2] time(ms):922 -- vertices_returned:162640 [mysql steps-3] time(ms):8851 -- vertices_returned:2206437 [mysql steps-4] time(ms):112930 -- vertices_returned:28125623 [mysql steps-5] n/a [neo4j steps-1] time(ms):27 -- vertices_returned:11360 [neo4j steps-2] time(ms):474 -- vertices_returned:162640 [neo4j steps-3] time(ms):3366 -- vertices_returned:2206437 [neo4j steps-4] time(ms):49312 -- vertices_returned:28125623 [neo4j steps-5] time(ms):862399 -- vertices_returned:358765631 next, the individual data points for both mysql and neo4j are presented in the plot below. each point denotes how long it took to return n number of vertices for the varying traversal lengths. finally, the data below provides the number of vertices returned per millisecond (on average) for each of the traversals. again, mysql did not finish in its 2 hour limit for a traversal of length 5. [mysql steps-1] vertices/ms:91.6128847554668 [mysql steps-2] vertices/ms:176.399127537985 [mysql steps-3] vertices/ms:249.286746556076 [mysql steps-4] vertices/ms:249.053599519823 [mysql steps-5] n/a [neo4j steps-1] vertices/ms:420.740351166341 [neo4j steps-2] vertices/ms:343.122344772028 [neo4j steps-3] vertices/ms:655.507125256186 [neo4j steps-4] vertices/ms:570.360621871775 [neo4j steps-5] vertices/ms:416.00886711325 conclusion in conclusion, given a traversal of an artificial graph with natural statistics, the graph database neo4j is more optimal than the relational database mysql. however, no attempts have been made to optimize the java vm, the sql queries, etc. these experiments were run with both neo4j and mysql “out of the box” and with a “natural syntax” for both types of queries. source: http://markorodriguez.com/2011/02/18/mysql-vs-neo4j-on-a-large-scale-graph-traversal/
December 5, 2011
by Marko Rodriguez
· 58,404 Views · 1 Like
article thumbnail
JAXB and Namespace Prefixes
In a previous post I covered how to use namespace qualification with JAXB. In this post I will cover how to control the prefixes that are used. This is not covered in the JAXB (JSR-222) specification but I will demonstrate the extensions available in both the reference and EclipseLink MOXy implementations for handling this use case Java Model The following domain model will be used for this post. The @XmlRootElement and @XmlElement annotation are used to specify the appropriate namespace qualification. package blog.prefix; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(namespace="http://www.example.com/FOO") public class Root { private String a; private String b; private String c; @XmlElement(namespace="http://www.example.com/BAR") public String getA() { return a; } public void setA(String a) { this.a = a; } @XmlElement(namespace="http://www.example.com/FOO") public String getB() { return b; } public void setB(String b) { this.b = b; } @XmlElement(namespace="http://www.example.com/OTHER") public String getC() { return c; } public void setC(String c) { this.c = c; } } Demo Code We will use the following code to populate the domain model and produce the XML. package blog.prefix; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Demo { public static void main(String[] args) throws Exception { JAXBContext ctx = JAXBContext.newInstance(Root.class); Root root = new Root(); root.setA("A"); root.setB("B"); root.setC("OTHER"); Marshaller m = ctx.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(root, System.out); } } Output XML like the following is produced by default. The JAXB implementation has arbitrarily assigned prefixes to the namespace URIs specified in the domain model: A B OTHER Specify Prefix Mappings with JAXB RI & Metro JAXB The reference and Metro implementations of JAXB provide a mechanism called NamespacePrefixMapper to control the prefixes that will be assigned to namespaces. NamespacePrefixMapper package blog.prefix; import com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper; //import com.sun.xml.bind.marshaller.NamespacePrefixMapper; public class MyNamespaceMapper extends NamespacePrefixMapper { private static final String FOO_PREFIX = ""; // DEFAULT NAMESPACE private static final String FOO_URI = "http://www.example.com/FOO"; private static final String BAR_PREFIX = "bar"; private static final String BAR_URI = "http://www.example.com/BAR"; @Override public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) { if(FOO_URI.equals(namespaceUri)) { return FOO_PREFIX; } else if(BAR_URI.equals(namespaceUri)) { return BAR_PREFIX; } return suggestion; } @Override public String[] getPreDeclaredNamespaceUris() { return new String[] { FOO_URI, BAR_URI }; } } Demo Code The NamespacePrefixMapper is set on an instance of Marshaller. I would recommend wrapping the setPropery call in a try/catch block so that your application does not fail if you change JAXB implementations. package blog.prefix; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Demo { public static void main(String[] args) throws Exception { JAXBContext ctx = JAXBContext.newInstance(Root.class); Root root = new Root(); root.setA("A"); root.setB("B"); root.setC("OTHER"); Marshaller m = ctx.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); try { m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new MyNamespaceMapper()); //m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new MyNamespaceMapper()); } catch(PropertyException e) { // In case another JAXB implementation is used } m.marshal(root, System.out); } } Output The resulting document now uses the NamespacePrefixMapper to determine the prefixes that should be used in the resulting document. A B OTHER Specify Prefix Mappings with EclipseLink JAXB (MOXy) MOXy will use the namespace prefixes as they are defined on the @XmlSchema annotation. In order for MOXy to be able to use the default namespace the elementFormDefault property on the @XmlSchema annotation must be set to XmlNsForm.QUALIFIED. package-info XmlSchema( elementFormDefault=XmlNsForm.QUALIFIED, namespace="http://www.example.com/FOO", xmlns={@XmlNs(prefix="bar", namespaceURI="http://www.example.com/BAR")} ) package blog.prefix; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema; Output The resulting document now uses the xmlns setting from the @XmlSchema annotation to determine the prefixes that should be used in the resulting document. A B OTHER Further Reading If you enjoyed this post then you may also be interested in: JAXB & Namespaces Specifying EclipseLink MOXy as Your JAXB Provider From http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
December 3, 2011
by Blaise Doughan
· 247,440 Views · 8 Likes
article thumbnail
Create Your Own XML/JSON/HTML API with PHP
Develop your own API service for your PHP projects.
December 1, 2011
by Andrei Prikaznov
· 68,147 Views
article thumbnail
Practical PHP Refactoring: Introduce Parameter Object
In the scenario of today, two or more parameters are often passed together to a set of similar methods. This happens for example with timing information containing day and month, or hours and minutes; or, in other domains, with parameters that are coupled to each other - such as an host and a port (google.com, 80), or an image and its alt text. A long list of coupled parameters is not necessarily the sign that a method does too much. Today's refactoring is a solution to simplify the signature and express the coupling between the current parameters: wrapping them into a Parameter Object. Why writing code for a new class? We shouldn't be afraid of adding classes, at the similar pace as we add methods. When parameters are almost always passed together, they will be written down together in each signature and each call: it's a form of duplication and as such can and should be eliminated. Moreover, the duplication is not limited to a single method: the set of coupled arguments can be passed to multiple methods, each called in many more places which must be synchronized. For example, adding a parameter in the initial situation means modifying lots of different source files. The parameters are often the sign of an hidden concept: an object modelling their union. You know you are on the right track if a name for this concepts comes up quickly; otherwise you will have to invent it. This refactoring enables you to put more logic on an object representing this set of values, instead of passing them around in an array (Primitive Obsession) or, like in this case, always together as multiple parameters. The end result is also a shorter and more clear parameter list, again reaching the goal of simplifying method calls as we are doing with lots of refactorings in this part of the series. Steps Create a new class: an instance of this class should wrap the various values which are passed to it in the constructor. The Parameter Object will usually be a Value Object, with an immutable state and with getters for each of its fields (for now). Execute Add Parameter to pass in also the new object (created on the spot) together with the various parameters. For each of the old parameters, apply Remove Parameter on it and access it inside the method by calling a getter on the Parameter Object. The tests should always pass between the steps. The final step enabled by this refactoring consists in moving logic onto the Parameter Object. If you're lucky, this even leads to some of the getters vanishing. Example We have an Invoice object, which accepts some rows in order to calculate a total. A copious amount of money covering the Value Added Tax is added to the net total. addRow(1000); $quotation->specifyTaxes(20, 'VATCODE'); $this->assertEquals(1200, $quotation->getTotal()); $this->assertEquals('Type: VATCODE', $quotation->getTypeOfService()); } } class Quotation { private $netTotal = 0; private $vatPercentage; private $vatCode; public function addRow($row) { // including just the logic to implement the test we have $this->netTotal += $row; } public function specifyTaxes($percentage, $code) { $this->vatPercentage = $percentage; $this->vatCode = $code; } public function getTotal() { return $this->netTotal * (1 + $this->vatPercentage / 100); } public function getTypeOfService() { return 'Type: ' . $this->vatCode; } } We notice two things: one in the rest of the code (not shown here): the 20% percentage and its related code are passed together to many methods. It makes sense, as different codes (bread vs. cars) may imply different tax percentages. in the class itself, the fields storing tax informations have very similar names: $vatRate and $vatCode. This is a mild form of duplication. So we want to transform the couple of parameters into a Parameter Object. We create the class we need: class VatRate { private $rate; private $code; public function __construct($rate, $code) { $this->rate = $rate; $this->code = $code; } public function getRate() { return $this->rate; } public function getCode() { return $this->code; } } Now we can add a parameter to the method, which is an instance of our Parameter Object: addRow(1000); $quotation->specifyTaxes(new VatRate(20, 'VATCODE'), 20, 'VATCODE'); $this->assertEquals(1200, $quotation->getTotal()); $this->assertEquals('Type: VATCODE', $quotation->getTypeOfService()); } } class Quotation { private $netTotal = 0; private $vatRate; private $vatPercentage; private $vatCode; public function addRow($row) { // including just the logic to implement the test we have $this->netTotal += $row; } public function specifyTaxes(VatRate $vatRate, $percentage, $code) { $this->vatRate = $vatRate; $this->vatPercentage = $percentage; $this->vatCode = $code; } public function getTotal() { return $this->netTotal * (1 + $this->vatPercentage / 100); } public function getTypeOfService() { return 'Type: ' . $this->vatCode; } } Invoice objects have all the information they need, available from the VatRate instance. So let's remove $percentage, the first parameter wrapped into the Parameter Object: class Quotation { private $netTotal = 0; private $vatRate; private $vatPercentage; private $vatCode; public function addRow($row) { // including just the logic to implement the test we have $this->netTotal += $row; } public function specifyTaxes(VatRate $vatRate, $code) { $this->vatRate = $vatRate; $this->vatCode = $code; } public function getTotal() { return $this->netTotal * (1 + $this->vatRate->getRate() / 100); } public function getTypeOfService() { return 'Type: ' . $this->vatCode; } } And now we can also remove $code, the other parameter: class Quotation { private $netTotal = 0; private $vatRate; public function addRow($row) { // including just the logic to implement the test we have $this->netTotal += $row; } public function specifyTaxes(VatRate $vatRate) { $this->vatRate = $vatRate; } public function getTotal() { return $this->netTotal * (1 + $this->vatRate->getRate() / 100); } public function getTypeOfService() { return 'Type: ' . $this->vatRate->getCode(); } } We notice this refactoring has enabled a further step: moving the calculation of the tax into VatRate. This also means we can delete the getRate() method. class Quotation { private $netTotal = 0; private $vatRate; public function addRow($row) { // including just the logic to implement the test we have $this->netTotal += $row; } public function specifyTaxes(VatRate $vatRate) { $this->vatRate = $vatRate; } public function getTotal() { return $this->vatRate->tax($this->netTotal); } public function getTypeOfService() { return 'Type: ' . $this->vatRate->getCode(); } } class VatRate { private $rate; private $code; public function __construct($rate, $code) { $this->rate = $rate; $this->code = $code; } public function getCode() { return $this->code; } public function tax($netAmount) { return $netAmount * (1 + $this->rate / 100); } }
November 30, 2011
by Giorgio Sironi
· 12,330 Views
article thumbnail
Two Generally Useful Guava Annotations
Guava currently (Release 10) includes four annotations in its com.google.common.annotations package: Beta, VisibleForTesting, GwtCompatible, and GwtIncompatible. The last two are specific to use with Google Web Toolkit (GWT), but the former two can be useful in a more general context. The @Beta annotation is used within Guava's own code base to indicate "that a public API (public class, method or field) is subject to incompatible changes, or even removal, in a future release." Although this annotation is used to indicate at-risk public API constructs in Guava, it can also be used in code that has access to Guava on its classpath. Developers can use this annotation to advertise their own at-risk public API constructs. The @Beta annotation is defined as a @Documented, which means that it marks something that is part of the public API and should be considered by Javadoc and other source code documentation tools. The @VisibleForTesting annotation "indicates that the visibility of a type or member has been relaxed to make the code testable." I have never liked having to relax type or member visibility to make something testable. It feels wrong to have to compromise one's design to allow testing to occur. This annotation is better than nothing in such a case because it at least makes it clear to others using the construct that there is a reason for its otherwise surprisingly relaxed visibility. Conclusion Guava provides two annotations that are not part of the standard Java distribution, but cover situations that we often run into during Java development. The @Beta annotation indicates a construct in a public API that may be changed or removed. The @VisibleForTesting annotation advertises to other developers (or reminds the code's author) when a decision was made for relaxed visibility to make testing possible or easier. From http://marxsoftware.blogspot.com/2011/11/two-generally-useful-guava-annotations.html
November 23, 2011
by Dustin Marx
· 45,698 Views · 1 Like
  • Previous
  • ...
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • ...
  • 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
×