Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, May 06, 2014

Azure : Deploying a Java web site to Azure

Well, who would ever think that the words "Azure" and "Java" would be used in the same sentence?

I'm not talking about the Azure VM here; rather the Azure web site option.

As Mrs. Beaton would say "First catch your rabbit". For Java, this becomes "First catch your .war file".

You can create a simple Java web site in either Eclipse or NetBeans - whatever floats your boat.

Work through the following documentation:

Get started with Azure web sites and Java

Adding an application to your Java web site on Azure

I used the "Create a Java web site using the Azure configuration UI" option.

OK, but when you display the web site URL, you get the "This Java based application has been successfully created". So where's my index.jsp?

From the dashboard of the Azure web site, you'll see the FTP address. I use FileZilla.

Before you can use this, you have to set the credentials. There's a link under "Quick Glance" called "Reset your deployment credentials". So set them.

Assume your web site is called MyJavaWebSite.

So to get FileZilla to work, you use the FTP URL from the dashboard page, your user name is:

MyJavaWebSite\username

and the password is whatever you chose.

On the LHS menu, navigate to your war file. On the RHS, navigate to:

/site/wwwroot/webapps

Copy the war file over.

Now navigate to the actual Azure web site URL. Still shows the canned screen.

So append  /MyJavaWebSite/index.jsp to the URL.

Bingo.

Enjoy!

Friday, June 07, 2013

WIF : Is there a Java Equivalent?


Been asked this question a million times and now I have an answer of sorts.

If by WIF, you mean WS-Federation, then mosey on over to:

Apache CXF Fediz: An Open-Source Web Security Framework
 
This supports:
  • WS-Federation 1.0/1.1/1.2
  • SAML 1.1/2.0 Tokens
  • Custom token support
  • Publish WS-Federation Metadata document
  • Role information encoded as AttributeStatement in SAML 1.1/2.0 tokens
  • Claims information provided by FederationPrincipal interface
However, if by WIF by mean the FAM / SAM / CAM functionality then the jury is still out.

There is no direct Java replacement library for WIF.

Update:

Came across  auth10-java.
  • This library speaks the WS-Federation protocol and SAML 1.1 and 2.0 tokens. It interops fine with Microsoft-related products like ADFS, Windows Azure Active Directory and Windows Identity Foundation. 
Update:

Also  OIOSAML.

Enjoy!

Tuesday, November 23, 2010

Netbeans : Providing command line arguments inside Netbeans

I write a lot of command line Netbeans (6.9) Java programs. A lot of them take command line arguments e.g.


java Program Option1 Option2


and you access them from "String[] args".

When you are running inside Netbeans, you need to provide the arguments by:

Right click the project / Properties / Run / Arguments

If you right click the Java file you are testing (the Main class) and select "Run File" the program runs but ignores the configured arguments.

To get around this, you have to right click the project and select "Run".

Enjoy!

Java : Checking if environment variables are valid

Has a few problems with environment variables and I couldn't find a utility that would check them for me e.g. checking if all the entries in my PATH environment variable were valid.

So I rolled my own:


public class CheckEnv {

/**
* @param args the command line arguments
*/
static String envVar = "";
static String envValue = "";
static String envValueStrings[];
static String envValueString = "";
static boolean valid = false;

public static void main(String[] args) {
// TODO code application logic here

if (args.length < 1) {
System.out.println("\nUsage is 'java -jar CheckEnv.jar '");
System.out.println();
System.out.println(" e.g. 'java -jar CheckEnv.jar PATH'");
System.out.println(" 'java -jar CheckEnv.jar CLASSPATH'");
System.out.println(" 'java -jar CheckEnv.jar INCLUDE'");
System.out.println(" 'java -jar CheckEnv.jar LIB'");
System.exit(1);
}

envVar = args[0];

envValue = System.getenv(envVar);

System.out.println ("\nChecking for environment variable " + envVar + "\n");

if (envValue == null)
{
System.out.println ("Environment variable " + envVar + " doesn't exist");
System.exit(1);
}

envValueStrings = envValue.split(";");

for (int i = 0; i < envValueStrings.length; i++) {
envValueString = envValueStrings[i];

System.out.print("Checking " + envValueString + " ");

File file = new File(envValueString);
valid = file.exists();

if (valid) {
System.out.println("- variable exists");
} else {
System.out.println("- variable does not exist : WARNING");
}

}
}
}



Usage is 'java -jar CheckEnv.jar '

e.g. 'java -jar CheckEnv.jar PATH'
'java -jar CheckEnv.jar CLASSPATH'
'java -jar CheckEnv.jar INCLUDE'
'java -jar CheckEnv.jar LIB'


The output looks like e.g.


Checking C:\Program Files\Java\jdk1.6.0_22\jre\bin - variable exists
Checking C:\Program Files\Reflection - variable exists
Checking C:\Perl\bin\ - variable exists


Enjoy!

Tuesday, June 22, 2010

Java : FizzBuzz

I regularly read Jeff Atwood's blog and renewed my acquaintance for an old post: Why Can't Programmers.. Program?.

It talks about the Fizz-Buzz question i.e.

"Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". "

So I took up the challenge and knocked this out in Java using Netbeans in about 4 minutes.


for (int i = 1; i < 101; i++)
{
int j = i % 3;
int k = i % 5;
System.out.print("Number is " + i);
if (j == 0 && k == 0)
{
System.out.print(" FizzBuzz ");
}
else
{
if (j == 0)
System.out.print(" Fizz ");
if (k == 0)
System.out.print(" Buzz ");
}

System.out.println();
}


So there!

Enjoy!

Wednesday, March 10, 2010

Preventing Cross-Site scripting in Java

You can read about XSS here: Cross-site scripting

Been trying to figure out how to disable it using html encoding and what Java libraries are available.

OWASP's site has an article on this: http://www.owasp.org/index.php/How_to_perform_HTML_entity_encoding_in_Java

To quote:

"Injection attacks rely on the fact that interpreters take data and execute it as commands. If an attacker can modify the data that's sent to an interpreter, they may be able to make it misbehave. One way to help prevent this from happening is to encode the attacker's data in such a way that the interpreter will not get confused. HTML entity encoding is just such an encoding mechanism for many interpreters."

There are two ways to encode the data viz. entity reference and numeric reference:

From Wikipedia:
http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

An entity reference uses the "&" symbol:

& quot; (double) quotation mark
& amp; ampersand
& apos; apostrophe (= apostrophe-quote)
& lt; less-than sign
& gt; greater-than sign

A numeric character reference refers to a character by its Universal Character Set/Unicode code point, and uses the format

&#nnnn;
or

&#xhhhh;
where nnnn is the code point in decimal form, and hhhh is the code point in hexadecimal form

Although the OWASP article mentioned above talks about entity references, the code sample enclosed actually uses numeric entity encoding i.e.

<script></script>

encodes as:

&hash60;script&hash62;&hash60;&hash47;script&hash62;

where "hash" = the "#" character

Some further research around this issue leads to:
AntiXSS for Java which is a port to Java of the Microsoft Anti-Cross Site Scripting (AntiXSS) library for .NET applications

and to:
Open Web Application Security Project (OWASP)

which has a:
Enterprise Security API (ESAPI)

Click on the "Java EE" tab. There are two ways to invoke the functionality. One uses the classes directly:



import org.owasp.esapi.codecs.HTMLEntityCodec;

public static StringBuilder esapiCodecHtml (String s)
{
HTMLEntityCodec hec = new HTMLEntityCodec();
StringBuilder b = new StringBuilder(s.length());
char[] immune = { ',', '.', '-', '_', ' ' };
String returnStr = "";

String clean = ESAPI.encoder().canonicalize(s);
System.out.println ("Cleaned result is " + clean);

for (int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
returnStr = hec.encodeCharacter(immune, ch);
b.append(returnStr);
}

return b;
}


Note: ESAPI canonicalizes input before validation to prevent bypassing filters with encoded attacks. Failure to canonicalize input is a very common mistake when implementing validation schemes. Canonicalization is automatic when using the ESAPI Validator.

and the other uses the wrapper:



import org.owasp.esapi.ESAPI;

public static String esapiEncodeForHTML (String s)
{
String returnStr = "";

String clean = ESAPI.encoder().canonicalize(s);
System.out.println ("Cleaned result is " + clean);
returnStr = ESAPI.encoder().encodeForHTML(s);

return returnStr;
}


They both convert <script></script> to andlt;scriptandgt;andlt;&hashx2f;scriptandgt;

where "and" is the "&" character.

Interestingly, this is a combination of both reference types.

Just to note: The example at the top converted the "/" to &hash47; whereas ESAPI converts it to &hashx2f; This is because one is decimal and one is hex!

Asides:

Refer to:

XSS (Cross Site Scripting) Prevention Cheat Sheet

Refer to my SO question:

Java - XSS - HTML encoding - Character entity reference vs. Numeric entity reference

Enjoy!

Monday, February 08, 2010

Java : Sending a HTTP OPTIONS command

The HTTP OPTIONS command is documented here.

I needed to do this programmatically and thought I would document the code.

 
import java.net.HttpURLConnection;
import java.net.URL;

...

try {
String type = "text/plain;charset=UTF-8";
URL url = new URL("http://xxx/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoOutput(true);
conn.setRequestMethod("OPTIONS");
conn.setRequestProperty("Content-Type", type);

System.out.println(String.format("HTTP %d: %s",
conn.getResponseCode(), conn.getResponseMessage()));

for(String header : conn.getHeaderFields().keySet() ){
System.out.println(String.format("%s : %s",
header, conn.getHeaderFields().get(header)));
}

String rMessage = conn.getResponseMessage();
System.out.println ("Response " + rMessage);

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


Running this against Sun Java System Application Server 9.1 returns:

HTTP 200: OK
X-Powered-By : [Servlet/2.5]
Content-Length : [0]
Allow : [GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS]
null : [HTTP/1.1 200 OK]
Date : [Sun, 07 Feb 2010 19:11:57 GMT]
Server : [Sun Java System Application Server 9.1]
Content-Type : [text/html; charset=iso-8859-1]
Response OK


This sends something like "OPTIONS / HTTP/1.0". There is another version of the command that sends "OPTIONS * HTTP/1.0".

The "*" is actually part of the URI. However, "java.net.HttpURLConnection" has no facility which allows this. Some research suggests that this could be done by using "Apache Commons HttpClient".

Enjoy!

Thursday, January 28, 2010

Metro : Printing / dumping out the contents of a SOAP packet

I've used Metro a lot and I've always battled to have decent logging.

In the web service, I normally log all the inputs and the outputs and all the exceptions. Wouldn't it be easier if you could just log all the requests and responses which would guarantee that you had all the information all of the time?

I just couldn't figure out how.

Until I came across "MessageDumpingFeature". You find this in the Glassfish \lib directory in the webservices-rt.jar file.

If you've generated web services using Metro, you find the code below very familiar. All you really need to do is replace:

service.getWebServiceName();

with

service.getWebServiceName(messageDumper);

The code looks like:

 

import com.sun.xml.ws.assembler.MessageDumpingFeature;

... snip ...

messageDumper = new MessageDumpingFeature();

ServiceName service = new ServiceName();
WebServiceName port = service.getWebServiceName(messageDumper);
// TODO initialize WS operation arguments here
java.lang.String xxx = "yyy";
java.lang.String yyy = "zzz"
// TODO process result here
ResultName result = port.doWebService(xxx, yyy);

String request = messageDumper.nextMessage();
String response = messageDumper.nextMessage();

System.out.println (request);
System.out.println (response);

... snip ...

} catch (Exception ex) {
String request = messageDumper.nextMessage();
String response = messageDumper.nextMessage();

System.out.println (request);
System.out.println (response);
}


It prints out both normal responses and SOAP Faults.

A request would be dumped like:

 
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:doWebService xmlns:ns2="http://namespace/">
<xxx>yyy</xxx>
<yyy>zzz</yyy>
</ns2:doWebService>
</S:Body>
</S:Envelope>


A valid response would be dumped like:

 
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:doWebService xmlns:ns2="http://namespace/">
<return>
<aaa>bbb</aaa>
<bbb>ccc</bbb>
</return>
</ns2:doWebService>
</S:Body>
</S:Envelope>


A SOAP fault would be dumped like:

 
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
<faultcode>S:Server</faultcode>
<faultstring>SomeErrorString</faultstring>
<detail>
<ns2:SomeException xmlns:ns2="http://namespace/">
<message>SomeErrorMessage</message>
</ns2:SomeException>
</detail>
</S:Fault>
</S:Body>
</S:Envelope>


Of course, instead of dumping out the request / response, it could be written to a file instead.

Enjoy!

Thursday, January 07, 2010

SOAPUI : Adding a wsdl

Assume a WSDL like:

http://host:port/ApplicationServer/Service

Sometimes when you are adding a WSDL like the above you get an error:

SOAPUIException: Error inporting wsdl

Try qualifying the URL i.e.

http://host:port/ApplicationServer/Service?wsdl

Enjoy!

Wednesday, January 06, 2010

SOAPUI : NoClassDefFoundError

Using SOAPUI 3.0.1 to test web services created using Netbeans, JAX-WS and Metro.

When I try and run the TestRunner, I get:


java.lang.NoClassDefFoundError: org/apache/commons/cli/CommandLineParser


My solution was to edit soapui.bat (in the /bin directory) and add:

set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_16

at the top.

Then, instead of running soapui.exe from the desktop shortcut, I open a command prompt and run soapui.bat from there manually.

Problem solved.

Enjoy!

Tuesday, January 05, 2010

Metro : Sniffing the traffic with JAX-WS, Netbeans and Metro

I often use Fiddler to view / log browser traffic.

From the web site: "Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP(S) traffic, set breakpoints, and "fiddle" with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language."

However, it doesn't work when you want to look at Java web service (SOAP) traffic generated by the JAX-WS support in Netbeans (i.e. Metro).

I have a number of command line tools that I use to generate various types of traffic with a command line like:


java -jar SomeProgram.jar


To get Fiddler to work, you need to change the command line to:


java -DproxySet=true -DproxyHost=127.0.0.1 -DproxyPort=8888 -jar SomeProgram.jar


Fiddler uses port 8888 as default.

Enjoy!

Wednesday, June 17, 2009

Eclipse : Debugging web services and servlets

Been playing with this kind of stuff (Eclipse / Tomcat / Axis2 / jsp / servlets) and came across two good links that explain how to do it all!

How to Debug a Web Service?

and

Debugging a servlet with tomcat and Eclipse tutorial.

Enjoy!

Monday, March 16, 2009

Java : Checking version on your PC

Came across a nice feature that does this from the Sun web site.

Verify Java installation

If your installation is out-of-date, just click on the link and the latest one is installed.

Very handy!

Enjoy!

Thursday, December 04, 2008

Java : Axis2 client and Log4J

I was busy testing a client developed using the Eclipse plug-ins in the previous post.

This came up with the following error message.

log4j:WARN No appenders could be found for logger (org.apache.axis2.description.AxisService).
log4j:WARN Please initialize the log4j system properly.

To set this up inside an Eclipse project:

* Create a new folder in the project called e.g. "log4j".
* Add a file to that folder called log4j.properties which contains something like:


# Set root category priority to INFO and set its only appender to A1
log4j.rootCategory=INFO, A1

# A1 is set to be a ConsoleAppender (writes to system console).
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n


* In the project's "Run Dialog", click on the "Classpath" tab / "Advanced" / "Add folder" and then browse to the "log4j" folder previously created.
* That's it

Enjoy!

Java : Tomcat / Eclipse and Axis2

I needed to develop a Java web service that ran inside Tomcat and used Axis2 as the web server component.

I use Eclipse as my Java IDE and was looking around for plug-ins that would automate and simplify the whole process.

Came across this excellent tutorial - Developing Web Services Using Apache Axis2 Eclipse Plugins - Part 1

This uses two Eclipse plug-ins:

Apache Axis2 Service Archive Generator Wizard and
Apache Axis2 Code Generator Wizard

which generate the proxies and then wrap everything up for deployment to Tomcat.

I highly recommend working through the tutorial and then using that knowledge to develop and deploy your own.

Enjoy!

Java : Finding jars and classes

I seem to spend half my life looking for jars and classes to solve the ubiquitous "Class not defined" problem.

Found this very useful resource which allows you to find which jar files contain the required class and then download them if needed.

Enjoy!

Monday, July 07, 2008

Eclipse : Compiling JVM 1.4 with Eclipse Europa

Eclipse Europa won't work with anything less than JVM 1.5.

But what happens if your client needs a Java 1.4 program? Do you have to download an earlier version of Eclipse?

Actually - no!

You can compile 1.4 programs inside the Europa 1.5 workspace.

Under "Windows - Preferences - Java - Installed JREs", you need to add the path to the 1.4 JVM.

Right click on the 1.4 project.

Under "Properties - Java Build Path - Libraries", ensure that the JRE System Library points to the 1.4 version.

Under "Properties - Java Compiler", click "Enable project specific settings". Set "Compiler compliance level" to 1.4.

That's it.

Enjoy!

Thursday, June 26, 2008

Java : Implementing the C# foreach

This is a common construct:



for (int i = 0; i < "object".length; i++)
{
}



It's messy and in C# you can easily do this far more elegantly with the "foreach" command.

How do you do this in Java?

Use something like e.g. for Reflection fields:



import java.lang.reflect.Field;

Field[] fields = "object".getClass().getDeclaredFields();

for (Field field : fields)
{
...
field[i].getName();
...
}



Enjoy!

Java : Iterating and printing out elements of objects

It's a common problem.

You have an object aa with variables bb, cc and dd and for logging and for debugging purposes, you want to print out the current values of all three so you have:



System.out.println ("value of bb is " + aa.bb);
System.out.println ("value of cc is " + aa.cc);
...



which gets tedious when it's a large object.

Reflection to the rescue!



import java.lang.reflect.Field;

Field[] fields = aa.getClass().getDeclaredFields();

for (int i = 0; i < fields.length; i++)
{
try
{
fields[i].setAccessible(true);
System.out.println (fields[i].getName() + " = " + fields[i].get(xicmd));
}

catch (Exception ex)
{
System.out.println ("Reflection exception = " + ex.getMessage());
}
}



Note that if the variables in the object are declared as "private", this code will throw an exception. Hence the:

setAccessible(true);

method which overrides this.

Enjoy!

Tuesday, June 24, 2008

Eclipse : Starting with a different VM

For various reasons, a PC I use has Java 1.4 installed and the latest Eclipse Europa requires 1.5. I am unable to update the classpath, environment etc. so although 1.5 was installed, Eclipse would not find it.

The solution was to use the command line option:

C:\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.5.0_15\jre\bin\java.exe"

This forces Eclipse to load with the 1.5 VM.

I placed the command above in a shortcut so it's easily accessible from the desktop.

Enjoy!