public void testOpenPersistenceManagerInViewInterceptor() throws Exception { MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class); PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock(); MockControl pmControl = MockControl.createControl(PersistenceManager.class); PersistenceManager pm = (PersistenceManager) pmControl.getMock(); OpenPersistenceManagerInViewInterceptor interceptor = new OpenPersistenceManagerInViewInterceptor(); interceptor.setPersistenceManagerFactory(pmf); MockServletContext sc = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(sc); pmf.getPersistenceManager(); pmfControl.setReturnValue(pm, 1); pmfControl.replay(); pmControl.replay(); interceptor.preHandle(new ServletWebRequest(request)); assertTrue(TransactionSynchronizationManager.hasResource(pmf)); // check that further invocations simply participate interceptor.preHandle(new ServletWebRequest(request)); interceptor.preHandle(new ServletWebRequest(request)); interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); interceptor.preHandle(new ServletWebRequest(request)); interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); pmfControl.verify(); pmControl.verify(); pmfControl.reset(); pmControl.reset(); pmfControl.replay(); pmControl.replay(); interceptor.postHandle(new ServletWebRequest(request), null); assertTrue(TransactionSynchronizationManager.hasResource(pmf)); pmfControl.verify(); pmControl.verify(); pmfControl.reset(); pmControl.reset(); pm.close(); pmControl.setVoidCallable(1); pmfControl.replay(); pmControl.replay(); interceptor.afterCompletion(new ServletWebRequest(request), null); assertFalse(TransactionSynchronizationManager.hasResource(pmf)); pmfControl.verify(); pmControl.verify(); }
/** * Set the target JDO PersistenceManagerFactory that this proxy should delegate to. This should be * the raw PersistenceManagerFactory, as accessed by JdoTransactionManager. * * @see org.springframework.orm.jdo.JdoTransactionManager */ public void setTargetPersistenceManagerFactory(PersistenceManagerFactory target) { Assert.notNull(target, "Target PersistenceManagerFactory must not be null"); this.target = target; Class[] ifcs = ClassUtils.getAllInterfacesForClass(target.getClass(), getClass().getClassLoader()); this.proxy = (PersistenceManagerFactory) Proxy.newProxyInstance( target.getClass().getClassLoader(), ifcs, new TransactionAwareFactoryInvocationHandler()); }
public class ConnectionProvider implements DaoServiceLoader { PersistenceManagerFactory presistenceManagerFactory = PMF.get(); PersistenceManager persistenceManager = presistenceManagerFactory.getPersistenceManager(); public void savePojo(UserDetails user) { persistenceManager.makePersistent(user); } @SuppressWarnings("unchecked") public List<UserDetails> getPojo(String facebookId) { Query query = persistenceManager.newQuery(UserDetails.class, "facebookId == '" + facebookId + "'"); return (List<UserDetails>) query.execute(); } @SuppressWarnings("unchecked") public List<UserDetails> getPojoByField(String field, String fieldValue) { Query query = persistenceManager.newQuery(UserDetails.class, field + " == '" + fieldValue + "'"); return (List<UserDetails>) query.execute(); } /*@SuppressWarnings("unchecked") public List<UserDetails> changePassword(String username,String old_Password) { // TODO Auto-generated method stub Query query=persistenceManager.newQuery(UserDetails.class,"user_Name== '"+username+"' && passWord== '"+old_Password+"'"); return (List<UserDetails>)query.execute(); }*/ @SuppressWarnings("unchecked") public List<UserDetails> getAll() { Query query = persistenceManager.newQuery(UserDetails.class); return (List<UserDetails>) query.execute(); } }
@Override @Transactional(readOnly = true) public Collection<Pin> getPins(PnfsId pnfsId) { PersistenceManager pm = _pmf.getPersistenceManager(); Query query = pm.newQuery(Pin.class, "_pnfsId == :pnfsId"); Collection<Pin> pins = (Collection<Pin>) query.execute(pnfsId.toString()); return pm.detachCopyAll(pins); }
public User getUser(String email) { PersistenceManager persistenceManager = pmf.getPersistenceManager(); try { return persistenceManager.getObjectById(User.class, email); } catch (JDOObjectNotFoundException e) { return null; } }
@Override @Transactional(readOnly = true) public Collection<Pin> getPins() { PersistenceManager pm = _pmf.getPersistenceManager(); Query query = pm.newQuery(Pin.class); Collection<Pin> pins = (Collection<Pin>) query.execute(); return pm.detachCopyAll(pins); }
private PersistenceManager getManager() { if (usesXml) { if (!xml.exists() || !xml.isFile()) { if (pmf != null) { pmf.close(); pmf = null; } return null; } } if (pmf == null) { pmf = JDOHelper.getPersistenceManagerFactory(properties); } return pmf.getPersistenceManager(); }
@Override @Transactional(readOnly = true) public Pin getPin(PnfsId pnfsId, String requestId) { PersistenceManager pm = _pmf.getPersistenceManager(); Query query = pm.newQuery(Pin.class, "_pnfsId == :pnfsId && _requestId == :requestId"); query.setUnique(true); Pin pin = (Pin) query.execute(pnfsId.toString(), requestId); return (pin == null) ? null : pm.detachCopy(pin); }
@Override @Transactional(readOnly = true) public Pin getPin(long id, String sticky, Pin.State state) { PersistenceManager pm = _pmf.getPersistenceManager(); Query query = pm.newQuery(Pin.class, "_id == :id && _sticky == :sticky && _state == :state"); query.setUnique(true); Pin pin = (Pin) query.execute(id, sticky, state); return (pin == null) ? null : pm.detachCopy(pin); }
public <T> T getObj(Class<T> c, long id) { PersistenceManager pm = pmf.getPersistenceManager(); try { T obj = pm.getObjectById(c, id); return obj; } finally { pm.close(); } }
@Override public InventoryObject getInventoryObject(String ID) { PersistenceManager persistenceManager = pmf.getPersistenceManager(); try { return persistenceManager.getObjectById(InventoryObject.class, ID); } catch (JDOObjectNotFoundException e) { return null; } }
@Override @Transactional public Pin storePin(Pin pin) { PersistenceManager pm = _pmf.getPersistenceManager(); pin = pm.detachCopy(pm.makePersistent(pin)); if (_log.isDebugEnabled()) { _log.debug(pin.toString()); } return pin; }
public <T> T saveObj(T obj) { PersistenceManager pm = pmf.getPersistenceManager(); try { return pm.makePersistent(obj); } catch (Throwable e) { LOG.warning(e); } finally { pm.close(); } return obj; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); RequestDispatcher rd = null; resp.setContentType("text/html"); PersistenceManager pm = PMF.get().getPersistenceManager(); String name = req.getParameter("name"); // 客の名前 String order = req.getParameter("order"); // 注文するピザのデータストアのIDが入る String count = req.getParameter("count"); // 枚数が入る Date date = Calendar.getInstance().getTime(); String ordername = ""; String orderid = order; int price = 0; String query = "select from " + PizzaData.class.getName() + " where id == " + order; List<PizzaData> datas = (List<PizzaData>) pm.newQuery(query).execute(); for (PizzaData data : datas) { ordername = data.getName(); price = Integer.parseInt(data.getPrice()); } order = ordername; price = price * Integer.parseInt(count); String orderprice = Integer.toString(price); CustomerData data = new CustomerData(name, ordername, count, date); PersistenceManagerFactory factory = PMF.get(); PersistenceManager manager = factory.getPersistenceManager(); try { manager.makePersistent(data); req.setAttribute("price", orderprice); // ピザの値段 req.setAttribute("pizza", ordername); // 頼んだピザの名前 req.setAttribute("name", name); // 客の名前 req.setAttribute("count", count); // ピザの枚数 rd = req.getRequestDispatcher("/shop.jsp"); } finally { manager.close(); rd.forward(req, resp); } }
public static void main(String[] args) { PersistenceManagerFactory pmf = JdoUtils.getPMF(); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Query q = pm.newQuery(Country.class, "name == givenName"); q.declareParameters("String givenName"); q.setUnique(true); Country aus = (Country) q.execute("Aus"); // detaching null does not cause any problem aus = pm.detachCopy(aus); System.out.println("aus = " + aus); q.closeAll(); tx.commit(); } finally { if (tx.isActive()) tx.rollback(); pm.close(); } }
public <T> T getArbitrary(Class<T> classObj) { PersistenceManager pm = pmf.getPersistenceManager(); try { Extent<T> result = pm.getExtent(classObj, false); return result.iterator().next(); } catch (Throwable e) { LOG.warning(e); } finally { pm.close(); } return null; }
@Override @Transactional public void deletePin(Pin pin) { try { PersistenceManager pm = _pmf.getPersistenceManager(); pm.deletePersistent(pin); } catch (JDOObjectNotFoundException e) { /* The pin was already deleted (maybe because the file was * deleted). We don't care. */ _log.debug("Pin deletion failed: {}", e); } }
@SuppressWarnings("unchecked") @Override // Checks if campaign name already exists public String existsCampaign(String campaignName) { PersistenceManager pm = PMF.getPersistenceManager(); Extent<Campaign> campaignExtent = pm.getExtent(Campaign.class, true); Query campaignQuery = pm.newQuery(campaignExtent, "name == '" + campaignName + "'"); List<Campaign> chars = (List<Campaign>) campaignQuery.execute(); if (!chars.isEmpty()) { return "FAILURE"; } return "SUCCESS"; }
private void begin() { lock.lock(); try { if (isActive()) throw new IllegalStateException("Transaction is already active!"); lockIfWrite(); persistenceManager = persistenceManagerFactory.getPersistenceManager(); jdoTransaction = persistenceManager.currentTransaction(); jdoTransaction.begin(); listenerRegistry.onBegin(); } finally { lock.unlock(); } }
/** Tests the case when the user has not started the authorization process (no request token). */ public final void testCheckAuthorizationNoRequestToken() { // Setup. LoginFormHandler loginForm = mock(LoginFormHandler.class); OAuthClient client = mock(OAuthClient.class); PersistenceManager pm = mock(PersistenceManager.class); PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class); OAuthAccessor accessor = buildAccessor( CONSUMER_KEY, CONSUMER_SECRET, REQUEST_TOKEN_URL, AUTHORIZE_URL, CALLBACK_URL, ACCESS_TOKEN_URL); accessor.requestToken = REQUEST_TOKEN_STRING; oauthService = new OAuthServiceImpl(accessor, client, pmf, USER_RECORD_KEY); OAuthUser userWithRequestToken = new OAuthUser(USER_RECORD_KEY, REQUEST_TOKEN_STRING); // Expectations. when(pmf.getPersistenceManager()).thenReturn(pm); when(pm.getObjectById(OAuthUser.class, USER_RECORD_KEY)) .thenReturn(null, userWithRequestToken, userWithRequestToken); assertFalse(oauthService.checkAuthorization(null, loginForm)); String authUrl = userWithRequestToken.getAuthUrl(); try { new URL(authUrl); } catch (MalformedURLException e) { fail("Malformed authUrl"); } assertTrue(Pattern.matches(".+(oauth_token){1}.+", authUrl)); assertTrue(Pattern.matches(".+(oauth_callback){1}.+", authUrl)); }
@Override @Transactional(readOnly = true) public boolean hasSharedSticky(Pin pin) { PersistenceManager pm = _pmf.getPersistenceManager(); Query query = pm.newQuery( Pin.class, "_pnfsId == :pnfsId && _id != :id && _pool == :pool && _sticky == :sticky && _state != 'UNPINNING'"); query.setResult("count(this)"); return ((Long) query.executeWithArray( pin.getPnfsId().toString(), pin.getPinId(), pin.getPool(), pin.getSticky())) > 0; }
public <T> List<T> getAll(Class<T> c) { PersistenceManager pm = pmf.getPersistenceManager(); try { Extent<T> result = pm.getExtent(c, false); List<T> buffer = new ArrayList<T>(); for (T t : result) { buffer.add(t); } return buffer; } catch (Throwable e) { LOG.warning(e); } finally { pm.close(); } return new ArrayList<T>(); }
@Override @Transactional public void expirePins() { Date now = new Date(); PersistenceManager pm = _pmf.getPersistenceManager(); Query query = pm.newQuery(Pin.class, "_expirationTime < :now && _state != 'UNPINNING'"); query.addExtension("datanucleus.rdbms.query.resultSetType", "scroll-insensitive"); query.addExtension("datanucleus.query.resultCacheType", "none"); query.getFetchPlan().setFetchSize(FetchPlan.FETCH_SIZE_OPTIMAL); try { for (Pin pin : (Collection<Pin>) query.execute(now)) { pin.setState(Pin.State.UNPINNING); } } finally { query.closeAll(); } }
@RequestMapping(value = "expense", method = RequestMethod.POST) public ModelAndView createExpense(Expense expense) { if (expense.getDate() == null) { expense.setDate(new Date()); } User user = userService.currentUser(); Key key = user.getKey(); PersistenceManager pm = factory.getPersistenceManager(); try { User userInThisSession = pm.getObjectById(User.class, key); expense.setUser(userInThisSession); pm.makePersistent(expense); } finally { pm.close(); } return new ModelAndView("redirect:/expenses"); }
@Override @Transactional public boolean all(Pin.State state, Predicate<Pin> f) { PersistenceManager pm = _pmf.getPersistenceManager(); Query query = pm.newQuery(Pin.class, "_state == :state"); query.addExtension("datanucleus.rdbms.query.resultSetType", "scroll-insensitive"); query.addExtension("datanucleus.query.resultCacheType", "none"); query.getFetchPlan().setFetchSize(FetchPlan.FETCH_SIZE_OPTIMAL); try { for (Pin pin : (Collection<Pin>) query.execute(state)) { if (!f.apply(pm.detachCopy(pin))) { return false; } } } finally { query.closeAll(); } return true; }
public <T> List<T> getQuery( Class<T> c, String queryString, String parameterDeclaration, Object... parameters) { PersistenceManager pm = pmf.getPersistenceManager(); try { Query query = pm.newQuery(c, queryString); query.declareParameters(parameterDeclaration); List<T> list = (List<T>) query.executeWithArray(parameters); List<T> buffer = new ArrayList<T>(); for (T t : list) { buffer.add(t); } query.closeAll(); return buffer; } catch (Throwable e) { LOG.warning(e); } finally { pm.close(); } return new ArrayList<T>(); }
@SuppressWarnings("unchecked") @Override public List<Campaign> getCampaigns(String username) { try { PersistenceManager pm = PMF.getPersistenceManager(); Extent<Campaign> extent = pm.getExtent(Campaign.class, true); Query query = pm.newQuery(extent, "username == '" + username + "'"); List<Campaign> ret = new ArrayList<Campaign>(); for (Campaign campaign : (List<Campaign>) query.execute()) { pm.retrieve(campaign); ret.add(pm.detachCopy(campaign)); } return ret; } catch (Exception e) { e.printStackTrace(); } return null; }
// @SuppressWarnings("unchecked") private String saveCampaignToDB(Campaign campaign) { PersistenceManager pm = PMF.getPersistenceManager(); // check if campaign name already exists // Extent<Campaign> campaignExtent = pm.getExtent(Campaign.class, true); // Query campaignQuery = pm.newQuery(campaignExtent, "name == " + campaign.getName()); // List<Campaign> chars = (List<Campaign>) campaignQuery.execute(); // if (!chars.isEmpty()) { // return "FAILURE"; // } try { // campaign.setAllAttrInfo(); pm.makePersistent(campaign); pm.close(); } catch (Exception e) { e.printStackTrace(); } return "SUCCESS"; }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestURL = req.getRequestURL().toString(); if (!debug && !requestURL.startsWith(this.baseURL) && !requestURL.contains(".latest.")) { resp.sendRedirect(baseURL); return; } PersistenceManager pm = pmf.getPersistenceManager(); try { req.setAttribute("recentScripts", getRecentScripts(pm)); req.setAttribute("tagCloud", getTagCloud(pm)); UserService userSvc = UserServiceFactory.getUserService(); if (userSvc.isUserLoggedIn()) req.setAttribute("logoutURL", userSvc.createLogoutURL(req.getRequestURI())); else req.setAttribute("loginURL", userSvc.createLoginURL(req.getRequestURI())); super.getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp); } finally { pm.close(); } }
private PersistenceManager getPersistenceManager() { return PMF.getPersistenceManager(); }