Example usage for java.sql PreparedStatement setShort

List of usage examples for java.sql PreparedStatement setShort

Introduction

In this page you can find the example usage for java.sql PreparedStatement setShort.

Prototype

void setShort(int parameterIndex, short x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java short value.

Usage

From source file:ro.nextreports.engine.queryexec.QueryExecutor.java

private void setParameterValue(PreparedStatement pstmt, Class paramValueClass, Object paramValue, int index)
        throws SQLException, QueryException {

    // for "NOT IN (?)" setting null -> result is undeterminated
    // ParameterUtil.NULL was good only for list of strings (for NOT IN)!
    if (ParameterUtil.NULL.equals(paramValue)) {
        paramValue = null;//from w w  w.  java2  s.  com
    }
    if (paramValueClass.equals(Object.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.JAVA_OBJECT);
        } else {
            if (paramValue instanceof IdName) {
                pstmt.setObject(index + 1, ((IdName) paramValue).getId());
            } else {
                pstmt.setObject(index + 1, paramValue);
            }
        }
    } else if (paramValueClass.equals(Boolean.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.BIT);
        } else {
            if (paramValue instanceof IdName) {
                pstmt.setBoolean(index + 1, (Boolean) ((IdName) paramValue).getId());
            } else {
                pstmt.setBoolean(index + 1, (Boolean) paramValue);
            }
        }
    } else if (paramValueClass.equals(Byte.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.TINYINT);
        } else {
            if (paramValue instanceof IdName) {
                pstmt.setByte(index + 1, (Byte) ((IdName) paramValue).getId());
            } else {
                pstmt.setByte(index + 1, (Byte) paramValue);
            }
        }
    } else if (paramValueClass.equals(Double.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.DOUBLE);
        } else {
            if (paramValue instanceof IdName) {
                pstmt.setDouble(index + 1, (Double) ((IdName) paramValue).getId());
            } else {
                pstmt.setDouble(index + 1, (Double) paramValue);
            }
        }
    } else if (paramValueClass.equals(Float.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.FLOAT);
        } else {
            if (paramValue instanceof IdName) {
                pstmt.setFloat(index + 1, (Float) ((IdName) paramValue).getId());
            } else {
                pstmt.setFloat(index + 1, (Float) paramValue);
            }
        }
    } else if (paramValueClass.equals(Integer.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.INTEGER);
        } else {
            if (paramValue instanceof IdName) {
                pstmt.setObject(index + 1, ((IdName) paramValue).getId());
            } else {
                pstmt.setInt(index + 1, (Integer) paramValue);
            }
        }
    } else if (paramValueClass.equals(Long.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.BIGINT);
        } else {
            if (paramValue instanceof IdName) {
                pstmt.setLong(index + 1, (Long) ((IdName) paramValue).getId());
            } else {
                pstmt.setLong(index + 1, (Long) paramValue);
            }
        }
    } else if (paramValueClass.equals(Short.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.SMALLINT);
        } else {
            if (paramValue instanceof IdName) {
                pstmt.setShort(index + 1, (Short) ((IdName) paramValue).getId());
            } else {
                pstmt.setShort(index + 1, (Short) paramValue);
            }
        }

        //@todo    
        // ParameterUtil -> values are taken from dialect (where there is no BigDecimal yet!)
        // or from meta  data
    } else if (paramValueClass.equals(BigDecimal.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.DECIMAL);
        } else {
            if (paramValue instanceof IdName) {
                Serializable ser = ((IdName) paramValue).getId();
                if (ser instanceof BigDecimal) {
                    pstmt.setBigDecimal(index + 1, (BigDecimal) (ser));
                } else {
                    pstmt.setInt(index + 1, (Integer) (ser));
                }
            } else {
                // a simple value cannot be cast to BigDecimal!                   
                pstmt.setObject(index + 1, paramValue);
            }
        }
    } else if (paramValueClass.equals(BigInteger.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.BIGINT);
        } else {
            if (paramValue instanceof IdName) {
                Serializable ser = ((IdName) paramValue).getId();
                if (ser instanceof BigInteger) {
                    pstmt.setBigDecimal(index + 1, new BigDecimal((BigInteger) (ser)));
                } else if (ser instanceof BigDecimal) {
                    pstmt.setBigDecimal(index + 1, (BigDecimal) (ser));
                } else {
                    pstmt.setInt(index + 1, (Integer) (ser));
                }
            } else {
                // a simple value cannot be cast to BigDecimal!                   
                pstmt.setObject(index + 1, paramValue);
            }
        }
    } else if (paramValueClass.equals(String.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.VARCHAR);
        } else {
            if (paramValue instanceof IdName) {
                if (((IdName) paramValue).getId() == null) {
                    pstmt.setNull(index + 1, Types.VARCHAR);
                } else {
                    pstmt.setString(index + 1, ((IdName) paramValue).getId().toString());
                }
            } else {
                pstmt.setString(index + 1, paramValue.toString());
            }
        }
    } else if (paramValueClass.equals(Date.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.DATE);
        } else {
            if (paramValue instanceof IdName) {
                Serializable obj = ((IdName) paramValue).getId();
                Date date;
                if (obj instanceof String) {
                    try {
                        date = IdNameRenderer.sdf.parse((String) obj);
                    } catch (ParseException e) {
                        e.printStackTrace();
                        LOG.error(e.getMessage(), e);
                        date = new Date();
                    }
                } else {
                    date = (Date) obj;
                }
                pstmt.setDate(index + 1, new java.sql.Date(date.getTime()));
            } else {
                pstmt.setDate(index + 1, new java.sql.Date(((Date) paramValue).getTime()));
            }
        }
    } else if (paramValueClass.equals(Timestamp.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.TIMESTAMP);
        } else {
            if (paramValue instanceof IdName) {
                Serializable obj = ((IdName) paramValue).getId();
                Date date;
                if (obj instanceof String) {
                    try {
                        date = IdNameRenderer.sdf.parse((String) obj);
                    } catch (ParseException e) {
                        e.printStackTrace();
                        LOG.error(e.getMessage(), e);
                        date = new Date();
                    }
                } else {
                    date = (Date) obj;
                }

                pstmt.setTimestamp(index + 1, new Timestamp(date.getTime()));
            } else {
                pstmt.setTimestamp(index + 1, new Timestamp(((Date) paramValue).getTime()));
            }
        }
    } else if (paramValueClass.equals(Time.class)) {
        if (paramValue == null) {
            pstmt.setNull(index + 1, Types.TIME);
        } else {
            if (paramValue instanceof IdName) {
                Serializable obj = ((IdName) paramValue).getId();
                Date date;
                if (obj instanceof String) {
                    try {
                        date = IdNameRenderer.sdf.parse((String) obj);
                    } catch (ParseException e) {
                        e.printStackTrace();
                        LOG.error(e.getMessage(), e);
                        date = new Date();
                    }
                } else {
                    date = (Date) obj;
                }
                pstmt.setTime(index + 1, new Time(date.getTime()));
            } else {
                pstmt.setTime(index + 1, new Time(((Date) paramValue).getTime()));
            }
        }
    } else {
        throw new QueryException("Parameter type " + paramValueClass.getName() + " not supported in query");
    }

    // for logSql()
    statementParameters.put(index, paramValue);
}

From source file:org.apache.ctakes.ytex.uima.mapper.DocumentMapperServiceImpl.java

/**
 * bind the variables to the prepared statement
 * /*w w  w. j  a  v a2s .c o m*/
 * @param type
 * @param mapInfo
 * @param ps
 * @param annoId
 * @param anno
 * @throws SQLException
 */
private void saveAnnoBindVariables(final Type type, final AnnoMappingInfo mapInfo, PreparedStatement ps,
        int annoId, FeatureStructure anno, final BiMap<Annotation, Integer> mapAnnoToId) throws SQLException {
    // set anno_base_id
    int argIdx = 1;
    ps.setInt(argIdx++, annoId);
    if (mapInfo.getCoveredTextColumn() != null) {
        String trunc = null;
        if (anno instanceof Annotation) {
            trunc = truncateString(((Annotation) anno).getCoveredText(),
                    mapInfo.getCoveredTextColumn().getSize());
        }
        ps.setString(argIdx++, trunc);
    }
    if (!Strings.isNullOrEmpty(mapInfo.getUimaTypeIdColumnName())) {
        ps.setInt(argIdx++, mapInfo.getUimaTypeId());
    }
    // iterate over fields
    for (Map.Entry<String, ColumnMappingInfo> fieldEntry : mapInfo.getMapField().entrySet()) {
        ColumnMappingInfo fieldMapInfo = fieldEntry.getValue();
        String fieldName = fieldMapInfo.getAnnoFieldName();
        Feature feat = type.getFeatureByBaseName(fieldName);
        if (fieldMapInfo.getConverter() != null) {
            try {
                String prop = anno.getFeatureValueAsString(feat);
                ps.setObject(argIdx, fieldMapInfo.getConverter().convert(fieldMapInfo.getTargetType(), prop));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (!feat.getRange().isPrimitive()) {
            // feature is a structure/annotation
            FeatureStructure fs = anno.getFeatureValue(feat);
            if (fs == null) {
                // feature is null - set the column to null
                ps.setNull(argIdx, fieldMapInfo.getSqlType());
            } else {
                if (fieldMapInfo.getJxpath() != null) {
                    // jxpath to pull out feature attribute
                    Object o = this.extractFeature(fieldMapInfo.getJxpath(), fs);
                    if (o == null) {
                        // extracted value null - set column to null
                        ps.setNull(argIdx, fieldMapInfo.getSqlType());
                    } else if (o instanceof String) {
                        // string - truncate as needed
                        String trunc = truncateString((String) o, fieldMapInfo.getSize());
                        ps.setString(argIdx, trunc);
                    } else {
                        // set value
                        ps.setObject(argIdx, o);
                    }
                } else {
                    // reference to another annotation - get the other
                    // anno's id
                    Integer refAnnoId = null;
                    if (fs instanceof Annotation) {
                        refAnnoId = mapAnnoToId.get(fs);
                    }
                    if (refAnnoId != null) {
                        ps.setInt(argIdx, refAnnoId);
                    } else {
                        ps.setNull(argIdx, Types.INTEGER);
                    }
                }
            }
        } else {
            if ("uima.cas.Integer".equals(feat.getRange().getName())) {
                ps.setInt(argIdx, anno.getIntValue(feat));
            } else if ("uima.cas.Short".equals(feat.getRange().getName())) {
                ps.setShort(argIdx, anno.getShortValue(feat));
            } else if ("uima.cas.Long".equals(feat.getRange().getName())) {
                ps.setLong(argIdx, anno.getLongValue(feat));
            } else if ("uima.cas.Float".equals(feat.getRange().getName())) {
                ps.setFloat(argIdx, anno.getFloatValue(feat));
            } else if ("uima.cas.Double".equals(feat.getRange().getName())) {
                ps.setDouble(argIdx, anno.getDoubleValue(feat));
            } else if ("uima.cas.Byte".equals(feat.getRange().getName())) {
                ps.setByte(argIdx, anno.getByteValue(feat));
            } else if ("uima.cas.Boolean".equals(feat.getRange().getName())) {
                ps.setBoolean(argIdx, anno.getBooleanValue(feat));
            } else if ("uima.cas.String".equals(feat.getRange().getName())) {
                String trunc = truncateString(anno.getStringValue(feat), fieldMapInfo.getSize());
                ps.setString(argIdx, trunc);
            }
        }
        argIdx++;
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

/**
 * Set the given value as a parameter to the statement.
 *///w  ww  .  ja  va  2  s  . co  m
public void setShort(PreparedStatement stmnt, int idx, short val, Column col) throws SQLException {
    stmnt.setShort(idx, val);
}

From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java

/**
 * Runs SQL Statement "UPDATE" on the given tableName with attribute values
 * and where clause.//w w  w  . j  a v  a  2  s  .c  o  m
 * 
 * @param tableName
 * @param attributeNameValue
 * @param whereClause
 * @return
 * @throws SQLException
 */
public int updateRow(String tableName, Map attributeNameValue, String whereClause, String dbType)
        throws SQLException {

    StringBuffer stmt = new StringBuffer();
    PreparedStatement prepStmt = null;
    int rowsUpdated = 0;
    Object attribute = null;
    Iterator itr = null;
    String[] key = new String[attributeNameValue.size()];
    int count = 0;

    stmt.append("UPDATE " + tablePrefix_ + tableName.trim() + " SET ");

    itr = attributeNameValue.keySet().iterator();

    while (itr.hasNext()) {
        key[count] = (String) itr.next();
        stmt.append(key[count++] + " = ?,");
    }

    /*
     * for (int i = 0; i < attributeNames.size(); i++) {
     * stmt.append(attributeNames.get(i) + " = ?,"); }
     */

    stmt = stmt.deleteCharAt(stmt.length() - 1);

    if (whereClause != null && !"".equals(whereClause)) {
        stmt.append(" WHERE ");
        stmt.append(whereClause);
    }

    // stmt = stmt.deleteCharAt(stmt.length());

    log.debug("************ UPDATE QUERY ************");
    log.debug(stmt.toString());
    log.debug("**************************************");
    try {

        String statement = new GenericSQLModifier(dbType, false).modifySQL(stmt.toString());

        prepStmt = sqlConnection_.prepareStatement(statement);

        itr = attributeNameValue.keySet().iterator();

        for (count = 0; count < key.length; count++) {

            attribute = attributeNameValue.get(key[count]);

            if (attribute instanceof String) {
                prepStmt.setString(count + 1, (String) attribute);
            } else if (attribute instanceof Blob) {
                prepStmt.setBlob(count + 1, (Blob) attribute);
            } else if (attribute instanceof Boolean) {
                prepStmt.setBoolean(count + 1, ((Boolean) attribute).booleanValue());
            } else if (attribute instanceof Byte) {
                prepStmt.setByte(count + 1, ((Byte) attribute).byteValue());
            } else if (attribute instanceof byte[]) {
                prepStmt.setBytes(count + 1, (byte[]) attribute);
            } else if (attribute instanceof Date) {
                prepStmt.setDate(count + 1, (Date) attribute);
            } else if (attribute instanceof Double) {
                prepStmt.setDouble(count + 1, ((Double) attribute).doubleValue());
            } else if (attribute instanceof Float) {
                prepStmt.setFloat(count + 1, ((Float) attribute).floatValue());
            } else if (attribute instanceof Integer) {
                prepStmt.setInt(count + 1, ((Integer) attribute).intValue());
            } else if (attribute instanceof Long) {
                prepStmt.setLong(count + 1, ((Long) attribute).longValue());
            } else if (attribute instanceof Short) {
                prepStmt.setShort(count + 1, ((Short) attribute).shortValue());
            } else if (attribute instanceof Timestamp) {
                prepStmt.setTimestamp(count + 1, (Timestamp) attribute);
            }
        }

        rowsUpdated = prepStmt.executeUpdate();
    } catch (Exception e) {
        log.error("Exception @ updateRow: " + e.getMessage());
    } finally {
        prepStmt.close();
    }

    return rowsUpdated;

}

From source file:edu.iu.incntre.flowscalestatcollector.StatCollector.java

public void startUp() {

    logger.trace("Startup of StatCollector");
    try {/*from  w ww  .  j a  va 2s.c o  m*/
        if (isQuery) {

            // initiate sqlite database

            try {

                Class.forName(databaseClass);
                conn = DriverManager.getConnection(databaseDriver, dbUsername, dbPassword);

            } catch (ClassNotFoundException e2) {

                logger.error("{}", e2);
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                logger.error("{}", e1);
            }

            // end initiate database

            // start up thread

            statThread = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        logger.trace("Starting Thread ..");
                        logger.trace("Getting flows from switch every {} seconds", intervalTime);

                        List<OFStatistics> portStats;
                        List<OFStatistics> flowStats;
                        List<OFPhysicalPort> portStatus;
                        SwitchDevice swd = null;
                        String[] datapathIdStringElements = datapathIdStrings.split(",");
                        try {

                            while (statThread != null) {
                                calendar = Calendar.getInstance();
                                logger.trace("getting flows from switches");

                                //check if conn is null if it is, reset connection 
                                if (conn == null) {
                                    conn = DriverManager.getConnection(databaseDriver, dbUsername, dbPassword);
                                }

                                for (String datapathIdString : datapathIdStringElements) {

                                    try {

                                        swd = flowscaleController.getSwitchDevices()
                                                .get(HexString.toLong(datapathIdString));

                                        if (swd == null) {
                                            logger.info("switch {} does not exist, is it connected?",
                                                    datapathIdString);
                                            continue;
                                        }

                                        logger.info("Getting flows from switch {} with ID {}",
                                                swd.getSwitchName(), datapathIdString);

                                        try {
                                            portStats = flowscaleController
                                                    .getSwitchStatisticsFromInterface(datapathIdString, "port");

                                            flowStats = flowscaleController
                                                    .getSwitchStatisticsFromInterface(datapathIdString, "flow");

                                            portStatus = swd.getPortStates();

                                            if (flowStats != null && portStats != null) {

                                                String flowStatsJSON = JSONConverter.toStat(flowStats, "flow")
                                                        .toJSONString();
                                                String portStatsJSON = JSONConverter.toStat(portStats, "port")
                                                        .toJSONString();
                                                String portStatusJSON = JSONConverter.toPortStatus(portStatus)
                                                        .toJSONString();

                                                // initialize or set hashmaps

                                                HashMap<Long, Long> tempPortStatTransmitted;
                                                HashMap<Long, Long> tempPortStatReceived;
                                                HashMap<String, Long> tempFlowStat;

                                                long datapathId = HexString.toLong(datapathIdString);
                                                if (tempPortStatTransmittedHashMap.get(datapathId) == null) {

                                                    tempPortStatTransmitted = new HashMap<Long, Long>();
                                                    tempPortStatTransmittedHashMap.put(datapathId,
                                                            tempPortStatTransmitted);
                                                } else {
                                                    tempPortStatTransmitted = tempPortStatTransmittedHashMap
                                                            .get(datapathId);

                                                }

                                                if (tempPortStatReceivedHashMap.get(datapathId) == null) {
                                                    tempPortStatReceived = new HashMap<Long, Long>();
                                                    tempPortStatReceivedHashMap.put(datapathId,
                                                            tempPortStatReceived);
                                                } else {
                                                    tempPortStatReceived = tempPortStatReceivedHashMap
                                                            .get(datapathId);
                                                }
                                                if (tempFlowStatHashMap.get(datapathId) == null) {
                                                    tempFlowStat = new HashMap<String, Long>();
                                                    tempFlowStatHashMap.put(datapathId, tempFlowStat);
                                                } else {

                                                    tempFlowStat = tempFlowStatHashMap.get(datapathId);
                                                }

                                                storeSwitchDetails(HexString.toLong(datapathIdString),
                                                        portStatsJSON, flowStatsJSON, portStatusJSON,
                                                        tempPortStatTransmitted, tempPortStatReceived,
                                                        tempFlowStat);
                                            } else {
                                                logger.error(
                                                        "Switch {} returned a null result possibility because the switch is not connected to the controller",
                                                        datapathIdString);
                                            }
                                        } catch (NoSwitchException e1) {
                                            // TODO Auto-generated catch block
                                            logger.error("Switch {} with ID {} is not connected aborting",
                                                    swd.getSwitchName(), datapathIdString);
                                        } catch (IOException e1) {
                                            logger.error("IOException {}", e1);

                                        } catch (InterruptedException e1) {
                                            logger.error("Thread Interrupted {}", e1);
                                            killThread();
                                        } catch (ExecutionException e1) {
                                            logger.error("Execution Exception {}", e1);
                                        } catch (TimeoutException e1) {
                                            logger.error("Switch Timeout Exception {}", e1);
                                            killThread();

                                        }

                                    } catch (Exception e) {
                                        logger.error("unchecked exception here {}", e);

                                        killThread();
                                        shutDown();
                                        Thread.yield();

                                    }

                                }

                                try {

                                    Thread.sleep(intervalTime);

                                } catch (InterruptedException e) {

                                    logger.error("{}", e);

                                    break;
                                }

                            }
                        } catch (Exception e) {
                            logger.error("exception in while {}", e);
                            shutDown();

                        }

                        try {
                            conn.close();
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            logger.error("{}", e);
                        }

                    } catch (Exception generalException) {
                        logger.error("General Exception throws {} ", generalException);

                    }
                }

                /**
                 * insert details into database, 3 tables will be populated: flow_stats, port_stats ,and port_status
                 * 
                 * @param datapathId
                 * @param portStats
                 * @param flowStats
                 * @param portStatus
                 * @param tempPortStatTransmitted
                 * @param tempPortStatReceived
                 * @param tempFlowStat
                 */
                private void storeSwitchDetails(long datapathId, String portStats, String flowStats,
                        String portStatus, HashMap<Long, Long> tempPortStatTransmitted,
                        HashMap<Long, Long> tempPortStatReceived, HashMap<String, Long> tempFlowStat) {

                    Object obj = JSONValue.parse(portStats);
                    JSONArray jsonArray = (JSONArray) obj;

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

                        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                        long transmittedPackets = (Long) jsonObject.get("transmit_packets");
                        long receivedPackets = (Long) jsonObject.get("receive_packets");

                        long portId = (Long) jsonObject.get("port_id");

                        // logger.info("the port is {}", portId);
                        // logger.info("{} packets transmitted and {} packets received",
                        // receivedPackets,transmittedPackets);

                        PreparedStatement prep = null;
                        try {
                            prep = null;
                            if (conn != null) {
                                prep = conn.prepareStatement("insert into port_stats values (?,?,?,?,?);");

                            } else {

                                logger.error("no connection object instantiated aborting .. ");
                                return;
                            }

                            prep.setLong(1, datapathId);
                            prep.setLong(2, calendar.getTimeInMillis());

                            if (tempPortStatTransmitted.get(portId) != null) {

                                long currentTransmittedPackets = transmittedPackets
                                        - tempPortStatTransmitted.get(portId);

                                if (currentTransmittedPackets < 0) {

                                    prep.setLong(5, transmittedPackets);
                                } else {

                                    prep.setLong(5, currentTransmittedPackets);
                                }
                            } else {

                                prep.setLong(5, transmittedPackets);
                            }

                            tempPortStatTransmitted.put(portId, transmittedPackets);

                            // take care of port received

                            if (tempPortStatReceived.get(portId) != null) {

                                long currentReceivedPackets = receivedPackets
                                        - tempPortStatReceived.get(portId);

                                if (currentReceivedPackets < 0) {

                                    prep.setLong(4, receivedPackets);
                                } else {

                                    prep.setLong(4, currentReceivedPackets);
                                }
                            } else {

                                prep.setLong(4, receivedPackets);
                            }

                            tempPortStatReceived.put(portId, receivedPackets);

                            prep.setLong(3, portId);
                            prep.addBatch();

                            conn.setAutoCommit(false);
                            prep.executeBatch();
                            conn.setAutoCommit(true);
                        } catch (SQLRecoverableException sqlRecoverableException) {

                            logger.error("{}", sqlRecoverableException);
                            //exit function since there is a timeout
                            return;
                        } catch (SQLException e) {

                            logger.error("{}", e);
                        } finally {
                            if (prep != null) {
                                try {
                                    prep.close();
                                } catch (SQLException e) {
                                    // TODO Auto-generated catch block
                                    logger.error("{}", e);
                                }
                            }
                        }
                    }

                    Object flowJSONobj = JSONValue.parse(flowStats);
                    JSONArray flowJsonArray = (JSONArray) flowJSONobj;

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

                        JSONObject jsonObject = (JSONObject) flowJsonArray.get(i);
                        long packets = (Long) jsonObject.get("packet_count");
                        String matchString = (String) jsonObject.get("match");
                        String action = (String) jsonObject.get("actions");
                        long priority = (Long) jsonObject.get("priority");

                        PreparedStatement prep = null;

                        try {
                            prep = conn.prepareStatement("insert  into flow_stats values (?,?,?,?,?,?);");
                            String insertString = datapathId + "," + calendar.getTimeInMillis() + ","
                                    + matchString + "," + action;
                            logger.debug("flow_stat values to insert are {}", insertString);
                            prep.setLong(1, datapathId);
                            prep.setLong(2, calendar.getTimeInMillis());

                            if (tempFlowStat.get(matchString) != null) {

                                long packetsReceived = packets - tempFlowStat.get(matchString);

                                if (packetsReceived < 0) {

                                    prep.setLong(5, packets);
                                } else {

                                    prep.setLong(5, packetsReceived);
                                }
                            } else {

                                prep.setLong(5, packets);
                            }

                            tempFlowStat.put(matchString, packets);

                            prep.setString(3, matchString);
                            prep.setString(4, action);

                            prep.setShort(6, (short) priority);
                            prep.addBatch();

                            conn.setAutoCommit(false);
                            prep.executeBatch();
                            conn.setAutoCommit(true);
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            logger.error("error when insert flow {} in switch {}", matchString, datapathId);
                            logger.error("{}", e);
                        } finally {
                            if (prep != null) {
                                try {
                                    prep.close();
                                } catch (SQLException e) {
                                    // TODO Auto-generated catch block
                                    logger.error("{}", e);
                                }
                            }
                        }

                    }

                    Object portStatusJSONobj = JSONValue.parse(portStatus);
                    JSONArray portStatusJsonArray = (JSONArray) portStatusJSONobj;

                    for (int i = 0; i < portStatusJsonArray.size(); i++) {
                        byte portStatusValue = 0;
                        JSONObject jsonObject = (JSONObject) portStatusJsonArray.get(i);
                        long portId = (Long) jsonObject.get("port_id");
                        String portAddress = (String) jsonObject.get("port_address");
                        try {
                            portStatusValue = (byte) (Integer.parseInt(jsonObject.get("state").toString()) % 2);
                        } catch (NumberFormatException nfe) {
                            logger.error("{}", nfe);
                            continue;
                        }
                        PreparedStatement prep = null;
                        try {
                            prep = conn.prepareStatement("insert into port_status    values (?,?,?,?,?);");
                            prep.setLong(1, datapathId);
                            prep.setLong(2, calendar.getTimeInMillis());
                            prep.setLong(3, portId);

                            prep.setString(4, portAddress);

                            prep.setByte(5, portStatusValue);
                            prep.addBatch();

                            conn.setAutoCommit(false);
                            prep.executeBatch();

                            conn.setAutoCommit(true);
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            logger.error("{}", e);
                        } finally {
                            if (prep != null) {
                                try {
                                    prep.close();
                                } catch (SQLException e) {
                                    // TODO Auto-generated catch block
                                    logger.error("{}", e);
                                }
                            }
                        }

                    }

                }

            }, "Switch Stat Collector");
            statThread.start();

        }
    } catch (Exception e) {
        logger.error("general excecption thrown {}", e);
    }
}

From source file:org.apache.cocoon.util.JDBCTypeConversions.java

/**
 * Set the Statement column so that the results are mapped correctly.
 *
 * @param statement the prepared statement
 * @param position the position of the column
 * @param value the value of the column/*from w ww . jav  a  2s.  com*/
 */
public static void setColumn(PreparedStatement statement, int position, Object value, Integer typeObject)
        throws Exception {
    if (value instanceof String) {
        value = ((String) value).trim();
    }
    if (typeObject == null) {
        throw new SQLException("Can't set column because the type is unrecognized");
    }
    if (value == null) {
        /** If the value is null, set the column value null and return **/
        statement.setNull(position, typeObject.intValue());
        return;
    }
    if ("".equals(value)) {
        switch (typeObject.intValue()) {
        case Types.CHAR:
        case Types.CLOB:
        case Types.VARCHAR:
            /** If the value is an empty string and the column is
            a string type, we can continue **/
            break;
        default:
            /** If the value is an empty string and the column
            is something else, we treat it as a null value **/
            statement.setNull(position, typeObject.intValue());
            return;
        }
    }

    File file = null;
    int length = -1;
    InputStream asciiStream = null;

    //System.out.println("========================================================================");
    //System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue());
    switch (typeObject.intValue()) {
    case Types.CLOB:
        //System.out.println("CLOB");
        Clob clob = null;
        if (value instanceof Clob) {
            clob = (Clob) value;
        } else if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new ByteArrayInputStream(asciiText.getBytes());
            length = asciiText.length();
            clob = new ClobHelper(asciiStream, length);
        }

        statement.setClob(position, clob);
        break;
    case Types.CHAR:
        // simple large object, e.g. Informix's TEXT
        //System.out.println("CHAR");

        if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new BufferedInputStream(new ByteArrayInputStream(asciiText.getBytes()));
            length = asciiText.length();
        }

        statement.setAsciiStream(position, asciiStream, length);
        break;
    case Types.BIGINT:
        //System.out.println("BIGINT");
        BigDecimal bd = null;

        if (value instanceof BigDecimal) {
            bd = (BigDecimal) value;
        } else if (value instanceof Number) {
            bd = BigDecimal.valueOf(((Number) value).longValue());
        } else {
            bd = new BigDecimal(value.toString());
        }

        statement.setBigDecimal(position, bd);
        break;
    case Types.TINYINT:
        //System.out.println("TINYINT");
        Byte b = null;

        if (value instanceof Byte) {
            b = (Byte) value;
        } else if (value instanceof Number) {
            b = new Byte(((Number) value).byteValue());
        } else {
            b = new Byte(value.toString());
        }

        statement.setByte(position, b.byteValue());
        break;
    case Types.DATE:
        //System.out.println("DATE");
        Date d = null;

        if (value instanceof Date) {
            d = (Date) value;
        } else if (value instanceof java.util.Date) {
            d = new Date(((java.util.Date) value).getTime());
        } else if (value instanceof Calendar) {
            d = new Date(((Calendar) value).getTime().getTime());
        } else {
            d = Date.valueOf(value.toString());
        }

        statement.setDate(position, d);
        break;
    case Types.DOUBLE:
        //System.out.println("DOUBLE");
        double db;

        if (value instanceof Number) {
            db = (((Number) value).doubleValue());
        } else {
            db = Double.parseDouble(value.toString());
        }
        statement.setDouble(position, db);
        break;
    case Types.FLOAT:
        //System.out.println("FLOAT");
        float f;

        if (value instanceof Number) {
            f = (((Number) value).floatValue());
        } else {
            f = Float.parseFloat(value.toString());
        }
        statement.setFloat(position, f);
        break;
    case Types.NUMERIC:
        //System.out.println("NUMERIC");
        long l;

        if (value instanceof Number) {
            l = (((Number) value).longValue());
        } else {
            l = Long.parseLong(value.toString());
        }

        statement.setLong(position, l);
        break;
    case Types.SMALLINT:
        //System.out.println("SMALLINT");
        Short s = null;

        if (value instanceof Short) {
            s = (Short) value;
        } else if (value instanceof Number) {
            s = new Short(((Number) value).shortValue());
        } else {
            s = new Short(value.toString());
        }

        statement.setShort(position, s.shortValue());
        break;
    case Types.TIME:
        //System.out.println("TIME");
        Time t = null;

        if (value instanceof Time) {
            t = (Time) value;
        } else if (value instanceof java.util.Date) {
            t = new Time(((java.util.Date) value).getTime());
        } else {
            t = Time.valueOf(value.toString());
        }

        statement.setTime(position, t);
        break;
    case Types.TIMESTAMP:
        //System.out.println("TIMESTAMP");
        Timestamp ts = null;

        if (value instanceof Time) {
            ts = (Timestamp) value;
        } else if (value instanceof java.util.Date) {
            ts = new Timestamp(((java.util.Date) value).getTime());
        } else {
            ts = Timestamp.valueOf(value.toString());
        }

        statement.setTimestamp(position, ts);
        break;
    case Types.ARRAY:
        //System.out.println("ARRAY");
        statement.setArray(position, (Array) value); // no way to convert string to array
        break;
    case Types.STRUCT:
        //System.out.println("STRUCT");
    case Types.OTHER:
        //System.out.println("OTHER");
        statement.setObject(position, value);
        break;
    case Types.LONGVARBINARY:
        //System.out.println("LONGVARBINARY");
        statement.setTimestamp(position, new Timestamp((new java.util.Date()).getTime()));
        break;
    case Types.VARCHAR:
        //System.out.println("VARCHAR");
        statement.setString(position, value.toString());
        break;
    case Types.BLOB:
        //System.out.println("BLOB");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else {
            Blob blob = null;
            if (value instanceof Blob) {
                blob = (Blob) value;
            } else if (value instanceof File) {
                file = (File) value;
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof String) {
                file = new File((String) value);
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof Part) {
                Part anyFile = (Part) value;
                blob = new BlobHelper(new BufferedInputStream(anyFile.getInputStream()), anyFile.getSize());
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            statement.setBlob(position, blob);
        }
        break;
    case Types.VARBINARY:
        //System.out.println("VARBINARY");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else if (value instanceof Part) {
            statement.setBinaryStream(position, ((Part) value).getInputStream(), ((Part) value).getSize());
        } else {
            if (value instanceof File) {
                file = (File) value;
            } else if (value instanceof String) {
                file = new File((String) value);
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            FileInputStream input = new FileInputStream(file);
            statement.setBinaryStream(position, input, (int) file.length());
        }
        break;
    case Types.INTEGER:
        //System.out.println("INTEGER");
        Integer i = null;
        if (value instanceof Integer) {
            i = (Integer) value;
        } else if (value instanceof Number) {
            i = new Integer(((Number) value).intValue());
        } else {
            i = new Integer(value.toString());
        }
        statement.setInt(position, i.intValue());
        break;
    case Types.BIT:
        //System.out.println("BIT");
        Boolean bo = null;
        if (value instanceof Boolean) {
            bo = (Boolean) value;
        } else if (value instanceof Number) {
            bo = BooleanUtils.toBooleanObject(((Number) value).intValue() == 1);
        } else {
            bo = BooleanUtils.toBooleanObject(value.toString());
        }
        statement.setBoolean(position, bo.booleanValue());
        break;

    default:
        //System.out.println("default");
        throw new SQLException("Impossible exception - invalid type ");
    }
    //System.out.println("========================================================================");
}

From source file:com.funambol.foundation.items.dao.PIMCalendarDAO.java

/**
 * Adds a calendar. If necessary, a new ID is generated and set in the
 * CalendarWrapper.// ww w  .j  a v  a  2 s .co  m
 *
 * @param c as a CalendarWrapper object, usually without an ID set.
 * @throws DAOException
 *
 * @see CalendarWrapper
 */
public void addItem(CalendarWrapper cw) throws DAOException {

    if (log.isTraceEnabled()) {
        log.trace("PIMCalendarDAO addItem begin");
    }

    Connection con = null;
    PreparedStatement ps = null;

    long id = 0;
    String allDay = null;
    String body = null;
    Short busyStatus = null;
    String categories = null;
    String companies = null;
    int duration = 0;
    Date dend = null;
    short importance = 0;
    String location = null;
    Short meetingStatus = null;
    String mileage = null;
    Date replyTime = null;
    short sensitivity = 0;
    Date dstart = null;
    String subject = null;
    int interval = 0;
    short monthOfYear = 0;
    short dayOfMonth = 0;
    String dayOfWeekMask = null;
    short instance = 0;
    String startDatePattern = null;
    String endDatePattern = null;
    Reminder reminder = null;
    RecurrencePattern rp = null;
    short recurrenceType = -1;
    String sId = null;
    int occurrences = -1;
    String folder = null;
    String dstartTimeZone = null;
    String dendTimeZone = null;
    String reminderTimeZone = null;
    Date completed = null;
    short percentComplete = -1;

    Timestamp lastUpdate = cw.getLastUpdate();
    if (lastUpdate == null) {
        lastUpdate = new Timestamp(System.currentTimeMillis());
    }

    try {

        sId = cw.getId();
        if (sId == null || sId.length() == 0) { // ...as it should be
            sId = getNextID();
            cw.setId(sId);
        }
        id = Long.parseLong(sId);

        CalendarContent c = cw.getCalendar().getCalendarContent();

        rp = c.getRecurrencePattern();

        boolean allDayB;
        if (c.getAllDay() != null && c.getAllDay().booleanValue()) {
            allDayB = true;
            allDay = "1";
        } else {
            allDayB = false;
            allDay = "0";
        }

        String sd = null;
        if (c.getDtStart() != null) {
            sd = c.getDtStart().getPropertyValueAsString();
            dstart = getDateFromString(allDayB, sd, "000000");
        }

        String ed = null;
        if ((sd != null && sd.length() > 0) || c.getDtEnd() != null) {
            ed = c.getDtEnd().getPropertyValueAsString();

            //
            // Fix for Siemens S56 end date issue only for event
            // @todo: verify if is really need to do this
            //
            if (c instanceof Event) {
                if (ed == null || ed.length() == 0) {
                    ed = sd;
                }
            }

            dend = getDateFromString(allDayB, ed, "235900");
        }

        body = Property.stringFrom(c.getDescription());

        if (c.getBusyStatus() != null) {
            busyStatus = new Short(c.getBusyStatus().shortValue());
        }

        categories = Property.stringFrom(c.getCategories());
        companies = Property.stringFrom(c.getOrganizer());
        location = Property.stringFrom(c.getLocation());
        folder = Property.stringFrom(c.getFolder());
        dstartTimeZone = timeZoneFrom(c.getDtStart());
        dendTimeZone = timeZoneFrom(c.getDtEnd());
        reminderTimeZone = timeZoneFrom(c.getReminder());
        meetingStatus = c.getMeetingStatus();

        Integer mileageInteger = c.getMileage(); // NB: not an int...
        if (mileageInteger != null) { // ...therefore it may be null
            mileage = String.valueOf(mileageInteger);
        }

        if (c instanceof Event) {
            replyTime = getDateFromString(allDayB, // @todo or false?
                    Property.stringFrom(((Event) c).getReplyTime()), "000000");
        }

        try {
            sensitivity = Short.parseShort(Property.stringFrom(c.getAccessClass()));
        } catch (NumberFormatException nfe) {
            sensitivity = 0;
            // The short must go on
        }

        if ((subject = Property.stringFrom(c.getSummary())) == null && body != null) {
            int endOfSentence = body.indexOf('.');
            if (endOfSentence == -1) {
                endOfSentence = body.length();
            }
            if (endOfSentence > SQL_SUBJECT_DIM) {
                endOfSentence = SQL_SUBJECT_DIM;
            }
            subject = body.substring(0, endOfSentence);
        }

        String isInfinite = "0";
        if (rp != null) {
            interval = rp.getInterval();
            recurrenceType = rp.getTypeId();
            monthOfYear = rp.getMonthOfYear();
            dayOfMonth = rp.getDayOfMonth();
            dayOfWeekMask = String.valueOf(rp.getDayOfWeekMask());
            instance = rp.getInstance();
            startDatePattern = rp.getStartDatePattern();
            endDatePattern = rp.getEndDatePattern();
            if (rp.isNoEndDate()) {
                isInfinite = "1";
            }
            occurrences = rp.getOccurrences();
        }

        if (c instanceof Task) {
            Task t = (Task) c;
            if (t.getDateCompleted() != null) {
                completed = getDateFromString(allDayB, ((Task) c).getDateCompleted().getPropertyValueAsString(),
                        "000000");
            }

            try {
                String complete = Property.stringFrom(t.getComplete());
                if (complete != null && complete.equals("1")) {
                    percentComplete = 100;
                } else {
                    percentComplete = Short.parseShort(Property.stringFrom(t.getPercentComplete()));
                }
                if (percentComplete < 0 || percentComplete > 100) {
                    throw new NumberFormatException("A percentage can't be " + percentComplete);
                }
            } catch (NumberFormatException nfe) {
                percentComplete = -1; // the short must go on
            }

            meetingStatus = getTaskStatus(t);
        }

        con = getUserDataSource().getRoutedConnection(userId);

        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CALENDAR);

        ps.setLong(1, id);
        ps.setString(2, userId);
        ps.setLong(3, lastUpdate.getTime());
        ps.setString(4, String.valueOf(Def.PIM_STATE_NEW));
        ps.setString(5, allDay);
        ps.setString(6, StringUtils.left(body, SQL_BODY_DIM));
        if (busyStatus != null) {
            ps.setShort(7, busyStatus.shortValue());
        } else {
            ps.setNull(7, Types.SMALLINT);
        }
        ps.setString(8, StringUtils.left(categories, SQL_CATEGORIES_DIM));
        ps.setString(9, StringUtils.left(companies, SQL_COMPANIES_DIM));
        ps.setInt(10, duration);
        if (dend != null) {
            ps.setTimestamp(11, new Timestamp(dend.getTime()));
        } else {
            ps.setNull(11, Types.TIMESTAMP);
        }

        if (c.getPriority() != null) {

            String priority = c.getPriority().getPropertyValueAsString();

            if (priority != null && priority.length() > 0) {
                importance = Short.parseShort(priority);
                ps.setShort(12, importance);
            } else {
                ps.setNull(12, Types.SMALLINT);
            }

        } else {
            ps.setNull(12, Types.SMALLINT);
        }

        ps.setString(13, StringUtils.left(location, SQL_LOCATION_DIM));

        if (meetingStatus != null) {
            ps.setShort(14, meetingStatus.shortValue());
        } else {
            ps.setNull(14, Types.SMALLINT);
        }

        ps.setString(15, mileage);

        reminder = c.getReminder();
        if (reminder != null && reminder.isActive()) {
            Timestamp reminderTime = getReminderTime(dstart, reminder);
            if (reminderTime == null) {
                ps.setNull(16, Types.TIMESTAMP);
            } else {
                ps.setTimestamp(16, reminderTime);
            }
            ps.setInt(17, reminder.getRepeatCount());
            ps.setString(18, (reminder.isActive()) ? "1" : "0");

            String soundFileValue = reminder.getSoundFile();
            ps.setString(19, StringUtils.left(soundFileValue, SQL_SOUNDFILE_DIM));
            ps.setInt(20, reminder.getOptions());
        } else {
            ps.setNull(16, Types.TIMESTAMP);
            ps.setInt(17, 0);
            ps.setString(18, "0");
            ps.setString(19, null);
            ps.setInt(20, 0);
        }

        if (replyTime != null) {
            ps.setTimestamp(21, new Timestamp(replyTime.getTime()));
        } else {
            ps.setNull(21, Types.TIMESTAMP);
        }

        ps.setShort(22, sensitivity);

        if (dstart != null) {
            ps.setTimestamp(23, new Timestamp(dstart.getTime()));
        } else {
            ps.setNull(23, Types.TIMESTAMP);
        }
        ps.setString(24, StringUtils.left(subject, SQL_SUBJECT_DIM));
        ps.setShort(25, recurrenceType);
        ps.setInt(26, interval);
        ps.setShort(27, monthOfYear);
        ps.setShort(28, dayOfMonth);
        ps.setString(29, StringUtils.left(dayOfWeekMask, SQL_DAYOFWEEKMASK_DIM));
        ps.setShort(30, instance);
        ps.setString(31, StringUtils.left(startDatePattern, SQL_STARTDATEPATTERN_DIM));
        ps.setString(32, isInfinite);
        ps.setString(33, StringUtils.left(endDatePattern, SQL_ENDDATEPATTERN_DIM));
        ps.setInt(34, occurrences);

        if (c instanceof Event) {
            ps.setInt(35, CALENDAR_EVENT_TYPE);
            ps.setNull(36, Types.TIMESTAMP); // completed
            ps.setNull(37, Types.SMALLINT); // percent_complete
        } else {
            ps.setInt(35, CALENDAR_TASK_TYPE);

            if (completed != null) {
                ps.setTimestamp(36, new Timestamp(completed.getTime()));
            } else {
                ps.setNull(36, Types.TIMESTAMP);
            }

            if (percentComplete != -1) {
                ps.setShort(37, percentComplete);
            } else {
                ps.setNull(37, Types.SMALLINT);
            }
        }

        ps.setString(38, StringUtils.left(folder, SQL_FOLDER_DIM));
        ps.setString(39, StringUtils.left(dstartTimeZone, SQL_TIME_ZONE_DIM));
        ps.setString(40, StringUtils.left(dendTimeZone, SQL_TIME_ZONE_DIM));
        ps.setString(41, StringUtils.left(reminderTimeZone, SQL_TIME_ZONE_DIM));

        ps.executeUpdate();
        DBTools.close(null, ps, null);

        if (recurrenceType != -1) {
            List<ExceptionToRecurrenceRule> exceptions = rp.getExceptions();
            for (ExceptionToRecurrenceRule etrr : exceptions) {
                ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CALENDAR_EXCEPTION);

                ps.setLong(1, id);
                ps.setString(2, (etrr.isAddition() ? "1" : "0"));
                ps.setTimestamp(3,
                        new Timestamp(getDateFromString(allDayB, etrr.getDate(), "000000").getTime()));

                ps.executeUpdate();
                DBTools.close(null, ps, null);
            }
        }

    } catch (Exception e) {
        throw new DAOException("Error adding a calendar item: " + e.getMessage(), e);
    } finally {
        DBTools.close(con, ps, null);
    }
}

From source file:com.osparking.osparking.Settings_System.java

private void SettingsSaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SettingsSaveButtonActionPerformed
    Connection conn = null;//  w  ww  .  jav a 2s  . c om
    PreparedStatement updateSettings = null;
    int result = -1;
    boolean newStorePassingDelay = RecordPassingDelayChkBox.isSelected();
    Locale locale = LanguageBox.getLocale();
    boolean langNotSupported = (!locale.equals(defaultLocale) && !locale.equals(enUS_Locale));

    if (langNotSupported) {
        String message = WRONG_LANG_DIALOG_1.getContent() + System.lineSeparator();
        message += WRONG_LANG_DIALOG_2.getContent() + locale.getDisplayName() + System.lineSeparator()
                + System.lineSeparator();
        message += WRONG_LANG_DIALOG_3.getContent() + System.lineSeparator();
        message += WRONG_LANG_DIALOG_4.getContent() + defaultLocale.getDisplayName() + ", "
                + enUS_Locale.getDisplayName() + System.lineSeparator();

        JOptionPane.showConfirmDialog(this, message, LANGUAGE_ERROR_TITLE.getContent(),
                JOptionPane.PLAIN_MESSAGE, WARNING_MESSAGE);
        return;
    }

    //<editor-fold desc="--check setting input errors">
    if (!TextFieldNumericValueOK(TextFieldPicWidth, "Photo Extent Typing Errors")) {
        return;
    }

    if (!TextFieldNumericValueOK(TextFieldPicHeight, "Photo Height Typing Errors")) {
        return;
    }

    if (Integer.parseInt(removeNonNumeric(TextFieldPicHeight.getText().trim())) < 100) {
        TextFieldPicHeight.requestFocusInWindow();
        JOptionPane.showConfirmDialog(this, "Please enter a height value of 100 or more",
                "Picture Height Input Error", JOptionPane.PLAIN_MESSAGE, WARNING_MESSAGE);
        return;
    }

    if (Integer.parseInt(removeNonNumeric(TextFieldPicWidth.getText().trim())) < 100) {
        TextFieldPicWidth.requestFocusInWindow();
        JOptionPane.showConfirmDialog(this, "Please enter a width value of 100 or more",
                "Picture Width Input Error", JOptionPane.PLAIN_MESSAGE, WARNING_MESSAGE);
        return;
    }

    if (someIPaddressWrong()) {
        return;
    }

    if (someCOMportIDsame()) {
        return;
    }
    //</editor-fold>

    int newStatCount = 0;
    short pwLevel = -1;
    short optnLogLevel = -1;
    String maxLineStr = "";
    int imageKeepDuration = 0;
    int picWidth = Integer.parseInt(removeNonNumeric(TextFieldPicWidth.getText()));
    int picHeight = Integer.parseInt(removeNonNumeric(TextFieldPicHeight.getText()));
    int flowCycle = Integer.parseInt(removeNonNumeric((String) FlowingComboBox.getSelectedItem()));
    int blinkCycle = Integer.parseInt(removeNonNumeric(TextFieldPicWidth.getText()));
    boolean gateCountChanged = false;

    try {
        StringBuffer sb = new StringBuffer("Update SettingsTable SET ");
        //<editor-fold desc="--create update statement">
        sb.append("Lot_Name = ?, ");
        sb.append("perfEvalNeeded = ?, PWStrengthLevel = ?, OptnLoggingLevel = ?, ");
        sb.append("languageCode = ?, countryCode = ?, localeIndex = ?, statCount =  ?, ");
        sb.append("MaxMessageLines = ?, GateCount = ?, ");
        sb.append("PictureWidth = ?, PictureHeight = ?, ");
        sb.append("EBD_flow_cycle = ?, EBD_blink_cycle = ?, ");
        sb.append("max_maintain_date = ? ");
        //</editor-fold>

        ConvComboBoxItem selectedItem = (ConvComboBoxItem) PopSizeCBox.getSelectedItem();
        newStatCount = (Integer) selectedItem.getKeyValue();
        if (newStorePassingDelay) {
            for (int gateID = 1; gateID <= gateCount; gateID++) {
                initPassingDelayStatIfNeeded(newStatCount, gateID);
            }
        }
        conn = JDBCMySQL.getConnection();
        updateSettings = conn.prepareStatement(sb.toString());

        int pIndex = 1;

        // <editor-fold defaultstate="collapsed" desc="--Provide values to each parameters of the UPDATE statement">
        updateSettings.setString(pIndex++, lotNameTextField.getText().trim());
        if (newStorePassingDelay) {
            updateSettings.setInt(pIndex++, 1);
        } else {
            updateSettings.setInt(pIndex++, 0);
            if (DEBUG) {
                // Give warning that in debug mode PassingDelay is always recorded.
                JOptionPane.showMessageDialog(null, RECORD_DELAY_DEBUG.getContent());
            }
        }

        pwLevel = (short) (PWStrengthChoiceComboBox.getSelectedIndex());
        updateSettings.setShort(pIndex++, pwLevel);

        optnLogLevel = (short) (OptnLoggingLevelComboBox.getSelectedIndex());
        updateSettings.setShort(pIndex++, optnLogLevel);

        updateSettings.setString(pIndex++, LanguageBox.getLocale().getLanguage());
        updateSettings.setString(pIndex++, LanguageBox.getLocale().getCountry());
        updateSettings.setShort(pIndex++, (short) LanguageBox.getSelectedIndex());
        updateSettings.setInt(pIndex++, PopSizeCBox.getSelectedIndex());

        maxLineStr = (String) MessageMaxLineComboBox.getSelectedItem();
        updateSettings.setShort(pIndex++, new Short(maxLineStr));
        updateSettings.setShort(pIndex++, new Short((String) GateCountComboBox.getSelectedItem()));

        updateSettings.setInt(pIndex++, picWidth);
        updateSettings.setInt(pIndex++, picHeight);
        updateSettings.setInt(pIndex++, flowCycle);
        updateSettings.setInt(pIndex++, blinkCycle);

        ConvComboBoxItem item = (ConvComboBoxItem) ImageDurationCBox.getSelectedItem();
        imageKeepDuration = (Integer) (item.getKeyValue());
        updateSettings.setInt(pIndex++, imageKeepDuration);
        // </editor-fold>

        result = updateSettings.executeUpdate();
        if (index2Level(opLoggingIndex) != Level.OFF && index2Level(optnLogLevel) == Level.OFF) {
            Globals.isFinalWishLog = true;
        }
    } catch (SQLException se) {
        Globals.logParkingException(Level.SEVERE, se,
                "(Save settings: " + (newStorePassingDelay ? "Y" : "N") + ")");
    } finally {
        // <editor-fold defaultstate="collapsed" desc="--Return resources and display the save result">
        closeDBstuff(conn, updateSettings, null, "(Save settings: " + (newStorePassingDelay ? "Y" : "N") + ")");

        if (result == 1) {
            //<editor-fold desc="-- Log system settings change if set to do so">
            if (statCount != newStatCount) {
                logParkingOperation(OpLogLevel.SettingsChange,
                        "Settings Change, Statistics Population Size: " + statCount + " => " + newStatCount);
            }

            if (storePassingDelay != newStorePassingDelay) {
                logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Average Passing Delay: "
                        + storePassingDelay + " => " + newStorePassingDelay);
            }

            if (pwStrengthLevel != pwLevel) {
                logParkingOperation(OpLogLevel.SettingsChange,
                        "Settings Change, Password Strength Level: "
                                + PWStrengthChoiceComboBox.getItemAt(pwStrengthLevel) + " => "
                                + PWStrengthChoiceComboBox.getItemAt(pwLevel));
            }

            if (opLoggingIndex != optnLogLevel) {
                logParkingOperation(OpLogLevel.LogAlways,
                        "Settings Change, Gen' Operation Log Level: "
                                + OptnLoggingLevelComboBox.getItemAt(opLoggingIndex) + " => "
                                + OptnLoggingLevelComboBox.getItemAt(optnLogLevel));
            }

            if (localeIndex != (short) LanguageBox.getSelectedIndex()) {
                logParkingOperation(OpLogLevel.SettingsChange,
                        "Settings Change, Date Chooser Lang': " + LanguageBox.getItemAt(localeIndex) + " => "
                                + LanguageBox.getItemAt((short) LanguageBox.getSelectedIndex()));
            }

            if (maxMessageLines != new Short(maxLineStr)) {
                logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Recent Event Line Max: "
                        + maxMessageLines + " => " + new Short(maxLineStr));
            }

            short newGateCount = new Short((String) GateCountComboBox.getSelectedItem());

            gateCountChanged = gateCount != newGateCount;
            if (gateCountChanged) {
                logParkingOperation(OpLogLevel.SettingsChange,
                        "Settings Change, Number of Gates: " + gateCount + " => " + newGateCount);
            }

            if (maxMaintainDate != imageKeepDuration) {
                logParkingOperation(OpLogLevel.SettingsChange, "Settings Change, Image Keep Duration: "
                        + maxMaintainDate + " => " + imageKeepDuration);
            }

            if (PIC_WIDTH != picWidth) {
                logParkingOperation(OpLogLevel.SettingsChange,
                        "Settings Change, Image width: " + PIC_WIDTH + " => " + picWidth);
            }

            if (PIC_HEIGHT != picHeight) {
                logParkingOperation(OpLogLevel.SettingsChange,
                        "Settings Change, Image Height: " + PIC_HEIGHT + " => " + picHeight);
            }

            if (EBD_flowCycle != flowCycle) {
                logParkingOperation(OpLogLevel.UserCarChange,
                        "E-Board Settings Change, Cycles--flowing: " + EBD_flowCycle + " => " + flowCycle);
            }

            if (EBD_blinkCycle != blinkCycle) {
                logParkingOperation(OpLogLevel.UserCarChange,
                        "E-Board Settings Change, Cycles--blinking: " + EBD_blinkCycle + " => " + blinkCycle);
            }

            if (mainForm != null && gateCountChanged) {
                JOptionPane.showMessageDialog(mainForm, REBOOT_MESSAGE.getContent(), REBOOT_POPUP.getContent(),
                        WARNING_MESSAGE,
                        new javax.swing.ImageIcon(mainForm.getClass().getResource("/restart.png")));
                mainForm.askUserIntentionOnProgramStop(true);
            }
            //</editor-fold>

            Globals.getOperationLog().setLevel(index2Level(opLoggingIndex));
        } else {
            JOptionPane.showMessageDialog(this, FAIL_SAVE_SETTINGS_DIALOG.getContent(),
                    SETTINGS_SAVE_RESULT.getContent(), JOptionPane.ERROR_MESSAGE);
        }
        // </editor-fold>
    }
    boolean majorChange[] = new boolean[] { false };

    result += saveGateDevices(majorChange);

    if (mainForm != null && (gateCountChanged || majorChange[0])) {
        JOptionPane.showMessageDialog(mainForm, REBOOT_MESSAGE.getContent(), REBOOT_POPUP.getContent(),
                WARNING_MESSAGE, new javax.swing.ImageIcon(mainForm.getClass().getResource("/restart.png")));
        mainForm.askUserIntentionOnProgramStop(true);
    }

    if (result == gateCount + 1) {
        readSettings();
        Globals.getOperationLog().setLevel(index2Level(opLoggingIndex));
        JOptionPane.showMessageDialog(this, SAVE_SETTINGS_DIALOG.getContent(),
                SETTINGS_SAVE_RESULT.getContent(), JOptionPane.PLAIN_MESSAGE);
        enableSaveCancelButtons(false);
    } else {
        JOptionPane.showMessageDialog(this, FAIL_SAVE_SETTINGS_DIALOG.getContent(),
                SETTINGS_SAVE_RESULT.getContent(), JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Adds a contact. If necessary, a new ID is generated and set in the
 * ContactWrapper./*from   ww w . ja va2 s . co m*/
 *
 * @param cw as a ContactWrapper object, usually without an ID set.
 * @throws DAOException
 *
 * @see ContactWrapper
 */
public void addItem(ContactWrapper cw) throws DAOException {
    if (log.isTraceEnabled()) {
        log.trace("Storing a contact item...");
    }

    Connection con = null;
    PreparedStatement ps = null;

    long id = 0;
    int type = 0;

    PersonalDetail personalDetail = null;
    BusinessDetail businessDetail = null;
    Address homeAddressBook = null;
    Address workAddressBook = null;
    Address otherAddressBook = null;

    Name name = null;
    Phone phone = null;
    Email email = null;
    WebPage webPage = null;

    List<WebPage> webPages = new ArrayList<WebPage>();
    List<Email> emails = new ArrayList<Email>();
    List<Phone> phones = new ArrayList<Phone>();
    List<String[]> labels = new ArrayList<String[]>();

    String webPageType = null;

    Short importance = null;
    Short sensitivity = null;
    String mileage = null;
    String subject = null;
    String folder = null;
    String anniversary = null;
    String firstName = null;
    String middleName = null;
    String lastName = null;
    String displayName = null;
    String birthday = null;
    String categories = null;
    String gender = null;
    String hobbies = null;
    String initials = null;
    String languages = null;
    String nickName = null;
    String spouse = null;
    String suffix = null;
    String assistant = null;
    String officeLocation = null;
    String company = null;
    String companies = null;
    String department = null;
    String manager = null;
    String role = null;
    String children = null;
    String salutation = null;
    String sId = null;

    Timestamp lastUpdate = cw.getLastUpdate();
    if (lastUpdate == null) {
        lastUpdate = new Timestamp(System.currentTimeMillis());
    }

    try {

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        sId = cw.getId();
        if (sId == null) { // ...as it should be
            sId = getNextID();
            cw.setId(sId);
        }
        id = Long.parseLong(sId);

        Contact c = cw.getContact();
        personalDetail = c.getPersonalDetail();
        businessDetail = c.getBusinessDetail();
        name = c.getName();

        if (personalDetail != null) {
            homeAddressBook = personalDetail.getAddress();
            otherAddressBook = personalDetail.getOtherAddress();
            webPages.addAll(personalDetail.getWebPages());
            emails.addAll(personalDetail.getEmails());
            phones.addAll(personalDetail.getPhones());
        }

        if (businessDetail != null) {
            workAddressBook = businessDetail.getAddress();
            webPages.addAll(businessDetail.getWebPages());
            emails.addAll(businessDetail.getEmails());
            phones.addAll(businessDetail.getPhones());
            companies = businessDetail.getCompanies();

        }

        importance = c.getImportance();
        sensitivity = c.getSensitivity();
        mileage = c.getMileage();
        subject = c.getSubject();
        languages = c.getLanguages();

        categories = Property.stringFrom(c.getCategories());
        folder = c.getFolder();

        if (personalDetail != null) {
            anniversary = personalDetail.getAnniversary();
            birthday = personalDetail.getBirthday();
            children = personalDetail.getChildren();
            spouse = personalDetail.getSpouse();
            hobbies = personalDetail.getHobbies();
            gender = personalDetail.getGender();
        }

        if (businessDetail != null) {
            assistant = businessDetail.getAssistant();
            manager = businessDetail.getManager();
            officeLocation = businessDetail.getOfficeLocation();
            company = Property.stringFrom(businessDetail.getCompany());
            department = Property.stringFrom(businessDetail.getDepartment());
            role = Property.stringFrom(businessDetail.getRole());
        }

        if (name != null) {
            firstName = Property.stringFrom(name.getFirstName());
            middleName = Property.stringFrom(name.getMiddleName());
            lastName = Property.stringFrom(name.getLastName());
            displayName = Property.stringFrom(name.getDisplayName());
            initials = Property.stringFrom(name.getInitials());
            nickName = Property.stringFrom(name.getNickname());
            suffix = Property.stringFrom(name.getSuffix());
            salutation = Property.stringFrom(name.getSalutation());
        }

        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT);

        //
        // GENERAL
        //

        if (log.isTraceEnabled()) {
            log.trace("Preparing statement with ID " + id);
        }
        ps.setLong(1, id);

        if (log.isTraceEnabled()) {
            log.trace("Preparing statement with user ID " + userId);
        }
        ps.setString(2, userId);

        ps.setLong(3, lastUpdate.getTime());
        ps.setString(4, String.valueOf(Def.PIM_STATE_NEW));

        boolean hasPhoto = false;
        Photo photo = personalDetail.getPhotoObject();
        if (photo != null && (photo.getImage() != null || photo.getUrl() != null)) {
            hasPhoto = true;
            ps.setShort(5, photo.getImage() != null ? ContactWrapper.PHOTO_IMAGE : ContactWrapper.PHOTO_URL);
        } else if (photo != null) {
            ps.setShort(5, ContactWrapper.EMPTY_PHOTO);
        } else {
            ps.setNull(5, Types.SMALLINT);
        }

        //
        // CONTACT DETAILS
        //

        if (importance != null) {
            ps.setShort(6, importance.shortValue());
        } else {
            ps.setNull(6, Types.SMALLINT);
        }

        if (sensitivity != null) {
            ps.setShort(7, sensitivity.shortValue());
        } else {
            ps.setNull(7, Types.SMALLINT);
        }

        ps.setString(8, StringUtils.left(subject, SQL_SUBJECT_DIM));
        ps.setString(9, StringUtils.left(folder, SQL_FOLDER_DIM));

        //
        // PERSONAL DETAILS
        //

        ps.setString(10, StringUtils.left(anniversary, SQL_ANNIVERSARY_DIM));
        ps.setString(11, StringUtils.left(firstName, SQL_FIRSTNAME_DIM));
        ps.setString(12, StringUtils.left(middleName, SQL_MIDDLENAME_DIM));
        ps.setString(13, StringUtils.left(lastName, SQL_LASTNAME_DIM));
        ps.setString(14, StringUtils.left(displayName, SQL_DISPLAYNAME_DIM));
        ps.setString(15, StringUtils.left(birthday, SQL_BIRTHDAY_DIM));

        if (c.getNotes() != null && c.getNotes().size() > 0) {
            String noteValue = ((Note) c.getNotes().get(0)).getPropertyValueAsString();
            ps.setString(16, StringUtils.left(noteValue, SQL_NOTE_DIM));
        } else {
            ps.setString(16, null);
        }

        ps.setString(17, StringUtils.left(categories, SQL_CATEGORIES_DIM));
        ps.setString(18, StringUtils.left(children, SQL_CHILDREN_DIM));
        ps.setString(19, StringUtils.left(hobbies, SQL_HOBBIES_DIM));
        ps.setString(20, StringUtils.left(initials, SQL_INITIALS_DIM));
        ps.setString(21, StringUtils.left(languages, SQL_LANGUAGES_DIM));
        ps.setString(22, StringUtils.left(nickName, SQL_NICKNAME_DIM));
        ps.setString(23, StringUtils.left(spouse, SQL_SPOUSE_DIM));
        ps.setString(24, StringUtils.left(suffix, SQL_SUFFIX_DIM));
        ps.setString(25, StringUtils.left(salutation, SQL_SALUTATION_DIM));

        //
        // BUSINESS DETAILS
        //
        ps.setString(26, StringUtils.left(assistant, SQL_ASSISTANT_DIM));
        ps.setString(27, StringUtils.left(company, SQL_COMPANY_DIM));
        ps.setString(28, StringUtils.left(department, SQL_DEPARTMENT_DIM));

        if (businessDetail.getTitles() != null && businessDetail.getTitles().size() > 0) {
            String titleValue = ((Title) businessDetail.getTitles().get(0)).getPropertyValueAsString();
            ps.setString(29, StringUtils.left(titleValue, SQL_TITLE_DIM));
        } else {
            ps.setString(29, null);
        }

        ps.setString(30, StringUtils.left(manager, SQL_MANAGER_DIM));
        if (mileage != null && mileage.length() > SQL_MILEAGE_DIM) {
            mileage = mileage.substring(0, SQL_MILEAGE_DIM);
        }
        ps.setString(31, StringUtils.left(mileage, SQL_MILEAGE_DIM));
        ps.setString(32, StringUtils.left(officeLocation, SQL_OFFICELOCATION_DIM));
        ps.setString(33, StringUtils.left(role, SQL_ROLE_DIM));
        ps.setString(34, StringUtils.left(companies, SQL_COMPANIES_DIM));
        ps.setString(35, StringUtils.left(gender, SQL_GENDER_DIM));

        ps.executeUpdate();

        DBTools.close(null, ps, null);

        //
        // emails
        //
        if (!emails.isEmpty()) {

            ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = emails.size(); i < l; i++) {

                email = emails.get(i);

                type = getContactEmailItemTypeFromEmailPropertyType(email.getEmailType());
                // Unknown property: saves nothing
                if (TYPE_UNDEFINED == type)
                    continue;

                String emailValue = email.getPropertyValueAsString();

                if (emailValue != null && emailValue.length() != 0) {
                    if (emailValue.length() > SQL_EMAIL_DIM) {
                        emailValue = emailValue.substring(0, SQL_EMAIL_DIM);
                    }
                    ps.setLong(1, id);
                    ps.setInt(2, type);
                    ps.setString(3, emailValue);

                    ps.executeUpdate();
                }

            }

            DBTools.close(null, ps, null);

        }

        //
        // phones
        //
        if (!phones.isEmpty()) {

            ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = phones.size(); i < l; i++) {

                phone = phones.get(i);

                type = getContactPhoneItemTypeFromPhonePropertyType(phone.getPhoneType());
                // Unknown property: saves nothing
                if (TYPE_UNDEFINED == type)
                    continue;

                String phoneValue = phone.getPropertyValueAsString();
                if (phoneValue != null && phoneValue.length() != 0) {
                    if (phoneValue.length() > SQL_PHONE_DIM) {
                        phoneValue = phoneValue.substring(0, SQL_PHONE_DIM);
                    }

                    ps.setLong(1, id);
                    ps.setInt(2, type);
                    ps.setString(3, phoneValue);

                    ps.executeUpdate();
                }

            }

            DBTools.close(null, ps, null);

        }

        //
        // webPages
        //
        if (!webPages.isEmpty()) {

            ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = webPages.size(); i < l; i++) {

                webPage = webPages.get(i);

                webPageType = webPage.getWebPageType();

                if ((FIELD_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_WEB_PAGE;
                } else if ((FIELD_HOME_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_HOME_WEB_PAGE;
                } else if ((FIELD_BUSINESS_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_BUSINESS_WEB_PAGE;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                String webPageValue = webPage.getPropertyValueAsString();
                if (webPageValue != null && webPageValue.length() != 0) {
                    if (webPageValue.length() > SQL_WEBPAGE_DIM) {
                        webPageValue = webPageValue.substring(0, SQL_WEBPAGE_DIM);
                    }

                    ps.setLong(1, id);
                    ps.setInt(2, type);
                    ps.setString(3, webPageValue);

                    ps.executeUpdate();
                }

            }

            DBTools.close(null, ps, null);

        }

        if (homeAddressBook != null) {

            String homeStreet = Property.stringFrom(homeAddressBook.getStreet());
            String homeCity = Property.stringFrom(homeAddressBook.getCity());
            String homePostalCode = Property.stringFrom(homeAddressBook.getPostalCode());
            String homeState = Property.stringFrom(homeAddressBook.getState());
            String homeCountry = Property.stringFrom(homeAddressBook.getCountry());
            String homePostalOfficeAddress = Property.stringFrom(homeAddressBook.getPostOfficeAddress());
            String homeExtendedAddress = Property.stringFrom(homeAddressBook.getExtendedAddress());

            String homeLabel = Property.stringFrom(homeAddressBook.getLabel());
            if (homeLabel != null) {
                String[] label = { homeLabel, FIELD_HOME_LABEL };
                labels.add(label);
            }

            String[] homeAddressFields = { homeStreet, homeCity, homePostalCode, homeCountry, homeState,
                    homePostalOfficeAddress, homeExtendedAddress };

            if (!hasOnlyEmptyOrNullContent(homeAddressFields)) {

                ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                ps.setLong(1, id);
                ps.setInt(2, ADDRESS_TYPE_HOME);
                ps.setString(3, replaceNewLine(StringUtils.left(homeStreet, SQL_STREET_DIM)));
                ps.setString(4, StringUtils.left(homeCity, SQL_CITY_DIM));
                ps.setString(5, StringUtils.left(homeState, SQL_STATE_DIM));
                ps.setString(6, StringUtils.left(homePostalCode, SQL_POSTALCODE_DIM));
                ps.setString(7, StringUtils.left(homeCountry, SQL_COUNTRY_DIM));
                ps.setString(8, StringUtils.left(homePostalOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM));
                ps.setString(9, StringUtils.left(homeExtendedAddress, SQL_EXTENDEDADDRESS_DIM));

                ps.executeUpdate();

                DBTools.close(null, ps, null);
            }
        }

        if (otherAddressBook != null) {

            String otherStreet = Property.stringFrom(otherAddressBook.getStreet());
            String otherCity = Property.stringFrom(otherAddressBook.getCity());
            String otherPostalCode = Property.stringFrom(otherAddressBook.getPostalCode());
            String otherState = Property.stringFrom(otherAddressBook.getState());
            String otherCountry = Property.stringFrom(otherAddressBook.getCountry());
            String otherPostalOfficeAddress = Property.stringFrom(otherAddressBook.getPostOfficeAddress());
            String otherExtendedAddress = Property.stringFrom(otherAddressBook.getExtendedAddress());

            String otherLabel = Property.stringFrom(otherAddressBook.getLabel());
            if (otherLabel != null) {
                String[] label = { otherLabel, FIELD_OTHER_LABEL };
                labels.add(label);
            }

            String[] otherAddressFields = { otherStreet, otherCity, otherPostalCode, otherCountry, otherState,
                    otherPostalOfficeAddress, otherExtendedAddress };

            if (!hasOnlyEmptyOrNullContent(otherAddressFields)) {

                ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                ps.setLong(1, id);
                ps.setInt(2, ADDRESS_TYPE_OTHER);
                ps.setString(3, replaceNewLine(StringUtils.left(otherStreet, SQL_STREET_DIM)));
                ps.setString(4, StringUtils.left(otherCity, SQL_CITY_DIM));
                ps.setString(5, StringUtils.left(otherState, SQL_STATE_DIM));
                ps.setString(6, StringUtils.left(otherPostalCode, SQL_POSTALCODE_DIM));
                ps.setString(7, StringUtils.left(otherCountry, SQL_COUNTRY_DIM));
                ps.setString(8, StringUtils.left(otherPostalOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM));
                ps.setString(9, StringUtils.left(otherExtendedAddress, SQL_EXTENDEDADDRESS_DIM));

                ps.executeUpdate();

                DBTools.close(null, ps, null);

            }
        }

        if (workAddressBook != null) {

            String workStreet = Property.stringFrom(workAddressBook.getStreet());
            String workCity = Property.stringFrom(workAddressBook.getCity());
            String workPostalCode = Property.stringFrom(workAddressBook.getPostalCode());
            String workState = Property.stringFrom(workAddressBook.getState());
            String workCountry = Property.stringFrom(workAddressBook.getCountry());
            String workPostalOfficeAddress = Property.stringFrom(workAddressBook.getPostOfficeAddress());
            String workExtendedAddress = Property.stringFrom(workAddressBook.getExtendedAddress());

            String workLabel = Property.stringFrom(workAddressBook.getLabel());
            if (workLabel != null) {
                String[] label = { workLabel, FIELD_BUSINESS_LABEL };
                labels.add(label);
            }

            String[] workAddressFields = { workStreet, workCity, workPostalCode, workCountry, workState,
                    workPostalOfficeAddress, workExtendedAddress };

            if (!hasOnlyEmptyOrNullContent(workAddressFields)) {

                ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                ps.setLong(1, id);
                ps.setInt(2, ADDRESS_TYPE_WORK);
                ps.setString(3, replaceNewLine(StringUtils.left(workStreet, SQL_STREET_DIM)));
                ps.setString(4, StringUtils.left(workCity, SQL_CITY_DIM));
                ps.setString(5, StringUtils.left(workState, SQL_STATE_DIM));
                ps.setString(6, StringUtils.left(workPostalCode, SQL_POSTALCODE_DIM));
                ps.setString(7, StringUtils.left(workCountry, SQL_COUNTRY_DIM));
                ps.setString(8, StringUtils.left(workPostalOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM));
                ps.setString(9, StringUtils.left(workExtendedAddress, SQL_EXTENDEDADDRESS_DIM));

                ps.executeUpdate();

                DBTools.close(null, ps, null);
            }

        }

        //
        // labels
        //
        if (!labels.isEmpty()) {

            ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = labels.size(); i < l; i++) {

                String[] label = labels.get(i);

                String labelType = label[1];

                if ((FIELD_HOME_LABEL).equals(labelType)) {
                    type = TYPE_HOME_LABEL;
                } else if ((FIELD_BUSINESS_LABEL).equals(labelType)) {
                    type = TYPE_BUSINESS_LABEL;
                } else if ((FIELD_OTHER_LABEL).equals(labelType)) {
                    type = TYPE_OTHER_LABEL;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                String labelValue = label[0];
                if (labelValue != null && labelValue.length() != 0) {
                    if (labelValue.length() > SQL_LABEL_DIM) {
                        labelValue = labelValue.substring(0, SQL_LABEL_DIM);
                    }

                    ps.setLong(1, id);
                    ps.setInt(2, type);
                    ps.setString(3, labelValue);

                    ps.executeUpdate();
                }

            }

            DBTools.close(null, ps, null);

        }

        if (hasPhoto) {
            insertPhoto(con, Long.parseLong(cw.getId()), photo);
        }

    } catch (Exception e) {
        throw new DAOException("Error adding contact.", e);
    } finally {
        DBTools.close(con, ps, null);
    }

    if (log.isTraceEnabled()) {
        log.trace("Added item with ID '" + id + "'");
    }
}

From source file:com.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Updates a contact.//from  w w w  .  ja v a  2s . c  om
 *
 * @param cw as a ContactWrapper object. If its last update time is null,
 *           then it's set to the current time.
 * @return the UID of the contact
 * @throws DAOException
 *
 * @see ContactWrapper
 */
public String updateItem(ContactWrapper cw) throws DAOException {

    Connection con = null;
    PreparedStatement ps = null;
    PreparedStatement ps1 = null;
    ResultSet rs = null;

    int type = 0;

    PersonalDetail personalDetail = null;
    BusinessDetail businessDetail = null;
    Address homeAddressBook = null;
    Address workAddressBook = null;
    Address otherAddressBook = null;

    Name name = null;
    Phone phone = null;
    Email email = null;
    WebPage webPage = null;

    List<WebPage> webPages = new ArrayList<WebPage>();
    List<Email> emails = new ArrayList<Email>();
    List<Phone> phones = new ArrayList<Phone>();
    List<String[]> labels = new ArrayList<String[]>();

    String phoneType = null;
    String webPageType = null;

    StringBuffer queryUpdateFunPimContact = null;

    Short importance = null;
    Short sensitivity = null;
    String mileage = null;
    String subject = null;
    String folder = null;
    String anniversary = null;
    String firstName = null;
    String middleName = null;
    String lastName = null;
    String displayName = null;
    String birthday = null;
    String note = null;
    String categories = null;
    String hobbies = null;
    String gender = null;
    String initials = null;
    String languages = null;
    String nickName = null;
    String spouse = null;
    String suffix = null;
    String assistant = null;
    String company = null;
    String companies = null;
    String department = null;
    String jobTitle = null;
    String manager = null;
    String city = null;
    String state = null;
    String role = null;
    String children = null;
    String salutation = null;
    String officeLocation = null;
    String street = null;
    String postalCode = null;
    String country = null;
    String postOfficeAddress = null;
    String extendedAddress = null;

    String[] addressFields = null;

    boolean findRecord = false;
    boolean emptyAddress = false;

    short photoType = ContactWrapper.EMPTY_PHOTO;
    boolean photoToRemove = false;
    boolean photoToSet = false;
    boolean photoNothingToDo = false;

    StringBuffer sqlUpdateFunPimAddress = null;

    try {

        Timestamp lastUpdate = (cw.getLastUpdate() == null) ? new Timestamp(System.currentTimeMillis())
                : cw.getLastUpdate();

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        Contact c = cw.getContact();

        personalDetail = c.getPersonalDetail();
        businessDetail = c.getBusinessDetail();
        name = c.getName();
        importance = c.getImportance();
        sensitivity = c.getSensitivity();
        mileage = c.getMileage();
        subject = c.getSubject();
        languages = c.getLanguages();
        folder = c.getFolder();
        categories = Property.stringFrom(c.getCategories());

        if (personalDetail != null) {

            homeAddressBook = personalDetail.getAddress();
            otherAddressBook = personalDetail.getOtherAddress();
            anniversary = personalDetail.getAnniversary();
            birthday = personalDetail.getBirthday();
            children = personalDetail.getChildren();
            spouse = personalDetail.getSpouse();
            hobbies = personalDetail.getHobbies();
            gender = personalDetail.getGender();
            webPages.addAll(personalDetail.getWebPages());
            emails.addAll(personalDetail.getEmails());
            phones.addAll(personalDetail.getPhones());
        }

        if (businessDetail != null) {

            assistant = businessDetail.getAssistant();
            manager = businessDetail.getManager();
            workAddressBook = businessDetail.getAddress();
            companies = businessDetail.getCompanies();
            company = Property.stringFrom(businessDetail.getCompany());
            department = Property.stringFrom(businessDetail.getDepartment());
            role = Property.stringFrom(businessDetail.getRole());
            officeLocation = businessDetail.getOfficeLocation();
            webPages.addAll(businessDetail.getWebPages());
            emails.addAll(businessDetail.getEmails());
            phones.addAll(businessDetail.getPhones());
        }

        if (name != null) {
            firstName = Property.stringFrom(name.getFirstName());
            middleName = Property.stringFrom(name.getMiddleName());
            lastName = Property.stringFrom(name.getLastName());
            displayName = Property.stringFrom(name.getDisplayName());
            initials = Property.stringFrom(name.getInitials());
            nickName = Property.stringFrom(name.getNickname());
            suffix = Property.stringFrom(name.getSuffix());
            salutation = Property.stringFrom(name.getSalutation());
        }

        if (c.getNotes() != null && c.getNotes().size() > 0) {
            note = ((Note) c.getNotes().get(0)).getPropertyValueAsString();
        } else {
            note = null;
        }

        if (businessDetail.getTitles() != null && businessDetail.getTitles().size() > 0) {
            jobTitle = ((Title) businessDetail.getTitles().get(0)).getPropertyValueAsString();
        } else {
            jobTitle = null;
        }

        queryUpdateFunPimContact = new StringBuffer();

        queryUpdateFunPimContact.append(
                SQL_UPDATE_FNBL_PIM_CONTACT_BEGIN + SQL_FIELD_LAST_UPDATE + SQL_EQUALS_QUESTIONMARK_COMMA);

        //
        // Updating photo:
        // 1. if the contact doesn't have a photo (photo null),
        //    nothing should be done (If there is a photo in the db this will
        //    be kept)
        // 2. if the contact has a photo (image or url) it must be inserted
        //    in the db
        // 3. if the photo has a photo but the image and the url are null,
        //    the one in the db must be removed
        //
        Photo photo = personalDetail.getPhotoObject();
        if (photo == null) {
            //
            // nothing to do
            //
            photoNothingToDo = true;
        } else {
            if (photo.getImage() != null) {
                photoType = ContactWrapper.PHOTO_IMAGE;
                photoToSet = true;
            } else if (photo.getUrl() != null) {
                photoType = ContactWrapper.PHOTO_URL;
                photoToSet = true;
            } else {
                photoToRemove = true;
                photoType = ContactWrapper.EMPTY_PHOTO;
            }
            queryUpdateFunPimContact.append(SQL_FIELD_PHOTO_TYPE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        if (importance != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_IMPORTANCE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (sensitivity != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_SENSITIVITY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (subject != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_SUBJECT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (folder != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_FOLDER + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (anniversary != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_ANNIVERSARY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (firstName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_FIRST_NAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (middleName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_MIDDLE_NAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (lastName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_LAST_NAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (displayName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_DISPLAY_NAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (birthday != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_BIRTHDAY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (note != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_BODY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (categories != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_CATEGORIES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (children != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_CHILDREN + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (hobbies != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_HOBBIES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (initials != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_INITIALS + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (languages != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_LANGUAGES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (nickName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_NICKNAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (spouse != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_SPOUSE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (suffix != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_SUFFIX + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (salutation != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_TITLE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (assistant != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_ASSISTANT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (company != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_COMPANY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (department != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_DEPARTMENT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (jobTitle != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_JOB_TITLE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (manager != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_MANAGER + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (mileage != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_MILEAGE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (officeLocation != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_OFFICE_LOCATION + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (role != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_PROFESSION + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (companies != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_COMPANIES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (gender != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_GENDER + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        queryUpdateFunPimContact
                .append(SQL_FIELD_STATUS + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_CONTACT_END);

        ps = con.prepareStatement(queryUpdateFunPimContact.toString());

        int k = 1;

        //
        // GENERAL
        //
        ps.setLong(k++, lastUpdate.getTime());

        //
        // PHOTO TYPE
        //
        if (!photoNothingToDo) {
            ps.setShort(k++, photoType);
        }

        //
        // CONTACT DETAILS
        //
        if (importance != null) {
            ps.setShort(k++, importance.shortValue());
        }
        if (sensitivity != null) {
            ps.setShort(k++, sensitivity.shortValue());
        }

        if (subject != null) {
            if (subject.length() > SQL_SUBJECT_DIM) {
                subject = subject.substring(0, SQL_SUBJECT_DIM);
            }
            ps.setString(k++, subject);
        }
        //
        // folder
        //
        if (folder != null) {
            if (folder.length() > SQL_FOLDER_DIM) {
                folder = folder.substring(0, SQL_FOLDER_DIM);
            }
            ps.setString(k++, folder);
        }

        //
        // PERSONAL DETAILS
        //

        //
        // anniversary
        //
        if (anniversary != null) {
            if (anniversary.length() > SQL_ANNIVERSARY_DIM) {
                anniversary = anniversary.substring(0, SQL_ANNIVERSARY_DIM);
            }
            ps.setString(k++, anniversary);
        }
        //
        // firstName
        //
        if (firstName != null) {
            if (firstName.length() > SQL_FIRSTNAME_DIM) {
                firstName = firstName.substring(0, SQL_FIRSTNAME_DIM);
            }
            ps.setString(k++, firstName);
        }
        //
        // middleName
        //
        if (middleName != null) {
            if (middleName.length() > SQL_MIDDLENAME_DIM) {
                middleName = middleName.substring(0, SQL_MIDDLENAME_DIM);
            }
            ps.setString(k++, middleName);
        }
        //
        // lastName
        //
        if (lastName != null) {
            if (lastName.length() > SQL_LASTNAME_DIM) {
                lastName = lastName.substring(0, SQL_LASTNAME_DIM);
            }
            ps.setString(k++, lastName);
        }
        //
        // displayName
        //
        if (displayName != null) {
            if (displayName.length() > SQL_DISPLAYNAME_DIM) {
                displayName = displayName.substring(0, SQL_DISPLAYNAME_DIM);
            }
            ps.setString(k++, displayName);
        }
        //
        // birthday
        //
        if (birthday != null) {
            if (birthday.length() > SQL_BIRTHDAY_DIM) {
                birthday = birthday.substring(0, SQL_BIRTHDAY_DIM);
            }
            ps.setString(k++, birthday);
        }
        //
        // note
        //
        if (note != null) {
            if (note.length() > SQL_NOTE_DIM) {
                note = note.substring(0, SQL_NOTE_DIM);
            }
            ps.setString(k++, note);
        }
        //
        // categories
        //
        if (categories != null) {
            if (categories.length() > SQL_CATEGORIES_DIM) {
                categories = categories.substring(0, SQL_CATEGORIES_DIM);
            }
            ps.setString(k++, categories);
        }
        //
        // children
        //
        if (children != null) {
            if (children.length() > SQL_CHILDREN_DIM) {
                children = children.substring(0, SQL_CHILDREN_DIM);
            }
            ps.setString(k++, children);
        }
        //
        // hobbies
        //
        if (hobbies != null) {
            if (hobbies.length() > SQL_HOBBIES_DIM) {
                hobbies = hobbies.substring(0, SQL_HOBBIES_DIM);
            }
            ps.setString(k++, hobbies);
        }
        //
        // initials
        //
        if (initials != null) {
            if (initials.length() > SQL_INITIALS_DIM) {
                initials = initials.substring(0, SQL_INITIALS_DIM);
            }
            ps.setString(k++, initials);
        }
        //
        // languages
        //
        if (languages != null) {
            if (languages.length() > SQL_LANGUAGES_DIM) {
                languages = initials.substring(0, SQL_LANGUAGES_DIM);
            }
            ps.setString(k++, languages);
        }
        //
        // nickName
        //
        if (nickName != null) {
            if (nickName.length() > SQL_NICKNAME_DIM) {
                nickName = nickName.substring(0, SQL_NICKNAME_DIM);
            }
            ps.setString(k++, nickName);
        }
        //
        // spouse
        //
        if (spouse != null) {
            if (spouse.length() > SQL_SPOUSE_DIM) {
                spouse = spouse.substring(0, SQL_SPOUSE_DIM);
            }
            ps.setString(k++, spouse);
        }
        //
        // suffix
        //
        if (suffix != null) {
            if (suffix.length() > SQL_SUFFIX_DIM) {
                suffix = suffix.substring(0, SQL_SUFFIX_DIM);
            }
            ps.setString(k++, suffix);
        }
        //
        // salutation
        //
        if (salutation != null) {
            if (salutation.length() > SQL_SALUTATION_DIM) {
                salutation = salutation.substring(0, SQL_SALUTATION_DIM);
            }
            ps.setString(k++, salutation);
        }
        //
        // assistant
        //
        if (assistant != null) {
            if (assistant.length() > SQL_ASSISTANT_DIM) {
                assistant = assistant.substring(0, SQL_ASSISTANT_DIM);
            }
            ps.setString(k++, assistant);
        }
        //
        // company
        //
        if (company != null) {
            if (company.length() > SQL_COMPANY_DIM) {
                company = company.substring(0, SQL_COMPANY_DIM);
            }
            ps.setString(k++, company);
        }
        //
        // department
        //
        if (department != null) {
            if (department.length() > SQL_DEPARTMENT_DIM) {
                department = department.substring(0, SQL_DEPARTMENT_DIM);
            }
            ps.setString(k++, department);
        }
        //
        // jobTitle
        //
        if (jobTitle != null) {
            if (jobTitle.length() > SQL_TITLE_DIM) {
                jobTitle = jobTitle.substring(0, SQL_TITLE_DIM);
            }
            ps.setString(k++, jobTitle);
        }
        //
        // manager
        //
        if (manager != null) {
            if (manager.length() > SQL_MANAGER_DIM) {
                manager = manager.substring(0, SQL_MANAGER_DIM);
            }
            ps.setString(k++, manager);
        }
        //
        // mileage
        //
        if (mileage != null) {
            if (mileage.length() > SQL_MILEAGE_DIM) {
                mileage = mileage.substring(0, SQL_MILEAGE_DIM);
            }
            ps.setString(k++, mileage);
        }
        if (officeLocation != null) {
            if (officeLocation.length() > SQL_OFFICELOCATION_DIM) {
                officeLocation = officeLocation.substring(0, SQL_OFFICELOCATION_DIM);
            }
            ps.setString(k++, officeLocation);
        }
        //
        // role
        //
        if (role != null) {
            if (role.length() > SQL_ROLE_DIM) {
                role = role.substring(0, SQL_ROLE_DIM);
            }
            ps.setString(k++, role);
        }

        //
        // companies
        //
        if (companies != null) {
            if (companies.length() > SQL_COMPANIES_DIM) {
                companies = companies.substring(0, SQL_COMPANIES_DIM);
            }
            ps.setString(k++, companies);
        }

        //
        // gender
        //
        if (gender != null) {
            if (gender.length() > SQL_GENDER_DIM) {
                gender = gender.substring(0, SQL_GENDER_DIM);
            }
            ps.setString(k++, gender);
        }

        //
        // status
        //
        ps.setString(k++, String.valueOf('U'));
        //
        // id
        //
        ps.setLong(k++, Long.parseLong(cw.getId()));
        //
        // userId
        //
        ps.setString(k++, userId);

        ps.executeUpdate();

        DBTools.close(null, ps, null);

        //
        // emails
        //
        if (!emails.isEmpty()) {
            ps1 = con.prepareStatement(SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = emails.size(); i < l; i++) {

                email = emails.get(i);

                if ((FIELD_EMAIL_1_ADDRESS).equals(email.getEmailType())) {
                    type = TYPE_EMAIL_1_ADDRESS;
                } else if ((FIELD_EMAIL_2_ADDRESS).equals(email.getEmailType())) {
                    type = TYPE_EMAIL_2_ADDRESS;
                } else if ((FIELD_EMAIL_3_ADDRESS).equals(email.getEmailType())) {
                    type = TYPE_EMAIL_3_ADDRESS;
                } else if ((FIELD_INSTANT_MESSENGER).equals(email.getEmailType())) {
                    type = TYPE_INSTANT_MESSENGER;
                } else {
                    //
                    // no save unknown property
                    //
                    continue;
                }

                ps1.setLong(1, Long.parseLong(cw.getId()));
                ps1.setInt(2, type);

                rs = ps1.executeQuery();

                findRecord = rs.next();

                rs.close();
                rs = null;

                String emailValue = email.getPropertyValueAsString();

                emailValue = StringUtils.left(emailValue, SQL_EMAIL_DIM);

                if (!findRecord) {

                    if (emailValue != null && emailValue.length() != 0) {
                        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                        ps.setString(3, emailValue);

                        ps.executeUpdate();

                        DBTools.close(null, ps, null);
                    }

                } else {

                    if (emailValue != null) {
                        ps = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_ITEM);

                        ps.setString(1, emailValue);
                        ps.setLong(2, Long.parseLong(cw.getId()));
                        ps.setInt(3, type);

                    } else {

                        ps = con.prepareStatement(SQL_DELETE_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);

                    }

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }
            }

            DBTools.close(null, ps1, null);

        }

        //
        // phones
        //
        if (!phones.isEmpty()) {

            ps1 = con.prepareStatement(SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = phones.size(); i < l; i++) {

                phone = phones.get(i);

                phoneType = phone.getPhoneType();

                if ((FIELD_HOME_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_HOME_TELEPHONE_NUMBER;
                } else if ((FIELD_HOME_2_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_HOME_2_TELEPHONE_NUMBER;
                } else if ((FIELD_HOME_FAX_NUMBER).equals(phoneType)) {
                    type = TYPE_HOME_FAX_NUMBER;
                } else if ((FIELD_MOBILE_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_MOBILE_TELEPHONE_NUMBER;
                } else if ((FIELD_CAR_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_CAR_TELEPHONE_NUMBER;
                } else if ((FIELD_OTHER_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_OTHER_TELEPHONE_NUMBER;
                } else if ((FIELD_OTHER_FAX_NUMBER).equals(phoneType)) {
                    type = TYPE_OTHER_FAX_NUMBER;
                } else if ((FIELD_PRIMARY_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_PRIMARY_TELEPHONE_NUMBER;
                } else if ((FIELD_BUSINESS_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_BUSINESS_TELEPHONE_NUMBER;
                } else if ((FIELD_BUSINESS_2_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_BUSINESS_2_TELEPHONE_NUMBER;
                } else if ((FIELD_BUSINESS_FAX_NUMBER).equals(phoneType)) {
                    type = TYPE_BUSINESS_FAX_NUMBER;
                } else if ((FIELD_COMPANY_MAIN_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_COMPANY_MAIN_TELEPHONE_NUMBER;
                } else if ((FIELD_PAGER_NUMBER).equals(phoneType)) {
                    type = TYPE_PAGER_NUMBER;
                } else if ((FIELD_ASSISTANT_NUMBER).equals(phoneType)) {
                    type = TYPE_ASSISTANT_NUMBER;
                } else if ((FIELD_CALLBACK_NUMBER).equals(phoneType)) {
                    type = TYPE_CALLBACK_NUMBER;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                ps1.setLong(1, Long.parseLong(cw.getId()));
                ps1.setInt(2, type);

                rs = ps1.executeQuery();

                findRecord = rs.next();

                String phoneValue = phone.getPropertyValueAsString();
                phoneValue = StringUtils.left(phoneValue, SQL_EMAIL_DIM);

                if (!findRecord) {
                    if (phoneValue != null && phoneValue.length() != 0) {
                        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                        ps.setString(3, phoneValue);

                        ps.executeUpdate();

                        DBTools.close(null, ps, null);
                    }

                } else {

                    if (phoneValue != null) {
                        ps = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_ITEM);

                        ps.setString(1, phoneValue);
                        ps.setLong(2, Long.parseLong(cw.getId()));
                        ps.setInt(3, type);

                    } else {
                        ps = con.prepareStatement(SQL_DELETE_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                    }

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }

                DBTools.close(null, null, rs);

            }

            DBTools.close(null, ps1, null);

        }

        //
        // web pages
        //
        if (!webPages.isEmpty()) {

            ps1 = con.prepareStatement(SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = webPages.size(); i < l; i++) {

                webPage = webPages.get(i);

                webPageType = webPage.getWebPageType();

                if ((FIELD_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_WEB_PAGE;
                } else if ((FIELD_HOME_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_HOME_WEB_PAGE;
                } else if ((FIELD_BUSINESS_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_BUSINESS_WEB_PAGE;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                ps1.setLong(1, Long.parseLong(cw.getId()));
                ps1.setInt(2, type);

                rs = ps1.executeQuery();

                findRecord = rs.next();

                String webPageValue = webPage.getPropertyValueAsString();
                webPageValue = StringUtils.left(webPageValue, SQL_WEBPAGE_DIM);

                if (!findRecord) {

                    if (webPageValue != null && webPageValue.length() != 0) {
                        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                        ps.setString(3, webPageValue);

                        ps.executeUpdate();

                        DBTools.close(null, ps, null);
                    }

                } else {

                    if (webPageValue != null) {
                        ps = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_ITEM);

                        ps.setString(1, webPageValue);
                        ps.setLong(2, Long.parseLong(cw.getId()));
                        ps.setInt(3, type);
                    } else {
                        ps = con.prepareStatement(SQL_DELETE_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                    }

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }

                DBTools.close(null, null, rs);

            }

            DBTools.close(null, ps1, null);

        }

        //
        // home address
        //
        if (homeAddressBook != null) {

            ps = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_ADDRESS);

            ps.setLong(1, Long.parseLong(cw.getId()));
            ps.setInt(2, ADDRESS_TYPE_HOME);

            rs = ps.executeQuery();

            findRecord = rs.next();

            DBTools.close(null, ps, rs);

            street = Property.stringFrom(homeAddressBook.getStreet());
            city = Property.stringFrom(homeAddressBook.getCity());
            postalCode = Property.stringFrom(homeAddressBook.getPostalCode());
            state = Property.stringFrom(homeAddressBook.getState());
            country = Property.stringFrom(homeAddressBook.getCountry());
            postOfficeAddress = Property.stringFrom(homeAddressBook.getPostOfficeAddress());
            extendedAddress = Property.stringFrom(homeAddressBook.getExtendedAddress());

            street = replaceNewLine(StringUtils.left(street, SQL_STREET_DIM));
            city = StringUtils.left(city, SQL_CITY_DIM);
            state = StringUtils.left(state, SQL_STATE_DIM);
            postalCode = StringUtils.left(postalCode, SQL_POSTALCODE_DIM);
            country = StringUtils.left(country, SQL_COUNTRY_DIM);
            postOfficeAddress = StringUtils.left(postOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM);
            extendedAddress = StringUtils.left(extendedAddress, SQL_EXTENDEDADDRESS_DIM);

            String homeLabel = Property.stringFrom(homeAddressBook.getLabel());
            if (homeLabel != null) {
                String[] label = { homeLabel, FIELD_HOME_LABEL };
                labels.add(label);
            }

            addressFields = new String[] { street, city, postalCode, country, state, postOfficeAddress,
                    extendedAddress };

            emptyAddress = hasOnlyNullContent(addressFields);

            if (!emptyAddress) {

                if (!findRecord && !hasOnlyEmptyOrNullContent(addressFields)) {
                    ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                    ps.setLong(1, Long.parseLong(cw.getId()));
                    ps.setInt(2, ADDRESS_TYPE_HOME);
                    ps.setString(3, street);
                    ps.setString(4, city);
                    ps.setString(5, state);
                    ps.setString(6, postalCode);
                    ps.setString(7, country);
                    ps.setString(8, postOfficeAddress);
                    ps.setString(9, extendedAddress);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);

                } else {

                    sqlUpdateFunPimAddress = new StringBuffer();

                    sqlUpdateFunPimAddress.append(SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN);

                    if (street != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STREET + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (city != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_CITY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (state != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STATE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postalCode != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_POSTAL_CODE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (country != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_COUNTRY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postOfficeAddress != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_PO_BOX + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (extendedAddress != null) {
                        sqlUpdateFunPimAddress
                                .append(SQL_FIELD_EXTENDED_ADDRESS + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }

                    sqlUpdateFunPimAddress
                            .append(SQL_FIELD_TYPE + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_ADDRESS_END);

                    ps = con.prepareStatement(sqlUpdateFunPimAddress.toString());

                    k = 1;

                    if (street != null) {
                        ps.setString(k++, street);
                    }
                    if (city != null) {
                        ps.setString(k++, city);
                    }
                    if (state != null) {
                        ps.setString(k++, state);
                    }
                    if (postalCode != null) {
                        ps.setString(k++, postalCode);
                    }
                    if (country != null) {
                        ps.setString(k++, country);
                    }
                    if (postOfficeAddress != null) {
                        ps.setString(k++, postOfficeAddress);
                    }
                    if (extendedAddress != null) {
                        ps.setString(k++, extendedAddress);
                    }

                    ps.setInt(k++, ADDRESS_TYPE_HOME);
                    ps.setLong(k++, Long.parseLong(cw.getId()));
                    ps.setInt(k++, ADDRESS_TYPE_HOME);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }

            }

        }

        //
        // other address
        //
        if (otherAddressBook != null) {

            ps = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_ADDRESS);

            ps.setLong(1, Long.parseLong(cw.getId()));
            ps.setInt(2, ADDRESS_TYPE_OTHER);

            rs = ps.executeQuery();

            findRecord = rs.next();

            DBTools.close(null, ps, rs);

            street = Property.stringFrom(otherAddressBook.getStreet());
            city = Property.stringFrom(otherAddressBook.getCity());
            postalCode = Property.stringFrom(otherAddressBook.getPostalCode());
            state = Property.stringFrom(otherAddressBook.getState());
            country = Property.stringFrom(otherAddressBook.getCountry());
            postOfficeAddress = Property.stringFrom(otherAddressBook.getPostOfficeAddress());
            extendedAddress = Property.stringFrom(otherAddressBook.getExtendedAddress());

            street = replaceNewLine(StringUtils.left(street, SQL_STREET_DIM));
            city = StringUtils.left(city, SQL_CITY_DIM);
            state = StringUtils.left(state, SQL_STATE_DIM);
            postalCode = StringUtils.left(postalCode, SQL_POSTALCODE_DIM);
            country = StringUtils.left(country, SQL_COUNTRY_DIM);
            postOfficeAddress = StringUtils.left(postOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM);
            extendedAddress = StringUtils.left(extendedAddress, SQL_EXTENDEDADDRESS_DIM);

            addressFields = new String[] { street, city, postalCode, country, state, postOfficeAddress,
                    extendedAddress };

            String otherLabel = Property.stringFrom(otherAddressBook.getLabel());
            if (otherLabel != null) {
                String[] label = { otherLabel, FIELD_OTHER_LABEL };
                labels.add(label);
            }

            emptyAddress = hasOnlyNullContent(addressFields);

            if (!emptyAddress) {

                if (!findRecord && !hasOnlyEmptyOrNullContent(addressFields)) {

                    ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                    ps.setLong(1, Long.parseLong(cw.getId()));
                    ps.setInt(2, ADDRESS_TYPE_OTHER);
                    ps.setString(3, street);
                    ps.setString(4, city);
                    ps.setString(5, state);
                    ps.setString(6, postalCode);
                    ps.setString(7, country);
                    ps.setString(8, postOfficeAddress);
                    ps.setString(9, extendedAddress);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                } else {

                    sqlUpdateFunPimAddress = new StringBuffer();

                    sqlUpdateFunPimAddress.append(SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN);

                    if (street != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STREET + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (city != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_CITY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (state != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STATE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postalCode != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_POSTAL_CODE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (country != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_COUNTRY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postOfficeAddress != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_PO_BOX + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (extendedAddress != null) {
                        sqlUpdateFunPimAddress
                                .append(SQL_FIELD_EXTENDED_ADDRESS + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }

                    sqlUpdateFunPimAddress
                            .append(SQL_FIELD_TYPE + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_ADDRESS_END);

                    ps = con.prepareStatement(sqlUpdateFunPimAddress.toString());

                    k = 1;

                    if (street != null) {
                        ps.setString(k++, street);
                    }
                    if (city != null) {
                        ps.setString(k++, city);
                    }
                    if (state != null) {
                        ps.setString(k++, state);
                    }
                    if (postalCode != null) {
                        ps.setString(k++, postalCode);
                    }
                    if (country != null) {
                        ps.setString(k++, country);
                    }
                    if (postOfficeAddress != null) {
                        ps.setString(k++, postOfficeAddress);
                    }
                    if (extendedAddress != null) {
                        ps.setString(k++, extendedAddress);
                    }

                    ps.setInt(k++, ADDRESS_TYPE_OTHER);
                    ps.setLong(k++, Long.parseLong(cw.getId()));
                    ps.setInt(k++, ADDRESS_TYPE_OTHER);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);

                }

            }

        }

        //
        // work address
        //
        if (workAddressBook != null) {

            ps = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_ADDRESS);

            ps.setLong(1, Long.parseLong(cw.getId()));
            ps.setInt(2, ADDRESS_TYPE_WORK);

            rs = ps.executeQuery();

            findRecord = rs.next();

            DBTools.close(null, ps, rs);

            street = Property.stringFrom(workAddressBook.getStreet());
            city = Property.stringFrom(workAddressBook.getCity());
            postalCode = Property.stringFrom(workAddressBook.getPostalCode());
            state = Property.stringFrom(workAddressBook.getState());
            country = Property.stringFrom(workAddressBook.getCountry());
            postOfficeAddress = Property.stringFrom(workAddressBook.getPostOfficeAddress());
            extendedAddress = Property.stringFrom(workAddressBook.getExtendedAddress());

            street = replaceNewLine(StringUtils.left(street, SQL_STREET_DIM));
            city = StringUtils.left(city, SQL_CITY_DIM);
            state = StringUtils.left(state, SQL_STATE_DIM);
            postalCode = StringUtils.left(postalCode, SQL_POSTALCODE_DIM);
            country = StringUtils.left(country, SQL_COUNTRY_DIM);
            postOfficeAddress = StringUtils.left(postOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM);
            extendedAddress = StringUtils.left(extendedAddress, SQL_EXTENDEDADDRESS_DIM);

            String workLabel = Property.stringFrom(workAddressBook.getLabel());
            if (workLabel != null) {
                String[] label = { workLabel, FIELD_BUSINESS_LABEL };
                labels.add(label);
            }

            addressFields = new String[] { street, city, postalCode, country, state, postOfficeAddress,
                    extendedAddress };

            emptyAddress = hasOnlyNullContent(addressFields);

            if (!emptyAddress) {

                if (!findRecord && !hasOnlyEmptyOrNullContent(addressFields)) {

                    ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                    ps.setLong(1, Long.parseLong(cw.getId()));
                    ps.setInt(2, ADDRESS_TYPE_WORK);
                    ps.setString(3, street);
                    ps.setString(4, city);
                    ps.setString(5, state);
                    ps.setString(6, postalCode);
                    ps.setString(7, country);
                    ps.setString(8, postOfficeAddress);
                    ps.setString(9, extendedAddress);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);

                } else {

                    sqlUpdateFunPimAddress = new StringBuffer();

                    sqlUpdateFunPimAddress.append(SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN);

                    if (street != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STREET + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (city != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_CITY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (state != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STATE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postalCode != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_POSTAL_CODE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (country != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_COUNTRY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postOfficeAddress != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_PO_BOX + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (extendedAddress != null) {
                        sqlUpdateFunPimAddress
                                .append(SQL_FIELD_EXTENDED_ADDRESS + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }

                    sqlUpdateFunPimAddress
                            .append(SQL_FIELD_TYPE + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_ADDRESS_END);

                    ps = con.prepareStatement(sqlUpdateFunPimAddress.toString());

                    k = 1;

                    if (street != null) {
                        ps.setString(k++, street);
                    }
                    if (city != null) {
                        ps.setString(k++, city);
                    }
                    if (state != null) {
                        ps.setString(k++, state);
                    }
                    if (postalCode != null) {
                        ps.setString(k++, postalCode);
                    }
                    if (country != null) {
                        ps.setString(k++, country);
                    }
                    if (postOfficeAddress != null) {
                        ps.setString(k++, postOfficeAddress);
                    }
                    if (extendedAddress != null) {
                        ps.setString(k++, extendedAddress);
                    }

                    ps.setInt(k++, ADDRESS_TYPE_WORK);
                    ps.setLong(k++, Long.parseLong(cw.getId()));
                    ps.setInt(k++, ADDRESS_TYPE_WORK);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);

                }

            }

        }

        //
        // labels
        //
        if (!labels.isEmpty()) {

            ps1 = con.prepareStatement(SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = labels.size(); i < l; i++) {

                String[] label = labels.get(i);

                String labelType = label[1];

                if ((FIELD_HOME_LABEL).equals(labelType)) {
                    type = TYPE_HOME_LABEL;
                } else if ((FIELD_BUSINESS_LABEL).equals(labelType)) {
                    type = TYPE_BUSINESS_LABEL;
                } else if ((FIELD_OTHER_LABEL).equals(labelType)) {
                    type = TYPE_OTHER_LABEL;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                ps1.setLong(1, Long.parseLong(cw.getId()));
                ps1.setInt(2, type);

                rs = ps1.executeQuery();

                findRecord = rs.next();

                String labelValue = StringUtils.left(label[0], SQL_LABEL_DIM);

                if (!findRecord) {

                    if (labelValue != null && labelValue.length() != 0) {
                        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                        ps.setString(3, labelValue);

                        ps.executeUpdate();

                        DBTools.close(null, ps, null);
                    }

                } else {

                    if (labelValue != null) {
                        ps = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_ITEM);

                        ps.setString(1, labelValue);
                        ps.setLong(2, Long.parseLong(cw.getId()));
                        ps.setInt(3, type);
                    } else {
                        ps = con.prepareStatement(SQL_DELETE_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                    }

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }

                DBTools.close(null, null, rs);

            }

            DBTools.close(null, ps1, null);

        }
        if (photoToSet) {
            setPhoto(con, Long.parseLong(cw.getId()), photo);
        } else if (photoToRemove) {
            deletePhoto(con, Long.parseLong(cw.getId()));
        }

    } catch (Exception e) {
        throw new DAOException("Error updating contact.", e);
    } finally {
        DBTools.close(con, ps, rs);
    }

    return cw.getId();
}