2

I am writing RESTful web service to insert dynamic table into the database. I am going wrong somewhere in that and it is not working what i am trying to do. can someone please figure out and correct me where I am doing wrong?

Persistance class:

public void createTable(String tableName, List<String> columns, List<String> datatypes) {

         StringBuilder createTableQuery = new StringBuilder("CREATE TABLE IF NOT EXISTS `" + tableName + "` (");
          columns = new ArrayList<>();


         for (int i=0;i<columns.size();i++) {

                 createTableQuery.append("`" + columns + "` ");
                 createTableQuery.append(datatypes + ", ");
            }

             //To replace last ',' character and place the bracket.
            createTableQuery.replace(createTableQuery.lastIndexOf(","),createTableQuery.length(), ")");
        eTableQuery);

            Session session = null;
            Transaction transaction = null;
            try {

                session = HibernateUtil.getSessionFactory().getCurrentSession();
                transaction = session.beginTransaction();
                int count = session.createSQLQuery(createTableQuery.toString()).executeUpdate();   

                transaction.commit();
            } catch (Exception ex) {
                transaction.rollback();         
            }
    }    

Service Class:

@POST
    @Path("/selfbi/addtable")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createTable(JSONObject jsonObject, @QueryParam("uniqueid") String uniqueid, @QueryParam("sheetname") String sheetname) throws JSONException  {
        Response res = null;
        try{
        String tableName = "";
        if(jsonObject.has("tableName")){
            tableName = jsonObject.getString("tableName");
        }

        JSONArray jsonArray = jsonObject.getJSONArray("columns");

        List<String> col = new ArrayList<String>(); 
            if (jsonArray != null) { 
            for (int i=0;i<jsonArray.length();i++) { 
                col.add(jsonArray.getString(i));    
            } 
        }


        JSONArray json = jsonObject.getJSONArray("datatypes");
        List<String> dtype = new ArrayList<String>(); 
        if (json != null) { 
            for (int i=0;i<json.length();i++) { 
                dtype.add(json.getString(i));   
            } 
        }


        restService.createTable(tableName, col, dtype);



        res = Response.status(Status.CREATED).build();

        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("service------>>>"+res);
        return res;
    }  

ERROR in Console:

java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:789)
    at java.lang.StringBuilder.replace(StringBuilder.java:266)
    at com.acinfotech.timebound.jpa.service.ReportJobsPersistenceServiceImpl.createTable(ReportJobsPersistenceServiceImpl.java:7843)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy81.createTable(Unknown Source)
    at com.acinfotech.timebound.restservice.service.RestServiceImpl.createTable(RestServiceImpl.java:2751)
    at com.acinfotech.timebound.restservice.service.RestrsService.createTable(RestrsService.java:428)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)

If you dont want to answer please ignore it instead of down voting/blocking it.

1
  • I'm not sure if it's the cause of your error (probably not), but when adding the column definitions, make sure to append the current element from the columns and datatypes list to the StringBuilder, instead of the lists themselves. Commented Jul 10, 2015 at 8:15

2 Answers 2

2

The problem might be caused by the fact that you've re-assigned the columns variable with a new, empty ArrayList. This means no columns will be added to the query, and such lastIndexOf() will return -1.

Sign up to request clarification or add additional context in comments.

5 Comments

Yes you are right. Any code suggestion to resolve it?
How about removing the statement columns = new ArrayList<>();?
The offending statement is in the createTable method of the persistence class; it re-assigns one of its input parameters a new (and thus empty) list. Marking the method parameter final ensures re-assignment is not possible, by the way.
Removing columns = new ArrayList<>(); solved the StringIndexOutOfBoundsException. But still table is not inserting into the database.
Check my comment right below your question (about the elements in the list vs. the list itself).
1

Replacing last comma with bracket won't work if columns.size() is zero. Do something like:

if (columns.size() > 0){
createTableQuery.replace(createTableQuery.lastIndexOf(","),createTableQuery.length(), ")");
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.