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

Events

View Events Video Library

The Latest Languages Topics

article thumbnail
Create Windows 7 start menu using CSS3 only
I am fascinated with how much you can do with so little using CSS3. Many user interface elements that require images in order to have appropriate visual appearance now can be styled only with CSS3. In order to prove that I assigned myself a task to create Windows 7 start menu only with CSS3 (and some icons). If we decompose the menu we'll get one div, two unordered lists with a couple of links each and a few icons. Let's see how each one of those is styled. Demo - Source Container The container named startmenu holds two unordered lists that act as menus. It has linear gradient with three color stops: light blue at the top, dark blue in the middle, and another shade of light blue at the bottom. Transparency is achieved using rgba() which has four parameters. The first three represent red, green and blue color values and the last one is opacity. Two borders are created with border and box-shadow properties. #startmenu { border:solid 1px #102a3e; overflow:visible; display:inline-block; margin:60px 0 0 20px; -moz-border-radius:5px;-webkit-border-radius:5px; position:relative; box-shadow: inset 0 0 1px #fff; -moz-box-shadow: inset 0 0 1px #fff; -webkit-box-shadow: inset 0 0 1px #fff; background-color:#619bb9; background: -moz-linear-gradient(top, rgba(50, 123, 165, 0.75), rgba(46, 75, 90, 0.75) 50%, rgba(92, 176, 220, 0.75)); background: -webkit-gradient(linear, center top, center bottom, from(#327aa4),color-stop(45%, #2e4b5a), to(#5cb0dc)); } Programs menu This unordered list has white background and two borders created with border and box-shadow properties. Its links, which contain icons and program names, uses gradients and box shadows in hover state. #programs, #links {float:left; display:block; padding:0; list-style:none;} #programs { background:#fff; border:solid 1px #365167; margin:7px 0 7px 7px; box-shadow: 0 0 1px #fff; -moz-box-shadow: 0 0 1px #fff; -webkit-box-shadow: 0 0 1px #fff; -moz-border-radius:3px;-webkit-border-radius:3px;} #programs a { border:solid 1px transparent; display:block; padding:3px; margin:3px; color:#4b4b4b; text-decoration:none; min-width:220px;} #programs a:hover {border:solid 1px #7da2ce; -moz-border-radius:3px; -webkit-border-radius:3px; box-shadow: inset 0 0 1px #fff; -moz-box-shadow: inset 0 0 1px #fff; -webkit-box-shadow: inset 0 0 1px #fff; background-color:#cfe3fd; background: -moz-linear-gradient(top, #dcebfd, #c2dcfd); background: -webkit-gradient(linear, center top, center bottom, from(#dcebfd), to(#c2dcfd));} #programs a img {border:0; vertical-align:middle; margin:0 5px 0 0;} Links menu As in the previous case, links menu is quite simple. But the interesting part comes in hover state. Each link has horizontal gradient with three stops: dark blue on the left and right side, and a bit lighter blue in the middle. Now, unlike programs menu links, here, every links has inner element which contains text. This span element has one more gradient - vertical linear gradient. It is transparent in the upper half and the lower part goes from very dark blue to almost transparent light blue. The combination of two transparent gradients gives exactly the same look as buttons in Windows 7 link menu. #links {margin:7px; margin-top:-30px;} #links li.icon {text-align:center;} #links a {border:solid 1px transparent; display:block; margin:5px 0; position:relative; color:#fff; text-decoration:none; min-width:120px;} #links a:hover {border:solid 1px #000; -moz-border-radius:3px; -webkit-border-radius:3px; box-shadow: 0 0 1px #fff; -moz-box-shadow: inset 0 0 1px #fff; -webkit-box-shadow: inset 0 0 1px #fff; background-color:#658da0; background: -moz-linear-gradient(center left, rgba(81,115,132,0.55), rgba(121,163,184,0.55) 50%, rgba(81,115,132,0.55)); background: -webkit-gradient(linear, 0% 100%, 100% 100%, from(#517384), color-stop(50%, #79a3b8), to(#517384)); } #links a span { padding:5px; display:block; } #links a:hover span { background: -moz-linear-gradient(center top, transparent, transparent 49%, rgba(2,37,58,0.5) 50%, rgba(63,111,135,0.5)); background: -webkit-gradient(linear, center top, center bottom, from(transparent), color-stop(49%, transparent), color-stop(50%, rgba(2,37,58,0.5)), to(rgba(63,111,135,0.5))); } Here is the preview, but I suggest you to check out the demo. You can play with backgrounds and see how transparency works. The code works fine in Firefox 3.6+, Safari and Chrome. It degrades gracefully in Opera and IE. I guess I could optimize it a bit so if you have any suggestions please let me know.
April 7, 2010
by Janko Jovanovic
· 8,949 Views
article thumbnail
Converting PDF to HTML Using PDFBox
Over the past few days, while working on another project, I needed to covert PDF documents into HTML. I did the usual searches for tools, but as I'm sure you'll have noticed, the tools available don't get great results. But then, seeing as I'm a software developer, I decided to see if I could program it myself. My requirements were quite simple: get the text out of the document, with the aim of HTML output, and extract the images at the same time. My first port of call was iText, as it was a library that I was already familiar with. iText is great for creating documents, and I was able to get some text out, but the image extraction wasn't really working out for me. The following is a code snippet that I was using to get the images from the PDFs in iText, based on a post on the iText mailing list. But when I used it, none of the images I generated were right - mostly just the box outlines/borders of the images in the PDF. I presume I was doing something wrong. PdfReader reader = new PdfReader(new FileInputStream(new File("C:\\test.pdf"))); for(int i =0; i < reader.getXrefSize(); i++) { PdfObject pdfobj = reader.getPdfObject(i); if(pdfobj != null) { if (!pdfobj.isStream()) { //throw new Exception("Not a stream"); } else { PdfStream stream = (PdfStream) pdfobj; PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE); if (pdfsubtype == null) { // throw new Exception("Not an image stream"); } else { if (!pdfsubtype.toString().equals(PdfName.IMAGE.toString())) { //throw new Exception("Not an image stream"); } else { // now you have a PDF stream object with an image byte[] img = PdfReader.getStreamBytesRaw((PRStream) stream); // but you don't know anything about the image format. // you'll have to get info from the stream dictionary System.out.println("----img ------"); System.out.println("height:" + stream.get(PdfName.HEIGHT)); System.out.println("width:" + stream.get(PdfName.WIDTH)); int height = new Integer(stream.get(PdfName.HEIGHT).toString()).intValue(); int width = new Integer(stream.get(PdfName.WIDTH).toString()).intValue(); System.out.println("bitspercomponent:" + stream.get(PdfName.BITSPERCOMPONENT)); java.awt.Image image = Toolkit.getDefaultToolkit().createImage(img); BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bi.createGraphics(); ImageIO.write(bi, "PNG",new File("C:\\images\\"+ i + ".png")); } } } // ... // // or you could try making a java.awt.Image from the array: // j } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } As I was low on time, I moved onto PDFBox which looked like it had already considered my use cases. I got the latest source code from SVN and tried the org.apache.pdfbox.ExtractText class straight away. This allows you to specify a -html flag instead of using the default text output. I ran into an exception straight away. After some debugging I found that what I had downloaded was missing the resources/glyphlist.txt file. I found a copy on the Adobe site and was able to run the utility then. One other thing to note while using these utilities is that you'll need to have ICU4J, iText and the Apache Commons Logging libraries on your build path. The good news was that the utility got all the text out and put it into a HTML format. But the generated HTML wasn't that pretty. Each line that it read got terminated with a , admittedly, an easy thing to change around. Moving onto image extraction, I tried out org.apache.pdfbox.ExtractImages. This class worked perfectly, saving all the images in the PDF as jpeg. I did make one alteration to PDXObjectImage.write2file so that I put the images in a particular folder. The PDFBox utilities really impressed me, as I wasn't sure if it was possible to get this information out of the PDF so easily. All the pieces are there for one single utility that would generate better HTML for you along with the images. As far as I know, no solution exists to do all of this in Java (if I'm wrong, please let me know in the comments section). Have any of the readers tried to achieve this process using iText, PDFBox or any other Java library?
April 7, 2010
by James Sugrue
· 93,846 Views · 2 Likes
article thumbnail
Template Method Pattern Tutorial with Java Examples
Learn the Template Method Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
April 6, 2010
by James Sugrue
· 150,519 Views · 11 Likes
article thumbnail
Python Script For Sending Free Sms Using Way2sms.com
#!/usr/bin/python __author__ = """ NAME: Abhijeet Rastogi (shadyabhi) Profile: http://www.google.com/profiles/abhijeet.1989 """ import cookielib import urllib2 from getpass import getpass import sys from urllib import urlencode from getopt import getopt username = None passwd = None message = None number = None def Usage(): print '\t-h, --help: View help' print '\t-u, --username: Username' print '\t-p, --password: Password' print '\t-n, --number: numbber to send the sms' print '\t-m, --message: Message to send' sys.exit(1) opts, args = getopt(sys.argv[1:], 'u:p:m:n:h',["username=","password=","message=","number=","help"]) for o,v in opts: if o in ("-h", "--help"): Usage() elif o in ("-u", "--username"): username = v ask_username = False elif o in ("-p", "--password"): passwd = v ask_password = False elif o in ("-m", "--message"): message = v ask_message = False elif o in ("-n", "--number"): number = v ask_number = False #Credentials taken here if username is None: username = raw_input("Enter USERNAME: ") if passwd is None: passwd = getpass() if message is None: message = raw_input("Enter Message: ") if number is None: number = raw_input("Enter Mobile number: ") #Logging into the SMS Site url = 'http://wwwb.way2sms.com//auth.cl' data = 'username='+username+'&password='+passwd+'&Submit=Sign+in' #Remember, Cookies are to be handled cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) # To fool way2sms as if a Web browser is visiting the site opener.addheaders = [('User-Agent','Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20091020 Ubuntu/9.10 (karmic) Firefox/3.5.3 GTB7.0')] try: usock = opener.open(url, data) except IOError: print "Check your internet connection" sys.exit(1) #urlencode performed.. Because it was done by the site as i checked through HTTP headers message = urlencode({'message':message}) message = message[message.find("=")+1:] #SMS sending send_sms_url = 'http://wwwb.way2sms.com//FirstServletsms?custid=' send_sms_data = 'custid=undefined&HiddenAction=instantsms&Action=custfrom950000&login=&pass=&MobNo='+number+'&textArea='+message opener.addheaders = [('Referer','http://wwwb.way2sms.com//jsp/InstantSMS.jsp?val=0')] try: sms_sent_page = opener.open(send_sms_url,send_sms_data) except IOError: print "Check your internet connection( while sending sms)" sys.exit(1) print "SMS sent!!!"
April 4, 2010
by Snippets Manager
· 16,001 Views · 1 Like
article thumbnail
Command Pattern Tutorial with Java Examples
Learn the Command Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
April 2, 2010
by James Sugrue
· 312,190 Views · 21 Likes
article thumbnail
Complete List of Macro Keywords for the NetBeans Java Editor
In NetBeans IDE's Java editor, you can create macros by clicking the "Start Macro Recording" button, performing some actions you'd like to record, then clicking the "Stop Macro Recording" button. The Macro Editor then pops up and you can finetune the macro and also assign a keyboard shortcut to it. (You can also edit macros in the Options window, in the Editor | Macros tab.) A special macro syntax is used to define these macros. For example, if you want to clear the current line in the editor from the cursor, your macro definition would be as follows: selection-end-line remove-selection Then you could assign "Ctrl+L" as the keyboard shortcut for this macro. Whenever you'd then press that key combination, the whole line, from the position of the cursor, would be deleted. But the only way for the syntax to be useful is for it to be made publicly available. I've seen in various places on-line that people are complaining about a lack of documentation in this area. I asked the developers from the NetBeans Java editor team and their advice was: "it should not be that hard to create an action, which will get EditorKit from the JEditorPane in an opened editor, call EK.getActions() and dump Action.NAME property of each action to System.out". That's what I did (together with Action.SHORT_DESCRIPTION) and here is the result: abbrev-debug-line -- Debug Filename and Line Number adjust-caret-bottom -- Move Insertion Point to Bottom adjust-caret-center -- Move Insertion Point to Center adjust-caret-top -- Move Insertion Point to Top adjust-window-bottom -- Scroll Insertion Point to Bottom adjust-window-center -- Scroll Insertion Point to Center adjust-window-top -- Scroll Insertion Point to Top all-completion-show -- Show All Code Completion Popup annotations-cycling -- Annotations Cycling beep -- Beep build-popup-menu -- Build Popup Menu build-tool-tip -- Build Tool Tip caret-backward -- Insertion Point Backward caret-begin -- Insertion Point to Beginning of Document caret-begin-line -- Insertion Point to Beginning of Text on Line caret-begin-word -- Insertion Point to Beginning of Word caret-down -- Insertion Point Down caret-end -- Insertion Point to End of Document caret-end-line -- Insertion Point to End of Line caret-end-word -- Insertion Point to End of Word caret-forward -- Insertion Point Forward caret-line-first-column -- Insertion Point to Beginning of Line caret-next-word -- caret-next-word caret-previous-word -- caret-previous-word caret-up -- Insertion Point Up collapse-all-code-block-folds -- Collapse All Java Code collapse-all-folds -- Collapse All collapse-all-javadoc-folds -- Collapse All Javadoc collapse-fold -- Collapse Fold comment -- Comment complete-line -- Complete Line complete-line-newline -- Complete Line and Create New Line completion-show -- Show Code Completion Popup copy-selection-else-line-down -- Copy Selection else Line down copy-selection-else-line-up -- Copy Selection else Line up copy-to-clipboard -- Copy cut-to-clipboard -- Cut cut-to-line-begin -- Cut from Insertion Point to Line Begining cut-to-line-end -- Cut from Insertion Point to Line End default-typed -- Default Typed delete-next -- Delete Next Character delete-previous -- Delete Previous Character documentation-show -- Show Documentation Popup dump-view-hierarchy -- Dump View Hierarchy expand-all-code-block-folds -- Expand All Java Code expand-all-folds -- Expand All expand-all-javadoc-folds -- Expand All Javadoc expand-fold -- Expand Fold fast-import -- Fast Import find-next -- Find Next Occurrence find-previous -- Find Previous Occurrence find-selection -- Find Selection first-non-white -- Go to First Non-whitespace Char fix-imports -- Fix Imports format -- Format generate-code -- Insert Code generate-fold-popup -- Generate Fold Popup generate-goto-popup -- Generate Goto Popup generate-gutter-popup -- Margin goto -- Go to Line... goto-declaration -- Go to Declaration goto-help -- Go to Javadoc goto-implementation -- Go to Implementation goto-source -- Go to Source goto-super-implementation -- Go to Super Implementation in-place-refactoring -- Instant Rename incremental-search-backward -- Incremental Search Backward incremental-search-forward -- Incremental Search Forward insert-break -- Insert Newline insert-date-time -- Insert Current Date and Time insert-tab -- Insert Tab introduce-constant -- Introduce Constant... introduce-field -- Introduce Field... introduce-method -- Introduce Method... introduce-variable -- Introduce Variable... java-next-marked-occurrence -- Navigate to Next Occurrence java-prev-marked-occurrence -- Navigate to Previous Occurrence jump-list-last-edit -- Last edit jump-list-next -- Forward jump-list-prev -- Back last-non-white -- Go to Last Non-whitespace Char make-getter -- Replace Variable With its Getter make-is -- Replace Variable With its is* Method make-setter -- Replace Variable With its Setter match-brace -- Insertion Point to Matching Brace move-selection-else-line-down -- Move Selection else Line down move-selection-else-line-up -- Move Selection else Line up org.openide.actions.PopupAction -- Show Popup Menu page-down -- Page Down page-up -- Page Up paste-formated -- Paste Formatted paste-from-clipboard -- Paste redo -- Redo reindent-line -- Re-indent Current Line or Selection remove-line -- Delete Line remove-line-begin -- Delete Preceding Characters in Line remove-selection -- Delete Selection remove-tab -- Delete Tab remove-trailing-spaces -- Remove Trailing Spaces remove-word-next -- remove-word-next remove-word-previous -- remove-word-previous replace -- Replace run-macro -- Run Macro scroll-down -- Scroll Down scroll-up -- Scroll Up select-all -- Select All select-element-next -- Select Next Element select-element-previous -- Select Previous Element select-identifier -- Select Identifier select-line -- Select Line select-next-parameter -- Select Next Parameter select-word -- Select Word selection-backward -- Extend Selection Backward selection-begin -- Extend Selection to Beginning of Document selection-begin-line -- Extend Selection to Beginning of Text on Line selection-begin-word -- Extend Selection to Beginning of Word selection-down -- Extend Selection Down selection-end -- Extend Selection to End of Document selection-end-line -- Extend Selection to End of Line selection-end-word -- Extend Selection to End of Word selection-first-non-white -- Extend Selection to First Non-whitespace Char selection-forward -- Extend Selection Forward selection-last-non-white -- Extend Selection to Last Non-whitespace Char selection-line-first-column -- Extend Selection to Beginning of Line selection-match-brace -- Extend Selection to Matching Brace selection-next-word -- selection-next-word selection-page-down -- Extend Selection to Next Page selection-page-up -- Extend Selection to Previous Page selection-previous-word -- selection-previous-word selection-up -- Extend Selection Up shift-line-left -- Shift Line Left shift-line-right -- Shift Line Right split-line -- Split Line start-macro-recording -- Start Macro Recording start-new-line -- Start New Line stop-macro-recording -- Stop Macro Recording switch-case -- Switch Case to-lower-case -- To Lowercase to-upper-case -- To Uppercase toggle-case-identifier-begin -- Switch Capitalization of Identifier toggle-comment -- Toggle Comment toggle-highlight-search -- Toggle Highlight Search toggle-line-numbers -- Toggle Line Numbers toggle-non-printable-characters -- Toggle Non-printable Characters toggle-toolbar -- Toggle Toolbar toggle-typing-mode -- Toggle Typing Mode tooltip-show -- Show Code Completion Tip Popup uncomment -- Uncomment undo -- Undo word-match-next -- Next Matching Word word-match-prev -- Previous Matching Word Now that this list is public, I am looking forward to many new and interesting (and useful) macros being published (maybe even here on NetBeans Zone).
March 31, 2010
by Geertjan Wielenga
· 21,100 Views
article thumbnail
Chain of Responsibility Pattern Tutorial with Java Examples
Learn the Chain of Responsibility Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
March 30, 2010
by James Sugrue
· 161,725 Views · 4 Likes
article thumbnail
How to Rotate Tomcat catalina.out
Avoid a crash and failure to start in tomcat through auto rotation of catalina.out on a linux/unix machine.
March 25, 2010
by Vineet Manohar
· 407,331 Views · 11 Likes
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,631 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,796 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,496 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,650 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,520 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,973 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,028 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,038 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,046 Views · 23 Likes
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,506 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,174 Views · 13 Likes
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,485 Views · 23 Likes
  • Previous
  • ...
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • 459
  • 460
  • 461
  • 462
  • ...
  • 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
×