List of usage examples for org.apache.ibatis.session SqlSession insert
int insert(String statement, Object parameter);
From source file:in.flipbrain.dao.MyBatisDao.java
License:Apache License
public void saveQuestion(QuestionDto dto) { SqlSession session = sqlSessionFactory.openSession(); try {/*from w ww . j a va 2 s . co m*/ if (dto.questionId < 1 && !dto.isDeleted()) { session.insert("insertQuestion", dto); } else if (dto.isDeleted()) { session.delete("deleteQuestion", dto); } else { session.update("updateQuestion", dto); } for (AnswerOptionDto opt : dto.answerOptions) { opt.questionId = dto.questionId; opt.author = dto.author; if (opt.answerOptId < 1 && !opt.isDeleted()) { session.insert("insertAnswerOption", opt); } else if (opt.isDeleted()) { session.delete("deleteAnswerOption", opt); } else { session.update("updateAnswerOption", opt); } } session.commit(); } finally { session.close(); } }
From source file:in.flipbrain.dao.MyBatisDao.java
License:Apache License
public void saveAssessment(AssessmentDto dto) { SqlSession session = sqlSessionFactory.openSession(); try {/*w w w. ja v a 2 s .co m*/ if (dto.assessId < 1 && !dto.isDeleted()) { session.insert("insertAssessment", dto); } else if (dto.isDeleted()) { session.delete("deleteAssessment", dto); } else { session.update("updateAssessment", dto); } for (AssessmentQuestionDto q : dto.questions) { q.assessId = dto.assessId; if (q.assessQuestId < 1 && !q.isDeleted()) { session.insert("insertAssessmentQuestion", q); } else if (q.isDeleted()) { session.delete("deleteAssessmentQuestion", q); } else { session.update("updateAssessmentQuestion", q); } } session.commit(); } finally { session.close(); } }
From source file:in.flipbrain.dao.MyBatisDao.java
License:Apache License
protected <T> int saveEntity(String stmtId, T dto, Operation op) { int rows = 0; SqlSession session = sqlSessionFactory.openSession(); try {//from w w w. j a v a 2 s . co m logActivity(session); switch (op) { case Del: rows = session.delete(stmtId, dto); break; case Ins: rows = session.insert(stmtId, dto); break; case Upd: rows = session.update(stmtId, dto); break; } session.commit(); } finally { session.close(); } return rows; }
From source file:io.starter.datamodel.ContentData.java
License:Open Source License
/** * do the work of deleting all existing acls for content, inserting a new * owner acl, and optionally inserting necessary new ACL(s) based on the * OP_TYPE//from ww w. j a v a2s.c om * * @param optype * @param servletRequest * @param id * @return * @throws ServletException */ private String resetAclsForContent(int optype, ServletRequest servletRequest, Integer id) throws ServletException { // DELETE all ACLs except the User's OWNER ACL Object u = servletRequest.getAttribute(SESSION_VAR_USER); if (u == null) throw new ServletException("No User in Request -- Anonymous users cannot modify content permissions."); User user = (User) u; int uid = user.getId(); user.clearCachedAuthorizationForAllUsers(); SqlSession session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION); int rowsDeleted = 0; // delete content acls AclExample ax = new AclExample(); Criteria c = ax.createCriteria(); c.andTargetIdEqualTo(id); c.andTargetTypeEqualTo(SECURITY_TARGET_TYPE_CONTENT); session.delete("io.starter.dao.AclMapper.deleteByExample", ax); session.commit(); Acl a = new Acl(); // give permission to current session user -- only one allowed to do // this a.setPrincipleId(user.getId()); a.setPrincipleType(SECURITY_PRINCIPAL_TYPE_USER); // allow them to a.setPermission(SECURITY_ACL_OWNER); // to this thing a.setTargetId(id); a.setTargetType(SECURITY_TARGET_TYPE_CONTENT); int rowsInserted = session.insert("io.starter.dao.AclMapper.insert", a); if (rowsInserted < 1) throw new ServletException("Could not make Content object private: setting Owner ACL failed."); if (optype == OPTYPE_SET_PUBLIC) { // make public Acl ae = new Acl(); // give permission to current session user -- only one allowed // to do // this ae.setPrincipleId(SECURITY_ROLE_EVERYONE); ae.setPrincipleType(SECURITY_PRINCIPAL_TYPE_ROLE); // allow them to ae.setPermission(SystemConstants.SECURITY_ACL_APPEND); // required // to allow // comments/rating // to this thing ae.setTargetId(id); ae.setTargetType(SECURITY_TARGET_TYPE_CONTENT); rowsInserted = session.insert("io.starter.dao.AclMapper.insert", ae); session.commit(); ae = new Acl(); ae.setPrincipleId(SECURITY_ROLE_EVERYONE); ae.setPrincipleType(SECURITY_PRINCIPAL_TYPE_ROLE); // allow them to ae.setPermission(SystemConstants.SECURITY_ACL_READ); // need to see // to this thing ae.setTargetId(id); ae.setTargetType(SECURITY_TARGET_TYPE_CONTENT); rowsInserted += session.insert("io.starter.dao.AclMapper.insert", ae); session.commit(); if (rowsInserted < 2) throw new ServletException( "Could not make Content object private: setting Everyone READ-ONLY and APPEND ACLs failed."); } else if (optype == OPTYPE_SET_TAKEOVER_OWNERSHIP) { // take over // ownership // (administrators) if (!user.isAdmin()) throw new ServletException( "Could not take over Content object ownership: Only Administrators can do this."); Acl ax1 = new Acl(); // give permission to current session user -- only one allowed // to do // this ax1.setPrincipleId(1); ax1.setPrincipleType(SECURITY_PRINCIPAL_TYPE_USER); // allow them to ax1.setPermission(SECURITY_ACL_OWNER); // to this thing ax1.setTargetId(id); ax1.setTargetType(SECURITY_TARGET_TYPE_CONTENT); rowsInserted = session.insert("io.starter.dao.AclMapper.insert", ax1); if (rowsInserted < 1) throw new ServletException( "Could not take over Content object ownership: setting Owner ACL failed."); } session.commit(); // return the result return "true"; }
From source file:io.starter.datamodel.ContentData.java
License:Open Source License
/** * create a new content item in the system * /*from w w w . j ava 2 s .co m*/ * @param author * @param device * @param copyright * @param description * @param url * @param categories * @param servletRequest * @param servletResponse * @param longitude * @param latitude * @param width * @param height * @return * @throws IOException * @throws ServletException * @throws JSONException * @throws org.json.JSONException */ @PUT @Path("create") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String create(@FormParam("author") int author, @FormParam("device") int device, @FormParam("copyright") String copyright, @FormParam("description") String description, @FormParam("url") String url, @FormParam("categories") String categories, @Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse, @FormParam("longitude") Double longitude, @FormParam("latitude") Double latitude, @FormParam("mimeType") String mimeType, @FormParam("width") Long width, @FormParam("height") Long height) throws IOException, ServletException, JSONException, org.json.JSONException { Object u = servletRequest.getAttribute(SESSION_VAR_USER); if (u == null) throw new ServletException("No User in Request -- Cannot create anonymously owned content."); User user = (User) u; int uid = user.getId(); url = fixContentURLs(url); user.getSubject().getSession(true); Content content = new Content(); content.setUserId(uid); content.setAuthor(author); content.setAuthorDevice(device); content.setCopyright(copyright); content.setDescription(description); content.setLongitude(longitude); content.setLatitude(latitude); content.setWidth(width); content.setHeight(height); content.setUrl(url); content.setMimeType(mimeType); content.setFlag(FLAG_NONE); content.setPostDate(new Date(System.currentTimeMillis())); content.setLicense( "Content has been uploaded by end-users and is provided for personal non-commercial viewing under fair use laws of the United States, and additionally as satirical works protected speech under the First Amendment."); SqlSession session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION); int rowsInserted = 0; rowsInserted = session.insert("io.starter.dao.ContentMapper.insert", content); session.commit(); if (rowsInserted > 0) { ContentData.setContentOwnerPermissions(content, user, session); String dq = "userId=" + user.getId(); removeCachedContentList(dq, servletRequest); } // set the categories for the object.. setCategories(content.getId(), categories, session); content = this.getContentObject(servletRequest, content.getId()); // return the JSON result JSONObject j = new JSONObject(content); // handle ownership here. if ((content.getUserId() == uid) || (user.isAdmin())) j.put("isowner", true); else j.put("isowner", false); return j.toString(); }
From source file:io.starter.datamodel.ContentData.java
License:Open Source License
/** * handle the details of ownership ACLs and cache reset * //w w w . j a v a2s. c o m * @param content * @param user * @param session * @throws ServletException */ public static void setContentOwnerPermissions(Content content, User user, SqlSession session) throws ServletException { // share a content item with the share group Acl a = new Acl(); // give permission to a.setPrincipleId(user.getId()); a.setPrincipleType(SECURITY_PRINCIPAL_TYPE_USER); // allow them to a.setPermission(SECURITY_ACL_OWNER); // to this thing a.setTargetId(content.getId()); a.setTargetType(SECURITY_TARGET_TYPE_CONTENT); int rowsInserted = session.insert("io.starter.dao.AclMapper.insert", a); session.commit(); if (rowsInserted > 0) { ; } else { throw new ServletException( "Null rows inserted in ACL could not assign Ownership ACL to new Content object."); } user.clearCachedAuthorization(); WildcardPermission owner = new WildcardPermission(SystemConstants.SECURITY_TARGET_TYPE_CONTENT + ":" + SystemConstants.SECURITY_ACL_OWNER + ":" + content.getId()); assert (user.checkAccess(owner)); // return content; }
From source file:io.starter.datamodel.ContentData.java
License:Open Source License
/** * assign categories to an item//from w w w .ja v a2 s. c o m * * @param obj * @param cats * @throws ServletException */ public static void setCategories(Integer objId, String cats, SqlSession session) throws ServletException { int rowsInserted = 0; StringTokenizer toker = new StringTokenizer(cats, ","); while (toker.hasMoreElements()) { String st = toker.nextElement().toString(); if (st.contains("[")) { st = st.substring(1); } if (st.contains("]")) { st = st.substring(0, st.length() - 1); } Integer categoryId = Integer.parseInt(st); ContentCategoryIdx cat = new ContentCategoryIdx(); cat.setCategoryId(categoryId); cat.setContentId(objId); rowsInserted = session.insert("io.starter.dao.ContentCategoryIdxMapper.insert", cat); session.commit(); } if (rowsInserted > 0) { ; } else { throw new ServletException( "Null rows inserted in ContentCategory IDX -- could not assign categories to Content object."); } }
From source file:io.starter.datamodel.Sys.java
License:Open Source License
/** * this method returns a JSON string with a summarized set of data for the * entire starter system/*from w ww .j a v a 2 s .c o m*/ * * includes: * * Top Content Leader board System-wide Alliances * * @param query * @param servletRequest * @param servletResponse * @return * @throws IOException * @throws ServletException * @throws JSONException * @throws SQLException */ @GET @Path("stats") @Produces(MediaType.APPLICATION_JSON) public String getStats(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse) throws IOException, ServletException, JSONException, SQLException { String jsonStr = ""; Map namevals = new HashMap(); // System-wide eazy squeezy User u = (User) servletRequest.getSession(true).getAttribute(SESSION_VAR_USER); SqlSession session = (SqlSession) servletRequest.getAttribute(SESSION_VAR_SQLSESSION); Connection connection = session.getConnection(); try { namevals.put("system.totalusers", this.getValueFromDB("SELECT COUNT(id) as ct FROM user", connection)); namevals.put("system.totalcontent", this.getValueFromDB("SELECT COUNT(id) as ct FROM content", connection)); namevals.put("system.totalalliances", this.getValueFromDB("SELECT COUNT(id) as ct FROM role WHERE id > 100", connection)); namevals.put("system.totalshares", this.getValueFromDB( "SELECT COUNT(id) FROM acl WHERE target_type = 2 AND principle_id = 2 AND principle_type = 1 AND permission = 3", connection)); namevals.put("system.totalsocialshares", this.getValueFromDB( "SELECT COUNT(syslog.id) as CT FROM syslog WHERE ( event_type = 25 OR event_type = 26) AND syslog.description LIKE '%OK [%' ORDER BY CT desc", connection)); namevals.put("system.totalratings", this.getValueFromDB("SELECT COUNT(id) as CT FROM content_rating", connection)); namevals.put("system.totalcategories", this.getValueFromDB("SELECT COUNT(id) as CT FROM category", connection)); namevals.put("system.totallogins", this.getValueFromDB( "SELECT COUNT(syslog.id) as CT FROM syslog WHERE event_type = 0 AND syslog.description LIKE '%OK [%' ORDER BY CT desc", connection)); // Top Content -- the easiest ContentData cdx = new ContentData(); String lx = cdx.list("top", servletRequest, servletResponse); JSONArray jaray = new JSONArray(lx); for (int t = 0; t < jaray.length(); t++) { namevals.put("topcontent." + t, jaray.get(t)); } // Leader board // Top Content -- the easiest if (servletRequest.getParameter("leaderboard") != null) { try { lx = UserData.list("leaders", servletRequest, servletResponse); jaray = new JSONArray(lx); int lx1 = jaray.length() - 1; for (int t = 0; t < jaray.length(); t++) { namevals.put("leader." + t, jaray.get(lx1 - t)); } } catch (Exception e) { ; // couldn't get leaderboard } } // Alliances try { lx = RoleData.list("top", servletRequest, servletResponse); jaray = new JSONArray(lx); for (int t = 0; t < jaray.length(); t++) { namevals.put("alliance." + t, jaray.get(t)); } } catch (Exception e) { ; // couldn't get alliances } // JSONify jsonStr = new JSONObject(namevals).toString(); // oh yes, record it for posterity... this is going to come in // handy... Syslog logEntry = new Syslog(); logEntry.setDescription("OK [ ANONYMOUS -1 ], [GET] [stats " + jsonStr.substring(0, 100) + "]"); logEntry.setEventType(SystemConstants.LOG_EVENT_TYPE_SYSTEM_CONTENT); logEntry.setSourceId(-1); logEntry.setSourceType(SystemConstants.TARGET_TYPE_SYSTEM); logEntry.setTimestamp(new java.util.Date(System.currentTimeMillis())); session.insert("io.starter.dao.SyslogMapper.insert", logEntry); session.commit(); } catch (Exception x) { Logger.log("Getting System Stats Failed: " + x.toString()); } return jsonStr; }
From source file:io.starter.datamodel.Sys.java
License:Open Source License
/** * // w w w . j a v a2s . co m * @param params * @throws Exception * * */ public static void sendEmail(String url, final User from, String toEmail, Map params, SqlSession session, CountDownLatch latch) throws Exception { final CountDownLatch ltc = latch; if (from == null) { throw new ServletException("Sys.sendEmail cannot have a null FROM User."); } String fromEmail = from.getEmail(); final String fro = fromEmail; final String to = toEmail; final Map p = params; final String u = url; final SqlSession sr = session; // TODO: check message sender/recipient validity if (!checkEmailValidity(fromEmail)) { throw new RuntimeException( fromEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED"); } // TODO: check mail server if it's a valid message if (!checkEmailValidity(toEmail)) { throw new RuntimeException( toEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED"); } // message.setSubject("Testing Email From Starter.io"); // Send the actual HTML message, as big as you like // fetch the content final String content = getText(u); new Thread(new Runnable() { @Override public void run() { // Sender's email ID needs to be mentioned // String sendAccount = "$EMAIL_USER_NAME$"; // final String username = "$EMAIL_USER_NAME$", password = // "hum0rm3"; // Assuming you are sending email from localhost // String host = "gator3083.hostgator.com"; String sendAccount = "$EMAIL_USER_NAME$"; final String username = "$EMAIL_USER_NAME$", password = "$EMAIL_USER_PASS$"; // Assuming you are sending email from localhost String host = SystemConstants.EMAIL_SERVER; // Get system properties Properties props = System.getProperties(); // Setup mail server props.setProperty("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.port", "587"); // Get the default Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(sendAccount)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(sendAccount)); // Set Subject: header field Object o = p.get("MESSAGE_SUBJECT"); message.setSubject(o.toString()); String ctx = new String(content.toString()); // TODO: String Rep on the params ctx = stringRep(ctx, p); message.setContent(ctx, "text/html; charset=utf-8"); // message.setContent(new Multipart()); // Send message Transport.send(message); Logger.log("Sending message to:" + to + " SUCCESS"); } catch (MessagingException mex) { // mex.printStackTrace(); Logger.log("Sending message to:" + to + " FAILED"); Logger.error("Sys.sendEmail() failed to send message. Messaging Exception: " + mex.toString()); } // log the data Syslog logEntry = new Syslog(); logEntry.setDescription("OK [ email sent from: " + fro + " to: " + to + "]"); logEntry.setUserId(from.getId()); logEntry.setEventType(SystemConstants.LOG_EVENT_TYPE_SEND_EMAIL); logEntry.setSourceId(from.getId()); // unknown logEntry.setSourceType(SystemConstants.TARGET_TYPE_USER); logEntry.setTimestamp(new java.util.Date(System.currentTimeMillis())); SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory(); SqlSession sesh = sqlSessionFactory.openSession(true); sesh.insert("io.starter.dao.SyslogMapper.insert", logEntry); sesh.commit(); if (ltc != null) ltc.countDown(); // release the latch } }).start(); }
From source file:io.starter.model.Content.java
/** * Passing a content rating in, insert into the database and commit * /*w w w. j a va 2 s.c o m*/ * @param contentRating * @throws Exception */ public void insertContentRating(ContentRating contentRating) throws Exception { SqlSession session = MyBatisConnectionFactory.getSqlSessionFactory().openSession(true); try { session.insert("io.starter.dao.ContentRatingMapper.insert", contentRating); } catch (Exception e) { session.close(); throw e; } session.commit(); session.close(); }