private static void printTimeSeries( String filename, String title, MergeMap.MinMap<String, Timestamp> firstUse) throws FileNotFoundException { PrintWriter out = new PrintWriter(filename); out.println(title + ",time,full time"); TreeSet<TimeSeries<String, Timestamp>> series = new TreeSet<TimeSeries<String, Timestamp>>(); for (Map.Entry<String, Timestamp> e : firstUse.entrySet()) { series.add(new TimeSeries<String, Timestamp>(e.getKey(), e.getValue())); } Multiset<Timestamp> counter = new Multiset<Timestamp>(new TreeMap<Timestamp, Integer>()); for (TimeSeries<String, Timestamp> t : series) { counter.add(bucketByHour(t.v)); } int total = 0; SimpleDateFormat format = new SimpleDateFormat("h a EEE"); SimpleDateFormat defaultFormat = new SimpleDateFormat(); for (Map.Entry<Timestamp, Integer> e : counter.entrySet()) { Timestamp time = e.getKey(); total += e.getValue(); if (time.after(fixitStart)) out.printf("%d,%s,%s%n", total, format.format(time), defaultFormat.format(time)); } out.close(); }
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase("rtp")) { if (sender instanceof Player) { Player player = (Player) sender; if (player.hasPermission("precipice.canrtp")) { if (lastrtp.containsKey(player)) { if (player.isOp()) randomTP(player); Timestamp last = new Timestamp(lastrtp.get(player) + (config.getLong("time") * 60 * 1000)); Date date = new Date(); Timestamp now = new Timestamp(date.getTime()); if (now.after(last)) { randomTP(player); } else { player.sendMessage("Sorry, you must wait to randomly teleport again"); } } else { randomTP(player); } } else { player.sendMessage("You don't have permission to run this command"); } } else { sender.sendMessage("This doesn't make sense to run from the console."); } } return true; }
private boolean isAccountExpire(Timestamp accessStartDate, Timestamp accessExpiryDate) { Timestamp currentDttm = new Timestamp(System.currentTimeMillis()); LOGGER.info("accessStartDate:---" + accessStartDate); LOGGER.info("accessExpiryDate:---" + accessExpiryDate); LOGGER.info("currentDttm:---" + currentDttm); // Checking if Current Date is between Access StartDate and ExpiryDate if (currentDttm.after(accessStartDate) && currentDttm.before(accessExpiryDate)) return false; else return true; }
/** * Date In Period * * @param date date * @return true if in period */ public boolean isInPeriod(Timestamp date) { if (date == null) return false; Timestamp dateOnly = TimeUtil.getDay(date); Timestamp from = TimeUtil.getDay(getStartDate()); if (dateOnly.before(from)) return false; Timestamp to = TimeUtil.getDay(getEndDate()); if (dateOnly.after(to)) return false; return true; } // isInPeriod
/** * Check conflictin update events. * * @param newEvent the new event * @return true, if successful * @throws ParseException the parse exception */ @SuppressLint("LongLogTag") public boolean checkConflictinUpdateEvents(Event newEvent) throws ParseException { SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm"); String sTime = newEvent.getStartTime(); String sDate = newEvent.getStartDate(); String eTime = newEvent.getEndTime(); String eDate = newEvent.getEndDate(); Date parsedStartTime = timeFormat.parse(sTime); Timestamp newStartTime = new Timestamp(parsedStartTime.getTime()); Date parsedEndTime = timeFormat.parse(eTime); Timestamp newEndTime = new Timestamp(parsedEndTime.getTime()); if (sDate.equalsIgnoreCase(eDate)) { if (newStartTime.after(newEndTime)) { Log.e("Illogiacl Update", "StartTime is greater then EndTime"); return false; } } List<Event> allEvents = getEvent(sDate, eDate); for (Event prevEvent : allEvents) { Log.d( "Event: " + prevEvent.getTitle(), "" + prevEvent.getId() + " " + prevEvent.getDescription()); Date parsedPreviousStartTime = timeFormat.parse(prevEvent.getStartTime()); Timestamp previousStartTime = new Timestamp(parsedPreviousStartTime.getTime()); Date parsedPreviousEndTime = timeFormat.parse(prevEvent.getEndTime()); Timestamp previousEndTime = new Timestamp(parsedPreviousEndTime.getTime()); if (newStartTime.after(previousStartTime) && newStartTime.before(previousEndTime) || newEndTime.after(previousStartTime) && newEndTime.before(previousEndTime) || previousStartTime.after(newStartTime) && previousStartTime.before(newEndTime) || previousEndTime.after(newStartTime) && previousEndTime.before(newEndTime)) { if (newEvent.getId() != prevEvent.getId()) { Log.e("Conflict with existent event", "Can't update this event"); return false; } } } return true; }
private Boolean isAccountExpired( Timestamp accessStartDate, Timestamp accessExpiryDate, String username, Integer userid) { Timestamp currentDttm = new Timestamp(System.currentTimeMillis()); if (accessExpiryDate != null && accessStartDate != null) { // Checking if Current Date is between Access StartDate and ExpiryDate if (currentDttm.after(accessStartDate) && currentDttm.before(accessExpiryDate)) { return false; } } // unlimited access else if (currentDttm.after(accessStartDate) && accessExpiryDate == null) { return false; } // log user for account expire saveUserAccessLog( "139004", messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired"), username, userid); return true; }
public void run() { String filename = requestParams.get("filename"); String tsp = requestParams.get("timestamp").replace('+', ' '); Timestamp requestDate = null; if (!tsp.equals("start")) requestDate = Timestamp.valueOf(tsp); String responseBody = "{\"changes\": ["; String line; File f = new File(filename + "log"); try { if (f.exists() && !f.isDirectory()) { BufferedReader br; br = new BufferedReader(new FileReader(f)); boolean addChanges = false; if (requestDate == null) addChanges = true; if (br.ready()) while ((line = br.readLine()) != null) { String[] aux = line.split("/"); Timestamp changeDate = Timestamp.valueOf(aux[aux.length - 1]); if (!addChanges) { if (changeDate.after(requestDate)) addChanges = true; } if (addChanges) { responseBody += "'"; responseBody += line; responseBody += "'"; responseBody += ","; } } br.close(); } responseBody += "]}"; System.out.println(responseBody); header.set("Content-Type", "application/json"); byte[] rawResponseBody = responseBody.getBytes(CHARSET); t.sendResponseHeaders(200, rawResponseBody.length); OutputStream os = t.getResponseBody(); os.write(rawResponseBody); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void clearPeriodList(String entryBeginDate, String entryEndDate) { String entry = null; Timestamp feedBeginDate = null; Timestamp feedEndDate = null; Timestamp entryBeginDateTs = getTimeStampFromString(entryBeginDate); Timestamp entryEndDateTs = getTimeStampFromString(entryEndDate); for (int i = 0; i < rssFileURIsCacheListByPeriod.size(); i++) { entry = (String) rssFileURIsCacheListByPeriod.get(i); if (entry.startsWith("period")) { feedBeginDate = getTimeStampFromString(entry.substring(7, 15)); feedEndDate = getTimeStampFromString(entry.substring(16, 24)); } if (!(entryBeginDateTs.after(feedEndDate) || entryEndDateTs.before(feedBeginDate))) { rssFileURIsCacheListByPeriod.remove(i); } } }
/** * Returns a formatted string that indicates the last time a Ticket was worked on (in other words, * the date of the last annotation) */ public static String getLastActivity(int ticketNumber) { DBHelper db = DBHelperFactory.createDBHelper(); ArrayList<Annotation> annos = db.createAnnotationArrayListByTicket(ticketNumber); java.sql.Timestamp lastActivity = new java.sql.Timestamp(0L); for (int i = 0; i < annos.size(); i++) { java.sql.Timestamp ts = annos.get(i).getCreatedOn(); if (ts.after(lastActivity)) { lastActivity.setTime(ts.getTime()); } } String result = getTime(lastActivity); db.close(); return result; }
/** * returns the surrounding segementaion stamp according to the timestamps * * @param start start timestamp * @param end end timestamp * @return surrounding segmentation rate */ private double getSegmentationRate(Timestamp start, Timestamp end) { if (segmentationRates != null) { List<Timestamp> ts = new ArrayList<Timestamp>(segmentationRates.keySet()); Collections.sort(ts); int i = 0; while (i < ts.size() && start.before(ts.get(i))) { i++; } double rate = segmentationRates.get(ts.get(i)); int buckets = 1; i++; while (i < ts.size() && end.after(ts.get(i))) { rate += segmentationRates.get(ts.get(i)); buckets++; i++; } return rate / buckets; } else { return -1.0; } }
/** * Makes a list of TrackingCodeOrder entities to be attached to the current order; called by the * createOrder event; the values in the returned List will not have the orderId set */ public static List<GenericValue> makeTrackingCodeOrders(HttpServletRequest request) { Delegator delegator = (Delegator) request.getAttribute("delegator"); java.sql.Timestamp nowStamp = UtilDateTime.nowTimestamp(); List<GenericValue> trackingCodeOrders = FastList.newInstance(); Cookie[] cookies = request.getCookies(); Timestamp affiliateReferredTimeStamp = null; String siteId = null; String isBillable = null; String trackingCodeId = null; if (cookies != null && cookies.length > 0) { for (int i = 0; i < cookies.length; i++) { String cookieName = cookies[i].getName(); Debug.logInfo(" cookieName is " + cookieName, module); Debug.logInfo(" cookieValue is " + cookies[i].getValue(), module); // find the siteId cookie if it exists if ("Ofbiz.TKCD.SiteId".equals(cookieName)) { siteId = cookies[i].getValue(); } // find the referred timestamp cookie if it exists if ("Ofbiz.TKCD.UpdatedTimeStamp".equals(cookieName)) { String affiliateReferredTime = cookies[i].getValue(); if (affiliateReferredTime != null && !affiliateReferredTime.equals("")) { try { affiliateReferredTimeStamp = Timestamp.valueOf(affiliateReferredTime); } catch (IllegalArgumentException e) { Debug.logError( e, "Error parsing affiliateReferredTimeStamp value from cookie", module); } } } // find any that start with TKCDB_ for billable tracking code cookies with isBillable=Y // also and for each TKCDT_ cookie that doesn't have a corresponding billable code add it to // the list with isBillable=N // This cookie value keeps trackingCodeId if (cookieName.startsWith("TKCDB_")) { isBillable = "Y"; trackingCodeId = cookies[i].getValue(); } else if (cookieName.startsWith("TKCDT_")) { isBillable = "N"; trackingCodeId = cookies[i].getValue(); } } } GenericValue trackingCode = null; try { trackingCode = delegator.findByPrimaryKeyCache( "TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId)); } catch (GenericEntityException e) { Debug.logError( e, "Error looking up TrackingCode with trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId", module); } if (trackingCode != null) { // check effective dates if (trackingCode.get("fromDate") != null && nowStamp.before(trackingCode.getTimestamp("fromDate"))) { if (Debug.infoOn()) Debug.logInfo( "The TrackingCode with ID [" + trackingCodeId + "] has not yet gone into effect, ignoring this trackingCodeId", module); } if (trackingCode.get("thruDate") != null && nowStamp.after(trackingCode.getTimestamp("thruDate"))) { if (Debug.infoOn()) Debug.logInfo( "The TrackingCode with ID [" + trackingCodeId + "] has expired, ignoring this trackingCodeId", module); } GenericValue trackingCodeOrder = delegator.makeValue( "TrackingCodeOrder", UtilMisc.toMap( "trackingCodeTypeId", trackingCode.get("trackingCodeTypeId"), "trackingCodeId", trackingCodeId, "isBillable", isBillable, "siteId", siteId, "hasExported", "N", "affiliateReferredTimeStamp", affiliateReferredTimeStamp)); Debug.logInfo(" trackingCodeOrder is " + trackingCodeOrder, module); trackingCodeOrders.add(trackingCodeOrder); } else { // Only log an error if there was a trackingCodeId to begin with if (trackingCodeId != null) { Debug.logError( "TrackingCode not found for trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId.", module); } } return trackingCodeOrders; }
public static String checkAccessTrackingCode( HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); java.sql.Timestamp nowStamp = UtilDateTime.nowTimestamp(); String trackingCodeId = request.getParameter("autoTrackingCode"); if (UtilValidate.isEmpty(trackingCodeId)) trackingCodeId = request.getParameter("atc"); if (UtilValidate.isEmpty(trackingCodeId)) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("TKCDT_ACCESS".equals(cookie.getName())) { trackingCodeId = cookie.getValue(); } } } } if (UtilValidate.isNotEmpty(trackingCodeId)) { // find the tracking code object GenericValue trackingCode = null; try { trackingCode = delegator.findByPrimaryKeyCache( "TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId)); } catch (GenericEntityException e) { Debug.logError( e, "Error looking up TrackingCode with trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId", module); } if (trackingCode != null) { // verify the tracking code type if ("ACCESS".equals(trackingCode.getString("trackingCodeTypeId"))) { // verify the effective date if (trackingCode.get("fromDate") != null && nowStamp.after(trackingCode.getTimestamp("fromDate"))) { if (trackingCode.get("thruDate") != null && nowStamp.before(trackingCode.getTimestamp("thruDate"))) { // tracking code is valid return "success"; } else { if (Debug.infoOn()) Debug.logInfo( "The TrackingCode with ID [" + trackingCodeId + "] has expired, ignoring this trackingCodeId", module); request.setAttribute( "_ERROR_MESSAGE_", "Access code [" + trackingCodeId + "], is not valid."); } } else { if (Debug.infoOn()) Debug.logInfo( "The TrackingCode with ID [" + trackingCodeId + "] has not yet gone into effect, ignoring this trackingCodeId", module); request.setAttribute( "_ERROR_MESSAGE_", "Access code [" + trackingCodeId + "], is not valid."); } } else { Debug.logWarning( "Tracking code found [" + trackingCodeId + "] but was not of the type ACCESS; access denied", module); request.setAttribute( "_ERROR_MESSAGE_", "Access code [" + trackingCodeId + "] not found."); } } else { request.setAttribute("_ERROR_MESSAGE_", "Access code [" + trackingCodeId + "] not found."); } } // no tracking code or tracking code invalid; redirect to the access page (i.e. request named // 'protect') return ":_protect_:"; }
/** * If attaching TrackingCode Cookies to the visit is desired this event should be added to the * list of events that run on the first hit in a visit. */ public static String checkTrackingCodeCookies( HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); java.sql.Timestamp nowStamp = UtilDateTime.nowTimestamp(); GenericValue visit = VisitHandler.getVisit(request.getSession()); if (visit == null) { Debug.logWarning( "Could not get visit, not checking trackingCode cookies to associate with visit", module); } else { // loop through cookies and look for ones with a name that starts with TKCDT_ for trackable // cookies Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().startsWith("TKCDT_")) { String trackingCodeId = cookies[i].getValue(); GenericValue trackingCode; try { trackingCode = delegator.findByPrimaryKeyCache( "TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId)); } catch (GenericEntityException e) { Debug.logError( e, "Error looking up TrackingCode with trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId", module); continue; } if (trackingCode == null) { Debug.logError( "TrackingCode not found for trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId.", module); // this return value will be ignored, but we'll designate this as an error anyway continue; } // check effective dates if (trackingCode.get("fromDate") != null && nowStamp.before(trackingCode.getTimestamp("fromDate"))) { if (Debug.infoOn()) Debug.logInfo( "The TrackingCode with ID [" + trackingCodeId + "] has not yet gone into effect, ignoring this trackingCodeId", module); continue; } if (trackingCode.get("thruDate") != null && nowStamp.after(trackingCode.getTimestamp("thruDate"))) { if (Debug.infoOn()) Debug.logInfo( "The TrackingCode with ID [" + trackingCodeId + "] has expired, ignoring this trackingCodeId", module); continue; } // for each trackingCodeId found in this way attach to the visit with the TKCDSRC_COOKIE // sourceEnumId GenericValue trackingCodeVisit = delegator.makeValue( "TrackingCodeVisit", UtilMisc.toMap( "trackingCodeId", trackingCodeId, "visitId", visit.get("visitId"), "fromDate", nowStamp, "sourceEnumId", "TKCDSRC_COOKIE")); try { // not doing this inside a transaction, want each one possible to go in trackingCodeVisit.create(); } catch (GenericEntityException e) { Debug.logError(e, "Error while saving TrackingCodeVisit", module); // don't return error, want to get as many as possible: return "error"; } } } } } return "success"; }
private static String processTrackingCode( GenericValue trackingCode, HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); String trackingCodeId = trackingCode.getString("trackingCodeId"); // check effective dates java.sql.Timestamp nowStamp = UtilDateTime.nowTimestamp(); if (trackingCode.get("fromDate") != null && nowStamp.before(trackingCode.getTimestamp("fromDate"))) { if (Debug.infoOn()) Debug.logInfo( "The TrackingCode with ID [" + trackingCodeId + "] has not yet gone into effect, ignoring this trackingCodeId", module); return "success"; } if (trackingCode.get("thruDate") != null && nowStamp.after(trackingCode.getTimestamp("thruDate"))) { if (Debug.infoOn()) Debug.logInfo( "The TrackingCode with ID [" + trackingCodeId + "] has expired, ignoring this trackingCodeId", module); return "success"; } // persist that info by associating with the current visit GenericValue visit = VisitHandler.getVisit(request.getSession()); if (visit == null) { Debug.logWarning( "Could not get visit, not associating trackingCode [" + trackingCodeId + "] with visit", module); } else { GenericValue trackingCodeVisit = delegator.makeValue( "TrackingCodeVisit", UtilMisc.toMap( "trackingCodeId", trackingCodeId, "visitId", visit.get("visitId"), "fromDate", UtilDateTime.nowTimestamp(), "sourceEnumId", "TKCDSRC_URL_PARAM")); try { trackingCodeVisit.create(); } catch (GenericEntityException e) { Debug.logError(e, "Error while saving TrackingCodeVisit", module); } } // write trackingCode cookies with the value set to the trackingCodeId // NOTE: just write these cookies and if others exist from other tracking codes they will be // overwritten, ie only keep the newest // load the properties from the website entity String cookieDomain = null; String webSiteId = WebSiteWorker.getWebSiteId(request); if (webSiteId != null) { try { GenericValue webSite = delegator.findByPrimaryKeyCache("WebSite", UtilMisc.toMap("webSiteId", webSiteId)); if (webSite != null) { cookieDomain = webSite.getString("cookieDomain"); } } catch (GenericEntityException e) { Debug.logWarning( e, "Problems with WebSite entity; using global default cookie domain", module); } } if (cookieDomain == null) { cookieDomain = UtilProperties.getPropertyValue("url", "cookie.domain", ""); } // if trackingCode.trackableLifetime not null and is > 0 write a trackable cookie with name in // the form: TKCDT_{trackingCode.trackingCodeTypeId} and timeout will be // trackingCode.trackableLifetime Long trackableLifetime = trackingCode.getLong("trackableLifetime"); if (trackableLifetime != null && (trackableLifetime.longValue() > 0 || trackableLifetime.longValue() == -1)) { Cookie trackableCookie = new Cookie( "TKCDT_" + trackingCode.getString("trackingCodeTypeId"), trackingCode.getString("trackingCodeId")); if (trackableLifetime.longValue() > 0) trackableCookie.setMaxAge(trackableLifetime.intValue()); trackableCookie.setPath("/"); if (cookieDomain.length() > 0) trackableCookie.setDomain(cookieDomain); response.addCookie(trackableCookie); } // if trackingCode.billableLifetime not null and is > 0 write a billable cookie with name in the // form: TKCDB_{trackingCode.trackingCodeTypeId} and timeout will be // trackingCode.billableLifetime Long billableLifetime = trackingCode.getLong("billableLifetime"); if (billableLifetime != null && (billableLifetime.longValue() > 0 || billableLifetime.longValue() == -1)) { Cookie billableCookie = new Cookie( "TKCDB_" + trackingCode.getString("trackingCodeTypeId"), trackingCode.getString("trackingCodeId")); if (billableLifetime.longValue() > 0) billableCookie.setMaxAge(billableLifetime.intValue()); billableCookie.setPath("/"); if (cookieDomain.length() > 0) billableCookie.setDomain(cookieDomain); response.addCookie(billableCookie); } // if site id exist in cookies then it is not required to create it, if exist with different // site then create it int siteIdCookieAge = (60 * 60 * 24 * 365); // should this be configurable? String siteId = request.getParameter("siteId"); if (UtilValidate.isNotEmpty(siteId)) { String visitorSiteIdCookieName = "Ofbiz.TKCD.SiteId"; String visitorSiteId = null; // first try to get the current ID from the visitor cookie javax.servlet.http.Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(visitorSiteIdCookieName)) { visitorSiteId = cookies[i].getValue(); break; } } } if (visitorSiteId == null || (visitorSiteId != null && !visitorSiteId.equals(siteId))) { // if trackingCode.siteId is not null write a trackable cookie with name in the form: // Ofbiz.TKCSiteId and timeout will be 60 * 60 * 24 * 365 Cookie siteIdCookie = new Cookie("Ofbiz.TKCD.SiteId", siteId); siteIdCookie.setMaxAge(siteIdCookieAge); siteIdCookie.setPath("/"); if (cookieDomain.length() > 0) siteIdCookie.setDomain(cookieDomain); response.addCookie(siteIdCookie); // if trackingCode.siteId is not null write a trackable cookie with name in the form: // Ofbiz.TKCSiteId and timeout will be 60 * 60 * 24 * 365 Cookie updatedTimeStampCookie = new Cookie("Ofbiz.TKCD.UpdatedTimeStamp", UtilDateTime.nowTimestamp().toString()); updatedTimeStampCookie.setMaxAge(siteIdCookieAge); updatedTimeStampCookie.setPath("/"); if (cookieDomain.length() > 0) updatedTimeStampCookie.setDomain(cookieDomain); response.addCookie(updatedTimeStampCookie); } } // if we have overridden logo, css and/or catalogId set some session attributes HttpSession session = request.getSession(); String overrideLogo = trackingCode.getString("overrideLogo"); if (overrideLogo != null) session.setAttribute("overrideLogo", overrideLogo); String overrideCss = trackingCode.getString("overrideCss"); if (overrideCss != null) session.setAttribute("overrideCss", overrideCss); String prodCatalogId = trackingCode.getString("prodCatalogId"); if (UtilValidate.isNotEmpty(prodCatalogId)) { session.setAttribute("CURRENT_CATALOG_ID", prodCatalogId); CategoryWorker.setTrail(request, FastList.<String>newInstance()); } // if forward/redirect is needed, do a response.sendRedirect and return null to tell the control // servlet to not do any other requests/views String redirectUrl = trackingCode.getString("redirectUrl"); if (UtilValidate.isNotEmpty(redirectUrl)) { try { response.sendRedirect(redirectUrl); } catch (java.io.IOException e) { Debug.logError( e, "Could not redirect as requested in the trackingCode to: " + redirectUrl, module); } return null; } return "success"; }
/** * Journal - Period. Check that selected period is in DateAcct Range or Adjusting Period Called * when C_Period_ID or DateAcct, DateDoc changed * * @param ctx context * @param WindowNo window no * @param mTab tab * @param mField field * @param value value * @return null or error message */ public String period(Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value) { String colName = mField.getColumnName(); if (value == null) return ""; int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID"); Timestamp DateAcct = null; if (colName.equals("DateAcct")) DateAcct = (Timestamp) value; else DateAcct = (Timestamp) mTab.getValue("DateAcct"); int C_Period_ID = 0; if (colName.equals("C_Period_ID")) C_Period_ID = ((Integer) value).intValue(); // When DateDoc is changed, update DateAcct if (colName.equals("DateDoc")) { mTab.setValue("DateAcct", value); } // When DateAcct is changed, set C_Period_ID else if (colName.equals("DateAcct")) { String sql = "SELECT C_Period_ID " + "FROM C_Period " + "WHERE C_Year_ID IN " + " (SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID =" + " (SELECT C_Calendar_ID FROM AD_ClientInfo WHERE AD_Client_ID=?))" + " AND ? BETWEEN StartDate AND EndDate" // globalqss - cruiz - Bug [ 1577712 ] Financial Period Bug + " AND IsActive='Y'" + " AND PeriodType='S'"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, AD_Client_ID); pstmt.setTimestamp(2, DateAcct); rs = pstmt.executeQuery(); if (rs.next()) C_Period_ID = rs.getInt(1); rs.close(); pstmt.close(); pstmt = null; } catch (SQLException e) { log.log(Level.SEVERE, sql, e); return e.getLocalizedMessage(); } finally { DB.close(rs, pstmt); } if (C_Period_ID != 0) mTab.setValue("C_Period_ID", new Integer(C_Period_ID)); } // When C_Period_ID is changed, check if in DateAcct range and set to end date if not else { String sql = "SELECT PeriodType, StartDate, EndDate " + "FROM C_Period WHERE C_Period_ID=?"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, C_Period_ID); rs = pstmt.executeQuery(); if (rs.next()) { String PeriodType = rs.getString(1); Timestamp StartDate = rs.getTimestamp(2); Timestamp EndDate = rs.getTimestamp(3); if (PeriodType.equals("S")) // Standard Periods { // out of range - set to last day if (DateAcct == null || DateAcct.before(StartDate) || DateAcct.after(EndDate)) mTab.setValue("DateAcct", EndDate); } } } catch (SQLException e) { log.log(Level.SEVERE, sql, e); return e.getLocalizedMessage(); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } } return ""; } // Journal_Period
/** Restores the specialized (auto-save) shopping list back into the shopping cart */ public static String restoreAutoSaveList( HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericValue productStore = ProductStoreWorker.getProductStore(request); if (!ProductStoreWorker.autoSaveCart(productStore)) { // if auto-save is disabled just return here return "success"; } HttpSession session = request.getSession(); ShoppingCart cart = ShoppingCartEvents.getCartObject(request); // safety check for missing required parameter. if (cart.getWebSiteId() == null) { cart.setWebSiteId(WebSiteWorker.getWebSiteId(request)); } // locate the user's identity GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); if (userLogin == null) { userLogin = (GenericValue) session.getAttribute("autoUserLogin"); } // find the list ID String autoSaveListId = cart.getAutoSaveListId(); if (autoSaveListId == null) { try { autoSaveListId = getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId()); } catch (GeneralException e) { Debug.logError(e, module); } cart.setAutoSaveListId(autoSaveListId); } else if (userLogin != null) { String existingAutoSaveListId = null; try { existingAutoSaveListId = getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId()); } catch (GeneralException e) { Debug.logError(e, module); } if (existingAutoSaveListId != null) { if (!existingAutoSaveListId.equals(autoSaveListId)) { // Replace with existing shopping list cart.setAutoSaveListId(existingAutoSaveListId); autoSaveListId = existingAutoSaveListId; cart.setLastListRestore(null); } else { // CASE: User first login and logout and then re-login again. This condition does not // require a restore at all // because at this point items in the cart and the items in the shopping list are same so // just return. return "success"; } } } // check to see if we are okay to load this list java.sql.Timestamp lastLoad = cart.getLastListRestore(); boolean okayToLoad = autoSaveListId == null ? false : (lastLoad == null ? true : false); if (!okayToLoad && lastLoad != null) { GenericValue shoppingList = null; try { shoppingList = EntityQuery.use(delegator) .from("ShoppingList") .where("shoppingListId", autoSaveListId) .queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); } if (shoppingList != null) { java.sql.Timestamp lastModified = shoppingList.getTimestamp("lastAdminModified"); if (lastModified != null) { if (lastModified.after(lastLoad)) { okayToLoad = true; } if (cart.size() == 0 && lastModified.after(cart.getCartCreatedTime())) { okayToLoad = true; } } } } // load (restore) the list of we have determined it is okay to load if (okayToLoad) { String prodCatalogId = CatalogWorker.getCurrentCatalogId(request); try { addListToCart( delegator, dispatcher, cart, prodCatalogId, autoSaveListId, false, false, userLogin != null ? true : false); cart.setLastListRestore(UtilDateTime.nowTimestamp()); } catch (IllegalArgumentException e) { Debug.logError(e, module); } } return "success"; }
/** * Before Save. Truncate Dates * * @param newRecord new * @return true */ @Override protected boolean beforeSave(boolean newRecord) { Timestamp startdate = getStartDate(); Timestamp enddate = getEndDate(); if (enddate != null && startdate.after(enddate)) { s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodInvalidDate")); return false; } // Truncate Dates startdate = TimeUtil.getDay(startdate); setStartDate(startdate); if (enddate != null) enddate = TimeUtil.getDay(enddate); else enddate = TimeUtil.getMonthLastDay(getStartDate()); // Adding the time component of 23:59:59 to the end date enddate = new Timestamp(enddate.getTime() + 86399000); setEndDate(enddate); MPeriod[] periods = getAllPeriodsInYear(getC_Year_ID(), "S", getCtx(), get_Trx()); MPeriod[] allperiods = getAllPeriodsInCalendar(getC_Calendar_ID(), "S", getCtx(), get_Trx()); // Check for non-negative period number if (getPeriodNo() < 0) { s_log.saveError("Error", Msg.getMsg(getCtx(), "CalNegPeriodNo")); return false; } // Check for standard period if (isStandardPeriod() == true) { // Check Period number is in ascending order Timestamp nextPeriodStartDate = null; Timestamp prevPeriodStartDate = null; // Get the next standard period number Start Date in this year String sql = "SELECT StartDate FROM C_Period WHERE " + "C_Period.IsActive='Y' AND PeriodType='S' " + "AND C_Period.C_Year_ID =? " + "AND C_Period.C_Period_ID <> ?" + "AND C_Period.PeriodNo " + " > ? ORDER BY C_Period.PeriodNo ASC"; Object[][] result = null; result = QueryUtil.executeQuery(get_Trx(), sql, getC_Year_ID(), getC_Period_ID(), getPeriodNo()); if (result.length != 0) nextPeriodStartDate = (Timestamp) result[0][0]; // Get the previous standard period number Start Date in this year sql = "SELECT StartDate FROM C_Period WHERE " + "C_Period.IsActive='Y' AND PeriodType='S' " + "AND C_Period.C_Year_ID =? " + "AND C_Period.C_Period_ID <> ?" + "AND C_Period.PeriodNo " + "< ? ORDER BY C_Period.PeriodNo DESC"; result = QueryUtil.executeQuery(get_Trx(), sql, getC_Year_ID(), getC_Period_ID(), getPeriodNo()); if (result.length != 0) prevPeriodStartDate = (Timestamp) result[0][0]; if ((prevPeriodStartDate != null && TimeUtil.max(prevPeriodStartDate, startdate) == prevPeriodStartDate)) { s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodAsc")); return false; } if ((nextPeriodStartDate != null && TimeUtil.max(nextPeriodStartDate, startdate) == startdate)) { s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodAsc")); return false; } // Check if the Standard Period is overlapping other periods. for (MPeriod period : allperiods) { if ((TimeUtil.isValid(period.getStartDate(), period.getEndDate(), startdate) == true || TimeUtil.isValid(period.getStartDate(), period.getEndDate(), enddate) == true) && period.getC_Period_ID() != getC_Period_ID()) { s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodOverlap")); return false; } } } // Check for adjusting period else { boolean startflag = false; boolean endflag = false; for (MPeriod period : periods) { if (TimeUtil.isValid(period.getStartDate(), period.getEndDate(), startdate) == true) startflag = true; if (TimeUtil.isValid(period.getStartDate(), period.getEndDate(), enddate) == true) endflag = true; if (startflag == true && endflag == true) break; } if (startflag == false || endflag == false) { s_log.saveError("Error", Msg.getMsg(getCtx(), "CalAdjPeriod")); return false; } } return true; } // beforeSave
/** * Is date in period * * @param date date * @return true if in period */ public boolean inPeriod(Timestamp date) { if (date == null) return false; if (date.before(m_StartDate)) return false; if (date.after(m_EndDate)) return false; return true; } // inPeriod
/** * This actual CCN loop to send/receive messages. Called by the UI class. This method blocks! If * the UI is not multi-threaded, you should start a thread to hold listen(). * * <p>When shutdown() is called, listen() will exit. * * @throws ConfigurationException * @throws IOException * @throws MalformedContentNameStringException */ public void listen() throws ConfigurationException, IOException, MalformedContentNameStringException, RuntimeException { // Also publish your keys under the chat "channel name" namespace if (_namespace.toString().startsWith("ccnx:/")) { UserConfiguration.setDefaultNamespacePrefix(_namespace.toString().substring(5)); } else { UserConfiguration.setDefaultNamespacePrefix(_namespace.toString()); } CCNHandle tempReadHandle = CCNHandle.getHandle(); // Writing must be on a different handle, to enable us to read back text // we have // written when nobody else is reading. CCNHandle tempWriteHandle = CCNHandle.open(); _readString = new CCNStringObject(_namespace, (String) null, SaveType.RAW, tempReadHandle); _readString.updateInBackground(true); String introduction = UserConfiguration.userName() + " has entered " + _namespace; _writeString = new CCNStringObject(_namespace, introduction, SaveType.RAW, tempWriteHandle); _writeString.save(); // Publish the user's friendly name as a speaker if needed // AND if this topic doesn't already have a speaker! if (this.currentUser.isSpeaker()) { if (this.userList.getSpeaker() == null || this.userList.getSpeaker().equals(this.currentUser)) { String friendlyNameNamespaceStr = _namespaceStr + TextConf.SPEAKER_COMPONENT; _spkrNamespace = KeyProfile.keyName( ContentName.fromURI(friendlyNameNamespaceStr), _writeString.getContentPublisher()); Log.info("**** Speaker Namespace is " + _spkrNamespace); // read the string here..... _readNameString = new CCNStringObject(_spkrNamespace, (String) null, SaveType.RAW, tempReadHandle); _readNameString.updateInBackground(true); String publishedNameStr = UserConfiguration.userName(); Log.info("*****I am adding my own speaker name as " + publishedNameStr); _writeNameString = new CCNStringObject(_spkrNamespace, publishedNameStr, SaveType.RAW, tempWriteHandle); _writeNameString.save(); } else { throw new RuntimeException( "The conference topic " + this.currentTopic.getTopicName() + " already has a Speaker (" + this.userList.getSpeaker().getUserName() + ")!!!"); } } else { // If the current user isn't a speaker, then they can't join a conference // that doesn't have one (i.e. they can't create a conference) if (this.userList.speaker == null) { throw new RuntimeException( "The conference topic " + this.currentTopic.getTopicName() + " doesn't have a Speaker yet so it isn't accepting non-Speakers!!!"); } } // Publish the user's friendly name under a new ContentName String friendlyNameNamespaceStr = _namespaceStr + TextConf.MEMBER_COMPONENT; _userNamespace = KeyProfile.keyName( ContentName.fromURI(friendlyNameNamespaceStr), _writeString.getContentPublisher()); Log.info("**** Friendly Namespace is " + _userNamespace); // read the string here..... _readNameString = new CCNStringObject(_userNamespace, (String) null, SaveType.RAW, tempReadHandle); _readNameString.updateInBackground(true); String publishedNameStr = UserConfiguration.userName(); Log.info("*****I am adding my own friendly name as " + publishedNameStr); _writeNameString = new CCNStringObject(_userNamespace, publishedNameStr, SaveType.RAW, tempWriteHandle); _writeNameString.save(); try { addNameToHash(_writeNameString.getContentPublisher(), _writeNameString.string()); } catch (IOException e) { System.err.println("Unable to read from " + _writeNameString + "for writing to hashMap"); e.printStackTrace(); } // Need to do synchronization for updates that come in while we're // processing last one. while (!_finished) { try { synchronized (_readString) { _readString.wait(CYCLE_TIME); } } catch (InterruptedException e) { } if (_readString.isSaved()) { Timestamp thisUpdate = _readString.getVersion(); if ((null == _lastUpdate) || thisUpdate.after(_lastUpdate)) { Log.info( "Got an update from " + _readString.getBaseName().toURIString() + ": " + _readString.getVersion() + "..." + _readString.string()); _lastUpdate = thisUpdate; // lookup friendly name to display for this user..... User userFriendlyName = getFriendlyName(_readString.getContentPublisher(), tempReadHandle, tempWriteHandle); if (!userFriendlyName.equals(this.currentUser)) { messageReceived(userFriendlyName, thisUpdate, _readString.string()); } } } } }