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

article thumbnail
Unrolling Spock: Advanced @Unroll Usages in 0.4
Some of the Spock Framework 0.4 features are starting to see the light of day, with the Data Tables being explained last week in a nice blog post from Peter Niederwieser. One of the new features that I had not seen before is the new advanced @Unroll usage. Mixed with Data Tables, it produces some very cool results, and it can still be used with 0.3 style specs as well. Here's the juice: JUnit Integration and @Unroll Spock is built on JUnit, and has always had good IDE support without any effort from you as a user. For the most part, the IDEs just think Spock is another unit test. Here's the a Spock spec for the new Data Tables feature and how it shows up in an IDE. import spock.lang.* class TableTest extends Specification { def "maximum of two numbers"() { expect: Math.max(a, b) == c where: a | b | c 3 | 7 | 7 5 | 4 | 5 9 | 9 | 9 } } The assertion will be run 3 times: once for each row in the data table. And JUnit faithfully reports the method name correctly, even when the method names has a space in it: The problem with data driven tests and xUnit is poor error location. When a test fails you will receive an error stating which method is the culprit... but what if the method runs an assertion across 50 or 60 pieces of data? The cause of a failure is almost never clear with data driven tests. At it's worst you have to step through several iterations of code waiting for an exception. Good tests have a clear point of failure, but good tests also do not repeat themselves with boilerplate. This is exactly why Spock has the @Unroll annotation. As a test author you get to write one concise unit test, and JUnit does the work of reporting results that help you isolate failures. Consider the same test method with the @Unroll annotation and the accompanying IDE output. @Unroll def "maximum of two numbers"() { expect: Math.max(a, b) == c where: a | b | c 3 | 7 | 7 5 | 4 | 5 9 | 9 | 9 } When executed, JUnit sees three test methods instead of one: one for each row in the data table: The end result for you as a test writer is accurate failure resolution. You can pinpoint exactly which row failed. This feature is available in Spock 0.3 and you can use it today. What is new in 0.4 is the ability to change the test name dynamically. Here is a full @Unroll annotation that changes the method name: @Unroll("maximum of #a and #b is #c") def "maximum of two numbers"() { expect: Math.max(a, b) == c where: a | b | c 3 | 7 | 7 5 | 4 | 5 9 | 9 | 9 } Notice the #variable syntax in the annotation parameter. The # produces a sort of GString-like variable substitution that lets you bind columns from your data table into your test name. The annotation parameter references #a, #b, and #c, which aligns with the data table definition of a | b | c. Check out the IDE output: Previously, the test name was just the iteration number within the test. The new @Unroll parameter allows you to make the test name much more meaningful. Your tests will improve because failures become more descriptive. Unrolled failure messages before simply had the iteration name embedded in them, while now they can have meaningful data that you prescribe. My favorite part of playing with the new @Unroll was to see the default value of the parameter within the Spock source code: java.lang.String value() default "#featureName[#iterationCount]"; Talk about eating your own dog food... the default value is a test name template, just like you could have written in your own test. Makes you wonder what other variables are in scope, huh? Spock snapshot builds for 0.4 are available at: http://m2repo.spockframework.org. Get it before the link breaks. From http://hamletdarcy.blogspot.com
March 24, 2010
by Hamlet D'Arcy
· 36,205 Views · 1 Like
article thumbnail
Distance Calculation Using Latitude And Longitude In Java
private double distance(double lat1, double lon1, double lat2, double lon2, char unit) { double theta = lon1 - lon2; double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta)); dist = Math.acos(dist); dist = rad2deg(dist); dist = dist * 60 * 1.1515; if (unit == "K") { dist = dist * 1.609344; } else if (unit == "N") { dist = dist * 0.8684; } return (dist); } /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ /*:: This function converts decimal degrees to radians :*/ /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ private double deg2rad(double deg) { return (deg * Math.PI / 180.0); } /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ /*:: This function converts radians to decimal degrees :*/ /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ private double rad2deg(double rad) { return (rad * 180.0 / Math.PI); } system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "M") + " Miles\n"); system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "K") + " Kilometers\n"); system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "N") + " Nautical Miles\n");
March 23, 2010
by Snippets Manager
· 50,627 Views · 1 Like
article thumbnail
Aspect Oriented Programming For Eclipse Plug-ins
It seems to me that Aspect Oriented Programming never really took off when it was introduced. However, it's a useful way to intercept, or analyse, methods as they happen, in an independent way. Eclipse has a useful suite of AspectJ tools that you can download for your Eclipse installlation. Paired with the benefits of Eclipse's plug-in system, aspects are a nice way of intercepting your RCP application. The following instructions show how to get up and running with aspects in the Plug-in Development Environment really quickly. Once you have downloaded the Eclipse AspectJ tools, you will also want to include the Equinox Aspect jars in your plug-ins directory. The plug-ins you will need are org.eclipse.equinox.weaving.aspectj and org.eclipse.equinox.weaving.hook Create a new OSGi plug-in: Right click on the project and choose AspectJ Tools/Convert to AspectJ Project Create a new package within the plugin eg. com.dzone.aspects.aspectTest Make a new aspectj Aspect within the package e.g. MyAspect In your manifest.mf export the package created in the previous step Export-Package: com.dzone.aspects A you write your AspectJ code, you will be advising another plug-in (for example org.eclipse.jdt.junit) You'll need to do some extra setup in order to advise other plug-ins, by adding the following to your Aspect plug-in manifest.mf. Eclipse-SupplementBundle: org.eclipse.jdt.junit Note you can only supplement one bundle in an aspect. Therefore, if you want to crosscut another bundle, you’ll need to create a new AspectJ plug-in. It also helps to add the plugin that you are advising (org.eclipse.jdt.junit) to your aspect plugin's dependencies. If you don't do it you will get lint warnings from the AspectJ compiler In your plugins META-INF directory make a file called aop.xml, consisting of content similar to the following When executing use the following VM arguments in your Run Configuration -Dosgi.framework.extensions=org.eclipse.equinox.weaving.hook -Dorg.aspectj.osgi.verbose=true It's as simple as that. Have you any instructions to add to this?
March 23, 2010
by James Sugrue
· 10,781 Views
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,483 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,644 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,498 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
· 158,953 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,018 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,028 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,004 Views · 23 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,190 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,747 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,167 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,380 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,465 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
· 45,922 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,258 Views · 15 Likes
article thumbnail
Concurrent Programming in Groovy
It seems that the Groovy has a project for just about anything. That's one of the reasons why the language is so popular. The GPars library is an especially useful project in this new era of mult-core processors and concurrent programming. Formerly known as GParallelizer, GPars offers a framework for handling tasks concurrently and asynchronously while safe-guarding mutable values. DZone recently got an update on the project's latest news from project lead Václav Pech, and we've provided some examples of GPars concepts. GPars uses some of the best concepts from emerging languages and implements them for Groovy. Its actor support was inspired by the Actors library in Scala and the SafeVariable class in GPars was inspired by Agents in Clojure. The Groovy-based APIs in GPars are used to declare which parts of the code should be run concurrently. Objects can be enhanced with asynchronous methods to perform collections-based operations in parallel based on the fork/join model. GPars also has a Dataflow concurrency model that offers an alternative model that is inherently safe and robust due to algorithms that prevent having to deal with live-locks and race-conditions. The SafeVariable class is another technology in GPars that alleviates problems with concurrency by providing a non-blocking mt-safe reference to mutable state when Java libraries are integrated. Finally the Parallelizer, Asynchronizer, and Actors are some of the most interesting concepts in GPars. Actors Actors can be generated quickly to consume and send messages between each other even across distributed machines. You can build a messaging-based concurrency model with actors that are not limited by the number of threads. What was once only available to Scala developers, GPars now brings to Java and Groovy developers. Actors perform three different operations - send messages, receive messages and create new actors. New actors are created with the actor() method passing in the actor's body as a closure parameter. Inside the actor's body loop() is used to iterate, react() to receive messages, and reply() to send a message to the actor, which has sent the currently processed message. Here is how to create an actor that prints out all messages that it receives: import static groovyx.gpars.actor.Actors.* def console = actor { loop { react { println it } } } The loop() method ensures that the actor doesn't stop after processing the first message. Messages are sent using the send() method or the << operator. Here is an example of the sendAndWait () method in a message: actor << 'Message' actor.send 'Message' def reply1 = actor.sendAndWait('Message') def reply2 = actor.sendAndWait(10, TimeUnit.SECONDS, 'Message') def reply3 = actor.sendAndWait(10.seconds, 'Message') The sendAndWait() family blocks the caller until a reply from the actor becomes available. The reply is returned from sendAndWait() as a return value. For non-blocking message retrieval, calling the react() method, with or without a timeout parameter, from within the actor's code will consume the next message from the actor's inbox: println 'Waiting for a gift' react {gift -> if (myWife.likes gift) reply 'Thank you!' } Here is a more 'real world' example of an event-driven actor that receives two numeric messages, generates a sum, and sends the result to the console actor: import static groovyx.gpars.actor.Actors.* //not necessary, just showing that a single-threaded pool can still handle multiple actors defaultPooledActorGroup.resize 1 final def console = actor { loop { react { println 'Result: ' + it } } } final def calculator = actor { react {a -> react {b -> console.send(a + b) } } } calculator.send 2 calculator.send 3 calculator.join() Since Actors can share a relatively small thread pool, they bypass the threading limitations of the JVM and don't require excessive system resources even if an application consists of thousands of actors. There are some more sophisticated actor examples on the old GParallelizer wiki and there's also a nice article on the key concepts behind actors in erlang and scala. The documentation on GPars Actors can be found here. Asynchronizer A major feature of GPars is the Asynchronizer class, which runs tasks asynchronously in the background. It enables a Java Executor Service-based DSL on collections and closures. Inside the Asynchronizer.doParallel() blocks, asynchronous methods can be added to the closures. async() creates a variant of the supplied closure returning a future for the potential return value when invoked. callAsync() calls a closure in a separate thread supplying the given arguments and also returns a future for the potential value. Here is one example of Asynchronizer use: Asynchronizer.doParallel() { Closure longLastingCalculation = {calculate()} Closure fastCalculation = longLastingCalculation.async() //create a new closure, which starts the original closure on a thread pool Future result=fastCalculation() //returns almost immediately //do stuff while calculation performs … println result.get() } Parallelizer Finally, there's the Parallelizer, which is a concurrent collection processor. The common pattern to process collections takes elements sequentially, one at a time. This algorithm however, won't work well on multi-core hardware. The min() function on a dual-core chip can only leverage 50% of the computing power - 25% for a quad-core. Instead, GPars uses a tree-like structure for parallel processing. The Parallelizer class enables a ParallelArray(from JSR-166y)-based DSL on collections. Here is a use exapmle: doParallel { def selfPortraits = images.findAllParallel{it.contains me}.collectParallel {it.resize()} //a map-reduce functional style def smallestSelfPortrait = images.parallel.filter{it.contains me}.map{it.resize()}.min{it.sizeInMB} } Václav Pech told DZone that GPars currently has two new people joining the project - Jon Kerridge and Kevin Chalmers. The two developers are bringing their JCSP Groovy library with them into GPars. Pech said, "Apart from experimenting with the CSP concept, we will also enhance actor remoting and polish a couple of rough edges on the APIs. The documentation and especially the samples also deserve more attention." GPars' documentation is already quite robust. Pech says there quite a few issues queued up in their JIRA, but the previously listed issues remain the top priorities. Depending on the amount of time required to make progress with CSP, the GPars 1.0 release might happen in the summer says Pech. GPars is also developed by Alex Tkachman, a leading developer on the Groovy++ project. In an with Andres Almiray, Tkachman said that some of the work that comes out of Groovy++ might be assimilated into GPars, but no plans are in place yet since Groovy++ developers are still experimenting.
February 22, 2010
by Mitch Pronschinske
· 53,512 Views · 2 Likes
article thumbnail
Top 10 Interesting NetBeans IDE Java Shortcuts I Never Knew Existed
I'm working on updating the NetBeans IDE Keyboard Shortcut Card (which you can always find under the "Help" menu in the IDE) and have learned about a lot of shortcuts I never knew about before. Here's a grab bag of things I have added to the shortcut card (some new, some old that hadn't been included before) that you might find interesting too. Type "fcom" (without the quotes, same as all the rest below) and then press Tab. You now have this, i.e., a brand new code fold: // // Type "bcom" and then press Tab to create the start of a new set of comments in your code: /**/ Type "runn" and press Tab and you'll have all of this: Runnable runnable = new Runnable() { public void run() { } }; If I have this: String something = ""; ...and then below that type "forst" and press Tab, I now have this: String something = ""; for (StringTokenizer stringTokenizer = new StringTokenizer(something); stringTokenizer.hasMoreTokens();) { String token = stringTokenizer.nextToken(); } Also, experiment with "forc", "fore", "fori", "forl", and "forv"! I always knew that "sout" turns into "System.out.println("");" but did you know that (again assuming you first have a string something like above) if you type "soutv" you end up with this: System.out.println("something = " + something); Thanks Tom Wheeler for this tip. Next, here are the new shortcuts that are new from NetBeans IDE 6.9 onwards: as - assert=true; su - super db - double sh - short na - native tr - transient vo - volatile I knew that "ifelse" would resolve to an if/else block. But did you know that if you don't need an 'else', you can simply type "iff", press Tab, and then end up with this: if (exp) { } From NetBeans IDE 6.9 onwards, the "sw" shortcut expands to the following: switch (var) { case val: break; default: throw new AssertionError(); } If you're using while loops, experiment with "whileit", "whilen", and "whilexp". Always remember these: "im" expands to "implements; "ex" to "extends". Other tips along these lines are more than welcome here on NetBeans Zone!
February 19, 2010
by Geertjan Wielenga
· 97,873 Views · 4 Likes
article thumbnail
Factory Method Pattern Tutorial with Java Examples
Learn the Factory Method Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
February 18, 2010
by James Sugrue
· 185,943 Views · 8 Likes
  • Previous
  • ...
  • 564
  • 565
  • 566
  • 567
  • 568
  • 569
  • 570
  • 571
  • 572
  • 573
  • ...
  • 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
×