Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, 13 March 2012

Read a file in Java - oneliner?

Can anyone read a file in Java using the standard libraries in a single line?

This was the best I could do:

1:      public static List<String> readRows(InputStream stream) {  
2:          try {  
3:              byte[] data = new byte[stream.available()];  
4:              new DataInputStream(stream).readFully(data);  
5:              return Arrays.asList(new String(data).split("\\r\\n|\\n|\\r"));  
6:          } catch (IOException e) {  
7:              throw new IllegalStateException(e);  
8:          }  
9:      }  

It has the obvious caveat that stream.available() only returns an estimate for the size of the stream so this isn't suitable for production code.

This is one line longer and the more sensible choice, though I am being deliberately terse with the for loop:

1:      public static List<String> readRows2(InputStream stream) {  
2:          try {  
3:              LinkedList<String> rows = new LinkedList<String>();  
4:              BufferedReader reader = new BufferedReader(new InputStreamReader(stream));  
5:              for (String data = ""; (data = reader.readLine()) != null; rows.add(data));  
6:              return rows;  
7:          } catch (IOException e) {  
8:              throw new IllegalStateException(e);  
9:          }  
10:      }  

I'm aware that Guava and Apache Commons have utilities for this problem, so those would be also good choices.

Sunday, 22 January 2012

Hack-O-Matic 3000 J2ME Version

Before I worked with Android I also ported the Hack-O-Matic to the J2ME platform. This version requires the MIDP 2.0 profile or higher. This worked well on my Sony Ericsson Viewty very nicely.

Download:
Hack-O-Matic J2ME

This version works in the same way as the other versions.

Hack-O-Matic 3000 Windows

There is also a version of this utility available for Windows and other systems that run Java.

Download:
Hack-O-Matic for Windows
Hack-O-Matic Crossplatform

The application works in the same way as the other versions. Once you start a hacking session, you need to enter all the available keywords, and then provide the matches count. With this the program will elimiate the incorrect answers, helping you find the solution quicker.

You will need Java 5 or higher installed.


Thursday, 8 December 2011

Mockito mysteriously not mocking

Mockito mysteriously not mocking

This may sound familiar to you if you have worked on a large software project which was not previously designed with mocking in mind. I'm working on one of those at the moment and decided to get Mockito involved to make the testing more sane.

The legacy code was not designed with unit testing in mind, and as such a lot tightly coupled business logic has been pushed higher up the inheritance stack to make it available to more classes. We have been attempting to refactor the code base so it is more testable, but there is little appetite for major changes, and a number of customer deadlines are holding up this refactoring work.

Meanwhile we still need to write unit tests, and Mockito has proven useful in testing everything except classes from the main inheritance stack (we call them Business Objects).

Recently I read this excellent article on spying. Which allows you to change the behaviour of a real instance of a class with some mocked behaviour. Sure, this approach isn't pleasant and its code smell for the larger problem of poor architecture and design. However, it does work.

We found the one thing we couldn't do was mock/spy on methods higher up the inheritance chain, and were unable to work out the reason for this.

Turns out other people are having this problem as well.

Its not pretty, but it works in our case. Make all classes in the inheritance hierarchy public.

References:

Monday, 5 December 2011

Misusing Reflection

I don't think we should do this in production code...

private static Map<String, Object> extractTheStuffIWanted(Object obj, String className, String... keys) {
    Map<String, Object> resultMap = new HashMap<String, Object>();
    List<Object> search = new LinkedList<Object>();
    search.add(obj);
  
    while (!search.isEmpty()) {
        Object o = search.remove(0);
      
        if (o.getClass().getName().contains(className)) {
            for (String key : keys) {
                try {
                    Field f = o.getClass().getDeclaredField(key);
                    f.setAccessible(true);
                    resultMap.put(key, f.get(o));
                } catch (IllegalAccessException e) {
                    // nom nom nom
                } catch (NoSuchFieldException e) {
                    // nom nom nom
                }
            }
            break;
        }
       
        for (Field f : o.getClass().getDeclaredFields()) {
            try {
                f.setAccessible(true);
                Object value = f.get(o);
                if (value != null &&
                    !f.getType().isPrimitive()) {
                    search.add(value);
                }
            } catch (IllegalAccessException e) {
                // nom nom nom
            }
        }
    }
    return resultMap;
}

Thursday, 7 April 2011

Java Drag and Drop Summary

Key concepts


The core class in Java Drag and Drop (DnD) is the TransferHandler. This can be used to transfer data to and from both Java and native applications in the same way.


  • All JComponents support DnD automatically. Use the setDragEnabled to enable the default behaviour for the component.
  • DnD to and from any JComponent can be customised by calling setTransferHandler with your own TransferHandler.
  • To provide the effect of being able to drop something anywhere on the application, assign a suitable TransferHandler to all components from the JPanel downwards.
  • Assigning a TransferHandler overrides the default behaviour. Careful consideration should be made if there are complex requirements.

TransferHandler Drag Methods


When sub-classing a TransferHandler, the following are the methods to override to control the drag source behaviour.


  • getSourceActions Controls which drag types are supported from this component.
  • createTransferrable When a drag is started, the data to send is bundled up into a Transferable which will be delivered to the drop target.
  • exportDone Signalled when a drag has been completed using this TransferHandler.

TransferHandler Drop Methods


The drop methods below control the behaviour of a component which is to be the drop target for a DnD operation.


  • canImport Called repeatedly to determine whether the component to receive the drop is able to.
  • startImport Called when the drop is initiated.

Tuesday, 5 April 2011

Java Access Modifiers+

You would think that the main Java tutorial on access modifiers would be the final word on Java access modifiers. I have referred to their table enough times.


Java access levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

But one thing that caught me out today was, all methods defined in an interface are public by default. The language specification confirms this.