I had a lot of things to blog during the past 3 months but I just couldn't get myself to write any of them online.
Well, since I've been using the Visual Studio.Net immediate window a lot lately so I thought it would be useful for fellow eclipse users to know that an equivalent tool exist in Eclipse.
I don't have to write what's already written, right? Just follow the link below, it's pretty much self-explanatory.
http://askville.amazon.com/debugging-Eclipse-Visual-Studio-equivalent-Window-interactive-top-level/AnswerViewer.do?requestId=9072383
I was encountering the error below everytime I tried to invoke a WS client in RAD7. I was calling the WS through a console application using a generated client stub.
Deployment error:
java.io.IOException: FATAL ERRORS encountered by WSDL2Java tool.
at com.ibm.ws.webservices.wsdl.Parser.generate(Unknown Source)
at com.ibm.ws.webservices.wsdl.Parser.generate(Unknown Source)
at com.ibm.ws.webservices.tools.wsad.WSDL2Java._execute(Unknown Source)
at com.ibm.ws.webservices.tools.wsad.WSDL2JavaBase.execute(Unknown Source)
at com.ibm.etools.webservice.command.adapter.CommandToCommand.execute(Unknown Source)
at com.ibm.ast.ws.v61.consumption.j2ee14.stub.WSDeployStub.execute(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.ibm.ast.ws.v61.consumption.j2ee14.command.AbstractEmitterAdapterCommand.execute(Unknown Source)
at com.ibm.ast.ws.deployer.WASV61DeploymentModule.generateDeploymentCode(Unknown Source)
at com.ibm.etools.webservice.deploy.core.AbstractDeploymentModule.deploy(Unknown Source)
at com.ibm.etools.webservice.deploy.core.AbstractDeploymentModule.deployWebservice(Unknown Source)
at com.ibm.etools.webservice.deploy.core.AbstractDeploymentModule.execute(Unknown Source)
at com.ibm.ast.ws.deployer.WASDeploymentModule.execute(Unknown Source)
at com.ibm.ast.ws.deployer.WASDeploy.execute(Unknown Source)
at com.ibm.ast.ws.deployer.WSDeployer.runWSDeploy(Unknown Source)
at com.ibm.ast.ws.deployer.WSDeployer.processModuleComponent(Unknown Source)
at com.ibm.ast.ws.deployer.WSDeployer.execute(Unknown Source)
After searching google, I found one solution. I added the jar, in my classpath (buildpath/libraries). I found the jar in
<RAD_INSTALL>/SDP70/runtimes/base_v61/runtimes/com.ibm.jaxws.thinclient_6.1.0.jar
However, I was able to make it work without this before. For some weird reason it just pops out randomly, each time I do an update from SVN...
I wanted to start learning Eclipse RCP (Rich Client Platform) and was following a tutorial here, but I was already stuck on the first step (getting started). Friend google made me find this, and this.
Basically, I didn't install the RCP plugin and to quote from those two links:
Lots of people report that if they try this they can only select a
"Generic" entry. The common source of this problem seems to be that
you did not download the package "Eclipse for RCP/Plug-in
Developers". Please see
Eclipse Installation
.
You might have to click on "More Packages" to see the RCP
download package.
On the webpage of eclipse (www.eclipse.org), click on DOWNLOADS.
Download the package "Eclipse for RCP/Plug-in Developers".
I'll be posting more about RCP once I finish setting up my IDE. :)
I've only used this template engine for a short time but I'm already inloved with it. We use Velocity to generate e-mail templates and I happen to encounter an error when I was trying to configure it progmatically:
Properties p = new
Properties() ;
p.setProperty("resource.loader","file");
p.setProperty("file.resource. loader.class",
"org.apache.velocity .runtime. resource. loader.FileResou rceLoader");
p.setProperty("file.resource. loader.path",
"C:/opt/templates/");
p.setProperty("file.resource. loader.cache", "false");
p.setProperty("file.resource. loader.modificat ionCheckInterval",
"0");
Velocity.init( p);
VelocityEngine ve =
new VelocityEngine( );
ve.init();
Template t =
ve.getTemplate("my_template. vm");
VelocityContext
context = new VelocityContext( );
t.merge( context,
writer );
I would encounter an error
org.apache.velocity .exception. ResourceNotFound Exception: Unable to find
resource 'my_template. vm'
I'm surpirsed it took me about 2 or 3 days to figure out that there are actually 2 ways of using the Velocity engine. Singleton and separate instance model. So the above code could've been fine if I changed the lines
VelocityEngine ve =
new VelocityEngine( );
ve.init();
Template t =
ve.getTemplate("my_template. vm");
VelocityContext
context = new VelocityContext( );
t.merge( context,
writer );
with
Template t = Velocity.getTemplate("my_template. vm");
VelocityContext
context = new VelocityContext( );
t.merge( context,
writer );
I hope this helps a lot of people. :)
I'm not really fond of configuring log4j. I know the basic stuff but then, didn't anticipate to be assigned a task to log into two different loggers. I usually just log in the console and leave the complexities to the guys who setup the application server in production.
My typical, simple log4j.properties
log4j.rootCategory=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
What the above does is just simply to log in the console whenever it encounters a "debug" statement. Now, what I needed was to log to a different log. I didn't want to share with the console and I want specific things to be written to my other log file.
First off, make sure the log4j.properties is visible in your classpath.
Add the following code in your log4j.properties
log4j.logger.devpinoyLogger=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=5000KB
log4j.appender.dest1.maxBackupIndex=3
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=${application.log.root}/MyOtherLogFile.log
The above listing gives us a logger named devpinoyLogger. You might be wondering what dest1 is. It's an Appender, named dest1. Yes, you can name it anything you like. One last thing you might be wondering is ${application.log.root}. This is called a System Variable, it's a little different from an environment variable because this is something you either set in your application server or with the -D argument when you invoke a console application.
Now, going to the Java code.
Typically, you would call a logger like this.
Logger logger = Logger.getLogger(SomeClass.class);
To setup a different logger, just supply the logger name(in our case, devpinoyLogger) as the argument to getLogger.
Logger logger = Logger.getLogger("devpinoyLogger);
You can now log separately. I use this to log in two different files.
Logger logger1 = Logger.getLogger(SomeClass.class);
Logger logger2 = Logger.getLogger("devpinoyLogger");
public void testLog(){
logger1.debug("This is logger 1 logging");
logger2.debug("This is logger 2 logging");
}
Now, I know I didn't went into details. I expect you to have enough common sense to modify the above properties and code to fit your needs.
HTH. ;)
I'm very sensitive on how I know my variables when I program and the most I'm very careful with is naming boolean variables.
So I was trying to create a new variable inside of Eclipse and I'm not used to naming my boolean vars like isNew, isAllowed or isValid but instead I know them new, allowed or valid but still adhere to the Java naming convention for my methods like setNew() and isNew().
Just today though, I accidentally named one of my boolean variables "isNew". To my surprise, Eclipse was intelligent enough to detect this and named my generated accessor/mutator as setNew() and isNew() instead of setIsNew and isIsNew().
Nice. :)
I was setting up my workspace today and noticed that my wrist was hurting.
Sometimes, we just so forget to get back to our fundamentals and leaves us stressed. We don't always realize that they could make our job easier.
So I was creating the directory of the following structure
/dir1/some_other_dir/one_more_level_deep/put_here
I don't know if I was the only one guilty of this... What I did was right click several times and create a new folder for each of the directory listed above. I was about to do it again until I remembered... Wtf?I studied computer 4 years in College and I'm doing this? So I fired up my command prompt did
c:\ mkdir c:/dir1/some_other_dir/one_more_level_deep/put_here <---paste
Only took a few steps. Whew!
Weird post? Not unless you've been doing the same! Lolz!
I just want to spread that word that there is a lightweight framework for running EJB's outside a container. You could use it together with JUnit so unit testing EJB's becomes easier. The current project that I'm working on uses this and though right now. I don't have a concrete example on how this works, I can guarantee you that it does though. It's free and opensource .
http://www.mockejb.org/
Long live the EJB!
I just want to share a quick code snippet for using Strut's(1.1) bean:message tag with dynamic keys
Assuming you have the following
1. A class named Event with attributes eventId(Long), and myMessageKey(String).
2. myMesssageKey values would come from a database and will have values like label.my.message.
3. You put List of Events in a request-scoped attribute named eventList
You can then iterate through it like this (used inside an html:select):
<logic:iterate id="event" name="eventList" scope="request">
<option value="<bean:write name="event" property="eventId"/>">
<bean:define id="dynamicMessageKey" name="event" property="myMessageKey" type="java.lang.String"/>
<bean:message key="<%= dynamicMessageKey %>"/>
</option>
</logic:iterate>
</html:select>
I hope a lot of Struts developer would still find this useful.
In my office, TDD is a new methodology that we've just began adopting. My senior wrote a TestCase class before he left the company. Thanks to him, I got some sample codes to study.
After baby sitting, I decided to open my computer and fire up netbeans. We're using RAD at my work btw, I could use eclipse but I like netbeans for learning something new or trying out small things. Oh, that makes me an unofficial netbeans evangelist at the same time! Lolz!
Using the JBible app I created a few weeks ago, I created a simple JUnit test class that tests one of my DAO(Data Access Object) methods.

What did I gain?
1. For some reason, I actually enjoyed doing it.
2. I can now officially perform TDD at my work! Though it may take a while to improve on that. My knowledge of TDD is not so advanced afterall.
3. I don't know if it's right to say, but in netbeans you get instant profiling of your methods(if you look on the lower-left where the test status are).
There are probably more complicated scenarios to test against. For now, this will do for me.
Below is the code I used for testing. Please forgive the formatting. Also, if you have comments on things like how I can improve my test code, please don't hesitate to comment. I would also appreciate if you could give me pointers so I could get better at this.
Special thanks to Jop and Cruizer, though I may never become an advocate of TDD as you are guys.
package org.devpinoy.bibleapp.dao.test;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.devpinoy.bibleapp.dao.BibleDAO;
import org.devpinoy.bibleapp.dao.DAOHelper;
import org.devpinoy.bibleapp.dao.exceptions.NoBookFoundException;
import org.devpinoy.bibleapp.dao.impl.BibleDAOImpl;
import org.devpinoy.bibleapp.dto.Book;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class BibleDAOTest {
BibleDAO bibleDAO;
public BibleDAOTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
try {
bibleDAO = new BibleDAOImpl(DAOHelper.getAccessDBConnection("C:/BibleDB/BibleDB.mdb"));
}
catch (SQLException ex) {
Logger.getLogger(BibleDAOTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
@After
public void tearDown() {
bibleDAO = null;
}
@Test
public void bibleDAOTest(){
assertNotNull("BibleDAO is null, everything else will fail", bibleDAO);
}
@Test
public void getBookListTest(){
List bookList = null;
try {
bookList = bibleDAO.getBookList();
}
catch (NoBookFoundException ex) {
Logger.getLogger(BibleDAOTest.class.getName()).log(Level.SEVERE, null, ex);
}
assertNotNull("List should not be null", bookList);
assertTrue("List should have value greater than zero", bookList.size() > 0);
System.out.println("Book list size: " + bookList.size() );
for (int i = 0; i < bookList.size(); i++){
Book book = (Book)bookList.get(i);
System.out.println("Book" + i + ": " + book);
assertTrue("Only book instance should exist inside getBookList", book instanceof Book);
assertNotNull("Book should not be null", book);
}
}
@Test
public void testNothing(){
System.out.println("Testing nothing");
}
}
Well... It was one hell of a week for me and I needed something to remind me how fun programming is. Or used to be hehehe.
This
was supposed to be an entry to Keith's contest, I unfortunately fell
ill a few days before the deadline and wasn't able to continue with it.
I had the change to continue working with it so rather than playing
video games, I sitted and turned on my computer, and started coding. I
tried to stick to my original concept eventhough I've already seen
other people's submission (or screenshots).
Aside from my first statement, basically the motivation to continue with this app are the following:
1. Spread the Gospel
2.
Utilize Netbean's Swing Editor, I had a lot of fun using it. I had no
prior professional experience with Swing so netbeans really made up for
that shortcoming.
3. Demonstrate to young and starting Java developers how a
database driven Swing app might be built using Java. This is actually
also my first database driven Swing application.
You can open the source in Netbeans 6.1, you need JDK 1.6 installed.
God Bless! ;)
UPDATE 11/03/2008: I just included an executable jar in the zip file.
You also need to place your database in C:\BibleDB\BibleDB.mdb
Enjoy!



I'm currently maintaining an application built on Websphere 5. It's such a shame that once you select a default workspace, there would be no option inside the IDE to switch workspace(RAD7 and plain old Eclipse has this). Luckily, I had a friend who already experienced this kind of problem and he gave me this CLI command
wsappdev -setworkspace
Just be sure to run wsappdev from your websphere install directory and once WS starts, it will prompt you to select your workspace.
Ok, in my last post I tried to follow Mike J. Potter's tutorial on how to read data from PHP to Flex. He actually also tried to make an example of how to write data but he left some part out.
Ofcourse I'm still just trying out the examples, making some little twists wherever I feel like adding one. To get directly to the point, I modified the PHP file in his example as follow:
<?php
$host =
"localhost";
$username =
"root";
$password =
"";
$db_name =
"flextestdb";
$mysql_connection
= mysql_connect($host, $username, $password);
mysql_select_db($db_name);
$param_username =
$_POST["username"];
$param_password =
$_POST["password"];
$text =
$param_username . $param_password;
$query =
"INSERT INTO users_tbl(username, password) VALUES('$param_username',
'$param_password')";
if (
!mysql_query($query, $mysql_connection) ){
die('ERROR: '. mysql_error() );
}
echo "INSERT
SUCCESSFUL, 1 Record Added";
?>
Pretty straight-forward. Here's the MXML code:
<?xml
version="1.0" encoding="utf-8"?>
<!--
======================================================================
Aug 1, 2008 12:27:00 PM
======================================================================
-->
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:HTTPService
id="writeData" url="http://localhost/flextest/write.php" method="POST" resultFormat="text" result="resultHandler(event)"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
/*HTTPService result callback*/
public function resultHandler( event:ResultEvent ):void
{
Alert.show("Result " +
String( event.result ) );
}
/*Function to send over HTTP*/
public
function sendData():void
{
var validEntry:Boolean = !(usernameTxt.text
== "" || passwordTxt.text == "");
if (validEntry){
var
objSend:Object = new Object;
objSend.username =
usernameTxt.text;
objSend.password =
passwordTxt.text;
writeData.send(objSend);
}
else{
Alert.show("Username
and Password cannot be blank!");
}
}
]]>
</mx:Script>
<mx:Label x="10" y="10" text="Username:
"/>
<mx:TextInput x="100" y="10" id="usernameTxt"/>
<mx:Label x="10" y="50" text="Password:
"/>
<mx:TextInput x="100" y="50" id="passwordTxt"/>
<mx:Button x="10" y="100" id="sendButton" label="Send" click="sendData()"/>
</mx:Application>
I've heard about using CSS to aid in aligning your form. Yes, CSS in Flex. But I don't know how to do that yet so I'm sticking with hardcoded values. Above you will see that I tried to validate using a simple if check and the Alert class. Spket, sad to say, as of this point doesn't have support for Actionscript, that's why the Actionscript portion were all green... No code-completion feature even for the <mx:Script> tag.

The first time I tried to run the SWF file and click on the submit button I received an error saying:
[RPC Fault faultString="HTTP request error" faultCode="Server.Error.Request" faultDetail="Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL: http://localhost/write.php"]. URL: http://localhost/write.php"]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()
at mx.rpc::Responder/fault()
at mx.rpc::AsyncRequest/fault()
at DirectHTTPMessageResponder/errorHandler()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/redirectEvent()
Make sure you put the correct url in your HTTPService to avoid this, and if you ever encouter it, you know what to do.
Once you try out the app, data successfully inserted into the MySQL table. You can check the output of the app (see my previous post) to verify that the record was indeed inserted. Next time, I'm gonna try to combine these two so they don't have to be two separate swf files.


main.swf (The result list)

Resources:
http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&productId=2&postId=7744&loc=en_US
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Boolean.html
Note: This post is not intended as a tutorial. I'm just sharing my own personal experience with learning FLEX.
Finally, I was able to sit down for a few hours and do some coding with Flex. Well, I didn't write my own code but I think it helps a lot when you type "most" of the code you copy(you don't have to code everything).
As a learner, I want to reduce as much roadblocks as I can. I want to learn and move forward. So I installed xampp which bundles Apache Webserver and MySQL. It also has PHPMyAdmin. I followed a tutorial from adobe which will teach you how to communicate with PHP. You can find it here.
I had an MXML editor but not a PHP editor so I encountered an error right-away.

XML Parser Failure, I knew right away that I forgot to close a tag that I'm printing through PHP's echo function. I modified the PHP source a bit for my own convenience.
<?php
//modified by Lamia, original code
written by Mike J. Potter
$host =
"localhost";
$username =
"root";
$password =
""; //MYSQL bundled with xampp uses an empty space as the default
password
$db_name =
"flextestdb";
$mysql_connection
= mysql_connect($host, $username, $password);
mysql_select_db($db_name);
$query =
"SELECT * FROM users_tbl";
$result =
mysql_query($query);
echo
"<people>";
while ( $row =
mysql_fetch_object($result) ){
echo "<person>";
echo "<userid>" .
$row->user_id . "</userid>" ;
echo "<username>" .
$row->username . "</username>";
echo "<password>" .
$row->password . "</password>";
echo "</person>";
}
echo
"</people>";
?>
The database, the table name and field names are different since I wanted to adhere to my personal way of naming them. Below is the output of the above code. I included the browser output and the HTML source.

If you're working from a blank mxml project in Spket IDE, try pressing ctrl + space to bring-up the code-assist window and type "A", select Application and the mxml skeleton should be generated for you.

Original MXML code written by Mike J. Potter
<?xml
version="1.0" encoding="utf-8"?>
<!--
======================================================================
Jul 30, 2008 2:23:46 PM
======================================================================
-->
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="rest_service.send()">
<mx:HTTPService id="rest_service" url="http://localhost/flextest/rest.php"/>
<mx:DataGrid left="0" right="0" bottom="0" top="0" dataProvider="{rest_service.lastResult.people.person}">
<mx:columns>
<mx:DataGridColumn headerText="Id" dataField="userid"></mx:DataGridColumn>
<mx:DataGridColumn headerText="Username" dataField="username"></mx:DataGridColumn>
<mx:DataGridColumn headerText="Password" dataField="password"></mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
</mx:Application>
And for some nice FLEX application. :)

I tried to create a simple batch program to help me in compiling.
[code]
del *.swf
mxmlc main.mxml
[code]
In the future, I'll try to see if this can be done with Ant.

Thanks to Mike J. Potter for the wonderful tutorial at the adobe website.
Installing the Flex SDK
If you haven't downloaded the Flex SDK yet, go to the adobe website. Installing it is just a matter of extracting the zip file to your preferred directory(mine is in C:\flexSDK\bin). If you want to be able to compile from the command line, right click my computer, click on the Advance tab, then Environment Variables. Create a new system variable and put FLEX_HOME as the variable name, the location of your SDK(e.g. C:\Applications\flexSDK) as the value. Click ok. Look for the "Path" variable and click edit. At the end of the path variable value, put the following w/out the quotation marks, ";%FLEX_HOME%". Click ok until all windows are closed. You should be ready to go now. Go to your command line and type "mxmlc", if you see something like:
Adobe Flex Compiler (mxmlc)
Version 3.0.0 build 477
Copyright (c) 2004-2007 Adobe Systems, Inc. All rights reserved.
mxmlc [options] [defaultVar]
Use 'mxmlc -help' for more information.
It means you did it right.
Installing the Spket IDE, eclipse plugin
Note: Spket IDE flex editor is still in its early stage.
I was browsing for an alternative flex code editor(i.e. aside from Flex Builder) and I found spket IDE which is currently on version 1.6.12. I only needed to download the Eclipse plugin since I already have Eclipse(3.4.0) installed on my machine. I first made sure that I'm currently not running Eclipse, thenI extracted the zip file. Now, there should be a plugin and features folders. Browse inside those two directories and copy-paste the contents into your eclipse folder's features and plugin directories respectively.
Once done, open Eclipse and go to window->preferences and a new window will open. Collapse sa Spket tree, click on Flex SDK and specify your Flex SDK directory. Mine is in C:\flexSDK\. Change to the spket perspective as shown in the image below.

In an empty workspace, create a new project, under general, just select "Project". Name the project anything you want, I named mine "FlexTest". Create a new file, name it test.mxml (or whatever you like, as long as it ends with mxml). From here on, it's up to you to play with it. :)
Some notable pros and cons for this release:
Pros:
1. Very powerful code-completion feature
2. Drag and drop feature(look for the snippets window)
3. Free for non-commercial use
Cons:
1. No Flex compiler as of now
2. No visual designer
3. No Flex project support
4. No Flex file template available
Right now, the cons still a little outweigh the pros. All-in-all, it's still just an editor and you probably have to compile from the commandline. I'm looking forward to seeing improvements with this product.
Until next time 
More Posts
Next page »