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
Flamingo Tutorial
In this article, I will provide you with the documentation to easily use the Flamingo framework and more precisely, its ribbon widget. Introduction Never say that Microsoft never innovates: in Office, it introduced an interesting concept, the ribbon band. The ribbon band is a toolbar of sort. But whereas toolbars are fixed, ribbons layout can change according to the width they display. If you have such an application, just play with it for a few seconds and you will see the magic happens. Recent versions of Swing do not have such widgets. However, I found the Flamingo project on java.net. Examples made with Flamingo look awfully similar to Office. Trying to use Flamingo for the first time is no small feat since there’s no documentation on the Web, apart from Javadocs and the source for a test application. The following is what I understood since I began my trial and error journey. The basics Semantics the ribbon is the large bar on the screenshot above. There can be only a single ribbon for a frame a task is a tabbed group of one or more band. On the screenshot, tasks are Page Layout, Write, Animations and so on a band is a group of one or more widgets. On the screenshot, bands are Clipboard, Quick Styles, Font and so on Underlying concepts The core difference between buttons in a toolbar and band in a ribbon bar is that bands are resizable. For examples, these are the steps for displaying the Document band, in regard to both its relative width and the ribbon width. The last step is known as the iconified state. When you click on the button, it displays the entire band as a popup. Your first ribbon Setup In order to use the Flamingo framework, the first step is to download it. If you’re using Maven, tough luck! I didn’t find Flamingo in central nor java.net repositories. So download it anyway and install it manually in your local (or enterprise) repository. For information, I choosed the net.java.dev.flamingo:flamingo location. The frame If you are starting from scratch, you’re lucky. Just inherit from JRibbonFrame: the method getRibbon() will provide you a reference to the ribbon instance. From there, you will be able to add tasks to it. However, chances are you probably already have your own frame hierachy. In this case, you have to instantiate a JRibbon and add it on the NORTH location of your BorderLayout-ed frame. In both cases, the result should be something akin to that: Adding a task Tasks represent logical band grouping. They look like tabs and act the part too. Let’s add two such tasks aptly named “One” and “Two”. public class MainFrame extends JRibbonFrame { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MainFrame frame = new MainFrame(); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); RibbonTask task1 = new RibbonTask("One"); RibbonTask task2 = new RibbonTask("Two"); frame.getRibbon().addTask(task1); frame.getRibbon().addTask(task2); } }); } Notice the getRibbon() method on the JRibbonFrame. It is the reference on the ribbon bar. Also notice that the addTask() method accepts a task but also a varargs of JRibbonBand. And if you launch the above code, it will fail miserably with the following error: Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot have empty ribbon task at org.jvnet.flamingo.ribbon.RibbonTask.(RibbonTask.java:85) at MainFrame$1.run(MainFrame.java:37) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) Adding bands To satisfy our Flamingo friend, let’s add a ribbon band to each task. The constructor of JRibbonBand takes two argument, the label and an instance of a previously unknown class, ResizableIcon. It will be seen in detail in the next section. As for now, if you just create the RibbonTask with a reference to the JRibbonBand and launch the application, you will get such an error: Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot have empty ribbon task at org.jvnet.flamingo.ribbon.RibbonTask.(RibbonTask.java:85) at MainFrame$1.run(MainFrame.java:37) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) Remember that bands are resizable? Flamingo needs information on how to do it. Before initial display, it will check that those policies are consistent. By default, they are not and this is the reason why it complains: Flamingo requires you to have at least the iconified policy that must be in the last place. In most cases, however, you’ll want to have at least a normal display in the policies list. Let’s modify the code to do it: JRibbonBand band1 = new JRibbonBand("Hello", null);JRibbonBand band2 = new JRibbonBand("world!", null);band1.setResizePolicies((List) Arrays.asList(new IconRibbonBandResizePolicy(band1.getControlPanel())));band2.setResizePolicies((List) Arrays.asList(new IconRibbonBandResizePolicy(band1.getControlPanel())));RibbonTask task1 = new RibbonTask("One", band1);RibbonTask task2 = new RibbonTask("Two", band2); The previous code let us at least see something: Adding buttons (at last!) Even if the previous compiles and runs, it still holds no interest. Now is the time to add some buttons! JCommandButton button1 = new JCommandButton("Square", null);JCommandButton button2 = new JCommandButton("Circle", null);JCommandButton button3 = new JCommandButton("Triangle", null);JCommandButton button4 = new JCommandButton("Star", null);band1.addCommandButton(button1, TOP);band1.addCommandButton(button2, MEDIUM);band1.addCommandButton(button3, MEDIUM);band1.addCommandButton(button4, MEDIUM); Too bad there’s no result! Where are our buttons? Well, they are well hidden. Remember the resize policies? There’s only one, the iconified one and its goal is only to display the iconified state. Just update the policies line with the code: band1.setResizePolicies((List) Arrays.asList(new CoreRibbonResizePolicies.None(band1.getControlPanel()), new IconRibbonBandResizePolicy(band1.getControlPanel()))); The result looks the same at first, but when you resize the frame, it looks like this: Even if it’s visually not very attractive, it looks much better than before. We see the taks, the name of the band and the labels on our four buttons. Resizable icons The JCommandButton‘s constructor has 2 parameters: one for the label, the other for a special Flamingo class, the ResizableIcon. Since Flamingo is all about displaying the same button in different sizes, that’s no surprise. Resizable icons can be constructed from Image, ico resources or even SVG. Let’s add an utility method to our frame, and spice up our UI: public static ResizableIcon getResizableIconFromResource(String resource) { return ImageWrapperResizableIcon.getIcon(MainFrame.class.getClassLoader().getResource(resource), new Dimension(48, 48));}...JCommandButton button1 = new JCommandButton("Square", getResizableIconFromResource("path"));JCommandButton button2 = new JCommandButton("Circle", getResizableIconFromResource("to"));JCommandButton button3 = new JCommandButton("Triangle", getResizableIconFromResource("the"));JCommandButton button4 = new JCommandButton("Star", getResizableIconFromResource("resource"));band1.addCommandButton(button1, TOP);band1.addCommandButton(button2, MEDIUM);band1.addCommandButton(button3, MEDIUM);band1.addCommandButton(button4, MEDIUM); This is somewhat more satisfying: Choosing policies Now we’re ready to tackle Flamingo’s core business, resizing management. If you have Office, and played with it, you saw that the resizing policies are very rich. And we also saw previously that with only two meager policies, we can either see the iconified display or the full display. Let’s see how we could go further. You probably noticed that the addCommandButton() of JRibbonBand has 2 parameters: the button to add and a priority. It is this priority and the policy that Flamingo use to choose how to display the band. Priorities are the following: TOP, MEDIUM and LOW. Policies are: Policy Description CoreRibbonResizePolicies.None Command buttons will be represented in the TOP state (big button with label and icon) CoreRibbonResizePolicies.Mid2Mid Command buttons that have MEDIUM priority will be represented in the MEDIUM state (small button with label and icon) CoreRibbonResizePolicies.Mid2Low Command buttons that have MEDIUM priority will be represented in the LOW state (small button only icon) CoreRibbonResizePolicies.High2Mid Command buttons that have HIGH priority will be represented in the MEDIUM state CoreRibbonResizePolicies.High2Low Command buttons that have HIGH priority will be represented in the LOW state CoreRibbonResizePolicies.Low2Mid Command buttons that have LOW priority will be represented in the MEDIUM state CoreRibbonResizePolicies.Mirror Command buttons will be represented in the priority they were assigned to IconRibbonBandResizePolicy Command buttons will be not represented. The entire band will be represented by a command button that when pressed will show a popup of the unconstrained band Now, you have all elements to let you decide which policies to apply. There’s one rule though: when setting policies, the width of the band must get lower and lower the higher the index of the policy (and it must end with the IconRibbonBandResizePolicy) let you’ll get a nasty IllegalStateException: Inconsistent preferred widths (see above). Let’s apply some policies to our band: band1.setResizePolicies((List) Arrays.asList( new CoreRibbonResizePolicies.None(band1.getControlPanel()), new CoreRibbonResizePolicies.Mirror(band1.getControlPanel()), new CoreRibbonResizePolicies.Mid2Low(band1.getControlPanel()), new CoreRibbonResizePolicies.High2Low(band1.getControlPanel()), new IconRibbonBandResizePolicy(band1.getControlPanel()))); This will get us the following result: Note: there won’t be any iconified state in my example since the band does not compete for space with another one. More features Flamingo’s ribbon feature let you also: add standard Swing components to the ribbon add a menu on the top left corner integration with standard Look and Feels tight integration with Substance L&F Those are also undocumented but are much easier to understand on your own. It also has other features: Breadcrumb bar Command button strips and panels Conclusion Flamingo is a nice and powerful product, hindered by a big lack of documentation. I hope this article will go one step toward documenting it. Here are the sources for this article in Eclipse/Maven format. To go further: The Flamingo site Some demo applications The latest release (4.2) download page Kirill Grouchnivkov (Flamingo’s father) site, where he blogs about Flamingo and other products From http://blog.frankel.ch/flamingo-tutorial
June 29, 2010
by Nicolas Fränkel
· 40,763 Views · 1 Like
article thumbnail
How to Automatically Recover Tomcat From Crashes
Tomcat occasionally crashes if you do frequent hot-deploys or if you are running it on a machine with low memory. Every time tomcat crashes someone has to manually restart it, so I wrote a script which automatically detects that tomcat has crashed and restarts it. Here’s the pseudo logic: every few minutes { check tomcat status; if (status is "not running") { start tomcat; } } every few minutes { check tomcat status; if (status is "not running") { start tomcat; } } Here’s a shell script to implement the above logic. It assumes that you are running on a unix/linux system and have /etc/init.d/tomcat* script setup to manage tomcat. Adjust the path to “/etc/init.d/tomcat” in the script below to reflect the correct path on your computer. Sometimes it is called /etc/init.d/tomcat5 or /etc/init.d/tomcat6 depending on your tomcat version. Also make sure that the message “Tomcat Servlet Container is not running.” matches with the message that you get when you run the script when tomcat is stopped. #! /bin/sh SERVICE=/etc/init.d/tomcat STOPPED_MESSAGE="Tomcat Servlet Container is not running." if [ "`$SERVICE status`" == "$STOPPED_MESSAGE"]; then { $SERVICE start } fi #! /bin/sh SERVICE=/etc/init.d/tomcat STOPPED_MESSAGE="Tomcat Servlet Container is not running." if [ "`$SERVICE status`" == "$STOPPED_MESSAGE"]; then { $SERVICE start } fi To run the script every 10 minutes: 1. Save the above script to “/root/bin/recover-tomcat.sh”. 2. Add execute permission: chmod +x /root/bin/recover-tomcat.sh chmod +x /root/bin/recover-tomcat.sh 3. Add this to root’s crontab, type the following as root: crontab -e crontab -e 4. Add the following lines to the crontab: # monitor tomcat every 10 minutes */10 * * * * /root/bin/recover-tomcat.sh # monitor tomcat every 10 minutes */10 * * * * /root/bin/recover-tomcat.sh What if I don’t have /etc/init.d/tomcat* script on my computer? Tomcat creates a pid file, typically in the TOMCAT_HOME/bin directory. This file contains the process id of the tomcat process running on the machine. The pseudo logic in that case would be: if (the PID file does not exist) { // conclude that tomcat is not running start tomcat } else { read the process id from the PID file if (no process that id is running) { // conclude that tomcat has crashed start tomcat } } if (the PID file does not exist) { // conclude that tomcat is not running start tomcat } else { read the process id from the PID file if (no process that id is running) { // conclude that tomcat has crashed start tomcat } } You can implement the above logic as follows. The following is experimental and is merely a suggested way, test it on your computer before using it. # adjust this to reflect tomcat home on your computer TOMCAT_HOME=/opt/tomcat5 if [ -f $TOMCAT_HOME/bin/tomcat.pid ] then echo "PID file exists" pid="`cat $TOMCAT_HOME/bin/tomcat.pid`" if [ "X`ps -p $pid | awk '{print $1}' | tail -1`" = "X"] then echo "Tomcat is running" else echo "Tomcat had crashed" $TOMCAT_HOME/bin/startup.sh fi else echo "PID file does not exist. Restarting..." $TOMCAT_HOME/bin/startup.sh fi # adjust this to reflect tomcat home on your computer TOMCAT_HOME=/opt/tomcat5 if [ -f $TOMCAT_HOME/bin/tomcat.pid ] then echo "PID file exists" pid="`cat $TOMCAT_HOME/bin/tomcat.pid`" if [ "X`ps -p $pid | awk '{print $1}' | tail -1`" = "X"] then echo "Tomcat is running" else echo "Tomcat had crashed" $TOMCAT_HOME/bin/startup.sh fi else echo "PID file does not exist. Restarting..." $TOMCAT_HOME/bin/startup.sh fi Why would tomcat crash? The most common reason is low memory. For example, if you have allocated 1024MB of max memory to tomcat and enough memory is not available on that machine. Other reasons may involve repeated hot-deploys causing memory leaks, rare JVM bugs causing the JVM to crash. From http://www.vineetmanohar.com/2010/06/howto-auto-recover-tomcat-crashes
June 28, 2010
by Vineet Manohar
· 29,841 Views
article thumbnail
Implementing Build-time Bytecode Instrumentation With Javassist
If you need to modify the code in class files at the (post-)build time without adding any third-party dependencies, for example to inject cross-cutting concerns such as logging, and you don’t wan’t to deal with the low-level byte code details, Javassist is the right tool for you. I’ve already blogged about “Injecting better logging into a binary .class using Javassist” and today I shall elaborate on the instrumentation capabilities of Javassist and its integration into the build process using a custom Ant task. Terminology Instrumentation – adding code to existing .class files Weaving – instrumentation of physical files, i.e. applying advices to class files Advice – the code that is “injected” to a class file; usually we distinguish a “before”, “after”, and ‘around” advice based on how it applies to a method Pointcut – specifies where to apply an advice (e.g. a fully qualified class + method name or a pattern the AOP tool understands) Injection – the “logical” act of adding code to an existing class by an external tool AOP – aspect oriented programming Javassist versus AspectJ Why should you use Javassit over a classical AOP tool like AspectJ? Well, normally you wouldn’t because AspectJ is easier to use, less error-prone, and much more powerful. But there are cases when you cannot use it, for example you need to modify bytecode but cannot afford to add any external dependencies. Consider the following when deciding between them: Javassist: Only basic (but often sufficient) instrumentation capabilities Build-time only – modifies .class files The modified code has no additional dependencies (except those you add), i.e. you don’t need the javassist.jar at the run-time Easy to use but not as easy as AspectJ; the code to be injected is handled over as a string, which is compiled to bytecode by Javassist AspectJ: Very powerful Both build-time and load-time (when class gets loaded by the JVM) weaving (instrumentation) supported The modified code depends on the AspectJ runtime library (advices extend its base class, special objects used to provide access to the runtime information such as method parameters) It’s use is no different from normal Java programming, especially if you use the annotation-based syntax (@Pointcut, @Around etc.). Advices are compiled before use and thus checked by the compiler Classical bytecode manipulation library: Too low-level, you need to define and add bytecode instructions, while Javassist permits you to add pieces of Java code Instrumenting with Javassist About some of the basic changes you can do with Javassist. This by no means an exhaustive list. Declaring a local variable for passing data from a before to an after advice If you need to pass some data from a before advice to an after advice, you cannot create a new local variable in the code passed to Javassist (e.g. “int myVar = 5;”). Instead of that, you must declare it via CtMethod.addLocalVariable(String name, CtClass type) and then you can use is in the code, both in before and after advices of the method. Example: final CtMethod method = ...; method.addLocalVariable("startMs", CtClass.longType); method.insertBefore("startMs = System.currentTimeMillis();"); method.insertAfter("{final long endMs = System.currentTimeMillis();" + "System.out.println(\"Executed in ms: \" + (endMs-startMs));}"); Instrumenting a method execution Adding a code at the very beginning or very end of a method: // Advice my.example.TargetClass.myMethod(..) with a before and after advices final ClassPool pool = ClassPool.getDefault(); final CtClass compiledClass = pool.get("my.example.TargetClass"); final CtMethod method = compiledClass.getDeclaredMethod("myMethod"); method.addLocalVariable("startMs", CtClass.longType); method.insertBefore("startMs = System.currentTimeMillis();"); method.insertAfter("{final long endMs = System.currentTimeMillis();" + "System.out.println(\"Executed in ms: \" + (endMs-startMs));}"); compiledClass.writeFile("/tmp/modifiedClassesFolder"); // Enjoy the new /tmp/modifiedClassesFolder/my/example/TargetClass.class There is also CtMethod.insertAfter(String code, boolean asFinally) – JavaDoc: if asFinally “is true then the inserted bytecode is executed not only when the control normally returns but also when an exception is thrown. If this parameter is true, the inserted code cannot access local variables.” Notice that you always pass the code as either a single statement, as in “System.out.println(\”Hi from injected!\”);” or as a block of statements, enclosed by “{” and “}”. Instrumenting a method call Sometimes you cannot modify a method itself, for example because it’s a system class. In that case you can instrument all calls to that method, that appear in your code. For that you need a custom ExprEditor subclass, which is a Visitor whose methods are called for individual statements (such as method calls, or instantiation with a new) in a method. You would then invoke it on all classes/methods that may call the method of interest. In the following example, we add performance monitoring to all calls to javax.naming.NamingEnumeration.next(): final CtClass compiledClass = pool.get("my.example.TargetClass"); final CtMethod[] targetMethods = compiledClass.getDeclaredMethods(); for (int i = 0; i < targetMethods.length; i++) { targetMethods[i].instrument(new ExprEditor() { public void edit(final MethodCall m) throws CannotCompileException { if ("javax.naming.NamingEnumeration".equals(m.getClassName()) && "next".equals(m.getMethodName())) { m.replace("{long startMs = System.currentTimeMillis(); " + "$_ = $proceed($$); " + "long endMs = System.currentTimeMillis();" + "System.out.println(\"Executed in ms: \" + (endMs-startMs));}"); } } }); } The call to the method of interest is replaced with another code, which also performs the original call via the special statement “$_ = $proceed($$);”. Beware: What matters is the declared type on which the method is invoked, which can be an interface, as in this example, the actual implementation isn’t important. This is opposite to the method execution instrumentation, where you always instrument a concrete type. The problem with instrumenting calls is that you need to know all the classes that (may) include them and thus need to be processed. There is no official way of listing all classes [perhaps matching a pattern] that are visible to the JVM, though ther’re are some workarounds (accessing the Sun’s ClassLoader.classes private property). The best way is thus – aside of listing them manually – to add the folder or JAR with classes to Javassist ClassPool’s internal classpath (see below) and then scan the folder/JAR for all .class files, converting their names into class names. Something like: // Groovy code; the method instrumentCallsIn would perform the code above: pool.appendClassPath("/path/to/a/folder"); new File("/path/to/a/folder").eachFileRecurse(FileType.FILES) { file -> instrumentCallsIn( pool.get(file.getAbsolutePath().replace("\.class$","").replace('/','.')) );} Javassist and class-path configuration You certainly wonder how does Javassist find the classes to modify. Javassist is actually extremely flexible in this regard. You obtain a class by calling private final ClassPool pool = ClassPool.getDefault(); ... final CtClass targetClass = pool.get("target.class.ClassName"); The ClassPool can search a number of places, that are added to its internal class path via the simple call /* ClassPath newCP = */ pool.appendClassPath("/path/to/a/folder/OR/jar/OR/(jarFolder/*)"); The supported class path sources are clear from the available implementations of ClassPath: there is a ByteArrayClassPath, ClassClassPath, DirClassPath, JarClassPath, JarDirClassPath (used if the path ends with “/*”), LoaderClassPath, URLClassPath. The important thing is that the class to be modified or any class used in the code that you inject into it doesn’t need to be on the JVM classpath, it only needs to be on the pool’s class path. Implementing mini-AOP with Javassist and Ant using a custom task This part briefly describes how to instrument classes with Javassist via a custom Ant task, which can be easily integrated into a build process. The corresponding part of the build.xml is: Noteworthy: I’ve implemented a simple custom Ant task with the class example.JavassistInjectTask, extending org.apache.tools.ant.Task. It has setters for attributes and nested elements and uses the custom class PerfmonAopInjector (not shown) to perform the actual instrumentation via Javassist API. Attributes/nested elements: setLoglevel(EchoLevel level) – see the EchoTask setOutputFolder(File out) addConfiguredCall(MethodDescriptor call) addConfiguredExecution(MethodDescriptor exec) addFileset(FileSet fs) – use fs.getDirectoryScanner(super.getProject()).getIncludedFiles() to get the names of the files under the dir MethodDescriptor is a POJO with a no-arg public constructor and setters for its attributes (name, type, metric), which is introduced to Ant via and its instances are passed to the JavassistInjectTask by Ant using its addConfigured, where the name equlas the element’s name, i.e. the name specified in the typedef PerfmonAopInjector is another POJO that uses Javassist to inject execution time logging to method executions and calls as shown in the previous section, applying it to the classes/methods supplied by the JavassistInjectTask based on its and configuration The fileset element is used both to tell Javassist in what directory it should look for classes and to find out the classes that may contain calls that should be instrumented (listing all the .class files and converting their names to class names) All the typedefs use the same ClassLoader instance so that the classes can see each other, this is ensured by loaderref="javassistinject" (its value is a custom identifier, same for all three) The monitoringInjectorTask.classpath contains javassist.jar, ant.jar, JavassistInjectTask, PerfmonAopInjector and their helper classes The classes.dir contains all the classes that may need to be instrumented and the classes used in the injected code, it’s added to the Javassist’s internal classpath via ClassPool.appendClassPath(“/absolute/apth/to/the/classes.dir”) Notice that System.out|err.println called by any referenced class are automatically intercepted by Ant and changed into Task.log(String msg, Project.MSG_INFO) and will be thus included in Ant’s output (unless -quiet). PS: If using maven, you’ll be happy yo know that Javassist is in a Maven repository (well, at least it has a pom.xml, so I suppose so). Ant custom task resources Rob Lybarger: Introduction to Custom Ant Tasks (2006) – the basics Rob Lybarger: More on Custom Ant Tasks (2006) – about nested elements Ant manual: Writing Your Own Task Stefan Bodewig: Ant 1.6 for Task Writers (2005) From http://theholyjava.wordpress.com/2010/06/25/implementing-build-time-instrumentation-with-javassist/
June 25, 2010
by Jakub Holý
· 26,057 Views · 3 Likes
article thumbnail
16 Tips for Securing Your Admin Page
So you've finished that shiny new website and you want make sure that you and your buddies are in control. Besides the obvious things such as SSL and logging all access, there are a fewest practices for authentication/access that developers recommend. Here are some of the recommendations: Require separate login pages for users and admin using the same DB table. This will prevent XSRF and session-stealing, plus the attacker won't be able to access to admin areas) [Thief Master] Use complex passwords for admin accounts. For example, "uvula{:&:>iuJ", not "12345". Of course, you have to remember it. :) [Developer Art] Introduce an artificial pause between each admin password attempt to prevent brute force attacks. [Lo'oris] Blocking users IP after a number of failed admin login attempts or requiring a CAPTCHA after a failed login (but not the first one, because that's really annoying) will also stop brute force attacks. [Thief Master] If the admin section is in a separate subdirectory, you should consider also adding webserver native authentication to that area (e.g. via .htaccess in Apache). Then an attacker would need both the subdirectory password and the user password. [Thief Master] Consider Second level authentication such as client certificates (e.g. x509 certs), smart cards, cardspace, etc. [JoeGeeky] Restrict access to the admin area. Only allow clients from trusted IPs/Domains. [JoeGeeky] Lock down IPrincipal & Principal-based authorization and make rights immutable and non-enumerable. Also make sure that all authorization assessments are based on the Principal. [JoeGeeky] Set up an email notification system that alerts admins when any rights are upgraded. This will help you catch an attacker that elevates his/her rights. [JoeGeeky] Consider fine-grained rights for admins. Typical Role-Based Security (RBS) approaches are not as safe because some roles will end up with more rights that they need. You should distribute rights based on the exact actions that a admin performs. This could cause a lot of overhead with more diverse admin-types, but it is safer because rights are issued more sparingly. [JoeGeeky] Restrict the creation of further admins and carefully control what admins can do to other admins. It's best to have a locked-down 'super-admin' client. [JoeGeeky] Consider Client Side SSL Certificates or RSA type keyfobs (electronic tokens) for added security. [Daniel Papasian] If you're using using cookies for authentication, use separate cookies for admin and normal pages. One way is to put the admin section on a different domain. [Daniel Papasian] One possibility, if it's practical, is to put the admin site on a private subnet instead of the internet. [John Hartsock] Re-issue auth/session tickets when moving between admin and normal usage contexts of the website. [Richard JP Le Guen] Require equally strong mechanisms (using the above techniques) for basic users so that admins aren't the only ones with highly-secure accounts. [Lo'oris] These tips were gathered in a question by UpTheCreek from StackOverflow.
June 21, 2010
by Mitch Pronschinske
· 9,191 Views
article thumbnail
NeoLoad 3.1 load tests Java Serialization
Neotys, a leader in easy-to-use, cost effective load testing tools for web applications today announced NeoLoad 3.1, the first test solution on the market to incorporate support for new push technologies such as Adobe RTMP or Ajax Push and now supports Java serialization. A new Java serialization module has been added to record and replay applications using the Java object serialization over HTTP. This module is fully compatible with the spring remote framework. New features Push Technologies module RTMP module Java Serialization module Advanced variabilization Alerts thresholds Customized reports > View all the new features. Free Trial Download the NeoLoad v3.1 demo (30-day free trial). More information http://www.neotys.com
June 18, 2010
by Christophe Marton
· 1,341 Views
article thumbnail
Working with the bit.ly API to shorten URLs
Bit.ly is a quite popular URL shortening service. On Tiwtter, almost all of the links I see provided by the people I follow are posted as bit.ly shortcuts. If you’ve used a Twitter client, you probably already know that some of them (if not almost every single of them) offers URL shortening as a built-in capability. Now, you can implement the same functionality, thanks to the fact that bit.ly offers a public API to do this. But let’s start with coding. First of all, all data that is passed to the service is transferred via HTTP requests. The response generated by the service is by default formatted as a JSON document, however the developer can explicitly specify that XML data should be returned. A request to the bit.ly shortening service requires authentication, and the username and API key are required to be passed as parameters. This means that in order to use the service, a bit.ly account is needed (it is free). The API key can be found here (http://bit.ly/account/your_api_key) once the user registered. Shortening The first (and probably the most important method) is the one that actually shortens the URL and it is called /v3/shorten. V3 at the beginning stands for the API version (that is 3.0 at the moment, so don’t worry about that). This method accepts 5 parameters: • format – determines the output format for the request • longUrl –determines the long URL that needs to be shortened • domain – [optional] the domain used for shortening – either bit.ly or j.mp (default: bit.ly) • x_login – the user ID (although in the documentation it is indicated as optional, it is not) • x_apiKey – the user API key (although in the documentation it is indicated as optional, it is not) Let’s look at the method I’ve written to shorten the URL: enum Format { XML, JSON, TXT } enum Domain { BITLY, JMP } string ShortenUrl(string longURL, string username, string apiKey, Format format = Format.XML, Domain domain = Domain.BITLY) { string _domain; string output; // Build the domain string depending on the selected domain type if (domain == Domain.BITLY) _domain = "bit.ly"; else _domain = "j.mp"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create( string.Format(@"http://api.bit.ly/v3/shorten?login={0}&apiKey={1}&longUrl={2}&format={3}&domain={4}", username, apiKey, HttpUtility.UrlEncode(longURL), format.ToString().ToLower(), _domain)); using (WebResponse response = request.GetResponse()) { using (StreamReader reader = new StreamReader (response.GetResponseStream())) { output = reader.ReadToEnd(); } } return output; } There are two enums that hold the possible data formats as well as the domain names. This is made for safety reasons – if I would pass these as string parameters, there is a higher chance the end-user will pass the wrong string, and then the function will fail. The code is based on a single HttpWebRequest that creates a HTTP request to the URL that is built according to the data passed to it. Then, I am getting the response stream and passing the string representation to the returned string variable. Notice the fact that I am explicitly returning a string value for this method. In fact, I could either return a JsonDocument instance (requires a third-party library to use this class) or XmlDocument. But since there are two possible formats for the request to handle, it is better to return this as a simple string and then let the developer decide what he wants to do next. Once called, the function will return data similar to this: 200 OK http://j.mp/crnexS crnexS msft http://www.microsoft.com 0 Or this (for JSON): { "status_code": 200, "status_txt": "OK", "data": { "long_url": "http:\/\/www.microsoft.com", "url": "http:\/\/j.mp\/crnexS", "hash": "crnexS", "global_hash": "msft", "new_hash": 0 } } Or this (for TXT): http://j.mp/crnexS I am using a custom domain here, but as you see – the format and domain are optional parameters. I can leave them with default values without actually passing them to the function, and then the only values that need to be indicated are the user ID, API key and the long URL. Decoding There is also a way to decode the URL to its initial state from what was the shortened one. The method is called /v3/expand and is used in a similar manner as the shortening one. In this method, I am also using the Format enum to specify the output format: string DecodeUrl(string[] urlSet, string[] hashSet, string username, string apiKey, Format format = Format.XML) { string output; string URL = string.Format(@"http://api.bit.ly/v3/expand?login={0}&apiKey={1}&format={2}", username, apiKey, format.ToString().ToLower()); if (urlSet != null) { foreach (string url in urlSet) URL += "&shortUrl=" + HttpUtility.UrlEncode(url); } if (hashSet != null) { foreach (string hash in hashSet) URL += "&hash=" + hash; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); using (WebResponse response = request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { output = reader.ReadToEnd(); } } return output; } It works a bit different though. As you can see, I am requesting the user to pass two arrays – one with URLs and one with hashes. One of them can be null, therefore the URL can be decoded either by the hash or by the shortened URL. The user can pass both arrays, and get a result similar to this: 200 OK http://j.mp/crnexS http://www.microsoft.com crnexS msft crnexS http://www.microsoft.com crnexS msft The URLs are sanitized inside the function – I am not assuming that the user will pass the encoded URL. In fact, the developer should never assume that the user will pass the correct value – the code should be as foolproof as possible. User validation If you work on an application that depends on the URL shortening service, it would be a good idea to validate the user before making the API calls. Bit.ly provides a method for this as well and it is called /v3/validate. It only requires three parameters – the username, the API key and the output format (that is in fact optional). The C# implementation for this method looks like this: string ValidateUser(string username, string apiKey, string userToCheck, string keyToCheck, Format format = Format.XML) { string output; string URL = string.Format(@"http://api.bit.ly/v3/validate?x_login={0}&x_apiKey={1}&login={2}&apiKey={3}&format={4}", userToCheck, keyToCheck, username,apiKey, format.ToString().ToLower()); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); using (WebResponse response = request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { output = reader.ReadToEnd(); } } return output; } A bit of confusion can be caused by the fact that there are x_ -prefixed copies of login and API key. You need to pass your ID and API key to verify someone else’s account validity. X_ -prefixed parameters represent the end user. The output should look similar to this: 200 OK 1 Count clicks Bit.ly provides click statistics, so once you shorten a URL, you can track its basic usage. Statistics are available through the /v3/clicks method. It doesn’t have a TXT output format, so you will have to avoid using that (or create a separate enum, that is the best choice). The implementation for it looks like this: string GetClicks(string[] urlSet, string[] hashSet, string username, string apiKey, Format format = Format.XML) { string output; string URL = string.Format(@"http://api.bit.ly/v3/clicks?login={0}&apiKey={1}&format={2}", username, apiKey, format.ToString().ToLower()); if (urlSet != null) { foreach (string url in urlSet) URL += "&shortUrl=" + HttpUtility.UrlEncode(url); } if (hashSet != null) { foreach (string hash in hashSet) URL += "&hash=" + hash; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); using (WebResponse response = request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { output = reader.ReadToEnd(); } } return output; } Same as for the Expand method, an array of URLs and hash codes can be passed and statistics will be generated for multiple entries at once. The response looks like this (in XML format): 200 http://j.mp/crnexS msft 0 crnexS 2230 0 msft crnexS crnexS 2230 OK Note that the XML won’t be indented by default. Check for PRO domain Bit.ly offers pro, customizable domains. That means, that not only bit.ly and j.mp can be used for shortening, but user-defined domains as well. The /v3/bitly_pro_domain method allows to check whether a domain is bit.ly PRO-powered or not. It is very similar to the user validation method, but it accepts the domain name instead of the user credentials. The C# implementation looks like this: string CheckPro(string username, string apiKey, string domain, Format format = Format.XML) { string output; string URL = string.Format(@"http://api.bit.ly/v3/bitly_pro_domain?login={0}&apiKey={1}&domain={2}&format={3}", username, apiKey, domain, format.ToString().ToLower()); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); using (WebResponse response = request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { output = reader.ReadToEnd(); } } return output; } Once called, the output looks like this: 200 nyti.ms 1 OK URL lookup Bit.ly also allows the lookup of long URLs. For example, you might want to find if there is an existing short URL for the existing long URL. To do this, there is the /v3/lookup method. The implementation is quite simple and as other methods, it has the same base structure: string Lookup(string username, string apiKey, string[] url, Format format = Format.XML) { string output; string URL = string.Format(@"http://api.bit.ly/v3/lookup?login={0}&apiKey={1}&format={2}", username, apiKey, format.ToString().ToLower()); foreach (string _url in url) URL += "&url=" + HttpUtility.UrlEncode(_url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); using (WebResponse response = request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { output = reader.ReadToEnd(); } } return output; } The XML response looks similar to this for a positive result (there is a URL found): 200 http://www.dreamincode.net http://bit.ly/mviGY mviGY OK Notice that I can pass an array of URLs to be checked. Mind, though, that the maximum number of URLs that can be passed to the method is 15. With the methods described above, you can harness the power of bit.ly and bring it to your .NET application (the code can easily be ported to any .NET-compatible programming language). For official documentation, you can take a look here.
June 18, 2010
by Denzel D.
· 33,598 Views
article thumbnail
Builder Pattern Tutorial with Java Examples
Learn the Builder Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
June 15, 2010
by James Sugrue
· 92,417 Views · 14 Likes
article thumbnail
Waterfall vs. Agile (Part 2): Development and Business
There are so many differences between Agile and Waterfall that it takes a three-part series to cover it all.
June 15, 2010
by Alberto Gutierrez
· 30,028 Views · 1 Like
article thumbnail
Headless Build for Beginners - Part I
The easiest way to generate the plug-in jars is through Export Wizard. Assuming we already know this, lets try to play with headless build. Headless Build Here the workbench (IDE or UI) is referred to as 'head'. Headless build essentially means running the builds from command line in non-UI mode. This can be achieved by various means, however, we will start with java command line and org.eclipse.equinox.launcher jar. Java -jar This is standard Java part. Java executable has many command line options and -jar is one of them. The curious souls can learn more about packaging and executing jars. org.eclipse.equinox.launcher Eclipse has its own OSGi implementation which is known as Equinox. 'org.eclipse.equinox.launcher' is a plug-in as well as executable jar that launches the OSGi Runtime. It is located under plug-ins folder as org.eclipse.equinox.launcher_ ( for example org.eclipse.equinox.launcher_1.1.0.v20100507.jar). -application This '-application' option tells 'org.eclipse.equinox.launcher' that which application has to be launched. The application is identified by its id. The application is discovered using the Application Admin service. The Runtime Application Model explains how it works. org.eclipse.ant.core.antRunner Its the application id for the AntRunner application. It is contributed by org.eclipse.ant.core plug-in and its purpose it to run Ant build files. build.xml Its the Ant script to build the plug-in. Good news is the we need not be expert in Ant (however it good to have some knowledge about it). The PDE Build can generate this help for us. Right click on the build.properties and select PDE Tools -> Create Ant Build File. This will generate build.xml and javaCompiler...args files. There may be more and specially name of the later may vary depending on the output. entry in the build.properties file. Putting the pieces together Assuming that the name of the plugins project is 'com.example.helloworld' the command to build it headlessly will be java -jar \plugins\org.eclipse.equinox.launcher_.jar -application org.eclipse.ant.core.antRunner -buildfile \\ Example: java -jar C:\eclipse\plugins\org.eclipse.equinox.launcher_1.1.0.v20100507.jar -application org.eclipse.ant.core.antRunner -buildfile C:\workspace\com.example.helloworld\build.xml Result This will build the plug-in project according to build.xml script. Since it was generated for us from build.propertied, it is essentially this file that governs the build. Note that build.xml is not generated automatically not kept in sync with build.properties. For any modifications to be reflected, the build.xml file has to be regenerated. Assuming our plug-in does not have the Bundle-Classpath entry in the Manifest.MF file and source.. and output.. are the only source and output entries in our build.properties. The resultant build of such a plug-in will be in a folder '@Dot' in the project along with the log-file @dot.log . This is not quite we expected. We were hoping to see a com.example.helloworld_1.0.0.v201006141121.jar kind of file. This happened because the default target (task) will just compile the classes. To make it generate the jar, edit build.xml and make the default target 'build.update.jar' (mentioned in the very first line). This shall generate the com.example.helloworld_.jar in the project folder. The build.xml can be modified to have it created in a desired location instead. Also note that the timestamp that replaces 'qualifier' is not the build time but the time when the build.xml was generated. From http://blog.ankursharma.org/2010/06/headless-build-for-beginners-part-i.html
June 15, 2010
by Ankur Sharma
· 15,719 Views · 1 Like
article thumbnail
XML Processing and Validation Merging Together
Where does the border lie between validation and the processing itself? The question is if those should be even two separate procedures at all. Let's start with something simple like what the default values are. The most of the other Schema languages allow you to specify the default value. But when should the default value be used? What if some external resources are needed for the default value itself, like a database or a different value in the same document? Does the default value really have to be static? Yes that sounds familiar, it is processing already. XML Processing And what about the processing, didn't you ever need to be sure that the input is valid? And there is another common case, when you need to take actions during the processing based on the fact that some part of the document is valid or not. Sometimes you can't determine the variation of invalidness but you need to take some action based upon that. XDefinition merging processing and validation XDefinition is a schema language developed from the beginning with close respect to the natural readability by keeping the form of the XML data source. Designed to be understandable not only for programmers but also to analysts, system architects and all the other parties concerned with the project. This kind of approach leaves no space to misinterpret data description during it's exchange, starting from the architects to database specialists. XDefinition merges the validation and processing of the XML document as much as you need and what is more important if you need. In the example below we show the usage of an external method, based on the information obtained during the validation is called method. An External method could be any static method in the class supplied to the XDefinition processor through it's API. If you find this kind of approach interesting read the article about readability of the schema languages here on the Javalobby called XSD Schema is not the only way or try the Tutorial with examples. Resources: XDefinition guidepost
June 10, 2010
by Daniel Kec
· 8,946 Views
article thumbnail
State Pattern Tutorial with Java Examples
Learn the State Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
June 9, 2010
by James Sugrue
· 138,827 Views · 17 Likes
article thumbnail
Getting started with Nexus Maven Repo Manager
This tutorial outlines steps required to install Nexus (Maven Repository Manager) under Tomcat, or another webapp container. It shows you practical configuration and includes code snippets that go in your pom.xml and settings.xml in order to read and publish artifacts to your Nexus server. Step 1: Download Download Nexus from here (at the time of writing, latest is 1.6.0) Step 2: Install Copy the war to TOMCAT_HOME/webapps/nexus.war Though not required, it is a generally good idea to restart tomcat after installing a new war /etc/init.d/tomcat restart /etc/init.d/tomcat restart Step 3: Configure security a) Change default admin password: The default admin username/password is admin/admin123. Login as admin and change the password to a secure password. Login -> [admin, admin123] -> Left Menu -> Security -> Change Password -> click “Change Password” b) Anonymous Access: By default Nexus is open to the public. If you want to secure access to nexus, disable ‘Nexus anonymous user’ Admin -> Left Menu -> Users -> ‘Nexus anonymous user’ -> Status=Disabled c) Deployment user: Change password for deployment user Admin -> Left menu -> Users -> Deployment user -> Change email address Admin -> Left menu -> Users -> Right click on ‘Deployment user’ in the user list -> Set Password -> click ‘Set password’ to finish Step 4: Set SMTP server It is a good idea to configure SMTP server, so that you can receive emails from Nexus. Admin login -> Left menu -> Administration -> Server ->SMTP Settings -> (host localhost, port 25, no login, no password mostly works on a linux machine) Step 5: Change Base Url If you are running Nexus behind Apache using mod_jk or mod_proxy, change your base url here. Admin login -> Left menu -> Administration -> Server -> Application Server Settings -> Base url Step 6: Add a task to periodically remove old snapshots If you or your CI server publishes snapshots to Nexus several times a day, then you should consider adding a task to delete duplicate/old snapshots for the same GAV (group, artifact, version). If you don’t do this, you will notice that the Nexus disk usage will increase with time. Admin login -> Left menu -> Administration -> Scheduled tasks -> Add… -> name=”Remove old snapshots”, Repository/Group=Snapshots (Repo), Minimum Snapshot Count=1, Snapshot Retention(days)=3, Recurrence=Daily, Recurring time=2:00 -> click ‘Save’ Step 7: Using Nexus: reading and publishing artifacts If you want to deploy your artifacts to your Nexus, you need to configure 2 files: pom.xml and settings.xml a) pom.xml – for each project which wishes to publish to Nexus, add your repo to the pom.xml vineetmanohar-nexus vineetmanohar nexus dav:http://nexus.vineetmanohar.com/nexus/content/repositories/releases vineetmanohar-nexus vineetmanohar nexus dav:http://nexus.vineetmanohar.com/nexus/content/repositories/snapshots vineetmanohar-nexus vineetmanohar http://nexus.vineetmanohar.com/nexus/content/groups/public true true vineetmanohar-nexus vineetmanohar http://nexus.vineetmanohar.com/nexus/content/groups/public true true vineetmanohar-nexus vineetmanohar nexus dav:http://nexus.vineetmanohar.com/nexus/content/repositories/releases vineetmanohar-nexus vineetmanohar nexus dav:http://nexus.vineetmanohar.com/nexus/content/repositories/snapshots vineetmanohar-nexus vineetmanohar http://nexus.vineetmanohar.com/nexus/content/groups/public true true vineetmanohar-nexus vineetmanohar http://nexus.vineetmanohar.com/nexus/content/groups/public true true b) settings.xml – If you have disabled anonymous access to Nexus, add the deployment password to your ~/.m2/repository/settings.xml file vineetmanohar-nexus deployment password_goes_here From http://www.vineetmanohar.com/2010/06/getting-started-with-nexus-maven-repo-manager
June 7, 2010
by Vineet Manohar
· 105,248 Views · 3 Likes
article thumbnail
Versioning Static Assets with UrlRewriteFilter
A few weeks ago, a co-worker sent me interesting email after talking with the Zoompf CEO at JSConf. One interesting tip mentioned was how we querystring the version on our scripts and css. Apparently this doesn't always cache the way we expected it would (some proxies will never cache an asset if it has a querystring). The recommendation is to rev the filename itself. This article explains how we implemented a "cache busting" system in our application with Maven and the UrlRewriteFilter. We originally used querystring in our implementation, but switched to filenames after reading Souders' recommendation. That part was figured out by my esteemed colleague Noah Paci. Our Requirements Make the URL include a version number for each static asset URL (JS, CSS and SWF) that serves to expire a client's cache of the asset. Insert the version number into the application so the version number can be included in the URL. Use a random version number when in development mode (based on running without a packaged war) so that developers will not need to clear their browser cache when making changes to static resources. The random version number should match the production version number formats which is currently: x.y-SNAPSHOT-revisionNumber When running in production, the version number/cachebust is computed once (when a Filter is initialized). In development, a new cachebust is computed on each request. In our app, we're using Maven, Spring and JSP, but the latter two don't really matter for the purposes of this discussion. Implementation Steps 1. First we added the buildnumber-maven-plugin to our project's pom.xml so the build number is calculated from SVN. org.codehaus.mojo buildnumber-maven-plugin 1.0-beta-4 validate create false false javasvn 2. Next we used the maven-war-plugin to add these values to our WAR's MANIFEST.MF file. maven-war-plugin 2.0.2 true ${project.version} ${buildNumber} ${timestamp} 3. Then we configured a Filter to read the values from this file on startup. If this file doesn't exist, a default version number of "1.0-SNAPSHOT-{random}" is used. Otherwise, the version is calculated as ${project.version}-${buildNumber}. private String buildNumber = null; ... @Override public void initFilterBean() throws ServletException { try { InputStream is = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF"); if (is == null) { log.warn("META-INF/MANIFEST.MF not found."); } else { Manifest mf = new Manifest(); mf.read(is); Attributes atts = mf.getMainAttributes(); buildNumber = atts.getValue("Implementation-Version") + "-" + atts.getValue("Implementation-Build"); log.info("Application version set to: " + buildNumber); } } catch (IOException e) { log.error("I/O Exception reading manifest: " + e.getMessage()); } } ... // If there was a build number defined in the war, then use it for // the cache buster. Otherwise, assume we are in development mode // and use a random cache buster so developers don't have to clear // their browswer cache. requestVars.put("cachebust", buildNumber != null ? buildNumber : "1.0-SNAPSHOT-" + new Random().nextInt(100000)); 4. We then used the "cachebust" variable and appended it to static asset URLs as indicated below. The injection of /v/[CACHEBUSTINGSTRING]/(assets|compressed) eventually has to map back to the actual asset (that does not include the two first elements of the URI). The application must remove these two elements to map back to the actual asset. To do this, we use the UrlRewriteFilter. The UrlRewriteFilter is used (instead of Apache's mod_rewrite) so when developers run locally (using mvn jetty:run) they don't have to configure Apache. 5. In our application, "/compressed/" is mapped to wro4j's WroFilter. In order to get UrlRewriteFilter and WroFilter to work with this setup, the WroFilter has to accept FORWARD and REQUEST dispatchers. rewriteFilter /* WebResourceOptimizer /compressed/* FORWARD REQUEST Once this was configured, we added the following rules to our urlrewrite.xml to allow rewriting of any assets or compressed resource request back to its "correct" URL. ^/v/[0-9A-Za-z_.\-]+/assets/(.*)$ /assets/$1 ^/v/[0-9A-Za-z_.\-]+/compressed/(.*)$ /compressed/$1 /compressed/** /compressed/$1 Of course, you can also do this in Apache. This is what it might look like in your vhost.d file: RewriteEngine on RewriteLogLevel 0! RewriteLog /srv/log/apache22/app_rewrite_log RewriteRule ^/v/[.A-Za-z0-9_-]+/assets/(.*) /assets/$1 [PT] RewriteRule ^/v/[.A-Za-z0-9_-]+/compressed/(.*) /compressed/$1 [PT] Whether it's a good idea to implement this in Apache or using the UrlRewriteFilter is up for debate. If we're able to do this with the UrlRewriteFilter, the benefit of doing this at all in Apache is questionable, especially since it creates a duplicate of code. From http://raibledesigns.com/rd/entry/versioning_static_assets_with_urlrewritefilter
June 5, 2010
by Matt Raible
· 11,816 Views
article thumbnail
Handling Exceptions in Java Using Eclipse
What exactly is an exception? Exceptions are irregular or unusual events that happen in a method the program is calling which usually occurs at runtime. The method throws the Exception back to the caller to show that it is having a problem. If the programmer runs into this case, then they will need to extend an Exception from the Exception class that is already in the Java class library. In Eclipse, on the class declaration panel, the coder and request “constructors from superclass” and it will give the programmer constructors in a child Exception class that will accept error messages or the address of another Exception as a constructor parameter. When creating an Exception class, the programmer has to designate a kind of exception that must be caught or optionally caught. If you declare the Exception class to extend Exception as shown below, the compiler will insist that the method that is being thrown should also be in a caught in catch block. public class CodeName extends Exception { ……. } The compiler gives the programmer two choices when they call a method that throws an Exception that must be caught: 1. Add a try/catch in the code that is being call to catch the Exception 2. Pass the Exception back on to the caller If the programmer chooses option two then they can do this by adding a "throws" clause to end of the method declaration line. The compiler will generate the code to pass the Exception back to the caller at run-time. In the code below, the AnApplcation program is calling a Java Bean object's openFile() method, passing it the file name. The compiler will say to the openFile() method at compile time: "How do you want to handle the Exception?" The AJavaBean should realize there is nothing they can do in the openFile() method to fix the problem so the programmer should throw the Exception back to AnApplication. Eclipse can see the myProgram() in AnApplication is calling the openFile() method and when openFile() adds "throws FileNotFoundException" to its method declaration line, the compiler gives myProgram() method an error message asking the application method how it would like to handle the Exception. public class AnApplication { public void myProgram() { bean.openFile(filename); …… } } public class AJavaBean { public void openFile(String filename) throws FileNotFoundException { file.open(filename); //open() may throw FileNotFoundException …. } } If the programmer choose the first method then they can see below that all the code to process, open, and read are put into a try block. Once a method is called that might throw and Exception, the call has to be from within a try block because there is a chance of failure. If an Exception has been thrown by a method that is called in the try block shown below, the execution jumps out of the try block and into one of the catch blocks. The code that is left below that point in the try block is skipped as you can tell from the structure below. Execution will continue out the bottom of the catch block which branches to the bottom of the catch group if the catch block doesn’t stop the method processing by doing a return. Try/Catch example in Java: public void myProgram() { try { bean.openFile(fileName); // throws FileNotFoundException help.readFileContents(); // throws ReadException do.processFileData(); // throws ProcessException } catch(FileNotFoundException ex) { System.out.println(ex); // calls toString() on ex } catch(ReadException ex) { System.out.println(ex); // calls toString() on ex } catch(ProcessException ex) { System.out.println(ex); // calls toString() on ex } } } What happen if it was really vital that we close the file we open at the top of the try block? If you close it at the bottom of the try block, an exception is thrown and the execution will never get to the bottom of the try block. To guarantee the file gets closed, you would have to repeat the close() action in every one of the catch blocks which becomes repetitive coding. So you could remove all the close() and include a finally block at the bottom like shown below. After the try block has been entered, the finally code will be executed. The finally code will also be executed also if a catch block is entered, even if the catch does a return. public void myProgram() { try { bean.openFile(fileName); // throws FileNotFoundException help.readFileContents(); // throws ReadException do.processFileData(); // throws ProcessException } catch(FileNotFoundException ex) { System.out.println(ex); // calls toString() on ex } catch(ReadException ex) { System.out.println(ea); // calls toString() on ex } catch(ProcessException ex) { System.out.println(ex); // calls toString() on ex } finally { bean.close(filename); } } All the catch blocks print the Exception object’s toString() on the console as an error message. If you are not going to differentiate processing for different kinds of Exceptions, then you could use a “catch-all” block. Since all exception objects are type Exception then they will be directed into this catch block as shown below. Any unanticipated types of exception will be caught also. public void myProgram() { try { bean.openFile(fileName); // throws FileNotFoundException helper.readFileContents(); // throws ReadException do.processFileData(); // throws ProcessException } catch(Exception ex) { System.out.println(ex); // calls toString() on ex } finally { bean.close(filename); } }
June 4, 2010
by Joseph Randolph
· 24,832 Views
article thumbnail
FlexMonkey 4 and FlexMonkium for Selenium
FlexMonkey is a free and open source Adobe AIR application used for testing Flex and AIR based applications. It can record, playback, and verify Flex UI interactions. FlexMonkey also generates ActionScript-based testing scripts that you can easily include within a continuous integration environment. Gorilla Logic is the company that builds FlexMonkey, and its CEO, Stuart Stern, recently spoke with DZone about their launch of FlexMonkey 4, which supports all of the new Spark components in Flex 4. For more info on FlexMonkey, see our interview with Stuart Stern at Adobe Max 2009. DZone: First thing's first. What's new in FlexMonkey 4? Stuart Stern: Before we talk about the updates to FlexMonkey, let me give you a bit of background for those who have not used any of the previous versions. We (Gorilla Logic) built and open sourced the first version of FlexMonkey in late 2008 because we needed a serious Flex testing solution for our enterprise customers. Basically, FlexMonkey allows developers and QA people to create comprehensive tests for their Flex applications by easily recording real interactions with the user interface, and by letting the test creator add verification checks on both data and visual snapshots of the UI. Once the interactions have been recorded the test can be played back through the FlexMonkey console or through generated test code in Fluint / FlexUnit. The generated code can be extended to create complex, data-driven test scenarios, and can be easily run within build and continuous integration environments. In our software consulting engagements, we have found that FlexMonkey reduces the overall numbers of tests that developers need to create, since driving testing from the user interface can exercise the entire application stack, top-to-bottom and even front-to-back. Let’s be clear though, api-level testing and tools like FlexUnit are still an essential part of Flex development, especially in testing non ui components. Where FlexMonkey is a better fit for testing is around visual components, which are difficult, if not impossible, to test as a ‘unit.’ On our typical applications, we tend to end up with about 80% of our developer created tests constructed through FlexMonkey, with the other 20% being created as more traditional unit tests. As far as FlexMonkey 4, the goals were pretty simple; the community has been beating down our door for Spark Component (Flex 4) support. So, we’ve added full support for the new component library recently released by Adobe. This is key for enterprise Flex development projects that have come to depend on FlexMonkey for regression and QA testing, and that are ready to move to Flex 4. We've also simplified the setup for FlexMonkey 4, so it's easier for new users to get up and running quickly. DZone: What were some of the difficulties in implementing support for all of Flex 4's Spark components? Stuart: From a FlexMonkey perspective, there is no difference between Spark and Halo components. However, one of the things that makes FlexMonkey so powerful is that it records "semantic" events such as "open combobox" rather than "click at this screen coordinate". So FlexMonkey needs to "understand" every Flex component, and we had to tell it some new things about the new Spark components and their events. . DZone: Are there any trends your seeing in how developers are using FlexMonkey in their UI design workflow? Stuart: FlexMonkey was initially envisioned as a tool for developers. Because developers test code that is still under development, it is important for a test automation tool to be able to express tests in a largely logical fashion. Tests that are too tied to the precise look of a screen at a particular point in time are two brittle for use by developers. FlexMonkey tests are typically robust across application skinning, since tests can be written independent of the exact positions or styling of the components on the screen, and can pinpoint specific functionality. In this way developers can automate testing of portions of an application even before the UI design is fully finalized. Although we designed it for developer testing, it's ability to record tests automatically, add verification logic by pointing and clicking, and do fuzzy bitmap comparisons on select portions of the screen, make FlexMonkey highly effective for QA testing purposes as well. Additionally, when developers and testers use the same tools, they can share some of the same tests, with QA using developer tests as a starting point, and developers incorporating some QA tests into continuous integration builds. DZone: Tell me about the next tool you'll be focusing on: FlexMonkium. Stuart: FlexMonkium is a plugin for Selenium IDE and Selenium RC. It adds FlexMonkey recording and playback capability to Selenium so you can create tests for applications that mix HTML and Flex. We recently completed development and are now doing final testing and documentation. We expect it make it publicly available any day now. FlexMonkium makes all of FlexMonkey's functionality available within the Selenium IDE, and generates JUnit-based tests that can be run with Selenium RC. DZone: Are there any interesting or exciting things you see down the road for the Flash platform ecosystem? How do you think the platform will fare against emerging UI design technologies like HTML5, CSS3, etc.? Stuart: The recent attacks on the Flash platform by Apple have certainly put the ‘HTML 5 vs. Flash’ battle on everyone’s radar. At Gorilla, we build both native browser applications (HTML 5, etc.) and Flex applications -- and even native iPhone applications -- for our customers. There are pros and cons to each and situations that definitively call for one versus another. Having said that, we are a consulting company that builds serious enterprise software. We embrace Flex because it enables us to do things we cannot do otherwise, and do them quickly. On any given project, we don't ask if we should use Flex, we ask if there is any reason why we can't.
June 4, 2010
by Mitch Pronschinske
· 14,821 Views
article thumbnail
System.ServiceModel.Syndication or how to read RSS feeds in .NET
Today, a lot of websites have their content provided in feeds that users can subscribe to. Feeds basically are a simplified version of the site content, providing text and media –only representation of the data published on the website. One of the most popular feed formats is RSS and it stands for Really Simple Syndication. It is XML-based and is used by the majority of websites that contain dynamically updated content, like blogs or news resources. Being XML based and having a well-defined structure, it is correct to think that it can be read as a regular XML document and this is absolutely true. However, there is System.Servicemodel.Syndication that can make the feed reading process a bit easier. So let’s look at a specific example. There is the DZone Link Feed, located here: http://feeds.dzone.com/dzone/frontpage?format=xml It’s an easy way to keep up with the upcoming interesting content, so I’d like to integrate this into my application. If I take a look at the source for the feed, I can see content similar to this: http://feeds.dzone.com/~r/dzone/frontpage/~3/wrVQN_7G8Hk/google_web_toolkit_blog_google_maps_api_for_gwt_1.html We are pleased to announce the Google Maps API for the Google Web Toolkit 1.1.0 release. The Google Maps API library provides a way to access the Google Maps API from a GWT project without having to write additional JavaScript code. frameworks java javascript web services Thu, 03 Jun 2010 18:54:42 GMT http://www.dzone.com/links/423703.html @thierry_lefort 2010-06-03T18:54:42Z We are pleased to announce the Google Maps API for the Google Web Toolkit 1.1.0 release. The Google Maps API library provides a way to access the Google Maps API from a GWT project without having to write additional JavaScript code.]]> 423703 2010-06-02T10:12:27Z 2010-06-03T18:54:42Z 6 0 90 0 http://www.dzone.com/links/images/thumbs/120x90/423703.jpg Thierry.Lefort http://www.dzone.com/links/images/avatars/252611.gif http://www.dzone.com/links/rss/google_web_toolkit_blog_google_maps_api_for_gwt_1.html As you can see here, an item is basically a feed entry that contains information about one content entity. Note that there are some site-specific tags that I am not covering here, but that are still readable via XmlDocument. An important note that has to be made here is that .NET (not using any third-party components) only supports RSS 2.0 feeds (I am not including Atom here). To get started, add a reference to System.ServiceModel and System.ServiceModel.Syndication. Now, in the class header, add the statement below: using System.ServiceModel.Syndication; Now you’re all set. Let’s try and read the feed above. To do this, I will need an instance of SyndicationFeed and XmlReader. Here is how the code looks like: SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create("http://feeds.dzone.com/dzone/frontpage")); This will read the actual feed. And since I mentioned that the feed is composed out of multiple items, all of them are stored in the Items collection. You can go through it via this: foreach (SyndicationItem item in feed.Items) { Debug.Print(item.Title.Text); } The code above will get the titles of each item included in the feed. A question that might arise is why do I have to call the Text property when Title should already be of type string. This is a wrong assumption, since Title in fact is of type TextSyndicationContent, therefore this means that it can contain HTML, XHTML or plain text. Therefore, converting it directly ToString() will not give correct results. For each of the items I can get the summary – a short representation of the published content: foreach (SyndicationItem item in feed.Items) { Debug.Print(item.Summary.Text); } Please remember that item.Summary is not the same as item.Content. As you see in the feed sample I provided, the content is surrounded by CDATA, meaning that it can provide HTML data to the receiving end. If I am going to call item.Content I will get an “Object reference not set to an instance of an object.” due to the fact that it is content:encoded instead of content. To read the content in this case, I am going to use this: foreach (SyndicationItem item in feed.Items) { foreach (SyndicationElementExtension ext in item.ElementExtensions) { if (ext.GetObject().Name.LocalName == "encoded") Debug.Print(ext.GetObject().Value); } } This will prevent the above mentioned exception and will read the string representation of the item content.
June 3, 2010
by Denzel D.
· 20,720 Views
article thumbnail
Iterator Pattern Tutorial with Java Examples
Learn the Iterator Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
June 3, 2010
by James Sugrue
· 62,267 Views · 1 Like
article thumbnail
StringTemplate Part 2: Collections and Template Groups
This Article deals with StringTemplate. If you've never heard of StringTemplate or a “template engine” you might want to read either Part 1 or the official StringTemplate documentation. Template Group Files: In the first article we used a template file (.st file) to hold our template definition. In those examples we had defined a single template that spanned the entire file. When things get more complicated it's convenient to be able to define multiple smaller templates in one file. StringTemplate calls this file a “String Template Group” and recommends a filename ending in “.stg”. Example String Template Group: This template group defines one template that takes two parameters, input1 and input2. Parameters passed to the template can then be used in the content area. Example template with content: exampleTemplate(input1, input2) ::= << input1 = $input1$ input2 = $input2$ >> StringTemplateGroups are a convenient way to group small interrelated templates. These smaller templates can be nested as shown below. group group-demo; outerTemplate(input) ::= << In the outer template. input = $input$ <-- I can see the value of the 'input' parameter and use it. $innerTemplate(input)$ >> innerTemplate(nestedInput) ::= << The Paramater 'nestedInput' was passed to this template. nestedInput = $nestedInput$ <-- I can see the value of the 'nestedInput' parameter and use it. >> Here is the code to use this StringTemplateGroup: StringTemplateGroup group = new StringTemplateGroup( new FileReader("templates/group-example.stg"), DefaultTemplateLexer.class); StringTemplate template = group.getInstanceOf("outerTemplate"); template.setAttribute("input", "Hello World"); System.out.println(template.toString()); The output form this example will look much like this: In the outer template. input = Hello World; <-- I can see the value of the 'input' parameter and use it. The Paramater 'nestedInput' was passed to this template. I can use it here also. nestedInput = Hello World <-- I can see the value of the 'nestedInput' parameter and use it. Collections (Multi-Valued Attributes): In the first article I showed some basic template tasks. Each example mapped a placeholder to a single piece of data. Very often complicated structures require dealing with collections of data that do not match one to one to placeholders in a template. In Java if we had to process the items in a list we might use a loop. List xmen = Arrays.asList("Jean Gray", "Cyclops", "Angel", "Iceman", "Beast"); System.out.println("Original X-Men"); for(String xman : xmen){ System.out.println(xman); } Output: Original X-Men Jean Gray Cyclops Angel Iceman Beast A valiant first attempt at using StringTemplate might result in code that looks like this: StringTemplate template = new StringTemplate( "Example 3\nOriginal X-MEN: $xmen$ "); template.setAttribute("xmen", xmen); System.out.println(template.toString()); As you can see we took the list of strings and just pushed it into the template. Unfortunately this won't give us the same output as above. Output: Example 3 Original X-MEN: Jean GrayCyclopsAngelIcemanBeast Whats happening here is that we gave a “multi-valued attribute” (collection) to StringTemplate but did not tell it how to handle that data. One way to accomplish this is to use a separator. Example 4: Original X-MEN members: $xmen; separator="\n"$ Output: Example 4: Original X-MEN members: Jean Gray Cyclops Angel Iceman Beast As you can see we specified a separator of “\n” which means newline. There is no restriction on the size of a separator. The following: $xmen; separator=" \"\$hi, this is a really long separator\$\"\n\n"$ would yield the following output. Original X-MEN members: Jean Gray "$hi, this is a really long separator$" Cyclops "$hi, this is a really long separator$" Angel "$hi, this is a really long separator$" Iceman "$hi, this is a really long separator$" Beast I have embedded both quotes and dollar signs to emphasize that you really can use anything in a separator. (If you really want to but I don't recommend it.) Applying Templates to multi-valued attributes: Separators have their place but I find that applying a template to a multi-valued attribute significantly more flexible and powerful. I also feel it's one of the key differentiators between StringTemplate and other template engines. First lets look at some good (bad?) old fashioned Java string building. // Manual formatting and spacing StringBuilder builder = new StringBuilder(); builder.append("Example 2 \n"); builder.append("\n"); builder.append("Original X-Men\n"); builder.append(" \n"); for(String xman : xmen){ builder.append(" "+ xman + "\n"); } builder.append(" \n"); builder.append("\n"); Here is some standard java code for building up a block of HTML. Note there are two different levels of formatting here. One is the HTML, which has requirements like the opening and closing of tags. The other is the actual formatting of the output text itself. This is done to keep the generated block readable after it's generated. Whenever text is appended both formatting concerns need to be taken into account. Unlike many of the examples from Part 1 this has some flow control going on. Specifically, we have a loop. When we translate this logic to a template, or more specifically two templates, we can eliminate the details of the loop. group list-demo; htmListExample(xmen) ::= << Example 5: Original X-Men $xmen:listItem()$ >> listItem() ::= << $it$ >> Here we have the contents of our template file “list-template-group.stg”. We have defined two templates “htmlListExample” and “listItem”. From our previous examples we know that xmen is a multi-valued attribute. The : syntax is used to apply the listItem template to every item in the list. This generates the following output: Output: Example 5: Original X-Men Jean GrayCyclopsAngelIcemanBeast As you can see there is no loop, no loop counter and we didn't even define a variable in our second template. StringTemplate makes the $it$ variable available if you have not explicitly named one. Now to be honest this output is not the exact same output as the above block of Java code. There is an extra new line at the beginning of the list items. Most of the time I find this to be “good enough” for the “readability” formatting, but there is a way to fix it. StringTemplate provides functions for slicing a list up into manageable parts. Here we are going to use first() and rest(). /** * HTML example for applying a template to a list using first() and rest() */ firstRestExample(xmen) ::= << Example 6: Original X-Men $first(xmen):firstListItem()$$rest(xmen):listItem()$ >> firstListItem() ::= "$it$" The first() function returns only the first element of the multi-valued attribute. We then apply the firstListItem() template to only the first item. Everything except the first element (returned by rest()) has the listItem() template applied to it. This generates the exact same output as the block of old fashioned Java code. Example 6: Original X-Men Jean GrayCyclopsAngelIcemanBeast In this example the use of first and rest was used to solve a trivial whitespace issue. In more complicated templates the functions first(), rest(), etc. may solve more important problems. Finally you are not restricted to applying just one template to an item in a list. /** * HTML example for applying multiple templates to a list. */ applyMultipleExample(xmen) ::= << Example 7: Original X-Men $xmen:bold():listItem()$ >> /** * wraps the text in a with a style of bold */ bold() ::= << $it$ >> For each value of the multi-valued attribute the templates are applied from left to right. In this case bold is applied first then list item. Output: Example 7: Original X-Men Jean GrayCyclopsAngelIcemanBeast In this article we have explored string template group files, defining multiple templates withing a single file and applying templates to multi-values attributes (collections). If you want to learn more I recommend the official StringTemplate documentation. It has more detailed explanations and examples. Source Code: StringTemplateDemos2.zip From http://weblogs.java.net/blog/aberrant/archive/2010/06/02/stringtemplate-part-2-collections-and-template-groups
June 3, 2010
by Collin Fagan
· 13,169 Views
article thumbnail
JavaScript: Creating timestamps with time zone offsets
I was converting the example code of my Windows Azure session to Visual Studio 2010 solution called MVC Time Planner when I discovered some date and time offset issues in my JavaScript code. In this posting I will show you some useful tricks you can use to convert JavaScript dates and times to timestamps. Date.getTime() returns UTC When you call getTime method on Date object you get the number of milliseconds from Unix epoch. Although your current Date object keeps time with some offset getTime gives seconds in UTC. Keep this in mind when creating timestamps if you are not living on zero-meridian. var currentDate = selectedDate; // current date with offset var currentTime = currentDate.getTime(); // offset is ignored This is pretty awkward, unexpected and unintuitive behavior but you have to keep in mind that all date and time calculations must use same time system to give appropriate results. Date.getTimezoneOffset() getTimezoneOffset method returns you the amount of minutes you have to add to your current timestamp to convert it to UTC time. If your time zone is UTC+3 then getTimezoneOffset returns you –180 because: UTC + 3 hours + (-180) minutes = UTC If your time zone is UTC-3 then UTC - 3 hours + 180 minutes = UTC Pretty simple math but confusing at first place. Getting timestamp with time zone In my application I have to give timestamp for selected dates and times to server. I need to find correct amount of seconds from Unix epoch so users can save times based on their region and not by UTC. Here is how calculate timestamps. var currentDate = selectedDate; var currentTime = currentDate.getTime(); var localOffset = (-1) * selectedDate.getTimezoneOffset() * 60000; var stamp = Math.round(new Date(currentTime + localOffset).getTime() / 1000); On server side I use the following method to convert timestamp to date. This method is borrowed from CodeClimber blog posting Convert a Unix timestamp to a .NET DateTime. private static DateTime ConvertFromUnixTimestamp(double timestamp) { var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); return origin.AddSeconds(timestamp); } Conclusion Playing with dates and times is always interesting thing to do because there are many different time zones in the world and supporting them all is not easy thing to do. Inside the system we must be able to keep all dates in appropriate system and usually it is UTC. This posting showed you some tricks about how to play with local times in JavaScript.
June 1, 2010
by Gunnar Peipman
· 54,159 Views · 1 Like
article thumbnail
Bridge Pattern Tutorial with Java Examples
Learn the Bridge Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered
June 1, 2010
by James Sugrue
· 108,553 Views · 3 Likes
  • Previous
  • ...
  • 1600
  • 1601
  • 1602
  • 1603
  • 1604
  • 1605
  • 1606
  • 1607
  • 1608
  • 1609
  • ...
  • 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
×