Best java questions in June 2011

Cut out image in shape of text

20 votes

I need to cut out an image in the shape of the text in another image. I think it's best shown in images.

This is a photo of a cat:

Photo of a nice cat

and this is the text I wish to cut out:

Text to cut out of the cat photo

The resulting image would be this:

Resulting cut-out of the cat photo

The text image will always be black with a transparent background, and the resulting cut-out should too have a transparent background. Both input images will also be the same size.

Create a new BufferedImage and iterate over all the pixels of word cat and if they are black, copy the cat-image pixels to the new image.

Here is some code: (Final working code, supports anti-alias)

public static BufferedImage textEffect(BufferedImage image, BufferedImage text) {
    if (image.getWidth() != text.getWidth() ||
        image.getHeight() != text.getHeight())
    {
        throw new IllegalArgumentException("Dimensions are not the same!");
    }
    BufferedImage img = new BufferedImage(image.getWidth(),
                                          image.getHeight(),
                                          BufferedImage.TYPE_INT_ARGB_PRE);

    for (int y = 0; y < image.getHeight(); ++y) {
        for (int x = 0; x < image.getWidth(); ++x) {
           int textPixel = text.getRGB(x, y);
           int textAlpha = (textPixel & 0xFF000000);
           int sourceRGB = image.getRGB(x, y);
           int newAlpha = (int) (((textAlpha >> 24) * (sourceRGB >> 24)) / 255d);
           int imgPixel = (newAlpha << 24) |  (sourceRGB & 0x00FFFFFF);
           int rgb = imgPixel | textAlpha;
           img.setRGB(x, y, rgb);

        }
    }
    return img;
}

Do Java sockets support full duplex?

19 votes

Is it possible to have one thread write to the OutputStream of a Java Socket, while another reads from the socket's InputStream, without the threads having to synchronize on the socket?

Sure. The exact situation you're describing shouldn't be a problem (reading and writing simultaneously).

Generally, the reading thread will block if there's nothing to read, and might timeout on the read operation if you've got a timeout specified.

Since the input stream and the output stream are separate objects within the Socket, the only thing you might concern yourself with is, what happens if you had 2 threads trying to read or write (two threads, same input/output stream) at the same time? The read/write methods of the InputStream/OutputStream classes are not synchronized. It is possible, however, that if you're using a sub-class of InputStream/OutputStream, that the reading/writing methods you're calling are synchronized. You can check the javadoc for whatever class/methods you're calling, and find that out pretty quick.

Java: Different between List, List<?>, List<T>, List<E>, and List<Object>

14 votes

What are the differences between List, List<?>, List<T>, List<E>, and List<Object>?

Now I do not blindly ask this question, so please don't close this thread. Let me first introduce the base code:

private static List<String> names = new ArrayList<String>();
static {
    names.add("Tom");
    names.add("Peter");
    names.add("Michael");
    names.add("Johnson");
    names.add("Vlissides");
}

public static void test(List<String> set){
    System.out.println(set);
}
public static void main(String args[]){
    test(names);
}

I do understand that:

1.List: is a raw type, therefore not typesafe. It will only generate a runtime error when the casting is bad. We want a compile time error when the cast is bad. Not recommended to use.

2.List<?>: is an unbounded wildcard. But not sure what this is for? So if I change the test method to

public static void test(List<?> set){
    System.out.println(set);
}

it still works good. If you can explain the usage of this, I would greatly appreciate it.

EDIT: If I do this:

public static void test(List<?> set){
    set.add(new Long(2)); //--> Error
    set.add("2");    //--> Error
    System.out.println(set);
}

but if I change test to this:

public static void test(List<String> set){
    set.add(new Long(2)); //--> Error
    set.add("2");    //--> Work
    System.out.println(set);
}

3.List<T>:

public static void test(List<T> set){   //T cannot be resolved
    System.out.println(set);
}

I guess I don't understand this syntax. I saw something like this, and it works:

public <T> T[] toArray(T[] a){
    return a;   
}

Please explain this for me please? Sometimes, I see <T>, or <E>, or <U>, <T,E>. Are they all the same or do they represent something different?

4.List<Object>

public static void test(List<Object> set){
    System.out.println(set);
}

Then I got the error The method test(List<Object>) is not application for the argument List<String> for the below code. I am confused. I thought String was a subset of Object?

public static void main(String args[]){
    test(names); 
}

EDIT: If I try this

test((List<Object>)names);

then I got Cannot cast from List<String> to List<Object>

1) Correct

2) You can think of that one as "read only" list, where you don't care about the type of the items.Could e.g. be used by a method that is returning the length of the list.

3) T, E and U are the same, but people tend to use e.g. T for type, E for Element, V for value and K for key. The method that compiles says that it taked an array of a certain type, and returns an array of the same type.

4) You can't mix oranges and apples. You would be able to add an Object to your String list if you could pass a string list to a method that expects object lists. (And not all objects are strings)

Whats possible in a for loop

13 votes

So today I went to an interview and one of the questions was the following (C# context).

//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

  1. Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.
  2. Where does this syntax stem from?
  3. Are there any other "not well known" structures that a for loop can take?
  4. Is writing code like above considered bad practice given how hard it is to read?
  5. Are there any good real world examples where such a structure is required?

for (statement1; statement2; statement3)
{
     /* body */
}

(1) First the statement1 is executed.

(2) Next statement2 is executed.

(3) If the evaluation of statement2 is true then the body is executed

(4) Then statement3 is executed.

(5) Repeat from step (2)

          |                  +<-----------------+
          |                  |                  ^
          V                  V                  |
 for (  (s1); -------->(s2 true? | false?);    (s3) )
 {                           |       |          ^
                             |       |          |
                             |       |          |
                             V       |          |
                          (body)-----|--------->+
 }                                   |
                                     |
                                     V
                                 (come out)

The structure you have shown is the same normal structure as above. The statement n could be any statement. In your example, you have separated by comma operators in statement1 and statement3. You can separate any number of statements by comma operators.

Generally for loops are used with the statement1 with initialization as it is executed only once. The statement2 is used for the loop termination condition checking, because the evaluation value of this statement is used to decide if to enter the body of break out. And the statement3 is used for update of the loop termination variable as it is executed after the body. But generally they could be used in any way.

First statement1 is i=10, j=0; this initializes the variables. Next in the statement2 is j <= 10 if this is true then the body is executed. After the body is executed, statement3 which is i--,j++ is executed. The loop will iterate 11 times 0 to 10. But will print 5 times, as at one point i and j will become same and the if (i > j) will evaluate false.

EDIT Here is an example where it might be used, not much practical but a sample use, to check for a palindrome string.

  int i, j, n, flag;
  char str[128];

  printf ("\nEnter string: ");
  scanf ("%s", &str);
  n = strlen (str);


for (flag=1, i=n-1, j=0; j<n/2; j++, i--)
{
  if (str[i] != str[j])
  {
    flag = 0;
    break;
  }
}

if (flag)
 printf ("\n\"%s\" is a palindrome");
else
 printf ("\n\"%s\" is not a palindrome");

We should always try to write code which is easy to read and which does not create confusion. This helps the code writer as well as others who read the code.

A tricky question of simple Java: variable scope

13 votes

I am not new to java and C#. I thought I understand the concept of variable scope until recently I was asked this question in an interview:

public class Q{ //starting y scope

    static int x = 11;
    private int y = 33; // Just added a “private” modifier to make it clearer.

    public static void main(String args[]){
        Q q = new Q();
        q.call(5);
    }

    public void call(int x){
        Q q = new Q();

        this.x = 22;
        y = 44;

        System.out.println("Output: " + Q.x);
        System.out.println("Output: " + q.x);
        System.out.println("Output: " + q.y);
    }

} //ending y scope

Define the output of this program.

I answered the question during the interview that the output would be a runtime exception. To my understanding, y is declared private, and the instance method call() is trying to access the instance private variable y of another instance of class Q. How could that happen at all!? However answering this question wrongly didn't affect my interview too much because this is the kind of "tricky basic" question. But, answering wrongly means my years' Java experience needs rehab, that's terrible!

Could someone help me on this matter? I would be so much appreciated!

You can access private members of your own class, even from a different instance of the class.

Generics: T extends MyClass vs. T extends MyClass<T>

13 votes

Is there a semantic difference between these two declaration or is it only syntactic sugar?

class C<T extends C> vs class C<T extends C<T>>

Background: I recently answered a question on generics using the C<T extends C> approach and a peer provided a similar answer based on C<T extends C<T>>. At the end, both alternatives provided the same result (in the context of the question asked). I remained curious about the difference between these two constructs.

Is there's a semantic difference? If so, what are the implications and consequences of each approach?

Sure - often these "self types" are used to constrain subtypes to return exactly their own type. Consider something like the following:

public interface Operation {
    // This bit isn't very relevant
    int operate(int a, int b);
}

public abstract class AbstractOperation<T extends AbstractOperation<T>> {
    // Lets assume we might need to copy operations for some reason
    public T copy() {
        // Some clever logic that you don't want to copy and paste everywhere
    }
}

Cool - we have a parent class with a useful operator which can be specific to subclasses. For instance, if we create an AddOperation, what can its generic parameters be? Because of the "recursive" generic definition, this can only be AddOperation giving us:

public class AddOperation extends AbstractOperation<AddOperation> {
    // Methods etc.
}

And hence the copy() method is guaranteed to return an AddOperation. Now lets imagine we're silly, or malicious, or creative, or whatever, and try to define this class:

public class SubtractOperation extends AbstractOperation<AddOperation> {
    // Methods etc.

    // Because of the generic parameters, copy() will return an AddOperation
}

This will be rejected by the compiler because the generic type isn't within its bounds. This is quite important - it means that in the parent class, even though we don't know what the concrete type is (and it might even be a class that didn't exist at compile time), the copy() method will return an instance of that same subclass.

If you simply went with C<T extends C>, then this weird definition of SubtractOperation would be legal, and you lose the guarantees about what T is in that case - hence the subtract operation can copy itself into an add operation.

This isn't so much about protecting your class hierarchy from malicious subclasses, it's more that it gives the compiler stronger guarantees about the types involved. If you're calling copy from another class altogther on an arbitrary Operation, one of your formations guarantees that the result will be of the same class, while the other will require casting (and might not be a correct cast, as with the SubtractOperation above).

Something like this for example:

// This prelude is just to show that you don't even need to know the specific
// subclass for the type-safety argument to be relevant
Set<? extends AbstractOperation> operations = ...;
for (AbstractOperation<?> op : operations) {
    duplicate(op);
}

private <T extends AbstractOperation<T>> Collection<T> duplicate(T operation) {
    T opCopy = operation.copy();
    Collection<T> coll = new HashSet<T>();
    coll.add(operation);
    coll.add(opCopy);

    // Yeah OK, it's ignored after this, but the point was about type-safety! :)
    return coll; 
}

The assignment on the first line of duplicate to T wouldn't be type-safe with the weaker of the two bounds you proposed, so the code wouldn't compile. Even if you define all of the subclasses sensibly.

Why "System.arraycopy" uses "Object" instead of "Object[]"?

12 votes

Just curious:

Someone knows why the method System.arraycopy uses Object as type for src and dest? Would be perfectly possible to use Object[] instead?

Why define:

arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

instead of

arraycopy(Object[] src, int srcPos, Object[] dest, int destPos, int length)

?

Primitive array types like boolean[] and double[] do not extend Object[] but they do extend Object

This method allows you to copy any type of array, so the type is Object.

int[] a =
int[] b =
System.arraycopy(a, 0, b, 0, a.length);

How to statically analyze reference types passed to each bytecode instruction?

11 votes

I have rewritten the question (the question remains the same, just with less background noise) in hopes of creating less confusion directed at all the wrong things - due to this, some of the comments below may seem out of context.

Analyzing Java bytecode, what is the easiest way to find all the possible reference types given as parameters for a given Java bytecode instruction? I'm interested in the type of the reference, that is, that a given putfield instruction will receive an Integer, or that it might receive an Integer or a Float, etc.

For example, consider this code block:

   0:   aload_1
   1:   invokestatic    #21; //Method java/lang/Integer.valueOf:(Ljava/lang/String;)Ljava/lang/Integer;
   4:   astore_2
   5:   aload_2
   6:   ifnull  17
   9:   aload_0
   10:  aload_2
   11:  putfield    #27; //Field value:Ljava/lang/Number;
   14:  goto    25
   17:  aload_0
   18:  iconst_0
   19:  invokestatic    #29; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   22:  putfield    #27; //Field value:Ljava/lang/Number;
   25:  return

We can deduce that the putfield instruction at pc 11 will receive a ref type of Integer.

0: aload pushes ref type of String (the method param)
1: invokestatic pops the ref type and pushes a ref type of Integer (invoked method return type)
4: astore pops the ref type of Integer and stores it in local variable 2
5: aload pushes the ref type of Integer from local variable 2
6: ifnull pops the ref type of Integer and conditionally jumps to pc 17
9: aload pushes "this"
10: aload pushes the ref type of Integer
11: putfield: we know we have a ref type of Integer that the instruction will put in field

Do any of the bytecode/code analysis libraries do this for me, or do I have to write this myself? The ASM project has an Analyzer, which seems like it might do part of the work for me, but really not enough to justify switching to using it.

EDIT: I have done my homework and have studied the Java VM Spec.

The Analyzer.analyze(...) method seems to do exactly what you need, and if not you've got the option of hacking it. This would be a better approach than starting over again.

Another idea would be to see if you can find a bytecode verifier that is implemented in Java. A verifier must use data flow analysis to ensure that methods don't get called with the wrong type of parameters.

Overloading with Short and int

11 votes

Why this code will print int?

public static void main(String[] args) {
    short s = 5;
    A(s);
}
public static void A(int a){
    System.out.println("int");
}

public static void A(Short a){
    System.out.println("short");
}

Because upcasting to int was in version 1.0 of Java and auto-boxing was added in version 5.0. Changing the behaviour would break code written for older version of Java.

However, mixing types like this suggests there is something wrong with your design, its only something you are going to find in puzzlers. ;)

Java generics, nested collection of wildcard

11 votes

This compiles (1.6)

List<? extends Object> l = new ArrayList<Date>();

But this does not

List<List<? extends Object>> ll = new ArrayList<List<Date>>();

with the error of

Type mismatch: cannot convert from ArrayList<List<Date>> to List<List<? extends Object>>

Could someone explain why? Thanks

EDIT: edited for being consequent

Because it would break type safety:

List<List<Object>> lo = new ArrayList<List<Object>>();
List<List<? extends Object>> ll = lo;
List<String> ls = new ArrayList<String>();
ll.add(ls);
lo.get(0).add(new Object());
String s = ls.get(0); // assigns a plain Object instance to a String reference

java thread question

11 votes

This is a question asked to one of my friends during an interview.

How do you know whether a thread is blocked inside a synchronised method form another thread?

Can anybody please explain this using an example?

Using Thread.getState():

Thread.State state = getThreadInQuestion().getState();
if(state == Thread.State.BLOCKED) {
    System.out.println("Blocked");
} else {
    System.out.println("Not blocked");
}

Outside of a VM, you can use the jstack tool to get full thread information for every thread, or connect to JMX and explore the Thread MBeans.

JNI: From C code to Java and JNI

8 votes

Background

I am developing an application for android in eclipse and now I have a problem and I need your help. So I must Call function written in C from JAVA application. But on my way of writing code I have some Questions which you can see below. I am waiting for your answers and ideas ...

C Code:

typdef struct blobData_s {
    unsigned long length;
    unsigned char data[1];
} blobData_t;

unsigned int CheckEnrollmentExist ( unsigned long hdevice, blobData_t* pInputInfo ) {
    // Function code goes here
    ..........................
    return some_value;
}

JAVA Code:

In JAVA code instead of unsigned long I use int so I can write.

class jblobData_c {
    public int langth;
    *Question 1.*
}

public class ApplicationMainClass extends Activity {
    // Some code goes here
    ......................

    public native int JCheckEnrollmentExist( int jhdevive, *Question 2.* );

}

Question 1.

  • What I can use instead of unsigned char in JAVA Code ?
  • What I must write in JAVA code instead of unsigned char data[1]; ?

Question 2.

  • How I can use class jblobData_c instead of blobData_t* pInputInfo in the JAVA Code ?
  • What I must write in JAVA instead of blobData_t* pInputInfo ?

JNI Code:

JNIEXPORT jint JNICALL Java_com_Test_JCheckEnrollmentExist(JNIEnv* env, jobject obj, jint jhdevice, *Question 2.* ) {

    // Call the base function from C code.
    return CheckEnrollmentExist( jhdevice, *Question 3.*);
}

Question 3.

  • What I must write in CheckEnrollmentExist function that is C Code Function instead of blobData_t* pInputInfo in order this function works right and given parameter be the same

Reference

  1. How to pass C structs back and forth to Java code in JNI ?
  2. Passing large C structure through JNI efficiently
  3. Return a Structure Object from C to Java Through JNI
  4. Pass data between Java and C
  5. Passing a pointer from JNI to Java using a long
  6. Passing pointers between C and Java through JNI

For question #1:

You can use a jchar. Primitive chars in java are not signed, it's about the only primitive that isn't. Note that jchar is a UTF-16 char, so you will have to "map" the jchar to a regular char, as you would have to with any character conversion issue. For simple conversions, this can typically be done by casting

char c_char = (char)java_char;

because the core ASCII shares the same numeric values between ASCII and UTF-16. However, this is prone to error should anyone actually attempt to pass a "special" character through the interface. A much better way would be to (in the java side, as it is easier) convert the characters to bytes using the appropriate character set for your platform (to ensure platform compatibility in the C layers). Then you only need to pass a byte[] to the JNI call, and the bytes will correctly correspond to the characters that C likely will expect.

For question #2:

If your CheckEnrollmentExists(...) method is the JNI binding entry point, you cannot change data types safely. That means that all entry inputs must be JNI data type values. While you might be able to select the C data type equivalents (and you might be able to get your compiler to do it anyway) such techniques should be frowned upon. This implicitly means that JNI entry points cannot accept struct data structure not defined in the JNI headers. In other words, you can't pass your own struct to the method.

If the method needs access to a C struct across calls, use another means. I've seen people store the pointer to the allocated data structure in a member integer or long (doing correct casting). You can then rewrite the native code side to retrieve the pointer from the "this" object being passed into the call, and the do a dereference to obtain the required data.

For Question #3:

This is actually the same as question #2. In the "binding wrapper" you put, you would retrieve the pointer's stored value in the java object's int or long field, cast it to the appropriate struct pointer and then pass it to the internal method. As the passing of the pointer is a C to C call, no extra magic is required.

Android to node.js communication

8 votes

I saw there are a couple of similar threads but i could not find my answer.

I'm making and android app, an i want to use node as server for realtime communication.

I really cannot get this to work.

Probably i'm making many many things wrong but i like to try to understand.

my server is as simple as

    var http = require('http'),  
    io = require('socket.io'),
server = http.createServer(function(req, res){ 
     res.writeHead(200, {'Content-Type': 'text/html'}); 
     res.end(':)'); 
});
server.listen(8080);
var socket = io.listen(server); 
socket.on('connection', function(client){
    client.send("hello");
    console.log("connected!");
});

and this works... i tried his with a web app and i can connect.

But i can't with java..

i tried kryonet but i get an exception like "connected but timeout on registration"

i tried weberknecht i get a "error while creating socket to ws://184.xxxxxx:8080"

i tried TooTallNate, no luck, it just call onClose method.

i tried jWebSocket but i couldn't get it to work...

So i'm here, asking for help, does anyone knows how to get this done? any suggestion?

P.S. for TooTallNate i'm using something like this:

Net net=new Net(new URI("ws://184.xxxxxx:8080"),WebSocketDraft.DRAFT76);

might the problem be here?

UPDATE: i handled this! after a good sleep i had the idea, i was using socket.io, bad idea... know i use Node Websocket Server with weberknecht. The server looks like this:

var ws = require("websocket-server");

var server = ws.createServer();

server.addListener("connection", function(client){
    console.log("new connection");
    client.send("aaaaaa");
    client.addListener("message", function(msg){
    });
});

server.listen(8080);

and the client:

try {
            URI url = new URI("ws://184.106.69.64:8080/");
            WebSocket websocket = new WebSocketConnection(url);
            websocket.setEventHandler(new WebSocketEventHandler() {
                    public void onOpen(){
                            System.out.println("--open");
                    }    
                    public void onMessage(WebSocketMessage message){
                            System.out.println("--received message: " + message.getText());
                    }   
                    public void onClose(){
                            System.out.println("--close");
                    }
            });

            websocket.connect();
            websocket.send("hello world");
        }
        catch (WebSocketException wse) {
                wse.printStackTrace();
        }
        catch (URISyntaxException use) {
                use.printStackTrace();
        }

Thanks for your help!

I'm the author of node-websocket-server (nws), and I'm pretty sure the reason for node-websocket-server working and socket.io not, is due to the implementation of each. NWS will auto negotiate the right draft to use, and it also has a hopefully 90-100% compliance with the drafts of 76 and 75.

As for socket.io, I can't comment too much, but the last I looked, it's websocket implementation was rather poorly implemented.

I'm currently working on a project at the moment called node-websocket-protocol, which will be able to be used by socket.io, faye, etc as to provide them with a really reliable and compliant websocket implementation. This will also replace the current implementation in node-websocket-server in version 2.0.0.

As a side note, if you'd rather not host your own websocket server, you could look at using Pusher.com, who're actually my employers.

[Update] As for whether websockets are the most appropriate technology choice for your application, is a matter of what type of data and interaction your application needs. On a mobile device, it may be best to use something like urbanairship or notifio if you're just sending push notifications.

Regards, Micheil Smith

Why does "hello\\s*world" not match "hello world"?

7 votes

Why does this code throw a InputMismatchException ?

Scanner scanner = new Scanner("hello world");
System.out.println(scanner.next("hello\\s*world"));

The same regex matches in http://regexpal.com/ (with \s instead of \\s)

A Scanner, as opposed to a Matcher, has built in tokenization of the string, the default delimiter is white space. So your "hello world" is getting tokenized into "hello" "world" before the match runs. It would be a match if you changed the delimiter before scanning to something not in the string, eg.:

Scanner scanner = new Scanner("hello world");
scanner.useDelimiter(":");
System.out.println(scanner.next("hello\\s*world"));

but it seems like really for your case you should just be using a Matcher.

This is an example of using a Scanner "as intended":

   Scanner scanner = new Scanner("hello,world,goodnight,moon");
   scanner.useDelimiter(",");
   while (scanner.hasNext()) {
     System.out.println(scanner.next("\\w*"));
   }

output would be

hello
world
goodnight
moon

Java API for SQL Data Definition Language

7 votes

Before I write one, is there a Java API for manipulating a database. Like an object orientated wrapper around java.sql.DatabaseMetaData, with support for things like Schema.createTable(name, columns)?

Obviously correct SQL statements should be executed in the background based on the DB in use.

I'm specifically interested in an API for performing DDL statements.

As far as I can remember some tools such as NetBeans can create/ modify database schemas on-the-fly. You could have a look at the source code if you don't find a specific library.

Proper Way of Handling an Orientation Change in Android

7 votes

What is the proper way of handling an orientation change in Android? When I researched this question there are two methods that came up.

1st Method Use the methods onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) to store and restore your Activity after being killed by the Android OS after the orientation change.

2nd Method Added android:configChanges="orientation|keyboardHidden" to your AndroidManifest.xml so the Activity will not be destroyed when the orientation is changed.

I have tried both methods and they both work, however the first method takes a lot longer to implement. While I do see posts about the 2nd method, I want to know if this is an "accepted" and "proper" way of handling an orientation change. And what are the advantages and disadvantages for each method? Thanks!

The 1st method you mentioned is the proper way to do it (using bundles to pass data between new and old instances). The second option you listed is a hack for the most part.

There is one other way which isn't mentioned, and that's by onRetainNonConfigurationInstance.

Here's a bit more info on that method: http://developer.android.com/resources/articles/faster-screen-orientation-change.html

Edit: Be careful using this method though, it can cause memory leaks and similar issues if not done properly.

Pattern.matches doesn't work, while replaceAll does

7 votes

The regular expression seems to be ok, since the first line line correctly replace the substring with "helloworld", but the same expression won't match in the latter since i cannot see "whynothelloworld?" on console

System.out.println(current_tag.replaceAll("^[01][r]\\s", "helloworld"));

if (Pattern.matches("^[01][r]\\s", current_tag)) { System.out.println("whynothelloworld?");}

Pattern.matches() expects the entire string to match, not just a substring.

Use the .find() method of the regex matcher object instead:

Pattern regex = Pattern.compile("^[01]r\\s");
Matcher regexMatcher = regex.matcher(current_tag);
foundMatch = regexMatcher.find();

Re-define wait method in a Java interface

6 votes

I would like to use wait(int) as the signature of a method in a fluent API (used for http://www.jooq.org). The goal is to be able to construct SQL queries like this example:

SELECT * FROM T_AUTHOR
WHERE ROWNUM <= 1
FOR UPDATE OF FIRST_NAME, LAST_NAME
WAIT 5

The full FOR UPDATE clause syntax specification (at least for Oracle) can be seen here:

FOR UPDATE [ OF [ [ schema. ] { table | view } . ] column
             [, [ [ schema. ] { table | view } . ] column]...]
[ { NOWAIT | WAIT integer | SKIP LOCKED } ]

http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/img_text/for_update_clause.htm

With jOOQ, I really want to stay close to the SQL syntax. So I'd like to be able to model the above SQL clause with the jOOQ fluent API like this:

Result<Record> result = create.select()
                              .from(T_AUTHOR)
                              .limit(1)
                              .forUpdate()
                              .of(FIRST_NAME, LAST_NAME)
                              .wait(5) // Here's the issue
                              .fetch();

The fetch method is used to render the API's underlying object as SQL and run the SQL statement against an Oracle (or any other) database. The above can be legally specified in an interface:

/**
 * A type that models a "step" in the creation of a query using the fluent API
 */
public interface SelectForUpdateWaitStep extends SelectFinalStep {
    // [...]

    /**
     * Add a "FOR UPDATE .. WAIT n" clause to the query
     */
    SelectFinalStep wait(int seconds);

    // [...]
}

I have some doubts about this, though, because there is a risk of collision with another method:

public class Object {
    // [...]

    public final native void wait(long timeout) throws InterruptedException;

    // [...]
}

Thanks to method-overloading (int vs. long arguments), I can actually do this. But I'm afraid it might confuse my users and lead to mistakes. So this would be wrong:

                              .forUpdate()
                              .of(FIRST_NAME, LAST_NAME)
                              .wait((long) 5) // This doesn't make sense
                              .fetch();       // This doesn't compile

So my questions are:

  1. Can I somehow prevent calling/accessing Object.wait(long) altoghether? I don't think so because it's declared final but maybe someone knows a compiler-trick, or something else?
  2. Do you have a better idea for my API design apart from just renaming the method to something silly like doWait(int) or WAIT(int)?

What this requires is a way to disable an Object method. And main reason seems to be because it has a nice name that would fit the purposes of a proprietary API.

At first, this contradicts the entire idea of inheritance -- once you inherit from a class, all subclasses must expose the same non-private fields & method. You can always override a method, except when (1) it is marked as final and (2) it has an incompatible (non-covariant) return type, both of which are true with the void wait(long) method.

Furthermore, since every object is an Object in Java, everything must have a method void wait(long) and there should be no way to hide/delete/disable/forward/override it. Assuming it were possible to hide the void wait(long) method, how would you go about invoking it, should you wish to invoke it?

However, assuming you would never need to invoke void wait(long) for your particular classes, there is always the approach of source/byte-code weaving that AspectJ uses in order to make changes to the .class Java bytecode based on certain invocation rules. You could trap every call to wait(long) and declare an error/warning. See more here: http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations-decp.html

However, native method pointcuts are not possible even with AspectJ with byte-code weaving. Most likely, this is not possible even with source-code weaving -- but it might be worth a try.

Help building a regex

6 votes

I need to build a regular expression that finds the word "int" only if it's not part of some string.

I want to find whether int is used in the code. (not in some string, only in regular code)

Example:

int i;  // the regex should find this one.
String example = "int i"; // the regex should ignore this line.
logger.i("int"); // the regex should ignore this line. 
logger.i("int") + int.toString(); // the regex should find this one (because of the second int)

thanks!

It's not going to be bullet-proof, but this works for all your test cases:

(?<=^([^"]*|[^"]*"[^"]*"[^"]*))\bint\b(?=([^"]*|[^"]*"[^"]*"[^"]*)$)

It does a look behind and look ahead to assert that there's either none or two preceding/following quotes "

Here's the code in java with the output:

    String regex = "(?<=^([^\"]*|[^\"]*\"[^\"]*\"[^\"]*))\\bint\\b(?=([^\"]*|[^\"]*\"[^\"]*\"[^\"]*)$)";
    System.out.println(regex);
    String[] tests = new String[] { 
            "int i;", 
            "String example = \"int i\";", 
            "logger.i(\"int\");", 
            "logger.i(\"int\") + int.toString();" };

    for (String test : tests) {
        System.out.println(test.matches("^.*" + regex + ".*$") + ": " + test);
    }

Output (included regex so you can read it without all those \ escapes):

(?<=^([^"]*|[^"]*"[^"]*"[^"]*))\bint\b(?=([^"]*|[^"]*"[^"]*"[^"]*)$)
true: int i;
false: String example = "int i";
false: logger.i("int");
true: logger.i("int") + int.toString();

Using a regex is never going to be 100% accurate - you need a language parser. Consider escaped quotes in Strings "foo\"bar", in-line comments /* foo " bar */, etc.

Disk storage in a jee application

5 votes

I have JavaEE app in which I want to small little amount of data to disk, eg just user/passwords.

I dont want to go through the hassle of integrating with a full db for this little amount of data.

Is there a standard way to access the file system and a standard folder where web applications can store their data on disk, other than using a database?

Note:

I am not using EJB's. Its a web application using servlets.

You could consider using the preferences API to store this data - it's available on Java EE as well.