HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

HTTP request path parser

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
parserrequesthttppath

Problem

I have written a method to tokenize HTTP request paths such as /employee/23/edit:

protected void compile(String path){
    int mark=0;
    for(int i=0; i<path.length(); ++i){
        if(path.charAt(i)==DELIM){
            if(mark!=i)
                tokens.add(path.substring(mark,i));
            mark=i+1;
        }
        else if(path.length()==i+1){
            tokens.add(path.substring(mark,i+1));
        }
    }
}


And a method to tokenize the consumer of these paths such as /employee/[id]/edit:

protected void compile(String path){
    int mark=0;
    boolean wild=false;
    for(int i=0; i<path.length(); ++i){
        if(!wild){
            if(path.charAt(i)==DELIM){
                if(mark!=i)
                    tokens.add(path.substring(mark,i));
                mark=i+1;
            }
            else if(path.length()==i+1){
                tokens.add(path.substring(mark,i+1));
            }
            else if(path.charAt(i)=='['){
                wild=true;
            }
        }
        else if(path.charAt(i)==']'){
            tokens.add("?");
            wild=false;
            mark=i+1;
        }
    }
}


The idea here is that there will be an implicit variable called id with the value 23. However, that isn't here nor there. How does my approach look? Can it be improved? Also: DELIM = '/'.

This is more-or-less an exercise in writing a parser, which is why I didn't use String#split().

Solution

Your first compile method can be replaced by a single call to String.split.

Assuming the intended behavior for the second compile method is such that "/foo/b[a]r/baz" will compile to {"foo", "?", "baz"}, it can be replaced by a call to split and then iterating over the result and replacing any string the includes square brackets with "?".

If the intended behavior is rather that it will compile to {"foo", "b", "?", "r", "baz"}, you can first replace [anything] by /?/ using String.replace and then use String.split.

Context

StackExchange Code Review Q#109, answer score: 11

Revisions (0)

No revisions yet.