Friday, September 9, 2016

Find the most repeating character in a string

Following snipper will return most repeated character in a string

public char getMax(String str) {
    char maxChar = ' ';
    int maxCnt = 0;
    char [] charmax = new char[Character.MAX_VALUE+1];
    for(int i = str.length()-1; i>=0; i--) {
        char ch = str.charAt(i);
        int num = ++charmax[ch];
        if(num >= maxCnt) {
            maxCnt = charmax[ch];
            maxChar = ch;
        }
    }
    return maxChar;
}


Thursday, September 8, 2016

Validate String parathesis

Simple program to validate parenthesis in a string. e.g. "(12(ab(dkc)))" is valid but "(12(ab)(dkc)))" is not

The simple solution is to use stack to push the "(" character and pop the same when you have ")"

import java.util.Stack;

public class StringValidation {
public Boolean isValid(String str) {
Boolean isValid = true;
Stack stack = new Stack<>();
char[] chars = str.toCharArray();
for (char achar : chars) {
if (achar == '(') {
stack.push(achar);
}
if (achar == ')') {
if (stack.isEmpty()) return false;
stack.pop();
}
}
if (!stack.isEmpty()) return false;
return isValid;
}
public static void main(String [] args) {
String str1 = "(12(ab(dkc)))";
                String str2 = "(12(a)b(dkc)))";
StringValidation ex = new StringValidation();
System.out.println("str1: " + ex.isValid(str1));
                System.out.println("str2: " + ex.isValid(str2));
}
}

Tuesday, September 6, 2016

Run Groovy script as Rest service

We have a requirement to call the arbitrary groovy script and the server execute the script and sends back the JSON response.

Groovy shell is not thread safe and we either need to synchronize access to the groovy shell's evaluate method or pre-initialize the groovy shell instances in object pool. We have used object pool since each shell is associated with predefined initialization.

Also GSON is used to format the groovy output into JSON format and the json string can be returned  to the client. The groovy script can return any object and the same object is formatted to JSON and will send back to the client.

public class GroovyRequest {

private String client;
private String type;
private String script;
private String user;

public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
}

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("processGroovy")
public Response getJsonData(GroovyRequest req) {
String script = req.getScript();
String type = req.getType();
String client = req.getClient();
String user = req.getUser();
Response response = null;
response = processRequest(client, type, script, user, MediaType.APPLICATION_JSON);
return response;
}

private Response processRequest(String client, String type, String script, String user, String responseType) {
String gvyOutput = null;
Response response = null;
mLogger.log(Level.INFO, "Client: {0} type: {1} Script: {2}", new Object[] {client, type, script});
if (client == null || client.equals("") ||
type == null || type.equals("") ||
script == null || script.equals("") ){
//user == null || user.equals("")) {
gvyOutput = "Please correct the request parameters";
response =  Response.status(200).type(MediaType.TEXT_PLAIN).entity(gvyOutput).build();
return response;
}

if (responseType == null) {
responseType = MediaType.TEXT_PLAIN;
}
        GroovyShell shell = null;
try {
mLogger.info("---------------------------------------------------\n GroovyPool: total: " + groovyPool.getMaxTotal() + " maxIdle: " + groovyPool.getMaxIdle() + " createdCount: " + groovyPool.getCreatedCount() +
" \n MinEvictableIdleTimeMillis: " + groovyPool.getMinEvictableIdleTimeMillis() + " TimeBetweenEvictionRunsMillis: " + groovyPool.getTimeBetweenEvictionRunsMillis() +
" \n NumActive: " + groovyPool.getNumActive() + " NumIdle: " + groovyPool.getNumIdle());
            shell = groovyPool.borrowObject();
gvyOutput = (String) shell.evaluate(script);
response =  Response.status(200).type(responseType).entity(gvyOutput).build();
} catch (Exception ex) {
gvyOutput = "Error processing request: " + ex.getMessage();
response =  Response.status(200).type(responseType).entity(gvyOutput).build();
} finally {
            if(shell != null) {
                groovyPool.returnObject(shell);
            }
        }
return response;