/* * Copyright (c) 2020 * San Diego Supercomputer Center * University of California, San Diego * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution.* * * Neither the name of the author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.ngbw.cipres.sdk.dao; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.ngbw.cipres.sdk.dao.bean.ApplicationPreference; import org.ngbw.cipres.sdk.dao.bean.ClientCredentials; import org.ngbw.cipres.sdk.dao.bean.ClientToken; import org.ngbw.cipres.sdk.dao.bean.JobStatistics; import org.ngbw.cipres.sdk.dao.bean.ResourceConversion; import org.ngbw.cipres.sdk.dao.bean.TgUsage; import org.ngbw.cipres.sdk.dao.bean.User; import org.ngbw.cipres.sdk.dao.bean.UserAllocationTransaction; import org.ngbw.cipres.sdk.dao.bean.UserSuAllocation; import org.ngbw.cipres.sdk.dao.bean.XdUsage; import org.ngbw.cipres.sdk.dao.bean.XsedeAttributeReportingSchedule; import org.ngbw.cipres.sdk.dao.bean.category.SuTransactionType; import org.ngbw.cipres.sdk.dao.bean.range.RangeValue; import org.ngbw.cipres.sdk.dao.bean.utils.SortOrders; import org.ngbw.cipres.sdk.dao.bean.utils.StringUtils; import org.ngbw.cipres.sdk.dao.bean.utils.Validator; /** * The main DAO class with various methods for basic database CRUD operations. * * @author Tony Chen */ public class CipresDAO extends AppDAO { private static final Logger logger = Logger.getLogger(CipresDAO.class); /** * Constructor. * * @param uuid the UUID when the object is instantiated * @param session the Hibernate Session from session factory * * @throws HibernateException */ public CipresDAO ( String uuid, Session session ) throws HibernateException { super(uuid, session); } /** * Retrieves the preference value of the application. * * @param appName the application name * @param preference the preference name * * @return * * @throws HibernateException */ public ApplicationPreference getApplicationPreference ( String appName, String preference ) throws HibernateException { appName = Validator.notNull(appName, "Application name cannot be empty or null."); preference = Validator.notNull(preference, "Preference name cannot be empty or null."); try { Criteria rootCriteria = super.getSession().createCriteria(ApplicationPreference.class); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("name", appName))); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("preference", preference))); return (ApplicationPreference) rootCriteria.uniqueResult(); } catch ( HibernateException e ) { throw e; } finally { } } public String getApplicationPreference ( final String appName, final String preference, final String defaultValue ) throws HibernateException { ApplicationPreference appPref = getApplicationPreference(appName, preference); if (null != appPref) { return (null == appPref.getValue()) ? defaultValue : appPref.getValue(); } return defaultValue; } @Override public void close () throws Exception { super.closeQuietly(); } public void testConnection () throws HibernateException { try { final ApplicationPreference pref = getApplicationPreference("NONE", "NONE"); } catch ( HibernateException e ) { throw e; } finally { } } // ====================[ User ]==================== // public User getUser ( final Long id ) throws HibernateException { if (id == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "ID")); } return retrieveUser("id", id); } public User getUserByUsername ( final String userName ) throws HibernateException { if (userName == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Username")); } return retrieveUser("username", userName); } public User getUserByEmail ( final String emailAddress ) throws HibernateException { if (emailAddress == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Email address")); } return retrieveUser("email", emailAddress); } public User getUserByUUID ( final String uuid ) throws HibernateException { if (uuid == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "User's UUID")); } return retrieveUser("uuid", uuid); } private User retrieveUser ( final String variable, final Object value ) throws HibernateException { if (variable == null || variable.trim().isEmpty()) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Variable name")); } try { Criteria rootCriteria = super.getSession().createCriteria(User.class); if (value == null) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.isNull(variable))); } else { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq(variable, value))); } // Distinct rows only. super.distinctRootEntityResults(rootCriteria); super.startTransaction(); super.commit(); return (User) rootCriteria.uniqueResult(); } catch ( HibernateException e ) { super.rollback(); throw e; } finally { //super.closeAndQuitSilently(session); } } /** * Retrieves users. * * @param firstResult * @param maxResults * @param sortOrders * * @return * @throws HibernateException */ public List getUsers ( final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { return getUsers(null, firstResult, maxResults, sortOrders); } /** * Retrieves users who currently have the given role. * * @param role * @param firstResult * @param maxResults * @param sortOrders * * @return * @throws HibernateException */ public List getUsers ( final String role, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { try { final SortOrders orderBy = (sortOrders != null) ? sortOrders : SortOrders.build().add(User.ORDER_BY_ID_ASC); Criteria rootCriteria = super.getSession().createCriteria(User.class); super.setSortOrders(rootCriteria, User.class, orderBy); this.setLimit(rootCriteria, firstResult, maxResults); if (role != null && !role.trim().isEmpty()) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("role", role))); } // Distinct rows only. super.distinctRootEntityResults(rootCriteria); super.setLimit(rootCriteria, firstResult, maxResults); return (List) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } public List getActiveUsers ( final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { return retrieveUsers("a", firstResult, maxResults, sortOrders); } public List getInactiveUsers ( final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { return retrieveUsers("i", firstResult, maxResults, sortOrders); } private List retrieveUsers ( final String status, // 'a' = active, 'i' = inactive final long firstResult, final long maxResults, SortOrders sortOrders ) throws HibernateException { if (sortOrders == null) { sortOrders = SortOrders.build().add(User.ORDER_BY_ID_ASC); } try { Criteria rootCriteria = super.getSession().createCriteria(User.class); super.setSortOrders(rootCriteria, User.class, sortOrders); if (status.equals("a")) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("active", Boolean.TRUE))); } else if (status.equals("i")) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("active", Boolean.FALSE))); } // Distinct rows only. super.distinctRootEntityResults(rootCriteria); super.setLimit(rootCriteria, firstResult, maxResults); super.startTransaction(); super.commit(); return (List) rootCriteria.list(); } catch ( HibernateException e ) { super.rollback(); throw e; } finally {} } public User save ( final User obj ) throws HibernateException { if (obj == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "object")); } if (obj.getId() == null || obj.getId() <= 0) { return (User) super.create(obj); } return (User) super.update(obj); } // ====================[ ClientCredentials ]==================== // public ClientCredentials getClientCredentials ( final Long id ) throws HibernateException { if (null == id) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "ID")); } try { Query query = super.getSession().createQuery( " FROM ClientCredentials AS cred " + " WHERE cred.id =:id "); query.setLong("id", id); return (ClientCredentials) query.uniqueResult(); } catch ( HibernateException e ) { throw e; } finally { } } public ClientCredentials getClientCredentials ( final String identifier ) throws HibernateException { if (null == identifier || identifier.trim().isEmpty()) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Identifier")); } try { Query query = super.getSession().createQuery( " FROM ClientCredentials AS cred " + " WHERE cred.clientIdentifier =:id "); query.setString("id", identifier); return (ClientCredentials) query.uniqueResult(); } catch ( HibernateException e ) { throw e; } finally { } } public List getActiveClientCredentials ( final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { return retrieveClientCredentials( "Y", firstResult, maxResults, sortOrders); } public List getInactiveClientCredentials ( final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { return retrieveClientCredentials( "N", firstResult, maxResults, sortOrders); } private List retrieveClientCredentials ( final String status, final long firstResult, final long maxResults, SortOrders sortOrders ) throws HibernateException { try { if (sortOrders == null) { sortOrders = SortOrders.build().add(ClientCredentials.ORDER_BY_CREATED_TIME_ASC); } Criteria rootCriteria = super.getSession().createCriteria(ClientCredentials.class); super.setSortOrders(rootCriteria, ClientCredentials.class, sortOrders); if (null != status && !status.trim().isEmpty()) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("active", status))); } super.distinctRootEntityResults(rootCriteria); super.setLimit(rootCriteria, firstResult, maxResults); return (List) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } public ClientCredentials save ( final ClientCredentials obj ) throws HibernateException { if (obj == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "object")); } if (obj.getId() == null || obj.getId() <= 0) { return (ClientCredentials) super.create(obj); } return (ClientCredentials) super.update(obj); } // ====================[ ClientToken ]==================== // public ClientToken getClientToken ( final Long id ) throws HibernateException { if (null == id) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "ID")); } try { Query query = super.getSession().createQuery( " FROM ClientToken AS token " + " WHERE token.id =:id "); query.setLong("id", id); return (ClientToken) query.uniqueResult(); } catch ( HibernateException e ) { throw e; } finally { } } public ClientToken getClientToken ( final String clientIdentifier ) throws HibernateException { List tokens = retrieveClientTokens( clientIdentifier, null, null, Boolean.TRUE, 0, 1, SortOrders.build().add(ClientToken.ORDER_BY_EXPIRES_TIME_DESC)); return (tokens == null || tokens.isEmpty())? null : tokens.get(0); } /** * Retrieves the current active (if exist) Access Token. * *

* An Access Token is active iff: *

    *
  • it has not been revoked
  • *
  • its 'NotBefore' date is before current time
  • *
  • its expires time is after current time
  • *
* * @param clientIdentifier * * @return * * @throws HibernateException */ public ClientToken getActiveClientToken ( final String clientIdentifier ) throws HibernateException { final Date now = new Date(); final RangeValue notBeforeTimeRange = new RangeValue<>(); notBeforeTimeRange.atMost(now); final RangeValue expiresTimeRange = new RangeValue<>(); expiresTimeRange.atLeast(now); List tokens = retrieveClientTokens( clientIdentifier, notBeforeTimeRange, expiresTimeRange, Boolean.TRUE, 0, 0, SortOrders.build().add(ClientToken.ORDER_BY_EXPIRES_TIME_ASC)); if (null != tokens && (tokens.size() > 1)) { throw new RuntimeException("More than one active tokens found for the Client: " + clientIdentifier); } else if (null != tokens && (tokens.size() == 1)) { return tokens.get(0); } return null; } public List getClientTokens ( final String clientIdentifier, final boolean activeOnly, final long firstResult, final long maxResults, SortOrders sortOrders ) throws HibernateException { return retrieveClientTokens(clientIdentifier, null, null, activeOnly, firstResult, maxResults, sortOrders); } private List retrieveClientTokens ( final String clientIdentifier, final RangeValue notBeforeTimeRange, final RangeValue expiresTimeRange, final boolean activeOnly, final long firstResult, final long maxResults, SortOrders sortOrders ) throws HibernateException { if (null == clientIdentifier || clientIdentifier.trim().isEmpty()) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Client ID")); } try { if (sortOrders == null) { sortOrders = SortOrders.build().add(ClientToken.ORDER_BY_EXPIRES_TIME_DESC); } Criteria rootCriteria = super.getSession().createCriteria(ClientToken.class); super.setSortOrders(rootCriteria, ClientToken.class, sortOrders); Criteria credCr = rootCriteria.createCriteria("credentials"); credCr.add(Restrictions.conjunction().add(Restrictions.eq("clientIdentifier", clientIdentifier))); super.setSortOrders(credCr, ClientCredentials.class, sortOrders); // Active only ==> Revoked = 'N' if (activeOnly) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("revoked", "N"))); } if (null != notBeforeTimeRange) { rootCriteria.add(super.setRangeValues(Restrictions.conjunction(), "notBefore", notBeforeTimeRange)); } if (null != expiresTimeRange) { rootCriteria.add(super.setRangeValues(Restrictions.conjunction(), "expiresTime", expiresTimeRange)); } // Distinct rows only. super.distinctRootEntityResults(rootCriteria); super.setLimit(rootCriteria, firstResult, maxResults); return (List) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } public ClientToken save ( final ClientToken obj ) throws HibernateException { if (obj == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "object")); } if (obj.getId() == null || obj.getId() <= 0) { return (ClientToken) super.create(obj); } return (ClientToken) super.update(obj); } // ====================[ User SU Balance ]==================== // /** * Gets count of SU allocations. * * @param startTimeRange * @param expireTimeRange * * @return * * @throws HibernateException */ public long getUserSuAllocationCount ( final RangeValue startTimeRange, final RangeValue expireTimeRange ) throws HibernateException { try { Criteria rootCriteria = super.getSession().createCriteria(UserSuAllocation.class); if (null != startTimeRange) { rootCriteria.add( super.setRangeValues( Restrictions.conjunction(), "startTime", startTimeRange)); } if (null != expireTimeRange) { rootCriteria.add( super.setRangeValues( Restrictions.conjunction(), "suExpireTime", expireTimeRange)); } // Distinct rows only. rootCriteria = super.distinctRootEntityResults(rootCriteria); rootCriteria.setProjection(Projections.rowCount()); super.startTransaction(); super.commit(); Long count = (Long) rootCriteria.uniqueResult(); return (count == null)? 0 : count; } catch ( HibernateException e ) { super.rollback(); throw e; } finally { //super.closeAndQuitSilently(session); } } /** * Retrieves the user's last (non-expired) SU allocation. * * @param userId the user id * @param nonExpiredOnly exclude expired ones * * @return */ public UserSuAllocation getLastUserSuAllocation ( Long userId, boolean nonExpiredOnly ) { if (userId == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "User ID")); } List allocations = null; if (nonExpiredOnly) { allocations = getNonExpiredUserSuAllocations(userId, 0, 0, null); } else { allocations = getUserSuAllocations( userId, null, 0, 1, SortOrders.build().add(UserSuAllocation.ORDER_BY_SU_EXPIRE_TIME_DESC)); } if (null != allocations && !allocations.isEmpty()) { if (allocations.size() > 1) { throw new RuntimeException("Multiple SU Allocations found for user '" + userId + "'."); } return allocations.get(0); } return null; } /** * Retrieves expired users' SU allocations. * *

* Current time will be used to determine which user's SU allocation has expired. * * @param userId the user id (optional) * @param firstResult * @param maxResults * @param sortOrders * * @return * * @throws HibernateException */ public List getExpiredUserSuAllocations ( final Long userId, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { RangeValue dateRange = new RangeValue(); dateRange.atMost(new Date()); return getUserSuAllocations(userId, dateRange, firstResult, maxResults, sortOrders); } /** * Retrieves non-expired users' SU allocations. * *

* Current time will be used to determine which user's SU allocation has not expired. * * @param userId the user id (optional) * @param firstResult * @param maxResults * @param sortOrders * * @return * * @throws HibernateException */ public List getNonExpiredUserSuAllocations ( final Long userId, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { RangeValue dateRange = new RangeValue(); dateRange.atLeast(new Date()); return getUserSuAllocations(userId, dateRange, firstResult, maxResults, sortOrders); } /** * Retrieves SU allocations which will expire on or after the specified {@code expireDate}. * * @param userId * @param expireDate * @param firstResult * @param maxResults * @param sortOrders * @return * @throws HibernateException */ public List getUserSuAllocationsExpiredAfter ( final Long userId, final Date expireDate, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { RangeValue dateRange = new RangeValue(); dateRange.atLeast(expireDate); return getUserSuAllocations(userId, dateRange, firstResult, maxResults, sortOrders); } /** * Retrieves SU allocations which will expire on or before the specified {@code expireDate}. * * @param userId * @param expireDate * @param firstResult * @param maxResults * @param sortOrders * * @return * * @throws HibernateException */ public List getUserSuAllocationsExpiredBefore ( final Long userId, final Date expireDate, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { RangeValue dateRange = new RangeValue(); dateRange.atMost(expireDate); return getUserSuAllocations(userId, dateRange, firstResult, maxResults, sortOrders); } /** * Retrieves SU allocations which {@code expireTime} is in the range of {@code expireTimeRange}. * In another words, this method returns all SU allocations which have expired or will expire during * the specified {@code expireTimeRange}. * * @param userId the user id (optional) * @param expireTimeRange the expire time range * @param firstResult * @param maxResults * @param sortOrders * * @return * * @throws HibernateException */ public List getUserSuAllocations ( final Long userId, final RangeValue expireTimeRange, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { try { final SortOrders orderBy = (sortOrders != null) ? sortOrders : SortOrders.build().add(UserSuAllocation.ORDER_BY_SU_EXPIRE_TIME_DESC); Criteria rootCriteria = super.getSession().createCriteria(UserSuAllocation.class); super.setSortOrders(rootCriteria, UserSuAllocation.class, orderBy); if (null != userId) { Criteria userCr = rootCriteria.createCriteria("user"); super.setSortOrders(userCr, User.class, orderBy); userCr.add(Restrictions.conjunction().add(Restrictions.eq("id", userId))); } if (null != expireTimeRange) { rootCriteria.add(super.setRangeValues(Restrictions.conjunction(), "suExpireTime", expireTimeRange)); } super.distinctRootEntityResults(rootCriteria); // Distinct rows only. super.setLimit(rootCriteria, firstResult, maxResults); return (List) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } public UserSuAllocation save ( final UserSuAllocation obj ) throws HibernateException { if (obj == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "object")); } if (obj.getId() == null || obj.getId() <= 0) { return (UserSuAllocation) super.create(obj); } return (UserSuAllocation) super.update(obj); } // ====================[ User SU Transaction ]==================== // public long getUserAllocationTransactionCount ( final User user ) throws HibernateException { return getUserAllocationTransactionCount(user, null, null); } public long getUserAllocationTransactionCount ( final User user, final RangeValue transactionTimeRange ) throws HibernateException { return getUserAllocationTransactionCount(user, transactionTimeRange, null); } public long getUserAllocationTransactionCount ( final User user, final SuTransactionType type ) throws HibernateException { return getUserAllocationTransactionCount(user, null, type); } public long getUserAllocationTransactionCount ( final User user, final RangeValue transactionTimeRange, final SuTransactionType type ) throws HibernateException { try { if (null == user) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "User")); } Criteria rootCriteria = super.getSession().createCriteria(UserAllocationTransaction.class); Criteria userCr = rootCriteria.createCriteria("user"); userCr.add(Restrictions.conjunction().add(Restrictions.eq("id", user.getId()))); if (null != transactionTimeRange) { rootCriteria.add(super.setRangeValues( Restrictions.conjunction(), "transactionTime", transactionTimeRange)); } if (null != type) { Criteria typeCr = rootCriteria.createCriteria("transactionType"); typeCr.add(Restrictions.conjunction().add(Restrictions.eq("id", type.getId()))); } // Distinct rows only. rootCriteria = super.distinctRootEntityResults(rootCriteria); rootCriteria.setProjection(Projections.rowCount()); Long count = (Long) rootCriteria.uniqueResult(); return (count == null) ? 0 : count; } catch ( HibernateException e ) { throw e; } finally { } } public long allocationTransactionsTotal ( final User user, final RangeValue transactionTimeRange ) throws HibernateException { return allocationTransactionsTotal(user, transactionTimeRange, null); } public long allocationAdjustmentsTotal ( final User user, final RangeValue transactionTimeRange ) throws HibernateException { try { return allocationTransactionsTotal(user, transactionTimeRange, SuTransactionType.Adjustment()); } catch ( Throwable t ) { throw new HibernateException(t); } } public long allocationAwardsTotal ( final User user, final RangeValue transactionTimeRange ) throws HibernateException { try { return allocationTransactionsTotal(user, transactionTimeRange, SuTransactionType.Award()); } catch ( Throwable t ) { throw new HibernateException(t); } } public long allocationPurchasesTotal ( final User user, final RangeValue transactionTimeRange ) throws HibernateException { try { return allocationTransactionsTotal(user, transactionTimeRange, SuTransactionType.Purchase()); } catch ( Throwable t ) { throw new HibernateException(t); } } private long allocationTransactionsTotal ( final User user, final RangeValue transactionTimeRange, final SuTransactionType type ) throws HibernateException { try { if (null == user) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "User")); } Criteria rootCriteria = super.getSession().createCriteria(UserAllocationTransaction.class); Criteria userCr = rootCriteria.createCriteria("user"); userCr.add(Restrictions.conjunction().add(Restrictions.eq("id", user.getId()))); if (null != transactionTimeRange) { rootCriteria.add(super.setRangeValues( Restrictions.conjunction(), "transactionTime", transactionTimeRange)); } if (null != type) { Criteria typeCr = rootCriteria.createCriteria("transactionType"); typeCr.add(Restrictions.conjunction().add(Restrictions.eq("name", type.getName()))); } // Distinct rows only. rootCriteria = super.distinctRootEntityResults(rootCriteria); rootCriteria.setProjection(Projections.sum("suAmount")); Long count = (Long) rootCriteria.uniqueResult(); return (count == null) ? 0 : count; } catch ( HibernateException e ) { throw e; } finally { } } public UserAllocationTransaction getUserAllocationTransaction ( final String transactionNumber ) { if (transactionNumber == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Transaction number")); } try { Criteria rootCriteria = super.getSession().createCriteria(UserAllocationTransaction.class); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("transactionNumber", transactionNumber))); // Distinct rows only. super.distinctRootEntityResults(rootCriteria); super.startTransaction(); super.commit(); return (UserAllocationTransaction) rootCriteria.uniqueResult(); } catch ( HibernateException e ) { super.rollback(); throw e; } finally { //super.closeAndQuitSilently(session); } } public List getUserAllocationTransactions ( final Long userId, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { return getUserAllocationTransactions(userId, null, null, firstResult, maxResults, sortOrders); } public List getUserAllocationTransactions ( final RangeValue transactionTimeRange, final Long transactionType, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { return getUserAllocationTransactions(null, transactionTimeRange, null, firstResult, maxResults, sortOrders); } public List getUserAllocationTransactions ( final Long userId, final RangeValue transactionTimeRange, final Long transactionType, final long firstResult, final long maxResults, SortOrders sortOrders ) throws HibernateException { try { if (null == sortOrders) { sortOrders = SortOrders.build() .add(UserAllocationTransaction.ORDER_BY_TRANSACTION_TIME_DESC) .add(User.ORDER_BY_ID_ASC); } Criteria rootCriteria = super.getSession().createCriteria(UserAllocationTransaction.class); super.setSortOrders(rootCriteria, UserAllocationTransaction.class, sortOrders); if (null != transactionTimeRange) { rootCriteria.add( super.setRangeValues( Restrictions.conjunction(), "transactionTime", transactionTimeRange)); } if (null != userId) { Criteria userCr = rootCriteria.createCriteria("user"); userCr.add(Restrictions.conjunction().add(Restrictions.eq("id", userId))); super.setSortOrders(userCr, User.class, sortOrders); } if (null != transactionType) { Criteria transTypeCr = rootCriteria.createCriteria("transactionType"); transTypeCr.add(Restrictions.conjunction().add(Restrictions.eq("id", transactionType))); super.setSortOrders(transTypeCr, SuTransactionType.class, sortOrders); } // Distinct rows only. super.distinctRootEntityResults(rootCriteria); super.setLimit(rootCriteria, firstResult, maxResults); super.startTransaction(); super.commit(); return (List) rootCriteria.list(); } catch ( HibernateException e ) { super.rollback(); throw e; } finally { //super.closeAndQuitSilently(session); } } public UserAllocationTransaction save ( final UserAllocationTransaction obj ) throws HibernateException { if (obj == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "object")); } if (obj.getId() == null || obj.getId() <= 0) { return (UserAllocationTransaction) super.create(obj); } return (UserAllocationTransaction) super.update(obj); } // ====================[ Job Statistics ]==================== // /** * Retrieves {@link JobStatistics} by specified {@code jobHandle}. * * @param jobHandle * @return * @throws HibernateException */ public JobStatistics getJobStatistics ( final String jobHandle ) throws HibernateException { if (jobHandle == null || jobHandle.trim().isEmpty()) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Job handle")); } try { Criteria rootCriteria = super.getSession().createCriteria(JobStatistics.class); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("jobHandle", jobHandle))); // Distinct rows only. super.distinctRootEntityResults(rootCriteria); super.startTransaction(); super.commit(); return (JobStatistics) rootCriteria.uniqueResult(); } catch ( HibernateException e ) { super.rollback(); throw e; } finally { //super.closeAndQuitSilently(session); } } /** * @deprecated * * Retrieves {@link JobStatistics} by specified {@code remoteJobId} and {@code resource}. * *

* The {@code remoteJobId} is also known as {@code XSEDE Job ID}. * * @param remoteJobId the XSEDE job id * @param resource the resource the job runs on such as {@code Comet} or {@code Expanse} * * @return * @throws HibernateException */ public JobStatistics getJobStatistics_tbd ( final String remoteJobId, final String resource ) throws HibernateException { if (StringUtils.isNullOrEmpty(remoteJobId, true)) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Remote Job ID")); } else if (StringUtils.isNullOrEmpty(resource, true)) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Resource")); } List stats = retrieveJobStatistics(remoteJobId, resource, null, null, 0, 0, 0, null); if (stats != null && stats.size() > 1) { throw new RuntimeException(String.format( "Result has more than one records of JobStatistics for RemoteJobID=[%s] Resource=[%s]", remoteJobId, resource)); } return (stats == null || stats.isEmpty())? null : stats.get(0); } /** * @deprecated * @param taskId * @param runNumber * @return * @throws HibernateException */ public JobStatistics getJobStatistics_tbd ( final Long taskId, final Integer runNumber ) throws HibernateException { if (taskId == null || taskId <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Task ID")); } else if (runNumber == null || runNumber <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Run number")); } List stats = retrieveJobStatistics(null, null, taskId, runNumber, 0, 0, 0, null); if (stats != null && stats.size() > 1) { throw new RuntimeException(String.format( "Result has more than one records of JobStatistics for TaskID=[%d] RunNumber=[%d]", taskId, runNumber)); } return (stats == null || stats.isEmpty())? null : stats.get(0); } public List getJobStatistics ( final String remoteJobId, final String resource, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { if (StringUtils.isNullOrEmpty(remoteJobId, true)) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Remote Job ID")); } else if (StringUtils.isNullOrEmpty(resource, true)) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Resource")); } return retrieveJobStatistics(remoteJobId, resource, null, null, 0, firstResult, maxResults, sortOrders); } public List getJobStatistics ( final Long taskId, final Integer runNumber, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { if (taskId == null || taskId <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Task ID")); } else if (runNumber == null || runNumber <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Run number")); } return retrieveJobStatistics(null, null, taskId, runNumber, 0, firstResult, maxResults, sortOrders); } private List retrieveJobStatistics ( final String remoteJobId, final String resource, final Long taskId, final Integer runNumber, final int xsedeJobIdStage, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { try { final SortOrders orderBy = (sortOrders != null) ? sortOrders : SortOrders.build().add(JobStatistics.ORDER_BY_DATE_SUBMITTED_ASC); final Criteria rootCriteria = super.getSession().createCriteria(JobStatistics.class); super.setSortOrders(rootCriteria, JobStatistics.class, orderBy); if (StringUtils.notNullAndNotEmpty(remoteJobId, true)) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("remoteJobId", remoteJobId))); } if (StringUtils.notNullAndNotEmpty(resource, true)) { Criteria resourceCr = rootCriteria.createCriteria("resourceConversion"); resourceCr.add(Restrictions.conjunction().add(Restrictions.eq("resource", resource))); super.setSortOrders(resourceCr, ResourceConversion.class, orderBy); } if (taskId != null) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("taskId", taskId))); } if (runNumber != null) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("taskRunNumber", runNumber))); } if (xsedeJobIdStage == XSEDE_JOBID_PRESENT) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.isNotNull("remoteJobId"))); } else if (xsedeJobIdStage == XSEDE_JOBID_NON_PRESENT) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.isNull("remoteJobId"))); } // Distinct rows only. super.distinctRootEntityResults(rootCriteria); super.setLimit(rootCriteria, firstResult, maxResults); return (List) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } public List getJobStatistics ( final Long userId, final int xsedeJobIdStage, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { if (userId == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "User ID")); } return retrieveJobStatistics( userId, null, // Charge number null, // Job creation time range xsedeJobIdStage, firstResult, maxResults, sortOrders); } public List getJobStatistics ( final Long userId, final RangeValue jobsCreatedTimeRange, // Time interval where jobs are created/entered. final int xsedeJobIdStage, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { if (userId == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "User ID")); } else if (jobsCreatedTimeRange == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Job created time range")); } return retrieveJobStatistics( userId, null, // Charge number jobsCreatedTimeRange, xsedeJobIdStage, firstResult, maxResults, sortOrders); } public List getJobStatistics ( final Long userId, final String chargeNumber, final RangeValue jobsCreatedTimeRange, // Time interval where jobs are created/entered. final int xsedeJobIdStage, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { if (userId == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "User ID")); } else if (chargeNumber == null || chargeNumber.trim().isEmpty()) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Charge number")); } else if (jobsCreatedTimeRange == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Job created time range")); } return retrieveJobStatistics( userId, chargeNumber, jobsCreatedTimeRange, xsedeJobIdStage, firstResult, maxResults, sortOrders); } public List getJobStatistics ( final RangeValue jobsCreatedTimeRange, // Time interval where jobs are created/entered. final int xsedeJobIdStage, final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { if (jobsCreatedTimeRange == null) { throw new IllegalArgumentException(String.format( ERR_PARAM_NULL_EMPTY, "Job created time range")); } return retrieveJobStatistics( null, // User ID null, // Charge number jobsCreatedTimeRange, xsedeJobIdStage, firstResult, maxResults, sortOrders); } private List retrieveJobStatistics ( final Long userId, final String chargeNumber, final RangeValue jobsCreatedTimeRange, // Time interval where jobs are created/entered. final int xsedeJobIdStage, // 1=PRESENT | 2=NON-PRESENT final long firstResult, final long maxResults, final SortOrders sortOrders ) throws HibernateException { try { final Session session = super.getSession(); final SortOrders orderBy = (sortOrders != null) ? sortOrders : SortOrders.build().add(JobStatistics.ORDER_BY_DATE_ENTERED_ASC); Criteria rootCriteria = session.createCriteria(JobStatistics.class); super.setSortOrders(rootCriteria, JobStatistics.class, orderBy); if (null != chargeNumber && !chargeNumber.trim().isEmpty()) { rootCriteria.add(Restrictions.conjunction().add( Restrictions.eq("tgChargeNumber", chargeNumber))); } if (null != jobsCreatedTimeRange) { rootCriteria.add(super.setRangeValues( Restrictions.conjunction(), "dateEntered", jobsCreatedTimeRange)); } if (xsedeJobIdStage == XSEDE_JOBID_PRESENT) { rootCriteria.add(Restrictions.conjunction().add( Restrictions.isNotNull("remoteJobId"))); } else if (xsedeJobIdStage == XSEDE_JOBID_NON_PRESENT) { rootCriteria.add(Restrictions.conjunction().add( Restrictions.isNull("remoteJobId"))); } if (userId != null) { Criteria userCr = rootCriteria.createCriteria("user"); userCr.add(Restrictions.conjunction().add(Restrictions.eq("id", userId))); super.setSortOrders(userCr, User.class, orderBy); } super.distinctRootEntityResults(rootCriteria); super.setLimit(rootCriteria, firstResult, maxResults); return (List) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } /** * Retrieves total SU the user has used. * * @param userId the user ID * @param jobsCreatedTimeRange time interval where jobs are created (entered) * @param chargeNumber the XSEDE charge number * * @return the total SU * * @throws HibernateException * * @see org.ngbw.cipres.sdk.dao.bean.range.Range * @see org.ngbw.cipres.sdk.dao.bean.range.RangeValue */ public long getUserTotalUsage ( final Long userId, final RangeValue jobsCreatedTimeRange, // Time interval where jobs are created/entered. final String ... chargeNumbers ) throws HibernateException { try { StringBuilder stmtBuilder = new StringBuilder(); // SELECT statement. stmtBuilder.append("SELECT SUM("); stmtBuilder.append("COALESCE(js.suOverride, COALESCE(js.suCharged, COALESCE(js.suComputed, COALESCE(js.suPredicted, 0))))"); // Times the SU with Conversion Ratio (non-null value only) stmtBuilder.append(" * COALESCE(js.resourceConversion.conversion, 1)"); // Close of the SELECT statement. stmtBuilder.append(")"); // FROM statement stmtBuilder.append(" FROM JobStatistics AS js"); // WHERE statement stmtBuilder.append(" WHERE js.user.id =:userId "); if (jobsCreatedTimeRange != null) { // It is NOT a range, it only contains one value hence it is an exact match. if (jobsCreatedTimeRange.isExactEqual()) { // Exact match ==> propertyValue = rangeValue stmtBuilder.append(" AND js.dateEntered =:startTime "); //System.out.println("DateEntered = StartTime"); } else { // It contains range values. if (jobsCreatedTimeRange.lowerValue() != null) { // It has lower bound. if (jobsCreatedTimeRange.isLowerBoundOpen()) { // GreaterThan (gt) ==> propertyValue > rangeValue stmtBuilder.append(" AND js.dateEntered >:startTime "); //System.out.println("DateEntered > StartTime"); } else { // GreaterThanEqual/AtLeast (ge) ==> propertyValue >= rangeValue stmtBuilder.append(" AND js.dateEntered >=:startTime "); //System.out.println("DateEntered >= StartTime"); } } if (jobsCreatedTimeRange.upperValue() != null) { // It has upper bound. if (jobsCreatedTimeRange.isUpperBoundOpen()) { // LessThan (lt) ==> propertyValue < rangeValue stmtBuilder.append(" AND js.dateEntered <:endTime "); //System.out.println("DateEntered < EndTime"); } else { // LessThanEqual/AtMost (le) ==> propertyValue <= rangeValue stmtBuilder.append(" AND js.dateEntered <=:endTime "); //System.out.println("DateEntered <= EndTime"); } } } } // Process charge numbers separately. final StringBuilder chargeNumsStmt = new StringBuilder(); if (null != chargeNumbers && chargeNumbers.length > 0) { for (int i = 0; i < chargeNumbers.length; i++) { String cn = chargeNumbers[i]; if (null != cn && !cn.trim().isEmpty()) { if (chargeNumsStmt.length() > 0) { chargeNumsStmt.append(" OR "); } chargeNumsStmt.append(String.format("js.tgChargeNumber =:chargeNumber%d", i)); } } } else { // chargeNumsStmt.append("js.tgChargeNumber IS NULL"); } if (chargeNumsStmt.length() > 0) { stmtBuilder.append(" AND (").append(chargeNumsStmt.toString()).append(")"); } stmtBuilder.append(" GROUP BY js.user.id "); //System.out.println("\n" + stmtBuilder.toString()); Query query = super.getSession().createQuery(stmtBuilder.toString()); query.setLong("userId", userId); if (jobsCreatedTimeRange != null) { // It is NOT a range, it only contains one value hence it is an exact match. if (jobsCreatedTimeRange.isExactEqual()) { // Exact match ==> propertyValue = rangeValue query.setTimestamp("startTime", jobsCreatedTimeRange.lowerValue()); //System.out.println("StartTime = JobsCreatedTimeRange.lower"); } else { // It contains range values. if (jobsCreatedTimeRange.lowerValue() != null) { // It has lower bound. query.setTimestamp("startTime", jobsCreatedTimeRange.lowerValue()); //System.out.println("StartTime <<- JobsCreatedTimeRange.lower"); } if (jobsCreatedTimeRange.upperValue() != null) { // It has upper bound. query.setTimestamp("endTime", jobsCreatedTimeRange.upperValue()); //System.out.println("EndTime <<- JobsCreatedTimeRange.upper"); } } } if (null != chargeNumbers && chargeNumbers.length > 0) { for (int i = 0; i < chargeNumbers.length; i++) { String cn = chargeNumbers[i]; if (null != cn && !cn.trim().isEmpty()) { query.setString(String.format("chargeNumber%d", i), cn); } } } Object obj = query.uniqueResult(); Double totalUsage = 0.00; if (obj != null) { totalUsage = new Double(obj.toString()); } return totalUsage.longValue(); } catch ( HibernateException e ) { throw e; } finally { } } public JobStatistics save ( final JobStatistics obj ) throws HibernateException { if (obj == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "object")); } // if (obj.isNew()) { // return (JobStatistics) super.create(obj); // } // // return (JobStatistics) super.update(obj); return (JobStatistics) super.saveOrUpdate(obj); } // ====================[ TG Usage ]==================== // public TgUsage getTgUsage ( final Long id ) throws HibernateException { if (id == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "TG Usage ID")); } try { Criteria rootCriteria = super.getSession().createCriteria(TgUsage.class); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("tgusageId", id))); super.distinctRootEntityResults(rootCriteria); return (TgUsage) rootCriteria.uniqueResult(); } catch ( HibernateException e ) { throw e; } finally { } } public TgUsage getTgUsage ( final String resource, final String jobId, final Date submitTime ) throws HibernateException { List tgusages = retrieveTgUsage(resource, jobId, submitTime); if (tgusages != null && tgusages.size() > 1) { final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); throw new RuntimeException(String.format( "Result has more than one records of TgUsage for JobID=[%s] Resource=[%s] SubmitTime=[%s]", jobId, resource, sdf.format(submitTime))); } return (tgusages == null || tgusages.isEmpty())? null : tgusages.get(0); } private List retrieveTgUsage ( final String resource, final String jobId, final Date submitTime ) throws HibernateException { if (resource == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Resource")); } else if (jobId == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Job ID")); } else if (submitTime == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Submit time")); } try { Criteria rootCriteria = super.getSession().createCriteria(TgUsage.class); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("resource", resource))); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("jobId", jobId))); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("submitTime", submitTime))); super.distinctRootEntityResults(rootCriteria); return (List) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } public TgUsage save ( final TgUsage obj ) throws HibernateException { if (obj == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "object")); } // if (obj.isNew()) { // return (TgUsage) super.create(obj); // } // // return (TgUsage) super.update(obj); return (TgUsage) super.saveOrUpdate(obj); } // ====================[ XD Usage ]==================== // public XdUsage getXdUsage ( final Long id ) throws HibernateException { if (id == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "XD Usage ID")); } try { Criteria rootCriteria = super.getSession().createCriteria(XdUsage.class); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("xdusageId", id))); super.distinctRootEntityResults(rootCriteria); return (XdUsage) rootCriteria.uniqueResult(); } catch ( HibernateException e ) { throw e; } finally { } } public XdUsage getXdUsage ( final String resource, final String jobId, final Date submitTime ) throws HibernateException { List xdusages = retrieveXdUsage(resource, jobId, submitTime); if (xdusages != null && xdusages.size() > 1) { final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); throw new RuntimeException(String.format( "Result has more than one records of XdUsage for JobID=[%s] Resource=[%s] SubmitTime=[%s]", jobId, resource, sdf.format(submitTime))); } return (xdusages == null || xdusages.isEmpty())? null : xdusages.get(0); } private List retrieveXdUsage ( final String resource, final String jobId, final Date submitTime ) throws HibernateException { if (resource == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Resource")); } else if (jobId == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Job ID")); } else if (submitTime == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Submit time")); } try { Criteria rootCriteria = super.getSession().createCriteria(XdUsage.class); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("resource", resource))); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("jobId", jobId))); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("submitTime", submitTime))); super.distinctRootEntityResults(rootCriteria); return (List) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } public XdUsage save ( final XdUsage obj ) throws HibernateException { if (obj == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "object")); } return super.saveOrUpdate(obj); } // ====================[ XsedeAttributeReportingSchedule ]==================== // public XsedeAttributeReportingSchedule getSchedule ( Long scheduleId ) throws HibernateException { if (scheduleId == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Schedule ID")); } try { Criteria rootCriteria = super.getSession().createCriteria(XsedeAttributeReportingSchedule.class); rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("id", scheduleId))); super.distinctRootEntityResults(rootCriteria); return (XsedeAttributeReportingSchedule) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } public XsedeAttributeReportingSchedule getLastSchedule ( final Long taskId, final Integer runNumber ) throws HibernateException { if (taskId == null || taskId <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Task ID")); } else if (runNumber == null || runNumber <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Run number")); } List schedules = getSchedules( taskId, runNumber, 0, 1, // Last report time on top SortOrders.build().add( XsedeAttributeReportingSchedule.ORDER_BY_SCHEDULED_TIME_DESC) ); return (schedules == null || schedules.isEmpty()) ? null : schedules.get(0); } public List getSchedules ( final Long taskId, final Integer runNumber, final int firstResult, final int maxResults, final SortOrders sortOrders ) throws HibernateException { if (taskId == null || taskId <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Task ID")); } else if (runNumber == null || runNumber <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Run number")); } return retrieveXsedeAttributeReportingSchedules( null, // User taskId, runNumber, null, // XSEDE Job ID null, // scheduledTimeRange 0, // No particular status (ALL) 0, // Regardless of XsedeJobID present or non-present firstResult, maxResults, sortOrders); } public XsedeAttributeReportingSchedule getSchedule ( Long taskId, Integer runNumber, String xsedeJobId ) throws HibernateException { if (taskId == null || taskId <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Task ID")); } else if (runNumber == null || runNumber <= 0) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Run number")); } else if (StringUtils.isNullOrEmpty(xsedeJobId, true)) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "XSEDE Job ID")); } List schedules = retrieveXsedeAttributeReportingSchedules( null, // User taskId, runNumber, xsedeJobId, // XSEDE Job ID null, // scheduledTimeRange 0, // No particular status (ALL) 0, // Regardless of XsedeJobID present or non-present 0, 0, SortOrders.build().add(XsedeAttributeReportingSchedule.ORDER_BY_SCHEDULED_TIME_DESC)); return (schedules == null || schedules.isEmpty()) ? null : schedules.get(0); } public List getQueuedSchedulesBefore ( final Date onOrBeforeScheduledTime, final int xsedeJobIdStage, final int firstResult, final int maxResults, final SortOrders sortOrders ) throws HibernateException { if (onOrBeforeScheduledTime == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Date")); } final RangeValue scheduledTimeRange = new RangeValue<>(); scheduledTimeRange.atMost(onOrBeforeScheduledTime); return retrieveXsedeAttributeReportingSchedules( null, // User null, // Task ID null, // Run number null, // XSEDE Job ID scheduledTimeRange, QUEUED, // Schedule status xsedeJobIdStage, firstResult, maxResults, sortOrders); } public List getQueuedSchedulesAfter ( final Date onOrAfterScheduledTime, final int xsedeJobIdStage, final int firstResult, final int maxResults, final SortOrders sortOrders ) throws HibernateException { if (onOrAfterScheduledTime == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Date")); } final RangeValue scheduledTimeRange = new RangeValue<>(); scheduledTimeRange.atLeast(onOrAfterScheduledTime); return retrieveXsedeAttributeReportingSchedules( null, // User null, // Task ID null, // Run number null, // XSEDE Job ID scheduledTimeRange, QUEUED, // Schedule status xsedeJobIdStage, firstResult, maxResults, sortOrders); } public List getQueuedSchedules ( final RangeValue scheduledTimeRange, final int xsedeJobIdStage, final int firstResult, final int maxResults, final SortOrders sortOrders ) throws HibernateException { if (scheduledTimeRange == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Scheduled time range")); } return retrieveXsedeAttributeReportingSchedules( null, // User null, // Task ID null, // Run number null, // XSEDE Job ID scheduledTimeRange, QUEUED, // Schedule status xsedeJobIdStage, firstResult, maxResults, sortOrders); } public static final int QUEUED = 0x01; public static final int REPORTED = 0x02; public static final int XSEDE_JOBID_PRESENT = 0x01; public static final int XSEDE_JOBID_NON_PRESENT = 0x02; private List retrieveXsedeAttributeReportingSchedules ( final User user, final Long taskId, final Integer runNumber, final String xsedeJobId, final RangeValue scheduledTimeRange, final int status, // QUEUED | REPORTED final int xsedeJobIdStage, // PRESENT | NON-PRESENT final int firstResult, final int maxResults, final SortOrders sortOrders ) throws HibernateException { try { final SortOrders orderBy = (sortOrders != null) ? sortOrders : SortOrders.build().add( XsedeAttributeReportingSchedule.ORDER_BY_SCHEDULED_TIME_ASC); final Session session = super.getSession(); final Criteria rootCriteria = session.createCriteria( XsedeAttributeReportingSchedule.class); super.setSortOrders(rootCriteria, XsedeAttributeReportingSchedule.class, orderBy); if (taskId != null && taskId > 0) { rootCriteria.add(Restrictions.conjunction().add(Restrictions.eq("taskId", taskId))); } if (runNumber != null && runNumber > 0) { rootCriteria.add(Restrictions.conjunction().add( Restrictions.eq("taskRunNumber", runNumber))); } if (StringUtils.notNullAndNotEmpty(xsedeJobId, true)) { rootCriteria.add(Restrictions.conjunction().add( Restrictions.eq("xsedeJobId", xsedeJobId))); } else if (xsedeJobIdStage == XSEDE_JOBID_PRESENT) { rootCriteria.add(Restrictions.conjunction().add( Restrictions.isNotNull("xsedeJobId"))); } else if (xsedeJobIdStage == XSEDE_JOBID_NON_PRESENT) { rootCriteria.add(Restrictions.conjunction().add( Restrictions.isNull("xsedeJobId"))); } if (scheduledTimeRange != null) { rootCriteria.add(super.setRangeValues( Restrictions.conjunction(), "scheduledTime", scheduledTimeRange)); } if (status == QUEUED) { rootCriteria.add(Restrictions.conjunction().add( Restrictions.isNull("reportTime"))); } else if (status == REPORTED) { rootCriteria.add(Restrictions.conjunction().add( Restrictions.isNotNull("reportTime"))); } if (user != null) { final Criteria userCr = rootCriteria.createCriteria("user"); super.setSortOrders(userCr, User.class, orderBy); userCr.add(Restrictions.conjunction().add(Restrictions.eq("id", user.getId()))); } super.distinctRootEntityResults(rootCriteria); super.setLimit(rootCriteria, firstResult, maxResults); return (List) rootCriteria.list(); } catch ( HibernateException e ) { throw e; } finally { } } public XsedeAttributeReportingSchedule save ( final XsedeAttributeReportingSchedule obj ) throws HibernateException { if (obj == null) { throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "object")); } return super.saveOrUpdate(obj); } // public List // getJobStatisticsForXsedeAttributeReporting ( // final RangeValue jobsCreatedTimeRange, // Time interval where jobs are created/entered. // final int firstResult, // final int maxResults, // final SortOrders sortOrders ) throws HibernateException // { // if (jobsCreatedTimeRange == null) { // throw new IllegalArgumentException(String.format(ERR_PARAM_NULL_EMPTY, "Job created time range")); // } // // try { // final SortOrders orderBy = (sortOrders != null) ? sortOrders // : SortOrders.build().add(JobStatistics.ORDER_BY_DATE_ENTERED_ASC); // // Criteria rootCriteria = super.getSession().createCriteria(JobStatistics.class); // super.setSortOrders(rootCriteria, JobStatistics.class, orderBy); // // rootCriteria.add(super.setRangeValues(Restrictions.conjunction(), "dateEntered", jobsCreatedTimeRange)); // rootCriteria.add(Restrictions.conjunction().add(Restrictions.isNotNull("remoteJobId"))); // // // Distinct rows only. // super.distinctRootEntityResults(rootCriteria); // super.setLimit(rootCriteria, firstResult, maxResults); // return (List) rootCriteria.list(); // } // catch ( HibernateException e ) { // throw e; // } // finally { // } // } }