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

article thumbnail
IntelliJ Keymap for NetBeans IDE
Have been using IntelliJ for about 5 years now. It is still the Roll Royce of all IDEs, and of that there is no doubt. But having said that, you should once in a while jump the ship, and try out something different and it is with this intention that I am currently trying out NetBeans IDE 6.1. I was a NetBeans IDE user starting from its “Forte for Java” days to about 2003, and did also develop some plugins on it. So it feels great to be back home. Well not quite. Though NetBeans IDE has now added almost every trick in the bag, it is still challenging even for a veteran, to pick up from where they left off. To ease this pain of transition, here is the link to an IntelliJ Key Map, which when applied to NetBeans IDE, will make it feel more like IntelliJ to you. If you find yourself pressing CTRL+ALT+L, CTRL+ALT+O and CTRL+F12, this keymap will be a real time saver. From: IntelliJ Keymap for NetBeans
July 14, 2008
by Swapnonil Mukherjee
· 10,857 Views
article thumbnail
First Release of Nuxeo WebEngine
WebEngine relies on the Nuxeo content infrastructure (OSGi runtime, component architecture, document repository, ECM services, etc.) to provide a component-based programing model and a web development model for building componentized content-centric applications (such as wikis, blogs, content-oriented websites, etc.). Summary: WebEngine is a lightweight, versatile, content-centric, open source web framework to quickly build and deliver next generation content-oriented web applications. WebEngine relies heavily on the REST paradigm: URLs are mapped to the hierarchical content repository, content is accessed using GETs, user actions are GETs and POSTs, etc. Hence it’s very easy and straightforward to write RESTful apps using WebEngine. WebEngine is fully extensible and componentized, thanks to OSGi (all components are OSGi bundles) and Nuxeo Runtime’s extension points. WebEngine can run either standalone (with startup time <4s) using the Nuxeo Runtime launcher and the embedded Jetty 6, or in a full-blown Java EE app server such as JBoss. WebEngine can also be connected to any Nuxeo EP instance (and Nuxeo Core repository) and be used to expose / publish its content to the web. (click to run the slideshow) Features highlights: Scripting (Groovy, JavaScript, Ruby, Python…) or Java code for business logic Advanced content model Leverage Nuxeo Platform’s ECM services Smart URLs management Powerful templating (based on the FreeMarker engine) Wikitext renderer (using Wikimodel) Open source under the LGPL license Join the community! Download it and give it a try Check out the presentation on SlideShare Read the reference documentation Join the discussion to get help and give feedback on the forums Learn how WebEngine fits in the overall Nuxeo roadmap and… Contribute]! :-)
July 11, 2008
by Stefane Fermigier
· 1,338 Views
article thumbnail
Create New Eclipse Workspace - With All Your Old Settings
It's all a matter of taste. Do you like to have just one workspace for all your projects, or do you prefer to have multiple separate workspaces? Sure, the first way seems to be the official, supported. It should be easy to manage the workspace -- given the tools like working sets (and working set filters), mylyn and the ability to close projects. But I still don't get it. I hate when my workspace is overflowing with projects, I want to have as many workspaces as projects. So I create new workspace and live happily ever after. But wait -- all my settings are gone. All my carefully crafted custom templates, all my keybindings, my font settings, everything is gone. It's all text, fortunately Lucky us. All eclipse settings are saved as a plain text in the workspace directory. So if you want to create new workspace, but preserve your settings, I have two answers for you: The short answer All settings are stored in the .metadata/.plugins/org.eclipse.core.runtime/.settings directory. I mean -- all relevant settings. If you look into .metadata/.plugins directory there are many more directories with settings, but they are too project specific. I've walked trough these configuration files one by one, believe me, nothing useful lies hidden there. So the short answer is: If you want to create a new eclipse workspace and preserve all your settings, simply copy the .metadata/.plugins/org.eclipse.core.runtime/.settings directory into your new workspace directory. Do not copy other directories! There are project specific settings and since your old projects are left in your old workspace, the copied settings would not be valid and you would get some nasty exceptions at eclipse startup. The long answer Let the code do the talk for me. I have created a (simple) shell script that automates new workspace creation. The downside is that it requires either a *nix shell or windows with cygwin. Nevertheless, you can always manually copy the .settings directory (see the short answer). The script has been tested by me, I and myself so it should work (most of the time). To use it, save it somewhere, make it executable (chmod +x new-workspace.sh) and run it either in interactive mode ./new-workspace.sh -i where it will ask you the details, or with paths to your workspaces (the new workspace directory will be created for you, just specify the path) ./new-workspace.sh old-workspace new-workspace The script will create new workspace directory and copy the relevant settings from your old workspace. If it doesn't work for you, drop me a comment. Feel free to improve it. Update: the pastebin page expired (although I'd swear I checked the keep forever option), so I moved the script over to github.
June 30, 2008
by Tomas Kramar
· 237,334 Views
article thumbnail
Python Development in NetBeans IDE
The nbPython project aims to provide support for Python development to NetBeans IDE. Below follow the step-by-step instructions for getting started! The bits are available (milestone releases) for download now as NetBeans modules (nbms). Let us get started: Download/lnstall the M3 NBMs from here. Fire up NetBeans IDE. Go to Tools -> Plugins -> Downloaded Tab. Click on "Add Plugins" and select all the NBM files in the unzipped directory. Now, you will see all the chosen modules along with their descriptions. You should see something like this: Press the "Install" button. Using NetBeans IDE 6.1, I get a dependency error: Then, I downloaded a latest build NetBeans IDE Build 200806220002 from here and repeated the above steps. This time there was no dependency problem. You will get a "Validation Warning". Press "Continue": The installation will continue and will be over without any further user interaction required. Creating a New Python Project Go to File-> New Project-> Python-> Python Project. Choose a Project Name- say "HelloNbPython". Click on Finish. A new project gets created and is visible in the Project Explorer window. No default file is created. Right Click on the project name, and select New-> Empty Python File. Enter a name, say- HelloWorld. A Python script will be generated for you which will simply print "Hello World". The project tree is now as follows: HelloNbPython/ pyproject/ project.properties src/ HelloWorld.py Runing a Python Script Right Click on HelloWorld.py in the project explorer and click "Run Python Script". First time I did this, I got the following exception message: java.io.IOException: Cannot run program "/home/amit/netbeans-dev-200806220002/nbpython/jython-2.5/bin/jython" (in directory "/home/amit/NetBeansProjects/HelloNbPython"): java.io.IOException: error=13, Permission denied So I checked the file permission of the 'jython' executable: $ ls -l jython -rw-r--r-- 1 amit amit 5101 2008-06-22 15:05 jython As you can see there is no executable permission for 'jython' as indicated by the absence of the 'x' flag So, I made the 'jython' executable by: chmod +x jython Run the script again and you should get "Hello World" in the output window.
June 22, 2008
by Amit Saha
· 33,155 Views
article thumbnail
Common REST Design Pattern
Based on the same architectural pattern of the web, "REST" has a growing dominance of the SOA (Service Oriented Architecture) implementation these days. In this article, we will discuss some basic design principles of REST. SOAP : The Remote Procedure Call Model Before the REST become a dominance, most of SOA architecture are built around WS* stack, which is fundamentally a RPC (Remote Procedure Call) model. Under this model, "Service" is structured as some "Procedure" exposed by the system. For example, WSDL is used to define the procedure call syntax (such as the procedure name, the parameter and their structure). SOAP is used to define how to encode the procedure call into an XML string. And there are other WS* standards define higher level protocols such as how to pass security credentials around, how to do transactional procedure call, how to discover the service location ... etc. Unfortunately, the WS* stack are getting so complicated that it takes a steep learning curve before it can be used. On the other hand, it is not achieving its original goal of inter-operability (probably deal to different interpretation of what the spec says). In the last 2 years, WS* technology development has been slowed down and the momentum has been shifted to another model; REST. REST: The Resource Oriented Model REST (REpresentation State Transfer) is introduced by Roy Fielding when he captured the basic architectural pattern that make the web so successful. Observing how the web pages are organized and how they are linked to each other, REST is modeled around a large number of "Resources" which "link" among each other. As a significant difference with WS*, REST raises the importance of "Resources" as well as its "Linkage", on the other hand, it push down the importance of "Procedures". Under the WS* model, "Service" in the SOA is organized as large number of "Resources". Each resource will have a URI that make it globally identifiable. A resource is represented by some format of "Representation" which is typically extracted by an idempotent HTTP GET. The representation may embed other URI which refers to other resources. This emulates an HTML link between web pages and provide a powerful way for the client to discover other services by traversing its links. It also make building SOA search engine possible. On the other hand, REST down play the "Procedure" aspect and define a small number of "action" based on existing HTTP Methods. As we discussed above, HTTP GET is used to get a representation of the resource. To modify a resource, REST use HTTP PUT with the new representation embedded inside the HTTP Body. To delete a resource, REST use HTTP DELETE. To get metadata of a resource, REST use HTTP HEAD. Notice that in all these cases, the HTTP Body doesn't carry any information about the "Procedure". This is quite different from WS* SOAP where the request is always made using HTTP POST. At the first glance, it seems REST is quite limiting in terms of the number of procedures that it can supported. It turns out this is not the case, REST allows any "Procedure" (which has a side effect) to use HTTP POST. Effectively, REST categorize the operations by its nature and associate well-defined semantics with these categories (ie: GET for read-only, PUT for update, DELETE for remove, all above are idempotent) while provide an extension mechanism for application-specific operations (ie: POST for application procedures which may be non-idempotent). URI Naming Convention Since resource is usually mapped to some state in the system, analyzing its lifecycle is an important step when designing how a resource is created and how an URI should be structured. Typically there are some eternal, singleton "Factory Resource" which create other resources. Factory resource typically represents the "type" of resources. Factory resource usually have a static, well-known URI, which is suffixed by a plural form of the resource type. Some examples are ... http://xyz.com/books http://xyz.com/users "Resource Instance", which are created by the "Factory Resource" usually represents an instance of that resource type. "Resource instances" typically have a limited life span. Their URI typically contains some unique identifier so that the corresponding instance of the resource can be located. Some examples are ... http://xyz.com/books/4545 http://xyz.com/users/123 "Dependent Resource" are typically created and owned by an existing resource during part of its life cycle. Therefore "dependent resource" has an implicit life-cycle dependency on its owning parent. When a parent resource is deleted, all the dependent resource it owns will be deleted automatically. Dependent resource use an URI which has prefix of its parent resource URI. Some examples are ... http://xyz.com/books/4545/tableofcontent http://xyz.com/users/123/shopping_cart Creating Resource To create a resource instance of a particular resource type, make an HTTP POST to the Factory Resource URI. If the creation is successful, the response will contain a URI of the resource that has been created. To create a book ... POST /books HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 Content-Length: nnn Ricky Ho HTTP/1.1 201 Created Content-Type: application/xml; charset=utf-8 Location: /books/4545 http://xyz.com/books/4545 To create a dependent resource, make an HTTP POST to its owning resource's URI To upload the content of a book (using HTTP POST) ... POST /books/4545 HTTP/1.1 Host: example.org Content-Type: application/pdf Content-Length: nnnn {pdf data} HTTP/1.1 201 Created Content-Type: application/pdf Location: /books/4545/content http://xyz.com/books/4545/tableofcontent HTTP POST is typically used to create a resource when its URI is unknown to the client before its creation. However, if the URI is known to the client, then an idempotent HTTP PUT should be used with the URI of the resource to be created. To upload the content of a book (using HTTP PUT) ... HTTP/1.1 201 Created Content-Type: application/pdf Location: /books/4545/content http://xyz.com/books/4545/tableofcontent HTTP/1.1 200 OK Finding Resources Make an HTTP GET to the factory resource URI, criteria pass in as parameters. (Note that it is up to the factory resource to interpret the query parameter). To search for books with a certain author ... GET /books?author=Ricky HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 HTTP/1.1 200 OK Content-Type: application/xml; charset=utf-8 Content-Length: nnn http://xyz.com/books/4545 Ricky http://xyz.com/books/4546 Ricky Another school of thoughts is to embed the criteria in the URI path, such as ... http://xyz.com/books/author/Ricky I personally prefers the query parameters mechanism because it doesn't imply any order of search criteria. Lookup a particular resource Make an HTTP GET to the resource object URI Lookup a particular book... GET /books/4545 HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 HTTP/1.1 200 OK Content-Type: application/xml; charset=utf-8 Content-Length: nnn Ricky Ho In case the resource have multiple representation format. The client should specify within the HTTP header "Accept" of its request what format she is expecting. Lookup a dependent resource Make an HTTP GET to the dependent resource object URI Download the table of content of a particular book... GET /books/4545/tableofcontent HTTP/1.1 Host: xyz.com Content-Type: application/pdf HTTP/1.1 200 OK Content-Type: application/pdf Content-Length: nnn {pdf data} Modify a resource Make an HTTP PUT to the resource object URI, pass in the new object representation in the HTTP body Change the book title ... PUT /books/4545 HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 Content-Length: nnn Ricky Ho HTTP/1.1 200 OK Delete a resource Make an HTTP DELETE to the resource object URI Delete a book ... DELETE /books/4545 HTTP/1.1 Host: xyz.com HTTP/1.1 200 OK Resource Reference In some cases, we do not want to create a new resource, but we want to add a "reference" to an existing resource. e.g. consider a book is added into a shopping cart, which is another resource. Add a book into the shopping cart ... POST /users/123/shopping_cart HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 Content-Length: nnn http://xyz.com/books/4545 HTTP/1.1 200 OK Show all items of the shopping cart ... GET /users/123/shopping_cart HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 HTTP/1.1 200 OK Content-Type: application/xml; charset=utf-8 Content-Length: nnn http://xyz.com/books/4545 ... Note that the shopping cart resource contains "resource reference" which acts as links to other resources (which is the books). Such linkages create a resource web so that client can discovery and navigate across different resources. Remove a book from the shopping cart ... POST /users/123/shopping_cart HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 Content-Length: nnn http://xyz.com/books/4545 HTTP/1.1 200 OK Note that we are using HTTP POST rather than HTTP DELETE to remove a resource reference. This is because we are remove a link but not the actual resource itself. In this case, the book still exist after it is taken out from the shopping cart. Checkout the shopping cart ... POST /orders HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 Content-Length: nnn http://xyz.com/users/123/shopping_cart HTTP/1.1 201 Created Content-Type: application/xml; charset=utf-8 Location: /orders/2008/04/10/1001 http://xyz.com/orders/2008/04/10/1001 Note that here the checkout is implemented by creating another resource "Order" which is used to keep track of the fulfillment of the purchase. Transaction Resource One of the common criticism of REST is because it is so tied in to HTTP (which doesn't support a client callback mechanism), doing asynchronous service or notification on REST is hard. So how do we implement long running transactions (which typically require asynchronicity and callback support) in REST ? The basic idea is to immediately create a "Transaction Resource" to return back to the client. While the actual processing happens asynchronously in the background, the client at any time, can poll the "Transaction Resource" for the latest processing status. Lets look at an example to request for printing a book, which may take a long time to complete Print a book POST /books/123 HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 Content-Length: nnn ?xml version="1.0" ?> http://xyz.com/printers/abc HTTP/1.1 200 OK Content-Type: application/xml; charset=utf-8 Location: /transactions/1234 http://xyz.com/transactions/1234 Note that a response is created immediately which contains the URI of a transaction resource, even before the print job is started. Client can poll the transaction resource to obtain the latest status of the print job. Check the status of the print Job ... GET /transactions/1234 HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 HTTP/1.1 200 OK Content-Type: application/xml; charset=utf-8 Content-Length: nnn PrintJob In Progress It is also possible to cancel the transaction if it is not already completed. Cancel the print job POST /transactions/1234 HTTP/1.1 Host: xyz.com Content-Type: application/xml; charset=utf-8 Content-Length: nnn HTTP/1.1 200 OK Conclusion The Resource Oriented Model that REST advocates provides a more natural fit for our service web. Therefore, I suggest that SOA implementation should take the REST model as a default approach.
June 4, 2008
by Ricky Ho
· 133,578 Views
article thumbnail
Converting a Java Project to a Dynamic Web Project in Eclipse
To convert a Java Project to a Web Project switch to or open the Resource Perspective of the project, in the root of the project. Open the .project file and make sure the builders and natures are present that are needed for a web project. See the example below, the name should be the name of your project, the most important nodes are the nature children in the natures node: testProjectorg.eclipse.jdt.core.javabuilderorg.eclipse.wst.common.project.facet.core.builderorg.eclipse.wst.validation.validationbuilderorg.eclipse.wst.common.project.facet.core.natureorg.eclipse.jdt.core.javanatureorg.eclipse.wst.common.modulecore.ModuleCoreNatureorg.eclipse.jem.workbench.JavaEMFNature Once you’ve updated the .project file you can close the file and right click and choose properties on the project. When the properties window opens click on Project Facets. The Facets grid is probably empty, click the Modify Project button. Check the Dynamic Web Module and Java Facets, choose the Java and Servlet version that applies to your project. Click Next and specify the existing or new location of your src and web content directories. Click Finish. As a final step I would recommend modifying the build path to compile your source directly into your /WEB-INF/classes directory by selecting Java Build Path and modifying the Default output directory. Now you should be able to create a local tomcat server, or if you’ve already created one you should be able to add the project to the server by right clicking the server and choosing Add and Remove Projects. Original article at http://greatwebguy.com/programming/eclipse/converting-a-java-project-to-a-dynamic-web-project-in-eclipse/.
May 6, 2008
by Jason Crow
· 114,710 Views
article thumbnail
5 Techniques for Creating Java Web Services From WSDL
WSDL is a version of XML used to better work with web severs. In this post, we'll learn how to better use it alongside the Java language.
April 29, 2008
by Milan Kuchtiak
· 604,473 Views
article thumbnail
Quick Start: Creating Language Tools In NetBeans IDE
NetBeans IDE is one of the main free Java editors in the market. In fact, it can be used to program in many other computer languages, like C/C++, Ajax, Javascript. NetBeans IDE can be extended by adding modules that add new features. So... you can have a programming editor customized to your needs. This tutorial can be of interest for all those who want to create a module that adds support for a new language inside NetBeans IDE. Original article: http://hiperia3d.blogspot.com/2008/04/netbeans-tutorial.html (the original article has coloring that makes reading easier. If you have some dificulty reading it here, you can go there). The process of creating the first of the modules that compose my X3DV Module Suite was similar to the one described here. We will learn how to make a module that has these features: Syntax highlighting that is specific for the language we will define. Brace completion and auto-indentation. Icons for the new files of that language. To be able to create new files written in our new language. Template for the new files written in that language. Just download the last version of NetBeans IDE (download NetBeans IDE 6.1 Beta). Then, follow all the steps described here. This tutorial is valid for the 6.1 version of NetBeans IDE, which has many improvements that make module building easier. This tutorial takes a fictional language called Foo Language as a sample. I suggest to follow the tutorial as it is, and later, adapt it to your needs. This is not a highly technical tutorial, but a quickstart guide that can be very easy for newcomers. First Steps With Your Module Create a new NetBeans project: Choose NetBeans Modules in Categories and Module in Projects: Fill in your project Name, locate the directory where its project folder will be placed, and mark it as a Standalone Module. Fill the info for your module. You just have to fill the two first text boxes: change the Code Name Base to what is appropriate for your module and choose a Display Name. The project will be created. Now we will add the basic: support files for the new file type. New File Type Support Over the project name, right click and select New/File Type: In the dialog that appears, you must enter some data so the NetbBeans IDE recognizes the new file type. In MIME Type you must enter text/x- usually followed by the main extension of the file type. Why does it say text/x-? As you may note, what you enter is not the true MIME type. For the IDE, all the extensions we create are text files. In Extension(s) you must enter them separated with spaces. In our example, there's only one extensions for Foo Files: .foo In Class Name Prefix, you enter the name of the file type, so all classes generated by the IDE for this module will start with it. In Icon, you must locate in your hard drive a gif icon of 16x16 pixels. In our example, it's this: Although in some tutorials they say that jpg and png images can also be used, I found that sometimes they're not displayed. So I recommend using gif images, as they are less error-prone. The IDE will copy your icon to the project directory. At this point, a bunch of files will be created by NetBeans IDE and opened in the code editor. Close them all, you don't need to edit them. Now our module is ready to recognize and create the new file types. But we want the new files to have a default content. So we will edit the generated template. Locate the file named: Edit it and write the content that you want to be the default when you create a new file. Locate the XML Layer in the module. The XML Layer file is the soul of our module. It controls most of the things that a module can do. Locate these lines: The next step is to create a description of the new supported file type that will be displayed when you want to create it, in the New File Wizard. This description will be stored in a file called "Description.html" (strange... uh?). Add this line after the one highlighted in blue, modifying it to your project url: This line we added describes where the Description of the new file is. Right click over your project and select New/Other. Select Other/HTML file. Name the file "Description", and leave the rest as it is. Replace all the contents of the generated file with this: Creates a foo file that is useful for nothing at all. This is what we will see as a result of these steps once the module is finished and we want to create a Foo file. Create the Language Support Now that we have the new files recognized, we will add syntax coloring and other features to our language module. To be able to support language features, we must do the following: right click over your project and choose "Properties". The properties of your module will be displayed. Click over libraries (on the left) and then the "Add..." button. In the list, search for the entry called "Generic Languages Framework", and add it. Now, right click over your project and select New/Other. In Categories, select "Module Development", and on the right, select "Language Support". Then enter the MIME Type and Extensions as we did in the first section of our tutorial. You will see that the XML Layer has changed and now has more things added. Between them, there's a new file that describes our language. That file is called "language.nbs". As the XML Layer has been modified, the icon of our files may have disappeared, so we need to add something to the XML Layer file to recover it. Close all the opened files. Locate the file called XML Layer, and open it. Locate the line highlighted in blue in this image, that says And replace that entire line with: Editing The Language File The default language.nbs file is filled with contents that may be a good start point for a scripting language. For declarative languages like VRML or X3D, or markup languages like HTML or similar, these contents are not useful. In our example of the Foo Language, we will use a very simple language definition. This way you will understand the basics of defining languages. So delete all the contents of the file language.nbs, and replace them with this: # To change this template, choose Tools | Templates # and open the template in the editor. # definition of tokens TOKEN:header:( "# foo language v1.0" ) TOKEN:line_comment: ( "#"[^ "\n" "\r"]* | "//"[^ "\n" "\r"]* ) TOKEN:keyword:( "foo_function" | "foo_command" ) TOKEN:field:( "foo_value" ) # all that follows is useful for mostly all languages TOKEN:identifier: ( ["a"-"z" "A"-"Z"] ["a"-"z" "A"-"Z" "0"-"9" "_"]* ) TOKEN:number: (["0"-"9"]*) TOKEN:operator: ( ":" | "*" | "?" | "+" | "-" | "[" | "]" | "<" | ">" | "^" | "|" | "{" | "}" | "(" | ")" | "," | "=" | ";" | "." | "$" ) TOKEN:string:( "\"" ( [^ "\"" "\\" "\r" "\n"] | ("\\" ["r" "n" "t" "\\" "\'" "\""]) | ("\\" "u" ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"]) )* "\"" ) TOKEN:string:( "\'" ( [^ "\'" "\\" "\r" "\n"] | ("\\" ["r" "n" "t" "\\" "\'" "\""]) | ("\\" "u" ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"]) )* "\'" ) TOKEN:whitespace:( [" " "\t" "\n" "\r"]+ ) # colors COLOR:header:{ foreground_color:"orange"; background_color:"black"; font_type:"bold"; } COLOR:line_comment:{ foreground_color:"#969696"; } COLOR:keyword:{ foreground_color:"red"; font_type:"bold"; } COLOR:field:{ foreground_color:"#25A613"; font_type:"bold"; } # parser should ignore whitespaces SKIP:whitespace # brace completion COMPLETE "{:}" COMPLETE "(:)" COMPLETE "\":\"" COMPLETE "\':\'" # brace matching BRACE "{:}" BRACE "(:)" # indentation support INDENT "{:}" INDENT "(:)" Now, create a Foo file, using a plain text editor, and save it with the extension .foo These will be its contents: # foo language v1.0 # comment // another comment foo_function { foo_command ( foo_value 1 0 1 ); } Now let's see the language.nbs file and understand the basic parts. TOKEN:header:( "# foo language v1.0" ) TOKEN:keyword:( "foo_function" | "foo_command" ) The Tokens are the words that are part of your language, and you want them colored. They define types of words that have something in common in your language. You group them into a category, that is a token. The words are between double quotes, and separated by a | sign. COLOR:header:{ foreground_color:"orange"; background_color:"black"; font_type:"bold"; } COLOR:line_comment:{ foreground_color:"#969696"; } This defines the colors used for each token. You can specify more properties for colors, but these are the basic ones. All these properties are very easy to understand by their own names, as you see. The colors can be specified by their names (although it recognizes only a few) or by its number. # brace completion COMPLETE "{:}" What these lines do is that when you type a { sign, the editor automatically will type } after your caret, speeding your work and making it less error-prone. # brace matching BRACE "{:}" # indentation support INDENT "{:}" This sentences make that when you place the caret over a brace, the matching brace will be highlighted, and that lines after those signs will be indented. Final Note Now you know all that is needed to create the basic support for a new file type and language syntax highlighting. You can add anything you like to your module, that you think is important for you and that could make your work easier. There's much more than can be done with NetBeans IDE. I invite just to test it, join its huge community of users, and experience it by yourself. -Jordi R. Cardona- X3D/VRML Worldbuilder Java Programmer X3DV Module Suite Developer. Hiperia3D News © 2008 by Jordi R. Cardona. The images and text of this post were added by the author to dzone. The author has granted dzone.com with exclusivity to use these images and text for the only purpose to spread this article. If you want to promote this tutorial, you can link to the original one at: http://hiperia3d.blogspot.com/2008/04/netbeans-tutorial.html
April 14, 2008
by Jordi R Cardona
· 39,976 Views
article thumbnail
Eclipse Adapters - A Hands-On, Hand-Holding Explanation
When programming Eclipse plug-ins, you quickly come face to face with Eclipse adapters. If you are not familiar with the adapter pattern, adapters can be confusing. Eclipse adapters are actually very simple, and I hope to make them even simpler with this article. Adapters work on a simple premise: Given some adaptable object A, get me the relevant object of type B for it. The Eclipse adapter interface is shown in Listing 1. The interface returns an object which is an instance of the given class associated with the object or it returns null if no such associated object can be found. package org.eclipse.core.runtime; public interface IAdaptable { public Object getAdapter(Class adapter); } Listing 1: The Eclipse Adapter Interface For instance, if I wanted to go from apples to oranges then I would do something like Listing 2. In this example, IApple extends the IAdaptable interface. IApple macintosh = new Macintosh(); IOrange orange = (IOrange) macintosh.getAdapter(IOrange.class); if (orange==null) log("No orange"); else log("Created a "+ orange.getClass().getCanonicalName()); Listing 2: Adapting from Apples to Oranges One of the primary uses of adapters is to separate model code from view code, as in a view-model-controller or view model-presenter pattern. We would not want to put presentation information like icons in our apple model. We would another class to handle how to present it. We could do this with adapters as shown in Listing 3. IApple apple = new Macintosh(); ILableProvider label = (ILabelProvider)apple.getAdapter(ILabelProvider.class); String text = label.getText(apple); Listing 3: Using Adapters to seperate model from view. Adapters allow us to transform objects into other purposes that the objects did not need to anticipate. For instance, the apple objects in the Listing 3 do not need to know anything about the label provider. We can implement the getAdapter() method manually for each apple object, but that would defeat the purpose. Instead, we should defer the adaptation to the platform as shown in Listing 4. public abstract class Fruit implements IAdaptable{ public Object getAdapter(Class adapter){ return Platform.getAdapterManager().getAdapter(this, adapter); } } Listing 4: Adapting through the platform Adapter Factories To enable the platform to manage the adaptations, you need to register one or more adapter factories with the platform. The registration can be a bit confusing, so I am going to be very specific. package com.jeffricker.fruit; import org.eclipse.core.runtime.IAdapterFactory; import com.jeffricker.fruit.apples.IApple; import com.jeffricker.fruit.apples.Macintosh; import com.jeffricker.fruit.oranges.IOrange; import com.jeffricker.fruit.oranges.Mandarin; /** * Converts apples to oranges * @author Ricker */ public class OrangeAdapterFactory implements IAdapterFactory { public Object getAdapter(Object adaptableObject, Class adapterType) { if (adapterType == IOrange.class) { if (adaptableObject instanceof Macintosh) { return new Mandarin(); } } return null; } public Class[] getAdapterList() { return new Class[]{ IOrange.class }; } } Listing 5: Apples to Oranges adapter factory Listing 5 shows an adapter factory that converts apples to oranges. The factory enables the behavior shown earlier in Listing 2. We will detail its behavior. The adaptableObject is the object that we are starting with, the apple. The adaptableObject is always an object instance. The adapterType is the object to which we are adapting, the orange. The adapterType is always a class type, not an object instance The adapterType is always a class type, not an object instance. The adapter list is the list of class types to which this factory can adapt objects. In this case, it is only oranges. We must register the adapter factory with the Eclipse platform in order for it to be useful. Listing 6 shows the registration entry from the plug-in manifest file. The extension point is org.eclipse.core.runtime.adapters. This is where I usually mess up, so pay attention. The adaptableType is what we are adapting from. In this case, it is apples. The adapter is what we are adapting to. In this case, it is oranges. Listing 6: Registering the adapter factory There can be multiple adapter entries for the factory. The adapters listed in the extension point should be the same as those provided by the getAdapterList() method in the adapter factory. If we look at the listings together and trace through the logic, the adapters start to make sense. We create an instance of the Macintosh object. IApple macintosh = new Macintosh(); We request the Macintosh to adapt to an IOrange IOrange orange = (IOrange) macintosh.getAdapter(IOrange.class); The Macintosh object forwards the request to the platform public Object getAdapter(Class adapter){ return Platform.getAdapterManager().getAdapter(this, adapter); } The platform finds the appropriate adapter factory through the registry. The platform calls the factory method, passing it an instance of the Macintosh object and the IOrange class type. The adapter factory is creates an instance of the Mandarin object public Object getAdapter(Object adaptableObject, Class adapterType) { if (adapterType == IOrange.class) { if (adaptableObject instanceof Macintosh) { return new Mandarin(); } } return null; } The confusion arises for me with the adaptableType parameter in the extension point. We do not have that specified in the adapter factory interface. It is buried within the logic of the factory’s getAdapter() method. Its presence in the registry makes sense when you think about it. We ask the platform to find an adapter for a Macintosh object. The factories must somehow be associated to the class hierarchy of Macintosh. In our case the factory is registered with IApples. Figure 1 shows the relation between declarations in the extension point registry and the adapter factory class. [img_assist|nid=2268|title=Figure 1: Relation between factory and extension point|desc=|link=none|align=undefined|width=545|height=437] Presentation provider example Adapting apples to oranges is a silly example of course, but I could extend the example to something more relevant. In Listing 3 I showed the adaptation of an apple object to a ILabelProvider, an interface used by JFace widgets for presentation. The factory for this effort is shown in Listing 7. The registration is shown in Listing 8 and sketch of the providers is shown in Listing 9. If you look at the provider classes generated by the Eclipse Modeling Framework (EMF), you will see the concept of this example taken its logical conclusion. package com.jeffricker.fruit.provider; import org.eclipse.core.runtime.IAdapterFactory; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ILabelProvider; import com.jeffricker.fruit.apples.IApple; import com.jeffricker.fruit.oranges.IOrange; public class FruitProviderAdapterFactory implements IAdapterFactory { private AppleProvider appleProvider; private OrangeProvider orangeProvider; /** The supported types that we can adapt to */ private static final Class[] TYPES = { FruitProvider.class, ILabelProvider.class, IContentProvider.class }; public Object getAdapter(Object adaptableObject, Class adapterType) { if ((adapterType == FruitProvider.class)|| (adapterType == ILabelProvider.class)|| (adapterType == IContentProvider.class)){ if (adaptableObject instanceof IApple) return getAppleProvider(); if (adaptableObject instanceof IOrange) return getOrangeProvider(); } return null; } public Class[] getAdapterList() { return TYPES; } protected AppleProvider getAppleProvider(){ if (appleProvider == null) appleProvider = new AppleProvider(); return appleProvider; } protected OrangeProvider getOrangeProvider(){ if (orangeProvider == null) orangeProvider = new OrangeProvider(); return orangeProvider; } } Listing 7: The fruit provider factory for displaying fruit in a JFace widget Listing 8: Registering the fruit provider adapter factory package com.jeffricker.fruit.provider; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ILabelProvider; public abstract class FruitProvider implements ILabelProvider, IContentProvider { ... } /** * Provides the display of IApple objects */ public class AppleProvider extends FruitProvider{ public String getText(Object element){ ... } public Image getIcon(Object element){ ... } } /** * Provides the display of IOrange objects */ public class OrangeProvider extends FruitProvider { ... } Listing 9: The provider classes Real world example The Eclipse Communication Framework (ECF) began as a means of putting instant messaging in the Eclipse platform, but it has since expanded in scope to enable multiple means of data sharing in the Eclipse Rich Client Platform (RCP). ECF begins with a simple interface called a container and uses the IAdaptable pattern of Eclipse to achieve specific functionality. If we were using ECF for instant messaging, then we would focus on adapting the container for presence and other interfaces. Listing 10 shows how to create an ECF container. The container provides a generic means for handling any type of session level protocol. Listing 11 shows how to adapt a container for managing presence, a common feature of instant messaging. The container-adapter pattern decouples the session level protocols from the services provided over those protocols. // make container instance IContainer container = ContainerFactory.getDefault() .createContainer("ecf.xmpp"); // make targetID ID newID = IDFactory.getDefault() .createID("ecf.xmpp","[email protected]"); // then connect to targetID with null authentication data container.connect(targetID,null); Listing 10 Creating an ECF connection IPresenceContainer presence = (IPresenceContainer)container .getAdapter(IPresenceContainer.class); if (presence != null) { // The container DOES expose IPresenceContainer capabilities } else { // The container does NOT expose IPresenceContainer capabilities } Listing 11 Adapting a container for functionality The possibilities are sweeping. For instance, we can create our own adapter called IMarketDataContainer that provides streaming market data. We would create it the same way as IPresenceContainer. As shown in Listing 12, different market data providers might have different session level protocols, even proprietary protocols, but the containeradapter pattern would allow us to plug all of them in to our Eclipse RCP the same way. IContainer container = ContainerFactory.getDefault() .createContainer("md.nyse"); ID newID = IDFactory.getDefault().createID("md.nyse","[email protected]"); container.connect(targetID,null); IMarketDataContainer marketData = (IMarketDataContainer)container .getAdapter(IMarketDataContainer.class); Listing 12 New container types for ECF The adaptor pattern is a powerful tool which you will find used throughout the Eclipse platform. I hope with the hands-on, hand holding explanation in this article that you can now unleash that power in your own RCP applications.
April 9, 2008
by Jeffrey Ricker
· 40,245 Views
article thumbnail
Tips and Tricks for Debugging in Eclipse
In this article I will describe some tips and tricks for debugging your applications in Eclipse.
April 4, 2008
by chander prakash
· 145,687 Views · 4 Likes
article thumbnail
Ant Build File Changes for Java Web Projects in NetBeans IDE 6.1
While working with a Java Web Application in NetBeans, I noticed some slight changes in the Ant build file for my project between NetBeans 6.0 and 6.1. This article explores some of the problems these changes caused to help out anyone with similar issues. I started with a Java Web Application that was created in NetBeans 6.0.1. After adding some JSP files and several Java source files, I committed everything in the project to my CVS repository. For some of my projects, I utilize the Hudson continuous integration build server. Using a standard deployment of Hudson, I configured the project to poll the SCM every 60 minutes, check out the code from CVS (if changes had been committed), and trigger the NetBeans project’s Ant build file (calling several specific targets like compile, dist, and so on. My builds have been functioning correctly for several weeks using this standard setup. I recently opened one of those projects in NetBeans 6.1 Beta and have been thoroughly enjoying the new features (faster startup, better JSP parsing in the Source Editor). After adding some JAR files as libraries and making several configuration changes, I committed the entire project (particularly the build-related files in the nbproject directory). Suddenly, my build for that project started failing. The console output reported by Hudson was : -init-check: BUILD FAILED D:/projects/hudson-server/data/jobs/MyWebProjectl/workspace/nbproject/build-impl.xml:149: The Java EE server classpath is not correctly set up. Your active server type is Tomcat55. Either open the project in the IDE and assign the server or setup the server classpath manually. For example like this: ant -Duser.properties.file= (where you put the property “j2ee.platform.classpath” in a .properties file) or ant -Dj2ee.platform.classpath= (where no properties file is used) Total time: 2 seconds finished: FAILURE I undid the configuration changes one by one, but the build failed regardless of what I reset. Apparently the property j2ee.platform.classpath is now required. I did a DIFF on the nbproject/build-impl.xml file and discovered several changes. The -init-check target includes property checks including this new one : The Java EE server classpath is not correctly set up. Your active server type is ${j2ee.server.type}.Either open the project in the IDE and assign the server or setup the server classpath manually.For example like this: ant -Duser.properties.file= (where you put the property “j2ee.platform.classpath” in a .properties file) or ant -Dj2ee.platform.classpath= (where no properties file is used) I hadn’t really taken notice of this property in the build file before, but it is referenced in a number of other targets such as: -init-macrodef-javac, -init-macrodef-junit, -init-macrodef-java, -init-macrodef-nbjpda, -init-macrodef-debug, compile-jsps, -do-compile-single-jsp, connect-debugger, javadoc-build, -do-compile-test, -do-compile-test-single Not being able to find a definition of the property anywhere in the build file, I looked through the project’s project.properties file among the list of defined properties. The property j2ee.platform.classpath was not defined. Thus, I’m assuming this is passed into the build file dynamically by NetBeans? In general I wouldn’t care, but when running the build file via Ant inside Hudson, the property j2ee.platform.classpath is never passed in. Hudson DOES allow you to pass properties and values to the build file, so I suppose I can specify the value manually, but I would like to keep the number of per project customizations to a minimum to maintain a low level of maintenance. Unless this causes some problem with the project properties in the build system, I would suggest the following fix for anyone who is experiencing a similar issue. Open your project’s project.properties file. Navigate to the section that contains these properties: j2ee.platform=1.4 j2ee.server.type=Tomcat55 Add a new line that specifies a blank j2ee.platform.classpath property such as this: j2ee.platform=1.4 j2ee.platform.classpath= j2ee.server.type=Tomcat55 Now, if the project.properties file is committed to CVS, a Hudson build can be triggered, and the FAIL check in the build-impl.xml file will pass. I ran some quick tests with the project, and everything with the project inside NetBeans still seems to work fine. I would propose to the NetBeans team to have the j2ee.platform.classpath property automatically added to the project.properties file.
March 26, 2008
by Adam Myatt
· 15,505 Views
article thumbnail
Java Bean Code Generation In Eclipse
Where would we be without JavaBeans? We use them in all our basic Java applications. We have Struts Form Beans, Hibernate and Spring POJO's and the list goes on. We are all used to writing setters and getters in for our Java Bean's manually. With thanks to Eclipse and other plugins, this effort is now very very easy. This tip is for the beginners (seniors, this is my first quick tip post) to generate setters and getters in a Java Bean class. First declare all the variables you need in the class. Next, right click any where on the source file. Select Source and then Generate Getters and Setters. This can be done alternatively by pressing Alt+Shift+S. Now select the variables for which you want to generate the getters and setters and you're done. As you can see there are multiple options in the window. Finally, the source code is.. Happy Coding! Until Next Time... RD
March 20, 2008
by Ratna Dinakar Tumuluri
· 56,934 Views
article thumbnail
DJ NativeSwing - reloaded: JWebBrowser, JFlashPlayer, JVLCPlayer, JHTMLEditor.
Today's release of DJ Native Swing 0.9.4 greatly improves stability and brings new components: in addition to the JWebBrowser and JFlashPlayer, there is now the JVLCPlayer and the JHTMLEditor. Here is a summary of what to expect when using this library. 1. Various native components DJ Native Swing was designed to handle all the complexity of native integration, mainly in the form of components with a simple Swing-like API. Here are some screenshots of several components in action (click to enlarge): JWebBrowser: JFlashPlayer: JVLCPlayer: JHTMLEditor: 2. Simple API First, we need to initialize the framework. This needs to happen before any feature is used. A common place for this call is the first line of the main(): public static void main(String[] args) { NativeInterfaceHandler.init(); // Here goes the rest of the initialization. } Now, let's see how to create a JWebBrowser, with its URL set to Google's homepage: JWebBrowser webBrowser = new JWebBrowser(); webBrowser.setURL("http://www.google.com"); myContentPane.add(webBrowser); Note that we set a URL, but we could as well set the HTML text. The JWebBrowser also allows to execute Javascript calls, and we can even propagate notifications from custom pages to our Swing application. Moving to a more practical example, we may want to be notified of URL change events or track window opening events, potentially preventing navigation to occur or open the page elsewhere. This is easily achieved by attaching a listener: webBrowser.addWebBrowserListener(new WebBrowserAdapter() { public void urlChanging(WebBrowserNavigationEvent e) { String newURL = e.getNewURL(); if(newURL.startsWith("http://www.microsoft.com/")) { // Prevent the navigation to happen. e.consume(); } else { // We can consume the event and decide to open this page in a tab. } } public void windowWillOpen(WebBrowserWindowWillOpenEvent e) { // We can prevent, add the URL to a tab, etc. } // There are of course more events that can be received. }); Let's have a look at the JFlashPlayer: JFlashPlayer flashPlayer = new JFlashPlayer(); flashPlayer.setURL(myFlashURL); The JFlashPlayer can open local or remote Flash files, and files from the classpath; the latter being a general capability of the library by proxying files using a minimalistic web server. Of course, the JFlashPlayer allows to retrieve and set Flash variables, and play/pause/stop the execution. The JVLCPlayer and the JHTMLEditor are no exceptions to this simplicity: playlist can be manipulated in the VLC player, HTML can be set and retrieved from the HTML editor, etc. There is also the possibility to integrate Ole controls on Windows, still with a simple Swing-like API. An example is provided in the library in the form of an embedded Windows Media Player. 3. Advanced capabilities The library takes care of most common integration issues. This covers modal dialog handling, Z-ordering, heavyweight/lightweight mix (to a certain extent), invisible native components with regards to focus handling and threading. Here are some more screenshots, showing a lightweight/heavyweight mix, and Z-ordering capability: The demo application that is part of the distribution shows all the features along with the source code, so check it out! 4. Project info and technical notes Webstart demo: http://djproject.sourceforge.net/ns/DJNativeSwingDemo.jnlp Screenshots: http://djproject.sourceforge.net/ns/screenshots Native Swing: http://djproject.sourceforge.net/ns The DJ Project: http://djproject.sourceforge.net The 0.9.4 version has a completely new architecture. It still uses SWT under the hood, but it does not use the SWT_AWT bridge anymore. The JWebBrowser and browser-based components require XULRunner to be installed, except on Windows when using Internet Explorer. The JVLCPlayer requires VLC to be installed. The JHTMLEditor uses the FCKeditor. 5. Conclusions This project finally brings all that is needed to make Java on the desktop a reality. A web browser, a flash player, a multimedia player, and even an HTML editor. So, what next? Yes, what next? For that one, I am waiting for your feedback. So, what do you think? What are your comments and suggestions? -Christopher
March 12, 2008
by Christopher Deckers
· 54,482 Views
article thumbnail
Effective Eclipse: Custom Templates
The same way I try to avoid the redundancy in my code, the same way I try to avoid the redundancy in my writing. I am lazy and templates do the most writing for me. Eclipse comes bundled with predefined templates, but they are too general and not all of them are too useful. The real power is in custom templates. In this article I would like to show you how to create them and list a few useful pieces for inspiration. What are templates Exactly as the name suggests, templates are little pieces of code with defined placeholders. An example of simple template is System.out.println(${text}); Each template has a name, which serves as a shortcut to the template itself. You type the name, press CTRL + SPACE and it will be expanded. Our first template would expand to [img_assist|nid=1424|title=|desc=|link=none|align=middle|width=186|height=19] I will not explain here what it all means, I already did this in my previous post on templates. What is important now, is that the ${text} placeholder (variable) was highlighted and can be edited immediately. The true power of templates can be fully seen in more complex templates. The first power point lies in the fact, that you can have more than one variable with same name. Our second template will have more variables: int ${increment} = ${value}; y = ${increment} + ${increment}; and will expand to [img_assist|nid=1428|title=|desc=|link=none|align=middle|width=204|height=45] When you start typing now, all occurrences of increment variable will be changed. You can then switch to the next variable by pressing TAB key. In the end, you can have [img_assist|nid=1425|title=|desc=|link=none|align=middle|width=110|height=43] in just three key presses - one for i, one for TAB and one for 2. To make it even better, the template system provides predefined variables, which will be expanded depending on their context. I will not list them, you can find them under the Insert variable button. [img_assist|nid=1426|title=|desc=|link=popup|align=middle|width=640|height=274] Notice, that you are not getting only a list, you are also getting a description and an usage example. To make it clear, I will illustrate one builtin variable - ${enclosing_type}. When this one is expanded you will get a name of the class (or interface, enum) in which your template was expanded. "But how can I use it?", I hear you asking. I have prepared few templates just for inspiration, I believe that after reading this you will find thousands others and I believe that you will create them and share them with us. Custom templates Open Window -> Preferences and type Templates into the search box. [img_assist|nid=1427|title=|desc=|link=popup|align=middle|width=640|height=578] You will get a list of all editors, and their respective template settings. This is because templates are closely bound to editors - you will get different builtin variables in different editors. Also note, that your list may vary from my list, it all depends on installed plugins. Now you must decide what type of template you would like to create. If it is a Java template, which will be applicable in context of classes, interfaces and enums, then choose Java -> Editor -> Templates. If you create a Java template you won't be able to use it in XML editor, that's quite expected. So click on the New button, to get a dialog. Here it is, in all its glory: [img_assist|nid=1430|title=|desc=|link=popup|align=middle|width=640|height=316] Name is the name of the template. Choose it well, because it will serve as a shortcut to your template. After you type the name of the template (or at least a few characters from its name) and hit CTRL+SPACE it will be expanded. Description is what you will see next to the template name when the template name is ambiguous. [img_assist|nid=1433|title=|desc=|link=none|align=middle|width=415|height=296] Pattern is the template body. And the Context? This varies in every editor. If you look in the combobox in Java templates, you will see Java and Javadoc. It is simple a context within the respective editor in which the template would be applicable. Check Automatically insert if you want the template to expand automatically on ctrl-space when there is no other matching template available. It is usually good idea to leave the checkbox checked, otherwise you would get a template proposal "popup". See what happens when I uncheck it on sysout template. [img_assist|nid=1432|title=|desc=|link=none|align=middle|width=256|height=46] If I would have checked it, it would automatically expand, as there is no other template matching sysout* pattern. My list So here is the list I promised. I have categorized it. Java (Java->Editor->Templates) logger - create new Logger private static final Logger logger = Logger.getLogger(${enclosing_type}.class.getName()); Notice the usage of ${enclosing_type} variable. This way you can create a logger in few hits. After the template expands, you will probably get red lines, indicating that Logger clas could not be found. Just hit CTRL + SHIFT + O to invoke the organize imports function. You are using shortcuts, aren't you? loglevel - log with specified level if(${logger:var(java.util.logging.Logger)}.isLoggable(Level.${LEVEL})) { ${logger:var(java.util.logging.Logger)}.${level}(${}); } ${cursor} Let me explain the details. ${logger:var(java.util.logging.Logger)} uses a builtin "var" variable. It starts with logger, the default name, in case the var variable finds no match. It is then followed by var(java.util.logging.Logger), what will evaluate to the name of the variable (member or local) of the specified type (in our case of the Logger type). Further, the ${cursor} variable marks the place where the cursor will jump after you press enter. So the result after expanding could be [img_assist|nid=1429|title=|desc=|link=none|align=middle|width=297|height=66] You might wonder what is the purpose of the if. It is there only for performance gain. If specified level is not allowed the logging method will never be called and we can spare JVM some string manipulation to build the message. readfile - read text from file Never can remember how to open that pesky file and read from it? Nor can I, so I have a template for it. BufferedReader in; try { in = new BufferedReader(new FileReader(${file_name})); String str; while ((str = in.readLine()) != null) { ${process} } } catch (IOException e) { ${handle} } finally { in.close(); } ${cursor} Maven (Web and XML -> XML Files -> Templates) dependency - maven dependency ${groupId} ${artifactId} ${version} ${cursor} parent - maven parent project definition ${artifactId} ${groupId} ${version} {$path}/pom.xml ${cursor} web.xml (Web and XML -> XML Files -> Templates) servlet - new servlet definition ${servlet_name} ${servlet_class} ${0} ${servlet_name} *.html ${cursor} JSP pages (Web and XML -> JSP Files -> Templates) spring-text - spring text field with label and error ${cursor} spring-checkbox ${cursor} spring-select ${cursor} spring-generic ${cursor} These are my favorites. They regularly save me a huge amount of time. Creating spring forms has never been easier for me. In some editor types you can set the template to 'new', for example, in XML editor it is new XML. This is really useful, as you can prepare the skeleton of a new file. For example, this is what I use to create new Spring servlet configuration for freemarker application. true messages Now, I can create new XML file from template and it will be ready to use. Before I knew about templates, I used to copy this from an older project, or search for it in Spring documentation. Now I don't have to.. [img_assist|nid=1431|title=|desc=|link=none|align=middle|width=640|height=201] If you can overcome the initial laziness and create your own templates from the pieces of code you really use, than this investment will shortly return in form of less typing. If you have some interesting templates, please, share them with us. You can download the templates mentioned in this post and import them using the Import button in the editor template settings.
February 28, 2008
by Tomas Kramar
· 232,580 Views · 1 Like
article thumbnail
Ruby: Escape, Unescape, Encode, Decode, HTML, XML, URI, URL
This example will show you how to escape and un-escape a value to be included in a URI and within HTML. require 'cgi' # escape name = "ruby?" value = "yes" url = "http://example.com/?" + CGI.escape(name) + '=' + CGI.escape(value) + "&var=T" # url: http://example.com/?ruby%3F=yes&var=T html = %(example) # html: example # unescape name_encoded = html.match(/http:([^"]+)/)[0] # name_encoded: http://example.com/?ruby%3F=yes&var=T href = CGI.unescapeHTML(name_encoded) # href: http://example.com/?ruby%3F=yes&var=T query = href.match(/\?(.*)$/)[1] # query: ruby%3F=yes&var=T pairs = query.split('&') # pairs: ["ruby%3F=yes", "var=T"] name, value = pairs[0].split('=').map{|v| CGI.unescape(v)} # name, value: ["ruby?", "yes"]
February 26, 2008
by Snippets Manager
· 4,009 Views
article thumbnail
Effective Eclipse: Don't write the code, generate it
I hope that we will never be able to generate applications. I would be without a job then and you probably too. But what we can generate are various repetitive and boring pieces of code. The first thing that can be generated is class file. You are using it, but you have probably never realized how much time does it save you. If there was no class skeleton generation, you would have to: create new file in the proper directory (with respect to package (and create the folders too)) and place the package statement at the beginning of a class. I will make a short stop here. I noticed that all people generate their classes, but not all of them specify implemented interfaces and extended class. Surely, you can generate the class and write the extends and implements part afterwards, but it involves moving the cursor, writing and eventually generating abstract or implemented methods. I found it much easier to press ALT + E (extend) to add extended class and ALT + A (add interface) to add interfaces in the new class wizard. My class will then come out with empty overridden methods and correct imports. If you look at the Source menu you can find more "Generate" commands. But none of them is so valuable and useful as Eclipse templates. They are the true gem in my daily work and it is pity they are hidden out of sight. And they are hidden well. What are they and how to get them? Templates serve as a shorthand for a snippet of code. You type in the magical word and it will be transformed into the snippet. Some examples: Type sysout and press CTRL + SPACE (the autocompletion) and it will be automagically changed to System.out.println(); with the caret waiting right in the middle between the parenthesizes. While we are here, let's explore the next interesting feature. Type "for" and press CTRL + SPACE to change it to a skeleton of a for loop. The for template is a showcase of templates' power. Notice the blue boxes around some of the commands. They represent the caret stop and you can move between them using the TAB key. Now, with the caret on "iterator", type the name of the variable representing the iterator. Its name will be changed in the whole loop as you type (the occurrences are marked with a light blue background). Now just two more TABs to change the collection variable and the type. Noticed the green line waiting in the empty line? It marks the position where the caret will jump when Enter key is pressed. So after changing the variable type you can just press Enter and the caret will jump to the empty line. When you use autocompletion the green marker is always somewhere around, waiting for you to press Enter. Every particular template is closely bound to editor. Each editor has its own defined set of templates, which are applicable only in that editor type. It is quite logical that the sysout template will not work in JSP editor. Furthermore, each template is applicable only within the specified context of the particular editor. There are two contexts in the Java editor for example, Java and Javadoc. To see list of all templates open Window -> Preferences and type templates into the search box. You will get a list of all editors and their respective template settings. Your list may vary from my list, because it depends on installed plugins. I encourage you to walk through the list to see what predefined templates are available. Not all of them are useful, but you need to see it, because what does not work for me might work for you. The true and real power of templates lies in custom templates, but I will leave this topic for the next week article. Apart from the fact, that it can expand templates, CTR + SPACE has few more interesting uses. It is an autocompletion shortcut and it can complete the names of variables or methods and in fact, it is its most obligate and the most famous usage. But it has some more surprises to offer. If you get used to it, you will be hitting it often, even in situations where there is obviously nothing to autocomplete. Or is it? Guess what is on the picture above? It is eclipse trying to autocomplete the name of a variable. It is pity it cannot read my mind. I often find myself hitting the shortcut in the middle of the string ever wondering why it doesn't complete the word. Never can remember the signature of a method you want to override? Never mind, hit CTRL + SPACE and you will get a list. It can assist you in private method creation, and it can guess what to complete even from the upper case letters. Warning: Using autocompletion and templates can lead to uncontrolled ctrl + space hitting, surprises and productivity boost.
February 22, 2008
by Tomas Kramar
· 102,770 Views
article thumbnail
Binding a JTable to Swing Controls in NetBeans IDE
Here is an outline of a scenario that binds Swing controls to columns in a JTable, via the tools that NetBeans IDE provides.
February 20, 2008
by Geertjan Wielenga
· 183,844 Views
article thumbnail
Effective Eclipse: Shortcut Keys
The less you touch the mouse, the more code you can write. Below you will find a set of essential keyboard shortcuts that I love for Eclipse.
February 15, 2008
by Tomas Kramar
· 1,509,886 Views · 29 Likes
article thumbnail
Effective Eclipse: Setup Your Environment
Today, I was taught an important lesson. The lesson of effectiveness. I was attending a presentation, called "Python Django: Advanced web application in 40 minutes". The guy was a geek, he was writing the code in a very basic vim installation. I bet, that if he used something better (no offense, it was really basic installation and he was apparently no vim master) he could crack it in half the time. It was an "oh, I made a typo here" presentation. It was then, when I realized that you really need a good editor if you want to be productive. Choose your tool Just do it. Find what suits you best and use it. I found Eclipse. Basic setup The first thing you should do, is to set up your font. If you are using Windows, you are lucky, as the font looks probably good and is well readable. If you are using Ubuntu like me, you might have less luck. When I first started eclipse, I was stunned. The font was big and crappy. But not for too long. Open: Window->Preferences->General->Appearance->Color and Fonts->Basic->Text Font and change the font size to 8. Much better now. The font used is called Monospace, some people recommend Bitstream Vera Sans Mono. This is how it looked before and how it looks now. Before: After: I recommend lowering the font size for your whole desktop. You will be surprised how much more can you see now. You can improve the font rendering too. Don't be greedy Eclipse is running with very small memory by default, but there is really no reason to be greedy. Just give your toy what it needs. Fire up the text editor, open eclipse.ini and enter: -vmargs -Xms512M -Xmx1024M -XX:PermSize=128M -XX:MaxPermSize=256M The -Xms option specifies the minimum and -Xmx the maximum heap size. The same holds for PermSize and MaxPermSize. Heap is that part of memory, where all your objects live. PermGen means "Permanent Generation" and it is a part of memory where all permanent objects are stored. By permanent, I mean those, which are not going to be garbage collected (for example Strings, classes etc.). Here you can find a better explanation of what PermGen is. If you are running a linux box, you might experience OutOfMemoryError-s if you do not adjust memory size. The values provided above are only for example, you should enter the values appropriate to your RAM size. You can further tune the performance by providing additional arguments. In his article, Jim Bethancourt recommends using Throughput garbage collector (-XX:+UseParallelGC), Robi Sen recommends using CMS Collector (-XX:+UseConcMarkSweepGC) as more effective. Help, I am giving the crap all my memory and it still keeps OutOfMemoryErroring! The reason is that you are simply not giving it enough memory. But don't worry, you don't have to buy another memory module (well, unless you have 128MB RAM). It is possible that you have made a typo in eclipse.ini, or maybe you used wrong eclipse.ini or maybe it simply doesn't work. I cannot tell you how to fix it, but I can tell how much memory are you giving it. Open Window->Preferences->General and check the "Show heap status" checkbox. You should now see the memory status in the bottom right corner. If you see values which correspond to the values you entered, everything should be fine. Set it up You should really take a time to walk through all the options under Window -> Preferences and customize your eclipse installation. I am going to list few ba General Always run in background: when eclipse is doing something time consuming, it will bother you with a modal popup window showing the progress of a task. I used to dismiss the popup with "Run in background" button. I am usually not interested in watching the lazy progressbar. If you enable this option eclipse will no longer bother you, and all tasks will run in background by default. There is nothing worse than breaking your workflow with messages: Hey I am building, can you see? Appearance: You can set various font related options here. If you are interested, you can change the position of tabs from top to bottom. Editors->File associations: if you have some exotic extension you can map it to the appropriate editor here. If you have xml file called myfile.exotic you can map .exotic extension to the xml editor. Editors->Text Editors -> Show line numbers: If you like, you can see line numbers. Very useful. Editors->Text Editors -> Spelling: Eclipse comes bundled with a spell checking turned on by default. This is a good idea and I really liked it, until I opened localized messages for my web application. Every word in my file was marked as misspelled, I was looking at an yellow sea of warnings, editor became quickly unresponsive as it wasn't able to handle hundreds of spelling errors. I had to turn this feature off, at least until some kind of ignore list is implemented or some good folk creates dictionary for my language. Java Java->Code style: Under Cleanup and Formatter are code formatting settings which are applied everytime the file is saved. If you tune it, it can save you much time. Java->Code style->Code templates: Here you can find and edit various templates. The only thing I do here is changing the "new Type" template to show my real name as author instead of my operating system username. Run/Debug Run/Debug->Launching: In previous Eclipse releases if you hit the run button, the last launched application was started. In Eclipse 3.3 this behavior changed a bit, and the selected resource gets launched. I found it annoying as I usually have only one runnable class. You can switch to the old style by choosing the right option under Launch Operation fieldset. I know I am repeating myself, but it is essential that you walk through the options and set it, such that it works with you, not against you.
February 8, 2008
by Tomas Kramar
· 49,594 Views
article thumbnail
FreeMarker in NetBeans IDE 6.0: First Scenario
NetBeans IDE 6.0 provides support for FreeMarker, on many levels, covering a variety of scenarios. To not confuse things, I'll deal with each scenario in a separate article. The first scenario is aimed at NetBeans plugin authors. Authors of plugins frequently need to provide file templates to the users of their plugins. In short, FreeMarker is the language you can use to define these file templates. Your users will not deal with these file templates, at least not necessarily. Instead, they will use a wizard that will generate a file. Under the hood, the wizard will pass the values typed by the user (in the wizard's panels) to a FreeMarker file template for processing. In this article, I will show how you create such a file template and how to hook it into a wizard. In short, you will create a NetBeans module that provides a wizard that passes values to a FreeMarker template to generate a document when the user clicks "Finish" in the wizard. Take the steps below: Install the FreeMarker plugin. Install the FreeMarker Template Sample into NetBeans IDE 6.0. When you do this, you will be providing a sample project that will install syntax coloring and code completion for FreeMarker. (The sample plugin will also install other things, but so as not to confuse things, we won't look at these other features in this article.) Get the sample and install it. After you install the above plugin, go to Samples | NetBeans Modules in the New Project wizard (Ctrl-Shift-N). There you will find "FreeMarker Support Sample". Complete the wizard by clicking Next and Finish. Right-click the project node and install it. Now, all files that end in "ftl" or "template" will have FreeMarker syntax coloring and code completion. We will see this in action in a future step below. Create the plugin's initial source structure. Create a new module project, choosing NetBeans Modules | Module in the New Project wizard, and then completing the wizard, giving the project any name and code name base you like. In this case, I am interested in creating a module containing file templates for the "ItsNat" web framework. Therefore, I've called the module "ItsNatFileTemplates" and the code name base "org.netbeans.modules.itsnatfiletemplates". Generate a wizard. Let's generate the wizard's structure. Right-click the project node and choose New | Other. In the New Project wizard, choose Module Development | Wizard. Click Next. Choose "New File" and type "1" in "Number of Wizard Panels". Click Next. Type something in the class name prefix, such as "ItsNatServlet". Set something appropriate in the Category, Icon, and Package fields. Click Finish. Here's my source structure at this point: We don't need to know much about the generated code. We'll deal with the files one by one, as we need them. First, we will work with the iterator class, above it is called "ItsNatServletWizardIterator". We are going to modify it in such a way that we will add an existing panel, from the NetBeans sources, to our sequence of panels. Currently, we only have one and it is blank (look at "ItsNatServletVisualPanel1" in Design mode). So, we are going to replace this panel with an existing panel. The existing panel provides the fields "Class Name", "Project", and "Package", which we therefore will not need to create ourselves. Before continuing, open the layer file and add one attribute below the other attributes (or anywhere in the list) that modify the file template, to specify that we will be making use of the FreeMarker template engine: Set dependencies. In the next steps, we'll be adding code to the wizard iterator. Before doing so, we need to set some dependencies on modules that provide the NetBeans APIs that we will need. Therefore, set dependencies on the following: 'Java Project Support', 'Project API', and 'Project UI API' (right-click the project in the Projects window, choose Properties, click Libraries, then set dependencies on the above three and click OK). Specify our wizard panel. The first lines of the "getPanels()" method in the "ItsNatServletWizardIterator" are as follows: private WizardDescriptor.Panel[] getPanels() { if (panels == null) { panels = new WizardDescriptor.Panel[]{ new ItsNatServletWizardPanel1() }; Replace the above lines with these: private WizardDescriptor.Panel packageChooserPanel; private WizardDescriptor.Panel[] getPanels() { Project project = Templates.getProject(wizard); Sources sources = (Sources)project.getLookup().lookup(Sources.class); SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA); packageChooserPanel = JavaTemplates.createPackageChooser(project,groups); if (panels == null) { panels = new WizardDescriptor.Panel[] { packageChooserPanel, }; The above is a bit of magic that replaces the wizard panel that we created with a panel that all Java source file wizards have in NetBeans IDE. Clean up. Fix imports (Ctrl-Shift-I), making sure to select "org.netbeans.spi.project.ui.templates.support.Templates" from the Fix All Imports box. You can now delete the two classes that form the panel. That is, just delete the wizard panel and the visual panel. You don't need them. Then, having a nice little module which includes just one Java class, just install it. Try the plugin. Now, remember the category you selected, back in step 4, when you created the wizard? If not, look in the layer.xml file, which should give you a clue. Now that you have installed your plugin, you should be able to find your new wizard in the New File wizard and invoke it from there. You should see something that looks like this: Create the FreeMarker file template. When you click Finish above, nothing happens. That's what this step is all about. Let's create our FreeMarker template. Right-click the package where your Java class is found, choose New | Other and then, in the New File wizard, choose Other | Empty File. (You'll see a FreeMarker category, installed by the plugin that we installed in step 1 above, but let's leave that for a future article.) Type "ItsNatServlet.ftl" (or something else, so long as the extension is ".ftl"). Then... specify your FreeMarker template, as shown in the screenshot below. And now you can see the syntax coloring and code completion provided by NetBeans IDE 6.0, via the plugin you installed at the start of this tutorial. (It is at this point that FreeMarker becomes relevant, so apologies for the time it took to get here, but this is the exact context where FreeMarker begins to be useful in this scenario.) Hook the FreeMarker file template into the plugin. Now that our FreeMarker template is done, let's hook it into our wizard so that, when Finish is clicked by the user, it is used to create the user's file. First, open the layer.xml file and add a "URL" attribute to the file name definition of the template, pointing to the location of our FreeMarker template, and changing the extension of the file name to specify that we wll create a file with the ".java" file extension: Back in the iterator, i.e., our Java class, look at the instantiate method: public Set instantiate() throws IOException { return Collections.EMPTY_SET; } First, set dependencies on "File System API", "Datasystems API", and "Nodes API". Then change the above method to the following: public Set instantiate() throws IOException { String className = Templates.getTargetName(wizard); FileObject pkg = Templates.getTargetFolder(wizard); DataFolder targetFolder = DataFolder.findFolder(pkg); TemplateWizard template = (TemplateWizard) wizard; DataObject doTemplate = template.getTemplate(); doTemplate.createFromTemplate(targetFolder, className); FileObject createdFile = doTemplate.getPrimaryFile(); return Collections.singleton(createdFile); } Now install the module again. This time, when you complete the wizard, you will have a new "ItsNat" servlet: If you don't have the "ItsNat" JAR files on the classpath, you'll also have... helpful red error marks in the editor. At this point, there are several open items to explore in the next part of this series—for example, we defined a set of variables in the FreeMarker template. They were magically replaced when we created the file via the wizard. How did that happen? Also, the FreeMarker template starts with lines of code that seem to relate to a project license. But... when the file was created, there was no project license. Why? These two questions and others will be handled in the next part of this series.
January 21, 2008
by Geertjan Wielenga
· 33,829 Views
  • Previous
  • ...
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 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
×