Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Friday, March 12, 2010

CWWSS7200E: Unable to create AxisService from ServiceEndpointAddress

This is what I got back when I tried to bounce a JAVA WebSphere Axis service from a WCF client:
CWWSS7200E: Unable to create AxisService from ServiceEndpointAddress
Took me a while but eventually figured out what was wrong and ,long story short, WebSphere did not like the HttpHeaders generated by the WCF bindings (basicHttpBinding) when sending the request.

I started sniffing traffic with Fiddler, but initially I was paying attention only to the SOAP envelope. I then tried to directly invoke the service using SoapUI and it basically seemed to work fine (no Unable to create AxisService error message and I was getting back the result I expected). With the SOAP envelope ruled out, the next logical consequence needed to be the HttpHeader, so I compared the header generated by WCF with the one automatically generated by SoapUI (by pointing the tool to the endpoint url):

WCF Generated HttpHeader:
POST /MyWebServiceDomain/aWebService HTTP/1.1

SoapUI Generated HttpHeader:
POST http://xx.xxx.xxx.xx:9080/MyWebServiceDomain/aWebService HTTP/1.1

At this point it was fairly obvious that I needed to tweak the POST line of the HttpHeader to include the full definition of the endpoint, hopefully by WCF configuration - and after asking around a co-worker pointed me in the right direction: hostNameComparisonMode="Exact" on the WCF binding is what I was looking for (it seems to be set to StrongWildcard by default).

Couldn't find anything on the web about any of the above - I hope this helps someone else with the same problem.

Saturday, January 9, 2010

What a .NET guy likes about AppEngine

I recently completed work on an app built on AppEngine and Google Web Toolkit:



It's basically a logo design app with a twist - follow the link if you wanna find out more on the app itself.

To the point, the team on this project came mostly from a Java background and even though I am mainly a .NET nut I also have a bit of Java under the belt, so this project represented the perfect opportunity for me to get some sweet  AppEngine + GWT action.

So here we go, here's the good old list of things I really liked about the setup on this project (Java/AppEngine/GWT on Eclipse + Google plugins) compared to the setup I am more familiar with (C#/ASP.NET + SQLServer + Azure hosting, all on VS):
  • With AppEngine and the Google-Datastore you don't have to cope with SQL or SQLServer (and if you follow this blog you know how I feel about SQL)
  • You can literally deploy your app with one-click from the eclipse plug-in (all extremely easy to setup - and it works)
  • Hosting is free on google appspot (if you don't go over the free quotas, and quite cheap after that anyway)
  • GWT = virtually no messing around with javascript (I do like javascript but not if I am in a hurry)
  • .NET/VS to JAVA/Eclipse transition turned out to be OK (Eclipse is pretty cool) with people around to rely on
So far AppEngine has proven reliable - the app still runs a bit slow but we did not put any effort into improving performance (I've seen ASP.NET apps running much slower, and it rarely boils down to hosting anyway) - stay tuned for more.

Thursday, December 24, 2009

Nightmare before Christmas: How to use JFace + SWT standalone

I could've as easily called this Eclipse plugins from HELL, but being Christmas and all I thought I would go for the Christmas thing, which gives me the opportunity to wish Merry Xmas to all the geeks who happen to be reading this lame-ass blog over the holidays instead of watching Star Trek as per tradition.

Being mainly a .NET guy, I am not too familiar with the eclipse platform, but I desperately needed to put together a quick UI and decided to go with JFace and SWT after @tarelli suggested so (he's the JAVA guy). Unfortunately, at the time I didn't realize he was talking about an Eclipse plugin project and not about using JFace and SWT in a standalone Java app.

So I went on and got started with some nice tutorials specific to running JFace + SWT standalone, and some more gentle introductions.

Time to get my hands dirty, so I started a new Java project, and dropped in some of the code from the tutorials. In order to get it build I needed to import JFace and SWT plugins as external jars, which I could not find anywhere in my plugins folder (I am on Galileo C:\eclipse 3.5\plugins). I needed to somehow get the damn plugins, but could not quite figure out how to get only those I needed from Help --> Install Software Updates, so I ended up pulling down anything to do with Eclipse SDK. To my delight the SWT and JFace plugins were there (in the plugins folder) after the lengthy process of downloading tons of stuff I didn't need.

After a bit of mocking about (blindly trying to import anything with jface or swt in it) I managed to understand which jars I needed to import to get the damn thing to build (org.eclipse.jface_3.5.1.M20090826-0800.jar and org.eclipse.swt.win32.win32.x86_3.5.1.v3555a.jar) I started mocking about with the code and spent a good while playing around with ContentProviders, ListViewers and so forth. Everything was building nicely, but as soon as I tried to run it as java application got the cold shower:

Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/core/runtime/IProgressMonitor
    at demo.ui.test.EntryPoint.main(EntryPoint.java:18)
Caused by: java.lang.ClassNotFoundException: org.eclipse.core.runtime.IProgressMonitor

Apparently some type was missing somewhere. I've seen a lot of sh*t working on Visual Studio and all, but errors don't get much more cryptic than this.

After a good while, after unfruitfully trying to offline troubleshoot the heck out of my project (offline troubleshooting is just madness but I was waiting the phone company to turn on my broadband in the new apt i moved to recently), I reverted to @tarelli, the eclipse guru who got me into this mess, and begged for help: he promptly told me that I was in a bit of a feckin' mess, and if I wanted to get out of it alive I would've had to create a Plugin Project "with a view" and take it from there. I tried, and he was right, but I did not want a plugin and all the overhead that comes with it, so I kept pulling my hair for several hours with no luck, then went to bed. I felt rightly and truely screwed, if you want.

Luckily the day after the phone company turned on my broadband and I could stop passively obsessing about the problem and started aggressively abusing google in search of a solution to the problem.

After a not too long research (God bless THE INTERNET), turns out that if you want to use JFace + SWT outside a plugin based project you need some other jars. Basically if you're using JFace and SWT in a plugin project runtime dependencies are managed for you through the manifest file (I seem to understand) but if you go for the rogue option of having SWT running standalone then you need to know you need that stuff.

In the specific case of the IProgressMonitor thingy, adding a reference to the org.eclipse.equinox.common jar did the trick. After that I got the same error on a different class, EventManager, and after a couple of blind trials I got it working by importing the org.eclipse.core.commands jar. Obviously, not a mention of this in the tutorials, as I seem to understand there was a bit of refactoring on those packages after those tutorials were drafted (looks like this problem is around since eclipse 3.2 --> read this bug report for further info).

What can I say? If you're coming from .NET sometimes Java == Pain.

Thursday, October 1, 2009

How to mimic SQL WHERE clause on Google Datastore queries

This puzzled me for a while as I never used JDO before crashing the app-engine party.

Assuming we have an Order class with a member variable named customer of type User:

//get current user
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();

//prepare query
PersistenceManager pm = PMF.get().getPersistenceManager();
String select_query = "select from " + Order.class.getName();
Query query = pm.newQuery(select_query);
query.setFilter("customer == paramCustomer");
query.declareParameters("com.google.appengine.api.users.User paramCustomer");

//execute query
List<OrderDTO> result= OrderUtils.getOrderDTOList((List<Order>) query.execute(user));

//feck-off --> I'll never get an MVP but I can swear on my blog!
pm.close();

Just wanted to share to spare some random googler (you) the same process.

Wednesday, July 22, 2009

IPN delivery failed. HTTP error code 405: Method Not Allowed

I was trying to test a servlet I wrote to process payapal IPN notifications (my servlet is very similar to the jsp in this example) and even after enabling all the IPN settings in the paypal test account the IPN was not firing at all after the payment, or at least so I thought because my servlet wasn't logging anything.

I then found out that in the sandbox you can thest IPN notifications through the IPN simulator, which also gives you handy error codes in case of failed transactions, such as:

IPN delivery failed. HTTP error code 405: Method Not Allowed

Thanks to this I then realized that in my servlet I was only implementing the doGet method but not the doPost. Without the doPost method implemented the servlet won't accept any HTML POSTs, thus the error 405. Implementing the doPost (same code as doGet) method solved the problem.

Morale of the story: Paypal integration can be a bitch.

Wednesday, October 15, 2008

[.NET] Why are Exceptions not Checked in C#?

Going from Java to C#, I've been stunned by the absence of  the "throws" clause in the declaration of a method, in which you want to throw a particular exception.
Actually it hasn't caused me so much pain, but the knowledge at compile time of the possibility that an exception could be thrown sounded very useful to me.
Asking to the StackOverflow community, I found out Java is one of the few programming languages where exceptions are "caught" at compile time.
The philosophy behind C# is that what is useful about exceptions is not handling them, but mostly cleaning resources, implementing the IDisposable pattern (The trouble with Checked expcetions).
If you know that a particular method can throw an exception, you also know what it does and how to handle it, otherwise you will handle a generic exception, without need to specify it at compile time; moreover handling exceptions is something that comes near the caller of a method reather than the method itself, so there is no need to specify a chain of "throws" declarations, and that is so useful in versioning, because adding a new exception (or removing an old one) doesn't require a refactoring of your lib.
It is worth noting that C# supports the <exception> tag in the documentation section, with which the compiler informs you that an exception (whose type is anyway checked for existence) can be thrown, without any further constraints.
If you have other issues or different opinions I'd like to hear them.

Good butchering!

Thursday, October 9, 2008

[JAVA] Calendar Months Start from Zero

I don't have time to make a big deal out of this but please tell me which month is the 12th one in the year. I was so stupid to think it was December. Thanks to the JAVAAPI guys I got enlightened. The 12th month is Janaury cause the count starts from 0, it goes to 11 and then starts over again. Grand job to the java.util.Calendar guy!

Sunday, September 21, 2008

[.NET vs Java] Event Handling: Are you sure pure OOP is always the simplest?


After a long time I'm again here for another post!
I will talk about event handling, focusing at first on .NET way to supply it, and then spending 2 words about the Java style.
What I want to talk about is delegates and how are they used...I know old good Giovacchia has already spoken about them in a previous post (here) but I wanna talk about them again.
Why?
I'm leaving for a while the Java world and walking through the .NET Framework (I have to take some Microsoft Certifications, 2 or maybe 3 exams in just 1 month and a half...sounds crazy but it's my task in the short term): this means I have to study, as for now, 2 book of about 1000 pages each one.
I'm not taking part in the war between Open Source Multi Platforms Java Conding and Mama Microsoft Windows-Platform Framework yet, but in this path toward the MS certifications I will try to catch what's good and what's not in both frameworks.
At a first sight (I'm about at the half of the first book) 2 years of experience in Java programming has helped me a lot, but I stopped a while learning about delegates.
I don't want to explain what actually they are (Giovacchia in his post said it perfectly), let's just say delegates are a kind of function pointers, and you have to subscribe a delegate to a particular event in order to make it running when that event is raised.
Because my memory is so short term (could it be Google's fault?), during the reading I made a simple schema to remember which key words to use when declaring a delegate and rasing your own event.


namespace HereIsMyDelegateNamespace{
. . .

public delegate void MyEventHandler(object o, System.EventArgs ev);

. . .

public class MyClass{
. . .
public event MyEventHandler MyEvent;
. . .

/* this method raises an event */
publlic ReturnType RaisingMethod()
{
System.EventArgs ev = new System.EventArgs();
. . .
MyEvent(this,ev);
. . .
}
}
}

namespace ConsumerNamespace{

public class Consumer{

public static void Main(string[] args)
{
. . .
MyClass m = new MyClass();
m.MyEvent += MyEventHandler(m_MyEvent);
. . .
/* from now on we can call a method
* or make an action which causes MyClass to
* raise the MyEvent event */

m.SomeMethodThatRaisesTheEvent();
. . .
}

public static void m_MyEvent(object o, System.EventArgs ev)
{
. . .
/* handles the event */
}
}

}


You have to remember few things:


  • The signature of the delegate has to be the same of your own handling method

  • The signature of the delagete has to contain 2 parameters: the first one is an object reference, that refers to the object that launches the event, and the second one must be a subclass of System.EventArgs (there are a lots of them implemented for the common events)

  • You can subscribe to an event using the overloaded operator += but you can also unsubscribe by using the -=

  • For common applications, you won't need to raise yourself an event, but just supply a method and subscribe it to the event (the method, as said, has to have the same signature of the needed delegate)


And what about Java?
Learning Java I actually never had the need to write down some code to remember how Event Handling works.
Why? There are no delegates, in the sense you need to specify an entire class as the delegate for that event. What does it happen when you need to subscribe to an event?
In that situation Java is more OO then .NET, indeed you only use your Handler Class (such as MouseListener class, but for the common events, e.g. such as Mouse and Keyboard, you have at your disposal tons of ready-to-use classes) to manage the event. In this scenario you call directly by the object that throws the event, an addXXXListener() or removeXXXListener(), and inside your class, in which you surely have an array of potential listeners, when you want to raise the event, you have to iterate manually by calling all the needed methods of the listeners subscribed.
IMHO Java is straightforward to the OOP, but you need more code, and .NET allow you by using delegate and event keywords not to think to the propagation of the event. Moreover, in .NET you won't need to specify an entire class to handle the event, bringing to a more concise code style.

I'm not as experienced in .NET as I'm in Java, so maybe in few weeks I will post the exact opposite kind of opinion, but as for now I'm feeling better using C#, as it seems it has taken the good in Java and brought it to a more powerfull level (I'm refering to the whole framework ofcourse and not to the language itself).


kick it on DotNetKicks.com

Wednesday, April 23, 2008

[Java, SWT] Invalid thread access


Problem: You have your own GUI made with Eclipse SWT, you try to update a widget from within an external thread, and you obtain the exception:
org.eclipse.swt.SWTException: Invalid thread access

Solution: SWT is not thread safe, meaning that if you try to modify a widget from a thread you previously runned external from the one that contains the GUI, the JVM ends the application. Actually Swing is neither thread safe, but you won't receive an exception (and your application behaves in an unpredictable way).

Obviously there is a way to handle this problem, using the .asyncExec(Runnable r) or .syncExec(Runnable r) methods of the Display SWT class: passing a valid implementation of a Runnable class, SWT will allow GUI accesses as soon as possibile. This code is a way of using this pattern:

public class MyGUIClass{

private Display _display = null;

public static void main(String[] args)
{
/* main thread */
final Display display = new Display();
/* this allows a future catch of this class */
_display = display;
final Shell shell = new Shell(display);
final Button button = new Button(shell,SWT.PUSH);
button.setText("Run a thread");
button.addSelectionListener(new SelectionListener()
{
public void widgetSelected(SelectionEvent e) {
/* this class starts a new thread */
MyComputationClass mcc = new MyComputationClass ();
mcc.createNewThread(this);
}

public void widgetDefaultSelected(SelectionEvent e) {}
});
}

/* this main class exposes a public method that returns the
current Display class
*/
public Display getDisplay()
{
return _display;
}

The MyComputationClass in the .createNewThread(MyGUIClass aGUI) will try to update the GUI (from a separate thread). Inside the thread this is the correct code to make SWT dispatch your code:

public class MyComputationClass{
public void createNewThread(MyGUIClass aGUI)

/* a new thread is running */
/* make intensive computation . . .*/
/* . . . */
if(!aGUI.getDisplay().isDisposed()){
aGUI.getDisplay().asyncExec (new Runnable ()
{
public void run () {
aGUI.doSomeGUIModifications();
}
});

/* . . . */
/* thread is ended up */
}
}

This comes from a process of butchering my own Java GUI, so I'm not sure if it is the only way to do it. Anyway, like my dear old friend Giovacchia uses to say, "Don't try to be a perfect coder, just be a perfect butcher!".
See ya!

Wednesday, April 9, 2008

[Java, JSP] JSP for beginners: Are you prepared?


After a week or so of inactivity, we are back with a beginner tutorial about JSP (Java Server Pages).
Are you prepared? (this is a quote from a popular MMORPG).

Basically JSP is a way to use the power of Java inside usual HTML pages.
The first step is to install a capable web server, like Apache Tomcat: JSP files have to be put in the webapps directory or in a subfolder.

As you put Java into HTML files, you can insert neither one Java line of code and simply rename an html file into JSP (.jsp extension) and it will work!
Actually, when the web server open for the first time the page, it compiles it: it leads to a slower loading (only the first time), that happens each time you modify your page (even if there is no Java code), so don't change in JSP each page of your application without discrimination!

How do I embed Java code?

<HTML>
<BODY>
<%
String message = "<p>Hello, this is my first JSP page!!</p>"
String endPage = "<p>Bye bye!</p>"
System.out.println(message);
%>
<p>Above you are reading a wellcome message.</p>
<%=endPage%>
</BODY>
</HTML>


As you can see, inside the <% ... %> there is pure Java code: this is called a scriplet.
More over using <%=endPage%> you can output a java expression, that is the same as calling the System.out class: using JSP you have not to specify the System.out.print() function and call directly out.print(), where out is a global member that outputs directly.

If you need a specific Java class, you can import its package (that should be in the classpath, depending on you web server) usign a JSP directive:

<%@ page import="java.util.Date, java.util.ArrayList" %>


If you need to insert another JSP page inside the current page, in which I suppose you have a particular functionality you use frequently in several other pages, you can import it:

<%@ include file="hello.jsp" %>


In order to interact with your HTML controls, you use the current request object (that comes from the JSP context) and as for session variabiles you'll use the session global variable:

<%

String action = request.getParameter("submitted");

if( action.equals("true") )
{
/* saves a variable as a session variabile:
* from now on it is always available */
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
}


if(session.getAttribute("theName") == null)
{
%>
<FORM METHOD="POST" ACTION="thisPage.jsp">
What's your name? <INPUT TYPE="TEXT" NAME="username" SIZE="20">
<INPUT TYPE="HIDDEN" NAME="submitted" VALUE="true">
<INPUT TYPE="SUBMIT">
</FORM>
<%
}
else
{
out.println("<p>Hello "+ session.getAttribute("theName") +" !!!</p>");
}
%>


What does it mean?
Mainly if you have already set a session variabile with your own name, so there is no need to print out a form, but just a welcome.
First of all the action string is used to store the submitted vairaible, that comes from the submission of the form with the hidden input control.

In case of submission, the action variabile is equal to true, and in that case we store the session variabile thaName with the value of the input text control named username: from now on this session variabile will be available in all your JSP pages till the end on the session (depending on the settings of your web server).

Afterwards if there is not a value for the session variable theName, than prints out the form (without using the out.println() but just as HTML content); else prints out a welcome message, retrieving the session variable theName.

There is also a way of using particular JSP tags to use common Java functionalities...but it is another story!
Stay tuned!!

Tuesday, April 1, 2008

[Java] Introducing GUI with Swing and SWT

These days I'm having a look at JAVA GUIs, playing with different 2D libraries: AWT, JFC/Swing, SWT and JFace.
Actually AWT is the base library for 2D issues and lacks of several common controls (see figure, taken from here).

To fulfill those lacks, the JRE comes with the Java Foundation Classes (JFC) / Swing libraries, with all kind of controls, allowing the creation of complex GUIs.
If anyway you are looking for something quick to implement, you should use the SWT (Standard Widget Toolkit) library, based upon Swing and AWT, created by IBM as the graphic constituent for Eclipse Framework (actually over SWT lies JFace, a graphic library created to support common programming features, not treated in this post).
In Swing controls are disposed automatically by the garbage collector, while in SWT you have manually to dispose them, like in the current example in which a simple window with a lable is created:
SWING

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SwingHelloWorld extends JFrame {

public static void main(String args[]) {
new SwingHelloWorld();
}
SwingHelloWorld() {
JLabel jlbHelloWorld = new JLabel("Just a label");
add(jlbHelloWorld);
setTitle("Example Frame");
setLayout(new GridLayout());
this.setSize(300, 100);
setVisible(true);
}
}

SWT

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class SWTHelloWorld {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Example Frame");
shell.setSize(300,100);
shell.setLayout(new GridLayout());

/* controls code goes here */
Label label1 = new Label(shell, SWT.BORDER);
label1.setText("Just a label");
label1.setSize(100,20);

shell.open();
while(!shell.isDisposed())
{
if(!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
}

As seen in Swing the main class is inherited straight from the JFrame Swing class, while in the SWT version there is the Display object that is a repository of display OS-dependent features and a Shell which is the actual window: you can have several shells for one display. Moreover in the SWT code there is a while loop, which waits for the disposal of the shell (done by the close button [X]) and in that case the main class disposes the Display instance (actually the disposal of all objects is done automatically by the container's dispose event, i.e. by the disposal of the shell).

Another difference between the two libraries is the graphical look:


SwingSWT





It is clear that SWT library depends on the OS look (thanks to the Display object), while Swing uses typical JAVA interface.

If you are planning to learn basics of JAVA GUIs, try first with Swing and than switch to SWT, so you'll gain a wide view of those technologies and learn for each application the one which suites your needs.

Hope JohnnyIdol learned something... he just got served.

Stay tuned!

Thursday, February 14, 2008

[JAVA] How to Retrieve Application Path

This brief article will explain in a few lines how to retrieve the application path in a JAVA enviroment, both the official way and the butchers' way (just as we like!).

(1) The first way calls the System.getProperty static method passing the user.dir value:

String dir = System.getProperty("user.dir");

This way is simple but I found that sometimes (I'm not sure if Sun has fixed it) the returned directory could be slightly different from the one in which the application resides: this is because some times it gives out the directory in which the application has been started and not the one where your classes are.

This happened to me using Eclipse Plugins: usign several plugins, I needed a common directory to retrieve some XML resources, but the working directory returned was the one in which eclipse was running and of course not the same of the plugins one.

I fixed it using a ResourceBundle class. Actually that wasn't a bug, because most of libraries needed to run my plugins were inside Eclipse directory.

(2)And now the butchers' method! This method creates a fictitious file and retrieves its absolute path: I found that this method can overcome the problems using user.dir system property:

java.io.File currentDir = new java.io.File("");
String dir = currentDir.getAbsolutePath();

Generally to retrieve your resources that are in a class directory (and maybe not in the working directory) you won't need the entire path, because we can use this method:
InputStream in = MyClass.class.getResourceAsStream("MyImage.gif");

So my advice is using paths of external directories and storing them into configuration files (such as .properties files) or calling resources without using absolute paths; moreover don't try to modify user.dir system property because it is set when your application starts and if you change it you don't know how will be the behaviour of all other classes.

Stay tuned!

Monday, February 11, 2008

[.Net, J2EE] A walk from J2EE to .NET: impressions and hopes

Last night, just before bed time, I was reading a book [reference] about Component Oriented Programming using .Net framework. Surely the introduction that resembles OOP against COP was interesting, but after few pages I asked myself: "What is .Net?"
Its nothing more than the same stuff as J2EE.

Since my degree, about 1 year and a half ago, I'm currently programming in JAVA, using all that kind of stuff that J2EE represents, such as JSP with its libraries, servlets, portlets, DB integration, web services, and so on.
I've never thought about .NET because I haven't needed it and my company uses to program in JAVA: why should I begin with .NET?

Actually in this year and a half I found myself in trouble with all J2EE technologies, what is a web service and how to use it, how to make a web server run and configure it, what a servelt is, which portlet containers should I use (starting without any knowledge of what a portal container is), which libraries supports XML handling, which supports other stuff, and so on: this is all understandable regarding my total ignorance of J2EE, but this multitude of libraries slows me down even now, and usually what I need is not documented as it should be.
So it seems J2EE is hard for newcomers that, like me, have not many live links with J2EE experts (I learned all alone with so little help), and even forums don't help (great tutorial for real noobs or too much in depth for the beginning!!).

Still now I'm on a project developed using portlets, web services and servlets, but yesterday I was thinking about what happened about 1 year ago.
One of my friends was about to do an inteview, and one of the tasks before the "personal" interview, was to implement a simple web service using .NET framework: even without any knwoledge of web services and what it's behind, I managed to accomplish that task (and my friend has been hired!)... I don't tell you what such a disaster has been my attempts in JAVA (I dominated them, but how hard!).

And now I think: the aim of every enterprise is to make profit, so what if I managed to accomplish the same task in half the time?
Reading a book about ASP.NET lend from a friend (a +1000 pages book, from the bases to the most advanced features [reference]), I succeed to understand all topics presented...I haven't implemented anything yet, but now I know .NET Framework makes things easier.
Its learning curve is faster, maybe you need a greater effort at the beginning: that's different in JAVA, infact coming from a general C/C++ knowledge and XML undestanding, you can easily implement a JSP that print out "Hello World!", but as you proceed on the road of J2EE consciousnees, things gets harder and harder.
Instead in .NET you need some time to orientate yourself about technologies used (the base language, C#, web services, web page layout creation, DBs, and so on), but as soon as you have enough knowledge of the framework, building an application will be straighforward.

And moreover, one of the greatest benefits of using JAVA is its portability and platform-indipendence, but I always programmed in Windows, using Microsoft ways of representing files, web servers configured in "windows-mode", so all efforts may have been useless, and learning .NET I would have found time to learn anything else, and increse productivity.

Ending, .NET and J2EE offers the same kind of malicious machineries and the first seems to be more programmer friendly.
I wonder if you, the reader, leaving away every "f**ck the system" ideology and open source nerdology , agree with me.
I just hope that I haven't wasted my time...
And so I ask: where do you think is the future of component programming?

Monday, January 28, 2008

[JAVA] Easy management of XML content (Serializing, Deserializing, XSD ing, XSL ing)

problem: actually it is not a problem, it si more likely a collection of tips to manage a DOM document (using Xerces and Xalan open source library from Apache Group): parsing an XML file, serialization and deserialization, aplying an XSL or validating against a defined XSD. You don't need a degree to discover how to do it, but as you have thousands of thousands of classes inside that libraries, without Google I found it hard.

solution: ok, where is the beginning?
What we'll do first is a simple reading from a text file. Xerces gives you a simple way to open an XML file, by using:
 private Document parseXmlFromFile(String filePath){

try {
//get the factory
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();

//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();

//parse using builder to get DOM representation
//of the XML file
return db.parse(
filePath);

}catch(IOException ioe) {
ioe.printStackTrace();
}
}
Sometimes anyway you have only a string that contains your XML data (maybe got from an HTTP request or a webservice), and you just want to deserialize it into a Document object:

private Document deserialize(String xml)
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader reader = new StringReader(xml);
InputSource source = new InputSource(reader);
return db.parse(source);
}
catch(Exception e){
e.printStackTrace();
}

}

Ok, I know, it's quite the same of the previous code; the only difference is that now you take your data from a StringReader object rather then from the path of the file. I also have added two properties to the builder, one that ignores comments and the other that ignores useless white spaces (for example formatting spaces).

And what if you want to obtain the string equivalent to the content of a Document? Don't be scared, there is a solution:

private String serialize(Document document){
try {
OutputFormat format = new OutputFormat(document);
StringWriter stringOut = new StringWriter();
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer();
serial.serialize(document.getDocumentElement());
return stringOut.toString();

} catch (Exception e) {
e.printStackTrace();
}
}

...and voilà your string is right there!

And what if you need to apply an XSL style sheet to your wonderfull XML ?
No way of trouble, just use this simple code:

public String transform(Document xml, String urlSchema){
try{

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer =
tFactory.newTransformer(new StreamSource(urlSchema));

StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(xml),
new StreamResult(writer));


return writer.toString();
}
catch(Exception e){
e.printStackTrace();
}
}

Ending dear fellow butcher, if you want to validate your XML data against a XSD definition, just copy&paste this code:

public boolean validate(String xml, String schemaURL) {
try {
String schemaLang = "http://www.w3.org/2001/XMLSchema";
SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
Schema schema = factory.newSchema(new StreamSource(schemaURL));
Validator validator = schema.newValidator();
StringReader reader = new StringReader(xml);
validator.validate(new StreamSource(reader));

return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

This method returns true/false depending of the result of the the validation process; moreover you can catch, outside the method, the exception (if it is a DOMParserException or a SAXParseException) to have an idea of why xml content is not valid.

I showed how to use DOM Classes to manage the whole XML content of a specific file/string, without discovering all the whys and becauses of each line; I'm pretty sure you can find several other ways to do what I coded but this fits my usual needs.

Monday, September 10, 2007

[Java, Maven, Jetspeed-2] Can't build Jetspeed-2 with maven, settings.xml getting me bored

Problem: Maven2 doesn't build my Jetspeed-2 portal with a strange cast exception
Solution: Check %USERPROFILE%/.m2/settings.xml file position

My boss went in my office and said "Ok Scuffia, your time has come! With the mighty power of the holy Apache Ant you will package your application, no matter how nor why, but I want a spelled Ant script that builds all your application need to run!" .

First of all my application is composed by:
  • a Core (a simple Java Library with about 30 classes) that uses 4 other libraries (mainly XML Parsers, loggers, DB accessors)
  • A portal container (Jetspeed-2)
  • At the moment only one portlet (used to access data)
  • A servlet that is an interface between the Core and the Portlet
  • A web service (using Axis 1.x) that exports Core methods (in practice the same functionality as the servlet)
There were no problems to rule Ant scripts as to build the Core library (with all depencencies and all needed configuration files, like .properties files); as my application need to be held in one folder, I decided to put together Ant and all source folders.

I also decided to use Maven to build Jetspeed-2 and all portlets, bacause all installation scripts were already done (building, linking, db creating, and resource copying); Maven uses a local repository, in wich it stores downloaded libraries (from servers whose URL are in the configuration file); as my boss needs a completly "offline" installation, all libraries are supposed to be fully downloaded and ready to be linked. Obiously Maven has its configuration file (under ./mavenFolder/conf/settings.xml) in wich you can set the path to the repository: moreover you can choose a configuration different for each user of your OS (Win XP in my case), putting each configuration file inside %USERPROFILE%/.m2/, wich "overwrites" general settings.

Building the portal was as simple as writing:
mvn -P tomcat,min
that stated to build the portal with the underneath web server Tomcat, with just the portal itself and only the administrative portlets (that help administrator to manage users and portlets).

I was so happy that I knew all to do, that I thought to end the work in just 1 working day (inlcuding neverending breaks!)...but It was not so simple!
Each time I tried to build, I got the same error:
D:\GAPWORKSPACE\jetspeed-portal\gapportal\
etc\build.xml:502: java.lang.ClassCast Exception:
org.apache.maven.usability.MojoExecutionExceptionDiagnoser
cannot be cast to
org.apache.maven.usability.diagnostics.ErrorDiagnoser

It lasted for about 3 working days, with my powerlessness: I followed all errors, trying to change code, reading each Maven building script (O.O), when I saw that, as I was using only ./mavenFolder/conf/settings.xml file because I wanted to have the whole stuff inside the same directory and no other file elsewhere, Maven tried to use anyway %USERPROFILE%/.m2/ directory and, only for some libraries, were looking for them in %USERPROFILE%/.m2/repository/, in wich actually there was nothing...
THIS TOOK ME 3 FUCKING DAYS!!!!!
So, although it is not so nice, I decided to have a copy of settings.xml in the user directory, so maven always knows where the repoository is.
And that's the end of my asshole tragedy.

.Net Butchering (and JAVA messes)

Friday, September 7, 2007

[Java] Welcome to this new incredibly epic blog

Although it is not properly a Java blog I, in the person of Scuffia, will post my own Java defeats!
Moreover I take advantage of this room to thank Giovacchia for this opportunity and I hope to improove my english...that is a very f*****g hard goal!
Goodbye!