Example usage for java.lang StringBuilder delete

List of usage examples for java.lang StringBuilder delete

Introduction

In this page you can find the example usage for java.lang StringBuilder delete.

Prototype

@Override
public StringBuilder delete(int start, int end) 

Source Link

Usage

From source file:net.sf.vfsjfilechooser.accessories.connection.ConnectionDialog.java

private void initListeners() {
    this.portTextField.addKeyListener(new KeyAdapter() {
        @Override//  w w  w.  java2s .  c  om
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();

            if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
                getToolkit().beep();
                e.consume();
            } else {
                setPortTextFieldDirty(true);
            }
        }
    });

    this.portTextField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            JFormattedTextField f = (JFormattedTextField) e.getSource();
            String text = f.getText();

            if (text.length() == 0) {
                f.setValue(null);
            }

            try {
                f.commitEdit();
            } catch (ParseException exc) {
            }
        }
    });

    this.cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (currentWorker != null) {
                if (currentWorker.isAlive()) {
                    currentWorker.interrupt();
                    setCursor(Cursor.getDefaultCursor());
                }
            }

            setVisible(false);
        }
    });

    this.connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            currentWorker = new Thread() {
                @Override
                public void run() {
                    StringBuilder error = new StringBuilder();
                    FileObject fo = null;

                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                    try {
                        String m_username = usernameTextField.getText();
                        String m_defaultRemotePath = defaultRemotePathTextField.getText();
                        char[] m_password = passwordTextField.getPassword();
                        String m_hostname = hostnameTextField.getText();
                        String m_protocol = protocolList.getSelectedItem().toString();

                        int m_port = -1;

                        if (portTextField.isEditValid() && (portTextField.getValue() != null)) {
                            String s = portTextField.getValue().toString();
                            m_port = Integer.valueOf(s);
                        }

                        Builder credentialsBuilder = Credentials.newBuilder(m_hostname)
                                .defaultRemotePath(m_defaultRemotePath).username(m_username)
                                .password(m_password).protocol(m_protocol).port(m_port);

                        Credentials credentials = credentialsBuilder.build();

                        String uri = credentials.toFileObjectURL();

                        if (isInterrupted()) {
                            setPortTextFieldDirty(false);

                            return;
                        }

                        fo = VFSUtils.resolveFileObject(uri);

                        if ((fo != null) && !fo.exists()) {
                            fo = null;
                        }
                    } catch (Exception err) {
                        error.append(err.getMessage());
                        setCursor(Cursor.getDefaultCursor());
                    }

                    if ((error.length() > 0) || (fo == null)) {
                        error.delete(0, error.length());
                        error.append("Failed to connect!");
                        error.append("\n");
                        error.append("Please check parameters and try again.");

                        JOptionPane.showMessageDialog(ConnectionDialog.this, error, "Error",
                                JOptionPane.ERROR_MESSAGE);
                        setCursor(Cursor.getDefaultCursor());

                        return;
                    }

                    if (isInterrupted()) {
                        return;
                    }

                    fileChooser.setCurrentDirectory(fo);

                    setCursor(Cursor.getDefaultCursor());

                    resetFields();

                    if (bookmarksDialog != null) {
                        String bTitle = fo.getName().getBaseName();

                        if (bTitle.trim().equals("")) {
                            bTitle = fo.getName().toString();
                        }

                        String bURL = fo.getName().getURI();
                        bookmarksDialog.getBookmarks().add(new TitledURLEntry(bTitle, bURL));
                        bookmarksDialog.getBookmarks().save();
                    }

                    setVisible(false);
                }
            };

            currentWorker.setPriority(Thread.MIN_PRIORITY);
            currentWorker.start();
        }
    });

    // add the usual right click popup menu(copy, paste, etc.)
    PopupHandler.installDefaultMouseListener(hostnameTextField);
    PopupHandler.installDefaultMouseListener(portTextField);
    PopupHandler.installDefaultMouseListener(usernameTextField);
    PopupHandler.installDefaultMouseListener(passwordTextField);
    PopupHandler.installDefaultMouseListener(defaultRemotePathTextField);

    this.protocolList.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                selectPortNumber();
            }
        }
    });

    this.protocolList.setSelectedItem(Protocol.FTP);
}

From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java

/**
 * {@inheritDoc}//w ww.  ja v  a 2 s.  c om
 */
public String replaceSystemValues(String inString) {
    UserDirectoryService userDirectoryService = org.sakaiproject.user.cover.UserDirectoryService.getInstance();

    Session s = SessionManager.getCurrentSession();
    User user = userDirectoryService.getCurrentUser();
    String worksiteId = ToolManager.getCurrentPlacement().getContext(); // current site id
    Site site = getCurrentWorksite(worksiteId);

    Map map = new HashMap();
    map.put("{userid}", Validator.escapeSql(s.getUserId()));
    //system values are stored in session if report is scheduled through quartz
    if (s.getAttribute("toolid") == null) {
        UserDirectoryService dirServ = org.sakaiproject.user.cover.UserDirectoryService.getInstance();
        User u = dirServ.getCurrentUser();
        map.put("{userdisplayname}", Validator.escapeSql(u.getDisplayName()));
        map.put("{useremail}", Validator.escapeSql(u.getEmail()));
        map.put("{userfirstname}", Validator.escapeSql(u.getFirstName()));
        map.put("{userlastname}", Validator.escapeSql(u.getLastName()));
        map.put("{worksiteid}", Validator.escapeSql(ToolManager.getCurrentPlacement().getContext()));
        map.put("{toolid}", Validator.escapeSql(ToolManager.getCurrentPlacement().getId()));
    } else {
        map.put("{userdisplayname}", Validator.escapeSql((String) s.getAttribute("userdisplayname")));
        map.put("{useremail}", Validator.escapeSql((String) s.getAttribute("useremail")));
        map.put("{userfirstname}", Validator.escapeSql((String) s.getAttribute("userfirstname")));
        map.put("{userlastname}", Validator.escapeSql((String) s.getAttribute("userlastname")));
        map.put("{worksiteid}", Validator.escapeSql((String) s.getAttribute("worksiteid")));
        map.put("{toolid}", Validator.escapeSql((String) s.getAttribute("toolid")));
    }

    Iterator iter = map.keySet().iterator();
    StringBuilder str = new StringBuilder(inString);

    //   loop through all the parameters and find in query for replacement
    while (iter.hasNext()) {

        //   get the parameter and associated parameter definition
        String key = (String) iter.next();

        int i = str.indexOf(key);

        //   Loop until no instances exist
        while (i != -1) {

            //   replace the parameter with the value
            str.delete(i, i + key.length());
            str.insert(i, (String) map.get(key));

            //   look for a second instance
            i = str.indexOf(key);
        }
    }

    String string = str.toString();

    // create a list of the supported bean objects whose values can be replaced
    Map beans = new HashMap();
    beans.put("{session.attribute.", s);
    beans.put("{site.property.", site);
    beans.put("{user.property.", user);
    string = replaceSystemValues(string, beans);

    beans = new HashMap();
    beans.put("{session.", s);
    beans.put("{site.", site);
    beans.put("{user.", user);
    string = replaceSystemValues(string, beans);

    return string;
}

From source file:com.impetus.client.cassandra.query.ResultIterator.java

private void buildPartitionKeyTokens(MetamodelImpl metaModel, SingularAttribute idAttribute, Object id,
        CQLTranslator translator, StringBuilder pkNameTokens, StringBuilder pkValueTokens) {
    EmbeddableType keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());
    Field embeddedField = getPartitionKeyField();

    if (embeddedField == null) {
        // use tokens on the fields (no clustering keys
        Field[] fields = entityMetadata.getIdAttribute().getBindableJavaType().getDeclaredFields();

        for (Field field : fields) {
            Object value = PropertyAccessorHelper.getObject(id, field);
            String columnName = ((AbstractAttribute) keyObj.getAttribute(field.getName())).getJPAColumnName();
            translator.appendColumnName(pkNameTokens, columnName);
            translator.appendValue(pkValueTokens, field.getType(), value, false, false);
        }/*from w w w  . ja va2s .  c o  m*/
    } else {
        // use tokens for partition key fields (fields in embeddedField) and
        // where clause for clustering fields
        Attribute partitionKey = keyObj.getAttribute(embeddedField.getName());
        EmbeddableType partitionKeyObj = metaModel.embeddable(partitionKey.getJavaType());
        Object partitionKeyValue = PropertyAccessorHelper.getObject(id, (Field) partitionKey.getJavaMember());
        Field[] fields = partitionKey.getJavaType().getDeclaredFields();
        // handle for part keys
        for (Field field : fields) {
            if (!ReflectUtils.isTransientOrStatic(field)) {
                Object value = PropertyAccessorHelper.getObject(partitionKeyValue, field);
                String columnName = ((AbstractAttribute) partitionKeyObj.getAttribute(field.getName()))
                        .getJPAColumnName();
                translator.appendColumnName(pkNameTokens, columnName);
                translator.appendValue(pkValueTokens, field.getType(), value, false, false);
                pkNameTokens.append(CQLTranslator.COMMA_STR);
                pkValueTokens.append(CQLTranslator.COMMA_STR);
            }
        }
        pkNameTokens.delete(pkNameTokens.lastIndexOf(CQLTranslator.COMMA_STR), pkNameTokens.length());
        pkValueTokens.delete(pkValueTokens.lastIndexOf(CQLTranslator.COMMA_STR), pkValueTokens.length());
        pkNameTokens.append(CQLTranslator.CLOSE_BRACKET);
        pkValueTokens.append(CQLTranslator.CLOSE_BRACKET);

        // TODO: handle for cluster keys
        throw new UnsupportedOperationException(
                "Pagination is not suported via ThriftClient on primary key with clustering keys...");
    }

}

From source file:au.org.ala.delta.util.Utils.java

/**
 * Removes DELTA style <> comments from the supplied string.
 * /*from ww w.j av a 2  s .c  o m*/
 * @param text
 *            the string to remove comments from.
 * @param level
 *            0 = don't remove, 1 = remove all, 2 = remove only if other
 *            text, 3 = same as 2, but outer brackets are removed if
 *            commented text is used.
 * @return the string with comments removed
 */
public static String removeComments(String text, int level, boolean convertCommentsToBrackets,
        boolean removeInnerComments, boolean stripSpaces, boolean removeBrackets) {

    int mode = level;

    int commentLevel = 0;
    boolean hasText = mode == 1;
    boolean hadInner = false;
    char ch;
    int i, curStart = -1, start = -1, end = -1;
    int innerStart = -1;
    boolean wasSpace = true;
    boolean wasBrace = false;
    // TODO despaceRTF(text);
    if (stripSpaces) {
        text = stripExtraSpaces(text);
    }
    StringBuilder result = new StringBuilder(text);

    for (i = 0; i < result.length(); ++i) { // Work through string
        // Is character an opening bracket?
        if (result.charAt(i) == '<'
                && (wasSpace || wasBrace || (ch = result.charAt(i - 1)) == ' ' || ch == '<' || ch == '>')) {
            wasBrace = true;
            if (convertCommentsToBrackets) {
                result.setCharAt(i, ')');
            }
            if (removeBrackets || (mode == 3 && commentLevel == 0)) {
                result.deleteCharAt(i--);
            }
            if (commentLevel == 0) {
                curStart = i;
                if (start == -1)
                    start = i;
            } else if (commentLevel == 1) {
                innerStart = i;
                hadInner = true;
            }
            // Keep track of nesting level
            commentLevel++;
        }
        // Was it a closing bracket?
        else if (result.charAt(i) == '>' && commentLevel > 0 && result.charAt(i - 1) != '|'
                && (i + 1 == result.length() || (ch = result.charAt(i + 1)) == ' ' || ch == '<' || ch == '>')) {
            // Keep track of nesting level
            commentLevel--;
            wasBrace = true;
            if (convertCommentsToBrackets)
                result.setCharAt(i, ')');
            if (removeBrackets || (mode == 3 && commentLevel == 0))
                result.deleteCharAt(i--);
            if (commentLevel == 0) {
                if (start != -1) {
                    end = i;
                    if (removeInnerComments && hadInner) // In this case,
                                                         // check for
                                                         // and remove an empty
                                                         // comment...
                    {
                        int leng = end - curStart - 1;
                        String contents = result.substring(curStart + 1, end - 1);
                        contents = stripExtraSpaces(contents);
                        if (contents.isEmpty() || contents == " ") {
                            result.delete(curStart, end - 1);
                            i = curStart;
                        } else if (stripSpaces && contents.length() != leng) {
                            result.replace(curStart + 1, curStart + leng, contents);
                            i -= leng - contents.length();
                        }
                    }
                }
                hadInner = false;
            } else if (commentLevel == 1 && removeInnerComments) {
                // If we're removing inner comments, get rid of this
                // part of the string, and any space before it.
                int leng = i - innerStart + 1;
                result.delete(innerStart, innerStart + leng);
                i = innerStart - 1;
                while (result.length() > i && result.charAt(i) == ' ')
                    result.deleteCharAt(i--);
            }
        } else if (commentLevel == 0 && (hasText || result.charAt(i) != ' ')) {
            hasText = true;
            wasBrace = false;
            wasSpace = (end == i - 1 && i > 0);
            if (end != -1 && mode > 0) {
                result.delete(start, end + 1);
                i -= end - start + 2;
                // Hmm. How SHOULD spaces around the removed comments
                // be treated? This erases the spaces BEFORE the comment
                while (i >= 0 && result.length() > i && result.charAt(i) == ' ')
                    result.deleteCharAt(i--);
                start = -1;
                end = -1;
            }
        } else
            wasBrace = false;
    }
    if (end != -1 && hasText && mode > 0) {
        result.delete(start, end + 1);
        for (i = result.length() - 1; i >= 0 && result.charAt(i) == ' '; --i)
            result.deleteCharAt(i);
    }
    return result.toString();
}

From source file:de.knightsoftnet.validators.shared.util.RegExUtil.java

/**
 * get all allowed characters which can be part of a String which matches a given regular
 * expression. TODO: this is a first feature incomplete implementation, has to be improved.
 *
 * @param pregEx string contains a regular expression pattern
 * @return string with all characters that can be part of a string that matches the regex
 *//* w  w  w.j  a  va  2 s . c  o m*/
public static String getAllowedCharactersForRegEx(final String pregEx) {
    if (StringUtils.isEmpty(pregEx)) {
        return null;
    }
    final StringBuilder regExCheck = new StringBuilder();
    final StringBuilder regExCheckOut = new StringBuilder();
    boolean inSequence = false;
    boolean isNegativeSequence = false;
    boolean inSize = false;
    boolean isMasked = false;

    regExCheck.append("([");
    for (final char character : pregEx.toCharArray()) {
        switch (character) {
        case '\\':
            if (isMasked || inSequence) {
                regExCheck.append(character);
            }
            if (!inSequence) {
                isMasked = !isMasked;
            }
            break;
        case '^':
            if (inSequence) {
                if (isMasked) {
                    regExCheck.append(character);
                } else {
                    isNegativeSequence = true;
                }
            }
            isMasked = false;
            break;
        case '$':
        case '*':
        case '+':
        case '?':
        case '|':
            if (isMasked || inSequence) {
                regExCheck.append(character);
            }
            isMasked = false;
            break;
        case '[':
            if (isMasked || inSequence) {
                regExCheck.append(character);
            } else {
                inSequence = true;
                isNegativeSequence = false;
            }
            isMasked = false;
            break;
        case ']':
            if (isMasked) {
                regExCheck.append(character);
            } else {
                inSequence = false;
                isNegativeSequence = false;
            }
            isMasked = false;
            break;
        case '{':
            if (isMasked || inSequence) {
                regExCheck.append(character);
            } else {
                inSize = true;
            }
            isMasked = false;
            break;
        case '}':
            if (isMasked || inSequence) {
                regExCheck.append(character);
            } else {
                inSize = false;
            }
            isMasked = false;
            break;
        case '(':
            if (isMasked || inSequence) {
                regExCheck.append(character);
            }
            isMasked = false;
            break;
        case ')':
            if (isMasked || inSequence) {
                regExCheck.append(character);
            }
            isMasked = false;
            break;
        default:
            if (inSize) {
                if (character != ',' && (character < '0' || character > '9')) {
                    regExCheck.append(character);
                }
            } else if (!isNegativeSequence) {
                if (isMasked) {
                    if (regExCheckOut.length() > 1) {
                        regExCheckOut.append('|');
                    }
                    regExCheckOut.append('\\');
                    regExCheckOut.append(character);
                } else {
                    regExCheck.append(character);
                }
            }
            isMasked = false;
            break;
        }
    }
    if (regExCheck.length() < 3) {
        regExCheck.delete(1, regExCheck.length());
    } else {
        regExCheck.append(']');
        if (regExCheckOut.length() > 0) {
            regExCheck.append('|');
        }
    }
    regExCheck.append(regExCheckOut);
    regExCheck.append(')');
    final RegExp regEx = RegExp.compile(regExCheck.toString());
    final StringBuilder result = new StringBuilder();
    for (int count = Character.MIN_VALUE; count < Character.MAX_VALUE; count++) {
        if (regEx.exec(String.valueOf((char) count)) != null) {
            result.append((char) count);
        }
    }
    return result.toString();
}

From source file:com.impetus.client.cassandra.CassandraClientBase.java

/**
 * On delete query./*from w w  w.j  av  a 2 s.c  om*/
 * 
 * @param metadata
 *            the metadata
 * @param tableName
 *            TODO
 * @param metaModel
 *            the meta model
 * @param keyObject
 *            the compound key object
 * @return the string
 */
protected String onDeleteQuery(EntityMetadata metadata, String tableName, MetamodelImpl metaModel,
        Object keyObject) {
    CQLTranslator translator = new CQLTranslator();
    String deleteQuery = CQLTranslator.DELETE_QUERY;

    deleteQuery = StringUtils.replace(deleteQuery, CQLTranslator.COLUMN_FAMILY,
            translator.ensureCase(new StringBuilder(), tableName, false).toString());

    StringBuilder deleteQueryBuilder = new StringBuilder(deleteQuery);

    deleteQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);
    onWhereClause(metadata, keyObject, translator, deleteQueryBuilder, metaModel, metadata.getIdAttribute());

    // strip last "AND" clause.
    deleteQueryBuilder.delete(deleteQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),
            deleteQueryBuilder.length());

    if (log.isDebugEnabled()) {
        log.debug("Returning delete query {}.", deleteQueryBuilder.toString());
    }
    return deleteQueryBuilder.toString();
}

From source file:com.impetus.client.cassandra.CassandraClientBase.java

/**
 * Find inverse join column values for join column.
 * //from  w  w  w .  j a v  a 2  s .  co m
 * @param <E>
 *            the element type
 * @param schemaName
 *            the schema name
 * @param tableName
 *            the table name
 * @param pKeyColumnName
 *            the key column name
 * @param columnName
 *            the column name
 * @param pKeyColumnValue
 *            the key column value
 * @param columnJavaType
 *            the column java type
 * @return the columns by id using cql
 */
protected <E> List<E> getColumnsByIdUsingCql(String schemaName, String tableName, String pKeyColumnName,
        String columnName, Object pKeyColumnValue, Class columnJavaType) {
    // select columnName from tableName where pKeyColumnName =
    // pKeyColumnValue
    List results = new ArrayList();
    CQLTranslator translator = new CQLTranslator();
    String selectQuery = translator.SELECT_QUERY;
    selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,
            translator.ensureCase(new StringBuilder(), tableName, false).toString());
    selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMNS,
            translator.ensureCase(new StringBuilder(), columnName, false).toString());

    StringBuilder selectQueryBuilder = new StringBuilder(selectQuery);

    selectQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);

    translator.buildWhereClause(selectQueryBuilder, columnJavaType, pKeyColumnName, pKeyColumnValue,
            CQLTranslator.EQ_CLAUSE, false);
    selectQueryBuilder.delete(selectQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),
            selectQueryBuilder.length());

    CqlResult cqlResult = execute(selectQueryBuilder.toString(), getRawClient(schemaName));

    Iterator<CqlRow> rowIter = cqlResult.getRows().iterator();
    while (rowIter.hasNext()) {
        CqlRow row = rowIter.next();

        if (!row.getColumns().isEmpty()) {
            Column column = row.getColumns().get(0);
            Object columnValue = CassandraDataTranslator.decompose(columnJavaType, column.getValue(), true);
            results.add(columnValue);
        }
    }
    return results;
}

From source file:net.sourceforge.squirrel_sql.fw.dialects.DialectUtils.java

/**
 * Gets the SQL command to add a unique constraint to a table.
 * //  w w w  .ja  v  a  2  s  .c  om
 * @param tableName
 *           name of the table where the unique constraint should be added to.
 * @param constraintName
 *           name of the constraint.
 * @param columns
 *           the unique columns.
 * @param qualifier
 *           qualifier of the table
 * @param prefs
 *           preferences for generated sql scripts
 * @return the sql command to add a unique constraint.
 */
public static String getAddUniqueConstraintSQL(String tableName, String constraintName,
        TableColumnInfo[] columns, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs,
        HibernateDialect dialect) {
    // ALTER TABLE tableName
    // ADD CONSTRAINT constraintName UNIQUE (column1, column2);
    final StringBuilder sql = new StringBuilder();

    sql.append(DialectUtils.ALTER_TABLE_CLAUSE);
    sql.append(" ");
    sql.append(DialectUtils.shapeQualifiableIdentifier(tableName, qualifier, prefs, dialect));
    sql.append("\n");

    sql.append(" ");
    sql.append(DialectUtils.ADD_CONSTRAINT_CLAUSE);
    sql.append(" ");
    if (prefs.isQuoteConstraintNames()) {
        sql.append(DialectUtils.shapeIdentifier(constraintName, prefs, dialect));
    } else {
        sql.append(constraintName);
    }

    sql.append(" ");
    sql.append(DialectUtils.UNIQUE_CLAUSE);
    sql.append(" (");
    for (final TableColumnInfo column : columns) {
        if (prefs.isQuoteColumnNames()) {
            sql.append(DialectUtils.shapeIdentifier(column.getColumnName(), prefs, dialect));
        } else {
            sql.append(column.getColumnName());
        }
        sql.append(", ");
    }
    sql.delete(sql.length() - 2, sql.length()); // deletes the last ", "
    sql.append(")");

    return sql.toString();
}

From source file:org.apache.fineract.infrastructure.dataqueries.service.ReadWriteNonCoreDataServiceImpl.java

@Transactional
@Override/*from   w ww.  j a va2s  . c  om*/
public CommandProcessingResult createDatatable(final JsonCommand command) {

    String datatableName = null;

    try {
        this.context.authenticatedUser();
        this.fromApiJsonDeserializer.validateForCreate(command.json());

        final JsonElement element = this.fromJsonHelper.parse(command.json());
        final JsonArray columns = this.fromJsonHelper.extractJsonArrayNamed("columns", element);
        datatableName = this.fromJsonHelper.extractStringNamed("datatableName", element);
        final String apptableName = this.fromJsonHelper.extractStringNamed("apptableName", element);
        Boolean multiRow = this.fromJsonHelper.extractBooleanNamed("multiRow", element);

        /***
         * In cases of tables storing hierarchical entities (like m_group),
         * different entities would end up being stored in the same table.
         * 
         * Ex: Centers are a specific type of group, add abstractions for
         * the same
         ***/
        final String actualAppTableName = mapToActualAppTable(apptableName);

        if (multiRow == null) {
            multiRow = false;
        }

        validateDatatableName(datatableName);
        validateAppTable(apptableName);
        final boolean isConstraintApproach = this.configurationDomainService
                .isConstraintApproachEnabledForDatatables();
        final String fkColumnName = apptableName.substring(2) + "_id";
        final String dataTableNameAlias = datatableName.toLowerCase().replaceAll("\\s", "_");
        final String fkName = dataTableNameAlias + "_" + fkColumnName;
        StringBuilder sqlBuilder = new StringBuilder();
        final StringBuilder constrainBuilder = new StringBuilder();
        final Map<String, Long> codeMappings = new HashMap<>();
        sqlBuilder = sqlBuilder.append("CREATE TABLE `" + datatableName + "` (");

        if (multiRow) {
            sqlBuilder = sqlBuilder.append("`id` BIGINT(20) NOT NULL AUTO_INCREMENT, ")
                    .append("`" + fkColumnName + "` BIGINT(20) NOT NULL, ");
        } else {
            sqlBuilder = sqlBuilder.append("`" + fkColumnName + "` BIGINT(20) NOT NULL, ");
        }

        for (final JsonElement column : columns) {
            parseDatatableColumnObjectForCreate(column.getAsJsonObject(), sqlBuilder, constrainBuilder,
                    dataTableNameAlias, codeMappings, isConstraintApproach);
        }

        // Remove trailing comma and space
        sqlBuilder = sqlBuilder.delete(sqlBuilder.length() - 2, sqlBuilder.length());

        if (multiRow) {
            sqlBuilder = sqlBuilder.append(", PRIMARY KEY (`id`)")
                    .append(", KEY `fk_" + apptableName.substring(2) + "_id` (`" + fkColumnName + "`)")
                    .append(", CONSTRAINT `fk_" + fkName + "` ").append("FOREIGN KEY (`" + fkColumnName + "`) ")
                    .append("REFERENCES `" + actualAppTableName + "` (`id`)");
        } else {
            sqlBuilder = sqlBuilder.append(", PRIMARY KEY (`" + fkColumnName + "`)")
                    .append(", CONSTRAINT `fk_" + fkName + "` ").append("FOREIGN KEY (`" + fkColumnName + "`) ")
                    .append("REFERENCES `" + actualAppTableName + "` (`id`)");
        }

        sqlBuilder.append(constrainBuilder);

        sqlBuilder = sqlBuilder.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        this.jdbcTemplate.execute(sqlBuilder.toString());

        registerDatatable(datatableName, apptableName);
        registerColumnCodeMapping(codeMappings);
    } catch (final SQLGrammarException e) {
        final Throwable realCause = e.getCause();
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                .resource("datatable");

        if (realCause.getMessage().toLowerCase().contains("duplicate column name")) {
            baseDataValidator.reset().parameter("name").failWithCode("duplicate.column.name");
        } else if (realCause.getMessage().contains("Table")
                && realCause.getMessage().contains("already exists")) {
            baseDataValidator.reset().parameter("datatableName").value(datatableName)
                    .failWithCode("datatable.already.exists");
        } else if (realCause.getMessage().contains("Column") && realCause.getMessage().contains("big")) {
            baseDataValidator.reset().parameter("column").failWithCode("length.too.big");
        } else if (realCause.getMessage().contains("Row") && realCause.getMessage().contains("large")) {
            baseDataValidator.reset().parameter("row").failWithCode("size.too.large");
        }

        throwExceptionIfValidationWarningsExist(dataValidationErrors);
    }

    return new CommandProcessingResultBuilder().withCommandId(command.commandId())
            .withResourceIdAsString(datatableName).build();
}