List of usage examples for org.apache.ibatis.session SqlSession commit
void commit();
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 w w w .java 2s . c o m*/ * * @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 ww w . j a v a2s . c o 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 * //from w ww . j a v a 2s . co 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 . j a v a 2 s . c om * * @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 w w . 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
/** * /* ww w . j a va2 s .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 av a 2s. c om*/ * @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(); }
From source file:io.starter.TestContent.java
License:Open Source License
/** * test cpntent ownership ratings// w ww.jav a2 s . c o m * * @throws Exception */ @Test public void testOwnershipPermissions() throws Exception { Content content = new Content(); content.setAuthor(42); content.setUserId(42); content.setAuthorDevice(1); content.setCopyright("Copyright 2014. All rights reserved"); content.setDescription("TEST Starter Content"); content.setLicense("CC"); content.setFlag(FLAG_STAR); content.setMimeType("text/html"); content.setUrl("http://$$PROJECT_DOMAIN$$"); content.setPostDate(new java.util.Date(System.currentTimeMillis())); sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory(); SqlSession session = sqlSessionFactory.openSession(true); session.insert("io.starter.dao.ContentMapper.insert", content); session.commit(); Integer id = content.getId(); assertTrue(id != null); Content ccx = session.selectOne("io.starter.dao.ContentMapper.selectObjByPrimaryKey", id); User user = ccx.getUser(); assertTrue(ccx.getUserId() == 42); // assert that contact info is stripped from this assertEquals(null, user.getEmail()); // and that we got the right user assertEquals("test", user.getUsername()); // 1. Build the Subject instance for the test to run: Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject(); // 2. Bind the subject to the current thread: setSubject(subjectUnderTest); // see /login.jsp for these form fields String username = "test"; String password = API_CRYPT_KEY; // create a UsernamePasswordToken using the // username and password provided by the user UsernamePasswordToken token = new UsernamePasswordToken(username, password); // get the user (aka subject) associated with this request. Subject subject = SecurityUtils.getSubject(); try { subject.checkPermission("thing:action"); fail("User INCORRECTLY has permission thing:action"); } catch (AuthorizationException x) { // GOOD! } subject.login(token); user.setSubject(subject); ContentData.setContentOwnerPermissions(content, user, session); WildcardPermission owner = new WildcardPermission(SystemConstants.SECURITY_TARGET_TYPE_CONTENT + ":" + SystemConstants.SECURITY_ACL_OWNER + ":" + content.getId()); assert (user.checkAccess(owner)); // test deletion of that new content session = sqlSessionFactory.openSession(true); session.delete("io.starter.dao.ContentMapper.deleteByPrimaryKey", ccx); try { Content ccd = session.selectOne("io.starter.dao.ContentMapper.selectByPrimaryKey", id); String s1 = ccd.getDescription(); if (s1 != null) fail("Failed to delete inserted Content ID: " + id); } catch (Exception x) { // good! } session.close(); }
From source file:io.starter.TestContent.java
License:Open Source License
/** * test cpntent ratings!//from ww w . ja v a 2s . c om * * @throws Exception */ @Test @Ignore // we don't select ratings objects anymore... revisit someday public void testRatings() throws Exception { Content content = new Content(); content.setAuthor(42); content.setUserId(42); content.setAuthorDevice(1); content.setCopyright("Copyright 2013. All rights reserved"); content.setDescription("TEST Ostrich Pillow"); content.setLicense("CC"); content.setFlag(FLAG_STAR); content.setMimeType("text/html"); content.setUrl("http://www.ostrichpillow.com"); content.setPostDate(new java.util.Date(System.currentTimeMillis())); sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory(); SqlSession session = sqlSessionFactory.openSession(true); session.insert("io.starter.dao.ContentMapper.insert", content); Integer id = content.getId(); assertTrue(id != null); // rate the bastard ContentRating rx = new ContentRating(); rx.setContentId(id); rx.setFlag(0); rx.setRaterId(1); rx.setReview("that kinda sucked"); rx.setType(1); rx.setValue((long) 3); session.insert("io.starter.dao.ContentRatingMapper.insert", rx); session.commit(); Content ccx = session.selectOne("io.starter.dao.ContentMapper.selectObjByPrimaryKey", id); String s = ccx.getDescription(); if (s == null) fail("Failed to insert Content ID: " + id); ArrayList<ContentRating> ratings = ccx.getRatings(); ContentRating rating = ratings.get(0); assertEquals("that kinda sucked", rating.getReview()); User user = ccx.getUser(); assertTrue(ccx.getUserId() == 1); assertEquals("john@$$PROJECT_DOMAIN$$", user.getEmail()); // test deletion of that new content session = sqlSessionFactory.openSession(true); session.delete("io.starter.dao.ContentRatingMapper.deleteByPrimaryKey", rx); session.delete("io.starter.dao.ContentMapper.deleteByPrimaryKey", ccx); session.close(); try { Content ccd = session.selectOne("io.starter.dao.ContentMapper.selectByPrimaryKey", id); String s1 = ccd.getDescription(); if (s1 != null) fail("Failed to delete inserted Content ID: " + id); } catch (Exception x) { // good! } session.close(); }
From source file:jp.escofi.emr.transformer.writer.XmlWriterCallerTestE001_001.java
/** * XML???B/*w w w .j av a 2 s. c o m*/ * * @param dataModel f?[^f * @param attGroup ?O?[v * @throws IOException */ private void insertMeta(TblDataModel dataModel, TblAttributeGroup attGroup) throws IOException { // f?[^ SqlSession session = null; try { session = getSqlSession(); TblMapper dbMapper = session.getMapper(TblMapper.class); dbMapper.deleteAllDatamodel(); dbMapper.deleteAllAttGroup(); session.commit(); dbMapper.insertDatamodel(dataModel); dbMapper.insertAttGroup(attGroup); session.commit(); } finally { if (session != null) { session.close(); } } }