Skip to content

Tag: Java

parallel counting in Java using AtomicInteger

[java]
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.TimeUnit;

class ParallelCounterExample {
public static void main(String[] args) throws InterruptedException {
int threads = 2000;
ExecutorService executor = Executors.newFixedThreadPool(threads);
final AtomicInteger atomi = new AtomicInteger();
for(int i=0; i<threads; i++) {
executor.execute( new Runnable() {
@Override
public void run() {
atomi.getAndIncrement();
}
});
}
executor.awaitTermination(1, TimeUnit.SECONDS);
executor.shutdown();
System.out.println(atomi.get());
}
}
[/java]

Regex with negatives lookahead and lookbehind

"Looking different directions" by Paul Kline at (https://www.flickr.com/photos/paulelijah/6717953239/)
“Looking different directions” by Paul Kline.

Problem: Match strings that contains a single quotation mark ('), but not multiple ones together.

Solution:

(?<!')'(?!')

This is a regex for a single quotation mark with a (?<!') in the left and a (?!’) in the right. The (?<!') is a ?< look behind if not ! a single quotation mark '. The (?!') is a look ahead ? if not ! a single quotation mark '.

Java code:

[java]import java.util.regex.Pattern;

public class RegexProblem {
public static void main(String args[]) {
Pattern single_quote = Pattern.compile("(?<!’)'(?!’)");
String[] phrases = {
"",
"’",
"a’a",
"aaa",
"aa’aa",
"aa”aa",
"aa”’aaa",
"aaa””aaa"
};
for(String phrase: phrases){
System.out.println(String.format("For %s is %s.", phrase,
single_quote.matcher(phrase).find()));
}
}
}
[/java]

The output is:

For  is false.
For ' is true.
For a'a is true.
For aaa is false.
For aa'aa is true.
For aa''aa is false.
For aa'''aaa is false.
For aaa''''aaa is false.

Java, printing arrays

As I keep forgetting, this post is to remind me that Java Java doesn’t have a pretty toString() for arrays objects, and it does for Lists.

[java]import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class ListsExample {
public static void main (String args[]) {
// as an array
String[] list1 = {"a","b","c"};
System.out.println(Arrays.toString(list1));

// as an List provided by Arrays
List<String> list2 = Arrays.asList("d", "e", "f");
System.out.println(list2);

// as an implementation of the interface List
// ArrayList (could also be LinkedList, Vector, etc)
List<String> list3 = new ArrayList<String>();
list3.add("g");
list3.add("h");
list3.add("i");
System.out.println(list3);
}
}
[/java]

The output is:

[a, b, c]
[d, e, f]
[g, h, i]

Android screen height and width

Context ctx = getContext();
Display display = ((WindowManager)ctx.getSystemService(ctx.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

Yes, there are easier ways to retrieve the screen width on Android but there are cases that this long code is the only solution. You may already have the Context. WindowManager or the Display and so it would be smaller, but this code is more general.

Java: invoking a method by name


import java.lang.reflect.*;

public class Foo {
	public void bar(int param){
		System.out.println(param);
	}	

	public static void main(String args[]){
		Object f = new Foo();
		try {
			Method m = f.getClass().getMethod("bar", int.class);
			m.invoke(f, 42);
		} catch (Exception e){
			System.err.println(e);	
		}
	}

}

$ java Foo
42

calling commands in Java

I don’t like the approach of calling native shell commands in any language instead of using multi platform libraries, but here is a little prof of concept Java program to call native commands.

import java.io.*;
import java.util.*;
public class Exec {
   public static void main(String args[]) throws IOException {
      Process proc = Runtime.getRuntime().e xec(args);
      BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      String line;
      while ((line = br.readLine()) != null) {
         System.out.println(line);
      }
   }
}

Usage:

java Exec VALID_COMMAND

Example:

$ java Exec echo hello
hello

ps: I had to write “e xec” instead of exec because it was triggering some very strange security protection in the blog engine here. If you need to compile this code change that. =P Also there’s no error handling, you should pass a valid command when executing this code.

Iterating over a HashMap

Iterating over a HashMap using the enhanced loop (foreach) in Java is a good way to keep your code smaller, more legible and usually more semantically coherent.

import java.util.HashMap;
import java.util.Map;

class Foo {}

public class Main {
	
   public static void main(String args[]){
      Map mHash;
		
      mHash = new HashMap();
      mHash.put((byte)1, new Foo());
      mHash.put((byte)2, new Foo());
      mHash.put((byte)3, new Foo());
		
      for(Foo f: mHash.values()){
         System.out.println(f.toString());
      }
   }
}

Getting enviroment information on Android

This is a simple program I wrote called Who Am I that shows informations about the device which it is running. Which can be useful for developers and maybe advanced users.

Download:

  • WhoAmI.tar.bz2 – Eclipse project. It’s configured for Android platform 4 (1.6) but should work without problems in newer Android platform versions.
  • WhoAmI.apk – Application installation Android package.

Main Activity source code:

package net.silveiraneto.whoami;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.widget.EditText;

public class WhoAmI extends Activity {
    private EditText mEditor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.whoami);

        mEditor = (EditText) findViewById(R.id.editor);

        Object[][] properties = {
        	{"Build.BOARD", Build.BOARD},
        	{"Build.BRAND", Build.BRAND},
        	{"Build.CPU_ABI", Build.CPU_ABI},
        	{"Build.DEVICE", Build.DEVICE},
        	{"Build.DISPLAY", Build.DISPLAY},
        	{"Build.FINGERPRINT", Build.FINGERPRINT},
        	{"Build.HOST", Build.HOST},
        	{"Build.ID", Build.ID},
        	{"Build.MANUFACTURER", Build.MANUFACTURER},
        	{"Build.MODEL", Build.MODEL},
        	{"Build.PRODUCT", Build.PRODUCT},
        	{"Build.TAGS", Build.TAGS},
        	{"Build.TIME", Build.TIME},
        	{"Build.USER", Build.USER},
        };

        for(Object[] prop: properties) {
        	mEditor.append(String.format("%s: %s\n", prop[0], prop[1]));
        }
    }
}

And its Android Manifest:



    
        
            
                
                
            
        
    

The Caps Lock Java Socket Server

Here is a simple server for those who are starting studying sockets or just needs a simple socket server example for reuse while writing your own behavior.

Features:

  • A client should enter a string and the server would answer the same string, with each symbol in up case, when possible.
  • Default port at 8080.
  • One client at time.
  • No multi threading. I said its a simple server.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	private static final int DEFAULT = 8080;

	public Server() {
		this(DEFAULT);
	}

	public Server(int port) {
		ServerSocket sock;

		try {
			sock = new ServerSocket(port);
			System.out.println(String.format("Listening on port %d.", port));

			while (true) {
				try {
					Socket client = sock.accept();
					System.out.println("A new connection was accepted.");

					BufferedReader in = new BufferedReader(
							new InputStreamReader(client.getInputStream()));		
					OutputStreamWriter out = new OutputStreamWriter(client
							.getOutputStream());
					String input = "";

					while (!input.equals("exit")) {
						input = in.readLine();
						if (input.equals("shutdown")) {
							System.exit(0);
						}
						out.write(input.toUpperCase() + "\r\n");
						out.flush();
					}

					in.close();
					out.close();
					client.close();
					System.out.println("Connection closed.");
				} catch (NullPointerException npe) {
					System.out.println("Connection closed by client.");
				}
			}
		} catch (IOException ioe) {
			System.err.println(ioe);
			System.exit(-1);
		}
	}

	public static void main(String[] args) throws IOException {
		new Server();
	}
}

Usage:

$ javac Server.java
$ java Server
Listening on port 8080.

In another terminal:

$ telnet localhost 8080
Trying ::1…
Connected to localhost.
Escape character is ‘^]’.
hi
HI
The quick brown fox jumps over the lazy dog.
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
exi
EXI
exit
EXIT
Connection closed by foreign host.

Beware the locale

See-ming Lee 李思明 SML Photo

Today I was programming a toString method for a class widely used in a application, using the very useful String.format that provides a C’s like printf formatter.

@Override
public String toString() {
   return String.format("VO[a: %.1f, b: %.1f, c: %.1f]", a, b, a+b);
}

%.1f means a float with one digit precision after the dot separator. The code produces something like:

VO[a: 1.0, b: 2.0, c: 3.0]

The problem arises when running a JUnit test on this method wrote using a regular expression to extract the values from the String to test it correctness. We cannot assume that the dot will be always the separator for displaying a float value, in my locale pt_BR would be a comma. So the output would be:

VO[a: 1,0, b: 2,0, c: 3,0]

For a predictable output we can set a Locale for String.format:

Locale en = new Locale("en");
return String.format(en, "VO[a: %.1f, b: %.1f, c: %.1f]", a, b, a+b);

So it will always use the dot as common separator. Of course you should follow and respect the localization and internationalization efforts in others moments but in this toString case we are using it internally for debug and unitary testing so we can set a English default locale for safety reasons.