Example usage for java.sql Types BIGINT

List of usage examples for java.sql Types BIGINT

Introduction

In this page you can find the example usage for java.sql Types BIGINT.

Prototype

int BIGINT

To view the source code for java.sql Types BIGINT.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type BIGINT.

Usage

From source file:com.evolveum.midpoint.repo.sql.SqlAuditServiceImpl.java

/**
 * This method creates temporary table for cleanup audit method.
 *
 * @param session//from  ww w. j a  va  2s. com
 * @param dialect
 * @param tempTable
 */
private void createTemporaryTable(Session session, final Dialect dialect, final String tempTable) {
    session.doWork(new Work() {

        @Override
        public void execute(Connection connection) throws SQLException {
            //check if table exists
            try {
                Statement s = connection.createStatement();
                s.execute("select id from " + tempTable + " where id = 1");
                //table already exists
                return;
            } catch (Exception ex) {
                //we expect this on the first time
            }

            StringBuilder sb = new StringBuilder();
            sb.append(dialect.getCreateTemporaryTableString());
            sb.append(' ').append(tempTable).append(" (id ");
            sb.append(dialect.getTypeName(Types.BIGINT));
            sb.append(" not null)");
            sb.append(dialect.getCreateTemporaryTablePostfix());

            Statement s = connection.createStatement();
            s.execute(sb.toString());
        }
    });
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSybase.CFAsteriskSybaseClusterTable.java

public long nextHostNodeIdGen(CFSecurityAuthorization Authorization, CFSecurityClusterPKey PKey) {
    final String S_ProcName = "nextHostNodeIdGen";
    if (!schema.isTransactionOpen()) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Not in a transaction");
    }/*from   ww  w . j  a va2  s .  c o m*/
    Connection cnx = schema.getCnx();
    long Id = PKey.getRequiredId();

    CallableStatement stmtSelectNextHostNodeIdGen = null;
    try {
        String sql = "{ call sp_next_hostnodeidgen( ?" + ", " + "?" + " ) }";
        stmtSelectNextHostNodeIdGen = cnx.prepareCall(sql);
        int argIdx = 1;
        stmtSelectNextHostNodeIdGen.registerOutParameter(argIdx++, java.sql.Types.BIGINT);
        stmtSelectNextHostNodeIdGen.setLong(argIdx++, Id);
        stmtSelectNextHostNodeIdGen.execute();
        long nextId = stmtSelectNextHostNodeIdGen.getLong(1);
        return (nextId);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (stmtSelectNextHostNodeIdGen != null) {
            try {
                stmtSelectNextHostNodeIdGen.close();
            } catch (SQLException e) {
            }
            stmtSelectNextHostNodeIdGen = null;
        }
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.TableContextUtil.java

public static String getPartitionSizeValidationError(int colType, String column, String partitionSize) {
    switch (colType) {
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
        try {/*from w ww.j a va 2  s .  c om*/
            int intVal = Integer.parseInt(partitionSize);
            if (intVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.BIGINT:
        // TIME, DATE, and TIMESTAMP are represented as long (epoch)
    case Types.TIME:
    case Types.DATE:
    case Types.TIMESTAMP:
        try {
            long longVal = Long.parseLong(partitionSize);
            if (longVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.FLOAT:
    case Types.REAL:
        try {
            float floatVal = Float.parseFloat(partitionSize);
            if (floatVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.DOUBLE:
        try {
            double doubleVal = Double.parseDouble(partitionSize);
            if (doubleVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.NUMERIC:
    case Types.DECIMAL:
        try {
            BigDecimal decimalValue = new BigDecimal(partitionSize);
            if (decimalValue.signum() < 1) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    }
    return null;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_1.CFAstSybase.CFAstSybaseClusterTable.java

public long nextHostNodeIdGen(CFAstAuthorization Authorization, CFAstClusterPKey PKey) {
    final String S_ProcName = "nextHostNodeIdGen";
    if (!schema.isTransactionOpen()) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Not in a transaction");
    }//  w  w  w . jav a  2 s.co m
    Connection cnx = schema.getCnx();
    long Id = PKey.getRequiredId();

    CallableStatement stmtSelectNextHostNodeIdGen = null;
    try {
        String sql = "{ call sp_next_hostnodeidgen( ?" + ", " + "?" + " ) }";
        stmtSelectNextHostNodeIdGen = cnx.prepareCall(sql);
        int argIdx = 1;
        stmtSelectNextHostNodeIdGen.registerOutParameter(argIdx++, java.sql.Types.BIGINT);
        stmtSelectNextHostNodeIdGen.setLong(argIdx++, Id);
        stmtSelectNextHostNodeIdGen.execute();
        long nextId = stmtSelectNextHostNodeIdGen.getLong(1);
        return (nextId);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (stmtSelectNextHostNodeIdGen != null) {
            try {
                stmtSelectNextHostNodeIdGen.close();
            } catch (SQLException e) {
            }
            stmtSelectNextHostNodeIdGen = null;
        }
    }
}

From source file:at.alladin.rmbt.controlServer.RegistrationResource.java

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    final String secret = getContext().getParameters().getFirstValue("RMBT_SECRETKEY");

    addAllowOrigin();//  w  w  w .j  ava2s.co  m

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    final InetAddress clientAddress = InetAddresses.forString(clientIpRaw);
    final String clientIpString = InetAddresses.toAddrString(clientAddress);

    System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST"), clientIpRaw));

    final String geoIpCountry = GeoIPHelper.lookupCountry(clientAddress);
    // public_ip_asn
    final Long asn = Helperfunctions.getASN(clientAddress);
    // public_ip_as_name 
    // country_asn (2 digit country code of AS, eg. AT or EU)
    final String asName;
    final String asCountry;
    if (asn == null) {
        asName = null;
        asCountry = null;
    } else {
        asName = Helperfunctions.getASName(asn);
        asCountry = Helperfunctions.getAScountry(asn);
    }

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            int typeId = 0;

            final String lang = request.optString("language");

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            }

            //                System.out.println(request.toString(4));

            if (conn != null) {

                final Client clientDb = new Client(conn);

                if (!request.optString("type").isEmpty()) {
                    typeId = clientDb.getTypeId(request.getString("type"));
                    if (clientDb.hasError())
                        errorList.addError(clientDb.getError());
                }

                final List<String> clientNames = Arrays
                        .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*"));
                final List<String> clientVersions = Arrays
                        .asList(settings.getString("RMBT_VERSION_NUMBER").split(",\\s*"));

                if (clientNames.contains(request.optString("client"))
                        && clientVersions.contains(request.optString("version")) && typeId > 0) {

                    UUID uuid = null;
                    final String uuidString = request.optString("uuid", "");
                    if (uuidString.length() != 0)
                        uuid = UUID.fromString(uuidString);

                    final String clientName = request.getString("client");
                    final String clientVersion = request.getString("version");

                    String timeZoneId = request.getString("timezone");
                    // String tmpTimeZoneId = timeZoneId;

                    final long clientTime = request.getLong("time");
                    final Timestamp clientTstamp = java.sql.Timestamp
                            .valueOf(new Timestamp(clientTime).toString());

                    final JSONObject location = request.optJSONObject("location");

                    long geotime = 0;
                    double geolat = 0;
                    double geolong = 0;
                    float geoaccuracy = 0;
                    double geoaltitude = 0;
                    float geobearing = 0;
                    float geospeed = 0;
                    String geoprovider = "";

                    if (!request.isNull("location")) {
                        geotime = location.optLong("time", 0);
                        geolat = location.optDouble("lat", 0);
                        geolong = location.optDouble("long", 0);
                        geoaccuracy = (float) location.optDouble("accuracy", 0);
                        geoaltitude = location.optDouble("altitude", 0);
                        geobearing = (float) location.optDouble("bearing", 0);
                        geospeed = (float) location.optDouble("speed", 0);
                        geoprovider = location.optString("provider", "");
                    }

                    Calendar timeWithZone = null;

                    if (timeZoneId.isEmpty()) {
                        timeZoneId = Helperfunctions.getTimezoneId();
                        timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);
                    } else
                        timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);

                    long clientUid = 0;
                    /*
                     * if (uuid == null) {
                     * clientDb.setTimeZone(timeWithZone);
                     * clientDb.setTime(tstamp);
                     * clientDb.setClient_type_id(typeId); uuid =
                     * clientDb.storeClient(); if (clientDb.hasError()) {
                     * errorList.addError(clientDb.getError()); } else {
                     * answer.put("uuid", uuid.toString()); } }
                     */

                    if (errorList.getLength() == 0 && uuid != null) {
                        clientUid = clientDb.getClientByUuid(uuid);
                        if (clientDb.hasError())
                            errorList.addError(clientDb.getError());
                    }

                    if (clientUid > 0) {

                        final String testUuid = UUID.randomUUID().toString();
                        final String testOpenUuid = UUID.randomUUID().toString();

                        boolean testServerEncryption = true; // default is
                                                             // true

                        // hack for android api <= 10 (2.3.x)
                        // using encryption with test doesn't work
                        if (request.has("plattform") && request.optString("plattform").equals("Android"))
                            if (request.has("api_level")) {
                                final String apiLevelString = request.optString("api_level");
                                try {
                                    final int apiLevel = Integer.parseInt(apiLevelString);
                                    if (apiLevel <= 10)
                                        testServerEncryption = false;
                                } catch (final NumberFormatException e) {
                                }
                            }

                        final String serverType;
                        if (request.optString("client").equals("RMBTws"))
                            serverType = "RMBTws";
                        else
                            serverType = "RMBT";

                        final Boolean ipv6;
                        if (clientAddress instanceof Inet6Address)
                            ipv6 = true;
                        else if (clientAddress instanceof Inet4Address)
                            ipv6 = false;
                        else // should never happen, unless ipv > 6 is available
                            ipv6 = null;

                        final TestServer server = getNearestServer(errorList, geolat, geolong, geotime,
                                clientIpString, asCountry, geoIpCountry, serverType, testServerEncryption,
                                ipv6);

                        try {
                            if (server == null)
                                throw new JSONException("could not find server");

                            if (timeZoneId.isEmpty()) {
                                timeZoneId = Helperfunctions.getTimezoneId();
                                timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);
                            } else
                                timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);

                            answer.put("test_server_address", server.address);
                            answer.put("test_server_port", server.port);
                            answer.put("test_server_name", server.name);
                            answer.put("test_server_encryption", testServerEncryption);

                            answer.put("test_duration", getSetting("rmbt_duration"));
                            answer.put("test_numthreads", getSetting("rmbt_num_threads"));
                            answer.put("test_numpings", getSetting("rmbt_num_pings"));

                            answer.put("client_remote_ip", clientIpString);

                            final String resultUrl = new Reference(getURL(),
                                    settings.getString("RMBT_RESULT_PATH")).getTargetRef().toString();

                            // System.out.println(resultUrl);

                            answer.put("result_url", resultUrl);

                            final String resultQoSUrl = new Reference(getURL(),
                                    settings.getString("RMBT_QOS_RESULT_PATH")).getTargetRef().toString();

                            // System.out.println(resultUrl);

                            answer.put("result_qos_url", resultQoSUrl);
                        } catch (final JSONException e) {
                            System.out.println("Error generating Answer " + e.toString());
                            errorList.addError("ERROR_RESPONSE_JSON");

                        }

                        if (errorList.getLength() == 0)
                            try {

                                PreparedStatement st;
                                st = conn.prepareStatement(
                                        "INSERT INTO test(time, uuid, open_test_uuid, client_id, client_name, client_version, client_software_version, client_language, client_public_ip, client_public_ip_anonymized, country_geoip, server_id, port, use_ssl, timezone, client_time, duration, num_threads_requested, status, software_revision, client_test_counter, client_previous_test_status, public_ip_asn, public_ip_as_name, country_asn, public_ip_rdns, run_ndt)"
                                                + "VALUES(NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                                        Statement.RETURN_GENERATED_KEYS);

                                int i = 1;
                                // uuid
                                st.setObject(i++, UUID.fromString(testUuid));
                                // open_test_uuid
                                st.setObject(i++, UUID.fromString(testOpenUuid));
                                // client_id
                                st.setLong(i++, clientUid);
                                // client_name
                                st.setString(i++, clientName);
                                // client_version
                                st.setString(i++, clientVersion);
                                // client_software_version
                                st.setString(i++, request.optString("softwareVersion", null));
                                // client_language
                                st.setString(i++, lang);
                                // client_public_ip
                                st.setString(i++, clientIpString);
                                // client_public_ip_anonymized
                                st.setString(i++, Helperfunctions.anonymizeIp(clientAddress));
                                // country_geoip (2digit country code derived from public IP of client)
                                st.setString(i++, geoIpCountry);
                                // server_id
                                st.setInt(i++, server.id);
                                // port
                                st.setInt(i++, server.port);
                                // use_ssl
                                st.setBoolean(i++, testServerEncryption);
                                // timezone (of client)
                                st.setString(i++, timeZoneId);
                                // client_time (local time of client)
                                st.setTimestamp(i++, clientTstamp, timeWithZone);
                                // duration (requested)
                                st.setInt(i++, Integer.parseInt(getSetting("rmbt_duration")));
                                // num_threads_requested 
                                st.setInt(i++, Integer.parseInt(getSetting("rmbt_num_threads")));
                                // status (of test)
                                st.setString(i++, "STARTED"); //was "RUNNING" before
                                // software_revision (of client)
                                st.setString(i++, request.optString("softwareRevision", null));
                                // client_test_counter (number of tests the client has performed)
                                final int testCounter = request.optInt("testCounter", -1);
                                if (testCounter == -1) // older clients did not support testCounter
                                    st.setNull(i++, Types.INTEGER);
                                else
                                    st.setLong(i++, testCounter);
                                // client_previous_test_status (outcome of previous test)
                                st.setString(i++, request.optString("previousTestStatus", null));
                                // AS name
                                if (asn == null)
                                    st.setNull(i++, Types.BIGINT);
                                else
                                    st.setLong(i++, asn);
                                if (asName == null)
                                    st.setNull(i++, Types.VARCHAR);
                                else
                                    st.setString(i++, asName);
                                // AS country
                                if (asCountry == null)
                                    st.setNull(i++, Types.VARCHAR);
                                else
                                    st.setString(i++, asCountry);
                                //public_ip_rdns
                                String reverseDNS = Helperfunctions.reverseDNSLookup(clientAddress);
                                if (reverseDNS == null || reverseDNS.isEmpty())
                                    st.setNull(i++, Types.VARCHAR);
                                else {
                                    reverseDNS = reverseDNS.replaceFirst("\\.$", "");
                                    st.setString(i++, reverseDNS); // cut off last dot (#332)
                                }
                                // run_ndt
                                if (request.has("ndt"))
                                    st.setBoolean(i++, request.getBoolean("ndt"));
                                else
                                    st.setNull(i++, Types.BOOLEAN);

                                final int affectedRows = st.executeUpdate();
                                if (affectedRows == 0)
                                    errorList.addError("ERROR_DB_STORE_TEST");
                                else {
                                    long key = 0;
                                    final ResultSet rs = st.getGeneratedKeys();
                                    if (rs.next())
                                        // Retrieve the auto generated
                                        // key(s).
                                        key = rs.getLong(1);
                                    rs.close();

                                    final PreparedStatement getProviderSt = conn
                                            .prepareStatement("SELECT rmbt_set_provider_from_as(?)");
                                    getProviderSt.setLong(1, key);
                                    String provider = null;
                                    if (getProviderSt.execute()) {
                                        final ResultSet rs2 = getProviderSt.getResultSet();
                                        if (rs2.next())
                                            provider = rs2.getString(1);
                                    }

                                    if (provider != null)
                                        answer.put("provider", provider);

                                    final PreparedStatement testSlotStatement = conn
                                            .prepareStatement("SELECT rmbt_get_next_test_slot(?)");
                                    testSlotStatement.setLong(1, key);
                                    int testSlot = -1;
                                    if (testSlotStatement.execute()) {
                                        final ResultSet rs2 = testSlotStatement.getResultSet();
                                        if (rs2.next())
                                            testSlot = rs2.getInt(1);
                                    }

                                    if (testSlot < 0)
                                        errorList.addError("ERROR_DB_STORE_GENERAL");
                                    else {
                                        final String data = testUuid + "_" + testSlot;
                                        final String hmac = Helperfunctions.calculateHMAC(secret, data);
                                        if (hmac.length() == 0)
                                            errorList.addError("ERROR_TEST_TOKEN");
                                        final String token = data + "_" + hmac;

                                        final PreparedStatement updateSt = conn
                                                .prepareStatement("UPDATE test SET token = ? WHERE uid = ?");
                                        updateSt.setString(1, token);
                                        updateSt.setLong(2, key);
                                        updateSt.executeUpdate();

                                        answer.put("test_token", token);

                                        answer.put("test_uuid", testUuid);
                                        answer.put("test_id", key);

                                        final long now = System.currentTimeMillis();
                                        int wait = testSlot - (int) (now / 1000);
                                        if (wait < 0)
                                            wait = 0;

                                        answer.put("test_wait", wait);

                                        if (geotime != 0 && geolat != 0 && geolong != 0) {

                                            final GeoLocation clientLocation = new GeoLocation(conn);

                                            clientLocation.setTest_id(key);

                                            final Timestamp geotstamp = java.sql.Timestamp
                                                    .valueOf(new Timestamp(geotime).toString());
                                            clientLocation.setTime(geotstamp, timeZoneId);

                                            clientLocation.setAccuracy(geoaccuracy);
                                            clientLocation.setAltitude(geoaltitude);
                                            clientLocation.setBearing(geobearing);
                                            clientLocation.setSpeed(geospeed);
                                            clientLocation.setProvider(geoprovider);
                                            clientLocation.setGeo_lat(geolat);
                                            clientLocation.setGeo_long(geolong);

                                            clientLocation.storeLocation();

                                            if (clientLocation.hasError())
                                                errorList.addError(clientLocation.getError());
                                        }
                                    }
                                }

                                st.close();
                            } catch (final SQLException e) {
                                errorList.addError("ERROR_DB_STORE_GENERAL");
                                e.printStackTrace();

                            }

                    } else
                        errorList.addError("ERROR_CLIENT_UUID");

                } else
                    errorList.addError("ERROR_CLIENT_VERSION");

            } else
                errorList.addError("ERROR_DB_CONNECTION");
            //                System.out.println(answer.toString(4));
        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();
    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

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

/**
 * Adds file data object metadata of an item to the database.
 * @param fdow/*from   w  ww.  j  a v a2 s  .c  o  m*/
 * @throws com.funambol.foundation.exception.DAOException
 */
public String addItem(FileDataObjectWrapper fdow) throws DAOException {

    Connection con = null;
    PreparedStatement ps = null;

    try {

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

        if (fdow.getId() == null) {
            throw new DAOException("Unable to add item: id should be already defined");
        }

        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_FILE_DATA_OBJECT);

        int k = 1;

        ps.setLong(k++, Long.parseLong(fdow.getId()));

        ps.setString(k++, userId);

        ps.setString(k++, sourceURI);

        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        Timestamp lastUpdate = fdow.getLastUpdate();
        if (lastUpdate == null) {
            lastUpdate = currentTime;
        }
        ps.setLong(k++, lastUpdate.getTime());

        ps.setString(k++, String.valueOf(SyncItemState.NEW));

        FileDataObject fdo = fdow.getFileDataObject();

        ps.setString(k++, String.valueOf(fdo.getUploadStatus()));

        String fileName = fdow.getLocalName();
        if (fileName == null || fileName.length() == 0) {
            ps.setNull(k++, Types.VARCHAR);
        } else {
            ps.setString(k++, StringUtils.left(fileName, SQL_LOCAL_NAME_DIM));
        }

        Long crc = Long.valueOf(fdow.getFileDataObject().getCrc());
        ps.setLong(k++, crc);

        ps.setString(k++, StringUtils.left(fdo.getName(), SQL_TRUE_NAME_DIM));

        MediaUtils.setFDODates(fdo, fdo.getCreated(), fdo.getModified());

        Timestamp created = timestamp(fdo.getCreated());
        if (created != null) {
            ps.setTimestamp(k++, created);
        } else {
            ps.setTimestamp(k++, currentTime);
        }

        Timestamp modified = timestamp(fdo.getModified());
        if (modified != null) {
            ps.setTimestamp(k++, modified);
        } else {
            ps.setTimestamp(k++, currentTime);
        }

        ps.setTimestamp(k++, timestamp(fdo.getAccessed()));

        ps.setString(k++, fdo.isHidden() ? ONE : NIL);
        ps.setString(k++, fdo.isSystem() ? ONE : NIL);
        ps.setString(k++, fdo.isArchived() ? ONE : NIL);
        ps.setString(k++, fdo.isDeleted() ? ONE : NIL);
        ps.setString(k++, fdo.isWritable() ? ONE : NIL);
        ps.setString(k++, fdo.isReadable() ? ONE : NIL);
        ps.setString(k++, fdo.isExecutable() ? ONE : NIL);

        if (fdo.getContentType() != null) {
            ps.setString(k++, StringUtils.left(fdo.getContentType(), SQL_CTTYPE_DIM));
        } else {
            ps.setNull(k++, Types.VARCHAR);
        }

        if (fdo.getSize() == null) {
            ps.setNull(k++, Types.BIGINT);
        } else {
            ps.setLong(k++, fdo.getSize());
        }

        if (fdow.getSizeOnStorage() == null) {
            ps.setNull(k++, Types.BIGINT);
        } else {
            ps.setLong(k++, fdow.getSizeOnStorage());
        }

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

        // stores file data object properties
        addProperties(fdow);

    } catch (Exception e) {
        throw new DAOException("Error adding file data object.", e);
    } finally {
        DBTools.close(con, ps, null);
    }
    return fdow.getId();
}

From source file:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 * Return true is the SQL type is supported by the GeoJSON driver.
 *
 * @param sqlTypeId/*from w  ww . j ava2  s .co  m*/
 * @param sqlTypeName
 * @return
 * @throws SQLException
 */
public boolean isSupportedPropertyType(int sqlTypeId, String sqlTypeName) throws SQLException {
    switch (sqlTypeId) {
    case Types.BOOLEAN:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.INTEGER:
    case Types.BIGINT:
    case Types.SMALLINT:
    case Types.DATE:
    case Types.VARCHAR:
    case Types.NCHAR:
    case Types.CHAR:
        return true;
    default:
        throw new SQLException("Field type not supported by GeoJSON driver: " + sqlTypeName);
    }
}

From source file:com.alibaba.otter.shared.common.utils.meta.DdlUtils.java

private static Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values)
        throws SQLException {
    Column column = new Column();

    column.setName((String) values.get("COLUMN_NAME"));
    column.setDefaultValue((String) values.get("COLUMN_DEF"));
    column.setTypeCode(((Integer) values.get("DATA_TYPE")).intValue());

    String typeName = (String) values.get("TYPE_NAME");
    // column.setType(typeName);

    if ((typeName != null) && typeName.startsWith("TIMESTAMP")) {
        column.setTypeCode(Types.TIMESTAMP);
    }/*from  w w  w .ja  v a 2  s.c  om*/
    // modify 2013-09-25?unsigned
    if ((typeName != null) && StringUtils.containsIgnoreCase(typeName, "UNSIGNED")) {
        // unsigned????
        switch (column.getTypeCode()) {
        case Types.TINYINT:
            column.setTypeCode(Types.SMALLINT);
            break;
        case Types.SMALLINT:
            column.setTypeCode(Types.INTEGER);
            break;
        case Types.INTEGER:
            column.setTypeCode(Types.BIGINT);
            break;
        case Types.BIGINT:
            column.setTypeCode(Types.DECIMAL);
            break;
        default:
            break;
        }
    }

    Integer precision = (Integer) values.get("NUM_PREC_RADIX");

    if (precision != null) {
        column.setPrecisionRadix(precision.intValue());
    }

    String size = (String) values.get("COLUMN_SIZE");

    if (size == null) {
        size = (String) _defaultSizes.get(new Integer(column.getTypeCode()));
    }

    // we're setting the size after the precision and radix in case
    // the database prefers to return them in the size value
    column.setSize(size);

    int scale = 0;
    Object dec_digits = values.get("DECIMAL_DIGITS");

    if (dec_digits instanceof String) {
        scale = (dec_digits == null) ? 0 : NumberUtils.toInt(dec_digits.toString());
    } else if (dec_digits instanceof Integer) {
        scale = (dec_digits == null) ? 0 : (Integer) dec_digits;
    }

    if (scale != 0) {
        column.setScale(scale);
    }

    column.setRequired("NO".equalsIgnoreCase(((String) values.get("IS_NULLABLE")).trim()));
    column.setDescription((String) values.get("REMARKS"));
    return column;
}

From source file:com.netspective.axiom.sql.StoredProcedureParameter.java

/**
 * Extract the OUT parameter values from the callable statment and
 * assign them to the value of the parameter.
 *//*  w w  w  .  ja v  a 2 s  . co  m*/
public void extract(ConnectionContext cc, CallableStatement stmt) throws SQLException {
    if (getType().getValueIndex() == StoredProcedureParameter.Type.IN)
        return;

    int index = this.getIndex();
    QueryParameterType paramType = getSqlType();
    int jdbcType = paramType.getJdbcType();
    String identifier = paramType.getIdentifier();

    // result sets are special
    if (identifier.equals(QueryParameterType.RESULTSET_IDENTIFIER)) {
        ResultSet rs = (ResultSet) stmt.getObject(index);
        QueryResultSet qrs = new QueryResultSet(getParent().getProcedure(), cc, rs);
        value.getValue(cc).setValue(qrs);
        return;
    }

    switch (jdbcType) {
    case Types.VARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case Types.INTEGER:
        value.getValue(cc).setValue(new Integer(stmt.getInt(index)));
        break;
    case Types.DOUBLE:
        value.getValue(cc).setValue(new Double(stmt.getDouble(index)));
        break;
    case Types.CLOB:
        Clob clob = stmt.getClob(index);
        value.getValue(cc).setTextValue(clob.getSubString(1, (int) clob.length()));
        break;
    case java.sql.Types.ARRAY:
        Array array = stmt.getArray(index);
        value.getValue(cc).setValue(array);
        break;
    case java.sql.Types.BIGINT:
        long bigint = stmt.getLong(index);
        value.getValue(cc).setValue(new Long(bigint));
        break;
    case java.sql.Types.BINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.BIT:
        boolean bit = stmt.getBoolean(index);
        value.getValue(cc).setValue(new Boolean(bit));
    case java.sql.Types.BLOB:
        value.getValue(cc).setValue(stmt.getBlob(index));
        break;
    case java.sql.Types.CHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case java.sql.Types.DATE:
        value.getValue(cc).setValue(stmt.getDate(index));
        break;
    case java.sql.Types.DECIMAL:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.DISTINCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.FLOAT:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    case java.sql.Types.JAVA_OBJECT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.LONGVARBINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.LONGVARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    //case java.sql.Types.NULL:
    //    value.getValue(cc).setValue(null);
    //    break;
    case java.sql.Types.NUMERIC:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.OTHER:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.REAL:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    //case java.sql.Types.REF:
    //    Ref ref = stmt.getRef(index);
    //    break;
    case java.sql.Types.SMALLINT:
        short sh = stmt.getShort(index);
        value.getValue(cc).setValue(new Short(sh));
        break;
    case java.sql.Types.STRUCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.TIME:
        value.getValue(cc).setValue(stmt.getTime(index));
        break;
    case java.sql.Types.TIMESTAMP:
        value.getValue(cc).setValue(stmt.getTimestamp(index));
        break;
    case java.sql.Types.TINYINT:
        byte b = stmt.getByte(index);
        value.getValue(cc).setValue(new Byte(b));
        break;
    case java.sql.Types.VARBINARY:
        value.getValue(cc).setValue(stmt.getBytes(index));
        break;
    default:
        throw new RuntimeException(
                "Unknown JDBC Type set for stored procedure parameter '" + this.getName() + "'.");
    }
}

From source file:com.cloudera.sqoop.manager.SqlManager.java

/**
 * Resolve a database-specific type to the Java type that should contain it.
 * @param sqlType//from w w w  .  ja v  a2s . c  o  m
 * @return the name of a Java type to hold the sql datatype, or null if none.
 */
public String toJavaType(int sqlType) {
    // Mappings taken from:
    // http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
    if (sqlType == Types.INTEGER) {
        return "Integer";
    } else if (sqlType == Types.VARCHAR) {
        return "String";
    } else if (sqlType == Types.CHAR) {
        return "String";
    } else if (sqlType == Types.LONGVARCHAR) {
        return "String";
    } else if (sqlType == Types.NUMERIC) {
        return "java.math.BigDecimal";
    } else if (sqlType == Types.DECIMAL) {
        return "java.math.BigDecimal";
    } else if (sqlType == Types.BIT) {
        return "Boolean";
    } else if (sqlType == Types.BOOLEAN) {
        return "Boolean";
    } else if (sqlType == Types.TINYINT) {
        return "Integer";
    } else if (sqlType == Types.SMALLINT) {
        return "Integer";
    } else if (sqlType == Types.BIGINT) {
        return "Long";
    } else if (sqlType == Types.REAL) {
        return "Float";
    } else if (sqlType == Types.FLOAT) {
        return "Double";
    } else if (sqlType == Types.DOUBLE) {
        return "Double";
    } else if (sqlType == Types.DATE) {
        return "java.sql.Date";
    } else if (sqlType == Types.TIME) {
        return "java.sql.Time";
    } else if (sqlType == Types.TIMESTAMP) {
        return "java.sql.Timestamp";
    } else if (sqlType == Types.BINARY || sqlType == Types.VARBINARY) {
        return BytesWritable.class.getName();
    } else if (sqlType == Types.CLOB) {
        return ClobRef.class.getName();
    } else if (sqlType == Types.BLOB || sqlType == Types.LONGVARBINARY) {
        return BlobRef.class.getName();
    } else {
        // TODO(aaron): Support DISTINCT, ARRAY, STRUCT, REF, JAVA_OBJECT.
        // Return null indicating database-specific manager should return a
        // java data type if it can find one for any nonstandard type.
        return null;
    }
}