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

Events

View Events Video Library

Latest Articles - DZone

article thumbnail
Prototype Pattern Tutorial with Java Examples
Learn the Prototype Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
April 9, 2010
by James Sugrue
· 90,961 Views · 14 Likes
article thumbnail
Shutting Down Ehcache Properly
If you’re using ehcache’s disk persistence feature, which allows the cache to survive across JVM restarts, be sure to shut down ehcache properly. To do so when using ehcache within a webapp, simply add its ShutdownListener as a listener in web.xml. net.sf.ehcache.constructs.web.ShutdownListener Alternatively, or when not using ehcache inside a webapp, instruct ehcache to register its own shutdown hook by setting a system property. net.sf.ehcache.enableShutdownHook=true If you forget one of the above, your persisted cache may not be up-to-date, or worse, not persisted at all. From http://codeaweso.me/2010/01/shutting-down-ehcache-properly/
April 9, 2010
by Mike Christianson
· 10,606 Views
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
· 9,023 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,924 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,694 Views · 11 Likes
article thumbnail
What To Do When A Hard Drive Fails
When a hard drive crashes, you can lose all your data. Corrupt hard drives happen out of the blue and for seemingly no good reason. If your hard drive fails, what can you do? One option is to call a hard drive recovery company. If your data is worth a lot of money to you, you can pay a forensic computer company to get the data off your hard drive. Before you write a check though, try a little Do-It-Yourself first. What is going on inside the hard drive is a bunch of little platters spinning at high speed. When data is accessed or written to the disk, a little head (sort of like on a record player) moves to the right spot and does it's magic. The space between the head and the platter is very very tiny. Freezing the hard drive will shrink the head and the platter ever so slightly, often allowing you to read data. Here is how I got the data off of a failed hard drive. Remove the hard drive from the computer. Place the hard drive inside of a zip top freezer bag. (don't buy a cheap bag.) Place the wrapped hard drive inside of ANOTHER zip top freezer bag. (yes, you need to do this) (see figure 1 below) Place the double wrapped hard drive in the coldest part of your freezer. Leave the hard drive in the freezer for 12 hours at least. You want it good and cold! (see figure 2 below) Once very chilled, install the hard drive in your computer and start pulling off data. Begin with the most valuable data. At some point, the hard drive will fail again. When it does, mark the last successfully copied data, pull out the hard drive, double wrap it again and stick it in the Chill Chest for another 12 hours. You may need to do this a number of times to get all the data you want, or until the hard drive stops working completely. Double Wrapped Hard Drive Hard Drive in the Freezer
April 5, 2010
by Dan Wilson
· 124,555 Views · 1 Like
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,034 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,400 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,170 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,878 Views · 4 Likes
article thumbnail
The TDD Checklist (Red-Green-Refactor in Detail)
I have written up a checklist to use for unit-level Test-Driven Development, to make sure I do not skip steps while writing code, at a very low level of the development process. Ideally I will soon internalize this process to the point that I would recognize smells as soon as they show up the first time. This checklist is also applicable to the outer cycle of Acceptance TDD, but the Green part becomes much longer and it comprehends writing other tests. Ignore this paragraph if this get you confused. TDD is described by a basic red-green-refactor cycle, constantly repeatead to add new features or fix bugs. I do not want to descend too much in object-oriented design in this post as you may prefer different techniques than me, so I will insist on the best practices to apply as soon as possible in the development of tests and production code. The checklist is written in the form of questions we should ask ourselves while going through the different phases, and that are often overlooked for the perceived simplicity of this cycle. Red The development of every new feature should start with a failing test. Have you checked in the code in your remote or local repository? In case the code breaks, a revert is faster than a rewrite. Have you already written some production code? If so, comment it or (best) delete it to not be implicitly tied to an Api while writing the test. Have you chosen the right unit to expand? The modified class should be the one that remains more cohesive after the change, and often in new classes should be introduced instead of accomodating functionalites in existing ones. Does the test fail? If not, rewrite the test to expose the lack of functionality. Does a subset of the test already fail? Is so, you can remove the surplus part of the test, avoiding verbosity; it can come back in different test methods. Does the test prescribe overly specific assertions or expectations? If so, lessen the mock expectations by not checking method calls order or how many times a method is called; improve the assertions by substituting equality matches with matches over properties of the result object. Does the test name describe its intent? Make sure it is not tied to implementation details and works as low-level documentation. How much can you change in an hypothetical implementation without breaking the test (making it brittle)? Is the failure message expressive about what is broken? Make sure it describes where the failing functionality resides, highlighting the right location if it breaks in the future. Are magic numbers and strings expressed as constants? Is there repeated code? Test code refactoring is easy when done early and while a test fails, since in this paradigm it is more important to keep it failing then to keep it passing. Green Enough production code should be written to make the test pass. Does the production code make the test pass? (Plainly obvious) Does a subset of the production code make the test pass? If so, you can comment or (best) remove the unnecessary production code. Any more lines you write are untested lines you'll have to read and maintain in the future. Every other specific action will be taken in the Refactor phase. Refactor Improve the structure of the code to ease future changes and maintenance. Does repeated code exist in the current class? Is the name of the class under test appropriate? Do the public and protected method names describe their intent? Are they readable? Rename refactorings are between the most powerful ones. Does repeated code exist in different classes? Is there a missing domain concept? You can extract abstract classes or refactor towards composition. At this high-level the refactoring should be also applied to the unit tests, and there are many orthogonal techniques you can apply so I won't describe them all here. Feel free to add insights and items on the list in the comments. I value very much feedback from other TDDers. From http://giorgiosironi.blogspot.com/2010/03/tdd-checklist-red-green-refactor-in.html
March 30, 2010
by Giorgio Sironi
· 16,068 Views
article thumbnail
Share Eclipse Perspective Layouts Across Multiple Workspaces
once you’ve configured eclipse preferences to your heart’s content, you’ll often want to share those preferences across multiple workspaces. now normally you can go to file > export > general > preferences to save your preferences to a properties file which you can then import into the other workspace. this will share settings such as your customised keyboard shortcuts, formatting, repository settings, etc. but, for some reason, eclipse doesn’t save perspective/window layouts, such as which views are open and where they are placed in the perspective. so you’ll find yourself spending another half hour configuring the window to the way you like it. after the 3rd workspace you need to create, this becomes frustrating and just wastes time. fortunately there are ways to save and restore these settings automatically. the first is to save the perspective into the preferences and the other is to use eclipse’s copy settings feature when opening the other workspace. i prefer the first option, but i’ll mention the second option and when to use the one over the other. method 1: save the layout as a new perspective the first method is to save the perspective layout as another perspective, then export the preferences file as normal. the saved perspective’s settings will be included in the preferences file. when you’ve updated the layout, just resave and overwrite the perspective and export the preferences again. to save your perspective, select window > save perspective as… from the application menu. a dialog should popup (shown below), prompting you for a perspective name. enter a name that you’ll remember, eg. my java or debug jack . click ok once you’ve entered a new name. note : you can choose to overwrite one of the default perspectives, eg. java , without fear. however, i prefer to leave these intact, so always choose a new name, but you can choose whatever works for you. now you can go through the normal routine of exporting the preferences to a properties file via file > export > general > preferences . then import the same file in another workspace via file > import > general > preferences . all you now have to do is switch over to the perspective you saved and all your layout settings will be restored. if you overwrote one of the default perspectives, you may have to select window > reset perspective… to restore the saved settings. if you’ve chosen to create a new perspective, be sure to point your run/debug settings to the new perspective under window > preferences > run/debug > perspectives . for example, if you made a new perspective based on the debug perspective, then you’ll need to change references to the debug perspective to the my debug for launchers you use. luckily this is only required once as these settings are also saved when you export preferences (at least since eclipse 3.5). gotcha: i use fast views a lot , and for some reason the fast view dock’s position isn’t restored automatically. but manually restoring this is as easy as moving the dock, so it’s not that bad. toolbar settings aren’t saved either, but i haven’t tampered with these a lot anyway since i prefer using the keyboard and mouse gestures. method 2: use copy settings the other method of saving your window layout is to use the copy settings feature when switching to another workspace. to use this feature, first open the workspace that contains your customised layout. then select file > switch workspace > other… which will open a dialog prompting you for an existing/new workspace. select the workspace, then click the copy settings collapsible section. select the workbench layout checkbox and click ok. your workspace will open and should reflect the customised layout of the previous workspace. here’s what the dialog looks like: which method should i use? well, as i said before, i prefer the first method for a number of reasons. if some of these apply to you then you might want to use the first method as well. use this method if: you want to share layout settings across workspaces on different machines, eg. work and home. this method is a lot more portable because you only need one single properties file. you spend 90% of your time in 1 or 2 perspectives (eg. java & debug) then this method works well because you only have to manage those perspectives. you make a lot temporary changes to perspectives that you don’t necessarily want shared. for example, if you’ve opened a number of views that you rarely use, you don’t want to clutter your new workspace with these views. i find that i have my “base” perspective layout, around which things will change depending on the context and i don’t want these to clutter my “base” layout. you want to share preferences with a colleague/friend. use the copy settings method if: you want to quickly create another workspace with the saved layout without having to export any preferences. you have made a number of changes across many perspectives and you want to restore those settings. you’re feeling lazy. with this method, eclipse manages a lot more things, so it’s a bit easier to manage (in the short-term), but for the longer term, the first method is best. from http://eclipseone.wordpress.com
March 26, 2010
by Byron M
· 16,626 Views
article thumbnail
Pipes and Filters Pattern in .NET
A pipeline in software context is a very well-known architectural style in which a process consists of a series of steps to be followed in order to proceed the data, and the output of one step is the input of another step. This is also called the Pipes and Filters design pattern. The naming comes from the physical pipeline as this architectural style is very similar to a pipeline in which a stream of data comes in and leaves after being processed. The original idea of pipeline in software is implemented in Unix. This pattern is used in many places. Compiler pipeline, ASP.NET HTTP Pipeline, and workflows are three of many examples that I can mention. The pipes and filters style is implemented in various platforms with different techniques and technologies. Recently I was in a situation to implement this pattern and did some research to find more about the possible options to implement this pattern in the .NET Framework. Doing my research, I found many approaches introduced by community members but the most mature technique is the one that Oren Eini has described in his blog post using Generics. There is also an interesting technique described by Jeremy Likness using the yield keyword in C#. In this post I’m going to apply Oren’s approach and expand it to write a simple implementation of the classic KWIC example in Software Engineering. I liked Oren’s code because as he said, it’s comparatively simpler than other solutions introduced for this problem in the .NET Framework. An Overview of KWIC KWIC stands for Key Word in Context and is a classic problem in Software Engineering papers in which you try to create an index of words by sorting and aligning each word in a piece of text. David Parnas has a famous paper on modularity that uses KWIC as an example. There are some basic and advanced implementations of KWIC in different platforms but the main steps are: Reading the input Shifting the words in each line to get a new permutation Sorting the results Writing the output Interestingly, in this case the output of each step is the input of the next step which makes this a good candidate for the Pipes and Filters pattern. Implement the Pipes and Filters Pattern with Generics Oren’s technique for implementing the Pipes and Filters in the .NET Framework is based on a Generic interface and a Generic class. The Generic interface simulates the filter and the Generic class simulates the pipeline. The IOperation interface has a single method called Execute that is the implementation of the filter logic. Each filter should implement this interface. using System.Collections.Generic;namespace KwicPipesFilters{ public interface IOperation { IEnumerable Execute(IEnumerable input); } The use of a generic IEnumerable is a good choice because it leaves a lot of space for the developers to plug in any type that they want and use various types for their filters. The Pipeline class has an Execute and a Register method. Using the Register method, you add different filters to the pipeline and using the Execute method, you start processing the item in all the registered filters. using System.Collections.Generic;namespace KwicPipesFilters{ public class Pipeline { private readonly List> operations = new List>(); public Pipeline Register(IOperation operation) { operations.Add(operation); return this; } public void Execute() { IEnumerable current = new List(); foreach (IOperation operation in operations) { current = operation.Execute(current); } IEnumerator enumerator = current.GetEnumerator(); while (enumerator.MoveNext()); } } The implementation of the Pipeline class is straightforward: it keeps a list of filters and provides a Register function that lets you add new filters to your pipeline, and then use the Execute method to execute all the filters in the list to process an input. Reader The Reader filter reads the input text from a file and returns an IEnumerable list of lines. Of course, for the first filter in the pipe we don’t care about the input as the input is read inside the filter itself. using System;using System.Collections.Generic;using System.IO;namespace KwicPipesFilters{ public class Reader : IOperation { public IEnumerable Execute(IEnumerable input) { Console.Title = "Pipes and Filters Pattern in .NET"; Console.WriteLine("Enter the path of the file:"); return File.ReadLines(Console.ReadLine()); } } Shifter The Shifter filter is where the main logic of the KWIC application is implemented. It shifts the words in each line to find all the possible permutations suitable for the index. using System.Collections.Generic;namespace KwicPipesFilters{ public class Shifter : IOperation { public IEnumerable Execute(IEnumerable input) { List shifts = new List(); foreach (string line in input) { string[] words = line.Split(new char[] { ' ' }); for (int i = 0; i <= words.Length - 1; i++) { shifts.Add(string.Join(" ", words)); string firstWord = words[0]; for (int j = 1; j <= words.Length - 1; j++) { words.SetValue(words[j], j - 1); } words.SetValue(firstWord, words.Length - 1); } } return shifts; } } Here we have a basic implementation of the Shifter filter where we split the line into separate words based on the space between them, then shift all the words to find various permutations. Sorter Before returning the final results in the Writer filter, we need to sort the index alphabetically. This is done in the Sorter filter. using System.Collections.Generic;using System.Linq;namespace KwicPipesFilters{ public class Sorter : IOperation { public IEnumerable Execute(IEnumerable input) { LineComparer lineComparer = new LineComparer(); input.ToList().Sort(lineComparer); return input; } } Here I used a LineComparer class to implement the ICcomparer interface for the string type. using System.Collections.Generic;namespace KwicPipesFilters{ public class LineComparer : IComparer { public int Compare(string x, string y) { return string.Compare(x, y); } } Writer Obviously, the last filter should write the index to the output for the user and that’s the purpose of the Writer filter. using System;using System.Collections.Generic;namespace KwicPipesFilters{ public class Writer : IOperation { public IEnumerable Execute(IEnumerable input) { foreach (string line in input) { Console.WriteLine(); Console.WriteLine(line); } Console.ReadLine(); yield break; } } As you see, this filter uses a yield break to avoid returning any result. Pipeline Having all the filter implemented, I also need to implement the pipeline itself in order to register the filters and make the whole thing work. I do this in my KwicPipeline class with a simple code that it has. namespace KwicPipesFilters{ public class KwicPipeline : Pipeline { public KwicPipeline() { Register(new Reader()); Register(new Shifter()); Register(new Sorter()); Register(new Writer()); } } I inherit from the Pipeline class and register my filters in the public constructor. Putting It Together There is only one step remained and that is putting all these things together to start the pipeline. All I need to do is to create an instance of the KwicPipeline class, call its Execute method, and leave the rest to my pipes and filters. namespace KwicPipesFilters{ class Program { static void Main(string[] args) { KwicPipeline pipeline = new KwicPipeline(); pipeline.Execute(); } } Conclusion In this post I implemented the Pipes and Filters pattern in the .NET Framework using a simple and generalized technique that relies on Generics to implement the KWIC application. In my opinion this is one of the best ways to implement this pattern in the .NET Framework. I have uploaded the sample source code package here. Note that the solution is created using Visual Studio 2010 RC1. There are other techniques to implement this pattern in .NET and one specific technique that I have in mind is using the Windows Workflow Foundation. I may work more on this idea and write about it later.
March 25, 2010
by Keyvan Nayyeri
· 17,349 Views
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,723 Views · 11 Likes
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,339 Views · 1 Like
article thumbnail
Bean Validation and JSR 303
In this article, I will show you how to use the new Bean Validation Framework aka JSR-303. The legacy Before getting the result that is JSR 303, aka the Bean Validation framework, there were two interesting attempts at validation framework. Each came from an end of the layers and focused on its scope. Front-end validation Struts was the framework to learn and use on the presentation layer in 2001-2002. Struts uses the MVC model and focus on Controllers, which are represented in Struts with Action. Views are plain JSP and Struts uses ActionForm in order to pass data from Controllers to Views and vice-versa. In short, those are POJO that the framework uses to interact with the View. As a presentation layer framework, Struts concern is validating user input. Action forms have a nifty method called validate(). The signature of this method is the following: public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) The developer has to check whether the form is valid then fill the ActionErrors object (basically a List) if it’s not the case. Struts then redirects the flow to an error page (the input) if the ActionErrors object is not empty. Since manual checking is boring and error-prone, it may be a good idea to automate such validation. Even at that time, declarative validation was considered to be the thing. This is the objective of Apache Commons Validator. Its configuration is made through XML. You specify: the validators you have access to. There are some built-in but you can add your own the associations between beans and validators: which beans will be validated by which rules Though Struts tightly integrates Commons Validator, you can use the latter entirely separately. However, the last stable version (1.3.1) was released late 2006. The current developed version is 1.4 but the Maven site hasn’t been updated since early 2008. It is a bit left aside for my own tatse so I rule it out for my validation needs save when I am forced to use Struts. In this case it is mandatory for me to use it since the Struts plugin knows how to use both XML configuration files to also produce JavaScript client-side validation. Back-end validation Previously, we saw that the first validation framework came from user input. At the other end of the specter, inserting/updating data does not require such validation since constraints are enforced in the database. For example, trying to insert a 50 characters length string into a VARCHAR(20) column will fail. However, letting the database handle validation has two main drawbacks: it has a performance cost since you need to connect to the database, send the request and handle the error such error cannot be easily mapped to a Java exception and if possible, to a particular attribute in error In the end, it is better to validate the domain model in the Java world, before sending data to the database. Such was the scope of Hibernate Validator. Whereas Commons Validator configuration is based on XML, Hibernate Validator is based on Java 5 annotations. Even if Hibernate Validator was designed to validate the domain model, you could use it to validate any bean. JSR 303 Bean Validation Finally, JSR 303 came to fruitition. Two important facts: it is end-agnostic, meaning you can use it anywhere you like (front-end, back-end, even DTO if you follow this pattern) and its reference implementation is Hibernate Validator v4. JSR 303 features include: validation on two different levels: attribute or entire bean. That was not possible with Hibernate Validator (since it was database oriented) and only possible with much limitations with Commons Validator i18n ready and message are parameterized extensible with your own validators configurable with annotations or XML. In the following, only the annotation configuration will be shown In JSR 303, validation is the result of the interaction between: the annotation itself. Some come with JSR 303, but you can build your own the class that will validate the annotated bean Simplest example The simplest example possible consist of setting a not-null constraint on an attribute of a class. This is done simply so: public class Person { private String firstName; @NotNull public String getFirstName() { return firstName; } // setter } Note that the @NotNull annotation can be placed on the attribute or on the getter (just like in JPA). If you use Hibernate, it can also use your JSR 303 annotations in order to create/update the database schema. Now, in order to validate an instance of this bean, all you have to do is: Set> violations = validator.validate(person); If the set is empty, the validation succeeded, it not, it failed: the principle is very similar to both previous frameworks. Interestingly enough, the specs enforce that constraints be inherited. So, if a User class inherits from Person, its firstName attribute will have a not-null constraint too. Constraints groups On the presentation tier, it may happen that you have to use the same form bean in two different contexts, such as create and update. In both contexts you have different constraints. For example, when creating your profile, the username is mandatory. When updating, it cannot be changed so there’s no need to validate it. Struts (and its faithful ally Commons Validator) solve this problem by associating the validation rules not with the Java class but with the mapping since its scope is the front-end. This is not possible when using annotations. In order to ease bean reuse, JSR 303 introduce constraint grouping. If you do not specify anything, like previously, your constraint is assigned to the default group, and, when validating, you do so in the default group. You can also specify groups on a constraint like so: public class Person { private String firstName; @NotNull(groups = DummyGroup) public String getFirstName() { return firstName; } // setter } So, this will validate: Person person = new Person(); // Empty set Set> violations = validator.validate(person); This will also: Person person = new Person(); // Empty set Set> violations = validator.validate(person, Default.class); And this won’t: Person person = new Person(); // Size 1 set Set> violations = validator.validate(person, DummyGroup.class); Custom constraint When done playing with the built-in constraints (and the Hibernate extensions), you will probably need to develop your own. It is very easy: constraints are annotations that are themselves annotated with @Constraint. Let’s create a constraint that check for uncapitalized strings: @Target( { METHOD, FIELD, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = CapitalizedValidator.class) public @interface Capitalized { String message() default "{ch.frankel.blog.validation.constraints.capitalized}"; Class[] groups() default {}; Class[] payload() default {}; } The 3 elements are respectively for internationalization, grouping (see above) and passing meta-data. These are all mandatory: if not defined, the framework will not work! It is also possible to add more elements, for example to parameterize the validation: the @Min and @Max constraints use this. Notice there’s nothing that prevents constraints from being applied to instances rather than attributes, this is defined by the @Target and is a design choice. Next comes the validation class. It must implement ConstraintValidator: public class CapitalizedValidator implements ConstraintValidator { public void initialize(Capitalized capitalized) {} public boolean isValid(String value, ConstraintValidatorContext context) { return value == null || value.equals(WordUtils.capitalizeFully(value)); } } That’s all! All you have to do now is annotate attributes with @Capitalized and validate instances with the framework. There’s no need to register the freshly created validator. Constraints composition It is encouraged to create simple constraints then compose them to create more complex validation rules. In order to do that, create a new constraint and annotate it with the constraints you want to compose. Let’s create a constraint that will validate that a String is neither null nor uncapitalized: @NotNull @Capitalized @Target( { METHOD, FIELD, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = {}) public @interface CapitalizedNotNull { String message() default "{ch.frankel.blog.validation.constraints.capitalized}"; Class[] groups() default {}; Class[] payload() default {}; } Now, annotate your attributes with it and watch the magic happen! Of course, if you want to prevent constraint composition, you’ll have to restrain the @Target values to exclude ANNOTATION_TYPE. Conclusion This article only brushed the surface of JSR 303. Nevertheless, I hoped it was a nice introduction to its features and gave you the desire to look into it further. You can find here the sources (and more) for this article in Eclipse/Maven format. From http://blog.frankel.ch
March 23, 2010
by Nicolas Fränkel
· 60,815 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,731 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,895 Views
article thumbnail
Securing Your JSF Pages Against XSS
Cross site scripting (XSS) is a security vulnerability found in websites where malicious attackers inject malicious javascripts to steal information from users accessing the websites. This type of attack usually take advantage of defects in websites that have minimum checking on user inputs hence allow attackers to put malicious code onto the websites. There are a few types of attacks 1. Non-persistent, where attackers put malicious code in the request, resulting in the destination page executing the code. Even though this seems harmless (because it seems like the attackers can only attack the page he is viewing himself), however, attackers can put the malicious code inside a hidden frame on his/her own websites and once the user visits the website, the malicious code is executed without user knowing, and therefore steal visitors information. For example, I could have hide the code of this link inside a hidden frame and submit the cookie back into my server. 2. Persistent Very similiar technique are applied here, but this impact is much more wide spread and serious. This is because attackers are able to embed malicious code into the content of a prominent website. Websites that allows people to post HTML contents usually suffer from this vulnerability. Protect your site against XSS Obviously the best defense to XSS is to make sure that you always validate inputs from browser. Here I will share a few tips with JSF/Java developers on some of the defense techniques available. Escape output text and by default has the escape attribute set to True. By using this tag to display outputs, you are able to mitigate majority of the XSS vulnerability. SeamTextParser and If you would like to allow users to utilise some of the basic html tags to customise their inputs, JBoss Seam provides a tag that allows some basic html tags and styles specified by users. Please refer to the Seam Reference Manual for details on the syntax. You can also customise SeamTextParse to add additional supported syntax. The tag uses this class to validate and escape user's inputs by default. Protect your site's cookies Java web application doesn't make heavy uses of cookies, however, jsessionid is the cookie that mostjava web application must have in order for the application server to keep track of user sessions. To protect cookies against malicious javascript, most modern browsers support the feature to allow application to specify whether a specific cookie can be accessed by javascript or should be for http only. Below is a list of browsers and the support for http-only setting: Browser Version No Reads No Writes Read in XMLHttpResponse IE 6 sp1 yes no no IE 7 yes yes partially IE 8 beta 2 yes yes partially Firefox 3 yes yes yes Safari 3 no no no Chrome Beta yes no no (Source: OWASP) Some application servers also allow http-only jsessionid cookie configuration as well, here is a list of supported servers and their versions. Application Server Version HttpOnly jsessionid Tomcat 6 No, but can use apache with mod_header Header edit Set-Cookie ^(.*)$ $1;Secure;HttpOnly Tomcat 5 No, but can use apache with mod_header JBoss EAP 5 JBoss EAP 4.3 No, but can use apache with mod_header Weblogic 10.3 No, but can use apache with mod_header Weblogic 9 true Jetty No Defending against malicious attackers is not an easy tasks. However, most of the attacks can be mitigated by employing simple principles during application development, such as escaping user inputs. Raising the awareness of security, provide training, and setting common practices are the most effective way to protect your websites. From KoLe Enterprise Consulting blog
March 22, 2010
by Ed Lee
· 29,536 Views · 1 Like
article thumbnail
Distance Calculation Using Latitude And Longitude In C
ZIPCodeWorld.com provides this routine to calculate the distance between two points (given the latitude/longitude of those points) in C. It is being used to calculate distance between two points lat1, long1 and lat2, long2 and uses radius of earth in kilometers or miles as an argurments using our ZIPCodeWorld(TM) and PostalCodeWorld(TM) products which offer the United States ZIP codes, Canadian Postal Codes, Mexican Postal Codes and North American Area Codes database subscription and solution services. #include #define pi 3.14159265358979323846 double distance(double lat1, double lon1, double lat2, double lon2, char unit) { double theta, dist; theta = lon1 - lon2; dist = sin(deg2rad(lat1)) * sin(deg2rad(lat2)) + cos(deg2rad(lat1)) * cos(deg2rad(lat2)) * cos(deg2rad(theta)); dist = acos(dist); dist = rad2deg(dist); dist = dist * 60 * 1.1515; switch(unit) { case 'M': break; case 'K': dist = dist * 1.609344; break; case 'N': dist = dist * 0.8684; break; } return (dist); } /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ /*:: This function converts decimal degrees to radians :*/ /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ double deg2rad(double deg) { return (deg * pi / 180); } /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ /*:: This function converts radians to decimal degrees :*/ /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ double rad2deg(double rad) { return (rad * 180 / pi); }
March 19, 2010
by Snippets Manager
· 5,559 Views
  • Previous
  • ...
  • 1604
  • 1605
  • 1606
  • 1607
  • 1608
  • 1609
  • 1610
  • 1611
  • 1612
  • 1613
  • ...
  • 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
×