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

Latest Articles - DZone

article thumbnail
What's Happening in the Java World?
this morning at theserverside java symposium i attended james gosling's keynote . below are my notes from his talk. the unifying principle for java is the network - it ties everything together. enterprise, desktop, web, mobile, hpc, media and embedded. the most important thing in the java world is the acquisition of sun by oracle. james is showing a slide of duke in a fish tank with a "snorcle!" title above it. obligatory statistics for java: 15 million jre downloads/week (doesn't count tax season in brazil) 10 billion-ish java enabled devices (more devices than people) 1 billion-ish java enabled desktops 100 million-ish tv devices 2.6 billion-ish mobile devices 5.5 billion-ish smart cards 6.5 million professional java developers java has become "learn once, work anywhere". most college students worldwide have taken a java course in school. james' daughter is in college but isn't interested in java, mostly because her dad's name is all over the textbooks. java ee 6 was approved september 30, 2009. it was many years in the making; the result of large-scale community collaboration. it was built by hardware manufacturers, users, developers and academia. because of all the politics involved, many engineers had to become diplomats. most software engineers are from the wrong myers-brigg quadrant for this type of negotiation. needless to say, the process was interesting . new and updated apis in java ee 6: servlet 3.0, jax-rs 1.1, bean validation 1.0, di 1.0, cdi 1.0, managed beans 1.0, jaspic 1.1, ejb 3.1, jpa 2.0 and many others. also new is the web profile . it's the first java ee profile to be defined. it's a fully-functional, mid-size stack for modern web application development. it's complete, but not the kitchen sink. it's what most people use when building a modern web application in java. java ee 6 adds dependency injection with di (jsr-330) and cdi (jsr-299). @resource is still around, but an @inject annotation has been added for typesafe injection. it has automatic scope management (request, session, etc.) and is extensible via a beanmanager api. glassfish is the world's most downloaded app server (1 million-ish downloads/month). gfv2 was the ee 5 reference implementation. gfv3 is the reference implementation for ee 6. but it's not just a reference implementation, it's a benchmark-winning mission-critical large-scale app server. the fcs was released on december 10, 2009. goals of java ee: ease of use, right-sizing and extensibility. now roberto chinnici (ee 6 spec lead) and another guy are on stage showing a netbeans and glassfish demo. with servlet 3.0, you don't need a web.xml file, you just need a web-inf directory. there's a new @webservlet annotation that lets you specify a "urlpattern" value for the servlet-mapping. a new @ejb annotation allows you to easily inject ejbs into your servlet. roberto wired in an ejb, hit ctrl+s and refreshed his browser and it all worked immediately. in the background, netbeans and glassfish did the redeployment and initialized the ejb container in milliseconds. @managedbeans and @sessionscope and @named are all part of cdi. when using @named, the beans become available to jstl and you can access them using ${beanname.property}. interestingly, the cdi annotations are in difference packages: javax.annotation.managedbean and javax.enterprise.context.requestscoped. as david geary mentions , it's great to see the influence that ruby on rails has had on java ee. long demo of jee6 in netbeans. spent quite a bit of time extolling the virtues of hot deploy. thanks, ror! now roberto is showing us the admin console of glassfish and how modular it is. he's installing a jms module, but it's interesting to see that there's a ruby container installed by default. apache felix is the underlying osgi implementation used by glassfish. you can telnet into it and see the status of all the bundles installed. after installing the full-profile, roberto shows that you can restart the server from the console. isn't the whole point of osgi that you don't have to restart anything!? the glassfish management console is definitely impressive and visually appealing. apparently, it's extensible too, so you could easily write plugins to monitor your application and provide memory statistics. changing topics, one of the things that nice about java is its a two-level spec. the important thing in the java world isn't the language, it's the virtual machine. the magic is in the vm! scala, ruby/rails, groovy/grails, python, php, javascript, javafx and many others. in the same breath of talking about java.next languages, james mentioned javafx script. it's a new declarative scripting language for guis. it's similar to flash or silverlight, but it's much better because it has the java vm under it. at the current rate that we're going with cpus and cores, there's a good chance we'll have 5220 cores on our desktops by 2030. if you find the concurrency libraries scary, get over it. for the rest of talk, james talked about what he's hacking on these days. he's helping build an audi tts for the pikes peak road rally in colorado. the goal is to figure out a way to keep the vehicle above 130 mph for the whole race. sounds like a pretty cool project to me. i don't think there was a whole lot of new information covered in james' talk, but i really do like java ee 6's web profile. however, i think it's something most of the community has been using for many years with tomcat + spring + hibernate. now it's simply been standardized. if you happen to work at one of those companies that frowns on open source and smiles at standards, you've finally caught up with the rest of us. from http://raibledesigns.com/
March 18, 2010
by Matt Raible
· 19,606 Views · 1 Like
article thumbnail
Getting Started With Code Generation With Xpand
have you heard about model driven software development (mdd / mdsd) and are thinking "what's all this fuzz about models"? "why should models help me to be more productive," might be another thought you have. people have been asking how to leverage models on and off on the web and in meetings i attended, so i thought i might share this little tutorial with you. in this tutorial, we will develop a little code generator that helps you to create (html) forms from models. a short overview xpand is a template engine, similar to freemarker, velocity, jet and jsp. however, it features some very unique properties that makes using xpand very well suited for generating code from models, such as type safety and polymorphic dispatch . if you haven't heard those terms before, fear not! i'll show you how to use xpand by way of an easy-to-follow example. the usual process of writing a code generator with xpand is as follows: define the structure of the model you want to process. this is called a metamodel define one or more template(s) that teach the code generator how to translate your model into code. easy, isn't it? using the code generator is even easier: create a model start the code generator it is worth mentioning that you can use xpand to generate code for almost any known programming language. everything you can express in text can be generated using xpand. so, while we will be generating html and java code in the following example, you can easily write code templates that generate code for c#, basic, lua, smalltalk, abap, or any other programming language. you can also generate manuals and other documentation artifacts from your models using xpand. i've successfully used xpand to create docbook files from models. those docbook files have then been converted to pdf files and online help files. preparing your ide grab and install a recent copy of eclipse. at the time of writing, i am using eclipse 3.6 m6 . install the latest version of xpand ( help -> install new software ... ) add the xpand update site (at the time of this writing, i am using xpand 1.0 nightly builds from http://download.eclipse.org/modeling/m2t/xpand/updates/nightly/ ) add the mwe update site ( http://download.eclipse.org/modeling/emft/mwe/updates/nightly/ ) select mwe and xpand: after the obligatory restart, do yourself the favour and set the platform encoding to utf-8 ! creating a generator project xpand code generators are hosted in eclipse plug-ins, mainly because this makes handling the classpath a lot easier. people have reportedly used maven to run xpand code generators, but we won't go down this road today. let's create a simple generator project: open the new project wizard and choose xpand project from the list choose a meaningful name for your project (e.g. org.xpand.example.gettingstarted select create a sample emf based xpand project after clicking finish , the wizard will create an sample generator project for you: before we can start working with this project, we need to perform some clean-up actions: open src/metamodel/checks.chk and delete all its contents open src/metamodel/extensions.chk and delete all its contents open src/template/generatorextensions.ext and delete all its contents delete src/model.xmi don't forget to save all modified files creating the metamodel as mentioned before, we need to define the structure of our models before we can actually start writing the code template. xpand is capable of understanding a variety of metamodel types. for example, if you have an xml schema file, you can use this as a metamodel and thereby enable xpand to use xml files which are compliant to your schema as input models. or, if you already have a bunch of java files making up your data model, you can use those to drive xpand code generation. in this tutorial, however, we will be using an ecore metamodel to define the structure of our models. the project has already been configured to support ecore metamodels, so all we need to do is open metamodel.ecore and define the structure: please open src/metamodel/metamodel.ecore . remove the following elements from the metamodel: feature , entity , datatype , type , model . the metamodel should now be empty: select package metamodel (as depicted in the screenshot above) and add a new eclass ( context menu -> new child -> eclass ). use the properties view to change the name of the newly created eclass to model . create a new eclass form select the newly created eclass form and add the following eattribute s: name , set the etype to estring description , etype = estring title , etype = estring select eclass form and add a new ereference , setting its attributes as follows: name = forms etype = form containment = true upperbound = -1 (meaning: unlimited) create a new eclass field and add the following eattributes to it: name , etype = estring lable , etype = estring create another eclass textfield , setting its properties as follows: name = textfield esuper types = field add one eattribute text to textfield : name = text , etype = estring add an eclass multilinetextfield to the metamodel: name = multilinetexttield esuper types = textfield now that we have everythign in place, we finally need to add a reference from form to field so we can later add fields to a form. select eclass form and add an ereference to it, setting its properties as follows: name = fields etype = field containment = true upperbound = -1 (meaning: unlimited) creating a model let's now create a model that follows the structure of the metamodel: in metamodel.ecore , select eclass model create a model instance by choosing create dynamic instance... from the context menu save the model file to src/model.xmi the model file editor will now open and you can use the tree editor to input the following model: add a form to the model, seeting the following properties: name: context description: send your feedback title: contact form add a textfield to the form , setting the following properties: name: name label: name add another textfield to the form , setting the following properties: name: email label: email add a multilinetextfield to the form , setting the following properties: name: message label: message your model should now look like this: creating a code generator as mentioned before, we will create a code generator for simple forms. nothing too fancy, but enough to give you an idea of how to create generator templates. the result will look like this: open src/template/template.xpt and replace its contents with the following text: «import metamodel» «define main for model» «expand form foreach forms» «enddefine» on the first line, we import the metamodel so that the generator (and the editor as well) knows about the structure of our model. on line 2 - 4 we define a code template named main , making sure it is bound to model elements of type model . the template doesn't do much, except to call another template (which we will define in a minute) named form with the collection of form s, contained in the reference forms of the current form. add the following lines to the template file, defining the template for the html file: «define form for form» «file name + ".html"» in the first line, we start the template by specifying its name ( form ) and the type it is bound to ( form ). on the next line, we use the file statement to specify the file the output is going to be written to. the name of the file is derived by concatenating the attribute name of the current form and the string literal ".html" . continue the template by appending the following text: «this.title» «this.description» obviously, this piece of template code will create part of the body of the html page. again, we will access attributes of the current form (as read from the model) and insert their values into the template (in this case, the title and the description). by the way, you can omit the this. prefix in front of the variable names. the template goes on with the following text: «expand field foreach this.fields» «endfile» «enddefine» the expand statement will invoke yet another subtemplate with the name field . this sub template will be called for each element in the fields attribute (reference) of the current form . you might recall that we we defined three different kinds of >field s in the metamodel: field (which is the super class for the other two field types textfield multilinetextfield as their names imply, a textfield will be a single line text entry field, whereas multilinetextfield will be a multiline text input field. we somehow need to be able to render different htmnl code for each of these different text field types. as mentioned in the introduction, xpand is not only type safe, but also supports polymorphic dispatch . this basically means we will create three templates (one for each of the different field types) with the same name . when evaluating the code template, the xpand generator will dispatch to the appropriate template by matching the most concrete type of the current model element. add the following code to the template file: «define field for field» «error "should not happen"» «enddefine» «define field for textfield» «this.label»: «enddefine» «define field for multilinetextfield» «this.label»: «enddefine» as you can see, all three templates have the same name. only the type they are bound to differs. this is enough to let xpand know which template to choose according to the type of the current model element. let's suppose xpand is iterating the model and the current model element is a textfield . although field is a direct super type of textfield , xpand will not invoke the first template ( «define field for field» ), but the second template ( «define field for textfield» ), as this is the most concrete match for the type of the model element. running the code generator if you have followed the above steps, running the code generator is a piece of cake: open the context menu on src/workflow/workflow.mwe and select run as -> mwe workflow this will start the code generator. you will see some log messages in the console view. if all went well, the output in the console reads something like this: ... 1503 info generator - written 1 files to outlet [default](src-gen) 1503 info workflowrunner - workflow completed in 650ms! the result of the code generation can be found in src-gen/contact.html . as this file has some dependencies to css/image files, please download the files from the static folder ( here ) and place them in your project before opening contact.html in your browser. where to go from here if you want to learn more about xpand, be sure to attend my talk use models and let the computer do the grunt work with xpand at eclipsecon 2010. i'll show some more advanced topics in this talk (such as generator cartridges, using xtend to augment your models, partitioning your code templates, using other metamodels to define your models). xpand comes with an extensive documentation (just go to help -> help contents -> xpand documentation in eclipse). you can also get help on xpand in the eclipse community forums should you need help, itemis (the company i work with) offers training and consulting for xpand and a host of other modeling related technologies. no doubt you have heard about xtext . xpand and xtext go together great: you can use xtext to define the structure of your models and create great-looking text editors to edit your models. then, use xpand to create code generators that take your textual models and turn them into running software. actually, xtext comes with a wizard that you to create a code generator project for your dsl. downloads the code for this tutorial can be found in my svn repository on google code . from http://www.peterfriese.de
March 18, 2010
by Peter Friese
· 27,676 Views · 1 Like
article thumbnail
Play! Framework Usability
Perhaps the most striking thing about about the Play! framework is that its biggest advantage over other Java web application development frameworks does not fit into a neat feature list, and is only apparent after you have used it to build something. That advantage is usability. Note that usability is separate from functionality. In what follows, I am not suggesting that you cannot do this in some other framework: I merely claim that it is easier and more pleasant in Play! I need to emphasise this because geeks often have a total blind spot for usability because they enjoying figuring out difficult things, and under-appreciate the value of things that Just Work. Written by web developers for web developers The first hint that something different is going on here is when you first hear that the Play! framework is 'written by web developers for web developers', an unconventional positioning that puts the web's principles and conventions first and Java's second. Specifically, this means that the Play! framework is more in line with the W3C's Architecture of the World Wide Web than it is with Java Enterprise Edition (Java EE) conventions. URLs for perfectionists For example, the Play! framework, like other modern web frameworks, provides first-class support for arbitrary 'clean' URLs, which has always been lacking from the Servlet API. It is no coincidence that at the time of writing, Struts URLs for perfectionists, a set of work-arounds for the Servlet API-based Struts 1.x web framework, remains the third-most popular out of 160 articles on www.lunatech-research.com despite being a 2005 article about a previous-generation Java web technology. In Servlet-based frameworks, the Servlet API does not provide useful URL-routing support; Servlet-based frameworks configure web.xml to forward all requests to a single controller Servlet, and then implement URL routing in the framework, with additional configuration. At this point, it does not matter whether the Servlet API was ever intended to solve the URL-routing problem and failed by not being powerful enough, or whether it was intended to be a lower-level API that you do not build web applications in directly. Either way, the result is the same: web frameworks add an additional layer on top of the Servlet API, itself a layer on top of HTTP. Play! combines the web framework, HTTP API and the HTTP server, which allows it to implement the same thing more directly with fewer layers and a single URL routing configuration. This configuration, like Groovy's and Cake PHP's, reflects the structure of an HTTP request - HTTP method, URL path, and then the mapping: # Play! 'routes' configuration file… # Method URL path Controller GET / Application.index GET /about Application.about POST /item Item.addItem GET /item/{id} Item.getItem GET /item/{id}.pdf Item.getItemPdf In this example, there is more than one controller. We also see the use of an id URL parameter in the last two URLs. HttpServletRequest Another example is Play!'s Http.Request class, which is a far simpler than the Servlet API's HttpServletRequest interface. In addition, Play! uses a class where Java EE 6 uses the Java EE convention of using an interface. This interface is also split between HttpServletRequest and the more generic ServletRequest interface. This separation may be useful if you want to use Servlets for things other than web applications, or if you want to allow for the unlikely possibility of the web changing protocol, but for most of us it is merely irrelevant complexity. In other words, the Servlet API is always used with a framework on top these days because it is sub-optimised for building web applications, which is what all of us actually use it for. Play! fixes that. Better usability is not just for normal people Another way of looking at the idea that Play! is by and for web developers is to consider how a web developer might approach software design differently to a Java EE developer. When you write software, what is the primary interface? If you are a web developer, the primary interface is a web-based user-interface constructed with HTML, CSS and (increasingly) JavaScript. A Java EE developer, on the other hand, may consider their primary interface to be a Java API, or perhaps a web services API, for use by other layers in the system. This difference is a big deal, because a Java interface is intended for use by other programmers, while a web user-interface interface is intended for use by non-programmers. In both cases, good design includes usability, but usability for normal people is not the same as usability for programmers. In a way, usability for everyone is a higher standard than usability for programmers, when it comes to software, because programmers can cope better with poor usability. This is a bit like the Good Grips kitchen utensils: although they were originally designed to have better usability for elderly people with arthritis, it turns out that making tools easier to hold is better for all users. The Play! framework is different because the usability that you want to achieve in your web application is present in the framework itself. For example, the web interface to things like the framework documentation and error messages shown in the browser is just more usable. Along similar lines, the server's console output avoids the pages full of irrelevant logging and pages of stack traces when there is an error, leaving more focused and more usable information for the web developer. $ play run phase ~ _ _ ~ _ __ | | __ _ _ _| | ~ | '_ \| |/ _' | || |_| ~ | __/|_|\____|\__ (_) ~ |_| |__/ ~ ~ play! 1.0, http://www.playframework.org ~ ~ Ctrl+C to stop ~ Listening for transport dt_socket at address: 8000 10:15:58,629 INFO ~ Starting /Users/peter/Documents/work/workspace/phase 10:16:00,007 WARN ~ You're running Play! in DEV mode 10:16:00,424 INFO ~ Listening for HTTP on port 9000 (Waiting a first request to start) ... 10:16:11,847 INFO ~ Connected to jdbc:hsqldb:mem:playembed 10:16:13,448 INFO ~ Application 'phase' is now started ! 10:16:14,825 INFO ~ starting DispatcherThread 10:16:48,168 ERROR ~ @61lagcl6i Internal Server Error (500) for request GET /application/startprocess?account=x Java exception (In /app/controllers/Application.java around line 41) IllegalArgumentException occured : Person not found for account x play.exceptions.JavaExecutionException: Person not found for account x at play.mvc.ActionInvoker.invoke(ActionInvoker.java:200) at Invocation.HTTP Request(Play!) Caused by: java.lang.IllegalArgumentException: Person not found for account x at controllers.Application.startProcess(Application.java:41) at play.utils.Java.invokeStatic(Java.java:129) at play.mvc.ActionInvoker.invoke(ActionInvoker.java:127) ... 1 more Try to imagine a JSF web application producing a stack trace this short. In fact, Play! goes further: instead of showing the stack trace, the web application shows the last line of code within the application that appears in the stack trace. After all, what you really want to know is where things first went wrong in your own code. This kind of usability does not happen by itself; the Play! framework goes to considerable effort to filter out duplicate and irrelevant information, and focus on what is essential. Quality is in the details In the Play! framework, much of the quality turns out to be in the details: they may be small things individually, rather than big important features, but they add up to result in a more comfortable and more productive development experience. The warm feeling you get when building something with Play! is the absence of the frustration that usually results from fighting the framework. We recommend that you go to http://www.playframework.org/, download the latest binary release, and spend half an hour on the tutorial. Peter Hilton is a senior software developer at Lunatech Research.
March 16, 2010
by $$anonymous$$
· 24,765 Views
article thumbnail
Decorator Pattern Tutorial with Java Examples
Learn the Decorator Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
March 15, 2010
by James Sugrue
· 141,683 Views · 5 Likes
article thumbnail
Proxy Pattern Tutorial with Java Examples
Learn the Proxy Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
March 12, 2010
by James Sugrue
· 159,129 Views · 13 Likes
article thumbnail
Java Clojure Interop: Integrating Clojure into Your Java Project
It's easier to wrap an existing piece of Java code in Clojure than it is to do the inverse, but because Clojure is implemented as a Java class library, it's also relatively simple to embed Clojure in your Java applications, load code, and call functions. Repl.java and Script.java in the distribution are the normal examples for loading code from a user or from a file. In this quick tutorial, you'll find out how to use the same underlying machinery to load Clojure code and then manipulate it directly from Java. First, let's start with this script that defines a simple Clojure function: ; foo.clj (ns user) (defn foo [a b] (str a " " b)) This Java class will load the script and call the of function with arguments in the form of Java objects. Then it will print the returned object: // Foo.java import clojure.lang.RT; import clojure.lang.Var; public class Foo { public static void main(String[] args) throws Exception { // Load the Clojure script -- as a side effect this initializes the runtime. RT.loadResourceScript("foo.clj"); // Get a reference to the foo function. Var foo = RT.var("user", "foo"); // Call it! Object result = foo.invoke("Hi", "there"); System.out.println(result); } } Finally, you have to compile this and run it to see the printed result. For compiling Clojure into a .jar, Leiningen is a favorable option since it is made specifically for Clojure. There is a good video that explains how to use leiningen. It has the advantage of letting users write everything in Clojure, rather than writing a bunch of XML code like you would for Ant or Maven. Leiningen also has "uberjars," which build in Clojure and put all of your Clojure dependencies into one standalone file, meaning less work for you. If you want to be more Java friendly in your approach, you could add an Ant task to build it along with the Java project. This will just take a little more work. You'll need to call 'to-array' on the functions that need to return proper java arrays. Clojure supports the creation, reading, and modification of Java arrays, but it is recommended that you limit use of arrays to interop with Java libraries that require them as arguments or use them as return values. Once you have your .jar file, just add it to your java project as a build deployment. then you can call it directly from Java. Here is the printed result when you run the .jar: >javac -cp clojure.jar Foo.java >java -cp clojure.jar Foo Hi there > If you're doing Java interop from Clojure, things are even more simple. Clojure programs can use any Java class or interface. The classes in the java.lang package can be used in Clojure just like you would in Java without having to import them. Java classes in other packages are used by either specifying their package when referencing them or using the import function. Invoking Java methods from Clojure code is also pretty simple. As a result, Clojure doesn't provide functions for many common operations. Instead, it relies on Java methods. [http://java.dzone.com/articles/java-clojure-interop-calling]
March 10, 2010
by Mitch Pronschinske
· 19,127 Views
article thumbnail
Cache Java Webapps with Squid Reverse Proxy
This article shows you step by step how to cache your entire tomcat web application with Squid reverse Proxy without writing any Java code. What is Squid Squid is a free proxy server for HTTP, HTTPS and FTP which saves bandwidth and increases response time by caching frequently requested web pages. While squid can be used as a proxy server when users try to download pages from the internet, it can be also used as a reverse-proxy by putting squid between the user and your webapp. All user requests first hit Squid. If the requested page already exists in Squid’s cache it is served directly from the cache without hitting your Webapp. If the page does not exist in Squid’s cache, it is fetched from your web application and stored in the cache for future requests. Squid reduces hits to your server by caching response pages. You don’t have to worry about building page level caching in every application that your write, Squid takes care of that part. When should I use Squid Ideally you should use Squid for pages which have a high ratio of reads to writes. In other words, a page that changes less frequently but is accessed very often. Here are some scenarios: A dynamical web page which displays news and is updated once an hour, and receives hundreds of hits during the hour A static web page accessed freqently. Squid can give performance boost by caching frequently accessed static web pages in memory When should I not use Squid In most cases, if the request URL is the only factor which determines the response then you can safely use Squid. See more specific examples below: If the entire apps is very dynamic in nature, and the validity of pages changes immediately. Squid is not suitable for apps which require login. This unfortunately is a large number of applications. Such applications need to resort to back end caching, for example use other caching frameworks like Ehcache to cache re-usable page fragments and/or cache database queries and/or other performance bottlenecks. Apps which heavily use browser cookies. Squid relies on URLs to cache pages. If the page served is computed from URLs + cookies, then you should not cache those pages in Squid. How does the overall setup work Apache Squid Tomcat architecture Apache receives requests on port 80. Apache calls Squid with the request. Squid checks its cache to see if it has the response cached from before. If yes and if the response is not expired, it returns the cached response.In this case: Squid will write the following header to the response X-Cache: HIT from www.vineetmanohar.com X-Cache: HIT from www.vineetmanohar.com If the response is not found in Squid’s cache, squid will make a call to Tomcat on port 8082. Tomcat’s proxy connector is listening on this port. It processes the request and sends the response back to Squid. Squid saves the response in its cache, unless caching is disabled for that URL. Squid returns the final response to Apache which sends the response back to the user. What if I don’t want to use Apache Using Apache is not required to use Squid. You can run Squid on port 80, and point your users directly to Squid. If that is the case, skip section one and directly jump to section 2 below. Step 1/3: Apache Httpd Config If you are using Apache as a front end, you need to instruct Apache to forward requests to Squid at port 3128. See the following code snippet. Change the server name and paths to reflect your real values. Apache config file: /etc/httpd/conf/httpd.conf ServerName www.vineetmanohar.com DocumentRoot /home/webadmin/www.vineetmanohar.com/html # forward requests to squid running on port 3128 ProxyPass / http://localhost:3128/ ProxyPassReverse / http://localhost:3128/ /etc/httpd/conf/httpd.conf ServerName www.vineetmanohar.com DocumentRoot /home/webadmin/www.vineetmanohar.com/html # forward requests to squid running on port 3128 ProxyPass / http://localhost:3128/ ProxyPassReverse / http://localhost:3128/ In addition to the above, you also need mod_proxy installed. If you see the following in your httpd.conf, you probably already have mod_proxy installed. If you first need to install mod_proxy LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so Step 2/3: Squid Config First make sure that Squid is installed on your server. You can download Squid from here. The squid config file on Linux/Unix is located at this location /etc/squid/squid.conf /etc/squid/squid.conf The config file is pretty long. Follow these instructions and set the values appropriately. 1. # leave the port to 3128 2. http_port 3128 3. 4. # how much memory cache do you want? depends on how much memory you have on the machine 5. cache_mem 200 MB 6. 7. # what's the biggest page that you want stored in memory. If you home page is 100 KB and 8. # you want it stored in memory, you may set it to a number bigger than that. 9. maximum_object_size_in_memory 100 KB 10. 11. # how much disk cache do you want. It is 6400 MB in the following example, change it as per 12. # your needs. Make sure you have that much disk space free. 13. cache_dir ufs /var/spool/squid 6400 16 256 14. 15. # this is probably the most important config section. Here you can configure the cache life for 16. # each URL pattern. 17. 18. # Time is in minutes 19. # 1 day = 1440, 2 days = 2880, 7 days = 10080, 28 days = 40320 20. 21. # do not cache url1 22. refresh_pattern ^http://127.0.0.1:8082/url1/ 0 20% 0 23. 24. # cache url2 for 1 day 25. refresh_pattern ^http://127.0.0.1:8082/url2/ 1440 20% 1440 override-expire override-lastmod reload-into-ims ignore-reload 26. 27. # cache css for 7 days 28. refresh_pattern ^http://127.0.0.1:8082/css 10080 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload 29. 30. # by default cache the whole website for 1 minute 31. refresh_pattern ^http://127.0.0.1:8082/ 0 20% 0 override-expire override-lastmod reload-into-ims ignore-reload 32. 33. # how long should the errors should be cached for. For example 404s, HTTP 500 errors 34. negative_ttl 0 seconds 35. 36. # On which host does tomcat run. Set 127.0.0.1 for localhost 37. httpd_accel_host 127.0.0.1 38. 39. # this is the proxy port as defined in Tomcat server.xml. By default it is "8082" 40. httpd_accel_port 8082 41. 42. # set this to "on". Read more documentation if you want to change this. 43. httpd_accel_single_host on 44. 45. # To access Squid stats via the manager interface, you need to enter a password here 46. cachemgr_passwd your_clear_text_password all 47. 48. # Say "off" if you want the query string to appear in the squid logs. 49. strip_query_terms off # leave the port to 3128 http_port 3128 # how much memory cache do you want? depends on how much memory you have on the machine cache_mem 200 MB # what's the biggest page that you want stored in memory. If you home page is 100 KB and # you want it stored in memory, you may set it to a number bigger than that. maximum_object_size_in_memory 100 KB # how much disk cache do you want. It is 6400 MB in the following example, change it as per # your needs. Make sure you have that much disk space free. cache_dir ufs /var/spool/squid 6400 16 256 # this is probably the most important config section. Here you can configure the cache life for # each URL pattern. # Time is in minutes # 1 day = 1440, 2 days = 2880, 7 days = 10080, 28 days = 40320 # do not cache url1 refresh_pattern ^http://127.0.0.1:8082/url1/ 0 20% 0 # cache url2 for 1 day refresh_pattern ^http://127.0.0.1:8082/url2/ 1440 20% 1440 override-expire override-lastmod reload-into-ims ignore-reload # cache css for 7 days refresh_pattern ^http://127.0.0.1:8082/css 10080 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload # by default cache the whole website for 1 minute refresh_pattern ^http://127.0.0.1:8082/ 0 20% 0 override-expire override-lastmod reload-into-ims ignore-reload # how long should the errors should be cached for. For example 404s, HTTP 500 errors negative_ttl 0 seconds # On which host does tomcat run. Set 127.0.0.1 for localhost httpd_accel_host 127.0.0.1 # this is the proxy port as defined in Tomcat server.xml. By default it is "8082" httpd_accel_port 8082 # set this to "on". Read more documentation if you want to change this. httpd_accel_single_host on # To access Squid stats via the manager interface, you need to enter a password here cachemgr_passwd your_clear_text_password all # Say "off" if you want the query string to appear in the squid logs. strip_query_terms off Step 3/3: Tomcat Config Make sure that the HTTP Proxy Connector is defined in TOMCAT_HOME/conf/server.xml. If needed, see additional documentation on Tomcat proxy connector. Squid Manager Interface You can access the Squid config and stats via the Squid Manger HTTP interface. Make sure that the “cachemgr.cgi” file which ships with squid installation is in your cgi-bin directory. More documentation on setting that up here. Once you’ve set it up, you can access the cache manager via this URL: http:///cgi-bin/cachemgr.cgi http:///cgi-bin/cachemgr.cgi To continue enter the following values: Cache host: localhost Cache port: 3128 Manager name: manager Password: Cache host: localhost Cache port: 3128 Manager name: manager Password: Store Directory Stats shows you how much disk space is used by the disk cache. Cache Client List show you the cache HIT/MISS ratio as %. You should monitor this frequently and tune your cache to get a higher hit %. Reload Squid Config without restarting Edit the squid config using “vi” or your favorite editor vi /etc/squid/squid.conf vi /etc/squid/squid.conf Once you are done editing, reload the new config without restarting Squid /usr/sbin/squid -k reconfigure /usr/sbin/squid -k reconfigure Clearing Squid Cache To clear Squid cache: 1) Set the memory cache to 4 MB (or a lower number) cache_mem 8 MB cache_mem 8 MB 2) Set the disk cache to 8 MB (or a lower number). The disk cache must be higher that the memory cache. cache_dir ufs /var/spool/squid 20 16 256 cache_dir ufs /var/spool/squid 20 16 256 3) Reload squid config without restart as described in the previous section 4) You may need to wait a few hours for the cache to get cleared. Once the cache is clear, you may restore the previous cache sizes and reload the new config again. You can monitor the cache size through the Squid Manager HTTP interface. Bypassing Squid If for some reason you need to bypass Squid, reconfigure Apache to directly send requests to Tomcat. Edit the Apache config file /etc/httpd/conf/httpd.conf # forward requests directly to Tomcat's proxy connector running on port 8082 ProxyPass / http://localhost:8082/ ProxyPassReverse / http://localhost:8082/ # forward requests directly to Tomcat's proxy connector running on port 8082 ProxyPass / http://localhost:8082/ ProxyPassReverse / http://localhost:8082/ You will need to restart Apache after making this change. /etc/init.d/httpd restart Conclusion Squid is a very powerful tool for caching. It is not for all applications. Please examine the need of your application and use squid appropriately. I’ve used squid for several years for caching the output from a Java data mashup application and am very satisfied with the ease of use and benefits. Hope you found this tutorial useful. Feel free to post a comment or share your experience with squid. References Squid official website From http://www.vineetmanohar.com
March 10, 2010
by Vineet Manohar
· 109,090 Views · 1 Like
article thumbnail
Generate Class Constructors in Eclipse Based on Fields or Superclass Constructors
You’ll often need to add a constructor to a class based on some/all of its fields or even based on constructors of its superclass. Take the following code: public class Contact { private String name, surname; private int age; public Contact(String name, String surname, int age) { this.name = name; this.surname = surname; this.age = age; } } That’s 5 lines of code (lines 5-9) just to have a constructor. You could write them all by hand, but writing a constructor that accepts and initialises each field takes a lot of time and becomes irritating after a while. And creating constructors from a superclass can take even longer because the superclass can define multiple constructors that you need to reimplement. That is why Eclipse has two features to help you generate these constructor instantly: Generate Constructor using Field and Generate Constructor from Superclass. Both features will generate a constructor in seconds, freeing you up to get to the exciting code. You’ll also see how to add/remove/reorder arguments of an existing constructor based on fields defined in the class. Generate a constructor from fields The fastest way to generate a constructor based on fields is to press Alt+Shift+S, O (alternatively select Source > Generate Constructor using Fields… from the application menu). This pops up a dialog where you can select the fields you want to include in the constructor arguments. Once you’ve selected the fields you want, just click Ok and you’re done. BTW, Alt+Shif+S is the shortcut to display a shortened Source menu, allowing Java source editing commands. The following video shows an example of how much time this feature can save you. We’ll create a constructor for the class Message. Notes: You can additionally call a superclass constructor with a subset of the fields by changing the dropdown Select super constructor to invoke at the top of the dialog. This creates a super(…) call with the relevant arguments and initialising code for the rest of the arguments on your subclass’s constructor. If you don’t want the JavaDoc for the constructor, disable the checkbox Generate constructor comments on the dialog. You can include/exclude the calls to super() using the checkbox Omit call to default constructor super(), on the dialog. You have to be positioned in a class to invoke this command. If you use frequently use this command, you can remap its keyboard shortcut by changing the key binding for the command Generate Getters and Setters. Generate constructor(s) from a superclass Sometimes you’ll want to reimplement some/all of a superclass’s constructors, especially as part of the contract. To generate constructor(s) from a superclass, just press Alt+Shift+S, C (or alternatively select Source > Generate Constructor from Superclass… from the application menu). A dialog pops up allowing you to select the constructor(s) you’d like to create. Once you click Ok, Eclipse generates the constructor, together with a super() call. Here’s an example of how to create a constructor in SecretMessage, that inherits from the class Message. Message has three constructors: a default one, one that accepts one String (content) and another that accepts three Strings (content, fromAddress and toAddress). SecretMessage should only expose the last two constructors. Note: You have to be positioned in a class to invoke this command. If you use this command frequently, you can remap its keyboard shortcut by changing the key binding for the command Generate constructors from superclass. Add, reorder and remove fields on existing constructors If you have an existing constructor and want to reorder its arguments or remove some of them, have a look at the Change Method Signature refactoring that does that in a jiffy. If you want to add a single field to an existing constructor, have a look at the next video that uses Eclipse’s Quick Fix (Ctrl+1) to do that easily. I’ll add a field createdDate to an existing constructor in Message by choosing Assign parameter to field from the Quick Fix menu while positioned on the field. From http://eclipseone.wordpress.com
March 9, 2010
by Byron M
· 31,052 Views · 1 Like
article thumbnail
Visitor Pattern Tutorial with Java Examples
Learn the Visitor Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
March 9, 2010
by James Sugrue
· 384,278 Views · 23 Likes
article thumbnail
Getting Started with the HornetQ Messaging System
HornetQ is an open source project to build a multi-protocol, embeddable, clustered messaging system with very high performance, . Messaging systems (or MOM for Message-oriented middleware) are systems focused on sending and receiving messages to increase the interoperability, flexibility and the performance of applications. They decouple the producers of messages from the consumers. The producers and consumers of messages are completely independent and are not aware of each other spatially (they can run on different nodes) and temporally (they do not need to be running at the same time, the producers can send messages even if there is no consumers and vice versa). This allows to create systems more flexible and loosely coupled than using remote procedure calls (or RPC). Messaging systems are often used to implement as message bus which loosely couples heterogeneous systems together. Using a message bus to decouple disparate systems allows the systems to grow independtly and adapt more easily. It provides more flexibility to add new systems or update existing ones since they don't have brittle tight-coupled dependencies on each other. Features Current release The current release of HornetQ is 2.0.0. This release is the first release of HornetQ, why does it start at 2? Actually, HornetQ is the spiritual successor from JBoss Messaging. As the team was developing the next generation of JBoss Messaging, it realized that it was such a change in scope and design from the previous project than it was renamed to emphasis its new broader scope. Documentation and examples HornetQ ships with more than 80 examples showing all the features one by one to help the user understand them. The documentation is task-orientated and describes for each feature its goal, its use and its configuration. JMS 1.1 API - HornetQ provides the full JMS 1.1 API (connection, session, destinations, etc.) and more (dead letter, expiry queue, last value queue, preack mode) Optimised Core API - HornetQ also provides its own client side API which goes beyond what is possible with JMS to take advantage of all the features offered by HornetQ which are not available through the JMS API Flexible integration - HornetQ is small, with few dependencies and can be used to suit your need. You can run it standalone, integrated into JBoss Application Server or in other dependency injection frameworks, or directly instantiated from your code: it is your choice to integrate it as it fits. JavaEE support - In addtion to JMS, HornetQ provide support for additional JavaEE API used for enterprise applications. HornetQ is a fully functional XAResource which can be enlisted in any JTA transaction. HornetQ also provides a JCA adaptor that can be used by Java EE application servers to consume message via Message-Driven Beans Multiple transport choices - HornetQ low level transport is completely pluggable. Two implementations are provided: one is using Netty to communicate remotely and the other is a in-vm implementation to connect clients and servers running inside the same Java Virtual Machine. The Netty implementation provides support for TCP, SSL, HTTP and Servlet. Management - HornetQ provides an extensive management API that can be accessed using JMX. Alternatively, it is possible to manage HornetQ by sending messages to a special management address. In the same way, management notifications emitted by HornetQ servers can be received using JMX or by consuming messages. High-performance journal for message persistence - HornetQ provides message persistence using its own built-in, high performance journal. This journal is a unique piece of technology that automatically detects if HornetQ is running on Linux and uses Linux AIO via a native code layer for astonishing performance. If AIO is not available, the journal seamlessly falls back to using Java NIOto offer great performance on any Java platform. HornetQ 2.0.0 performance has been published using on SPECjms2007. There are many other features which are described on HornetQ Features wiki page. Getting Started with HornetQ The best way to getting started with HornetQ is to download it and run one of the examples. Download HornetQ distribution: $ wget http://sourceforge.net/projects/hornetq/files/2.0.0.GA/hornetq-2.0.0.GA.zip/download Unzip it $ unzip hornetq-2.0.0.GA.zip Go to the JMS Queue example: $ cd hornetq-2.0.0.GA/examples/jms/queue Run the example with build.sh: $ ./build.sh ... [java] Sent message: This is a text message [java] Received message: This is a text message [java] example complete [java] [java] ##################### [java] ### SUCCESS! ### [java] ##################### This example starts one HornetQ server, sends and receives a JMS text message on a Queue and stops the server. From there, the next step is to read the documentation to know which jars are required on the client side to use HornetQ and start sending and receiving messages from your application. Client example Let's write some code now. We will use a standalone ready-to-use HornetQ server and write a JMS client to send and receive messages on a queue. First, let's start the server from the HornetQ distribution: $ cd hornetq-2.0.0.GA/bin/ $ ./run.sh ... HornetQ Server version 2.0.0.GA (Hornet Queen, 113) started Now, we write a simple JMS client which will connect to the HornetQ server and use the JMS Queue /queue/ExampleQueue available on the server: // Step 1. Create an initial context to perform the JNDI lookup. Hashtable env = new Hashtable(); env.put(Context.PROVIDER_URL, "jnp://localhost:1099"); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces "); Context ctx = new InitialContext(env); // Step 2. Lookup the connection factory ConnectionFactory cf = (ConnectionFactory)ctx.lookup("/ConnectionFactory"); // Step 3. Lookup the JMS queue Queue queue = (Queue)ctx.lookup("/queue/ExampleQueue"); // Step 4. Create the JMS objects to connect to the server and manage a session Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Step 5. Create a JMS Message Producer to send a message on the queue MessageProducer producer = session.createProducer(queue); // Step 6. Create a Text Message and send it using the producer TextMessage message = session.createTextMessage("Hello, HornetQ!"); producer.send(message); System.out.println("Sent message: " + message.getText()); // now that the message has been sent, let's receive it // Step 7. Create a JMS Message Consumer to receive message from the queue MessageConsumer messageConsumer = session.createConsumer(queue); // Step 8. Start the Connection so that the server starts to deliver messages connection.start(); // Step 9. Receive the message TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); // Finally, we clean up all the JMS resources connection.close(); // Step 1. Create an initial context to perform the JNDI lookup. Hashtable env = new Hashtable(); env.put(Context.PROVIDER_URL, "jnp://localhost:1099"); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces "); Context ctx = new InitialContext(env); // Step 2. Lookup the connection factory ConnectionFactory cf = (ConnectionFactory)ctx.lookup("/ConnectionFactory"); // Step 3. Lookup the JMS queue Queue queue = (Queue)ctx.lookup("/queue/ExampleQueue"); // Step 4. Create the JMS objects to connect to the server and manage a session Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Step 5. Create a JMS Message Producer to send a message on the queue MessageProducer producer = session.createProducer(queue); // Step 6. Create a Text Message and send it using the producer TextMessage message = session.createTextMessage("Hello, HornetQ!"); producer.send(message); System.out.println("Sent message: " + message.getText()); // now that the message has been sent, let's receive it // Step 7. Create a JMS Message Consumer to receive message from the queue MessageConsumer messageConsumer = session.createConsumer(queue); // Step 8. Start the Connection so that the server starts to deliver messages connection.start(); // Step 9. Receive the message TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000); System.out.println("Received message: " + messageReceived.getText()); // Finally, we clean up all the JMS resources connection.close(); To run this code, you need to add the following jars to your classpath: hornetq-core-client.jar -- HornetQ client library hornetq-jms-client.jar -- client implementation of the JMS API netty.jar -- the high-performance client/server socket framework hornetq-transports.jar -- integration code to use Netty with HornetQ jnp-client.jar -- JNDI library Once the code is compiled, you can run it: Sent message: Hello, HornetQ! Received message: Hello, HornetQ! Such a simple example does not relect how powerful and flexible messaging systems really are. They really shine on complex heterogeneous systems where they help manage complexity and increase performance by decoupling systems. Integration HornetQ server is designed using POJOs to make it simple to integrate it in multiple environments. HornetQ adapts to your specific environment and not the opposite. It can be run standalone (leveraging JBoss Microcontainer) or you can directly instantiate HornetQ POJOs in your code to embed a server. HornetQ distribution contains scripts to deploy it in JBoss AS 4 & 5 and it will be the default messaging system in JBoss AS 6. Finally, HornetQ will also be used by next release of TorqueBox to provide task queues to Ruby applications. Advanced Features HornetQ provides advanced constructs to help applications use recurring messaging patterns. Let's introduce some of them. Core Bridges Core bridges are used to create message flows between two HornetQ servers which are remotely separated. Core bridges are resilient and will cope with temporary connection failure allowing them to be an ideal choice for forwarding over unreliable connections, e.g. a WAN. Core Bridges are configured and managed by the HornetQ servers so that you do not have to deal with them manually. An example of Core bridge configuration looks like: jms.queue.source jms.queue.target -1 Diverts Diverts allow messages to be transparently "diverted" or copied from one address to another with just some simple configuration defined on the server side. Diverts can be exclusive -- the message is diverted to the new address and does not go to the old address at all -- or non-exclusive -- the message goes to old address and a copy of the message is also sent to the new address. For example, non-exclusive diverts can therefore be used for splitting message flows if there is a requirement to monitor every order sent to an order queue without making any changes to the client application logic . An example of divert configuration looks like: jms.queue.orders jms.topic.monitoring false JMS Bridges JMS bridges can consume JMS messages from a source JMS destination and send them to a target JMS destination, typically on a different server. Like a Core bridge, the JMS bridge have built-in resilience to failure so if the source or target server connection is lost, e.g. due to network failure, the bridge will retry connecting to the source and/or target until they come back online. When it comes back online it will resume operation as normal. Unlike Core bridge, the JMS bridge an also be used to bridge messages from other JMS servers than HornetQ, as long as they are JMS 1.1 compliant. This helps migrating applications to HornetQ by providing a bridge to a previous legacy messaging systems during the migration phase. Want more? This is a brief introduction to HornetQ and lots of powerful features have not been mentioned (clustering, high availability, flow control, paging, etc.). If you want more information, the web site is the primary source of information. The latest release's quick start guide and user manual will have you sending and receiving messages in no time. If you encounter issues, ask the community on the user forum or open JIRA issues. You can also follow the project on Twitter and on the project blog. Getting involved? If you want to get involved in the project, come join the team on #hornetq IRC channel.
March 5, 2010
by Jeff Mesnil
· 82,886 Views · 1 Like
article thumbnail
Declaring Final Variables Elegantly Using The Assigner Design Pattern
a final variable is used to define a constant value and reference, and can only be defined once. in most cases, declaring a final variable is just a matter of assigning to a primitive value or an object reference directly. however, in some cases, declaring a final class/instance variable may be more involving especially it gets assigned from a method that throws an exception (eg api for database access, web access), or it may involve multiple statements. editors note: this content was submitted by geekycoder in such cases, the code may become cluttered with class helper methods and dummy temporary variables that help define the final variable, making the code look less elegant and harder to maintain. the following common ways of declaring a final variable in those situations might look familiar to many. declaring final variable by instance/class method declaring final variable by instance/class variable with static/instance initializer. the aforementioned ways definitely get the work done but at the cost of elegancy. the helper method and variable help to define the final variable but it inevitably becomes part of class method and variable. recommended way: assigner design pattern a better way to declare final instance/class variable is to use generic method and interface with the advantages of forcing initializing method in the same statement as the final variable declaration. reusing as design pattern (term: assigner design pattern) and enhancing code readability there is generic helper class whose interface and method accept a parametric type similar to the type of final variable. the advantage of using generics is that the type mismatch will be caught at compile time rather than runtime. this design pattern is termed assigner because it assigns value to a variable from initializing method. using the design pattern, the code becomes cleaner and elegant. the above can be downloaded - assigner.zip (1kb) some will probably argue that assigner design pattern may not be efficient compare to the first two ways since additional bytecode classes are generated for assigner helper class and inner class. however, like other design patterns, code readability and reusability may outweigh the negligible performance loss and inefficiency.
March 4, 2010
by James Sugrue
· 12,575 Views · 5 Likes
article thumbnail
Annotating Custom Types in Hibernate
Hibernate has a lot of nice features, and it's pretty well documented, but a recent need to add a simple custom type to an existing mapping left me flailing around for documentation on exactly how to do it. I wanted to do it with annotations, not by updating the Hibernate configuration (that approach is well-documented). Here's how it's done. Two new classes are needed. You can do it with one (and the Hibernate examples do it that way), but they really have different functions, so I coded them separately. The first is the class you want to use for the column. In my case, I needed a Date with no milliseconds, which is a thin wrapper over java.util.Date. Here's my class: /** * Oracle stores dates in DATE columns down to the second; Java stores them to the millisecond. * This occasionally can confuse Hibernate as to what data are stale. This class slices off * any milliseconds which might be present in its representation. */public class DateNoMs extends java.util.Date { private static final long serialVersionUID = 1L; /** @see java.util.Date() */ public DateNoMs() { super(); long t = getTime(); setTime(t - t%1000); } /** @see java.util.Date(long) */ public DateNoMs(long time) { super(time - time%1000); } /** * @param value */ public DateNoMs(Date value) { long t = value.getTime(); setTime(t - t%1000); } /** @see java.util.Date#setTime(long) */ @Override public void setTime(long time) { super.setTime(time - time%1000); } Straightforward, right? Now, in my class, I have a field mapping: @Column(name = "PAYMENT_DATE") private DateNoMs m_paymentDate; Of course, this won't run--Hibernate will gag on the mapping, because it doesn't know how to map a JDBC DATE column to a DateNoMs--as one would expect. There are two things we need at this point: first, an object which Hibernate can use to transform JDBC DATE into a DateNoMs, and an annotation pointing to that "Factory". The factory class is produced by implementing (in the simplest case) org.hibernate.usertype.UserType. Documentation in this interface is pretty thin, but there are good examples available in the Hibernate distribution. Here's my implementation. I'm greatly helped by the fact that my class (DateNoMs) is very close to java.util.Date, and java.sql.Date extends java.util.Date. /** * Map "things" (currently Oracle Date columns) to the DateNoMs. */public class DateNoMsType implements UserType { /** @see org.hibernate.usertype.UserType#assemble(java.io.Serializable, Object) */ public Object assemble(Serializable cached, @SuppressWarnings("unused") Object owner) { return cached; } /** @see org.hibernate.usertype.UserType#deepCopy(Object) */ public Object deepCopy(Object value) { if (value==null) return null; if (! (value instanceof java.util.Date)) throw new UnsupportedOperationException("can't convert "+value.getClass()); return new DateNoMs((java.util.Date)value); } /** @see org.hibernate.usertype.UserType#disassemble(Object) */ public Serializable disassemble(Object value) throws HibernateException { if (! (value instanceof java.util.Date)) throw new UnsupportedOperationException("can't convert "+value.getClass()); return new DateNoMs((java.util.Date)value); } /** @see org.hibernate.usertype.UserType#equals(Object, Object) */ public boolean equals(Object x, Object y) throws HibernateException { return x.equals(y); } /** @see org.hibernate.usertype.UserType#hashCode(Object) */ public int hashCode(Object value) throws HibernateException { return value.hashCode(); } /** @see org.hibernate.usertype.UserType#isMutable() */ public boolean isMutable() { return true; } /** @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, String[], Object) */ public Object nullSafeGet(ResultSet rs, String[] names, @SuppressWarnings("unused") Object owner) throws HibernateException, SQLException { // assume that we only map to one column, so there's only one column name java.sql.Date value = rs.getDate( names[0] ); if (value==null) return null; return new DateNoMs(value.getTime()); } /** @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, Object, int) */ public void nullSafeSet(PreparedStatement stmt, Object value, int index) throws HibernateException, SQLException { if (value==null) { stmt.setNull(index, Types.DATE); return; } if (! (value instanceof java.util.Date)) throw new UnsupportedOperationException("can't convert "+value.getClass()); stmt.setDate( index, new java.sql.Date( ((java.util.Date)value).getTime()) ); } /** @see org.hibernate.usertype.UserType#replace(Object, Object, Object) */ public Object replace(Object original, @SuppressWarnings("unused") Object target, @SuppressWarnings("unused") Object owner) { return original; } /** @see org.hibernate.usertype.UserType#returnedClass() */ @SuppressWarnings("unchecked") public Class returnedClass() { return DateNoMs.class; } /** @see org.hibernate.usertype.UserType#sqlTypes() */ public int[] sqlTypes() { return new int[] {Types.DATE}; } The core of this class is the two methods which get and set values associated with my new type: nullSafeSet and nullSafeGet. One key thing to note is that nullSafeGet is supplied with a list of all the column names mapped to the custom datatype in the current query. In my case, there's only one, but in complex cases, you can map multiple columns to one object (there are examples in the Hibernate documentation). The final piece of the puzzle is the annotation which tells Hibernate to use the new "Type" class to generate objects of your custom type by adding a new @Type annotation to the column: @Type(type="com.gorillalogic.type.DateNoMsType") @Column(name = "PAYMENT_DATE") private DateNoMs m_paymentDate; The @Type annotation needs a full path to the class that implements the userType interface; this is the factory for producing the target type of the mapped column. If you're going to use your new type in a lot of places, you can shorten the @Type annotation by doing a typedef; you can place this in package-info.java in any package you like (I put mine in the same package as the UserType class). Here's the line for the type defined above: @TypeDefs( { @TypeDef(name = "dateNoMs", typeClass = com.gorillalogic.type.DateNoMsType.class }) package com.gorillalogic.type; Now my column annotation can look like this: @Type(type="dateNoMsType") @Column(name = "PAYMENT_DATE") private DateNoMs m_paymentDate; That should be enough to get you started. From http://execdesign.blogspot.com
March 4, 2010
by Jerry Andrews
· 94,321 Views
article thumbnail
Building a Star Rating System with ASP.NET MVC and jQuery
While working on the WeBlog project I realized that I needed a star rating system for blog posts.
March 2, 2010
by Michael Ceranski
· 32,801 Views
article thumbnail
Practical PHP Patterns: Mediator
The pattern of the day is the Mediator one. The intent of this pattern is encapsulating the interactions of a set of objects, preventing aggressive coupling from each of them towards the other ones. A Mediator acts as a central point of convergence between the Colleague objects. In any domain there are many operations that do not fit on existent, modelled-from-reality objects, and if forced as methods of an already existent class would add a dependency towards a possibly unrelated collaborator. This approach would result in a web of highly interrelated Colleague objects and not in the Ravioli code we want to work with. The Colleague objects should be kept loosely coupled to avoid having to reference them as a whole any time one of them is needed from a Client. The solution to this common problem is implementing the Mediator pattern. When an object's relationships and dependencies start to conflict with its business responsibility (the reason it was created in the first place), we should introduce a Mediator that coordinates the workflow between the coupled objects, freeing them from this form of coupling; dependencies can be established from the Colleagues towards the Mediator and/or from the Mediator towards the Colleagues. Both directions of those dependencies can be broken with an interface AbstractColleague or AbstractMediator, if necessary. No object is an island, and each object in an application must cooperate with other parts of the graph to get its job done and addressing one concern. Since the interactions are a source of coupling, a Mediator is one of the most effective patterns in limiting it, although, if abused, it may render more difficult to write cohesive classes. As a practical example, Services in Domain-Driven Design are Mediators between Entities. For a php-related example, Zend_Form decorating and filtering capabilities are actually the implementation of a simple Mediator between Zend_Form_Decorator and Zend_Filter instances. The same goes for validation using Zend_Validate objects. Making every filter referencing the next one would build a Chain of Responsibility which potential would be unused. When a Mediator must listen to Colleagues events, it is often implemented as an Observer resulting in a blackboard object where some Colleagues write and other ones read. Events are pushed to the Mediator from a Colleague, before it delivers them to the others subscribed Colleagues. There is no knowledge of others Colleagues in anyone of them: this architecture is successfully used in the Dojo javascript library shipped with Zend Framework. Another advantage of this pattern is the variation of the objects involved in the computation: this goal can be achived by configuring the Mediator differently, whereas instancing interrelated objects would be an noncohesive operation and the collaboration relationships would be scattered between different containers or factories. Participants Colleague: focuses on its responsibility, communicating only with a Mediator or AbstractMediator. Mediator: coordinates the work of a set composed by several Colleagues (AbstractColleagues). AbstractMediator, AbstractColleague: optional interfaces that decouple from the actual implementation of these roles. There may be more than one AbstractColleague role. The code sample implements a filtering process for a form input that resembles Zend_Form_Element's feature. _filters[] = $filter; return $this; } public function setValue($value) { $this->_value = $this->_filter($value); } protected function _filter($value) { foreach ($this->_filters as $filter) { $value = $filter->filter($value); } return $value; } public function getValue() { return $this->_value; } } $input = new InputElement(); $input->addFilter(new NullFilter()) ->addFilter(new TrimFilter()) ->addFilter(new HtmlEntitiesFilter()); $input->setValue(' You should use the - tags for your headings.'); echo $input->getValue(), "\n";
March 2, 2010
by Giorgio Sironi
· 12,644 Views
article thumbnail
Automatically Place a Semicolon at the End of Java Statements in Eclipse
we all know that java statements are terminated by a semicolon (;), but they’re a bit of a pain to add to the end of a line. one way would be to press end (to move to the end of the line) then press semicolon, but this is tedious. because this is something that you do often it’s worth learning how to do this faster. it’s a good thing eclipse can automatically put the semicolon at the end of the line, no matter where you are in the statement. it’s as easy as setting one preference and there’s a bonus preference for adding braces to the correct position as well. for something so small, it saves a lot of time. so in the example below, if you imagine that your cursor is placed after the word blue since you were editing the string. pressing semicolon will cause eclipse to place the semicolon after the closing bracket at the end. nice. system.out.println("the house is blue") how to set the semicolon preference the preference is disabled by default, so you have to enable it. go to window > preferences > java > typing . then enable semicolons under the section automatically insert at correct position . now when you press semicolon from anywhere in a statement, eclipse adds a semicolon to the end of the line and places the cursor right after the semicolon so you can start editing the next line. the preference should look like this: notes: sometimes you’d want to add a semicolon to a string literal instead of at the end of the line. eclipse caters for this by allowing you to press backspace after you pressed semicolon. pressing backspace will remove the semicolon from the end of the line, move your cursor to the original position in the string and add the semicolon to the string. if there’s already a semicolon at the end of the line, eclipse won’t try to add another to the end. it will just add the semicolon to wherever you placed it. eclipse is smart enough to know that for for loops you’d want to add the semicolon to the middle of the statement (eg. when editing the initialiser, condition and increment code). bonus tip: you can also add braces automatically at the correct position by selecting the braces option on the preference page. this comes in handy when your coding standards require braces to be on the same line as the control structure statement. for example, when adding a for or while loop, you can type { at any place in the first line and eclipse will insert it at the end of the line. from http://eclipseone.wordpress.com
March 2, 2010
by Byron M
· 15,239 Views · 13 Likes
article thumbnail
Working With Custom Maven Archetypes (Part 3)
in part 1 and part 2 of this series i was able to demonstrate how you can create a custom archetype and release it to a maven repository. in this final part we’ll look at what you need to do to integrate it into your development process. this will involve the following steps: uploading the archetype and its associated metadata to a maven repository manager . configuring an ide to use the archetype. generating a skeleton project from the archetype. step 1 – upload your archetype in part 2 we covered releasing and deploying the archetype. for reasons of brevity i simply demonstrated deploying a release to the local file system, but if we wish to share our archetype we must deploy it to a remote repository that can be accessed by other developers. a remote maven repository, in its simplest form, can be served up using a http server such as apache or nginx . however, these days i would recommend that you use a maven repository manager (mrm) instead, as these tools are purpose-built for serving (and deploying) maven artefacts. there are basically three options for your mrm – nexus , artifactory or archiva . a features matrix comparision is available here . all are available in open source flavours and both nexus and artifactory in particular are great tools. however, currently artifactory is the only one that supports a cloud-based service option which, as you might expect, integrates very well with our hosted continuous integration service . this allows you to provision yourself a fully-fledged mrm in very short order. so, how do we add our archetype to the repository? this is a simple process using the built in artifact deployer of artifactory which allows you to upload a file and supply its maven gav co-ordinates. next, we need to add some additional metadata about our archetype in the form of a ‘catalog’: com.mikeci mikeci-archetype-springmvc-webapp 0.1.4 http://mikeci.artifactoryonline.com/mikeci/libs-releases mike ci archetype for creating a spring-mvc web application. this file should ideally be placed into an appropriate folder of a maven repository and it contains information about all of the archetypes that live within the repository. we can simply add this file to our ‘libs-releases’ repository using artifactory’s rest api: curl -u username:password -f -d @archetype-catalog.xml -x put "http://mikeci.artifactoryonline.com/mikeci/libs-releases/archetype-catalog.xml" step 2 – configure your ide now that our archetype is deployed remotely, we can start to use it from within our ide – in my case – eclipse. to get good maven integration inside eclipse, you really should be using the latest release (0.10.0) of m2eclipse . once m2eclipse is installed, it provides a handy feature that allows you to add and remove archetype catalogs. you will need to add your deployed archetypes catalog to the list of catalogs accessible from within m2eclipse. this ensures that you can access your custom archetypes when you run the create a maven project wizard in eclipse as we will see shortly. choose the menu item, windows>preferences, to open the preferences dialog and drill down to the maven>archetypes preferences, as shown. click add remote catalog to bring up the remote archetype catalog dialog. in the catalog file text box, enter the path to your remote catalog file and in the description text box, enter a name for your catalog: step 3 – generate your project you should now be ready to generate a skeleton maven project inside eclipse. choose the menu item, file>new>other, to open the select a wizard dialog. from the scrollbox, select maven project and then click next. follow the wizard to configure your project location. eventually, the wizard allows you to select the archetype to generate your maven project. from the catalog drop-down list, select your custom catalog. then locate and select your archetype : click next and enter the gav values for your new project. et voila – you should have just created a skeleton project based upon your custom archetype using a slick ide wizard. pretty impressive, don’t you think? from http://blogs.mikeci.com
March 2, 2010
by Adam Leggett
· 34,479 Views
article thumbnail
Strategy Pattern Tutorial with Java Examples
Learn the Strategy Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
March 1, 2010
by James Sugrue
· 404,663 Views · 23 Likes
article thumbnail
Open Source NoSQL Databases
For almost a year now, the idea of "NoSQL" has been spreading due to the demand for relational database alternatives. Maybe the biggest motivation behind NoSQL is scalability. Relational databases don't lend themselves well to the kind of horizontal scalability that's required for large-scale social networking or cloud applications, and ORMs can abstract away impedance mismatch only so much. In other cases, companies just don't need as many of the complex features and rigid schemas provided by relational databases. Most people are not suggesting that we all ditch the RDBMS, in fact, many companies don't really need to switch. Relational databases will probably be necessary for many applications years and years from now. In essence, NoSQL is a movement that aims to reexamine the way we structure data and draw attention to innovation in hopes of finding the solution to the next generation's data persistence problems. Here are some of the better known open source data stores/models labeled as "NoSQL": CouchDB- Document Store Maps keys to data It provides a RESTful JSON API and is written in Erlang You can upload functions to index data and then you can call those functions Has a very simple REST interface Provides an innovative replication strategy - nodes can reconnect, sync, and reconcile differences after being disconnected for long periods of time Enables new distributed types of applications and data MongoDB - Document Store Free-form key-value-like data store with good performance Powerful, expansive query model Usability rivals that of Redis Good for complex data storage needs. Production-quality sharding capabilities Neo4j - GraphDB Disk-based Has a restricted, single-threaded model for graph traversal Has optional layers to expose Neo4j as an RDF store Can handle graphs of several billion nodes, relationships, or properties on a single machine Released under a dual license - free for non-commercial use Apache Hbase - Wide Column Store/Column Families Built on top of Hadoop, which has functionality similar to Google's GFS and MapReduce systems Hadoop's HDFS provides a mechanism that reliably stores and organizes large amounts of data Random access performance is on par with MySQL Has a high performance Thrift gateway Cascading source and sink modules Redis - Key Value/Tuple Store Provides a rich API and does more operations in memory, using disk only periodically. It's extremely fast Lets you append a value to the end of a list of items that's already been stored on a key. Has atomic operations, making it a best-of-breed tally server. Memcached - Key Value/Tuple Store High-performance, distributed memory object caching Free and open source Generic and agnostic to the objects/strings it caches It's all in-memory data Simple yet elegant design enables easy development and deployment Language neutral caching scheme. Most of the large properties on the web are using it now, except for Microsoft Project Voldemort - Eventually Consistent Key Value Store Used by LinkedIn Handles server failure transparently Pluggable serialization supports rich keys and values including lists and tuples with named fields Supports common serialization frameworks including Protocol Buffers, Thrift, and Java Serialization Data items are versioned Supports pluggable data placement strategies Memory caching and the storage system are combined Tokyo Cabinet and Tokyo Tyrant - Key Value/Tuple Store Supports hashtable mode, b-tree mode, and table mode It's fast and straightforward Good for small to medium-sized amounts of data that require rapid updating and can be easily modeled in terms of keys and values Cassandra - Wide Column Store/Column Families First developed by Facebook SuperColumns can turn a simple key-value architecture into an architecture that handles sorted lists, based on an index specified by the user. Can scale from one node to several thousand nodes clustered in different data centers. Can be tuned for more consistency or availability Smooth node replacement if one goes down ____ Some other well known NoSQL-style data stores that are closed source include Google BigTable and Amazon SimpleDB. GigaSpaces is a popular space-based Grid solution that has NoSQL qualities. Check out this informative post on NoSQL patterns.
February 23, 2010
by Mitch Pronschinske
· 46,092 Views
article thumbnail
Abstract Factory Pattern Tutorial with Java Examples
Learn the Abstract Factory Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
February 23, 2010
by James Sugrue
· 267,495 Views · 15 Likes
article thumbnail
Free Online SVN Repositories
This week, I searched for free online SVN repositories for closed-source projects.
February 23, 2010
by Nicolas Fränkel
· 52,991 Views
  • Previous
  • ...
  • 1605
  • 1606
  • 1607
  • 1608
  • 1609
  • 1610
  • 1611
  • 1612
  • 1613
  • 1614
  • ...
  • 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
×