List of usage examples for org.hibernate Session createSQLQuery
@Override NativeQuery createSQLQuery(String queryString);
From source file:com.abiquo.abiserver.abicloudws.InfrastructureWS.java
License:Open Source License
@Override public BasicResult forceRefreshVirtualMachineState(final VirtualMachine virtualMachine) { logger.info("Forcing refresh of the virtual machine state: {}", virtualMachine.getId()); BasicResult result = new BasicResult(); VirtualappHB virtualappHBPojo = null; Session session = null; Transaction transaction = null;// www . j ava 2 s .c om try { session = HibernateUtil.getSession(); transaction = session.beginTransaction(); Query query = session.createSQLQuery(IDVIRTUALAPP_SQL_BY_VM); query.setString("id", virtualMachine.getId().toString()); Integer virtualApplianceId = (Integer) query.uniqueResult(); virtualappHBPojo = (VirtualappHB) session.get("VirtualappExtendedHB", virtualApplianceId); VirtualAppliance vapp = virtualappHBPojo.toPojo(); String virtualSystemMonitorAddress = RemoteServiceUtils.getVirtualSystemMonitorFromVA(vapp); // EventingSupport.subscribePullEventToVM(virtualMachine, virtualSystemMonitorAddress); } catch (PersistenceException e) { logger.trace("An error occurred when retrieving the VirtualSystemMonitor", e.getStackTrace()[0]); } catch (RemoteServiceException e) { logger.trace("An error occurred when contacting the VirtualSystemMonitor", e.getStackTrace()[0]); } result.setSuccess(true); return result; }
From source file:com.abiquo.abiserver.business.authentication.AuthenticationManagerDB.java
License:Open Source License
/** * gets a user from DB given the credentials. * /* ww w. j a v a 2 s . co m*/ * @param login The user credentials. * @param session The Hibernate session. * @return The user. */ private UserHB getUser(final Login login, final Session session) { // Checking if a user exists for the given credentials (remeber to check that the user String customQuery = "SELECT * FROM user WHERE user= :user AND password= :password"; Query query = session.createSQLQuery(customQuery).addEntity(UserHB.class); query.setString("user", login.getUser()); query.setString("password", login.getPassword()); return (UserHB) query.uniqueResult(); }
From source file:com.abiquo.abiserver.business.authentication.AuthenticationManagerDB.java
License:Open Source License
/** * Gets the user from DB using the authentication Token information. * /*from ww w . j av a2 s . co m*/ * @param login The object with the token information. * @param session The Hibernate session. * @return The user. */ private UserHB getUserUsingToken(final Login login, final Session session) throws Exception { // Get token data String[] token = TokenUtils.getTokenFields(login.getAuthToken()); String tokenUser = TokenUtils.getTokenUser(token); long tokenExpiration = TokenUtils.getTokenExpiration(token); String tokenSignature = TokenUtils.getTokenSignature(token); // Check token expiration if (TokenUtils.isTokenExpired(tokenExpiration)) { throw new Exception("Authentication token has expired."); } // Get the token user from db String customQuery = "SELECT * FROM user WHERE user= :user"; Query query = session.createSQLQuery(customQuery).addEntity(UserHB.class); query.setString("user", tokenUser); UserHB userHB = (UserHB) query.uniqueResult(); if (userHB != null) { // Validate credentials with the token String signature = TokenUtils.makeTokenSignature(tokenExpiration, userHB.getUser(), userHB.getPassword()); if (!signature.equals(tokenSignature)) { return null; } } return userHB; }
From source file:com.abiquo.abiserver.commands.impl.UserCommandImpl.java
License:Open Source License
@Override public BasicResult closeSessionUsers(final UserSession userSession, final ArrayList<User> users) { BasicResult basicResult = new BasicResult(); Session session = null; Transaction transaction = null;//from w w w . j av a 2s . c o m try { session = HibernateUtil.getSession(); transaction = session.beginTransaction(); // Generating the list of users for the query if (users.size() > 0) { String userNames = "("; User user; for (int i = 0; i < users.size(); i++) { user = users.get(i); if (i > 0) { userNames = userNames + "," + "'" + user.getUser() + "'"; } else { userNames = userNames + "'" + user.getUser() + "'"; } } userNames = userNames + ")"; // TODO use an HQL query instead of an SQL query session.createSQLQuery("DELETE FROM session WHERE user IN " + userNames).executeUpdate(); } transaction.commit(); // Generating result basicResult.setSuccess(true); basicResult.setMessage(resourceManager.getMessage("closeSessionUsers.success")); } catch (Exception e) { if (transaction != null && transaction.isActive()) { transaction.rollback(); } // Generating error errorManager.reportError(resourceManager, basicResult, "closeSessionUsers", e); } return basicResult; }
From source file:com.abiquo.abiserver.commands.UserCommand.java
License:Mozilla Public License
/** * Returns a list of users stored in the Data Base * /*from w w w .jav a 2 s . c o m*/ * @param userSession * @param userListOptions an UserListOptions object containing the options to retrieve the list * of users * @return A DataResult object containing an UserListResult object with an ArrayList of User and * the number of total users */ @SuppressWarnings("unchecked") protected DataResult<UserListResult> getUsers(UserSession userSession, UserListOptions userListOptions) { DataResult<UserListResult> dataResult = new DataResult<UserListResult>(); UserListResult userListResult = new UserListResult(); Session session = null; Transaction transaction = null; try { session = HibernateUtil.getSession(); transaction = session.beginTransaction(); // Getting the user that called this method UserHB userHB = (UserHB) session.createCriteria(UserHB.class) .add(Restrictions.eq("user", userSession.getUser())).uniqueResult(); // getUsers has two different authorization resources // If the user who called this method, does not match the security level for the // authorization resource // USER_GET_ALL_USERS, this method will only return those users who belongs to the same // enterprise than // the user that called this method // Getting the authorization resource USER_GET_ALL_USERS AuthResourceHB authResourceHB = (AuthResourceHB) session.createCriteria(AuthResourceHB.class) .add(Restrictions.eq("name", "USER_GET_ALL_USERS")).uniqueResult(); // Checking if the user has not the necessary security level to see the whole list of // Users. If so, we force // the userListOptions object to filter by the enterprise assigned to the user if (authResourceHB.getRoleHB().getSecurityLevel() .compareTo(userHB.getRoleHB().getSecurityLevel()) == -1) { // NOT GRANTED! userListOptions.setByEnterprise((Enterprise) userHB.getEnterpriseHB().toPojo()); } // Creating users criteria Criteria usersListCriteria = session.createCriteria(UserHB.class); Criteria usersCountCriteria = session.createCriteria(UserHB.class); // Removing the users that are deleted usersListCriteria.add(Restrictions.eq("deleted", 0)); usersCountCriteria.add(Restrictions.eq("deleted", 0)); // Adding filter by name, surname or email Disjunction filterDisjunction = Restrictions.disjunction(); if (userListOptions.getFilter().length() > 0) { filterDisjunction.add(Restrictions.like("name", '%' + userListOptions.getFilter() + '%')); filterDisjunction.add(Restrictions.like("surname", '%' + userListOptions.getFilter() + '%')); filterDisjunction.add(Restrictions.like("email", '%' + userListOptions.getFilter() + '%')); } usersListCriteria.add(filterDisjunction); usersCountCriteria.add(filterDisjunction); // Adding filter by Enterprise if (userListOptions.getByEnterprise() != null) { usersListCriteria.add(Restrictions.eq("enterpriseHB", (EnterpriseHB) userListOptions.getByEnterprise().toPojoHB())); usersCountCriteria.add(Restrictions.eq("enterpriseHB", (EnterpriseHB) userListOptions.getByEnterprise().toPojoHB())); } // Adding order // Little fix to match the object used in Hibernate if (userListOptions.getOrderBy().compareTo("role") == 0) userListOptions.setOrderBy("roleHB"); Order order; if (userListOptions.getAsc()) order = Order.asc(userListOptions.getOrderBy()); else order = Order.desc(userListOptions.getOrderBy()); usersListCriteria.addOrder(order); usersCountCriteria.addOrder(order); // Adding filter to get only the users that currently have an active session if (userListOptions.getLoggedOnly()) { ArrayList<String> currentLoggedUsers = (ArrayList<String>) session .createSQLQuery("SELECT user FROM session WHERE expireDate > CURRENT_TIMESTAMP()").list(); usersListCriteria.add(Restrictions.in("user", currentLoggedUsers)); usersCountCriteria.add(Restrictions.in("user", currentLoggedUsers)); } // Once we have the criteria... // 1. Getting the total number of users that match userListOptions Integer totalUsers = (Integer) usersCountCriteria.setProjection(Projections.rowCount()).uniqueResult(); // 2. Getting the list of users, applying an offset and a max of results ArrayList<UserHB> usersHB = (ArrayList<UserHB>) usersListCriteria .setFirstResult(userListOptions.getOffset()).setMaxResults(userListOptions.getLength()).list(); // Building result ArrayList<User> usersList = new ArrayList<User>(); for (UserHB userToReturnHB : usersHB) { usersList.add((User) userToReturnHB.toPojo()); } userListResult.setTotalUsers(totalUsers); userListResult.setUsersList(usersList); transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) transaction.rollback(); this.errorManager.reportError(resourceManager, dataResult, "getUsers", e); return dataResult; } dataResult.setData(userListResult); dataResult.setSuccess(true); dataResult.setMessage(UserCommand.resourceManager.getMessage("getUsers.success")); return dataResult; }
From source file:com.abiquo.abiserver.commands.UserCommand.java
License:Mozilla Public License
/** * Closes any existing session for the given users * @param userSession/* w ww . j a va 2s . c o m*/ * @param users The list of users whose session will be closed * @return A BasicResult object, informing if the operation had success */ protected BasicResult closeSessionUsers(UserSession userSession, ArrayList<User> users) { BasicResult basicResult = new BasicResult(); Session session = null; Transaction transaction = null; try { session = HibernateUtil.getSession(); transaction = session.beginTransaction(); //Generating the list of users for the query if (users.size() > 0) { String userNames = "("; User user; for (int i = 0; i < users.size(); i++) { user = users.get(i); if (i > 0) userNames = userNames + "," + "'" + user.getUser() + "'"; else userNames = userNames + "'" + user.getUser() + "'"; } userNames = userNames + ")"; //TODO use an HQL query instead of an SQL query session.createSQLQuery("DELETE FROM session WHERE user IN " + userNames).executeUpdate(); } transaction.commit(); //Generating result basicResult.setSuccess(true); basicResult.setMessage(UserCommand.resourceManager.getMessage("closeSessionUsers.success")); } catch (Exception e) { if (transaction != null && transaction.isActive()) transaction.rollback(); //Generating error this.errorManager.reportError(resourceManager, basicResult, "closeSessionUsers", e); } return basicResult; }
From source file:com.abiquo.abiserver.persistence.dao.infrastructure.hibernate.DataCenterDAOHibernate.java
License:Open Source License
@Override public Long getNumberStorageDevicesByDatacenter(final Integer idDatacenter) { Long numberOfStorageDevices;// ww w . j a v a 2s.c o m final Session session = HibernateDAOFactory.getSessionFactory().getCurrentSession(); final Query sdQuery = session .createSQLQuery("select count(sd.id) from storage_device sd where sd.idDataCenter = :idDataCenter"); sdQuery.setInteger("idDataCenter", idDatacenter); numberOfStorageDevices = ((BigInteger) sdQuery.list().get(0)).longValue(); return numberOfStorageDevices; }
From source file:com.abiquo.abiserver.persistence.dao.infrastructure.hibernate.DataCenterDAOHibernate.java
License:Open Source License
@Override public void updateUsedResourcesByDatacenter(final Integer idDatacenter) { final Session session = HibernateDAOFactory.getSessionFactory().getCurrentSession(); final String update = "update physicalmachine p, " + "(SELECT hy.idPhysicalMachine, IFNULL(SUM(vm.ram),0) ram, IFNULL(SUM(vm.cpu),0) cpu " + "FROM virtualmachine vm right join hypervisor hy on vm.idHypervisor = hy.id, " + "physicalmachine pm, rack r " + "WHERE (vm.state is null or vm.state != 'NOT_DEPLOYED') AND pm.idPhysicalMachine = hy.idPhysicalMachine " + "AND pm.idRack = r.idRack AND r.idDatacenter = :idDatacenter " + "group by hy.idPhysicalMachine) x " + "SET p.ramused = x.ram, p.cpuused = x.cpu where p.idPhysicalMachine = x.idPhysicalMachine "; final Query pmQuery = session.createSQLQuery(update); pmQuery.setInteger("idDatacenter", idDatacenter); pmQuery.executeUpdate();//from ww w . j a v a 2 s . c om }
From source file:com.abiquo.abiserver.persistence.dao.infrastructure.hibernate.DataCenterDAOHibernate.java
License:Open Source License
@Override public long getCurrentStorageAllocated(final int idEnterprise, final int idDatacenter) { Session session = HibernateDAOFactory.getSessionFactory().getCurrentSession(); BigDecimal storage = (BigDecimal) session.createSQLQuery(SUM_STORAGE_RESOURCES) .setParameter("datacenterId", idDatacenter).setParameter("enterpriseId", idEnterprise) .uniqueResult();//from ww w. j av a2 s. c o m return storage == null ? 0 : storage.longValue() * MB_TO_BYTES; }
From source file:com.abiquo.abiserver.persistence.dao.infrastructure.hibernate.DataCenterDAOHibernate.java
License:Open Source License
@Override public long getCurrentPublicIpAllocated(final int idEnterprise, final int idDatacenter) { Session session = HibernateDAOFactory.getSessionFactory().getCurrentSession(); BigInteger publicIps = (BigInteger) session.createSQLQuery(COUNT_IP_RESOURCES) .setParameter("datacenterId", idDatacenter).setParameter("enterpriseId", idEnterprise) .uniqueResult();/*from w w w . j ava2s . c om*/ return publicIps == null ? 0 : publicIps.longValue(); }