Example usage for java.sql PreparedStatement setLong

List of usage examples for java.sql PreparedStatement setLong

Introduction

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

Prototype

void setLong(int parameterIndex, long x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java long value.

Usage

From source file:com.flexive.ejb.beans.workflow.WorkflowEngineBean.java

/**
 * {@inheritDoc}// w  w  w. j  a v a2s  .  c  o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(Workflow workflow) throws FxApplicationException {
    UserTicket ticket = FxContext.getUserTicket();
    // Permission checks
    FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement);

    // Do work ..
    Connection con = null;
    PreparedStatement stmt = null;
    String sCurSql = null;
    boolean success = false;
    long id = -1;
    try {
        // Sanity checks
        checkIfValid(workflow);

        // Obtain a database connection
        con = Database.getDbConnection();

        // Create the new workflow instance
        sCurSql = "INSERT INTO " + TBL_WORKFLOW + " (ID,NAME,DESCRIPTION) VALUES (?,?,?)";
        stmt = con.prepareStatement(sCurSql);
        id = seq.getId(FxSystemSequencer.WORKFLOW);
        stmt.setLong(1, id);
        stmt.setString(2, workflow.getName());
        stmt.setString(3, StringUtils.defaultString(workflow.getDescription()));
        stmt.executeUpdate();

        // create step(s)
        final Map<Long, Step> createdSteps = new HashMap<Long, Step>();
        for (Step step : workflow.getSteps()) {
            final Step wfstep = new Step(-1, step.getStepDefinitionId(), id, step.getAclId());
            final long newStepId = stepEngine.createStep(wfstep);
            createdSteps.put(step.getId(), new Step(newStepId, wfstep));
        }

        // create route(s)
        for (Route route : workflow.getRoutes()) {
            routeEngine.create(resolveTemporaryStep(createdSteps, route.getFromStepId()),
                    resolveTemporaryStep(createdSteps, route.getToStepId()), route.getGroupId());
        }
        success = true;
    } catch (Exception exc) {
        if (StorageManager.isUniqueConstraintViolation(exc)) {
            throw new FxEntryExistsException("ex.workflow.exists", workflow.getName());
        } else {
            throw new FxCreateException(LOG, "ex.workflow.create", exc, exc.getMessage());
        }
    } finally {
        Database.closeObjects(WorkflowEngineBean.class, con, stmt);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
    return id;
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static void assertMessageDoesNotExist(Message message) throws SQLException {
    long localChannelId = ChannelController.getInstance().getLocalChannelId(message.getChannelId());

    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet result = null;/*from   w w w. ja va  2 s . c  o  m*/

    try {
        connection = getConnection();
        statement = connection.prepareStatement("SELECT * FROM d_m" + localChannelId + " WHERE id = ?");
        statement.setLong(1, message.getMessageId());
        result = statement.executeQuery();
        assertFalse(result.next());
    } finally {
        close(result);
        close(statement);
        close(connection);
    }
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static boolean isMessageProcessed(String channelId, long messageId) throws SQLException {
    long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId);
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet result = null;//from w  w w  . ja  va2 s  .  c o m

    try {
        connection = getConnection();
        statement = connection.prepareStatement("SELECT processed FROM d_m" + localChannelId + " WHERE id = ?");
        statement.setLong(1, messageId);
        result = statement.executeQuery();
        result.next();
        return result.getBoolean("processed");
    } finally {
        close(result);
        close(statement);
        close(connection);
    }
}

From source file:dk.netarkivet.harvester.datamodel.ScheduleDBDAO.java

/**
 * Create a new schedule./*from w w w .  ja  v a2  s .c  o m*/
 *
 * @param schedule The schedule to create
 * @throws ArgumentNotValid if schedule is null
 * @throws PermissionDenied if a schedule already exists
 */
public synchronized void create(Schedule schedule) {
    ArgumentNotValid.checkNotNull(schedule, "schedule");

    Connection c = HarvestDBConnection.get();
    PreparedStatement s = null;
    try {
        if (exists(c, schedule.getName())) {
            String msg = "Cannot create already existing schedule " + schedule;
            log.debug(msg);
            throw new PermissionDenied(msg);
        }

        s = c.prepareStatement("INSERT INTO schedules " + "( name, comments, startdate, enddate, maxrepeats, "
                + "timeunit, numtimeunits, anytime, onminute, onhour," + " ondayofweek, ondayofmonth, edition )"
                + "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )", Statement.RETURN_GENERATED_KEYS);
        setScheduleParameters(s, schedule);
        final long edition = 1;
        s.setLong(13, edition);
        s.executeUpdate();
        schedule.setID(DBUtils.getGeneratedID(s));
        schedule.setEdition(edition);
    } catch (SQLException e) {
        throw new IOFailure(
                "SQL error while creating schedule " + schedule + "\n" + ExceptionUtils.getSQLExceptionCause(e),
                e);
    } finally {
        HarvestDBConnection.release(c);
    }
}

From source file:com.archivas.clienttools.arcutils.utils.database.PopulateDmDb.java

private void insertRows() throws SQLException, DatabaseException, JobException {
    ArcMoverEngine engine = LocalJvmArcMoverEngine.getInstance();

    List<ManagedJobSummary> allJobs = engine.getAllManagedJobs();
    JobId jobId = null;/*from ww w  .  ja v  a 2  s.c o  m*/
    for (ManagedJobSummary summary : allJobs) {
        if (summary.getJobName().equals(jobName)) {
            jobId = summary.getJobId();
            break;
        }
    }
    if (jobId == null) {
        throw new IllegalArgumentException("Job \"" + jobName + "\" not found");
    }

    System.out.print("Loading managed job ....");
    System.out.flush();
    ManagedJobImpl jobImpl = engine.loadManagedJob(jobId, jobType);
    System.out.println(" done");

    ManagedJob job = jobImpl.getJob();
    AbstractProfileBase sourceProfile = job.getSourceProfile();
    AbstractProfileBase targetProfile = job.getTargetProfile();
    String sourcePath = job.getSourcePath();
    String targetPath = job.getTargetPath();

    ArcCopyFile file = generateFile(sourceProfile, targetProfile, sourcePath, targetPath);
    String fileSourcePath = file.getSourcePath();
    String fileSourceProfile = file.getSourceProfile().getName();
    String fileTargetPath = file.getTargetPath();
    String fileTargetProfile = (targetProfile == null ? null : file.getTargetProfile().getName());
    long fileSize = file.getSize();
    int fileObjectType = FileType.UNKNOWN.ordinal();
    if (file.isDirectory()) {
        fileObjectType = FileType.DIRECTORY.ordinal();
    } else if (file.isFile()) {
        fileObjectType = FileType.FILE.ordinal();
    }
    Long version = file.getSourceVersion();
    if (version == null) {
        version = 0L;
    }

    long recordId = jobImpl.getManagedJobSchema().getLastDbRecordId();
    long discoveredObjectCnt = jobImpl.getDiscoveredObjectCount();
    long totalObjCnt = jobImpl.getTotalObjectCount();

    System.out.println(
            "*** max RECORD_ID = " + recordId + ", initialDiscoveredObjectCnt = " + discoveredObjectCnt);

    boolean isDelete = (jobType == ManagedJob.Type.DELETE);
    String insertSql = "INSERT INTO " + ManagedJobSchema.getJobSchemaName(jobId.getId()) + "."
            + ManagedJobSchema.JOB_FILES_TABLE_NAME
            + (isDelete ? DELETE_INSERT_COLS_SQL : COPY_INSERT_COLS_SQL);
    String updateSql = "UPDATE " + ManagedJobsSchema.JOBS_TABLE_NAME + " set "
            + ManagedJobTableColumn.DISCOVERED_OBJ_CNT + " = ?, " + // 1
            ManagedJobTableColumn.MAX_RECORD_ID + " = ?, " + // 2
            ManagedJobTableColumn.TOTAL_OBJ_CNT + " = ? " + // 3
            " WHERE " + ManagedJobTableColumn.JOB_ID + " = ?"; // 4

    Connection conn = DatabaseResourceManager.createConnection();
    conn.setAutoCommit(false);
    PreparedStatement insertStatement = conn.prepareStatement(insertSql);
    PreparedStatement updateStatement = conn.prepareStatement(updateSql);

    startTime = System.currentTimeMillis();
    long l = 0;
    for (; l < rowCnt; l++) {
        recordId++;
        getLifeCycle(l);
        if (fileLifeCycle.ordinal() > FileLifeCycle.FINDING.ordinal()) {
            totalObjCnt++;
        }
        discoveredObjectCnt++;

        insertStatement.clearParameters();
        insertStatement.setInt(1, DatabaseResourceManager.boolToDbValue(false)); // initial list
        insertStatement.setLong(2, recordId); // record id

        insertStatement.setInt(3, fileObjectType); // record type
        insertStatement.setString(4, fileSourcePath); // source path
        insertStatement.setLong(5, version); // source version
        insertStatement.setString(6, fileSourceProfile); // source profile name
        insertStatement.setInt(7, fileLifeCycle.ordinal()); // life cycle
        if (fileStatus == null) {
            insertStatement.setNull(8, java.sql.Types.SMALLINT); // status
        } else {
            insertStatement.setInt(8, fileStatus.ordinal());
        }

        if (!isDelete) {
            insertStatement.setString(9, fileTargetPath); // target path
            insertStatement.setString(10, fileTargetProfile); // target profile name
            insertStatement.setLong(11, fileSize); // size
        }

        insertStatement.execute();
        if (l % 5000 == 0) {
            // update counts in jobs table
            updateStatement.clearParameters();
            updateStatement.setLong(1, discoveredObjectCnt);
            updateStatement.setLong(2, recordId);
            updateStatement.setLong(3, totalObjCnt);
            updateStatement.setLong(4, jobId.getId());
            updateStatement.execute();

            conn.commit();
            displayStats(l);
        }
    }

    updateStatement.clearParameters();
    updateStatement.setLong(1, discoveredObjectCnt);
    updateStatement.setLong(2, recordId);
    updateStatement.setLong(3, totalObjCnt);
    updateStatement.setLong(4, jobId.getId());
    updateStatement.execute();

    conn.commit();
    displayStats(l);
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static void assertMessageExists(Message message, boolean deepSearch) throws SQLException {
    long localChannelId = ChannelController.getInstance().getLocalChannelId(message.getChannelId());

    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet result = null;/*from  www.  jav a  2  s .c o m*/

    try {
        connection = getConnection();
        statement = connection.prepareStatement("SELECT * FROM d_m" + localChannelId + " WHERE id = ?");
        statement.setLong(1, message.getMessageId());
        result = statement.executeQuery();

        if (result.next()) {
            String serverId = result.getString("server_id");
            Boolean processed = result.getBoolean("processed");
            close(result);
            close(statement);

            assertTrue(testEquality(serverId, message.getServerId()));
            assertTrue(testEquality(processed, message.isProcessed()));

            if (deepSearch) {
                for (ConnectorMessage connectorMessage : message.getConnectorMessages().values()) {
                    assertConnectorMessageExists(connectorMessage, deepSearch, connection);
                }
            }
        } else {
            throw new AssertionError();
        }
    } finally {
        close(result);
        close(statement);
        close(connection);
    }
}

From source file:com.l2jfree.gameserver.model.entity.Auction.java

/** Update auction in DB */
private void updateInDB(L2Player bidder, int bid) {
    Connection con = null;/* w  w  w  .j  a v  a 2 s  .  com*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement;

        if (getBidders().get(bidder.getClanId()) != null) {
            statement = con.prepareStatement(
                    "UPDATE auction_bid SET bidderId=?, bidderName=?, maxBid=?, time_bid=? WHERE auctionId=? AND bidderId=?");
            statement.setInt(1, bidder.getClanId());
            statement.setString(2, bidder.getClan().getLeaderName());
            statement.setInt(3, bid);
            statement.setLong(4, System.currentTimeMillis());
            statement.setInt(5, getId());
            statement.setInt(6, bidder.getClanId());
            statement.execute();
            statement.close();
        } else {
            statement = con.prepareStatement(
                    "INSERT INTO auction_bid (id, auctionId, bidderId, bidderName, maxBid, clan_name, time_bid) VALUES (?, ?, ?, ?, ?, ?, ?)");
            statement.setInt(1, IdFactory.getInstance().getNextId());
            statement.setInt(2, getId());
            statement.setInt(3, bidder.getClanId());
            statement.setString(4, bidder.getName());
            statement.setInt(5, bid);
            statement.setString(6, bidder.getClan().getName());
            statement.setLong(7, System.currentTimeMillis());
            statement.execute();
            statement.close();
            L2Player highest = L2World.getInstance().getPlayer(_highestBidderName);
            if (highest != null)
                highest.sendMessage("You have been out bidded");
        }
        _highestBidderId = bidder.getClanId();
        _highestBidderMaxBid = bid;
        _highestBidderName = bidder.getClan().getLeaderName();
        if (_bidders.get(_highestBidderId) == null) {
            _bidders.put(_highestBidderId, new Bidder(_highestBidderName, bidder.getClan().getName(), bid,
                    System.currentTimeMillis()));
        } else {
            _bidders.get(_highestBidderId).setBid(bid);
            _bidders.get(_highestBidderId).setTimeBid(System.currentTimeMillis());
        }
        bidder.sendPacket(SystemMessageId.BID_IN_CLANHALL_AUCTION);
    } catch (Exception e) {
        _log.fatal("Exception: Auction.updateInDB(L2Player bidder, int bid): ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.dsf.dbxtract.cdc.journal.JournalExecutor.java

/**
 * Gets reference data from journal table.
 * /*from  w  w w.  ja  v  a 2s  .  c  o  m*/
 * @param client
 * @param conn
 * @return a Map list with column names and values
 * @throws SQLException
 * @throws ConfigurationException
 */
private List<Map<String, Object>> getJournalKeys(CuratorFramework client, Connection conn)
        throws SQLException, ConfigurationException {

    List<Map<String, Object>> result = new ArrayList<>();
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        // Obtem os dados do journal
        if (logger.isDebugEnabled())
            logger.debug(logPrefix + "getting journalized data");
        StringBuilder baseQuery = new StringBuilder("select * from ").append(handler.getJournalTable());
        if (JournalStrategy.WINDOW.equals(handler.getStrategy())) {
            Long lastWindowId = getLastWindowId(client);
            baseQuery.append(" where window_id > ?");
            ps = conn.prepareStatement(baseQuery.toString());
            ps.setLong(1, lastWindowId);
        } else {
            ps = conn.prepareStatement(baseQuery.toString());
        }
        ps.setFetchSize(handler.getBatchSize());
        ps.setMaxRows(handler.getBatchSize());
        rs = ps.executeQuery();
        copyResultsetToMap(rs, result);

    } finally {
        DBUtils.close(rs);
        DBUtils.close(ps);
    }
    return result;
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static void assertConnectorMessageExists(ConnectorMessage connectorMessage, boolean deepSearch,
        Connection connection) throws SQLException {
    long localChannelId = ChannelController.getInstance().getLocalChannelId(connectorMessage.getChannelId());
    PreparedStatement statement = null;
    ResultSet result = null;/*from  ww w.  j  a v  a 2  s .co m*/

    try {
        statement = connection
                .prepareStatement("SELECT * FROM d_mm" + localChannelId + " WHERE message_id = ? AND id = ?");
        statement.setLong(1, connectorMessage.getMessageId());
        statement.setLong(2, connectorMessage.getMetaDataId());
        result = statement.executeQuery();

        if (!result.next()) {
            throw new AssertionError();
        }

        Calendar receivedDate = Calendar.getInstance();
        receivedDate.setTimeInMillis(result.getTimestamp("received_date").getTime());
        Status status = Status.fromChar(result.getString("status").charAt(0));

        assertDatesEqual(receivedDate, connectorMessage.getReceivedDate());
        assertTrue(testEquality(status, connectorMessage.getStatus()));
    } finally {
        close(result);
        close(statement);
    }

    if (deepSearch) {
        for (ContentType contentType : ContentType.getMessageTypes()) {
            // Even though raw content exists on the destination connector message, it won't be stored in the database
            if (contentType != ContentType.RAW || connectorMessage.getMetaDataId() == 0) {
                MessageContent messageContent = connectorMessage.getMessageContent(contentType);

                if (messageContent != null) {
                    assertMessageContentExists(connection, messageContent);
                }
            }
        }
    }
}

From source file:net.mindengine.oculus.frontend.service.runs.JdbcTestRunDAO.java

@Override
public Long createSuiteRun(SuiteRun suite) throws Exception {
    PreparedStatement ps = getConnection().prepareStatement(
            "insert into suite_runs (start_time, end_time, name, runner_id, parameters, agent_name) "
                    + "values (?,?,?,?,?,?)");

    ps.setTimestamp(1, new Timestamp(suite.getStartTime().getTime()));
    ps.setTimestamp(2, new Timestamp(suite.getEndTime().getTime()));
    ps.setString(3, suite.getName());/*  w  w  w  . j  a v a2  s . c o m*/
    if (suite.getRunnerId() == null)
        suite.setRunnerId(0L);
    ps.setLong(4, suite.getRunnerId());
    ps.setString(5, suite.getParameters());
    String agentName = suite.getAgentName();
    if (agentName == null) {
        agentName = "";
    }
    ps.setString(6, agentName);

    logger.info(ps);
    ps.execute();

    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
        return rs.getLong(1);
    }
    return null;
}