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

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,020 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,334 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,140 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,818 Views · 4 Likes
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,487 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,549 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,291 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,767 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,694 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,858 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,574 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,723 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,613 Views · 5 Likes
article thumbnail
Proxy Pattern Tutorial with Java Examples
Learn the Proxy Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
March 12, 2010
by James Sugrue
· 159,084 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,097 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,069 Views · 1 Like
article thumbnail
Generate Class Constructors in Eclipse Based on Fields or Superclass Constructors
You’ll often need to add a constructor to a class based on some/all of its fields or even based on constructors of its superclass. Take the following code: public class Contact { private String name, surname; private int age; public Contact(String name, String surname, int age) { this.name = name; this.surname = surname; this.age = age; } } That’s 5 lines of code (lines 5-9) just to have a constructor. You could write them all by hand, but writing a constructor that accepts and initialises each field takes a lot of time and becomes irritating after a while. And creating constructors from a superclass can take even longer because the superclass can define multiple constructors that you need to reimplement. That is why Eclipse has two features to help you generate these constructor instantly: Generate Constructor using Field and Generate Constructor from Superclass. Both features will generate a constructor in seconds, freeing you up to get to the exciting code. You’ll also see how to add/remove/reorder arguments of an existing constructor based on fields defined in the class. Generate a constructor from fields The fastest way to generate a constructor based on fields is to press Alt+Shift+S, O (alternatively select Source > Generate Constructor using Fields… from the application menu). This pops up a dialog where you can select the fields you want to include in the constructor arguments. Once you’ve selected the fields you want, just click Ok and you’re done. BTW, Alt+Shif+S is the shortcut to display a shortened Source menu, allowing Java source editing commands. The following video shows an example of how much time this feature can save you. We’ll create a constructor for the class Message. Notes: You can additionally call a superclass constructor with a subset of the fields by changing the dropdown Select super constructor to invoke at the top of the dialog. This creates a super(…) call with the relevant arguments and initialising code for the rest of the arguments on your subclass’s constructor. If you don’t want the JavaDoc for the constructor, disable the checkbox Generate constructor comments on the dialog. You can include/exclude the calls to super() using the checkbox Omit call to default constructor super(), on the dialog. You have to be positioned in a class to invoke this command. If you use frequently use this command, you can remap its keyboard shortcut by changing the key binding for the command Generate Getters and Setters. Generate constructor(s) from a superclass Sometimes you’ll want to reimplement some/all of a superclass’s constructors, especially as part of the contract. To generate constructor(s) from a superclass, just press Alt+Shift+S, C (or alternatively select Source > Generate Constructor from Superclass… from the application menu). A dialog pops up allowing you to select the constructor(s) you’d like to create. Once you click Ok, Eclipse generates the constructor, together with a super() call. Here’s an example of how to create a constructor in SecretMessage, that inherits from the class Message. Message has three constructors: a default one, one that accepts one String (content) and another that accepts three Strings (content, fromAddress and toAddress). SecretMessage should only expose the last two constructors. Note: You have to be positioned in a class to invoke this command. If you use this command frequently, you can remap its keyboard shortcut by changing the key binding for the command Generate constructors from superclass. Add, reorder and remove fields on existing constructors If you have an existing constructor and want to reorder its arguments or remove some of them, have a look at the Change Method Signature refactoring that does that in a jiffy. If you want to add a single field to an existing constructor, have a look at the next video that uses Eclipse’s Quick Fix (Ctrl+1) to do that easily. I’ll add a field createdDate to an existing constructor in Message by choosing Assign parameter to field from the Quick Fix menu while positioned on the field. From http://eclipseone.wordpress.com
March 9, 2010
by Byron M
· 31,014 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,178 Views · 23 Likes
article thumbnail
Annotating Custom Types in Hibernate
Hibernate has a lot of nice features, and it's pretty well documented, but a recent need to add a simple custom type to an existing mapping left me flailing around for documentation on exactly how to do it. I wanted to do it with annotations, not by updating the Hibernate configuration (that approach is well-documented). Here's how it's done. Two new classes are needed. You can do it with one (and the Hibernate examples do it that way), but they really have different functions, so I coded them separately. The first is the class you want to use for the column. In my case, I needed a Date with no milliseconds, which is a thin wrapper over java.util.Date. Here's my class: /** * Oracle stores dates in DATE columns down to the second; Java stores them to the millisecond. * This occasionally can confuse Hibernate as to what data are stale. This class slices off * any milliseconds which might be present in its representation. */public class DateNoMs extends java.util.Date { private static final long serialVersionUID = 1L; /** @see java.util.Date() */ public DateNoMs() { super(); long t = getTime(); setTime(t - t%1000); } /** @see java.util.Date(long) */ public DateNoMs(long time) { super(time - time%1000); } /** * @param value */ public DateNoMs(Date value) { long t = value.getTime(); setTime(t - t%1000); } /** @see java.util.Date#setTime(long) */ @Override public void setTime(long time) { super.setTime(time - time%1000); } Straightforward, right? Now, in my class, I have a field mapping: @Column(name = "PAYMENT_DATE") private DateNoMs m_paymentDate; Of course, this won't run--Hibernate will gag on the mapping, because it doesn't know how to map a JDBC DATE column to a DateNoMs--as one would expect. There are two things we need at this point: first, an object which Hibernate can use to transform JDBC DATE into a DateNoMs, and an annotation pointing to that "Factory". The factory class is produced by implementing (in the simplest case) org.hibernate.usertype.UserType. Documentation in this interface is pretty thin, but there are good examples available in the Hibernate distribution. Here's my implementation. I'm greatly helped by the fact that my class (DateNoMs) is very close to java.util.Date, and java.sql.Date extends java.util.Date. /** * Map "things" (currently Oracle Date columns) to the DateNoMs. */public class DateNoMsType implements UserType { /** @see org.hibernate.usertype.UserType#assemble(java.io.Serializable, Object) */ public Object assemble(Serializable cached, @SuppressWarnings("unused") Object owner) { return cached; } /** @see org.hibernate.usertype.UserType#deepCopy(Object) */ public Object deepCopy(Object value) { if (value==null) return null; if (! (value instanceof java.util.Date)) throw new UnsupportedOperationException("can't convert "+value.getClass()); return new DateNoMs((java.util.Date)value); } /** @see org.hibernate.usertype.UserType#disassemble(Object) */ public Serializable disassemble(Object value) throws HibernateException { if (! (value instanceof java.util.Date)) throw new UnsupportedOperationException("can't convert "+value.getClass()); return new DateNoMs((java.util.Date)value); } /** @see org.hibernate.usertype.UserType#equals(Object, Object) */ public boolean equals(Object x, Object y) throws HibernateException { return x.equals(y); } /** @see org.hibernate.usertype.UserType#hashCode(Object) */ public int hashCode(Object value) throws HibernateException { return value.hashCode(); } /** @see org.hibernate.usertype.UserType#isMutable() */ public boolean isMutable() { return true; } /** @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, String[], Object) */ public Object nullSafeGet(ResultSet rs, String[] names, @SuppressWarnings("unused") Object owner) throws HibernateException, SQLException { // assume that we only map to one column, so there's only one column name java.sql.Date value = rs.getDate( names[0] ); if (value==null) return null; return new DateNoMs(value.getTime()); } /** @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, Object, int) */ public void nullSafeSet(PreparedStatement stmt, Object value, int index) throws HibernateException, SQLException { if (value==null) { stmt.setNull(index, Types.DATE); return; } if (! (value instanceof java.util.Date)) throw new UnsupportedOperationException("can't convert "+value.getClass()); stmt.setDate( index, new java.sql.Date( ((java.util.Date)value).getTime()) ); } /** @see org.hibernate.usertype.UserType#replace(Object, Object, Object) */ public Object replace(Object original, @SuppressWarnings("unused") Object target, @SuppressWarnings("unused") Object owner) { return original; } /** @see org.hibernate.usertype.UserType#returnedClass() */ @SuppressWarnings("unchecked") public Class returnedClass() { return DateNoMs.class; } /** @see org.hibernate.usertype.UserType#sqlTypes() */ public int[] sqlTypes() { return new int[] {Types.DATE}; } The core of this class is the two methods which get and set values associated with my new type: nullSafeSet and nullSafeGet. One key thing to note is that nullSafeGet is supplied with a list of all the column names mapped to the custom datatype in the current query. In my case, there's only one, but in complex cases, you can map multiple columns to one object (there are examples in the Hibernate documentation). The final piece of the puzzle is the annotation which tells Hibernate to use the new "Type" class to generate objects of your custom type by adding a new @Type annotation to the column: @Type(type="com.gorillalogic.type.DateNoMsType") @Column(name = "PAYMENT_DATE") private DateNoMs m_paymentDate; The @Type annotation needs a full path to the class that implements the userType interface; this is the factory for producing the target type of the mapped column. If you're going to use your new type in a lot of places, you can shorten the @Type annotation by doing a typedef; you can place this in package-info.java in any package you like (I put mine in the same package as the UserType class). Here's the line for the type defined above: @TypeDefs( { @TypeDef(name = "dateNoMs", typeClass = com.gorillalogic.type.DateNoMsType.class }) package com.gorillalogic.type; Now my column annotation can look like this: @Type(type="dateNoMsType") @Column(name = "PAYMENT_DATE") private DateNoMs m_paymentDate; That should be enough to get you started. From http://execdesign.blogspot.com
March 4, 2010
by Jerry Andrews
· 94,285 Views
article thumbnail
Building a Star Rating System with ASP.NET MVC and jQuery
While working on the WeBlog project I realized that I needed a star rating system for blog posts.
March 2, 2010
by Michael Ceranski
· 32,777 Views
  • Previous
  • ...
  • 878
  • 879
  • 880
  • 881
  • 882
  • 883
  • 884
  • 885
  • 886
  • 887
  • ...
  • 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
×