Wednesday, January 28, 2009

Iterating through a Collection in Java

There are three common ways to iterate through a Collection in Java using either while(), for() or for-each(). While each technique will produce more or less the same results, the for-each construct is the most elegant and easy to read and write. It doesn't require an Iterator and is thus more compact and probably more efficient. It is only available since Java 5 so you can't use it if you are restrained to Java 1.4 or earlier. Following, the three common methods for iterating through a Collection are presented, first using a while loop, then a for loop, and finally a for-each loop. The Collection in this example is a simple ArrayList of Strings.



While
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class WhileIteration {

public static void main(String[] args) {

Collection<String> collection = new ArrayList<String>();

collection.add("zero");
collection.add("one");
collection.add("two");

Iterator iterator = collection.iterator();

// while loop
while (iterator.hasNext()) {
System.out.println("value= " + iterator.next());
}
}
}




For
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class ForIteration {

public static void main(String[] args) {

Collection<String> collection = new ArrayList<String>();

collection.add("zero");
collection.add("one");
collection.add("two");

// for loop
for (Iterator<String> iterator = collection.iterator(); iterator.hasNext();) {
System.out.println("value= " + iterator.next());
}
}
}



For-Each
import java.util.ArrayList;
import java.util.Collection;

public class ForEachInteration {

public static void main(String[] args) {

Collection<String> collection = new ArrayList<String>();

collection.add("zero");
collection.add("one");
collection.add("two");

// for-each loop
for (String s : collection) {
System.out.println("value= " + s);
}
}
}


The result for each method should look like this:
value= zero
value= one
value= two


Friday, January 9, 2009

Ten German Birds

Moving to a new country opens up the opportunity to see and photograph many new things, in this case new birds in Germany. The following pictures were taken with a Canon 40D DSLR, with a Canon 70-200mm F4.0L IS lens and a Tamron 1.4X teleconverter. Click on the images for a higher-resolution view. You may also find interesting some photos I took of insects a while ago in Wisconsin.

Fasan


Hofente

Blaesshuhn

Teichhuhn

Amsel

Huehner

Rotkehlchen

Blaumeise

Huehner

Hahn


Greylag Goose - Graugans

Submit Photos to Shutterstock and make $$$!


Monday, January 5, 2009

Home made PBR - Photo Bio Reactor

Mmmmmmm, PBR. Either a cheap cold beer or a Photo Bio Reactor. Jared Bouck at AlgaeGeek has been experimenting with different designs and construction techniques for cultivating algae. The main reason you'd want to cultivate algae is to create a renewable fuel by taking carbon dioxide out of the atmosphere and turning it into a type of biodiesel. Millions of research dollars have been spent at Universities across the globe on discovering and genetically engineering the most ideal algae strains and building large scale biodiesel farms in warm areas. I've read somewhere that you can get around 10 times more fuel from algae than soybeans or corn given an equal cultivation area. I haven't really done too much research on cultivating algae at home and the advantage of algae, but it seems like it could be something worth pursuing. Anybody in Germany have an algae culture they want to share with me?





If you want to read more about that Algae Geek's projects check out his website. There are some funny passages there such as: "For this project we will be using some acrylic sheet that is 1/2 inch thick. This will be cut using a hole saw to make the plugs for the tube ends as well as making the holes for the plumbing. Now I realize that everything can be measured in carbon and energy required in making a product... and I realize that I will get email saying how plastics will kill the earth. Well... your likely right. So I wanted you to know preemptively that I actually got this magic carbon / pollution free acrylic from my future self coming back in time with a carbon free time machine to give it to myself so I could feel guilt free about using it. For those not fortunate enough to have a future self with a carbon free time machine and carbon free acrylic just go to your local plastics supplier. (Use your phone book, yes it’s in there)".

As a proof of concept experiment to test the feasibility of algae as a source of fuel for commercial consumption, the first 90-minute flight by a Continental Boeing 737-800 was just completed where one of the two engines was powered by a 50-50 blend of biofuel and normal aircraft fuel. No modifications of the engine were needed. The tests included an engine shutdown and restart at 38,000 feet. "Algae is viewed by many as a key fuel for the future because it is fast growing, does not compete with food crops for arable land, and yields up to 30 times more fuel than standard energy crops. But despite advances in the technology, biofuels derived from algae have yet to be proven as commercially competitive."

Tuesday, December 16, 2008

Enceladus - Sixth Largest Moon of Saturn


Saturn, the sixth planet from the sun and one of the gas giants in our solar system has 7 moons in addition to a prominent system of rings. One of these moons, Enceladus, is especially interesting to us humans because it is made mostly of water-ice and could possibly support life. It's diameter is roughly 500 km (15% of the moon's) and has a mass of about 0.2% of the moon's mass. Certain areas of the moon's surface lack craters indicating a dynamic surface similar to the floating ice sheets in the Earth's arctic regions. Water vapor has also been observed spewing from the surface. I found the image here and it is licensed under a Creative Commons liscence.

Optical Illusion - "Shifting Almonds"

I found this image in cyberspace here. It's just a plain ol' PNG, and one of the coolest optical illusions I've ever seen.

See also: Home-made and Bio-inspired Wind Power

Verify User Intent Before Closing an Eclipse RCP Application

Have you ever accidentally closed an application only to lose all the data you were working with or abort some long running calculation half way through? On one particular application I was working on, it would have been devastating to accidentally close the application so I needed to add a dialog box that asked the user to verify that s/he really wanted to close the application. I've also used some applications before with this feature, and found it annoying when I was asked every single time whether or not I was really sure I wanted to close the application. Use it sparingly. The best solution would be to add a preference to the application where the user could decide if s/he wanted the reminder or not. I'll add a tutorial on how to do that soon. Anyway, It took me a while to figure out how to add a confirmation dialog box, but it's actually quite easy. Here's how...



Step 0: Create a Hello World Application.

Step 1: Add code to create the dialog box when the close application action is triggered. In the ApplicationWorkbenchAdvisor class that was automatically generated when you created a hello world application using the new RCP application wizard in Eclipse, you need to override the preShutdown() method. The method returns a boolean where, if true, the application will shut down, and if false, the application will continue running. You need to add code in that method that opens up a dialog box, gets user input, and returns what the user selected. Eclipse's JFace library contains a nice little class called MessageDialog where we can easily make a dialog box pop up, ask a question, and get the answer. We use the MessageDialog.openQuestion() method and pass it three parameters: a Shell, the dialog box's title, and the question we want to ask.


package com.blogspot.obscuredclarity;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;

public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {

private static final String PERSPECTIVE_ID = "com.timmolter.helloWorld.perspective";

public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
return new ApplicationWorkbenchWindowAdvisor(configurer);
}

public String getInitialWindowPerspectiveId() {
return PERSPECTIVE_ID;
}

public boolean preShutdown(){

Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
String dialogBoxTitle = "Question";
String question = "Are you sure you want to close this application?";
return MessageDialog.openQuestion(shell, dialogBoxTitle, question);

}
}




Step 2: Run the application and test if everything worked. Your application should now have a dialog box that verifies user intent when the application is closed and look something like this:


Piece of Cake!

Next ---> Add Nested Menu Items and Custom Actions to an Eclipse RCP Application
<--- Previous - Add a Menu to an Eclipse RCP Application
Also see: Eclipse RCP Tutorial Table of Contents

Thursday, December 11, 2008

Add a Menu to an Eclipse RCP Application

As shown in the article Hello World with Eclipse RCP - Your First Application, it is quite simple to create and run your own very basic Java RCP application using Eclipse. In this article I will show you how to add a "Menu" to your application. In particular, I will add the "Exit" action to a "File" menu, and it is very simple. It only requires a few lines of code in one class. The application's menu is used to provide the user with a logical and organized interface to access all the global functions of the application. For example, almost all applications have a File--->Exit or a Help---> About menu. An Eclipse RCP application menu can be as simple or elaborate as needed, and it can contain icons, dividers, and expanding submenus. The following steps demonstrate how to add the Exit action to a File menu to an Eclipse RCP application.



Step 1: Add code to create the File menu and the Exit action. When you created a hello world application using the new RCP application wizard in Eclipse (which I always do to create a skeleton RCP project to build off of for a new application), Eclipse created a ApplicationActionBarAdvisor class that extends ActionBarAdvisor. You need to override 2 of the methods to configure the application's menu to suit the needs of the particular application. During certain strategic points in the workbench's lifecycle, these methods are called and your complete menu is created. In makeActions() the Exit action is created and registered. In fillMenuBar() the File menu is created, the Exit action is added to the File menu, and the File menu is added to the application's menu bar.

package com.blogspot.obscuredcalrity;

import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;

public class ApplicationActionBarAdvisor extends ActionBarAdvisor {

IWorkbenchAction exitAction;

public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}

protected void makeActions(IWorkbenchWindow window) {

exitAction = ActionFactory.QUIT.create(window); //the ActionFactory defines a set of common actions and can be used in the application.
register(exitAction);  //register the action so they are deleted when the Workbench window is closed

}

protected void fillMenuBar(IMenuManager menuBar) {

MenuManager fileMenu = new MenuManager("&File", "file"); //create a menuManager to take care of all submenus in "File"
fileMenu.add(exitAction); //Add the "exit" action
menuBar.add(fileMenu);//Add the "File" menu to the menuBar

}

}




Step 2: Run the application and test if everything worked. Your application should now have a File menu with an Exit action and look something like this:



Piece of Cake!

Next ---> Verify User Intent Before Closing an Eclipse RCP Application
<--- Previous - Add an Icon to an Eclipse RCP Application View
Also see: Eclipse RCP Tutorial Table of Contents

Wednesday, December 3, 2008

Add an Icon to an Eclipse RCP Application View

In the last Java Eclipse RCP tutorial, Adding a View to an Eclipse RCP Application, I demonstrated how to add a view to a simple RCP application. In RCP applications, views are where you put things like tables, buttons, combo boxes, labels, charts, etc. - all the graphical interfaces that a user will interact with when using your application. In this article I will show where to get icons and how to add an icon to a view, which is placed on a tab corresponding to that view. I will also show how to label that tab with some custom text.



Step 1: Get some icons. Mark James at www.famfamfam.com has graciously created and made available over 1000 icons suitable for Eclipse RCP applications. His work is licensed under a Creative Commons Attribution 2.5 License, so you can use the icons any way you like. Download the icons, browse through them, and choose one that you'd like to use for your view.





Step 2: Add the icon to your RCP application. With Eclipse open and the Package Explorer showing the contents of your project, drag and drop an icon into the "icons" folder. For this example, I put the bomb.png icon into the icons folder.



Step 3: Add the icon to the view. Make sure the View is highlighted in the All Extensions list. To the right are the properties of the view. To the right of the icon property, click on the "Browse..." button. In the dialog box that pops up, choose the icon that you just added. The icon should show up next to the view's name in the "All Extensions" list.




Step 4: Specify that the view's title should be shown. Now that the icon is added to the application project and associated with the view, some code is needed to tie everything together. In Perspective.java set the boolean flag for the second argument in the "addStandAloneView" method to true. This is the "showTitle" flag which tells the RCP application to show a tab for the view containing the icon and a title for the view.

package com.blogspot.obscuredclarity.addicon;

import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;

public class Perspective implements IPerspectiveFactory {

 public void createInitialLayout(IPageLayout layout) {

  layout.addStandaloneView(MainView.ID, true, IPageLayout.LEFT, 1.0f,   layout.getEditorArea());
  layout.setEditorAreaVisible(false); //hide the editor in the perspective

 }
}


Step 5: Give the view's tab a name. In the view's class, add the line "this.setPartName("Hello!");" to the createPartControl method (line 16). Change the "Hello!" String to whatever you want.

package com.blogspot.obscuredclarity.addicon;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;

public class MainView extends ViewPart {

 public static final String ID = "com.blogspot.eclipsercptutorials.addicon.mainView"; //the ID needs to match the id set in the view's properties

 public MainView() {    }

 public void createPartControl(Composite parent) {

  this.setPartName("Hello!");

  Label label = new Label(parent, SWT.None); //new up a Label widget
  label.setText("  All this program does is display this text in a view."); //set the label's text

 }

 public void setFocus() { }

}


Step 6: Run the application and test if everything worked. Your application should now look something like this:



Step 7: If you want the view to be non-closeable, add layout.getViewLayout(MainView.ID).setCloseable(false);" to the createInitialLayout" method (line 12). This will hide the little "X" on the tab and not allow the tab to be closed, which you probably want to do if your program only has one view.

package com.blogspot.obscuredclarity.addicon;

import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;

public class Perspective implements IPerspectiveFactory {

 public void createInitialLayout(IPageLayout layout) {

  layout.addStandaloneView(MainView.ID, true, IPageLayout.LEFT, 1.0f,   layout.getEditorArea());
  layout.setEditorAreaVisible(false); //hide the editor in the perspective
  layout.getViewLayout(MainView.ID).setCloseable(false);
 }
}




Piece of cake!

Next ---> Add a Menu to an Eclipse RCP Application
<--- Previous - Adding a View to an Eclipse RCP Application
Also see: Eclipse RCP Tutorial Table of Contents

Sunday, November 30, 2008

Import a CD into iTunes when Artist, Album, and Track Info is Missing

Every now and then, when I buy a new CD and import the music into iTunes, the artist, album, and track names don't come with the music. Instead I would get something like unknown artist, unknown album, and track 01, track2, track 3, etc after the import. Of course, when I search my library for my new music, it cannot find it, which is very irritating. After much googling and trial and error, I eventually figured out how to import the CD and add all the information so that the music shows up in iTunes with all of the important information. I thought since it was difficult for me to figure out how to do it, I would make this post to help other people. The trick is actually quite simple...



Step 1: Insert the CD. iTunes should display all the tracks (Track 01, Track 02...) and the duration of each. Highlight all the tracks by typing CTRL+A or command+A on a Mac.


Step 2: Add the album information. With all the tracks highlighted, choose on File--->"Get Info" or command+I on a Mac. This brings up a dialog box in which you can add the artist and album information as well as the year, genre, and album artwork if you want. After you type in all the information, click "OK". When viewing the track list, the new information should be displayed next to all the tracks.



Step 3: Enter the track names. Highlight the first track and choose File--->"Get Info" or command+I on a Mac. This brings up a dialog box in which you can add the track names one by one. I usually find the track names for the album somewhere online, so I don't have to type them all, but rather just copy and paste them. So copy the first track name from a website, and paste it in the "Name" text box. Don't click OK quite yet. Instead click "Next" and then enter the second track name, clicking "Next" until you fill in all the names. Finally click OK after all the track names have been entered.


Step 4: Choose the file type that the music should be converted to during the import. I usually choose the MP3 format. Go to the iTunes preferences, and under the "General" tab, click "Import Settings...". A dialog box will pop up. Choose "MP3 Encoder" next to "Import Using:". Choose the quality you'd like. Also, if the CD didn't show up in iTunes when you inserted it, make sure "Show CD" is selected in this dialog box.


Step 5: Import the CD. By now, all the information about the CD has been entered, and you can import the tracks. In the bottom right hand corner of the iTunes window click on "Import CD".


Step 6: After the CD is imported, you can verify that the CD and all the correct information has been saved in your file system properly. By default, the music will be imported in the iTunes folder usually in the My Music folder on your hard drive. Doing a search in iTunes should also bring up your newly imported music!


Piece of cake!

Please comment if you found this useful or if something is inaccurate. :)

Friday, November 21, 2008

How to Add an Amazon Widget to Your Blog to Make Some Extra Cash

Amazon.com allows you to place customizable product advertising widgets on your website or blog, and in return splits the profits with you any time someone clicks on your widget and buys something within 24 hours. There are a million ways to earn revenue from your website or blog, but most of them can be quite annoying and spammy in my opinion. Flashy animated banner ads or the ones that grow in size and cover up what you're trying to read are the worst, while textual Google AdSense ads, and relevant Amazon product ads, while still advertisements, are the least obtrusive. Amazon gives you 4% of the product's price as a referral fee once the item is ordered and shipped, and the bonus increases the more items you refer to Amazon. Anyway, why not earn a couple bucks from the effort it takes to post helpful information on your website? I think people are willing to put up with a bit of advertising if the content of the website or blog is substantial.

What I like about the Amazon widgets is that they are customizable and can contain products relevant to your blog post. While it's an advertisement, I feel placing an
Amazon widget on a relevant blog post can also be seen as a service for the people looking for a quick link to buy that product from a trusted vendor.

The appearance of the widgets can be customized to match the look and feel of your website. There are also many different types of widgets you can use, giving you several choices. I discovered the Amazon widgets on someone else's blog, but it took me forever to figure out how to put them on my own blog. In this article I hope to save some of you the time it took me to get Amazon widgets on your website!

Step 1: First off, here are four different examples of widgets. There are a bunch of different ones available in addition to this.

Search Box Link:




Deals:




MP3 Clips:




My Favorites:



The My Favorites widget is the only one I really use on my blog. I embed it in the text of some of my articles so that the recommendation for the product is right where the product is talked about in most cases. Since I have been a customer of Amazon.com for quite a while now, I can feel guilt free when sending readers of my blog to their website because I know it's a reputable company.

Step 2: To get an Amazon widget for yourself, just click on the "Get Widget" button on the My Favorites widget above. This will take you to the Amazon.com Associates Central website where you can sign up for an associates account and start building your own widgets and get the code to embed in your website. Doing so is pretty easy after you have an account. Just for the sake of completeness, I'll show you how easy it is to build a My Favorites widget and embed it in your blog.

Step 3: After logged into your Amazon associates account, click on the "Widgets" tab and click "Add to Your Webpage" for the "My Favorites" widget.


Step 4: Search for the type of product you would like to advertise and add one or more. I just typed "widget" because this article is about Amazon widgets. Click "Add Product" for the products you like and they will show up in the right hand column. You can remove them and/or sort the order. When you're done, click "Next Step". You can always add or remove products later, even without re-embedding the widget code in your website.



Step 5: Customize the visual display of your widget. Give it a title, choose whether or not to randomly shuffle the products, and choose colors, etc. If you want to add more columns, you might have to change the width of the widget first in units of pixels. When you are done customizing it, click "Add to My Webpage".


Step 6: Add the widget code to your webpage. Click "Copy" in the small box that popped up to copy the HTML code that defines your new widget. This code will need to be pasted into your webpage.


Step 7: Paste your widget HTML code into your webpage. With a blogger blog you have to click on the "Edit HTML" tab and paste your code there where ever you want the widget to appear between the article text.

Piece of cake!

See also: Add an HTML Footer to Every Post of Your Blogger Blog
and Place an Inline Link to an Amazon Product with Your Associates ID