Example usage for java.lang StringBuffer setLength

List of usage examples for java.lang StringBuffer setLength

Introduction

In this page you can find the example usage for java.lang StringBuffer setLength.

Prototype

@Override
public synchronized void setLength(int newLength) 

Source Link

Usage

From source file:com.tremolosecurity.provisioning.core.providers.BasicDB.java

@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> wfrequest)
        throws ProvisioningException {
    User foundUser = null;//from w ww  . j ava2 s.  c  o m

    int approvalID = 0;

    if (wfrequest.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) wfrequest.get("APPROVAL_ID");
    }

    Workflow workflow = (Workflow) wfrequest.get("WORKFLOW");

    Set<String> attributesForSearch = new HashSet<String>();
    attributesForSearch.addAll(attributes);
    if (!attributesForSearch.contains(this.userPrimaryKey)) {
        attributesForSearch.add(this.userPrimaryKey);
    }

    try {
        //logger.info("Lookin up user : " + user.getUserID());
        foundUser = this.findUser(user.getUserID(), attributesForSearch, wfrequest);
        //logger.info("Lookin up user result : " + foundUser);

        if (foundUser == null) {
            this.createUser(user, attributes, wfrequest);
            return;
        }
    } catch (Exception e) {
        //logger.info("Creating new user",e);
        if (logger.isDebugEnabled()) {
            logger.debug("Could not create user", e);
        }
        this.createUser(user, attributes, wfrequest);
        return;
    }

    String userID = foundUser.getAttribs().get(this.userPrimaryKey).getValues().get(0);
    int userIDnum = -1;

    try {
        userIDnum = Integer.parseInt(userID);
    } catch (Throwable t) {
        //do nothing
    }

    Connection con;
    try {
        con = this.ds.getConnection();
    } catch (SQLException e) {
        throw new ProvisioningException("Could not obtain connection", e);
    }

    try {
        con.setAutoCommit(false);
        Map<String, Object> request = new HashMap<String, Object>();
        if (this.customDBProvider != null) {
            this.customDBProvider.beginUpdate(con, userIDnum, request);
        }

        StringBuffer b = new StringBuffer();
        for (String attrName : attributes) {
            if (user.getAttribs().containsKey(attrName) && foundUser.getAttribs().containsKey(attrName)
                    && !user.getAttribs().get(attrName).getValues().get(0)
                            .equals(foundUser.getAttribs().get(attrName).getValues().get(0))) {
                if (this.customDBProvider != null) {
                    this.customDBProvider.updateField(con, userIDnum, request, attrName,
                            foundUser.getAttribs().get(attrName).getValues().get(0),
                            user.getAttribs().get(attrName).getValues().get(0));

                } else {
                    PreparedStatement ps = updateField(user, con, b, attrName, userID, userIDnum);
                }

                this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Replace, approvalID,
                        workflow, attrName, user.getAttribs().get(attrName).getValues().get(0));

            } else if (user.getAttribs().containsKey(attrName)
                    && !foundUser.getAttribs().containsKey(attrName)) {
                if (this.customDBProvider != null) {
                    this.customDBProvider.updateField(con, userIDnum, request, attrName, null,
                            user.getAttribs().get(attrName).getValues().get(0));
                } else {
                    PreparedStatement ps = updateField(user, con, b, attrName, userID, userIDnum);
                }

                this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID,
                        workflow, attrName, user.getAttribs().get(attrName).getValues().get(0));

            } else if (!user.getAttribs().containsKey(attrName) && foundUser.getAttribs().containsKey(attrName)
                    && !addOnly) {
                if (this.customDBProvider != null) {
                    this.customDBProvider.clearField(con, userIDnum, request, attrName,
                            foundUser.getAttribs().get(attrName).getValues().get(0));
                } else {
                    PreparedStatement ps = clearField(user, con, b, attrName, userID, userIDnum);
                }

                this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Delete, approvalID,
                        workflow, attrName, foundUser.getAttribs().get(attrName).getValues().get(0));
            }
        }

        if (this.customDBProvider != null) {
            this.customDBProvider.completeUpdate(con, userIDnum, request);
        }

        switch (this.groupMode) {
        case None:
            break;
        case One2Many:

            b.setLength(0);
            b.append("INSERT INTO ").append(this.groupTable).append(" (");
            this.getFieldName(this.groupName, b).append(",");
            this.getFieldName(this.groupUserKey, b).append(") VALUES (?,?)");
            PreparedStatement ps = con.prepareStatement(b.toString());

            for (String groupName : user.getGroups()) {
                if (!foundUser.getGroups().contains(groupName)) {
                    ps.setString(1, groupName);
                    ps.setInt(2, userIDnum);
                    ps.executeUpdate();

                    this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID,
                            workflow, "group", groupName);
                }
            }

            b.setLength(0);
            b.append("DELETE FROM ").append(this.groupTable).append(" WHERE ");
            this.getFieldName(this.groupUserKey, b).append("=? AND ");
            this.getFieldName(this.groupName, b).append("=?");
            ps = con.prepareStatement(b.toString());

            if (!addOnly) {
                for (String groupName : foundUser.getGroups()) {
                    if (!user.getGroups().contains(groupName)) {
                        ps.setInt(1, userIDnum);
                        ps.setString(2, groupName);
                        ps.executeUpdate();
                        this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Delete,
                                approvalID, workflow, "group", groupName);
                    }
                }
            }

            break;
        case Many2Many:
            many2manySyncGroups(user, addOnly, foundUser, userIDnum, con, b, wfrequest);
            break;
        case Custom:
            for (String groupName : user.getGroups()) {
                if (!foundUser.getGroups().contains(groupName)) {
                    this.customDBProvider.addGroup(con, userIDnum, groupName);
                    this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID,
                            workflow, "group", groupName);
                }
            }

            if (!addOnly) {
                for (String groupName : foundUser.getGroups()) {
                    if (!user.getGroups().contains(groupName)) {
                        this.customDBProvider.deleteGroup(con, userIDnum, groupName);
                        this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Delete,
                                approvalID, workflow, "group", groupName);
                    }
                }
            }
        }

        con.commit();

    } catch (Throwable t) {
        if (con != null) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                //do nothing
            }
        }

        throw new ProvisioningException("Could noy sync user", t);
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                //do nothing
            }
        }
    }

}

From source file:com.belle.yitiansystem.merchant.service.impl.MerchantsService.java

/**
 * ??/*from  www  .  j ava2 s  . c  o m*/
 * 
 * @author wang.m
 * @date 2012-05-11
 */
public PageFinder<MerchantRejectedAddress> getMerchantRejectedAddressList(Query query,
        MerchantRejectedAddress merchantRejectedAddress, String brand) {
    CritMap critMap = new CritMap();
    if (null != merchantRejectedAddress) {
        // ??
        if (StringUtils.isNotBlank(merchantRejectedAddress.getSupplierName())) {
            critMap.addLike("supplierName", merchantRejectedAddress.getSupplierName());
        }
        // ?
        if (StringUtils.isNotBlank(merchantRejectedAddress.getSupplierCode())) {
            critMap.addLike("supplierCode", merchantRejectedAddress.getSupplierCode());
        }
        // ??
        if (StringUtils.isNotBlank(merchantRejectedAddress.getConsigneeName())) {
            critMap.addLike("consigneeName", merchantRejectedAddress.getConsigneeName());
        }
        // 
        if (StringUtils.isNotBlank(merchantRejectedAddress.getConsigneePhone())) {
            critMap.addLike("consigneePhone", merchantRejectedAddress.getConsigneePhone());
        }
        // ?
        if (StringUtils.isNotBlank(merchantRejectedAddress.getConsigneeTell())) {
            critMap.addLike("consigneeTell", merchantRejectedAddress.getConsigneeTell());
        }
        // 
        List<String> merchantCodes = new ArrayList<String>();
        if (StringUtils.isNotBlank(merchantRejectedAddress.getSupplierYgContacts())) {
            merchantCodes = supplierYgContactService
                    .getSupplierList(merchantRejectedAddress.getSupplierYgContacts());

        }
        // ?
        List<String> merchantCodes_brand = new ArrayList<String>();
        if (StringUtils.isNotBlank(brand)) {
            List<Brand> brandList = commodityBaseApiService.getBrandListLikeBrandName("%" + brand, (short) 1);
            StringBuffer brand_in = new StringBuffer();
            if (CollectionUtils.isNotEmpty(brandList)) {
                for (Brand brandVo : brandList) {
                    brand_in.append("\"" + brandVo.getBrandNo() + "\",");
                }
                if (brand_in.length() > 0) {
                    brand_in.setLength(brand_in.length() - 1);
                }
                Map<String, String> map = new HashMap<String, String>();
                map.put("brands", brand_in.toString());
                merchantCodes_brand = merchantBrandMapper.queryMerchantByBrands(map);
            }
        }
        // ??merchantCodelist
        if (CollectionUtils.isNotEmpty(merchantCodes) && CollectionUtils.isNotEmpty(merchantCodes_brand)) {
            merchantCodes.retainAll(merchantCodes_brand);
            if (null != merchantCodes && merchantCodes.size() > 0) {
                critMap.addIN("supplierCode", merchantCodes.toArray());
            }
        } else if (CollectionUtils.isNotEmpty(merchantCodes)) {
            critMap.addIN("supplierCode", merchantCodes.toArray());
        } else if (CollectionUtils.isNotEmpty(merchantCodes_brand)) {
            critMap.addIN("supplierCode", merchantCodes_brand.toArray());
        }

        critMap.addDesc("createrTime");
    }

    PageFinder<MerchantRejectedAddress> pageFinder = merchantRejectedAddressDaoImpl.pagedByCritMap(critMap,
            query.getPage(), query.getPageSize());

    // PageFinder<MerchantRejectedAddress> pageFinder =
    // merchantRejectedAddressDaoImpl.pagedByHQL(hql, toPage, pageSize,
    // values)
    return pageFinder;
}

From source file:cgeo.geocaching.cgBase.java

/**
 * Replace the characters \n, \r and \t with a space
 *
 * @param buffer//from   w ww .ja v  a  2s.c  o m
 *            The data
 */
public static void replaceWhitespace(final StringBuffer buffer) {
    final int length = buffer.length();
    final char[] chars = new char[length];
    buffer.getChars(0, length, chars, 0);
    int resultSize = 0;
    boolean lastWasWhitespace = false;
    for (char c : chars) {
        if (c == ' ' || c == '\n' || c == '\r' || c == '\t') {
            if (!lastWasWhitespace) {
                chars[resultSize++] = ' ';
            }
            lastWasWhitespace = true;
        } else {
            chars[resultSize++] = c;
            lastWasWhitespace = false;
        }
    }
    buffer.setLength(0);
    buffer.append(chars);
}

From source file:org.alfresco.jlan.server.filesys.db.DBDiskDriver.java

/**
 * Convert a file id to a share relative path
 *
 * @param sess SrvSession/*from  www  . j  a v  a 2  s  .  c  om*/
 * @param tree TreeConnection
 * @param dirid int
 * @param fileid
 * @return String
 * @exception FileNotFoundException 
 */
public String buildPathForFileId(SrvSession sess, TreeConnection tree, int dirid, int fileid)
        throws FileNotFoundException {

    // Access the JDBC context
    String userName = sess.getClientInformation().getUserName();
    String shareName = tree.getContext().getShareName();
    DBDeviceContext dbCtx = (DBDeviceContext) tree.getContext();
    //  Build an array of folder names working back from the files id

    ArrayList<String> names = new ArrayList<String>(16);
    log4j.debug("DBD#buildPathForFileId ; dirid:" + dirid + " , fileid:" + fileid + " , shareName:" + shareName
            + ", userName:" + userName);
    try {

        int userId = 0;
        UserBean user = dbCtx.getDBInterface().getUserByUsername(userName);
        if (null != user) {
            userId = user.getId();
        } else {
            log4j.error("User is not exist from database ,userId:" + userId + ", username:" + userName);
            return null;
        }

        //  Loop, walking backwards up the tree until we hit root

        int curFid = fileid;
        int curDid = dirid;

        FileInfo finfo = null;

        do {

            //  Search for the current file in the database
            log4j.debug("do: curDid:" + curDid + " , curFid:" + curFid);
            finfo = dbCtx.getDBInterface().getFileInformation(curDid, curFid, DBInterface.FileIds, userId,
                    shareName, userName);

            if (finfo != null) {
                //  Get the filename

                names.add(finfo.getFileName());

                //  The directory id becomes the next file id to search for

                curFid = finfo.getDirectoryId();
                curDid = -1;
            } else {
                log4j.warn("FileNotFoundException ; curFid:" + curFid);
                throw new FileNotFoundException("" + curFid);
            }

        } while (curFid > 0);
    } catch (DBException ex) {
        log4j.error(ex);
        return null;
    }

    //  Build the path string

    StringBuffer pathStr = new StringBuffer(256);
    pathStr.append(FileName.DOS_SEPERATOR_STR);

    for (int i = names.size() - 1; i >= 0; i--) {
        pathStr.append(names.get(i));
        pathStr.append(FileName.DOS_SEPERATOR_STR);
    }

    //  Remove the trailing slash from the path

    if (pathStr.length() > 0)
        pathStr.setLength(pathStr.length() - 1);

    //  Return the path string

    return pathStr.toString();
}

From source file:org.alfresco.jlan.server.filesys.db.DBDiskWasLDriver.java

/**
 * Convert a file id to a share relative path
 *
 * @param sess SrvSession//  w w w.j  a v a 2 s .c  o m
 * @param tree TreeConnection
 * @param dirid int
 * @param fileid
 * @return String
 * @exception FileNotFoundException 
 */
public String buildPathForFileId(SrvSession sess, TreeConnection tree, int dirid, int fileid)
        throws FileNotFoundException {

    // Access the JDBC context
    String userName = sess.getClientInformation().getUserName();
    String shareName = tree.getContext().getShareName();
    log4j.error("\n\n\nDBD#buildPathForFileId ; shareName ??, shareName:" + shareName
            + ", userName:" + userName + "\n\n\n");

    DBDeviceContext dbCtx = (DBDeviceContext) tree.getContext();
    //  Build an array of folder names working back from the files id

    ArrayList<String> names = new ArrayList<String>(16);
    log4j.debug("DBD#buildPathForFileId ; dirid:" + dirid + " , fileid:" + fileid + " , shareName:" + shareName
            + ", userName:" + userName);
    try {

        int userId = 0;
        UserBean user = dbCtx.getDBInterface().getUserByUsername(userName);
        if (null != user) {
            userId = user.getId();
        } else {
            log4j.error("User is not exist from database ,userId:" + userId + ", username:" + userName);
            return null;
        }

        //  Loop, walking backwards up the tree until we hit root

        int curFid = fileid;
        int curDid = dirid;

        FileInfo finfo = null;

        do {

            //  Search for the current file in the database
            log4j.debug("do: curDid:" + curDid + " , curFid:" + curFid);
            finfo = dbCtx.getDBInterface().getFileInformation(curDid, curFid, DBInterface.FileIds, userId,
                    shareName, userName);

            if (finfo != null) {
                //  Get the filename

                names.add(finfo.getFileName());

                //  The directory id becomes the next file id to search for

                curFid = finfo.getDirectoryId();
                curDid = -1;
            } else {
                log4j.warn("FileNotFoundException ; curFid:" + curFid);
                throw new FileNotFoundException("" + curFid);
            }

        } while (curFid > 0);
    } catch (DBException ex) {
        log4j.error(ex);
        return null;
    }

    //  Build the path string

    StringBuffer pathStr = new StringBuffer(256);
    pathStr.append(FileName.DOS_SEPERATOR_STR);

    for (int i = names.size() - 1; i >= 0; i--) {
        pathStr.append(names.get(i));
        pathStr.append(FileName.DOS_SEPERATOR_STR);
    }

    //  Remove the trailing slash from the path

    if (pathStr.length() > 0)
        pathStr.setLength(pathStr.length() - 1);

    //  Return the path string

    return pathStr.toString();
}

From source file:org.pentaho.di.core.database.Database.java

/**
 * Execute an SQL statement inside a file on the database connection (has to be open)
 *
 * @param sql/*  w w w . j a  v  a  2  s . com*/
 *          The file that contains SQL to execute
 * @sendSinglestatement send one statement
 * @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
 * @throws KettleDatabaseException
 *           in case anything goes wrong.
 */
public Result execStatementsFromFile(String filename, boolean sendSinglestatement) throws KettleException {
    FileObject sqlFile = null;
    InputStream is = null;
    InputStreamReader bis = null;
    try {
        if (Const.isEmpty(filename)) {
            throw new KettleException("Filename is missing!");
        }
        sqlFile = KettleVFS.getFileObject(filename);
        if (!sqlFile.exists()) {
            throw new KettleException("We can not find file [" + filename + "]!");
        }

        is = KettleVFS.getInputStream(sqlFile);
        bis = new InputStreamReader(new BufferedInputStream(is, 500));
        StringBuffer lineStringBuffer = new StringBuffer(256);
        lineStringBuffer.setLength(0);

        BufferedReader buff = new BufferedReader(bis);
        String sLine = null;
        String sql = Const.CR;

        while ((sLine = buff.readLine()) != null) {
            if (Const.isEmpty(sLine)) {
                sql = sql + Const.CR;
            } else {
                sql = sql + Const.CR + sLine;
            }
        }

        if (sendSinglestatement) {
            return execStatement(sql);
        } else {
            return execStatements(sql);
        }

    } catch (Exception e) {
        throw new KettleException(e);
    } finally {
        try {
            if (sqlFile != null) {
                sqlFile.close();
            }
            if (is != null) {
                is.close();
            }
            if (bis != null) {
                bis.close();
            }
        } catch (Exception e) {
            // Ignore
        }
    }
}

From source file:org.apache.ddlutils.io.TestDatabaseIO.java

/**
 * Tests a database model containing foreignkeys with onUpdate values.
 *///from  w w  w. j a  va2 s .  c  o m
public void testForeignkeysWithOnUpdate() throws Exception {
    StringBuffer modelXml = new StringBuffer();

    modelXml.append("<database xmlns='" + DatabaseIO.DDLUTILS_NAMESPACE + "' name='test'>\n");
    modelXml.append("  <table name='SomeTable'\n");
    modelXml.append("         description='Some table'>\n");
    modelXml.append("    <column name='ID'\n");
    modelXml.append("            type='VARCHAR'\n");
    modelXml.append("            size='16'\n");
    modelXml.append("            primaryKey='true'\n");
    modelXml.append("            required='true'\n");
    modelXml.append("            description='The primary key'/>\n");
    modelXml.append("  </table>\n");
    modelXml.append("  <table name='AnotherTable'\n");
    modelXml.append("         description='And another table'>\n");
    modelXml.append("    <column name='Some_ID'\n");
    modelXml.append("            type='VARCHAR'\n");
    modelXml.append("            size='16'\n");
    modelXml.append("            description='The foreign key'/>\n");
    for (Iterator it = CascadeActionEnum.iterator(); it.hasNext();) {
        CascadeActionEnum enumValue = (CascadeActionEnum) it.next();

        modelXml.append("    <foreign-key name='foreignkey ");
        modelXml.append(enumValue.getName());
        modelXml.append("' foreignTable='SomeTable' onUpdate='");
        modelXml.append(enumValue.getName());
        modelXml.append("'>\n");
        modelXml.append("       <reference local='Some_ID' foreign='ID'/>\n");
        modelXml.append("    </foreign-key>\n");
    }
    modelXml.append("  </table>\n");
    modelXml.append("</database>");

    Database model = readModel(modelXml.toString());

    assertEquals("test", model.getName());
    assertEquals(2, model.getTableCount());

    Table someTable = model.getTable(0);

    assertEquals("SomeTable", "Some table", 1, 1, 0, 0, 0, someTable);
    assertEquals("ID", Types.VARCHAR, 16, 0, null, "The primary key", null, true, true, false,
            someTable.getColumn(0));

    Table anotherTable = model.getTable(1);

    assertEquals("AnotherTable", "And another table", 1, 0, 0, CascadeActionEnum.getEnumList().size(), 0,
            anotherTable);
    assertEquals("Some_ID", Types.VARCHAR, 16, 0, null, "The foreign key", null, false, false, false,
            anotherTable.getColumn(0));

    int idx = 0;

    for (Iterator it = CascadeActionEnum.iterator(); it.hasNext(); idx++) {
        CascadeActionEnum enumValue = (CascadeActionEnum) it.next();
        ForeignKey fk = anotherTable.getForeignKey(idx);

        assertEquals("foreignkey " + enumValue.getName(), enumValue, CascadeActionEnum.NONE, someTable, 1, fk);
        assertEquals(anotherTable.getColumn(0), someTable.getColumn(0), fk.getReference(0));
    }

    modelXml.setLength(0);
    modelXml.append("<?xml version='1.0' encoding='UTF-8'?>\n");
    modelXml.append("<database xmlns=\"" + DatabaseIO.DDLUTILS_NAMESPACE + "\" name=\"test\">\n");
    modelXml.append("  <table name=\"SomeTable\" description=\"Some table\">\n");
    modelXml.append(
            "    <column name=\"ID\" primaryKey=\"true\" required=\"true\" type=\"VARCHAR\" size=\"16\" autoIncrement=\"false\" description=\"The primary key\" />\n");
    modelXml.append("  </table>\n");
    modelXml.append("  <table name=\"AnotherTable\" description=\"And another table\">\n");
    modelXml.append(
            "    <column name=\"Some_ID\" primaryKey=\"false\" required=\"false\" type=\"VARCHAR\" size=\"16\" autoIncrement=\"false\" description=\"The foreign key\" />\n");
    for (Iterator it = CascadeActionEnum.iterator(); it.hasNext(); idx++) {
        CascadeActionEnum enumValue = (CascadeActionEnum) it.next();

        modelXml.append("    <foreign-key foreignTable=\"SomeTable\" name=\"foreignkey ");
        modelXml.append(enumValue.getName());
        if (enumValue != CascadeActionEnum.NONE) {
            modelXml.append("\" onUpdate=\"");
            modelXml.append(enumValue.getName());
        }
        modelXml.append("\">\n");
        modelXml.append("      <reference local=\"Some_ID\" foreign=\"ID\" />\n");
        modelXml.append("    </foreign-key>\n");
    }
    modelXml.append("  </table>\n");
    modelXml.append("</database>\n");

    assertEquals(modelXml.toString(), model);
}

From source file:org.apache.ddlutils.io.TestDatabaseIO.java

/**
 * Tests a database model containing foreignkeys with onDelete values.
 *///from w  ww .ja  va 2s .co m
public void testForeignkeysWithOnDelete() throws Exception {
    StringBuffer modelXml = new StringBuffer();

    modelXml.append("<database xmlns='" + DatabaseIO.DDLUTILS_NAMESPACE + "' name='test'>\n");
    modelXml.append("  <table name='SomeTable'\n");
    modelXml.append("         description='Some table'>\n");
    modelXml.append("    <column name='ID'\n");
    modelXml.append("            type='VARCHAR'\n");
    modelXml.append("            size='16'\n");
    modelXml.append("            primaryKey='true'\n");
    modelXml.append("            required='true'\n");
    modelXml.append("            description='The primary key'/>\n");
    modelXml.append("  </table>\n");
    modelXml.append("  <table name='AnotherTable'\n");
    modelXml.append("         description='And another table'>\n");
    modelXml.append("    <column name='Some_ID'\n");
    modelXml.append("            type='VARCHAR'\n");
    modelXml.append("            size='16'\n");
    modelXml.append("            description='The foreign key'/>\n");
    for (Iterator it = CascadeActionEnum.iterator(); it.hasNext();) {
        CascadeActionEnum enumValue = (CascadeActionEnum) it.next();

        modelXml.append("    <foreign-key name='foreignkey ");
        modelXml.append(enumValue.getName());
        modelXml.append("' foreignTable='SomeTable' onDelete='");
        modelXml.append(enumValue.getName());
        modelXml.append("'>\n");
        modelXml.append("       <reference local='Some_ID' foreign='ID'/>\n");
        modelXml.append("    </foreign-key>\n");
    }
    modelXml.append("  </table>\n");
    modelXml.append("</database>");

    Database model = readModel(modelXml.toString());

    assertEquals("test", model.getName());
    assertEquals(2, model.getTableCount());

    Table someTable = model.getTable(0);

    assertEquals("SomeTable", "Some table", 1, 1, 0, 0, 0, someTable);
    assertEquals("ID", Types.VARCHAR, 16, 0, null, "The primary key", null, true, true, false,
            someTable.getColumn(0));

    Table anotherTable = model.getTable(1);

    assertEquals("AnotherTable", "And another table", 1, 0, 0, CascadeActionEnum.getEnumList().size(), 0,
            anotherTable);
    assertEquals("Some_ID", Types.VARCHAR, 16, 0, null, "The foreign key", null, false, false, false,
            anotherTable.getColumn(0));

    int idx = 0;

    for (Iterator it = CascadeActionEnum.iterator(); it.hasNext(); idx++) {
        CascadeActionEnum enumValue = (CascadeActionEnum) it.next();
        ForeignKey fk = anotherTable.getForeignKey(idx);

        assertEquals("foreignkey " + enumValue.getName(), CascadeActionEnum.NONE, enumValue, someTable, 1, fk);
        assertEquals(anotherTable.getColumn(0), someTable.getColumn(0), fk.getReference(0));
    }

    modelXml.setLength(0);
    modelXml.append("<?xml version='1.0' encoding='UTF-8'?>\n");
    modelXml.append("<database xmlns=\"" + DatabaseIO.DDLUTILS_NAMESPACE + "\" name=\"test\">\n");
    modelXml.append("  <table name=\"SomeTable\" description=\"Some table\">\n");
    modelXml.append(
            "    <column name=\"ID\" primaryKey=\"true\" required=\"true\" type=\"VARCHAR\" size=\"16\" autoIncrement=\"false\" description=\"The primary key\" />\n");
    modelXml.append("  </table>\n");
    modelXml.append("  <table name=\"AnotherTable\" description=\"And another table\">\n");
    modelXml.append(
            "    <column name=\"Some_ID\" primaryKey=\"false\" required=\"false\" type=\"VARCHAR\" size=\"16\" autoIncrement=\"false\" description=\"The foreign key\" />\n");
    for (Iterator it = CascadeActionEnum.iterator(); it.hasNext(); idx++) {
        CascadeActionEnum enumValue = (CascadeActionEnum) it.next();

        modelXml.append("    <foreign-key foreignTable=\"SomeTable\" name=\"foreignkey ");
        modelXml.append(enumValue.getName());
        if (enumValue != CascadeActionEnum.NONE) {
            modelXml.append("\" onDelete=\"");
            modelXml.append(enumValue.getName());
        }
        modelXml.append("\">\n");
        modelXml.append("      <reference local=\"Some_ID\" foreign=\"ID\" />\n");
        modelXml.append("    </foreign-key>\n");
    }
    modelXml.append("  </table>\n");
    modelXml.append("</database>\n");

    assertEquals(modelXml.toString(), model);
}

From source file:com.pureinfo.studio.db.txt2SRM.impl.SchoolSCITxtImportRunner.java

/**
 * @throws Exception//w ww .ja  v a  2 s.  co m
 */
public int run(String _sFileName, List _errorDataList, List _repeatList, boolean _bBreakenIfError,
        int _nChooseIfRepeat) throws PureException {
    if (m_xmlConfig == null) {
        throw new PureException(PureException.SETTING_MISSING, "please call config() first");
    }

    long lStart = System.currentTimeMillis();
    IObjects objs = null;
    DolphinObject oldObj, newObj;
    Class clazz = m_entityMetadata.getEntityClass();
    int nCount = 1;

    boolean isToTemp = isToTemp();
    try {
        prepare();
        objs = this.loadOld(_sFileName, m_sDivide);
        String sViewProperty = m_xmlConfig.attributeValue("view-property");
        if (sViewProperty == null || (sViewProperty = sViewProperty.trim()).length() == 0) {
            sViewProperty = "ID";
        } else {
            sViewProperty = sViewProperty.toUpperCase();
        }

        while ((oldObj = objs.next()) != null) {
            // if EI:
            if (oldObj.getStrProperty("Title") != null) {
                if (oldObj.getProperty("Ei classification codes") == null
                        || oldObj.getPropertyAsString("Document type").startsWith("Conference article")) {

                    continue;
                }
            }

            List errorDataEachList = new ArrayList();
            StringBuffer error = new StringBuffer();

            if (checkObjIsNull(oldObj, sViewProperty))
                continue;

            oldObj = changeOldObjPropertysFitToSystems(oldObj);

            // it will be checked in the last,so at the beganning ,we will
            // new an instance.
            newObj = (DolphinObject) clazz.newInstance();

            copy(oldObj, newObj, errorDataEachList);

            getFirstValue(oldObj, newObj);

            if (errorDataEachList.size() > 0) {
                error.append("" + nCount + ":");
                for (int i = 0; i < errorDataEachList.size(); i++) {
                    error.append(errorDataEachList.get(i));
                    logger.debug(errorDataEachList.get(i));
                }
            }
            errorDataEachList.clear();

            convert(oldObj, newObj, errorDataEachList);

            if (errorDataEachList.size() > 0) {
                if (error.length() <= 0)
                    error.append("" + nCount + ":");
                for (int i = 0; i < errorDataEachList.size(); i++) {
                    error.append("" + errorDataEachList.get(i) + ",");
                }
            }
            errorDataEachList.clear();

            String errorEach = (error.length() > 0 ? error.toString() : "");

            fill(oldObj, newObj, _nChooseIfRepeat);

            mappingProperties(newObj);

            makeIsFirstDept4SCIImport(oldObj, newObj);

            conversAuthors2insideAuthorInfo(newObj, oldObj);

            beforeSave(newObj, errorDataEachList);

            changeNewObjPropertysFitToSystems(newObj);

            for (int i = 0; i < errorDataEachList.size(); i++) {
                String errorElement = errorDataEachList.get(i).toString();
                if (errorEach.indexOf(errorElement) > 0) {
                    errorDataEachList.remove(errorElement);
                }
            }
            if (errorDataEachList.size() > 0) {
                if (error.length() <= 0)
                    error.append("" + nCount + ":");
                for (int i = 0; i < errorDataEachList.size(); i++) {
                    error.append("" + errorDataEachList.get(i) + " ");
                }
            }

            errorDataEachList.clear();

            convert2RelatedTable(newObj, oldObj, true, errorDataEachList, Xls2srmForm.COVERDATAWHENREPEAT);

            if (errorDataEachList.size() > 0) {
                if (error.length() <= 0)
                    error.append("" + nCount + ":");
                for (int i = 0; i < errorDataEachList.size(); i++) {
                    error.append(errorDataEachList.get(i));
                }
            }

            errorDataEachList.clear();

            if (error.length() > 0) {
                _errorDataList.add(error.toString());
            }

            if (error.length() > 0) {
                error.setLength(0);
                if (_bBreakenIfError) {
                    logger.debug("" + nCount + "");
                    break;
                }

                logger.debug("" + nCount + "");
                nCount++;
                continue;

            }
            error.setLength(0);

            if (_nChooseIfRepeat == Xls2srmForm.JUSTFORCHECK) {
                // newObj = makeNewObject2(clazz, newObj,
                // Xls2srmForm.COVERDATAWHENREPEAT);
            } else {
                newObj = makeNewObject2(clazz, newObj, _nChooseIfRepeat, isToTemp);
                // System.out.println(">>>" + newObj);
            }
            if (newObj == null) {
                if (_nChooseIfRepeat == Xls2srmForm.MERGEDATAWHENREPEAT) {
                    _repeatList.add("" + nCount + "!");
                } else {
                    _repeatList.add("" + nCount + "!");
                }
                nCount++;
                continue;
            }

            if (_nChooseIfRepeat != Xls2srmForm.JUSTFORCHECK) {

                save(newObj);
                convert2RelatedTable(newObj, oldObj, false, errorDataEachList, _nChooseIfRepeat);
            }

            nCount++;

        } // endwhile
        lastUpdate();

        long lEnd = System.currentTimeMillis();
        logger.debug(clazz.getName() + ": all finished - time used: " + (lEnd - lStart) + "ms");
    } catch (Exception ex) {
        throw new PureException(PureException.DATABASE_ACCESS, "class=" + clazz.getName(), ex);
    } finally {
        if (objs != null)
            objs.clear();
    }
    return nCount - 1;
}

From source file:com.pureinfo.studio.db.xls2srm.impl.XlsImportRunner.java

private DolphinObject makeNewObject2(Class _clazz, DolphinObject _newObj, int _nChooseIfRepeat,
        boolean isToTemp) throws Exception {
    DolphinObject newObj = null;//ww w  .  j  a  v a 2s  .c om
    StringBuffer sbuff = null;
    boolean bStringProperty;
    String strSQL = m_xmlConfig.elementTextTrim("match-properties");
    if (strSQL != null && strSQL.length() > 0) {
        StringTokenizer st = new StringTokenizer(strSQL, ",", false);
        // 
        if (isToTemp) {
            sbuff = new StringBuffer("select * from {this}0 where ");
        } else {
            sbuff = new StringBuffer("select * from {this} where ");
        }
        try {
            String sValue;
            while (st.hasMoreElements()) {
                sValue = (String) st.nextElement();

                // sValue = StrUtil.sqlEncode(sValue);
                if (_newObj.getProperty(sValue) != null) {

                    bStringProperty = _newObj.getProperty(sValue) instanceof String
                            || _newObj.getProperty(sValue) instanceof Date;
                    if ((bStringProperty && _newObj.getPropertyAsString(sValue).trim().length() > 0)
                            || (!bStringProperty)) {
                        sbuff.append("{this.");
                        sbuff.append(sValue);
                        sbuff.append("}=");

                        if (bStringProperty)
                            sbuff.append("'");

                        String sPropertyValue = _newObj.getPropertyAsString(sValue);
                        //  
                        // sPropertyValue = sPropertyValue.replaceAll(":",
                        // "");
                        while (sPropertyValue.indexOf("{") >= 0) {
                            sPropertyValue = sPropertyValue.substring(0, sPropertyValue.indexOf("{"))
                                    + sPropertyValue.substring(sPropertyValue.indexOf("{") + 1,
                                            sPropertyValue.length());
                        }
                        while (sPropertyValue.indexOf("}") >= 0) {
                            sPropertyValue = sPropertyValue.substring(0, sPropertyValue.indexOf("}"))
                                    + sPropertyValue.substring(sPropertyValue.indexOf("}") + 1,
                                            sPropertyValue.length());
                        }
                        sPropertyValue = StrUtil.escapeEncode(sPropertyValue);
                        sPropertyValue = StrUtil.sqlEncode(sPropertyValue);
                        sPropertyValue = removeBlank(sPropertyValue);

                        sbuff.append(sPropertyValue);
                        if (bStringProperty)
                            sbuff.append("'");
                        sbuff.append(" and ");
                    }
                }
            }
            int nLength = sbuff.length() - 5;
            sbuff.setLength(nLength);
            strSQL = sbuff.toString();
        } finally {
            sbuff.setLength(0);
        }

        ISession session = getSession();
        logger.debug("to make new obj from sql:" + strSQL);
        IStatement query = session.createQuery(strSQL, _clazz, 1);
        IObjects objs = null;
        try {
            objs = query.executeQuery(false);
            newObj = objs.next();
            logger.debug(">>>>>>>>>>>>" + (newObj == null));
        } finally {
            DolphinHelper.clear(objs, query);
        }
    }

    if (newObj == null) {
        if (_nChooseIfRepeat == Xls2srmForm.MERGEDATAWHENREPEAT) {
            newObj = null;
        } else {
            newObj = _newObj;
        }
    } else {
        switch (_nChooseIfRepeat) {
        // 
        case Xls2srmForm.NEWDATAWHENREPEAT:
            newObj = _newObj;
            break;
        // 
        case Xls2srmForm.LEAPDATAWHENREPEAT:
            newObj = null;
            break;
        // 
        case Xls2srmForm.COVERDATAWHENREPEAT:
            String sExcludeProps = m_xmlConfig.elementTextTrim("exclude-props-overrite");
            if (sExcludeProps == null || sExcludeProps.length() == 0) {
                DolphinUtil.copyUpdateableProperties(_newObj, newObj);
            } else {
                Iterator iter = _newObj.getProperties(false).entrySet().iterator();
                sExcludeProps = ',' + sExcludeProps + ',';
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String sName = (String) entry.getKey();
                    if (entry.getValue() != null && sExcludeProps.indexOf("," + sName + ",") < 0) {
                        newObj.setProperty(sName, entry.getValue());
                    }
                }
            }
            break;
        // 
        case Xls2srmForm.MERGEDATAWHENREPEAT: {
            String strMatchSQL = m_xmlConfig.elementTextTrim("merge-properties");
            if (strMatchSQL != null && strMatchSQL.length() > 0) {
                StringTokenizer st2 = new StringTokenizer(strMatchSQL, ",", false);
                String sValue2;
                while (st2.hasMoreElements()) {
                    sValue2 = (String) st2.nextElement();
                    if (_newObj.getProperty(sValue2) != null) {
                        newObj.setProperty(sValue2, _newObj.getProperty(sValue2));
                    }
                }
            }
            // newObj.update();
            break;
        }

        default:
            throw new PureException(PureException.INVALID_VALUE, "");
        }

    }
    return newObj;
}