Search in sources :

Example 51 with EmptyResultDataAccessException

use of org.springframework.dao.EmptyResultDataAccessException in project perun by CESNET.

the class RegistrarManagerImpl method approveApplicationInternal.

/**
	 * Process application approval in 1 transaction
	 * !! WITHOUT members validation !!
	 *
	 * @param sess session for authz
	 * @param appId application ID to approve
	 * @return updated application
	 * @throws PerunException
	 */
@Transactional(rollbackFor = Exception.class)
public Application approveApplicationInternal(PerunSession sess, int appId) throws PerunException {
    Application app = getApplicationById(appId);
    Member member = null;
    // authz
    if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, app.getVo())) {
        if (app.getGroup() != null) {
            if (!AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, app.getGroup())) {
                throw new PrivilegeException(sess, "approveApplication");
            }
        } else {
            throw new PrivilegeException(sess, "approveApplication");
        }
    }
    // only VERIFIED applications can be approved
    if (!AppState.VERIFIED.equals(app.getState())) {
        if (AppState.APPROVED.equals(app.getState()))
            throw new RegistrarException("Application is already approved. Try to refresh the view to see changes.");
        if (AppState.REJECTED.equals(app.getState()))
            throw new RegistrarException("Rejected application cant' be approved. Try to refresh the view to see changes.");
        throw new RegistrarException("User didn't verify his email address yet. Please wait until application will be in a 'Submitted' state. You can send mail verification notification to user again if you wish.");
    }
    // get registrar module
    RegistrarModule module;
    if (app.getGroup() != null) {
        module = getRegistrarModule(getFormForGroup(app.getGroup()));
    } else {
        module = getRegistrarModule(getFormForVo(app.getVo()));
    }
    if (module != null) {
        // call custom logic before approving
        module.beforeApprove(sess, app);
    }
    // mark as APPROVED
    int result = jdbc.update("update application set state=?, modified_by=?, modified_at=? where id=?", AppState.APPROVED.toString(), sess.getPerunPrincipal().getActor(), new Date(), appId);
    if (result == 0) {
        throw new RegistrarException("Application with ID=" + appId + " not found.");
    } else if (result > 1) {
        throw new ConsistencyErrorException("More than one application is stored under ID=" + appId + ".");
    }
    // set back as approved
    app.setState(AppState.APPROVED);
    log.info("Application {} marked as APPROVED", appId);
    // Try to get reservedLogin and reservedNamespace before deletion, it will be used for creating userExtSources
    List<Pair<String, String>> logins;
    try {
        logins = jdbc.query("select namespace,login from application_reserved_logins where app_id=?", new RowMapper<Pair<String, String>>() {

            @Override
            public Pair<String, String> mapRow(ResultSet rs, int arg1) throws SQLException {
                return new Pair<String, String>(rs.getString("namespace"), rs.getString("login"));
            }
        }, appId);
    } catch (EmptyResultDataAccessException e) {
        // set empty logins
        logins = new ArrayList<Pair<String, String>>();
    }
    // FOR INITIAL APPLICATION
    if (AppType.INITIAL.equals(app.getType())) {
        if (app.getGroup() != null) {
            // free reserved logins so they can be set as attributes
            jdbc.update("delete from application_reserved_logins where app_id=?", appId);
            if (app.getUser() == null) {
                // application for group doesn't have user set, but it can exists in perun (joined identities after submission)
                User u = usersManager.getUserByExtSourceNameAndExtLogin(registrarSession, app.getExtSourceName(), app.getCreatedBy());
                // put user back to application
                app.setUser(u);
                // store user_id in DB
                int result2 = jdbc.update("update application set user_id=? where id=?", u.getId(), appId);
                if (result2 == 0) {
                    throw new RegistrarException("Application with ID=" + appId + " not found.");
                } else if (result2 > 1) {
                    throw new ConsistencyErrorException("More than one application is stored under ID=" + appId + ".");
                }
            }
            // add new member of VO as member of group (for group applications)
            // !! MUST BE MEMBER OF VO !!
            member = membersManager.getMemberByUser(registrarSession, app.getVo(), app.getUser());
            // meaning, user should submit membership extension application first !!
            if (!Arrays.asList(Status.VALID, Status.INVALID).contains(member.getStatus())) {
                throw new CantBeApprovedException("Application of member with membership status: " + member.getStatus() + " can't be approved. Please wait until member extends/re-validate own membership in a VO.");
            }
            // store all attributes (but not logins)
            storeApplicationAttributes(app);
            // cancel reservation of new duplicate logins and get purely new logins back
            logins = unreserveNewLoginsFromSameNamespace(logins, app.getUser());
            // store purely new logins to user
            storeApplicationLoginAttributes(app);
            for (Pair<String, String> pair : logins) {
                // LOGIN IN NAMESPACE IS PURELY NEW => VALIDATE ENTRY IN KDC
                // left = namespace, right = login
                perun.getUsersManagerBl().validatePasswordAndSetExtSources(registrarSession, app.getUser(), pair.getRight(), pair.getLeft());
            }
            // update titles before/after users name if part of application !! USER MUST EXISTS !!
            updateUserNameTitles(app);
            perun.getGroupsManager().addMember(registrarSession, app.getGroup(), member);
            log.debug("[REGISTRAR] Member {} added to Group {}.", member, app.getGroup());
        } else {
            // put application data into Candidate
            final Map<String, String> attributes = new HashMap<String, String>();
            jdbc.query("select dst_attr,value from application_data d, application_form_items i where d.item_id=i.id " + "and i.dst_attr is not null and d.value is not null and app_id=?", new RowMapper<Object>() {

                @Override
                public Object mapRow(ResultSet rs, int i) throws SQLException {
                    attributes.put(rs.getString("dst_attr"), rs.getString("value"));
                    return null;
                }
            }, appId);
            // DO NOT STORE LOGINS THROUGH CANDIDATE
            // we do not set logins by candidate object to prevent accidental overwrite while joining identities in process
            Iterator<Map.Entry<String, String>> iter = attributes.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, String> entry = iter.next();
                if (entry.getKey().contains("urn:perun:user:attribute-def:def:login-namespace:")) {
                    iter.remove();
                }
            }
            Candidate candidate = new Candidate();
            candidate.setAttributes(attributes);
            log.debug("[REGISTRAR] Retrieved candidate from DB {}", candidate);
            // first try to parse display_name if not null and not empty
            if (attributes.containsKey(URN_USER_DISPLAY_NAME) && attributes.get(URN_USER_DISPLAY_NAME) != null && !attributes.get(URN_USER_DISPLAY_NAME).isEmpty()) {
                // parse
                Map<String, String> commonName = Utils.parseCommonName(attributes.get(URN_USER_DISPLAY_NAME));
                if (commonName.get("titleBefore") != null && !commonName.get("titleBefore").isEmpty()) {
                    candidate.setTitleBefore(commonName.get("titleBefore"));
                }
                if (commonName.get("firstName") != null && !commonName.get("firstName").isEmpty()) {
                    candidate.setFirstName(commonName.get("firstName"));
                }
                // FIXME - ? there is no middleName in Utils.parseCommonName() implementation
                if (commonName.get("middleName") != null && !commonName.get("middleName").isEmpty()) {
                    candidate.setMiddleName(commonName.get("middleName"));
                }
                if (commonName.get("lastName") != null && !commonName.get("lastName").isEmpty()) {
                    candidate.setLastName(commonName.get("lastName"));
                }
                if (commonName.get("titleAfter") != null && !commonName.get("titleAfter").isEmpty()) {
                    candidate.setTitleAfter(commonName.get("titleAfter"));
                }
            }
            // if names are separated, used them after
            for (String attrName : attributes.keySet()) {
                // if value not null or empty - set to candidate
                if (attributes.get(attrName) != null && !attributes.get(attrName).isEmpty()) {
                    if (URN_USER_TITLE_BEFORE.equals(attrName)) {
                        candidate.setTitleBefore(attributes.get(attrName));
                    } else if (URN_USER_TITLE_AFTER.equals(attrName)) {
                        candidate.setTitleAfter(attributes.get(attrName));
                    } else if (URN_USER_FIRST_NAME.equals(attrName)) {
                        candidate.setFirstName(attributes.get(attrName));
                    } else if (URN_USER_LAST_NAME.equals(attrName)) {
                        candidate.setLastName(attributes.get(attrName));
                    } else if (URN_USER_MIDDLE_NAME.equals(attrName)) {
                        candidate.setMiddleName(attributes.get(attrName));
                    }
                }
            }
            // free reserved logins so they can be set as attributes
            jdbc.update("delete from application_reserved_logins where app_id=?", appId);
            // create member and user
            log.debug("[REGISTRAR] Trying to make member from candidate {}", candidate);
            member = membersManager.createMember(sess, app.getVo(), app.getExtSourceName(), app.getExtSourceType(), app.getExtSourceLoa(), app.getCreatedBy(), candidate);
            User u = usersManager.getUserById(registrarSession, member.getUserId());
            if (app.getUser() != null) {
                // if user was already known to perun, createMember() will set attributes
                // via setAttributes() method so core attributes are skipped
                // ==> updateNameTitles() in case of change in appForm.
                updateUserNameTitles(app);
            }
            // set NEW user id back to application
            app.setUser(u);
            result = jdbc.update("update application set user_id=? where id=?", member.getUserId(), appId);
            if (result == 0) {
                throw new RegistrarException("User ID hasn't been associated with the application " + appId + ", because the application was not found!");
            } else if (result > 1) {
                throw new ConsistencyErrorException("User ID hasn't been associated with the application " + appId + ", because more than one application exists under the same ID.");
            }
            log.info("Member " + member.getId() + " created for: " + app.getCreatedBy() + " / " + app.getExtSourceName());
            // unreserve new login if user already have login in same namespace
            // also get back purely new logins
            logins = unreserveNewLoginsFromSameNamespace(logins, u);
            // store purely new logins to user
            storeApplicationLoginAttributes(app);
            for (Pair<String, String> pair : logins) {
                // LOGIN IN NAMESPACE IS PURELY NEW => VALIDATE ENTRY IN KDC
                // left = namespace, right = login
                perun.getUsersManagerBl().validatePasswordAndSetExtSources(registrarSession, u, pair.getRight(), pair.getLeft());
            }
            // log
            perun.getAuditer().log(sess, "{} created for approved {}.", member, app);
        }
    // FOR EXTENSION APPLICATION
    } else if (AppType.EXTENSION.equals(app.getType())) {
        // free reserved logins so they can be set as attributes
        jdbc.update("delete from application_reserved_logins where app_id=?", app.getId());
        member = membersManager.getMemberByUser(registrarSession, app.getVo(), app.getUser());
        storeApplicationAttributes(app);
        // extend user's membership
        membersManager.extendMembership(registrarSession, member);
        // unreserve new logins, if user already have login in same namespace
        // also get back logins, which are purely new
        logins = unreserveNewLoginsFromSameNamespace(logins, app.getUser());
        // store purely new logins from application
        storeApplicationLoginAttributes(app);
        // validate purely new logins in KDC
        for (Pair<String, String> pair : logins) {
            // left = namespace, right = login
            perun.getUsersManagerBl().validatePasswordAndSetExtSources(registrarSession, app.getUser(), pair.getRight(), pair.getLeft());
        }
        // update titles before/after users name if part of application !! USER MUST EXISTS !!
        updateUserNameTitles(app);
        // log
        perun.getAuditer().log(sess, "Membership extended for {} in {} for approved {}.", member, app.getVo(), app);
    }
    if (module != null) {
        module.approveApplication(sess, app);
    }
    getMailManager().sendMessage(app, MailType.APP_APPROVED_USER, null, null);
    // return updated application
    return app;
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) SingleColumnRowMapper(org.springframework.jdbc.core.SingleColumnRowMapper) RowMapper(org.springframework.jdbc.core.RowMapper) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) RegistrarModule(cz.metacentrum.perun.registrar.RegistrarModule) Application(cz.metacentrum.perun.registrar.model.Application) Transactional(org.springframework.transaction.annotation.Transactional)

Example 52 with EmptyResultDataAccessException

use of org.springframework.dao.EmptyResultDataAccessException in project perun by CESNET.

the class TaskResultDaoTest method testClearOldTaskResult.

@Test
public void testClearOldTaskResult() throws InternalErrorException, PrivilegeException, ServiceExistsException, OwnerNotExistsException, FacilityExistsException, ServiceNotExistsException, FacilityNotExistsException, DestinationAlreadyAssignedException, WrongPatternException {
    System.out.println("TaskResultDao.clearOld");
    Owner testOwner = new Owner();
    testOwner.setContact("Call me");
    testOwner.setName("Tester-" + Long.toHexString(System.currentTimeMillis()));
    testOwner.setType(OwnerType.technical);
    testOwner = ownersManager.createOwner(perunSession, testOwner);
    Service testService = new Service();
    testService.setName("Test_service_1_" + Long.toHexString(System.currentTimeMillis()));
    testService = servicesManager.createService(perunSession, testService);
    Service testService2 = new Service();
    testService2.setName("Test_service_2_" + Long.toHexString(System.currentTimeMillis()));
    testService2 = servicesManager.createService(perunSession, testService2);
    Facility facility = new Facility();
    facility.setName("Facility 1-" + Long.toHexString(System.currentTimeMillis()));
    facility.setDescription("Description");
    facility = facilitiesManager.createFacility(perunSession, facility);
    Facility facility2 = new Facility();
    facility2.setName("Facility 2-" + Long.toHexString(System.currentTimeMillis()));
    facility2.setDescription("Description");
    facility2 = facilitiesManager.createFacility(perunSession, facility2);
    ExecService testExecService = new ExecService();
    testExecService.setDefaultDelay(1);
    testExecService.setDefaultRecurrence(1);
    testExecService.setEnabled(true);
    testExecService.setService(testService);
    testExecService.setScript("serviceGenerate.bash");
    testExecService.setExecServiceType(ExecService.ExecServiceType.GENERATE);
    testExecService.setId(execServiceDao.insertExecService(testExecService));
    ExecService testExecService2 = new ExecService();
    testExecService2.setDefaultDelay(1);
    testExecService2.setDefaultRecurrence(1);
    testExecService2.setEnabled(true);
    testExecService2.setService(testService2);
    testExecService2.setScript("serviceGenerate.bash");
    testExecService2.setExecServiceType(ExecService.ExecServiceType.GENERATE);
    testExecService2.setId(execServiceDao.insertExecService(testExecService2));
    Destination destination1 = new Destination();
    destination1.setDestination("Destination-1-" + Long.toHexString(System.currentTimeMillis()));
    destination1.setType(Destination.DESTINATIONEMAILTYPE);
    destination1 = servicesManager.addDestination(perunSession, testService, facility, destination1);
    Destination destination2 = new Destination();
    destination2.setDestination("Destination-2-" + Long.toHexString(System.currentTimeMillis()));
    destination2.setType(Destination.DESTINATIONEMAILTYPE);
    destination2 = servicesManager.addDestination(perunSession, testService, facility, destination2);
    Destination destination3 = new Destination();
    destination3.setDestination("Destination-3-" + Long.toHexString(System.currentTimeMillis()));
    destination3.setType(Destination.DESTINATIONEMAILTYPE);
    destination3 = servicesManager.addDestination(perunSession, testService2, facility2, destination3);
    Task testTask1 = new Task();
    testTask1.setDelay(10);
    testTask1.setExecService(testExecService);
    testTask1.setFacility(facility);
    testTask1.setRecurrence(10);
    testTask1.setSchedule(new Date());
    testTask1.setStatus(Task.TaskStatus.PROCESSING);
    testTask1.setId(taskDao.scheduleNewTask(testTask1, virtualEngineID));
    Task testTask2 = new Task();
    testTask2.setDelay(10);
    testTask2.setExecService(testExecService2);
    testTask2.setFacility(facility2);
    testTask2.setRecurrence(10);
    testTask2.setSchedule(new Date());
    testTask2.setStatus(Task.TaskStatus.PROCESSING);
    testTask2.setId(taskDao.scheduleNewTask(testTask2, virtualEngineID));
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -2);
    TaskResult taskResult = new TaskResult();
    taskResult.setDestinationId(destination1.getId());
    taskResult.setErrorMessage("error message");
    taskResult.setReturnCode(0);
    taskResult.setStandardMessage("std message");
    taskResult.setStatus(TaskResult.TaskResultStatus.DONE);
    taskResult.setTaskId(testTask1.getId());
    taskResult.setTimestamp(cal.getTime());
    taskResult.setService(testService);
    taskResult.setId(taskResultDao.insertNewTaskResult(taskResult, virtualEngineID));
    TaskResult taskResult2 = new TaskResult();
    taskResult2.setDestinationId(destination3.getId());
    taskResult2.setErrorMessage("error message");
    taskResult2.setReturnCode(0);
    taskResult2.setStandardMessage("std message");
    taskResult2.setStatus(TaskResult.TaskResultStatus.DONE);
    taskResult2.setTaskId(testTask2.getId());
    taskResult2.setTimestamp(cal.getTime());
    taskResult2.setService(testService2);
    taskResult2.setId(taskResultDao.insertNewTaskResult(taskResult2, virtualEngineID));
    cal.add(Calendar.DATE, -5);
    TaskResult oldTaskResult = new TaskResult();
    oldTaskResult.setDestinationId(destination1.getId());
    oldTaskResult.setErrorMessage("error message");
    oldTaskResult.setReturnCode(0);
    oldTaskResult.setStandardMessage("std message");
    oldTaskResult.setStatus(TaskResult.TaskResultStatus.DONE);
    oldTaskResult.setTaskId(testTask1.getId());
    oldTaskResult.setTimestamp(cal.getTime());
    oldTaskResult.setService(testService);
    oldTaskResult.setId(taskResultDao.insertNewTaskResult(oldTaskResult, virtualEngineID));
    TaskResult oldTaskResult2 = new TaskResult();
    oldTaskResult2.setDestinationId(destination3.getId());
    oldTaskResult2.setErrorMessage("error message");
    oldTaskResult2.setReturnCode(0);
    oldTaskResult2.setStandardMessage("std message");
    oldTaskResult2.setStatus(TaskResult.TaskResultStatus.DONE);
    oldTaskResult2.setTaskId(testTask2.getId());
    oldTaskResult2.setTimestamp(cal.getTime());
    oldTaskResult2.setService(testService2);
    oldTaskResult2.setId(taskResultDao.insertNewTaskResult(oldTaskResult2, virtualEngineID));
    TaskResult uniqueTaskResult = new TaskResult();
    uniqueTaskResult.setDestinationId(destination2.getId());
    uniqueTaskResult.setErrorMessage("error message");
    uniqueTaskResult.setReturnCode(0);
    uniqueTaskResult.setStandardMessage("std message");
    uniqueTaskResult.setStatus(TaskResult.TaskResultStatus.DONE);
    uniqueTaskResult.setTaskId(testTask1.getId());
    uniqueTaskResult.setTimestamp(cal.getTime());
    uniqueTaskResult.setService(testService);
    uniqueTaskResult.setId(taskResultDao.insertNewTaskResult(uniqueTaskResult, virtualEngineID));
    TaskResult uniqueTaskResult2 = new TaskResult();
    uniqueTaskResult2.setDestinationId(destination2.getId());
    uniqueTaskResult2.setErrorMessage("error message");
    uniqueTaskResult2.setReturnCode(0);
    uniqueTaskResult2.setStandardMessage("std message");
    uniqueTaskResult2.setStatus(TaskResult.TaskResultStatus.DONE);
    uniqueTaskResult2.setTaskId(testTask2.getId());
    uniqueTaskResult2.setTimestamp(cal.getTime());
    uniqueTaskResult2.setService(testService2);
    uniqueTaskResult2.setId(taskResultDao.insertNewTaskResult(uniqueTaskResult2, virtualEngineID));
    TaskResult foundTaskResult1 = taskResultDao.getTaskResultById(taskResult.getId());
    TaskResult foundTaskResult2 = taskResultDao.getTaskResultById(oldTaskResult.getId());
    TaskResult foundTaskResult3 = taskResultDao.getTaskResultById(uniqueTaskResult.getId());
    TaskResult foundTaskResult4 = taskResultDao.getTaskResultById(taskResult2.getId());
    TaskResult foundTaskResult5 = taskResultDao.getTaskResultById(oldTaskResult2.getId());
    TaskResult foundTaskResult6 = taskResultDao.getTaskResultById(uniqueTaskResult2.getId());
    assertEquals(taskResult, foundTaskResult1);
    assertEquals(oldTaskResult, foundTaskResult2);
    assertEquals(uniqueTaskResult, foundTaskResult3);
    assertEquals(taskResult2, foundTaskResult4);
    assertEquals(oldTaskResult2, foundTaskResult5);
    assertEquals(uniqueTaskResult2, foundTaskResult6);
    taskResultDao.clearOld(virtualEngineID, 6);
    foundTaskResult1 = taskResultDao.getTaskResultById(taskResult.getId());
    foundTaskResult3 = taskResultDao.getTaskResultById(uniqueTaskResult.getId());
    foundTaskResult4 = taskResultDao.getTaskResultById(taskResult2.getId());
    foundTaskResult6 = taskResultDao.getTaskResultById(uniqueTaskResult2.getId());
    assertEquals(taskResult, foundTaskResult1);
    assertEquals(uniqueTaskResult, foundTaskResult3);
    assertEquals(taskResult2, foundTaskResult4);
    assertEquals(uniqueTaskResult2, foundTaskResult6);
    try {
        taskResultDao.getTaskResultById(oldTaskResult.getId());
        fail("TaskResult " + taskResult + " should not have been found");
    } catch (EmptyResultDataAccessException e) {
    }
    try {
        taskResultDao.getTaskResultById(oldTaskResult2.getId());
        fail("TaskResult " + taskResult2 + " should not have been found");
    } catch (EmptyResultDataAccessException e) {
    }
    taskResultDao.clearOld(virtualEngineID, 1);
    foundTaskResult1 = taskResultDao.getTaskResultById(taskResult.getId());
    foundTaskResult3 = taskResultDao.getTaskResultById(uniqueTaskResult.getId());
    foundTaskResult4 = taskResultDao.getTaskResultById(taskResult2.getId());
    foundTaskResult6 = taskResultDao.getTaskResultById(uniqueTaskResult2.getId());
    assertEquals(taskResult, foundTaskResult1);
    assertEquals(uniqueTaskResult, foundTaskResult3);
    assertEquals(taskResult2, foundTaskResult4);
    assertEquals(uniqueTaskResult2, foundTaskResult6);
}
Also used : Task(cz.metacentrum.perun.taskslib.model.Task) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) Calendar(java.util.Calendar) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) TaskResult(cz.metacentrum.perun.taskslib.model.TaskResult) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) Date(java.util.Date) Test(org.junit.Test)

Example 53 with EmptyResultDataAccessException

use of org.springframework.dao.EmptyResultDataAccessException in project bamboobsc by billchen198318.

the class SysMessageUtil method get.

public static String get(String code) {
    if (code == null || "".equals(code)) {
        return "";
    }
    if (sysMsgMap.get(code) != null) {
        return sysMsgMap.get(code);
    }
    init();
    if (jdbcTemplate == null) {
        return "";
    }
    String message = null;
    TbSysCode sysCode = new TbSysCode();
    sysCode.setCode(code);
    Map<String, Object> queryMap = getQuery(sysCode);
    if (queryMap == null) {
        return "";
    }
    try {
        message = jdbcTemplate.queryForObject(((String) queryMap.get(SqlGenerateUtil.RETURN_SQL)), (Object[]) queryMap.get(SqlGenerateUtil.RETURN_PARAMS), String.class);
        if (message != null) {
            sysMsgMap.put(code, message);
        }
    } catch (EmptyResultDataAccessException eda) {
        System.out.println(eda.getMessage().toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return message == null ? code : message;
}
Also used : TbSysCode(com.netsteadfast.greenstep.po.hbm.TbSysCode) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException)

Example 54 with EmptyResultDataAccessException

use of org.springframework.dao.EmptyResultDataAccessException in project nixmash-blog by mintster.

the class GithubJobUI method getCurrentGithubId.

public long getCurrentGithubId() {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    String sql = "SELECT stat_id FROM github_stats WHERE stat_date = current_date()";
    long statId = -1;
    try {
        statId = jdbcTemplate.queryForObject(sql, Long.class);
    } catch (EmptyResultDataAccessException e) {
        jdbcTemplate.update(new PreparedStatementCreator() {

            String INSERT_SQL = "INSERT INTO github_stats (stat_date) VALUES (current_date())";

            public PreparedStatement createPreparedStatement(Connection cn) throws SQLException {
                PreparedStatement ps = cn.prepareStatement(INSERT_SQL, new String[] { "stat_id" });
                return ps;
            }
        }, keyHolder);
        statId = keyHolder.getKey().longValue();
    }
    logger.info("Current GitHub Stats ID: " + statId);
    return statId;
}
Also used : GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) Connection(java.sql.Connection) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) PreparedStatement(java.sql.PreparedStatement) KeyHolder(org.springframework.jdbc.support.KeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder)

Example 55 with EmptyResultDataAccessException

use of org.springframework.dao.EmptyResultDataAccessException in project perun by CESNET.

the class UsersManagerImpl method getUserExtsourcesByIds.

public List<UserExtSource> getUserExtsourcesByIds(PerunSession sess, List<Integer> ids) throws InternalErrorException {
    if (ids.size() == 0) {
        return new ArrayList<UserExtSource>();
    }
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("ids", ids);
    try {
        return namedParameterJdbcTemplate.query("select " + userExtSourceMappingSelectQuery + "," + ExtSourcesManagerImpl.extSourceMappingSelectQuery + " from user_ext_sources left join ext_sources on user_ext_sources.ext_sources_id=ext_sources.id where" + " user_ext_sources.id in ( :ids )", parameters, USEREXTSOURCE_MAPPER);
    } catch (EmptyResultDataAccessException ex) {
        return new ArrayList<UserExtSource>();
    } catch (RuntimeException e) {
        throw new InternalErrorException(e);
    }
}
Also used : MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException)

Aggregations

EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)99 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)46 MapSqlParameterSource (org.springframework.jdbc.core.namedparam.MapSqlParameterSource)31 ArrayList (java.util.ArrayList)19 HashSet (java.util.HashSet)9 Transactional (org.springframework.transaction.annotation.Transactional)9 Group (cz.metacentrum.perun.core.api.Group)8 User (cz.metacentrum.perun.core.api.User)8 ConsistencyErrorException (cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException)7 SQLException (java.sql.SQLException)7 Test (org.junit.Test)6 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)6 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 Autowired (org.springframework.beans.factory.annotation.Autowired)4 Service (cz.metacentrum.perun.core.api.Service)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3 SyncopeClientException (org.apache.syncope.common.lib.SyncopeClientException)3