List of usage examples for org.hibernate Session saveOrUpdate
void saveOrUpdate(Object object);
From source file:com.dell.asm.asmcore.asmmanager.db.TemplateDAO.java
License:Open Source License
public TemplateEntity updateTemplate(TemplateEntity updatedTemplate) throws AsmManagerInternalErrorException { Session session = null; Transaction tx = null;//from ww w . j a va 2s . co m TemplateEntity templateEntity = null; try { session = _dao._database.getNewSession(); tx = session.beginTransaction(); String hql = "from TemplateEntity where template_id = :id"; Query query = session.createQuery(hql); query.setString("id", updatedTemplate.getTemplateId()); templateEntity = (TemplateEntity) query.setMaxResults(1).uniqueResult(); if (templateEntity != null) { templateEntity.setTemplateType(updatedTemplate.getTemplateType()); templateEntity.setTemplateDesc(updatedTemplate.getTemplateDesc()); // templateEntity.setDisplayName(updatedTemplate.getDisplayName()); // templateEntity.setDeviceType(updatedTemplate.getDeviceType()); templateEntity.setState(updatedTemplate.getState()); templateEntity.setName(updatedTemplate.getName()); templateEntity.setUpdatedBy(_dao.extractUserFromRequest()); //TODO remove the set updated date when @PreUpdate is working GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("GMT")); templateEntity.setUpdatedDate(now); templateEntity.setMarshalledTemplateData(updatedTemplate.getMarshalledTemplateData()); session.saveOrUpdate(templateEntity); //commit tx.commit(); } else { String msg = "unable to update template with name " + updatedTemplate.getName(); logger.warn(msg); } } catch (Exception e) { logger.warn("Caught exception during update template: " + e); try { if (tx != null) { tx.rollback(); } } catch (Exception ex) { logger.warn("Unable to rollback transaction during update template: " + ex); } // TODO: Reviewer: instanceof will always return false since a RuntimeException can't be a com.dell.asm.asmcore.asmmanager.exception.AsmManagerCheckedException //if (e instanceof AsmManagerCheckedException) { // throw e; //} throw new AsmManagerInternalErrorException("update Template", "TemplateDAO", e); } finally { try { if (session != null) { session.close(); } } catch (Exception ex) { logger.warn("Unable to close session during update template: " + ex); } } return templateEntity; }
From source file:com.desoftmex.dao.impl.ManagerDao.java
public void saveOrUpdate(T entity) throws ExceptionDao { try {//from www . j a v a 2 s. c o m Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.saveOrUpdate(entity); session.getTransaction().commit(); //session.close(); } catch (HibernateException ex) { throw new ExceptionDao(ex.getMessage()); } }
From source file:com.dnn.jsf.alteracao.registro.bean.ProdutoBean.java
public void salvar() { Session s = null; Transaction tx = null;//from w w w .ja v a 2 s . c o m try { s = HibernateUtil.getSessionFactory().getCurrentSession(); tx = s.beginTransaction(); s.saveOrUpdate(p); s.save(new Log(p.getId(), "produto", p.toString())); tx.commit(); listar(); ls = new ArrayList<>(); p = new Produto(); p.setDescricao(""); RequestContext.getCurrentInstance().reset("form"); } catch (Exception e) { if (tx != null) { tx.rollback(); } System.out.println(e); } finally { if (s != null) { s.close(); } } }
From source file:com.dotosoft.dotoquiz.tools.OldApp.java
License:Apache License
private void processPicasa() { if (DATA_TYPE.EXCEL.toString().equals(settings.getDataType())) { log.info("process data from excel!"); } else if (DATA_TYPE.GOOGLESHEET.toString().equals(settings.getDataType())) { log.info("process data from googlesheet!"); }/*from w w w . j a va 2 s.c om*/ // variable for googlesheet GooglesheetClient googlesheetClient = null; WorksheetEntry fullSheet = null; // variable for excel FileInputStream file = null; XSSFWorkbook workbook = null; XSSFSheet sheet = null; // variable for DB Session session = null; Transaction trx = null; APPLICATION_TYPE type = APPLICATION_TYPE.valueOf(settings.getApplicationType()); try { if (APPLICATION_TYPE.DB.toString().equals(settings.getApplicationType())) { session = HibernateUtil.getSessionFactory().openSession(); trx = session.beginTransaction(); } if (DATA_TYPE.EXCEL.toString().equals(settings.getDataType())) { file = new FileInputStream(settings.getSyncDataFile()); workbook = new XSSFWorkbook(file); } else if (DATA_TYPE.GOOGLESHEET.toString().equals(settings.getDataType())) { googlesheetClient = new GooglesheetClient(auth, settings.getSyncDataFile()); } int index = 0; // -------------------------------------------------------------------------- // Extract Achievement ------------------------------------------------------ // -------------------------------------------------------------------------- // parent folder if (!APPLICATION_TYPE.SHOW_COLUMN_HEADER.toString().equals(settings.getApplicationType())) { DataTopicsParser topicAchievement = new DataTopicsParser(QuizParserConstant.ACHIEVEMENT_NAME, QuizParserConstant.EMPTY_STRING, QuizParserConstant.EMPTY_STRING, QuizParserConstant.EMPTY_STRING, QuizParserConstant.ACHIEVEMENT_NAME, QuizParserConstant.ACHIEVEMENT_DESCRIPTION, QuizParserConstant.ACHIEVEMENT_IMAGE_URL, QuizConstant.NO, new java.util.Date(), QuizConstant.SYSTEM_USER, QuizConstant.NO, type); topicAchievement = syncTopicToPicasa(topicAchievement); topicMapByTopicId.put(topicAchievement.getId(), topicAchievement); } List listRow = null; for (String achievementTab : settings.getStructure().getTabAchievements().split(";")) { String sheetName = ""; if (DATA_TYPE.EXCEL.toString().equals(settings.getDataType())) { sheet = workbook.getSheetAt(Integer.parseInt(achievementTab)); listRow = Lists.newArrayList(sheet.iterator()); sheetName = sheet.getSheetName(); } else if (DATA_TYPE.GOOGLESHEET.toString().equals(settings.getDataType())) { fullSheet = (WorksheetEntry) googlesheetClient.getWorksheet(Integer.parseInt(achievementTab)); listRow = googlesheetClient.getListRows(fullSheet); sheetName = fullSheet.getTitle().getPlainText(); } for (Object row : listRow) { if (showColumnHeader(row, sheetName)) break; ParameterAchievementParser achievement = DotoQuizStructure.convertDataToAchievement(row, settings); if (achievement != null) { if (type == APPLICATION_TYPE.DB) { session.saveOrUpdate(achievement.toParameterAchievements()); log.info("Save or update achievement: " + achievement); } else if (type == APPLICATION_TYPE.SYNC) { achievement = syncAchievementToPicasa(achievement); if (!QuizConstant.YES.equals(achievement.getIsProcessed())) { GooglesheetClient.updateSyncPicasa(settings, QuizParserConstant.PARSE_ACHIEVEMENT, row, achievement.getPicasaId(), achievement.getImagePicasaUrl(), QuizConstant.YES); } } } } } trx = CommitDB(trx, session, true); for (String dataTab : settings.getStructure().getTabTopics().split(";")) { // -------------------------------------------------------------------------- // Extract Topic // -------------------------------------------------------------------------- index = 0; String sheetName = ""; if (DATA_TYPE.EXCEL.toString().equals(settings.getDataType())) { sheet = workbook.getSheetAt(Integer.parseInt(dataTab)); listRow = Lists.newArrayList(sheet.iterator()); sheetName = sheet.getSheetName(); } else if (DATA_TYPE.GOOGLESHEET.toString().equals(settings.getDataType())) { fullSheet = (WorksheetEntry) googlesheetClient.getWorksheet(Integer.parseInt(dataTab)); listRow = googlesheetClient.getListRows(fullSheet); sheetName = fullSheet.getTitle().getPlainText(); } for (Object row : listRow) { if (showColumnHeader(row, sheetName)) break; DataTopicsParser topic = DotoQuizStructure.convertDataToTopics(row, settings); if (topic != null) { if (type == APPLICATION_TYPE.DB) { if (StringUtils.hasValue(topic.getTopicParentId())) { topic.setDatTopics(topicMapByTopicId.get(topic.getTopicParentId()).toDataTopics()); } session.saveOrUpdate(topic.toDataTopics()); log.info("Save or update topic: " + topic); } else if (type == APPLICATION_TYPE.SYNC) { topic = syncTopicToPicasa(topic); if (!QuizConstant.YES.equals(topic.getIsProcessed())) { GooglesheetClient.updateSyncPicasa(settings, QuizParserConstant.PARSE_TOPIC, row, topic.getPicasaId(), topic.getImagePicasaUrl(), QuizConstant.YES); } } topicMapByTopicId.put(topic.getId(), topic); } } } trx = CommitDB(trx, session, true); for (String dataTab : settings.getStructure().getTabQuestions().split(";")) { // -------------------------------------------------------------------------- // Extract QuestionAnswers // -------------------------------------------------------------------------- index = 0; String sheetName = ""; if (DATA_TYPE.EXCEL.toString().equals(settings.getDataType())) { sheet = workbook.getSheetAt(Integer.parseInt(dataTab)); listRow = Lists.newArrayList(sheet.iterator()); sheetName = sheet.getSheetName(); } else if (DATA_TYPE.GOOGLESHEET.toString().equals(settings.getDataType())) { fullSheet = (WorksheetEntry) googlesheetClient.getWorksheet(Integer.parseInt(dataTab)); listRow = googlesheetClient.getListRows(fullSheet); sheetName = fullSheet.getTitle().getPlainText(); } for (Object row : listRow) { if (showColumnHeader(row, sheetName)) break; DataQuestionsParser questionAnswer = DotoQuizStructure.convertDataToAnswerQuestion(row, settings); if (questionAnswer != null) { if (type == APPLICATION_TYPE.DB) { questionAnswer.setMtQuestionType(HibernateUtil.getQuestionTypeByName(session, questionAnswer.getQuestionTypeData())); session.saveOrUpdate(questionAnswer.toDataQuestion()); log.info("Save or update QuestionAnswers: " + questionAnswer); for (String topicId : questionAnswer.getTopics()) { DataTopicsParser datTopic = topicMapByTopicId.get(topicId); HibernateUtil.saveOrUpdateTopicQuestionData(session, datTopic.toDataTopics(), questionAnswer.toDataQuestion()); } } else if (type == APPLICATION_TYPE.SYNC) { questionAnswer = syncQuestionAnswersToPicasa(questionAnswer); if (!QuizConstant.YES.equals(questionAnswer.getIsProcessed())) { GooglesheetClient.updateSyncPicasa(settings, QuizParserConstant.PARSE_QUESTION_ANSWER, row, questionAnswer.getPicasaId(), questionAnswer.getImagePicasaUrl(), QuizConstant.YES); } } } } } trx = CommitDB(trx, session, false); if (DATA_TYPE.EXCEL.toString().equals(settings.getDataType())) { file.close(); log.info("Save data to file..."); FileOutputStream fos = new FileOutputStream(settings.getSyncDataFile()); workbook.write(fos); fos.close(); } log.info("Done"); } catch (Exception e) { trx.rollback(); session.close(); e.printStackTrace(); } System.exit(0); }
From source file:com.duroty.application.files.manager.FilesManager.java
License:Open Source License
/** * DOCUMENT ME!// w w w .j a va2 s. co m * * @param hsession DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param mids DOCUMENT ME! * * @throws FilesException DOCUMENT ME! */ public void applyLabel(Session hsession, String repositoryName, Integer label, Integer[] idints) throws FilesException { if ((idints == null) || (idints.length == 0)) { throw new FilesException("ErrorMessages.messages.selection.null"); } try { if ((label == null) || (label.intValue() <= 0)) { return; } Users user = getUser(hsession, repositoryName); Criteria crit = hsession.createCriteria(Label.class); crit.add(Restrictions.eq("labIdint", label)); crit.add(Restrictions.eq("users", user)); Label hlabel = (Label) crit.uniqueResult(); Query query = hsession.getNamedQuery("messages-by-attachments"); query.setParameterList("idints", idints); query.setInteger("user", user.getUseIdint()); ScrollableResults scroll = query.scroll(); while (scroll.next()) { Message message = (Message) scroll.get(0); LabMes labMes = new LabMes(new LabMesId(message, hlabel)); hsession.saveOrUpdate(labMes); hsession.flush(); } hsession.flush(); } catch (Exception e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.application.home.manager.HomeManager.java
License:Open Source License
/** * DOCUMENT ME!/*w ww .jav a 2 s . c o m*/ * * @param hsession DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param data DOCUMENT ME! * * @throws HomeException DOCUMENT ME! */ public void saveFeed(Session hsession, String repositoryName, int idintChannel, String name, String value) throws HomeException { try { FeedChannel channel = null; Users user = getUser(hsession, repositoryName); if (idintChannel == 0) { Criteria criteria = hsession.createCriteria(FeedChannel.class); criteria.add(Restrictions.eq("users", user)); criteria.add(Restrictions.eq("fechName", "Main")); channel = (FeedChannel) criteria.uniqueResult(); if (channel == null) { channel = new FeedChannel(); channel.setFechName("Main"); channel.setUsers(user); hsession.saveOrUpdate(channel); hsession.flush(); } } else { Criteria criteria = hsession.createCriteria(FeedChannel.class); criteria.add(Restrictions.eq("users", user)); criteria.add(Restrictions.eq("fechIdint", new Integer(idintChannel))); channel = (FeedChannel) criteria.uniqueResult(); } Criteria criteria = hsession.createCriteria(FeedData.class); criteria.add(Restrictions.eq("fedaName", name)); criteria.add(Restrictions.eq("feedChannel", channel)); FeedData feed = (FeedData) criteria.uniqueResult(); if (feed == null) { feed = new FeedData(); feed.setFedaName(name); feed.setFedaValue(value); feed.setFeedChannel(channel); hsession.save(feed); } else { feed.setFedaName(name); feed.setFedaValue(value); hsession.saveOrUpdate(feed); } hsession.flush(); /*if (value.indexOf("=none;expires=") > -1) { hsession.delete(feed); hsession.flush(); }*/ } catch (Exception e) { throw new HomeException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.application.home.manager.HomeManager.java
License:Open Source License
/** * DOCUMENT ME!/*from w ww.ja va2 s . co m*/ * * @param hsession DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param idintChannel DOCUMENT ME! * @param name DOCUMENT ME! * * @throws HomeException DOCUMENT ME! */ public FeedObj getFeed(Session hsession, String repositoryName, int idintChannel, String name) throws HomeException { FeedObj obj = null; try { FeedChannel channel = null; Users user = getUser(hsession, repositoryName); if (idintChannel == 0) { Criteria criteria = hsession.createCriteria(FeedChannel.class); criteria.add(Restrictions.eq("users", user)); criteria.add(Restrictions.eq("fechName", "Main")); channel = (FeedChannel) criteria.uniqueResult(); if (channel == null) { channel = new FeedChannel(); channel.setFechName("Main"); channel.setUsers(user); hsession.saveOrUpdate(channel); hsession.flush(); } } else { Criteria criteria = hsession.createCriteria(FeedChannel.class); criteria.add(Restrictions.eq("users", user)); criteria.add(Restrictions.eq("fechIdint", new Integer(idintChannel))); channel = (FeedChannel) criteria.uniqueResult(); } Criteria criteria = hsession.createCriteria(FeedData.class); criteria.add(Restrictions.eq("fedaName", name)); criteria.add(Restrictions.eq("feedChannel", channel)); FeedData feed = (FeedData) criteria.uniqueResult(); if (feed != null) { obj = new FeedObj(); obj.setChannel(channel.getFechIdint()); obj.setIdint(feed.getFedaIdint()); obj.setName(feed.getFedaName()); obj.setValue(feed.getFedaValue()); } return obj; } catch (Exception e) { throw new HomeException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.application.home.manager.HomeManager.java
License:Open Source License
/** * DOCUMENT ME!//from w w w .java 2 s.c o m * * @param hsession DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param idintChannel DOCUMENT ME! * @param name DOCUMENT ME! * * @return DOCUMENT ME! * * @throws HomeException DOCUMENT ME! */ public Vector getAllFeed(Session hsession, String repositoryName, int idintChannel) throws HomeException { Vector feeds = new Vector(); try { FeedChannel channel = null; Users user = getUser(hsession, repositoryName); if (idintChannel == 0) { Criteria criteria = hsession.createCriteria(FeedChannel.class); criteria.add(Restrictions.eq("users", user)); criteria.add(Restrictions.eq("fechName", "Main")); channel = (FeedChannel) criteria.uniqueResult(); if (channel == null) { channel = new FeedChannel(); channel.setFechName("Main"); channel.setUsers(user); hsession.saveOrUpdate(channel); hsession.flush(); } } else { Criteria criteria = hsession.createCriteria(FeedChannel.class); criteria.add(Restrictions.eq("users", user)); criteria.add(Restrictions.eq("fechIdint", new Integer(idintChannel))); channel = (FeedChannel) criteria.uniqueResult(); } Criteria crit = hsession.createCriteria(FeedData.class); crit.add(Restrictions.eq("feedChannel", channel)); crit.addOrder(Order.asc("fedaName")); ScrollableResults scroll = crit.scroll(); while (scroll.next()) { FeedData feed = (FeedData) scroll.get(0); feeds.addElement(feed.getFedaValue()); } return feeds; } catch (Exception e) { throw new HomeException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.application.mail.manager.MailManager.java
License:Open Source License
/** * DOCUMENT ME!// w ww .j a v a2s. c o m * * @param hsession DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param mids DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public void applyLabel(Session hsession, String repositoryName, Integer label, String[] mids) throws MailException { if ((mids == null) || (mids.length == 0)) { throw new MailException("ErrorMessages.messages.selection.null"); } try { if ((label == null) || (label.intValue() <= 0)) { return; } Users user = getUser(hsession, repositoryName); Criteria crit = hsession.createCriteria(Label.class); crit.add(Restrictions.eq("labIdint", label)); crit.add(Restrictions.eq("users", user)); Label hlabel = (Label) crit.uniqueResult(); crit = hsession.createCriteria(Message.class); crit.add(Restrictions.in("mesName", mids)); crit.add(Restrictions.eq("users", getUser(hsession, repositoryName))); ScrollableResults scroll = crit.scroll(); while (scroll.next()) { Message message = (Message) scroll.get(0); LabMes labMes = new LabMes(new LabMesId(message, hlabel)); hsession.saveOrUpdate(labMes); hsession.flush(); } hsession.flush(); } catch (Exception e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.application.mail.manager.PreferencesManager.java
License:Open Source License
/** * DOCUMENT ME!/*from w ww . j a va 2 s . com*/ * * @param hsession DOCUMENT ME! * @param token DOCUMENT ME! * * @return DOCUMENT ME! * * @throws ManagerException DOCUMENT ME! */ public void createLabel(Session hsession, String repositoryName, LabelObj label) throws MailException { String lucenePathMessages = null; if (!defaultLucenePath.endsWith(File.separator)) { lucenePathMessages = defaultLucenePath + File.separator + repositoryName + File.separator + Constants.MAIL_LUCENE_MESSAGES; } else { lucenePathMessages = defaultLucenePath + repositoryName + File.separator + Constants.MAIL_LUCENE_MESSAGES; } Searcher searcher = null; try { searcher = MailIndexer.getSearcher(lucenePathMessages); Users user = getUser(hsession, repositoryName); if (user != null) { Label hlabel = new Label(); hlabel.setUsers(user); hlabel.setLabName(label.getName()); hsession.save(hlabel); hsession.flush(); if (label.getFilters() != null) { Iterator it = label.getFilters().iterator(); while (it.hasNext()) { FilterObj filter = (FilterObj) it.next(); Filter hfilter = new Filter(); //hfilter.setUser(user); hfilter.setLabel(hlabel); hfilter.setFilArchive(filter.isArchive()); hfilter.setFilDoesntHaveWords(filter.getDoesntHaveWords()); hfilter.setFilForwardTo(filter.getForward()); hfilter.setFilFrom(filter.getFrom()); //CANVIDUROT hfilter.setFilHasAttacment(filter.isHasAttachment()); hfilter.setFilHasWords(filter.getHasWords()); hfilter.setFilImportant(filter.isImportant()); hfilter.setFilSubject(filter.getSubject()); hfilter.setFilTo(filter.getTo()); hfilter.setFilTrash(filter.isTrash()); hfilter.setFilOrOperator(!filter.isOperator()); hsession.save(hfilter); hsession.flush(); org.apache.lucene.search.Query query = FilterQueryParser.parse(hfilter, analyzer); if ((searcher != null) && (query != null)) { Hits hits = searcher.search(query); for (int j = 0; j < hits.length(); j++) { Document doc = hits.doc(j); String uid = doc.get(Field_idint); Criteria crit = hsession.createCriteria(Message.class); crit.add(Restrictions.eq("mesName", uid)); crit.add(Restrictions.eq("users", user)); Message message = (Message) crit.uniqueResult(); if (message != null) { try { LabMesId id = new LabMesId(); id.setLabel(hlabel); id.setMessage(message); LabMes lm = new LabMes(id); hsession.saveOrUpdate(lm); hsession.flush(); } catch (HibernateException e) { } } } } } } } } catch (Exception ex) { throw new MailException(ex); } finally { GeneralOperations.closeHibernateSession(hsession); } }