Tuesday, 18 September 2012

wget HEAD request?

I wanted  to send HTTP HEAD request using wget, is it possible I wondered?

No as it's not wget, but you can do that quite easily by using curl.
curl -I http://www.superuser.com/
Produces this output:
HTTP/1.1 301 Moved Permanently                        
Content-Length: 144                       
Content-Type: text/html; charset=UTF-8     
Location: http://superuser.com/
Date: Sat, 09 Oct 2010 19:11:50 GMT
 
Thanks superuser.com!

Download Java JRE/JDK 7 from shell

File under the heading of Arrgh @#@?#&!

While setting up Tomcat7 from a console window on CENTOS I thought I would download the JDK but you can't because the fhe first step to do so, is to wget (download) the rpm / bin install file?

But as a fellar called Shmuel points out "Well it seems like since Java7, you must accept license agreement on the download page, before you can download java, which make sense. The problem with that is that you cannot accept this license agreement if you are on shell, doing wget."

In summary:
  1. Use Firefox & enable Fiddler to spy on your browser history;
  2. Go and find the down load you need from here;
  3. Accept the licence conditions and start the down;
  4. Then copy from fiddler the URL and most importantly the authorisation parameter which you can just add to your wget url.

Saturday, 8 September 2012

Set up Remote Debugging in Tomcat

Debugging tomcat can be a little but of a pain especially when it is a remote server.
So a quick solution is to use a remote debug option.
A good article on this can be found here (http://en.newinstance.it/2005/10/04/remote-debugging-tomcat-with-eclipse/).
But to add to this information I created a batch file called "runDebug.bat" in the tomcat/bin folder.

The file is:

set JPDA_TRANSPORT=dt_socket
set JPDA_ADDRESS=5050
catalina jpda start

Adding process monitoring

Having set that up you may want to use JConsole to monitor the process.
JConsole comes with the JDK and can be found lurking in the bin folder of your Java installation. 

To enable it with Tomcat you need to mmend your batch file as follows:

set JPDA_TRANSPORT=dt_socket
set JPDA_ADDRESS=5050
set JXM_PORT=5636
set CATALINA_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=%JXM_PORT% -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.hostname=%COMPUTERNAME%/%JXM_PORT%

(NB. Make sure the CATALINA_OPTS is on one line).

A usefull reference on JConsole can be found here (http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html)
 
The next thing you will want to do is add some MBeans to your project. Which can be handled via Annotations.


Friday, 31 August 2012

So which Jar is that class actually in?

When you can't find the JAR that a particular class is in it can be a frustrating experience.
Next time try this code snipit:

    URL url = Dodgy.class.getProtectionDomain().getCodeSource().getLocation();
    logger.debug(url.toString());

Now you should be able to tell where the offending class is!

Saturday, 21 July 2012

The real way to get information about Java Generics

An other bit of plagarism I am afraid but again on a task that I had searche for long and hard.
This is related to the problem of using Java reflection to examine generics. There are may articles  that will tell you is just can't be done at runtime and that the information has disappeared.

Not so!

The following code will show that you can do it:


    class TargetClass
    {
    public List<String> getData() { return null; }
    }
   
    Method method = TargetClass.class.getMethod("getData", null);

    Type returnType = method.getGenericReturnType();

    if(returnType instanceof ParameterizedType){
        ParameterizedType type = (ParameterizedType) returnType;
       
        Type rawType = type.getRawType() ;
        Class rawTypeClass = (Class) rawType ;
       
        Type[] typeArguments = type.getActualTypeArguments();
       
        System.out.println("returnType = " + rawTypeClass );

        if ( List.class.isAssignableFrom(rawTypeClass)  ) System.out.println("Is a list");
       
        for(Type typeArgument : typeArguments){
            Class typeArgClass = (Class) typeArgument;
            System.out.println("typeArgClass = " + typeArgClass);
        }

this prints out:

returnType = interface java.util.List
Is a list
typeArgClass = class java.lang.String

Which is correct!

The article what gets the credit for this is here: Java Reflection: Generics by Jakob Jenkov.

Friday, 20 July 2012

"Gang of Four" design paterns

There are times when you find something on the web and you go are that's useful! There are several reasons for this revelation, in this case it is a reminder that there are good ways and bad ways to write your code.

This article is one of those salutary reminders that we can all do better. So I have posted a link to the here with a short synopsis so I can find it when I need to be reminded.


Design patterns provide solutions to common software design problems. In the case of object-oriented programming, design patterns are generally aimed at solving the problems of object generation and interaction, rather than the larger scale problems of overall software architecture. They give generalised solutions in the form of templates that may be applied to real-world problems.
Design patterns are a powerful tool for software developers. However, they should not be seen as prescriptive specifications for software. It is more important to understand the concepts that design patterns describe, rather than memorising their exact classes, methods and properties. It is also important to apply patterns appropriately. Using the incorrect pattern for a situation or applying a design pattern to a trivial solution can overcomplicate your code and lead to maintainability issues.

The Gang of Four are the authors of the book, "Design Patterns: Elements of Reusable Object-Oriented Software". This important book describes various development techniques and pitfalls in addition to providing twenty-three object-oriented programming design patterns. The four authors were Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.

The full article by , is published at http://www.blackwasp.co.uk/GofPatterns.aspx but the types of patterns he describes are listed here:

Creational Patterns

The first type of design pattern is the creational pattern. Creational patterns provide ways to instantiate single objects or groups of related objects. There are five such patterns:
  • Abstract Factory. The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.
  • Builder. The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.
  • Factory Method. The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.
  • Prototype. The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.
  • Singleton. The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance.

Structural Patterns

The second type of design pattern is the structural pattern. Structural patterns provide a manner to define relationships between classes or objects.
  • Adapter. The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.
  • Bridge. The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.
  • Composite. The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.
  • Decorator. The decorator pattern is used to extend or alter the functionality of objects at run-time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.
  • Facade. The facade pattern is used to define a simplified interface to a more complex subsystem.
  • Flyweight. The flyweight pattern is used to reduce the memory and resource usage for complex models containing many hundreds, thousands or hundreds of thousands of similar objects.
  • Proxy. The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. The proxy provides the same public interface as the underlying subject class, adding a level of indirection by accepting requests from a client object and passing these to the real subject object as necessary.

Tuesday, 19 June 2012

Using Apache-IVY : Missing dependency

This is just in case I loose this reference.
I had an error with my Ivy dependencies which reported "org.eclipse.persistence#org.eclipse.persistence.jpa;2.2.0: not found". It took me a while to find it but this post on Stack-Overflow helped.
It means that the standard Maven repositories do not hold this JAR so I have connected to the Eclipse Maven repository @ http://download.eclipse.org/rt/eclipselink/maven.repo/.

How?

Well my ivysettings.xml has this setting in it <ibiblio name="Eclipse-libraries"   m2compatible="true" root="http://download.eclipse.org/rt/eclipselink/maven.repo/" /> and looks like this:

<!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.   
-->
<ivysettings>
    <properties file="${ivy.settings.dir}/ivysettings.properties"/>
   
    <settings defaultResolver="embedplaysafe" />
   
    <!-- Where the Cache is placed -->
    <!-- <caches defaultCacheDir="${ivy.settings.dir}/ivy-cache" /> -->
    <caches defaultCacheDir="${defaultCache.dir}" />
   
    <resolvers>
        <!-- Path is important as this is the final repository -->
        <chain name="embedplaysafe"
               returnFirst="true"> <!-- if a revision is found in the filesystem then ivyrep will not be queried -->
            <!--
            It is a filesystem resolver, so looks at a directory structure to retrieve the artifacts.
            This one is configured to look in the repository sub directory of the directory that contains the ivysettings.xml file
             -->
            <filesystem name="local">
                <artifact pattern="${repository.dir}/[type]/[artifact]-[revision].[ext]" />
                <ivy pattern="${repository.dir}/[type]/[module]-[revision].xml" />
            </filesystem>
            <!--  See http://www.buildmeister.com/articles/escape_from_jar_hell_with_apache_ivy_the_agile_dependency_manager -->
            <!-- 
            <url name="buildmeister"> 
               <ivy pattern="http://m2.buildmeister.com/[module]/[revision]/ 
                ivy-[revision].xml" /> 
               <artifact pattern="http://m2.buildmeister.com/[module]/[revision]/ 
                [artifact]-[revision].[ext]" /> 
            </url>
            -->
            <!--  See http://stackoverflow.com/questions/1033859/ivy-via-nexus-proxy  -->
            <!-- It looks in the ibiblio maven repository to retrieve the artifacts.  -->
            <!--   -->
            <ibiblio name="uk-libraries"         m2compatible="true" root="http://uk.maven.org/maven2" />
            <ibiblio name="global-libraries"     m2compatible="true" usepoms="true" />
            <ibiblio name="Eclipse-libraries"   m2compatible="true" root="http://download.eclipse.org/rt/eclipselink/maven.repo/" />
          
        </chain>
    </resolvers>

</ivysettings>


I hope this helps you.