Example usage for org.hibernate.type LongType LongType

List of usage examples for org.hibernate.type LongType LongType

Introduction

In this page you can find the example usage for org.hibernate.type LongType LongType.

Prototype

public LongType() 

Source Link

Usage

From source file:org.squashtest.tm.service.internal.repository.hibernate.HibernateEntityDao.java

License:Open Source License

@SuppressWarnings("unchecked")
protected List<Long> findDescendantIds(List<Long> params, String sql) {
    if (!params.isEmpty()) {
        Session session = currentSession();

        List<BigInteger> list;
        List<Long> result = new ArrayList<>();
        result.addAll(params); // the inputs are also part of the output.
        List<Long> local = params;

        do {//from   w  w  w  .j a  v  a  2  s  .  c o m
            Query sqlQuery = session.createSQLQuery(sql);
            sqlQuery.setParameterList("list", local, new LongType());
            list = sqlQuery.list();
            if (!list.isEmpty()) {
                local.clear();
                for (BigInteger bint : list) {
                    local.add(bint.longValue());
                    result.add(bint.longValue());
                }
            }
        } while (!list.isEmpty());
        if (result.isEmpty()) {
            return null;
        }
        return result;

    } else {
        return Collections.emptyList();

    }

}

From source file:org.squashtest.tm.service.internal.repository.hibernate.SetLibraryIdsCallback.java

License:Open Source License

@Override
public void setQueryParameters(Query query) {
    query.setParameterList("libraryIds", libraryIds, new LongType());
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.SetParamIdsParametersCallback.java

License:Open Source License

@Override
public void setQueryParameters(Query query) {
    query.setParameterList("paramIds", params, new LongType());
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.SetProjectIdsParameterCallback.java

License:Open Source License

@Override
public void setQueryParameters(Query query) {
    query.setParameterList(ParameterNames.PROJECT_IDS, projectIds, new LongType());
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.TestCaseDaoImpl.java

License:Open Source License

private List<NamedReferencePair> findTestCaseCallsDetails(final Collection<Long> testCaseIds,
        String mainQuery) {/*from w  ww .  j a  v a2  s . c o  m*/
    if (testCaseIds.isEmpty()) {
        return Collections.emptyList();
    }

    // the easy part : fetch the informations for those who are called
    SetQueryParametersCallback queryCallback = new SetQueryParametersCallback() {
        @Override
        public void setQueryParameters(Query query) {
            query.setParameterList(TEST_CASE_IDS_PARAM_NAME, testCaseIds, new LongType());
            query.setReadOnly(true);
        }
    };

    return executeListNamedQuery(mainQuery, queryCallback);

}

From source file:org.unitime.banner.util.BannerMessageIdGenerator.java

License:Apache License

public static IdentifierGenerator getGenerator() throws HibernateException {
    try {/*  w ww . j ava2  s.c  o m*/
        if (sGenerator != null)
            return sGenerator;
        UniqueIdGenerator idGen = new UniqueIdGenerator();
        Dialect dialect = (Dialect) Class
                .forName(LocationDAO.getConfiguration().getProperty("hibernate.dialect"))
                .getConstructor(new Class[] {}).newInstance(new Object[] {});
        Type type = new LongType();
        Properties params = new Properties();
        params.put(SequenceGenerator.SEQUENCE, sSequence);
        params.put(PersistentIdentifierGenerator.SCHEMA,
                _RootDAO.getConfiguration().getProperty("default_schema"));
        idGen.configure(type, params, dialect);
        sGenerator = idGen;
        return sGenerator;
    } catch (HibernateException e) {
        throw e;
    } catch (Exception e) {
        throw new HibernateException(e);
    }
}

From source file:org.unitime.timetable.events.EventEmail.java

License:Open Source License

public void send(SessionContext context) throws UnsupportedEncodingException, MessagingException {
    try {/*  w  w w.j a va2  s. co m*/
        if (!request().isEmailConfirmation())
            return;

        if (ApplicationProperty.EmailConfirmationEvents.isFalse()) {
            response().info(MESSAGES.emailDisabled());
            return;
        }

        Email email = Email.createEmail();
        if (event().hasContact() && event().getContact().getEmail() != null
                && !event().getContact().getEmail().isEmpty())
            email.addRecipient(event().getContact().getEmail(), event().getContact().getName(MESSAGES));
        if (event().hasAdditionalContacts()) {
            for (ContactInterface contact : event().getAdditionalContacts()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipient(contact.getEmail(), contact.getName(MESSAGES));
            }
        }
        if (event().hasSponsor() && event().getSponsor().hasEmail())
            email.addRecipientCC(event().getSponsor().getEmail(), event().getSponsor().getName());
        if (event().hasEmail()) {
            String suffix = ApplicationProperty.EmailDefaultAddressSuffix.value();
            for (String address : event().getEmail().split("[\n,]")) {
                if (!address.trim().isEmpty()) {
                    if (suffix != null && address.indexOf('@') < 0)
                        email.addRecipientCC(address.trim() + suffix, null);
                    else
                        email.addRecipientCC(address.trim(), null);
                }
            }
        }
        if (event().hasInstructors() && ApplicationProperty.EmailConfirmationEventInstructors.isTrue()) {
            for (ContactInterface contact : event().getInstructors()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipientCC(contact.getEmail(), contact.getName(MESSAGES));
            }
        }
        if (event().hasCoordinators() && ApplicationProperty.EmailConfirmationEventCoordinators.isTrue()) {
            for (ContactInterface contact : event().getCoordinators()) {
                if (contact.getEmail() != null && !contact.getEmail().isEmpty())
                    email.addRecipientCC(contact.getEmail(), contact.getName(MESSAGES));
            }
        }

        if (ApplicationProperty.EmailConfirmationEventManagers.isTrue()) {
            Set<Long> locationIds = new HashSet<Long>();
            if (event().hasMeetings()) {
                for (MeetingInterface m : event().getMeetings()) {
                    if (m.hasLocation())
                        locationIds.add(m.getLocation().getId());
                }
            }
            if (response().hasDeletedMeetings()) {
                for (MeetingInterface m : response().getDeletedMeetings())
                    if (m.hasLocation())
                        locationIds.add(m.getLocation().getId());
            }
            org.hibernate.Session hibSession = SessionDAO.getInstance().getSession();
            NameFormat nf = NameFormat.fromReference(context.getUser().getProperty(UserProperty.NameFormat));
            for (TimetableManager m : (List<TimetableManager>) hibSession.createQuery(
                    "select distinct m from Location l inner join l.eventDepartment.timetableManagers m inner join m.managerRoles r where "
                            + "l.uniqueId in :locationIds and m.emailAddress is not null and r.receiveEmails = true and :permission in elements (r.role.rights)")
                    .setParameterList("locationIds", locationIds, new LongType())
                    .setString("permission", Right.EventLookupContact.name()).list()) {
                email.addRecipientCC(m.getEmailAddress(), nf.format(m));
            }
        }

        if (replyTo() != null) {
            email.setReplyTo(replyTo().getAddress(), replyTo().getPersonal());
        } else if (context != null && context.isAuthenticated() && context.getUser().getEmail() != null) {
            email.setReplyTo(context.getUser().getEmail(), context.getUser().getName());
        } else {
            email.setReplyTo(event().getContact().getEmail(), event().getContact().getName(MESSAGES));
        }

        if (event().getId() != null && ApplicationProperty.InboundEmailsEnabled.isTrue()
                && ApplicationProperty.InboundEmailsReplyToAddress.value() != null) {
            email.setSubject("[EVENT-" + Long.toHexString(event().getId()) + "] " + event().getName() + " ("
                    + event().getType().getName(CONSTANTS) + ")");
            email.addReplyTo(ApplicationProperty.InboundEmailsReplyToAddress.value(),
                    ApplicationProperty.InboundEmailsReplyToAddressName.value());
        } else {
            email.setSubject(event().getName() + " (" + event().getType().getName(CONSTANTS) + ")");
        }

        if (context != null) {
            final FileItem file = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE);
            if (file != null) {
                email.addAttachement(new DataSource() {
                    @Override
                    public OutputStream getOutputStream() throws IOException {
                        throw new IOException("No output stream.");
                    }

                    @Override
                    public String getName() {
                        return file.getName();
                    }

                    @Override
                    public InputStream getInputStream() throws IOException {
                        return file.getInputStream();
                    }

                    @Override
                    public String getContentType() {
                        return file.getContentType();
                    }
                });
            }
        }

        if (attachment() != null)
            email.addAttachement(attachment());

        final String ical = icalendar();
        if (ical != null) {
            email.addAttachement(new DataSource() {
                @Override
                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("No output stream.");
                }

                @Override
                public String getName() {
                    return "event.ics";
                }

                @Override
                public InputStream getInputStream() throws IOException {
                    return new ByteArrayInputStream(ical.getBytes("UTF-8"));
                }

                @Override
                public String getContentType() {
                    return "text/calendar; charset=UTF-8";
                }
            });
        }

        email.setHTML(message());

        Long eventId = (response().hasEventWithId() ? response().getEvent().getId()
                : request().getEvent().getId());
        if (eventId != null) {
            String messageId = sMessageId.get(eventId);
            if (messageId != null)
                email.setInReplyTo(messageId);
        }

        email.send();

        if (eventId != null) {
            String messageId = email.getMessageId();
            if (messageId != null)
                sMessageId.put(eventId, messageId);
        }

        response().info(MESSAGES.infoConfirmationEmailSent(
                event().hasContact() ? event().getContact().getName(MESSAGES) : "?"));
    } catch (Exception e) {
        response().error(MESSAGES.failedToSendConfirmationEmail(e.getMessage()));
        sLog.warn(MESSAGES.failedToSendConfirmationEmail(e.getMessage()), e);
    }
}

From source file:org.unitime.timetable.server.solver.TimetableGridSolutionHelper.java

License:Apache License

public static TimetableGridModel createModel(String solutionIdsStr, StudentGroupInfo g,
        org.hibernate.Session hibSession, TimetableGridContext context) {
    TimetableGridModel model = new TimetableGridModel(ResourceType.STUDENT_GROUP.ordinal(), g.getGroupId());
    model.setName(g.getGroupName());//from w w w.ja  v  a 2s  .  c o m
    model.setFirstDay(context.getFirstDay());
    model.setFirstSessionDay(context.getFirstSessionDay());
    model.setFirstDate(context.getFirstDate());

    List<Long> classIds = new ArrayList<Long>();
    for (StudentGroupInfo.ClassInfo clazz : g.getGroupAssignments())
        classIds.add(clazz.getClassId());
    if (classIds.isEmpty())
        return null;

    Query q = hibSession.createQuery("select distinct a from Assignment a where a.solution.uniqueId in ("
            + solutionIdsStr + ") and a.classId in (:classIds)");
    q.setParameterList("classIds", classIds, new LongType());
    q.setCacheable(true);
    List assignments = q.list();
    model.setSize((int) Math.round(g.countStudentWeights()));

    for (Iterator i = assignments.iterator(); i.hasNext();) {
        Assignment assignment = (Assignment) i.next();
        List<TimetableGridCell> cells = createCells(model, assignment, hibSession, context, false);
        StudentGroupInfo.ClassInfo ci = g.getGroupAssignment(assignment.getClassId());
        if (ci != null) {
            int total = g.countStudentsOfOffering(assignment.getClazz().getSchedulingSubpart()
                    .getInstrOfferingConfig().getInstructionalOffering().getUniqueId());
            for (TimetableGridCell cell : cells) {
                cell.setGroup("(" + Math.round(ci.countStudentsWeight()) + ")");
                if (ci.getStudents() != null && !ci.getStudents().isEmpty() && total > 1) {
                    int assigned = ci.getStudents().size();
                    int minLimit = assignment.getClazz().getExpectedCapacity();
                    int maxLimit = assignment.getClazz().getMaxExpectedCapacity();
                    int limit = maxLimit;
                    if (minLimit < maxLimit) {
                        int roomLimit = (int) Math.floor(assignment.getPlacement().getRoomSize()
                                / (assignment.getClazz().getRoomRatio() == null ? 1.0f
                                        : assignment.getClazz().getRoomRatio()));
                        // int roomLimit = Math.round((c.getRoomRatio() == null ? 1.0f : c.getRoomRatio()) * p.getRoomSize());
                        limit = Math.min(Math.max(minLimit, roomLimit), maxLimit);
                    }
                    if (assignment.getClazz().getSchedulingSubpart().getInstrOfferingConfig()
                            .isUnlimitedEnrollment() || limit >= 9999)
                        limit = Integer.MAX_VALUE;
                    int p = 100 * assigned / Math.min(limit, total);
                    cell.setBackground(percentage2color(p));
                    cell.setPreference(assigned + " of " + total);
                }
            }
        }
    }
    model.setUtilization(g.getGroupValue());

    return model;
}

From source file:ubic.gemma.persistence.service.expression.designElement.CompositeSequenceDaoImpl.java

License:Apache License

@Override
public Map<CompositeSequence, Collection<Gene>> getGenes(Collection<CompositeSequence> compositeSequences) {
    Map<CompositeSequence, Collection<Gene>> returnVal = new HashMap<>();

    int BATCH_SIZE = 2000;

    if (compositeSequences.size() == 0)
        return returnVal;

    /*/*from   w w w  .ja v a 2s . c  o  m*/
     * Get the cs->gene mapping
     */
    final String nativeQuery = "SELECT CS, GENE FROM GENE2CS WHERE CS IN (:csids) ";

    for (CompositeSequence cs : compositeSequences) {
        returnVal.put(cs, new HashSet<Gene>());
    }

    List<Object> csGene = new ArrayList<>();
    Session session = this.getSessionFactory().getCurrentSession();
    org.hibernate.SQLQuery queryObject = session.createSQLQuery(nativeQuery);
    queryObject.addScalar("cs", new LongType());
    queryObject.addScalar("gene", new LongType());

    Collection<Long> csIdBatch = new HashSet<>();
    for (CompositeSequence cs : compositeSequences) {
        csIdBatch.add(cs.getId());

        if (csIdBatch.size() == BATCH_SIZE) {
            queryObject.setParameterList("csids", csIdBatch);
            csGene.addAll(queryObject.list());
            session.clear();
            csIdBatch.clear();
        }
    }

    if (csIdBatch.size() > 0) {
        queryObject.setParameterList("csids", csIdBatch);
        csGene.addAll(queryObject.list());
        session.clear();
    }

    StopWatch watch = new StopWatch();
    watch.start();

    int count = 0;
    Collection<Long> genesToFetch = new HashSet<>();
    Map<Long, Collection<Long>> cs2geneIds = new HashMap<>();

    for (Object object : csGene) {
        Object[] ar = (Object[]) object;
        Long cs = (Long) ar[0];
        Long gene = (Long) ar[1];
        if (!cs2geneIds.containsKey(cs)) {
            cs2geneIds.put(cs, new HashSet<Long>());
        }
        cs2geneIds.get(cs).add(gene);
        genesToFetch.add(gene);
    }

    // nothing found?
    if (genesToFetch.size() == 0) {
        returnVal.clear();
        return returnVal;
    }

    if (AbstractDao.log.isDebugEnabled())
        AbstractDao.log.debug("Built cs -> gene map in " + watch.getTime() + " ms; fetching "
                + genesToFetch.size() + " genes.");

    // fetch the genes
    Collection<Long> batch = new HashSet<>();
    Collection<Gene> genes = new HashSet<>();
    String geneQuery = "from Gene g where g.id in ( :gs )";

    org.hibernate.Query geneQueryObject = this.getSessionFactory().getCurrentSession().createQuery(geneQuery)
            .setFetchSize(1000);

    for (Long gene : genesToFetch) {
        batch.add(gene);
        if (batch.size() == BATCH_SIZE) {
            AbstractDao.log.debug("Processing batch ... ");
            geneQueryObject.setParameterList("gs", batch);
            //noinspection unchecked
            genes.addAll(geneQueryObject.list());
            batch.clear();
        }
    }

    if (batch.size() > 0) {
        geneQueryObject.setParameterList("gs", batch);
        //noinspection unchecked
        genes.addAll(geneQueryObject.list());
    }

    if (AbstractDao.log.isDebugEnabled())
        AbstractDao.log.debug("Got information on " + genes.size() + " genes in " + watch.getTime() + " ms");

    Map<Long, Gene> geneIdMap = new HashMap<>();
    for (Gene g : genes) {
        Hibernate.initialize(g);
        Long id = g.getId();
        geneIdMap.put(id, g);
    }

    // fill in the return value.
    for (CompositeSequence cs : compositeSequences) {
        Long csId = cs.getId();
        assert csId != null;
        Collection<Long> genesToAttach = cs2geneIds.get(csId);
        if (genesToAttach == null) {
            // this means there was no gene for that cs; we should remove it from the result
            returnVal.remove(cs);
            continue;
        }
        for (Long geneId : genesToAttach) {
            returnVal.get(cs).add(geneIdMap.get(geneId));
        }
        ++count;
    }

    if (AbstractDao.log.isDebugEnabled())
        AbstractDao.log.debug("Done, " + count + " result rows processed, " + returnVal.size() + "/"
                + compositeSequences.size() + " probes are associated with genes");
    return returnVal;
}

From source file:ubic.gemma.persistence.service.expression.experiment.ExpressionExperimentDaoImpl.java

License:Apache License

@Override
public Collection<ExpressionExperiment> findByExpressedGene(Gene gene, Double rank) {

    //language=MySQL
    final String queryString = "SELECT DISTINCT ee.ID AS eeID FROM "
            + "GENE2CS g2s, COMPOSITE_SEQUENCE cs, PROCESSED_EXPRESSION_DATA_VECTOR dedv, INVESTIGATION ee "
            + "WHERE g2s.CS = cs.ID AND cs.ID = dedv.DESIGN_ELEMENT_FK AND dedv.EXPRESSION_EXPERIMENT_FK = ee.ID"
            + " AND g2s.gene = :geneID AND dedv.RANK_BY_MEAN >= :rank";

    Collection<Long> eeIds;

    try {/*from  w  w  w  .  ja v  a 2  s . c o  m*/
        Session session = this.getSessionFactory().getCurrentSession();
        org.hibernate.SQLQuery queryObject = session.createSQLQuery(queryString);
        queryObject.setLong("geneID", gene.getId());
        queryObject.setDouble("rank", rank);
        queryObject.addScalar("eeID", new LongType());
        ScrollableResults results = queryObject.scroll();

        eeIds = new HashSet<>();

        // Post Processing
        while (results.next())
            eeIds.add(results.getLong(0));

        session.clear();
    } catch (org.hibernate.HibernateException ex) {
        throw super.convertHibernateAccessException(ex);
    }

    return this.load(eeIds);
}