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
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,341 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,310 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,890 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
· 10,054 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,764 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,473 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,433 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,563 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,582 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,658 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,253 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,401 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,763 Views · 1 Like
article thumbnail
Eventual Consistency in NoSQL Databases: Theory and Practice
One of NoSQL's goals: handle previously-unthinkable amounts of data. One of unthinkable-amounts-of-data's problems: previously-improbable events become extremely probable, precisely because the set of interactions is so large. Flip a coin a hundred times, and you're not likely to get 50 heads in a row. But flip it a few trillion times, and you probably will find some 50-heads streaks. So NoSQL's performance strength is also its mathematical weakness. This order of scale can result in lots of problems, but one of the most common is consistency -- the C in ACID -- clearly a fundamental desideratum for any database system, but in principle much harder to acheive for NoSQL databases than for others. Emerging database technologies have forced developers and computer scientists to define more exactly what kind of consistency is really needed, for any given application. Two years ago, ACM (the Association for Computing Machinery) published an extremely helpful examination of the attenuated notion of consistency called 'eventual consistency'. Their summary: Data inconsistency in large-scale reliable distributed systems must be tolerated for two reasons: improving read and write performance under highly concurrent conditions; and handling partition cases where a majority model would render part of the system unavailable even though the nodes are up and running. The article surveys technical solutions as well as user considerations that might soften the undesirability of anything less than perfect, instantaneous consistency. It's not long (4 pages plus pictures), and explains some deep database issues quite clearly. On the more practical side of the problem: Russell Brown recently gave a talk at the NoSQL Exchange 2011 on exactly this topic. More specifically, he showed how some distributed systems (Riak in particular) try to minimize conflicts, and suggested some ways to reconcile conflicts automatically using smart semantic techniques. Check out the NoSQL Exchange page for Russell's talk here, which includes an embedded video. But read the ACM article first for a broader overview, since Russell launches into technical details pretty quickly.
November 22, 2011
by John Esposito
· 12,614 Views
article thumbnail
Another approach to mocking properties in Python
mock is a library for testing in python. it allows you to replace parts of your system under test with mock objects. the main feature of mock is that it's simple to use, but mock also makes possible more complex mocking scenarios. this is my philosophy of api design as it happens: simple things should be simple but complex things should be possible . several of these more complex scenarios are shown in the further examples section of the documentation. i've just updated one of these, the example of mocking properties. properties in python are descriptors . when they are fetched from the class of an object they trigger code that is then executed. the code that is executed is the method that you have wrapped as the property getter. note that there is a special rule for attribute lookup on certain types of descriptors, which include properties. even if an instance attribute exists, the class attribute will still be used instead. this is an exception to the normal attribute lookup rule that instance attributes are fetched in preference to class attributes. this is important because it means that when you want to mock a property you have to do it on the class and can't simply stick an attribute onto an object. if you're using mock 0.7, with its support for magic methods , we can patch the property name and add a __get__ method to our mock. the presence of the __get__ method makes it a descriptor, so we can use it as a property: >>> from mock import mock, patch >>> class foo(object): ... @property ... def fish(self): ... return 'fish' ... >>> with patch.object(foo, 'fish') as mock_fish: ... mock_fish.__get__ = mock(return_value='mocked fish') ... foo = foo() ... print foo.fish ... mocked fish >>> mock_fish.__get__.assert_called_with(mock_fish, foo, foo) in this example mock_fish replaces the property and the mock we put in place of __get__ becomes the mocked getter method. as we're patching on the class this affects all instances of foo . there's no point in using magicmock for this. magicmock normallly makes using the python protocol methods simpler by preconfiguring them. as you can see from the example above, mocking __get__ is supported but it isn't hooked up by default. it wouldn't be helpful if mocking any method on a class replaced it with a mock that acted as a descriptor, so if you want a mock to behave as a descriptor then you have to configure __get__ , __set__ and __delete__ yourself. here's an alternative approach that works with all recent-ish versions of mock: >>> from mock import mock, patch >>> class propertymock(mock): ... def __get__(self, instance, owner): ... return self() ... >>> prop_mock = propertymock() >>> with patch.object(foo, 'fish', prop_mock): ... foo = foo() ... prop_mock.return_value = 'mocked fish' ... print foo.fish ... mocked fish >>> prop_mock.assert_called_with() as an added bonus, both of these examples work even if the foo instance is created outside of the patch block. so long as the code using the property is executed whilst the patch is in place the attribute lookup will find our mocked version. source: http://www.voidspace.org.uk/python/weblog/arch_d7_2011_06_04.shtml
November 18, 2011
by Michael Foord
· 28,635 Views
article thumbnail
Tackling the Circular Dependency in Java...
Let me first define what we mean by circular dependency in OOAD terms vis-a-vis Java. Suppose we have a class called A which has class B’s Object. (in UML terms A HAS B). at the same time we class B is also composed of Object of class A (in UML terms B HAS A). obviously this represents circular dependency because while creating the object of A, the compiler must know the size of B... on the other hand while creating object of B, the compiler must know the size of A. this is something like egg vs. chicken problem... this may be possible in real life situation as well. for example suppose a multi storied building has a lift. so in the UML terms, the building HAS lift... but at the same time, suppose, while constructing the lift object, we need to give it the information about the building object to access various functionalities of the Building class... for example, suppose the speed of the lift is set depending on the number of floors of the Building... hence while constructing the Lift object it must access the functionalities of the Building object which will give the number of floors the building has got...hence in UML terms the lift HAS building... so this is a sure case of circular dependency... in real java code it will look something as follows: public class Building { private Lift lift; private int floor; public Building(){ lift = new Lift(); setFloor(15); } public int getFloor(){ return floor; } public void setFloor(int floor){ this.floor = floor; } }//end of class building //class Lift public class Lift { private Building building; private int Speed; public Lift(){ building = new Building(); setSpeed(); } public void setSpeed(){ if (building.getFloor()>20){ //one set of functionalities //may be the the speed of the lift will be more this.Speed = 10; } else { //different set of functionalities //may be the speed of the lift will be less this.Speed = 5; } } public int getSpeed(){ return Speed; } }//end of class Lift As it becomes clear from the above code, that while creating the Building object it will create the Lift object, and while creating the Lift object, it will try to create a Building object to access some of its functionalities... So, ultimately it will go out of memory and we get a StackOverflow runtime exception... So how do we handle this problem in Java? We actually tackle this problem by declaring an IBuildingProxy interface and by deriving our Building class from that... the lift class, instead of Having Building object, it Has IBuildingProxy... the source code of the solution looks like the following... public interface IBuildingProxy { int getFloor(); void setFloor(int floor); } public class Building implements IBuildingProxy{ private Lift lift; private int floor; public Building(){ lift = new Lift(this); setFloor(15); } public int getFloor(){ return floor; } public void setFloor(int floor){ this.floor = floor; } } public class Lift { private IBuildingProxy building; private int Speed; public Lift(Building b){ this.building = b; setSpeed(); } private void setSpeed(){ if (building.getFloor()>20){ / /one set of functionalities //may be the the speed of the lift will be more this.Speed = 10; } else { //different set of functionalities //may be the speed of the lift will be less this.Speed = 5; } } public int getSpeed(){ return Speed; } } public class CircularDependencyTest { public static void main(String[] args){ Building b = new Building(); Lift l = new Lift(b); } } So whats the principle behind such work around... It will be clear soon... As it becomes clear from the code that Building HAS Lift... That is not a problem... Now when it comes to solve the part that Lift HAS Building, instead of the Building object, we have created an IBuildingProxy interface and we pass it to the Lift class... what it essentially means, that the building class knows the memory requirement to initialize the Lift object, and as the Lift class HAS just a proxy interface of the Building, it does not have to care for the Building's memory requirement... and that solves the problem... Hope this discussion becomes helpful for Java learners...
November 17, 2011
by Somenath Mukhopadhyay
· 32,534 Views · 2 Likes
article thumbnail
How You Clear Your HTML5 Canvas Matters
The performance difference between two above methods for clearing an HTML5 canvas can be measured in orders of magnitude or more.
November 15, 2011
by Simon Sarris
· 39,779 Views · 3 Likes
article thumbnail
PHP: Don’t Call the Destructor Explicitly
“PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++”[1] says the documentation for destructors, but let’s see the following class. class A { public function __construct() { echo 'building an object'; } public function __destruct() { echo 'destroying the object'; } } $obj = new A(); Well, as you can not call the constructor explicitly: $obj->__construct(); So we should not call the destructor explicitly: $obj->__destruct(); The problem is that I’ve seen this many times, but it’s a pity that this won’t destroy the object and it is still a valid PHP code. PHP destructors cannot be called explicitly! Constructors and destructors in PHP are part of the so called magic methods. Here’s what the doc page says about them. The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them. To be more precise let’s take a look of the definition of destructors. PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. What if I Call the Destructor Explicitly? Let’s see some examples! class A { public function __destruct() { echo 'destroying the object'; } } $obj = new A(); // prints hello world echo 'hello world'; // PHP interpreter stops the script execution and prints // 'destroying the object' This is actually a normal behavior. At the end of the script the interpreter frees the memory. Actually every object has a built-in destructor, just like it has built-in constructor. So even we don’t define it explicitly, the object has its destructor. Usually this destructor is executed at the end of the script, or whenever the object isn’t needed anymore. This can happen, for instance, at the end of a function body. Now if we call the destructor explicitly, which as I said I’ve seen many times, here’s what happens. class A { public function __destruct() { echo 'destroying the object'; } } $obj = new A(); // this is valid and it prints 'destroying the object' // BUT IT DOES NOT DESTROY THE OBJECT $obj->__destruct(); // prints hello world echo 'hello world'; // HERE PHP ACTUALLY DESTROYS THE $obj OBJECT // ... and again prints 'destroying the object' As you can see calling the destructor explicitly doesn’t destroy the object. So the question is … How to Destroy an Object Before the Script Stops? Well, to destroy an object you can assign a NULL value to it. class A { public function __destruct() { echo 'destroying the object'; } } $obj = new A(); // prints 'destroying the object' $obj = null; // prints 'hello world' echo 'hello world'; // the script stop its execution Caution Be aware that if you don’t clone the object $obj, and simply assign it to another variable, then $obj = null will be pointless. Let’s see the following example. class A { public function printMsg() { echo 'I still exist'; } public function __destruct() { echo 'destroying the object'; } } $obj = new A(); // $newObj is pointing to $obj $newObj = $obj; // this doesn't destroy $newObj // as it appears both $obj and $newObj point to the same memory // so PHP doesn't free this memory $obj = null; // prints 'i still exist' $newObj->printMsg(); // prints 'hello world' echo 'hello world'; // now the scripts destroys the "object", which in this // case is $newObj and prints 'destroying the object' This example shows us that actually assigning NULL to an object doesn’t quite destroy it if there are another objects pointing to the same memory. class A { public function printMsg() { echo 'I still exist'; } public function __destruct() { echo 'destroying the object'; } } $b = new A(); $d = $c = $b; $b = null; $c->printMsg(); $d->printMsg(); // prints 'destroying the object' ONLY ONCE In this last example there are two interesting things to note. First $b = null doesn’t call the destructor, and at the end of the script there’s only one implicit call of the destructor, although there are two objects. Conclusion The important thing to note is that you shouldn’t call the destructor of an object explicitly! Not because it will throw an fatal error, but simply because it won’t destroy the object. [1] PHP: Constructors and Destructors Related posts: Some Notes on the Object-oriented Model of PHP Construct a Sorted PHP Linked List Object Cloning and Passing by Reference in PHP Source: http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/
November 15, 2011
by Stoimen Popov
· 18,285 Views · 1 Like
article thumbnail
What Is CDI, How Does It Relate to @EJB And Spring?
A brief overview of dependency injection in Java EE, the difference between @Resource/@EJB and @Inject, and how does that all relate to Spring – mostly in the form of links. Context Dependency Injection (CDI, JSR 299) is a part of Java EE 6 Web Profile and itself builds on Dependency Injection for Java (JSR 330), which introduces @Inject, @Named etc. While JSR 330 is for DI only and is implemented e.g. by Guice and Spring, CDI adds various EE stuff such as @RequestScoped, interceptors/decorators, producers, eventing and a base for integration with JSF, EJBs etc. Java EE components such as EJBs have been redefined to build on top of CDI (=> @Stateless is now a CDI managed bean with additional services). A key part of CDI aside of its DI capabilities is its awarness of bean contexts and the management of bean lifecycle and dependencies within those contexts (such as @RequestScoped or @ConversationScoped). CDI is extensible – you can define new context scopes, drop-in interceptors and decorators, make other beans (e.g. from Spring) available for CDI,… . Resources to check: Contexts and Dependency Injection in Java EE 6 by Adam Bien – a very good explanation of the basics of CDI and how it differs from DI in Java EE 5 (hint: context awarness) Slideshow with a good overview of CDI and all it offers About CDI extensibility and SPIs (e.g. Seam 3 is basically a set of portable CDI extensions) Guice and Spring do not implement CDI (3/2011) – and Spring perhaps isn’t motivated to do so (it supports JSR 330, CDI would be too much work) DZone CDI Refcard may be handy CDI 1.0 vs. Spring 3.1 feature comparsion: bean definition & dependency injection: “in the area that I compared in this article [= DI], there is only little critical difference in the two technologies” (though Spring more fine-tunable) Java EE 6 (CDI / EJB 3.1) XOR Spring Core Reloaded: New projects should preferably start with pure Java EE including CDI and add Spring utilities such as JDBC/JMS when needed Oracle: CDI in the Java EE 6 Ecosystem – 62 pages slideshow, the stuff is explained more than in the previously mentioned slideshow Note: CDI 1.1 (JSR 346, Java EE 7) should have a standard way of bootstrapping it in non-EE environment (i.e. SE) From http://theholyjava.wordpress.com/2011/11/09/what-is-cdi-how-does-it-relate-to-ejb-and-spring/
November 12, 2011
by Jakub Holý
· 14,809 Views · 1 Like
article thumbnail
ASP.NET MVC: Converting business objects to select list items
Some of our business classes are used to fill dropdown boxes or select lists. And often you have some base class for all your business classes. In this posting I will show you how to use base business class to write extension method that converts collection of business objects to ASP.NET MVC select list items without writing a lot of code. BusinessBase, BaseEntity and other base classes I prefer to have some base class for all my business classes so I can easily use them regardless of their type in contexts I need. NB! Some guys say that it is good idea to have base class for all your business classes and they also suggest you to have mappings done same way in database. Other guys say that it is good to have base class but you don’t have to have one master table in database that contains identities of all your business objects. It is up to you how and what you prefer to do but whatever you do – think and analyze first, please. :) To keep things maximally simple I will use very primitive base class in this example. This class has only Id property and that’s it. public class BaseEntity { public virtual long Id { get; set; } } Now we have Id in base class and we have one more question to solve – how to better visualize our business objects? To users ID is not enough, they want something more informative. We can define some abstract property that all classes must implement. But there is also another option we can use – overriding ToString() method in our business classes. public class Product : BaseEntity { public virtual string SKU { get; set; } public virtual string Name { get; set; } public override string ToString() { if (string.IsNullOrEmpty(Name)) return base.ToString(); return Name; } } Although you can add more functionality and properties to your base class we are at point where we have what we needed: identity and human readable presentation of business objects. Writing list items converter Now we can write method that creates list items for us. public static class BaseEntityExtensions { public static IEnumerable ToSelectListItems (this IList baseEntities) where T : BaseEntity { return ToSelectListItems((IEnumerator) baseEntities.GetEnumerator()); } public static IEnumerable ToSelectListItems (this IEnumerator baseEntities) { var items = new HashSet(); while (baseEntities.MoveNext()) { var item = new SelectListItem(); var entity = baseEntities.Current; item.Value = entity.Id.ToString(); item.Text = entity.ToString(); items.Add(item); } return items; } } You can see here to overloads of same method. One works with List and the other with IEnumerator. Although mostly my repositories return IList when querying data there are always situations where I can use more abstract types and interfaces. Using extension methods in code In your code you can use ToSelectListItems() extension methods like shown on following code fragment. ... var model = new MyFormModel(); model.Statuses = _myRepository.ListStatuses().ToSelectListItems(); ... You can call this method on all your business classes that extend your base entity. Wanna have some fun with this code? Write overload for extension method that accepts selected item ID.
November 11, 2011
by Gunnar Peipman
· 13,667 Views
  • Previous
  • ...
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450
  • 451
  • ...
  • 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
×