Java tutorial
/* * Copyright 2014. Vadim Baranov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vader.apm.dao.util; import com.google.common.collect.Collections2; import com.google.common.collect.Sets; import org.apache.commons.lang3.Validate; import org.springframework.jdbc.core.JdbcTemplate; import org.vader.apm.domain.ApmDbObject; import java.util.Collection; import java.util.List; /** * @author Vadim Baranov */ public final class DaoUtils { /** * Asserts that only one row has been modified. * * @param rows modified rows number */ public static void assertOne(int rows) { Validate.isTrue(1 == rows, String.format("Only one row must be modified, but - %s", rows)); } /** * Asserts that object is in specified state. * * @param state state to check against * @param dbObject object to assert */ public static void assertObjectState(DbObjectState state, ApmDbObject dbObject) { Validate.isTrue(state.apply(dbObject), "DB object must be %s", state); } /** * Filter all objects by type. * * @param dbObjects objects to filter * @param state DB object state * @param <T> DB object type * @return filtered objects */ public static <T extends ApmDbObject> Collection<T> getDbObjectsByState(Collection<T> dbObjects, DbObjectState state) { final Collection<T> result = Sets.newIdentityHashSet(); result.addAll(Collections2.filter(dbObjects, state)); return result; } /** * Get sequence next N values. * * @param seqName sequence name * @param count values count * @param jdbcTemplate JDBC template * @return N next values */ public static List<Long> getSeqNextNVal(String seqName, int count, JdbcTemplate jdbcTemplate) { final String sql = "WITH RECURSIVE result(seq_value, level) AS (VALUES (nextval(?), 1) UNION ALL " + "SELECT nextval(?), level + 1 FROM result WHERE level < ?) SELECT seq_value FROM result"; return jdbcTemplate.queryForList(sql, Long.class, seqName, seqName, count); } private DaoUtils() { } }