Example usage for java.sql ResultSet getTimestamp

List of usage examples for java.sql ResultSet getTimestamp

Introduction

In this page you can find the example usage for java.sql ResultSet getTimestamp.

Prototype

java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Timestamp object in the Java programming language.

Usage

From source file:eionet.meta.dao.mysql.SchemaDAOImpl.java

/**
 * @see eionet.meta.dao.ISchemaDAO#getRootLevelSchemas(String)
 *//*  w w w .j  a  va 2s .  c o  m*/
@Override
public List<Schema> getRootLevelSchemas(String userName) {

    // Get the ID of 'Name' attribute beforehand.
    int nameAttrId = getNameAttributeId();

    // Now build the main sql, joining to ATTRIBUTE table via above-found ID of 'Name'.

    String sql = "select * ";
    if (nameAttrId > 0) {
        sql += ",ATTRIBUTE.VALUE as NAME ";
    }

    Map<String, Object> params = new HashMap<String, Object>();
    sql += "from T_SCHEMA ";

    if (nameAttrId > 0) {
        sql += "left outer join ATTRIBUTE on ";
        sql += "(T_SCHEMA.SCHEMA_ID=ATTRIBUTE.DATAELEM_ID and ATTRIBUTE.PARENT_TYPE=:attrParentType ";
        sql += "and ATTRIBUTE.M_ATTRIBUTE_ID=:nameAttrId) ";

        params.put("attrParentType", DElemAttribute.ParentType.SCHEMA.toString());
        params.put("nameAttrId", nameAttrId);
    }

    sql += "where (SCHEMA_SET_ID is null or SCHEMA_SET_ID<=0) ";

    if (StringUtils.isBlank(userName)) {
        sql += "and WORKING_COPY=false ";
        // sql += "and (WORKING_COPY=false and REG_STATUS=:regStatus) ";
        // params.put("regStatus", SchemaSet.RegStatus.RELEASED.toString());
    } else {
        sql += "and (WORKING_COPY=false or WORKING_USER=:workingUser) ";
        params.put("workingUser", userName);
    }

    sql += "order by ifnull(NAME,FILENAME), SCHEMA_ID";

    List<Schema> schema = getNamedParameterJdbcTemplate().query(sql, params, new RowMapper<Schema>() {
        @Override
        public Schema mapRow(ResultSet rs, int rowNum) throws SQLException {
            Schema schema = new Schema();
            schema.setId(rs.getInt("SCHEMA_ID"));
            schema.setFileName(rs.getString("FILENAME"));
            schema.setContinuityId(rs.getString("CONTINUITY_ID"));
            schema.setRegStatus(RegStatus.fromString(rs.getString("REG_STATUS")));
            schema.setWorkingCopy(rs.getBoolean("WORKING_COPY"));
            schema.setWorkingUser(rs.getString("WORKING_USER"));
            schema.setDateModified(rs.getTimestamp("DATE_MODIFIED"));
            schema.setUserModified(rs.getString("USER_MODIFIED"));
            schema.setComment(rs.getString("COMMENT"));
            schema.setCheckedOutCopyId(rs.getInt("CHECKEDOUT_COPY_ID"));
            schema.setOtherDocument(rs.getBoolean("OTHER_DOCUMENT"));

            String name = rs.getString("NAME");
            if (StringUtils.isNotBlank(name)) {
                schema.setAttributeValues(Collections.singletonMap("Name", Collections.singletonList(name)));
            }

            return schema;
        }
    });

    return schema;
}

From source file:com.flexive.core.storage.genericSQL.GenericEnvironmentLoader.java

/**
 * {@inheritDoc}/*from   w  w w. j a  va2s .  c  o m*/
 * @since 3.1.2
 */
@Override
public List<FxScriptSchedule> loadScriptSchedules(Connection con, FxEnvironmentImpl environment)
        throws FxLoadException {
    PreparedStatement ps = null;
    String sql;
    List<FxScriptSchedule> schedules = new ArrayList<FxScriptSchedule>(10);
    try {
        //             1   2     3      4       5         6         7             8            9
        sql = "SELECT ID,SCRIPT,SNAME,ACTIVE,STARTTIME,ENDTIME,REPEATINTERVAL,REPEATTIMES,CRONSTRING FROM "
                + TBL_SCRIPT_SCHEDULES + " ORDER BY SCRIPT";
        ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs != null && rs.next()) {
            long id = rs.getLong(1);
            long scriptId = rs.getLong(2);
            String name = rs.getString(3);
            if (rs.wasNull())
                name = "";
            boolean active = rs.getBoolean(4);
            java.util.Date startTime = new java.util.Date(rs.getTimestamp(5).getTime());
            Timestamp endts = rs.getTimestamp(6);
            final java.util.Date endTime;
            if (rs.wasNull())
                endTime = null;
            else
                endTime = new java.util.Date(endts.getTime());
            long repeatInterval = rs.getLong(7);
            int repeatTimes = rs.getInt(8);
            String cronString = rs.getString(9);
            if (rs.wasNull())
                cronString = "";
            schedules.add(new FxScriptSchedule(id, scriptId, name, active, startTime, endTime, repeatInterval,
                    repeatTimes, cronString));
        }
    } catch (SQLException exc) {
        throw new FxLoadException(LOG, exc, "ex.scripting.schedule.load.failed", -1, exc.getMessage());
    } finally {
        Database.closeObjects(GenericEnvironmentLoader.class, null, ps);
    }
    return schedules;
}

From source file:com.alfaariss.oa.engine.requestor.jdbc.JDBCRequestor.java

/**
 * Creates a Requestor object.//w  ww  . j a  va2s.c o  m
 * <br>
 * @param rsRequestor containing the requestor information 
 * @return Requestor object
 * @throws RequestorException if creation fails
 */
private Requestor getRequestor(ResultSet rsRequestor, ResultSet rsProperties) throws RequestorException {
    Requestor oRequestor = null;
    try {
        String sID = rsRequestor.getString(COLUMN_ID);

        String sFriendlyName = rsRequestor.getString(COLUMN_FRIENDLYNAME);
        if (sFriendlyName == null) {
            StringBuffer sbWarn = new StringBuffer("No '");
            sbWarn.append(COLUMN_FRIENDLYNAME);
            sbWarn.append("' available for requestor with id: ");
            sbWarn.append(sID);
            _logger.error(sbWarn.toString());
            throw new RequestorException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        boolean bEnabled = rsRequestor.getBoolean(COLUMN_ENABLED);
        Properties prop = new Properties();

        while (rsProperties.next()) {
            String sName = rsProperties.getString(JDBCRequestor.COLUMN_PROPERTY_NAME);
            Object value = rsProperties.getString(JDBCRequestor.COLUMN_PROPERTY_VALUE);
            prop.put(sName, value);
        }
        _logger.debug("Retrieved properties: " + prop);

        Date dLastModified = null;
        try {
            dLastModified = rsRequestor.getTimestamp(JDBCRequestor.COLUMN_DATELASTMODIFIED);
        } catch (Exception e) {
            _logger.info("No " + JDBCRequestor.COLUMN_DATELASTMODIFIED + " column found for requestor '" + sID
                    + "'; ignoring.");
        }

        oRequestor = new Requestor(sID, sFriendlyName, bEnabled, prop, dLastModified);
    } catch (RequestorException e) {
        throw e;
    } catch (SQLException e) {
        _logger.error("Can not read from database", e);
        throw new RequestorException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } catch (Exception e) {
        _logger.fatal("Internal error during create of a requestor", e);
        throw new RequestorException(SystemErrors.ERROR_INTERNAL);
    }

    return oRequestor;
}

From source file:eionet.meta.dao.mysql.SchemaDAOImpl.java

/**
 * @see eionet.meta.dao.ISchemaDAO#getSchemaVersions(String, java.lang.String, int...)
 *///from  w  w w  . jav  a 2  s .c  om
@Override
public List<Schema> getSchemaVersions(String userName, String continuityId, int... excludeIds) {

    if (StringUtils.isBlank(continuityId)) {
        throw new IllegalArgumentException("Continuity id must not be blank!");
    }

    String sql = "select * from T_SCHEMA where (SCHEMA_SET_ID is null or SCHEMA_SET_ID<=0) and WORKING_COPY=false"
            + " and CONTINUITY_ID=:continuityId";
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("continuityId", continuityId);

    if (StringUtils.isBlank(userName)) {
        sql += " and REG_STATUS=:regStatus";
        params.put("regStatus", RegStatus.RELEASED.toString());
    }

    if (excludeIds != null && excludeIds.length > 0) {
        sql += " and SCHEMA_ID not in (:excludeIds)";
        params.put("excludeIds", Arrays.asList(ArrayUtils.toObject(excludeIds)));
    }
    sql += " order by SCHEMA_ID desc";

    List<Schema> resultList = getNamedParameterJdbcTemplate().query(sql, params, new RowMapper<Schema>() {
        @Override
        public Schema mapRow(ResultSet rs, int rowNum) throws SQLException {
            Schema ss = new Schema();
            ss.setId(rs.getInt("SCHEMA_ID"));
            ss.setSchemaSetId(rs.getInt("SCHEMA_SET_ID"));
            ss.setFileName(rs.getString("FILENAME"));
            ss.setContinuityId(rs.getString("CONTINUITY_ID"));
            ss.setRegStatus(RegStatus.fromString(rs.getString("REG_STATUS")));
            ss.setWorkingCopy(rs.getBoolean("WORKING_COPY"));
            ss.setWorkingUser(rs.getString("WORKING_USER"));
            ss.setDateModified(rs.getTimestamp("DATE_MODIFIED"));
            ss.setUserModified(rs.getString("USER_MODIFIED"));
            ss.setComment(rs.getString("COMMENT"));
            ss.setCheckedOutCopyId(rs.getInt("CHECKEDOUT_COPY_ID"));
            ss.setOtherDocument(rs.getBoolean("OTHER_DOCUMENT"));
            return ss;
        }
    });

    return resultList;
}

From source file:edu.jhu.pha.vospace.meta.MySQLMetaStore2.java

@Override
public NodesList getNodeChildren(final VospaceId identifier, final boolean searchDeep /*always false*/,
        final boolean includeDeleted /*not used*/, final int start, final int count) {
    if (identifier.getNodePath().isRoot(false)) {
        String deletedCondition = includeDeleted ? "" : "nodes.`deleted` = 0 AND ";
        return DbPoolServlet.goSql("GetNodeChildren root request",
                "SELECT SQL_CALC_FOUND_ROWS containers.container_name as container, nodes.rev, nodes.deleted, nodes.mtime, nodes.size, nodes.mimetype, nodes.type "
                        + "FROM nodes JOIN containers ON nodes.container_id = containers.container_id JOIN user_identities ON containers.user_id = user_identities.user_id "
                        + "WHERE " + deletedCondition
                        + "`parent_node_id` is NULL AND `identity` = ? AND `container_name` <> '' order by container "
                        + ((count > 0) ? " limit ?, ?" : ""),
                new SqlWorker<NodesList>() {
                    @Override//from  w  w  w .  j a v  a  2s.  c  o  m
                    public NodesList go(Connection conn, PreparedStatement stmt) throws SQLException {
                        ArrayList<Node> result = new ArrayList<Node>();
                        int countRows = 0;

                        stmt.setString(1, owner);

                        if (count > 0) {
                            stmt.setInt(2, start);
                            stmt.setInt(3, count);
                        }

                        ResultSet rs = stmt.executeQuery();
                        while (rs.next()) {
                            try {
                                VospaceId id = new VospaceId(new NodePath(rs.getString("container")));
                                id.getNodePath()
                                        .setEnableAppContainer(identifier.getNodePath().isEnableAppContainer());

                                NodeInfo info = new NodeInfo();
                                info.setRevision(rs.getInt("rev"));
                                info.setDeleted(rs.getBoolean("deleted"));
                                info.setMtime(new Date(rs.getTimestamp("mtime").getTime()));
                                info.setSize(rs.getLong("size"));
                                info.setContentType(rs.getString("mimetype"));

                                Node newNode = NodeFactory.createNode(id, owner,
                                        NodeType.valueOf(rs.getString("type")));
                                newNode.setNodeInfo(info);

                                result.add(newNode);
                            } catch (URISyntaxException e) {
                                logger.error("Error in child URI: " + e.getMessage());
                            }
                        }

                        ResultSet resSet = conn.createStatement().executeQuery("SELECT FOUND_ROWS();");
                        resSet.next();
                        countRows = resSet.getInt(1);

                        return new NodesList(result, countRows);
                    }
                });
    } else {
        String deletedCondition = includeDeleted ? "" : "nodes.`deleted` = 0 AND ";
        String request = "SELECT SQL_CALC_FOUND_ROWS containers.container_name as container, nodes.path, nodes.rev, nodes.deleted, nodes.mtime, nodes.size, nodes.mimetype, nodes.type "
                + "FROM nodes JOIN containers ON nodes.container_id = containers.container_id "
                + "JOIN user_identities ON containers.user_id = user_identities.user_id "
                + "JOIN nodes b ON nodes.parent_node_id = b.node_id " + "WHERE " + deletedCondition
                + "containers.container_name = ? AND b.`path` = ? AND `identity` = ? order by path "
                + ((count > 0) ? " limit ?, ?" : "");

        return DbPoolServlet.goSql("GetNodeChildren request", request, new SqlWorker<NodesList>() {
            @Override
            public NodesList go(Connection conn, PreparedStatement stmt) throws SQLException {
                ArrayList<Node> result = new ArrayList<Node>();
                int countRows = 0;

                stmt.setString(1, identifier.getNodePath().getContainerName());
                stmt.setString(2, identifier.getNodePath().getNodeRelativeStoragePath());
                stmt.setString(3, owner);

                if (count > 0) {
                    stmt.setInt(4, start);
                    stmt.setInt(5, count);
                }

                ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    try {
                        VospaceId id = new VospaceId(
                                new NodePath(rs.getString("container") + "/" + rs.getString("path")));
                        id.getNodePath().setEnableAppContainer(identifier.getNodePath().isEnableAppContainer());

                        NodeInfo info = new NodeInfo();
                        info.setRevision(rs.getInt("rev"));
                        info.setDeleted(rs.getBoolean("deleted"));
                        info.setMtime(new Date(rs.getTimestamp("mtime").getTime()));
                        info.setSize(rs.getLong("size"));
                        info.setContentType(rs.getString("mimetype"));

                        Node newNode = NodeFactory.createNode(id, owner,
                                NodeType.valueOf(rs.getString("type")));
                        newNode.setNodeInfo(info);

                        result.add(newNode);
                    } catch (URISyntaxException e) {
                        logger.error("Error in child URI: " + e.getMessage());
                    }
                }

                ResultSet resSet = conn.createStatement().executeQuery("SELECT FOUND_ROWS();");
                resSet.next();
                countRows = resSet.getInt(1);

                return new NodesList(result, countRows);
            }
        });
    }
}

From source file:eionet.meta.dao.mysql.SchemaDAOImpl.java

/**
 * @see eionet.meta.dao.ISchemaDAO#getWorkingCopyOfSchema(int)
 *//*from  www  .  j  a v  a2s . c om*/
@Override
public Schema getWorkingCopyOfSchema(int schemaId) {

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("checkedOutCopyId", schemaId);

    Schema result = getNamedParameterJdbcTemplate().queryForObject(GET_WORKING_COPY_OF_SQL, parameters,
            new RowMapper<Schema>() {
                @Override
                public Schema mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Schema schema = new Schema();
                    schema.setId(rs.getInt("SCHEMA_ID"));
                    schema.setFileName(rs.getString("FILENAME"));
                    schema.setContinuityId(rs.getString("CONTINUITY_ID"));
                    schema.setRegStatus(RegStatus.fromString(rs.getString("REG_STATUS")));
                    schema.setWorkingCopy(rs.getBoolean("WORKING_COPY"));
                    schema.setWorkingUser(rs.getString("WORKING_USER"));
                    schema.setDateModified(rs.getTimestamp("DATE_MODIFIED"));
                    schema.setUserModified(rs.getString("USER_MODIFIED"));
                    schema.setComment(rs.getString("COMMENT"));
                    schema.setCheckedOutCopyId(rs.getInt("CHECKEDOUT_COPY_ID"));
                    schema.setOtherDocument(rs.getBoolean("OTHER_DOCUMENT"));
                    return schema;
                }
            });
    return result;
}

From source file:eionet.meta.dao.mysql.SchemaDAOImpl.java

/**
 * @see eionet.meta.dao.ISchemaDAO#getWorkingCopiesOf(java.lang.String)
 *//*from w  w  w.  j  av  a  2 s .  co  m*/
@Override
public List<Schema> getWorkingCopiesOf(String userName) {

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("userName", userName);

    List<Schema> resultList = getNamedParameterJdbcTemplate().query(GET_WORKING_COPIES_SQL, parameters,
            new RowMapper<Schema>() {
                @Override
                public Schema mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Schema schema = new Schema();
                    schema.setId(rs.getInt("SCHEMA_ID"));
                    schema.setFileName(rs.getString("FILENAME"));
                    schema.setContinuityId(rs.getString("CONTINUITY_ID"));
                    schema.setRegStatus(RegStatus.fromString(rs.getString("REG_STATUS")));
                    schema.setWorkingCopy(rs.getBoolean("WORKING_COPY"));
                    schema.setWorkingUser(rs.getString("WORKING_USER"));
                    schema.setDateModified(rs.getTimestamp("DATE_MODIFIED"));
                    schema.setUserModified(rs.getString("USER_MODIFIED"));
                    schema.setComment(rs.getString("COMMENT"));
                    schema.setCheckedOutCopyId(rs.getInt("CHECKEDOUT_COPY_ID"));
                    schema.setOtherDocument(rs.getBoolean("OTHER_DOCUMENT"));
                    return schema;
                }
            });

    return resultList;
}

From source file:architecture.ee.web.community.page.dao.jdbc.JdbcPageDao.java

private Page load(long pageId, int versionNumber) {
    if (pageId <= 0)
        return null;

    final Page page = new DefaultPage();
    page.setPageId(pageId);//w ww . j  a v a2 s  . co  m
    page.setVersionId(versionNumber);
    getExtendedJdbcTemplate().query(
            getBoundSql("ARCHITECTURE_COMMUNITY.SELECT_PAGE_BY_ID_AND_VERSION").getSql(),
            new RowMapper<Page>() {
                public Page mapRow(ResultSet rs, int rowNum) throws SQLException {
                    page.setName(rs.getString("NAME"));
                    page.setObjectType(rs.getInt("OBJECT_TYPE"));
                    page.setObjectId(rs.getLong("OBJECT_ID"));
                    page.setPageState(PageState.valueOf(rs.getString("STATE").toUpperCase()));
                    page.setUser(new UserTemplate(rs.getLong("USER_ID")));
                    if (rs.wasNull())
                        page.setUser(new UserTemplate(-1L));
                    page.setTitle(rs.getString("TITLE"));
                    page.setSummary(rs.getString("SUMMARY"));
                    page.setCreationDate(rs.getTimestamp("CREATION_DATE"));
                    page.setModifiedDate(rs.getTimestamp("MODIFIED_DATE"));
                    return page;
                }
            }, new SqlParameterValue(Types.NUMERIC, page.getPageId()),
            new SqlParameterValue(Types.NUMERIC, page.getVersionId()));

    if (page.getName() == null)
        return null;

    try {
        BodyContent bodyContent = getExtendedJdbcTemplate().queryForObject(
                getBoundSql("ARCHITECTURE_COMMUNITY.SELECT_PAGE_BODY").getSql(), bodyContentMapper,
                new SqlParameterValue(Types.NUMERIC, page.getPageId()),
                new SqlParameterValue(Types.NUMERIC, page.getVersionId()));
        page.setBodyContent(bodyContent);
    } catch (EmptyResultDataAccessException e) {
    }

    if (page.getBodyText() == null) {
        long bodyId = -1L;
        try {
            bodyId = getExtendedJdbcTemplate().queryForObject(
                    getBoundSql("ARCHITECTURE_COMMUNITY.DELETE_PAGE_BODY_VERSION").getSql(), Long.class,
                    new SqlParameterValue(Types.NUMERIC, page.getPageId()),
                    new SqlParameterValue(Types.NUMERIC, page.getVersionId()));
        } catch (EmptyResultDataAccessException e) {
        }
    }

    Map<String, String> properties = loadProperties(page);
    page.getProperties().putAll(properties);

    return page;
}

From source file:com.flexive.core.security.FxDBAuthentication.java

/**
 * Login a user using flexive's database
 *
 * @param loginname name of the user/* w  w w .  ja  va 2s.com*/
 * @param password plaintext password
 * @param callback callback providing datasource, ejb context and "take over"
 * @return Authenticated UserTicket
 * @throws FxAccountInUseException   on errors
 * @throws FxLoginFailedException    on errors
 * @throws FxAccountExpiredException on errors
 */
public static UserTicket login(String loginname, String password, FxCallback callback)
        throws FxAccountInUseException, FxLoginFailedException, FxAccountExpiredException {
    final long SYS_UP = CacheAdmin.getInstance().getSystemStartTime();
    FxContext inf = FxContext.get();

    // Avoid null pointer exceptions
    if (password == null)
        password = "";
    if (loginname == null)
        loginname = "";

    final String applicationId = StringUtils.defaultString(inf.getApplicationId());
    if (StringUtils.isBlank(applicationId)) {
        LOG.warn("Login: application ID is not set");
    }

    String curSql;
    PreparedStatement ps = null;
    Connection con = null;
    try {
        // Obtain a database connection
        con = callback.getDataSource().getConnection();
        //               1-6 7      8           9              10                 11           12       13      14         15       16
        curSql = "SELECT d.*,a.ID,a.IS_ACTIVE,a.IS_VALIDATED,a.ALLOW_MULTILOGIN,a.VALID_FROM,a.VALID_TO,NOW(),a.PASSWORD,a.MANDATOR,a.LOGIN_NAME "
                + "FROM " + TBL_ACCOUNTS + " a " + "LEFT JOIN "
                + " (SELECT ID,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC FROM "
                + TBL_ACCOUNT_DETAILS
                + " WHERE APPLICATION=? ORDER BY LAST_LOGIN DESC) d ON a.ID=d.ID WHERE UPPER(a.LOGIN_NAME)=UPPER(?)";
        ps = con.prepareStatement(curSql);
        ps.setString(1, applicationId);
        ps.setString(2, loginname);
        final ResultSet rs = ps.executeQuery();

        // Anything found?
        if (rs == null || !rs.next())
            throw new FxLoginFailedException("Login failed (invalid user or password)",
                    FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED);

        // check if the hashed password matches the hash stored in the database
        final long id = rs.getLong(7);
        final String dbLoginName = rs.getString(16); // use DB login name for non-lowercase login names
        final String dbPassword = rs.getString(14);
        boolean passwordMatches = FxSharedUtils.hashPassword(id, dbLoginName, password).equals(dbPassword);
        if (!passwordMatches && "supervisor".equalsIgnoreCase(loginname)) {
            // before 3.2.0 the default supervisor password was incorrectly hashed against the lower-cased login name
            passwordMatches = FxSharedUtils.hashPassword(id, "supervisor", password).equals(dbPassword);
        }
        if (!passwordMatches && !callback.isCalledAsGlobalSupervisor()) {
            increaseFailedLoginAttempts(con, id);
            throw new FxLoginFailedException("Login failed (invalid user or password)",
                    FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED);
        }

        // Read data
        final boolean loggedIn = rs.getBoolean(2);
        final Date lastLogin = new Date(rs.getLong(3));
        final String lastLoginFrom = rs.getString(4);
        final long failedAttempts = rs.getLong(5);
        final boolean active = rs.getBoolean(8);
        final boolean validated = rs.getBoolean(9);
        final boolean allowMultiLogin = rs.getBoolean(10);
        final Date validFrom = new Date(rs.getLong(11));
        final Date validTo = new Date(rs.getLong(12));
        final Date dbNow = rs.getTimestamp(13);
        final long mandator = rs.getLong(15);

        // Account active?
        if (!active || !validated || (CacheAdmin.isEnvironmentLoaded()
                && !CacheAdmin.getEnvironment().getMandator(mandator).isActive())) {
            if (LOG.isDebugEnabled())
                LOG.debug("Login for user [" + loginname + "] failed, account is inactive. Active=" + active
                        + ", Validated=" + validated + ", Mandator active: "
                        + CacheAdmin.getEnvironment().getMandator(mandator).isActive());
            increaseFailedLoginAttempts(con, id);
            throw new FxLoginFailedException("Login failed, account is inactive.",
                    FxLoginFailedException.TYPE_INACTIVE_ACCOUNT);
        }

        // Account date from-to valid?
        //Compute the day AFTER the dValidTo
        Calendar endDate = Calendar.getInstance();
        endDate.setTime(validTo);
        endDate.add(Calendar.DAY_OF_MONTH, 1);
        if (validFrom.getTime() > dbNow.getTime() || endDate.getTimeInMillis() < dbNow.getTime()) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            if (LOG.isDebugEnabled())
                LOG.debug("Login for user [" + loginname + "] failed, from/to date not valid. from='"
                        + sdf.format(validFrom) + "' to='" + validTo + "'");
            increaseFailedLoginAttempts(con, id);
            throw new FxAccountExpiredException(loginname, dbNow);
        }

        // Check 'Account in use and takeOver false'
        if (!allowMultiLogin && !callback.getTakeOverSession() && loggedIn && lastLogin != null) {
            // Only if the last login time was AFTER the system started
            if (lastLogin.getTime() >= SYS_UP) {
                FxAccountInUseException aiu = new FxAccountInUseException(loginname, lastLoginFrom, lastLogin);
                if (LOG.isInfoEnabled())
                    LOG.info(aiu);
                // don't log this as an invalid login attempt - this happens routinely when a session times
                // out and the cached session data has not been evicted by the maintenance task yet

                //increaseFailedLoginAttempts(con, id);
                throw aiu;
            }
        }

        // Clear any old data
        curSql = "DELETE FROM " + TBL_ACCOUNT_DETAILS + " WHERE ID=? AND APPLICATION=?";
        ps.close();
        ps = con.prepareStatement(curSql);
        ps.setLong(1, id);
        ps.setString(2, applicationId);
        ps.executeUpdate();

        // Mark user as active in the database
        // This can lead to duplicate rows for a user/application for concurrent logins (e.g. WebDAV clients),
        // but we prefer this to actually locking the complete table before updates. (FX-868)
        curSql = "INSERT INTO " + TBL_ACCOUNT_DETAILS
                + " (ID,APPLICATION,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC) "
                + "VALUES (?,?,?,?,?,?,?)";
        ps.close();
        ps = con.prepareStatement(curSql);
        ps.setLong(1, id);
        ps.setString(2, applicationId);
        ps.setBoolean(3, true);
        ps.setLong(4, System.currentTimeMillis());
        ps.setString(5, inf.getRemoteHost());
        ps.setLong(6, 0); //reset failed attempts
        ps.setString(7, AuthenticationSource.Database.name());
        ps.executeUpdate();

        // Load the user and construct a user ticket
        try {
            final UserTicketImpl ticket = (UserTicketImpl) UserTicketStore.getUserTicket(loginname);
            ticket.setFailedLoginAttempts(failedAttempts);
            ticket.setAuthenticationSource(AuthenticationSource.Database);
            return ticket;
        } catch (FxApplicationException e) {
            if (callback.getSessionContext() != null)
                callback.getSessionContext().setRollbackOnly();
            throw new FxLoginFailedException(
                    e.getExceptionMessage().getLocalizedMessage(
                            CacheAdmin.getEnvironment().getLanguage(FxLanguage.DEFAULT_ID)),
                    FxLoginFailedException.TYPE_UNKNOWN_ERROR);
        }
    } catch (SQLException exc) {
        if (callback.getSessionContext() != null)
            callback.getSessionContext().setRollbackOnly();
        throw new FxLoginFailedException("Database error: " + exc.getMessage(),
                FxLoginFailedException.TYPE_SQL_ERROR);
    } finally {
        Database.closeObjects(FxDBAuthentication.class, con, ps);
    }
}

From source file:eionet.meta.dao.mysql.SchemaDAOImpl.java

@Override
public List<Schema> getSchemas(List<Integer> ids) {

    int nameAttrId = getNameAttributeId();

    String sql = "select s.*, ss.IDENTIFIER, ss.REG_STATUS SS_REG_STATUS,"
            + "(select VALUE from ATTRIBUTE where M_ATTRIBUTE_ID = :nameAttrId and DATAELEM_ID = s.SCHEMA_ID "
            + "and PARENT_TYPE = :parentType limit 1 ) as SCHEMA_NAME_ATTR "
            + " from T_SCHEMA as s LEFT OUTER JOIN T_SCHEMA_SET as ss ON (s.schema_set_id = ss.schema_set_id) "
            + "where SCHEMA_ID in (:ids)";

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("ids", ids);
    params.put("parentType", DElemAttribute.ParentType.SCHEMA.toString());
    params.put("nameAttrId", nameAttrId);

    List<Schema> resultList = getNamedParameterJdbcTemplate().query(sql, params, new RowMapper<Schema>() {
        @Override/*from  w  w w. ja  v a  2  s . com*/
        public Schema mapRow(ResultSet rs, int rowNum) throws SQLException {
            Schema schema = new Schema();
            schema.setId(rs.getInt("SCHEMA_ID"));
            schema.setFileName(rs.getString("FILENAME"));
            schema.setSchemaSetId(rs.getInt("SCHEMA_SET_ID"));
            schema.setContinuityId(rs.getString("CONTINUITY_ID"));
            schema.setRegStatus(RegStatus.fromString(rs.getString("s.REG_STATUS")));
            schema.setWorkingCopy(rs.getBoolean("WORKING_COPY"));
            schema.setWorkingUser(rs.getString("WORKING_USER"));
            schema.setDateModified(rs.getTimestamp("DATE_MODIFIED"));
            schema.setUserModified(rs.getString("USER_MODIFIED"));
            schema.setComment(rs.getString("COMMENT"));
            schema.setCheckedOutCopyId(rs.getInt("CHECKEDOUT_COPY_ID"));
            schema.setSchemaSetIdentifier(rs.getString("IDENTIFIER"));
            schema.setSchemaSetRegStatus(RegStatus.fromString(rs.getString("SS_REG_STATUS")));
            schema.setNameAttribute(rs.getString("SCHEMA_NAME_ATTR"));
            schema.setOtherDocument(rs.getBoolean("OTHER_DOCUMENT"));
            return schema;
        }
    });

    return resultList;
}