List of usage examples for org.joda.time DateTime getMillis
public long getMillis()
From source file:com.tremolosecurity.proxy.auth.PasswordReset.java
License:Apache License
private void finishLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session, AuthChainType act, int step, AuthMechType amt, int minValidKey, String key, org.hibernate.Session con, RequestHolder reqHolder, AuthStep as) throws SQLException, ServletException, IOException { if (!this.enabled) { throw new ServletException("Operation Not Supported"); }//w ww .j a v a2 s. c o m HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session .getAttribute(ProxyConstants.AUTH_MECH_PARAMS); int maxChecks = 0; if (authParams.containsKey("maxChecks")) { maxChecks = Integer.parseInt(authParams.get("maxChecks").getValues().get(0)); } else { maxChecks = 1; } DateTime now = new DateTime().minusMinutes(minValidKey); Query query = con.createQuery( "FROM PasswordResetRequest r WHERE r.resetKey = :resetkey AND r.ts > :ts AND r.numRequests < :numRequests"); query.setParameter("resetkey", key); query.setParameter("ts", new Timestamp(now.getMillis())); query.setParameter("numRequests", maxChecks); List<PasswordResetRequest> resetRequests = query.list(); if (resetRequests == null || resetRequests.isEmpty()) { as.setSuccess(false); } else { PasswordResetRequest req = resetRequests.get(0); String email = req.getEmail(); try { LDAPSearchResults res = this.cfgMgr.getMyVD().search(AuthUtil.getChainRoot(cfgMgr, act), 2, equal(this.lookupAttributeName, email).toString(), new ArrayList<String>()); if (res.hasMore()) { LDAPEntry entry = res.next(); Iterator<LDAPAttribute> it = entry.getAttributeSet().iterator(); AuthInfo authInfo = new AuthInfo(entry.getDN(), (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(), act.getLevel()); ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo); while (it.hasNext()) { LDAPAttribute attrib = it.next(); Attribute attr = new Attribute(attrib.getName()); String[] vals = attrib.getStringValueArray(); for (int i = 0; i < vals.length; i++) { attr.getValues().add(vals[i]); } authInfo.getAttribs().put(attr.getName(), attr); } as.setSuccess(true); } else { as.setSuccess(false); } } catch (LDAPException e) { logger.error("Could not authenticate user", e); as.setSuccess(false); } con.beginTransaction(); req.setNumRequests(req.getNumRequests() + 1); if (req.getNumRequests() < maxChecks) { con.save(req); } else { con.delete(req); } con.getTransaction().commit(); } String redirectToURL = null; if (as.isSuccess()) { reqHolder.setURL(this.getFinalURL(request, response)); } else { request.getParameter("target"); if (redirectToURL != null && !redirectToURL.isEmpty()) { reqHolder.setURL(redirectToURL); } } this.cfgMgr.getAuthManager().nextAuth(request, response, session, false); }
From source file:com.tremolosecurity.proxy.auth.PasswordReset.java
License:Apache License
private void sendPasswordReset(org.hibernate.Session con, String uid, String emailAddress) throws SQLException, Exception { GenPasswd gp = new GenPasswd(30); String key = gp.getPassword(); DateTime now = new DateTime(); PasswordResetRequest req = new PasswordResetRequest(); req.setEmail(uid);//from w ww. jav a 2 s. c o m req.setResetKey(key); req.setTs(new Timestamp(now.getMillis())); con.beginTransaction(); con.save(req); con.getTransaction().commit(); this.sendEmail(emailAddress, key); }
From source file:com.tremolosecurity.proxy.auth.PasswordReset.java
License:Apache License
@Override public void run() { while (this.running) { PasswordReset.logger.info("Clearing Expired Tokens"); org.hibernate.Session con = null; try {// w w w.ja v a 2 s . c o m con = this.sessionFactory.openSession(); DateTime expires = new DateTime().minusMinutes(this.minutes); con.beginTransaction(); Query delq = con.createQuery("DELETE FROM PasswordResetRequest r WHERE r.ts <= :ts"); delq.setParameter("ts", new Timestamp(expires.getMillis())); delq.executeUpdate(); con.getTransaction().commit(); } finally { if (con != null) { con.close(); } } try { //TODO //I hate threads synchronized (this) { this.wait(30000); } } catch (InterruptedException e) { this.running = false; } } }
From source file:com.tremolosecurity.proxy.auth.sys.AuthManagerImpl.java
License:Apache License
private void failAuthentication(HttpServletRequest req, HttpServletResponse resp, UrlHolder holder, AuthChainType act) throws ServletException, IOException, Exception { AccessLog.log(AccessEvent.AuFail, holder.getApp(), req, null, act.getName()); req.setAttribute(AuthMgrSys.AU_RES, new Boolean(false)); AuthMgrSys ams = new AuthMgrSys(null); try {/*from w w w. ja v a 2s .c o m*/ ams.processAuthResp(req, resp, holder, new Boolean(false)); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new ServletException("Could not initialize custom response", e); } if (act.getCompliance() != null && act.getCompliance().isEnabled()) { String dn = getFailedUserDN(req); if (dn != null) { ArrayList<String> attrsToLoad = new ArrayList<String>(); attrsToLoad.add(act.getCompliance().getNumFailedAttribute()); attrsToLoad.add(act.getCompliance().getUidAttributeName()); LDAPSearchResults res = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(dn, 0, "(objectClass=*)", attrsToLoad); if (res.hasMore()) { LDAPEntry userObj = res.next(); String uid = userObj.getAttribute(act.getCompliance().getUidAttributeName()).getStringValue(); LDAPAttribute numFails = userObj.getAttribute(act.getCompliance().getNumFailedAttribute()); int fails = 0; if (numFails != null) { fails = Integer.parseInt(numFails.getStringValue()); } fails++; User updateAttrs = new User(uid); DateTime now = new DateTime(DateTimeZone.UTC); updateAttrs.getAttribs().put(act.getCompliance().getLastFailedAttribute(), new Attribute( act.getCompliance().getLastFailedAttribute(), Long.toString(now.getMillis()))); updateAttrs.getAttribs().put(act.getCompliance().getNumFailedAttribute(), new Attribute(act.getCompliance().getNumFailedAttribute(), Integer.toString(fails))); updateAttrs.getAttribs().put(act.getCompliance().getUidAttributeName(), new Attribute(act.getCompliance().getUidAttributeName(), uid)); HashMap<String, Object> wfReq = new HashMap<String, Object>(); wfReq.put(ProvisioningParams.UNISON_EXEC_TYPE, ProvisioningParams.UNISON_EXEC_SYNC); //load attributes from the user object if it exists /*AuthInfo userData = ((AuthController) req.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo(); if (GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getUserAttrbiutes() != null) { for (String attrName : GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getUserAttrbiutes()) { Attribute fromAuth = userData.getAttribs().get(attrName); if (fromAuth != null) { Attribute attrForWF = new Attribute(attrName); attrForWF.getValues().addAll(fromAuth.getValues()); updateAttrs.getAttribs().put(attrName,attrForWF); } } }*/ holder.getConfig().getProvisioningEngine() .getWorkFlow(act.getCompliance().getUpdateAttributesWorkflow()) .executeWorkflow(updateAttrs, wfReq); } } } }
From source file:com.tremolosecurity.proxy.filters.CheckSession.java
License:Apache License
@Override public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception { request.setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError"); ArrayList<Cookie> sessionCookies = request.getCookies(this.cookieName); if (sessionCookies == null || sessionCookies.isEmpty()) { response.sendError(401);/* w ww. j a v a 2s . c o m*/ } else { for (Cookie cookie : sessionCookies) { TremoloHttpSession session = SessionManagerImpl.findSessionFromCookie(cookie, this.secretKey, (SessionManagerImpl) GlobalEntries.getGlobalEntries() .get(ProxyConstants.TREMOLO_SESSION_MANAGER)); if (session == null) { response.sendError(401); } else { AuthInfo userData = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)) .getAuthInfo(); if (userData == null || !userData.isAuthComplete() || userData.getAuthLevel() == 0) { response.sendError(401); } else { SessionInfo si = new SessionInfo(); if (this.timeoutSeconds > 0) { DateTime lastAccessed = (DateTime) session .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED); DateTime now = new DateTime(); DateTime expires = lastAccessed.plusSeconds(this.timeoutSeconds); si.setMinsLeft((int) ((expires.getMillis() - System.currentTimeMillis()) / 1000 / 60)); } else { si.setMinsLeft(-1); } String json = gson.toJson(si); response.setContentType("application/json"); response.getWriter().println(json.trim()); response.sendError(200); } } } } }
From source file:com.trifork.stamdata.importer.jobs.sikrede.BrsUpdater.java
License:Mozilla Public License
void closeRelationship(long primaryKey, DateTime assignedTo) throws SQLException { PreparedStatement preparedStatement = connection .prepareStatement("UPDATE AssignedDoctor SET assignedTo = ? WHERE pk = ?"); preparedStatement.setDate(1, new Date(assignedTo.getMillis())); preparedStatement.setLong(2, primaryKey); preparedStatement.executeUpdate();/* ww w.j a va 2s. c o m*/ }
From source file:com.trifork.stamdata.importer.jobs.sikrede.BrsUpdater.java
License:Mozilla Public License
void insertRelationship(String patientCpr, String doctorOrganisationIdentifier, DateTime assignedFrom, DateTime assignedTo) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement( "INSERT INTO AssignedDoctor (patientCpr, doctorOrganisationIdentifier, assignedFrom, assignedTo, reference) VALUES (?, ?, ?, ?, ?)"); preparedStatement.setString(1, patientCpr); preparedStatement.setString(2, doctorOrganisationIdentifier); preparedStatement.setDate(3, new Date(assignedFrom.getMillis())); if (assignedTo != null) { preparedStatement.setDate(4, new Date(assignedTo.getMillis())); } else {// ww w . j a va2 s .c om preparedStatement.setNull(4, java.sql.Types.NULL); } preparedStatement.setString(5, new DateTime().toString()); preparedStatement.executeUpdate(); }
From source file:com.turn.sorcerer.status.impl.ZookeeperStatusStorage.java
License:Open Source License
@Override public void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException { String path = PATH.join(root, type, identifier, jobId, status); // Create ephemeral node for in progress if (status == Status.IN_PROGRESS) { // Destroy node if it already exists try {// w ww . j av a 2s . co m if (curator.checkExists().forPath(path) != null) { curator.delete().forPath(path); } } catch (Exception e) { // ignore exception for this call } // Create ephemeral node try { curator.create().withMode(CreateMode.EPHEMERAL).forPath(path); } catch (Exception e) { throw new IOException(e); } } else { try { ZKPaths.mkdirs(curator.getZookeeperClient().getZooKeeper(), path); curator.checkExists().forPath(path).setCtime(time.getMillis()); } catch (Exception e) { throw new IOException(e); } } }
From source file:com.twentyn.bioreactor.pH.ControlSystem.java
License:Open Source License
private Long timeDifference(DateTime longerTime, DateTime shorterTime) { return longerTime.getMillis() - shorterTime.getMillis(); }
From source file:com.twolinessoftware.authentication.AuthenticationManager.java
License:Apache License
public void completeLogin(Intent intent) { String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); final Account account = new Account(accountName, Config.BASE_ACCOUNT_TYPE); String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN); String authtokenType = Config.BASE_ACCOUNT_TYPE; ContentResolver.setSyncAutomatically(account, Config.BASE_ACCOUNT_TYPE, true); ContentResolver.setIsSyncable(account, Config.BASE_ACCOUNT_TYPE, 1); mAccountManager.addAccountExplicitly(account, null, null); mAccountManager.setAuthToken(account, authtokenType, authtoken); String password = intent.getStringExtra(AuthenticationManager.KEY_ACCOUNT_PASSWORD); mAccountManager.setPassword(account, password); long expirySec = intent.getLongExtra(AuthenticationManager.KEY_AUTH_TOKEN_EXPIRY, TimeUnit.DAYS.toSeconds(1)); DateTime expiry = DateTime.now().plusSeconds((int) expirySec); mAccountManager.setUserData(account, AuthenticationManager.KEY_AUTH_TOKEN_EXPIRY, String.valueOf(expiry.getMillis())); mUserManager.registerAuthListener(this); }