Example usage for org.hibernate Session persist

List of usage examples for org.hibernate Session persist

Introduction

In this page you can find the example usage for org.hibernate Session persist.

Prototype

void persist(Object object);

Source Link

Document

Make a transient instance persistent.

Usage

From source file:com.griddynamics.jagger.engine.e1.aggregator.workload.DurationLogProcessor.java

License:Open Source License

private void processLog(String sessionId, String taskId) {
    try {//from w  ww  . j ava 2s  .  c o m
        String dir = sessionId + File.separatorChar + taskId + File.separatorChar
                + DurationCollector.DURATION_MARKER;
        String file = dir + File.separatorChar + "aggregated.dat";
        AggregationInfo aggregationInfo = logAggregator.chronology(dir, file);

        if (aggregationInfo.getCount() == 0) {
            //no data collected
            return;
        }

        int intervalSize = intervalSizeProvider.getIntervalSize(aggregationInfo.getMinTime(),
                aggregationInfo.getMaxTime());
        if (intervalSize < 1) {
            intervalSize = 1;
        }

        TaskData taskData = getTaskData(taskId, sessionId);
        if (taskData == null) {
            log.error("TaskData not found by taskId: {}", taskId);
            return;
        }

        StatisticsGenerator statisticsGenerator = new StatisticsGenerator(file, aggregationInfo, intervalSize,
                taskData).generate();
        final Collection<TimeInvocationStatistics> statistics = statisticsGenerator.getStatistics();
        final WorkloadProcessDescriptiveStatistics workloadProcessDescriptiveStatistics = statisticsGenerator
                .getWorkloadProcessDescriptiveStatistics();

        log.info("BEGIN: Save to data base " + dir);
        getHibernateTemplate().execute(new HibernateCallback<Void>() {
            @Override
            public Void doInHibernate(Session session) throws HibernateException, SQLException {
                for (TimeInvocationStatistics stat : statistics) {
                    session.persist(stat);
                }
                session.persist(workloadProcessDescriptiveStatistics);
                session.flush();
                return null;
            }
        });
        log.info("END: Save to data base " + dir);

    } catch (Exception e) {
        log.error("Error during log processing", e);
    }

}

From source file:com.griddynamics.jagger.engine.e1.aggregator.workload.MetricLogProcessor.java

License:Open Source License

private void processLog(String sessionId, String taskId) {

    try {//from  w  w  w .j  a v a  2 s . c  o m
        TaskData taskData = getTaskData(taskId, sessionId);
        if (taskData == null) {
            log.error("TaskData not found by taskId: {}", taskId);
            return;
        }
        String dir = sessionId + File.separatorChar + taskId + File.separatorChar
                + MetricCollector.METRIC_MARKER + File.separatorChar;
        Set<String> metrics = fileStorage.getFileNameList(dir);

        for (String metricPath : metrics) {
            try {
                String file = metricPath + File.separatorChar + "aggregated.dat";
                AggregationInfo aggregationInfo = logAggregator.chronology(metricPath, file);

                if (aggregationInfo.getCount() == 0) {
                    //metric not collected
                    return;
                }
                int intervalSize = intervalSizeProvider.getIntervalSize(aggregationInfo.getMinTime(),
                        aggregationInfo.getMaxTime());
                if (intervalSize < 1) {
                    intervalSize = 1;
                }
                StatisticsGenerator statisticsGenerator = new StatisticsGenerator(file, aggregationInfo,
                        intervalSize, taskData).generate();
                final Collection<MetricPointEntity> statistics = statisticsGenerator.getStatistics();

                log.info("BEGIN: Save to data base " + metricPath);
                getHibernateTemplate().execute(new HibernateCallback<Void>() {
                    @Override
                    public Void doInHibernate(Session session) throws HibernateException, SQLException {
                        for (MetricPointEntity stat : statistics) {
                            session.persist(stat);
                        }
                        session.flush();
                        return null;
                    }
                });
                log.info("END: Save to data base " + metricPath);
            } catch (Exception e) {
                log.error("Error during processing metric by path: '{}'", metricPath);
            }
        }

    } catch (Exception e) {
        log.error("Error during log processing", e);
    }

}

From source file:com.griddynamics.jagger.engine.e1.aggregator.workload.ProfilerLogProcessor.java

License:Open Source License

private void saveProfiles(final String sessionId, final String taskId) throws IOException {
    String dir;/*from ww w . j a v  a 2 s.  c o  m*/
    dir = sessionId + "/" + taskId + "/" + MonitorProcess.PROFILER_MARKER;

    Set<String> fileNameList = fileStorage.getFileNameList(dir);
    if (fileNameList.isEmpty()) {
        log.debug("Directory {} is empty.", dir);
        return;
    }
    for (final String fileName : fileNameList) {
        LogReader.FileReader reader;
        try {
            reader = logReader.read(fileName, Object.class);
        } catch (IllegalArgumentException e) {
            log.warn(e.getMessage(), e);
            return;
        }
        final ProfileDTO profileDTO = SerializationUtils.fromString(reader.iterator().next().toString());

        getHibernateTemplate().execute(new HibernateCallback<Void>() {
            @Override
            public Void doInHibernate(Session session) throws HibernateException, SQLException {
                String prefix = "Agent on (" + profileDTO.getHostAddress() + ") : ";
                for (Map.Entry<String, RuntimeGraph> runtimeGraphEntry : profileDTO.getRuntimeGraphs()
                        .entrySet()) {
                    String context = SerializationUtils.toString(runtimeGraphEntry.getValue());
                    session.persist(new ProfilingSuT(prefix + runtimeGraphEntry.getKey(), sessionId,
                            getTaskData(taskId, sessionId), context));
                }
                session.flush();
                return null;
            }
        });
    }
}

From source file:com.griddynamics.jagger.engine.e1.sessioncomparation.limits.LimitsBasedFeatureComparator.java

License:Open Source License

@Override
public List<Verdict<String>> compare(String currentSession, String baselineSession) {

    Decision decisionPerSession;/*from ww  w. ja  va  2s  .  co m*/

    // If decision already taken => use it
    // Such case can occur, f.e. when Jagger is running in reporter mode
    Map<String, Decision> decisionPerSessionMap = databaseService
            .getDecisionsPerSession(new HashSet<String>(Arrays.asList(currentSession)));
    if (decisionPerSessionMap.containsKey(currentSession)) {
        decisionPerSession = decisionPerSessionMap.get(currentSession);
        log.info("Decision '{}' was fetched from database for session {}", decisionPerSession, currentSession);
    } else {

        WorstCaseDecisionMaker worstCaseDecisionMaker = new WorstCaseDecisionMaker();

        // Get tests ids
        // matching setup = no matching
        SessionMatchingSetup sessionMatchingSetup = new SessionMatchingSetup(false,
                Collections.<SessionMatchingSetup.MatchBy>emptySet());
        List<TaskDataDto> taskDataDtoList = databaseService.getTaskDataForSessions(
                new HashSet<String>(Arrays.asList(currentSession)), sessionMatchingSetup);
        Set<Long> testIds = new HashSet<Long>();
        for (TaskDataDto taskDataDto : taskDataDtoList) {
            testIds.addAll(taskDataDto.getIds());
        }

        // Get test group ids
        Set<Long> testGroupIds = databaseService.getTestGroupIdsByTestIds(testIds).keySet();

        // Get decisions for test groups
        Set<TaskDecisionDto> taskDecisionDtoSet = databaseService.getDecisionsPerTask(testGroupIds);
        List<Decision> testGroupDecisions = new ArrayList<Decision>();
        for (TaskDecisionDto taskDecisionDto : taskDecisionDtoSet) {
            testGroupDecisions.add(taskDecisionDto.getDecision());
        }

        // Make decision per session
        decisionPerSession = worstCaseDecisionMaker.getDecision(testGroupDecisions);
        log.info("Decision '{}' was made for session {}", decisionPerSession, currentSession);

        // Save decision per session
        final DecisionPerSessionEntity decisionPerSessionEntity = new DecisionPerSessionEntity(currentSession,
                decisionPerSession.toString());

        getHibernateTemplate().execute(new HibernateCallback<Void>() {
            @Override
            public Void doInHibernate(Session session) throws HibernateException, SQLException {
                session.persist(decisionPerSessionEntity);
                session.flush();
                return null;
            }
        });
    }

    List<Verdict<String>> verdicts = Lists.newArrayList();
    verdicts.add(new Verdict<String>("Decision per session based on comparing metrics to limits",
            decisionPerSession, ""));
    return verdicts;
}

From source file:com.griddynamics.jagger.monitoring.MonitoringAggregator.java

License:Open Source License

private void aggregateLogs(String sessionId, String taskId) {
    String dir = sessionId + "/" + taskId + "/" + LoggingMonitoringProcessor.MONITORING_MARKER;
    String aggregatedFile = dir + "/aggregated.dat";
    try {//from w w w .  ja  va2s .co m
        AggregationInfo aggregationInfo = logAggregator.chronology(dir, aggregatedFile);

        if (aggregationInfo.getCount() == 0) {
            //metric not collected
            return;
        }

        int intervalSize = intervalSizeProvider.getIntervalSize(aggregationInfo.getMaxTime(),
                aggregationInfo.getMinTime());
        if (intervalSize < 1) {
            intervalSize = 1;
        }

        TaskData taskData = getTaskData(taskId, sessionId);
        if (taskData == null) {
            log.error("TaskData not found by taskId: {}", taskId);
            return;
        }

        long currentInterval = aggregationInfo.getMinTime() + intervalSize;
        final Map<NodeId, Map<MonitoringParameter, Double>> sumByIntervalAgent = Maps.newHashMap();
        final Map<NodeId, Map<MonitoringParameter, Long>> countByIntervalAgent = Maps.newHashMap();
        final Map<String, Map<MonitoringParameter, Double>> sumByIntervalSuT = Maps.newHashMap();
        final Map<String, Map<MonitoringParameter, Long>> countByIntervalSuT = Maps.newHashMap();
        final ListMultimap<MonitoringStream, MonitoringStatistics> avgStatisticsByAgent = ArrayListMultimap
                .create();
        final ListMultimap<MonitoringStream, MonitoringStatistics> avgStatisticsBySuT = ArrayListMultimap
                .create();

        LogReader.FileReader<MonitoringLogEntry> fileReader = logReader.read(aggregatedFile,
                MonitoringLogEntry.class);
        Iterator<MonitoringLogEntry> it = fileReader.iterator();
        while (it.hasNext()) {
            MonitoringLogEntry logEntry = it.next();
            try {
                currentInterval = processLogEntry(sessionId, aggregationInfo, intervalSize, taskData,
                        currentInterval, sumByIntervalAgent, countByIntervalAgent, sumByIntervalSuT,
                        countByIntervalSuT, avgStatisticsByAgent, avgStatisticsBySuT, logEntry);
            } catch (ClassCastException e) {
                //HotFix for hessian de/serialization problem
                log.error("Deserialization problem: {}", e);
            }
        }

        fileReader.close();

        finalizeIntervalSysInfo(sessionId, taskData, currentInterval - aggregationInfo.getMinTime(),
                sumByIntervalAgent, countByIntervalAgent, avgStatisticsByAgent);
        finalizeIntervalSysUT(sessionId, taskData, currentInterval - aggregationInfo.getMinTime(),
                sumByIntervalSuT, countByIntervalSuT, avgStatisticsBySuT);

        differentiateRelativeParameters(avgStatisticsByAgent);
        differentiateRelativeParameters(avgStatisticsBySuT);

        log.info("BEGIN: Save to data base " + dir);
        getHibernateTemplate().execute(new HibernateCallback<Void>() {
            @Override
            public Void doInHibernate(Session session) throws HibernateException, SQLException {
                for (MonitoringStatistics stat : avgStatisticsByAgent.values()) {
                    session.persist(stat);
                }
                for (MonitoringStatistics stat : avgStatisticsBySuT.values()) {
                    session.persist(stat);
                }
                session.flush();
                return null;
            }
        });
        log.info("END: Save to data base " + dir);

        saveProfilers(sessionId, taskId);

    } catch (Exception e) {
        log.error("Error during log processing", e);
    }
}

From source file:com.griddynamics.jagger.monitoring.MonitoringAggregator.java

License:Open Source License

private void saveProfilers(final String sessionId, final String taskId) throws IOException {
    String dir;//w  ww.ja v  a2 s  .com
    dir = sessionId + "/" + taskId + "/" + MonitorProcess.PROFILER_MARKER;

    Set<String> fileNameList = fileStorage.getFileNameList(dir);
    if (fileNameList.isEmpty()) {
        log.debug("Directory {} is empty.", dir);
        return;
    }
    for (final String fileName : fileNameList) {
        LogReader.FileReader reader;
        try {
            reader = logReader.read(fileName, Object.class);
        } catch (IllegalArgumentException e) {
            log.warn(e.getMessage(), e);
            return;
        }
        final ProfileDTO profileDTO = SerializationUtils.fromString(reader.iterator().next().toString());

        getHibernateTemplate().execute(new HibernateCallback<Void>() {
            @Override
            public Void doInHibernate(Session session) throws HibernateException, SQLException {
                String prefix = "Agent on (" + profileDTO.getHostAddress() + ") : ";
                for (Map.Entry<String, RuntimeGraph> runtimeGraphEntry : profileDTO.getRuntimeGraphs()
                        .entrySet()) {
                    String context = SerializationUtils.toString(runtimeGraphEntry.getValue());
                    session.persist(new ProfilingSuT(prefix + runtimeGraphEntry.getKey(), sessionId,
                            getTaskData(taskId, sessionId), context));
                }
                session.flush();
                return null;
            }
        });
    }
}

From source file:com.icesoft.icefaces.tutorial.crud.hibernate.RegisterManager.java

License:Apache License

/**
 * Listener for the save changes button click action.
 * @param ActionEvent click action event.
 *//*  w  ww  .j a va2  s. c o  m*/
public void updateStudent(ActionEvent event) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    currentStudent = (Student) session.get(Student.class, currentStudent.getStudentId());
    if (updateStudent.getFirstName().length() > 0) {
        currentStudent.setFirstName(updateStudent.getFirstName());
    }
    if (updateStudent.getLastName().length() > 0) {
        currentStudent.setLastName(updateStudent.getLastName());
    }
    if (updateStudent.getAddress().length() > 0) {
        currentStudent.setAddress(updateStudent.getAddress());
    }
    session.persist(currentStudent);

    session.getTransaction().commit();

    updateStudent.clear();
}

From source file:com.icesoft.icefaces.tutorial.crud.hibernate.RegisterManager.java

License:Apache License

/**
 * Listener for the add course button click action.
 * @param ActionEvent click action event.
 *///from w w w .  j  a  va  2s .c om
public void addCourseToStudent(ActionEvent event) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    currentStudent = (Student) session.get(Student.class, currentStudent.getStudentId());
    currentCourse = (Course) session.load(Course.class, currentCourse.getCourseId());

    currentStudent.getCourses().add(currentCourse);
    currentCourse.getStudents().add(currentStudent);
    // Or persist currentCourse. Either way cascades.
    session.persist(currentStudent);
    setStudentCourses();

    session.getTransaction().commit();
}

From source file:com.icesoft.icefaces.tutorial.crud.hibernate.RegisterManager.java

License:Apache License

/**
 * Listener for the remove course button click action.
 * @param ActionEvent click action event.
 */// w  w  w  .j a  va 2s  .c o m
public void removeCourseFromStudent() {
    if (courseIdToRemoveFromStudent < 0) {
        return;
    }

    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    currentStudent = (Student) session.get(Student.class, currentStudent.getStudentId());
    Course removeCourse = (Course) session.load(Course.class, courseIdToRemoveFromStudent);

    currentStudent.getCourses().remove(removeCourse);
    removeCourse.getStudents().remove(currentStudent);
    // Or persist removeCourse. Either way cascades.
    session.persist(currentStudent);
    setStudentCourses();

    session.getTransaction().commit();

    courseIdToRemoveFromStudent = -1;
}

From source file:com.insert.java

public static void main(String[] args) {
    SessionFactory sessionFactory = new Configuration().configure("/resources/hibernate.cfg.xml")
            .buildSessionFactory();//w  w w  .  j  a v a2  s .c o  m
    Session session = sessionFactory.openSession();
    Buyer br = new Buyer();
    Seller sl = new Seller();
    User user = new User();
    Product proud = new Product();
    //Product proud1=new Product();
    Category cate = new Category();
    Buyer_bid_Product BuyerbidProduct = new Buyer_bid_Product();
    Buyer_buy_Product BuyerbuyProuduct = new Buyer_buy_Product();

    user.setUserName("radwa");
    user.setFullName("radwa hamdy");
    user.setBirthDate(new Date());
    user.setAddress("suez");
    user.setPhone("123456789");
    user.setEmail("radwa@mail.com");
    user.setRegistrationDate(new Date());
    user.setPassword("4815162342");
    user.setMobile("01025012646");

    br.setUser(user);
    br.setValue("Tea");

    sl.setUser(user);
    sl.setValue("teaaa");

    proud.setName("product1");
    proud.setQuantity(5);
    proud.setExpirationDate(new Date());
    proud.setDescription("firstproduct insert");
    proud.setFinishDate(new Date());
    proud.setManufacturingName("Hibernare");
    proud.setOfferedDate(new Date());
    proud.setManufacturingDate(new Date());
    proud.setSeller(sl);

    Product proud2 = new Product();

    proud2.setName("product10");
    proud2.setQuantity(5);
    proud2.setExpirationDate(new Date());
    proud2.setDescription("firstproduct insert");
    proud2.setFinishDate(new Date());
    proud2.setManufacturingName("Hibernare");
    proud2.setOfferedDate(new Date());
    proud2.setManufacturingDate(new Date());
    proud2.setSeller(sl);

    cate.setValue("cate2");
    cate.setDescription("blala");
    cate.getProducts().add(proud2);

    BuyerbidProduct.setBuyer(br);
    BuyerbidProduct.setProduct(proud2);
    BuyerbidProduct.setDate(new Date());
    BuyerbidProduct.setAmount(4f);
    BuyerbidProduct.setQuantity(2);

    BuyerbuyProuduct.setBuyer(br);
    BuyerbuyProuduct.setProduct(proud);
    BuyerbuyProuduct.setPaymentDate(new Date());
    BuyerbuyProuduct.setQuantity(4);
    BuyerbuyProuduct.setAmount(3f);

    session.save(user);
    session.save(sl);
    session.save(br);
    session.save(proud);
    //            session.save(proud1);
    session.save(proud2);

    session.save(cate);
    BuyerBidProductId bidID = new BuyerBidProductId();
    bidID.setBuyer_Id(br.getId());
    bidID.setProduct_id(proud2.getId());
    BuyerbidProduct.setId(bidID);
    session.save(BuyerbidProduct);
    BuyerBuyProductId buyId = new BuyerBuyProductId();
    buyId.setBuyer_id(br.getId());
    buyId.setProduct_id(proud.getId());
    BuyerbuyProuduct.setId(buyId);
    session.save(BuyerbuyProuduct);

    session.beginTransaction();

    session.persist(br);
    session.persist(sl);

    session.persist(BuyerbidProduct);
    session.persist(BuyerbuyProuduct);

    session.getTransaction().commit();
    session.close();
    System.out.println("Insertion Done");
}