Monday, October 29, 2007

Java : Creating a date

The old format was

Date date = new Date ("2007/10/29") but that has long been deprecated.

Use this:



DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd");
try
{
Date date = dfm.parse("1990-01-01");
}

catch (Exception e)
{
System.out.println("Date exception is: " + e.getMessage());
e.printStackTrace();
}



If you wanted to add the time:



DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try
{
Date date = dfm.parse("1990-01-01 12:40:00");
}

catch (Exception e)
{
System.out.println("Date exception is: " + e.getMessage());
e.printStackTrace();
}



Enjoy!

Thursday, September 06, 2007

Java : Disassembler

The standard javap will do this for you.

javap -help shows all the commands.

For class x, javap - c x (Note: Don't type x.class - just type x) will decompile the class for you and display methods like:

public int getUserType();
public void setUserType(int);

Enjoy!

Wednesday, August 15, 2007

Eclipse : Matching brackets

Clicking to the right of a bracket shows the matching one in a "box".

To toggle between the two, use Cntl / Shift / P.

Enjoy!

Eclipse : Running command line to EJB inside Eclipse

I'm running Eclipse Europa (the J2EE package).

See the previous post about running a command line Java program inside a DOS box and the million paths etc. you have to set up.

It's a lot easier to run it inside Eclipse by right clicking the application in the Package Explorer and selecting "Run As" / "Java Application".

(Note : JBoss needs to be started first by selecting the Server view inside the J2EE perspective , right click, "Start".)

You get this error in the console:

Need to specify class name in environment or system property, or as an
applet parameter, or in an application resource file: java.naming.factory.initial


As per the previous post, the solution then was to add a path to the jndi.properties file:

set CLASSPATH=C:\JBoss-4.0.5.GA\server\default\conf;%CLASSPATH%

In Eclipse, however, go "Project Properties" / "Run/Debug Settings" / select the launch configuration / "Edit" / click on the "Classpath" tab / "Advanced: / "Add External Folder" and then browse to the jndi.properties folder as above and "OK" out.

That's it - Eclipse takes care of all the other stuff!

Enjoy!

Tuesday, August 14, 2007

Java : Find which class is in which jar file

It's a real pain!

You keep getting ClassNotDefined and you have hundreds of Jar files and it takes ages to manually search them all.

The solution is to use Jarscan.

There's also a web version on the same page.

So e.g.

java -jar jarscan.jar -dir C:\JBoss-4.0.5.GA -class SafeClone

returns (for JBoss):

searching these jarfiles now ....

===============================================
Found: SafeClone
Class: org.jboss.serial.objectmetamodel.safecloning.SafeClone
Package: org.jboss.serial.objectmetamodel.safecloning
Library Name: jboss-serialization.jar
Library Path: C:\JBoss-4.0.5.GA\client\jboss-serialization.jar
===============================================

===============================================
Found: SafeClone
Class: org.jboss.serial.objectmetamodel.safecloning.SafeClone
Package: org.jboss.serial.objectmetamodel.safecloning
Library Name: jbossall-client.jar
Library Path: C:\JBoss-4.0.5.GA\client\jbossall-client.jar
===============================================

===============================================
Found: SafeClone
Class: org.jboss.serial.objectmetamodel.safecloning.SafeClone
Package: org.jboss.serial.objectmetamodel.safecloning
Library Name: jboss-serialization.jar
Library Path: C:\JBoss-4.0.5.GA\server\default\lib\jboss-serialization.jar
===============================================

Search took: 10360 milliseconds.


Neat!

Enjoy!

EJB : Running a command line client to a JBoss EJB

The EJB example running on JBoss is taken from the WTP (Web Tools Project) tutorials here plus XDoclet - all inside Eclipse.

Call the package ejbs.

We have an EJBTestBean:


/**
*
*
* @ejb.interface-method view-type="remote"
*
* @generated
*
* //TODO: Must provide implementation for bean method stub
*/
public String greet(String param) {
return "Hi dude " + param;
}


XDoclet creates all the Home and Util stubs.

Now we want to test this from a Java command line client.

So we create a Java class with a main() method (called CLTestClient):


try
{
EJBTestHome home = ejbs.EJBTestUtil.getHome();
EJBTest service = home.create();
String result = service.greet("Tom");
System.out.println();
System.out.println("Result is " + result);
}

catch (Exception e)
{
System.out.println();
System.out.println("Exception " + e.getMessage());
}


and we want to test from the command line:

java CLTestClient

and we get ClassNotDefined all over the place.

So we add the EJB files to the CLASSPATH:

set CLASSPATH=C:\JBoss-4.0.5.GA\
server\default\lib\jboss-j2ee.jar;C:\your path\EJBTestClient\build\classes;C:\your path\EJBTestClient\build\classes\ejbs;%CLASSPATH%

Then we get this error:

Need to specify class name in environment or system property, or as an
applet parameter, or in an application resource file: java.naming.factory.initial


The solution is to add a path to the jndi.properties file:

set CLASSPATH=C:\JBoss-4.0.5.GA\server\default\conf;%CLASSPATH%

More ClassNotDefined errors:

set CLASSPATH=C:\JBoss-4.0.5.GA\client\jbossall-client.jar;C:\JBoss-4.0.5.GA\lib\jboss-common.jar;C:\JBoss-4.0.5.GA\server\default\lib\jboss.jar;C:\JBoss-4.0.5.GA\client\jnp-client.jar;C:\JBoss-4.0.5.GA\client\jboss-client.jar;%CLASSPATH%

and finally:

java CLTestClient

returns:

Result is Hi dude Tom

By the way, if you wanted to do this from a browser inside a jsp page:


LT%@page import="ejbs.EJBTestUtil"%GT
LThtmlGT
LTheadGT
LTtitleGTEJBWebTestLT/titleGT
LT/headGT
LTbodyGT
LT%
ejbs.EJBTest tb = null;

try
{
ejbs.EJBTestHome home = EJBTestUtil.getHome();
tb = home.create();
}

catch(Exception exception)
{

}

%GT

LTbGTLT%= tb.greet("Tom") %GTLT/bGT

LT/bodyGT
LT/htmlGT




Where LT = "less than" and GT = "greater than".

Enjoy!

Tuesday, July 24, 2007

Visual Studio : Using a xsd to validate / create xml

With VS 2005, there's a neat feature which allows you to validate / check a xml document based on a xsd.

Load the xml document (or the bare bones) and then click the "Properties" tab on the RHS (where "Solution Explorer" is). You'll see a "schema" entry. Point this to the xsd that describes the xml.

You might need to use "file:// ... " if the file is on your hard drive.

Now you will see that all the errors are highlighted in the usual way and also Intelli-sense guides you as you build up the xml.

Enjoy!

Wednesday, July 18, 2007

Misc : Cracking XP Administrator passwords

Check out this site:

http://www.loginrecovery.com/

"Login Recovery is a service to reveal user names and recover passwords for Windows NT, 2000, XP, 2003 and Vista. As long as you have physical access to the computer, your passwords can be recovered

By following three simple steps, over 98.5% of passwords can be recovered within less than ten minutes. This service does not overwrite passwords, it does not write anything to the hard drive, it does not alter the computer in any way.

For immediate access to decrypted passwords, the priority service is available for GBP 12.95 + VAT (£15.22) (approx USD 25 or EUR 20). Alternatively a free service is available by waiting up to 48 hours (One free request every three months)."


Works like a charm as long as you don't mind waiting 48 hours!

Enjoy!

Thursday, July 05, 2007

DOS 'grep' equivalent - the find command

The previous post talked about finding which ports were open using the netstat command.

But you still have to scan the output manually to find the port you are looking for.

In the Unix world you could simply use grep and pipe the output to it.

In the DOS world, you can use find.


help find

Searches for a text string in a file or files.

FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]

/V Displays all lines NOT containing the specified string.
/C Displays only the count of lines containing the string.
/N Displays line numbers with the displayed lines.
/I Ignores the case of characters when searching for the string.
/OFF[LINE] Do not skip files with offline attribute set.
"string" Specifies the text string to find.
[drive:][path]filename
Specifies a file or files to search.

If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.



So to find if port 86 was open, use:

netstat -ano | find /i "86"

and the filtered output would something like:



TCP 0.0.0.0:86 0.0.0.0:0 LISTENING 728
UDP 0.0.0.0:86 *:* 728



Enjoy!

Which XP ports are open?

Don't know how many times I see the message "Error - port 8080 already in use" or some such.

So how do you find whose using that port. One answer is netstat which runs in a cmd window:


Displays protocol statistics and current TCP/IP network connections.

NETSTAT [-a] [-b] [-e] [-n] [-o] [-p proto] [-r] [-s] [-v] [interval]

-a Displays all connections and listening ports.
-b Displays the executable involved in creating each connection or
listening port. In some cases well-known executables host
multiple independent components, and in these cases the
sequence of components involved in creating the connection
or listening port is displayed. In this case the executable
name is in [] at the bottom, on top is the component it called,
and so forth until TCP/IP was reached. Note that this option
can be time-consuming and will fail unless you have sufficient
permissions.
-e Displays Ethernet statistics. This may be combined with the -s
option.
-n Displays addresses and port numbers in numerical form.
-o Displays the owning process ID associated with each connection.
-p proto Shows connections for the protocol specified by proto; proto
may be any of: TCP, UDP, TCPv6, or UDPv6. If used with the -s
option to display per-protocol statistics, proto may be any of:
IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.
-r Displays the routing table.
-s Displays per-protocol statistics. By default, statistics are
shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;
the -p option may be used to specify a subset of the default.
-v When used in conjunction with -b, will display sequence of
components involved in creating the connection or listening
port for all executables.
interval Redisplays selected statistics, pausing interval seconds
between each display. Press CTRL+C to stop redisplaying
statistics. If omitted, netstat will print the current
configuration information once.



so netstat -ano gives



Active Connections

Proto Local Address Foreign Address State PID
TCP 0.0.0.0:86 0.0.0.0:0 LISTENING 728
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1192
TCP 0.0.0.0:261 0.0.0.0:0 LISTENING 3684
...





You can look up the PID using Task Manager or (even better) using sysinternals Process Explorer (which you can get from here).

Their version of netstat is TCPView (which you can get from here).

Enjoy!

Friday, June 01, 2007

Unix : DOS format on a Unix box

Quite often I use an IDE on Windows to edit the file and then FTP the file to a Linux box. (Mainly because vi sucks major league, big time!)

Anyway, the Unix compiler sometimes complains about rogue characters. An easy way to fix this is to use the

dos2unix

utility which reads the text file and converts to Unix format.

Enjoy!

ASP : Using LiveHTTPHeaders to monitor what's being sent

Quite often, you need to see what a web site is sending from the ASP pages. You could use something like Ethereal but if you are a Firefox fan, an easy way is to use LiveHTTPHeaders.

You can get the LiveHTTPHeaders Firefox extension from here.

Then install it.

Click Firefox Tools / LiveHTTPHeaders.

If you want to limit the URL's that are monitored and you are a dab hand at regular expressions, then click Config tab / Filter URL's with regexp

Close the Config tab

From the Firefox menu, click Select View / Sidebar / LiveHTTPHeaders (or alternatively click Alt L)

Open a page from the website you wish to monitor. What is displayed is what is being sent to the server.

Enjoy!

Tuesday, May 01, 2007

Another reading list

Came across this reading list here.

This one comes from John Brewer.

Enjoy!

ASP : Getting configuration variables from web.config

Instead of hard-coding these in the .cs code, you could use the following:

string inputFile = ConfigurationManager.AppSettings.Get("FileLoc");

In the web.config, in the appSettings section, enter something like:

LSBadd key="FileLoc" value="C:\somewhere\File.xml" /RSB

where:

LSB = Left square bracket
RSB = Right square bracket

You can also do this from Visual Studio when viewing an .aspx page. Click Website / ASP.NET configuration and type in the entries there.

Enjoy!

ASP : Creating Javascript on the server side

Javascript is normally created in the HTML file but it can be created on the server side.

e.g. the script to open another window could be:


string exampleScript =
"LSBscript language='javascript'RSB\n" +
"window.open ('http://some url', '_blank', " +
"'scrollbars=yes,resizable=yes,status=yes" +
",toolbar=no,menubar=yes,location=no" +
",width=screen.availWidth" +
",height=screen.availHeight" +
",screenX=0,screenY=0,top=0,left=0');\n" +
"LSB/scriptRSB";

ClientScript.RegisterStartupScript(typeof(Page), "ExampleScript", exampleScript);


where:

LSB = Left square bracket
RSB = Right square bracket

Enjoy!

C# : Creating dates

The simplest way is to use:


string thisDate = "1990-01-01";
DateTime datetime = DateTime.Parse (thisDate);


Enjoy!

Friday, April 27, 2007

Recommended reading for developers

Another list from "Coding Horror" - programming and human factors by Jeff Atwood.

Blog here.

Reading list here.

Enjoy!

Thursday, April 19, 2007

ASP : Deploying web site from Visual Studio 5

From the ASP solution,

File / Add / New Project / Setup and Deployment / Web Setup Project

Type in a name and enter "OK".

The entry will now be in "Solution Explorer". Right-click and select "Add / Project Output". Ensure "Content Files" is selected and click "OK".

Now we want to build it. Right-click again and select build. This will create the .msi file in the directory.

Enjoy!

SOAP : Asynchronous web service

Had to implement an asynchronous web service which did not need to be real-time so no response was needed.

Had me a bit puzzled until I realised that a web service can return void!

i.e. in ASP:

[WebMethod]
public void webMethod(Some parameter)

compiles and runs no problem.

So what does it return?

The WSDL shows:


s:element name="webMethodResponse"
s:complexType /
/s:element


So it actually returns null!

Enjoy!

Wednesday, April 11, 2007

Windows : Getting a file list

Often need to put a list of files into a Word document or some such.

One way is to activate the command prompt (DOS box), navigate to the required directory and type:

dir /ON /B > dir.txt

The /ON option lists the files in alphabetic order. Further options are:


/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order


The /B option uses a bare format (i.e. no heading information or summary).

The pipe option (>) sends the results to a file called dir.txt in the current directory.

From here, it can be cut & pasted into the Word document.

BTW, if you ever need to get information about a DOS command, type:

help "command"

e.g. help dir

Enjoy!

Unix : sum

Often transfer large files around using FTP or whatever e.g. ear and war files and it's useful to see if they were transferred without error.

sum is a useful utility to use for this.

It calculates and prints a 16-bit checksum for the named file and the number of 512-byte blocks in the file.


sum abcd.ear
05612 25680


Enjoy!

Monday, March 19, 2007

SOAP : WSCF - Web Services Contract First

"Contract first" involves creating the WSDL first and then using that to generate the code. There aren't many tools to do this.

Essentially, this approach involves modelling the messages, data and interfaces at the start and then publishing them as a contract before coding the implementation begins. Typically, modelling of the data and messages is done using a XML Schema (i.e. XSD files) and the contract is formalised using the Web Services Description Language (WSDL files).

thinktecture offer their free tool to do this which is nicely integrated with Visual Studio (2003 and 2005) and also allows a command line interface.

Get it from here.

Documentation and walk-through here.

Two MSDN articles which cover this are:

here and

here

Enjoy!

Monday, February 26, 2007

C# : Predefining an array

The classic way of creating an array is:


Document[] doc = new Document[2];
doc[0] = new Document();
doc[0].code = "ABC";
doc[1] = new Document();
doc[1].code = "DEF";


but a more elegant way is:


Document doc1 = new Document();
doc1.code = "ABC";
Document doc2 = new Document();
doc2.code = "DEF";
? = new Document[] {doc1, doc2};


Enjoy!

Tuesday, January 23, 2007

C# : XML in a C# string

Note: "Left quote" replaced by #, "Right quote" replaced by ^

How do you do this? It has quotes, slashes etc. e.g.

string zzz = "#employees xsi="http://www.w3.org/2001/XMLSchema-instance"^#employee-record^#employee-id^00001#/EMPLOYEE-ID^#employee-from^01 10 2006#/EMPLOYEE-FROM^#employee-to^01 11 2006#/EMPLOYEE-TO^#employee^#employee-id^00001#/EMPLOYEE-ID^#employee-name^Washington#/EMPLOYEE-NAME^#employee-firstname^George#/EMPLOYEE-FIRSTNAME^#employee-dob^01 01 1930#/EMPLOYEE-DOB^#/employee^#/EMPLOYEE-RECORD^#/employees^";

won't compile.

You could put a "@" in front to make it a verbatim string literal but it still won't compile.

The trick is to make each quote (") a double quote ("") e.g.

string zzz = @"#employees xsi=""^#employee-record^#employee-id^00001#/EMPLOYEE-ID^#employee-from^01 10 2006#/EMPLOYEE-FROM^#employee-to^01 11 2006#/EMPLOYEE-TO^#employee^#employee-id^00001#/EMPLOYEE-ID^#employee-name^Washington#/EMPLOYEE-NAME^#employee-firstname^George#/EMPLOYEE-FIRSTNAME^#employee-dob^01 01 1930#/EMPLOYEE-DOB^#/employee^#/EMPLOYEE-RECORD^#/employees^";

which does compile.

Enjoy!

Thursday, January 11, 2007

Windows XP : cisvc.exe hogs the hard drive

My PC randomly just sat there with the hard disk light on but I wasn't doing anything - plus it was dog-slow.

Using the excellent Process Explorer, I discovered that the "cisvc.exe" program was the cause of the problem. This is part of indexing services.

My first solution was simply to suspend this via Process Explorer. (Right click on cisvc.exe). This helped but I had to do it every time on start-up.

So I googled and found one possible solution:

My Computer - right click on the C: drive - Properties - uncheck "Allow Indexing Service to index this disk for fast file searching" in the General tab.

This helped but the problem still remained.

Then I found another, better solution:

Control panel - Administrative Tools - Computer Management - expand "Services and Applications" - right-click on "Indexing Service" - "All Tasks -> Tune Performance". Then decide what level you want.

Enjoy!