@AroundInvoke
 public Object checkPermissions(InvocationContext context) throws Exception {
   try {
     logger.trace(Thread.currentThread().getName());
     HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
     AccessKey key = principal.getKey();
     if (key == null) {
       return context.proceed();
     }
     if (key.getUser() == null || !key.getUser().getStatus().equals(UserStatus.ACTIVE)) {
       throw new HiveException(UNAUTHORIZED.getReasonPhrase(), UNAUTHORIZED.getStatusCode());
     }
     Timestamp expirationDate = key.getExpirationDate();
     if (expirationDate != null
         && expirationDate.before(new Timestamp(System.currentTimeMillis()))) {
       throw new HiveException(UNAUTHORIZED.getReasonPhrase(), UNAUTHORIZED.getStatusCode());
     }
     Method method = context.getMethod();
     AllowedKeyAction allowedActionAnnotation = method.getAnnotation(AllowedKeyAction.class);
     List<AllowedKeyAction.Action> actions = Arrays.asList(allowedActionAnnotation.action());
     boolean isAllowed = CheckPermissionsHelper.checkAllPermissions(key, actions);
     if (!isAllowed) {
       throw new HiveException(UNAUTHORIZED.getReasonPhrase(), UNAUTHORIZED.getStatusCode());
     }
     return context.proceed();
   } finally {
     ThreadLocalVariablesKeeper.clean();
   }
 }
Exemplo n.º 2
0
 /**
  * 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
 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;
 }
  private String getFeedByLedger(String extraURI, RSSRequest rssRequest) {
    IWContext iwc = getIWContext(rssRequest);
    //		String feedFile = "ledger_"+extraURI.substring("ledger/".length(),
    // extraURI.length()-1)+"_"+iwc.getLocale().getLanguage()+".xml";
    String uri = extraURI.substring("ledger/".length(), extraURI.length());
    String feedFile =
        "ledger_" + getName(uri) + getPeriod(uri) + "_" + iwc.getLocale().getLanguage() + ".xml";
    if (rssFileURIsCacheList.contains(feedFile)) return PATH_TO_FEED_PARENT_FOLDER + feedFile;
    String ledger = extraURI.substring("ledger/".length());
    String ledgerID = ledger.substring(0, ledger.indexOf("/"));
    String ledgerPeriod = ledger.substring(ledgerID.length() + 1, ledger.length());
    Timestamp from = null;
    Timestamp to = null;
    CalBusiness calendar = new CalBusinessBean();
    int ledgerIdInt;
    List entries = null;
    try {
      ledgerIdInt = Integer.parseInt(ledgerID);
    } catch (NumberFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return getFeed(
          INCORRECT_URI_TITLE, INCORRECT_URI_FILE, null, rssRequest, getIWContext(rssRequest));
    }

    LedgerVariationsHandler ledgerVariationsHandler = new DefaultLedgerVariationsHandler();
    String title =
        ((DefaultLedgerVariationsHandler) ledgerVariationsHandler)
            .getCalBusiness(iwc)
            .getLedger(Integer.parseInt(ledgerID))
            .getName();

    if (ledgerPeriod.length() != 0) {
      String fromStr = ledgerPeriod.substring(0, DATE_LENGTH);
      String toStr = ledgerPeriod.substring(DATE_LENGTH + 1, ledgerPeriod.length() - 1);
      from = getTimeStampFromString(fromStr);
      to = getTimeStampFromString(toStr);
      if (to.before(from))
        return getFeed(INCORRECT_PERIOD_TITLE, INCORRECT_PERIOD_FILE, null, rssRequest, iwc);
      title = title + " " + fromStr + "-" + toStr;
      Collection coll = calendar.getEntriesBetweenTimestamps(from, to);
      entries = new ArrayList();
      for (Iterator iter = coll.iterator(); iter.hasNext(); ) {
        CalendarEntry element = (CalendarEntry) iter.next();
        if (element.getLedgerID() == ledgerIdInt) {
          entries.add(element);
        }
      }
    } else entries = new ArrayList(calendar.getEntriesByLedgerID(ledgerIdInt));
    if (entries.isEmpty())
      return getFeed(NO_ENTRIES_FOUND_TITLE, NO_ENTRIES_FOUND_FILE, null, rssRequest, iwc);
    else {

      return getFeed(title, feedFile, entries, rssRequest, iwc);
    }
  }
  /**
   * 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;
  }
 protected boolean validateActiveDate(
     String errorPath, Timestamp activeFromDate, Timestamp activeToDate) {
   // TODO : do not have detail bus rule yet, so just check this for now.
   boolean valid = true;
   if (activeFromDate != null && activeToDate != null && activeToDate.before(activeFromDate)) {
     MessageMap errorMap = GlobalVariables.getMessageMap();
     errorMap.putError(errorPath, RiceKeyConstants.ERROR_ACTIVE_TO_DATE_BEFORE_FROM_DATE);
     valid = false;
   }
   return valid;
 }
  /**
   * 比較を行います.
   *
   * @param o1 比較対象1
   * @param o2 比較対象2
   * @return 比較結果
   * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
   */
  public int compare(BeanMap o1, BeanMap o2) {
    Timestamp t1 = (Timestamp) o1.get("updDatetm");
    Timestamp t2 = (Timestamp) o2.get("updDatetm");
    if (!t1.equals(t2)) {
      return t1.before(t2) ? -1 : 1;
    }

    int key1 = ((Integer) o1.get("sortKey")).intValue();
    int key2 = ((Integer) o2.get("sortKey")).intValue();

    return key1 < key2 ? -1 : 1;
  }
 /**
  * @see
  *     org.kuali.kfs.module.ar.document.service.InvoiceRecurrenceService#isValidRecurrenceBeginDate(Date)
  */
 @Override
 public boolean isValidRecurrenceBeginDate(Date beginDate) {
   boolean success = true;
   if (ObjectUtils.isNull(beginDate)) {
     return success;
   }
   Timestamp currentDate =
       new Timestamp(SpringContext.getBean(DateTimeService.class).getCurrentDate().getTime());
   Timestamp beginDateTimestamp = new Timestamp(beginDate.getTime());
   if (beginDateTimestamp.before(currentDate) || beginDateTimestamp.equals(currentDate)) {
     return false;
   }
   return success;
 }
Exemplo n.º 9
0
 public synchronized FinalResultEntryPerDef getLatestQueryResultFile() {
   //
   FinalResultEntryPerDef entryToReturn = null;
   Timestamp latestTime = null;
   for (int i = 0; i < this.getFilesVec().size(); i++) {
     if (i == 0
         || (latestTime != null
             && latestTime.before(this.getFilesVec().elementAt(i).getCreationDate()))) {
       latestTime = this.getFilesVec().elementAt(i).getCreationDate();
       entryToReturn = this.getFilesVec().elementAt(i);
     }
   }
   return entryToReturn;
 }
Exemplo n.º 10
0
  /**
   * saveMessage
   *
   * @param message
   * @param type
   * @param path
   * @param tstamp
   * @param sourcesinkid
   * @param filepath
   * @throws SQLException
   * @throws UnsupportedOperationException
   */
  public void saveMessage(
      String message,
      String type,
      String path,
      Timestamp tstamp,
      long sourcesinkid,
      String filepath)
      throws UnsupportedOperationException, SQLException {
    getMessageContainer().removeAllContainerFilters();
    Object _newItemId = getMessageContainer().addItem();
    getMessageContainer()
        .getContainerProperty(_newItemId, "message")
        .setValue(message); // nothing, since file is stored
    getMessageContainer().getContainerProperty(_newItemId, "type").setValue(type);
    getMessageContainer().getContainerProperty(_newItemId, "path").setValue(path);
    getMessageContainer().getContainerProperty(_newItemId, "tstamp").setValue(tstamp);
    getMessageContainer().getContainerProperty(_newItemId, "sourcesink_id").setValue(sourcesinkid);
    getMessageContainer().getContainerProperty(_newItemId, "filepath").setValue(filepath);

    Object _connectionRowId =
        VaadinHelper.findRowWithValue(getSourceSinkContainer(), "id", sourcesinkid);
    boolean _needToUpdateLatestTimeStamp = false;
    if (_connectionRowId != null) {
      // what to do if this one is null?assume its not null
      if (getSourceSinkContainer().getContainerProperty(_connectionRowId, "lastmessagestamp")
              != null
          && getSourceSinkContainer()
                  .getContainerProperty(_connectionRowId, "lastmessagestamp")
                  .getValue()
              != null) {

        Timestamp _lastTimeStampRecorded =
            (Timestamp)
                getSourceSinkContainer()
                    .getContainerProperty(_connectionRowId, "lastmessagestamp")
                    .getValue();
        if (_lastTimeStampRecorded.before(tstamp)) {
          _needToUpdateLatestTimeStamp = true;
        }
      } else _needToUpdateLatestTimeStamp = true;

      if (_needToUpdateLatestTimeStamp == true)
        getSourceSinkContainer()
            .getContainerProperty(_connectionRowId, "lastmessagestamp")
            .setValue(tstamp);
    }
    getMessageContainer().commit();
    if (_needToUpdateLatestTimeStamp) getSourceSinkContainer().commit();
  }
 /**
  * @see
  *     org.kuali.kfs.module.ar.document.service.InvoiceRecurrenceService#isValidRecurrenceEndDate(Date)
  */
 @Override
 public boolean isValidRecurrenceEndDate(Date beginDate, Date endDate) {
   boolean success = true;
   if (ObjectUtils.isNull(beginDate) || ObjectUtils.isNull(endDate)) {
     return success;
   }
   Timestamp beginDateTimestamp = new Timestamp(beginDate.getTime());
   Timestamp endDateTimestamp = new Timestamp(endDate.getTime());
   if ((ObjectUtils.isNotNull(endDateTimestamp))
       && (endDateTimestamp.before(beginDateTimestamp)
           || endDateTimestamp.equals(beginDateTimestamp))) {
     return false;
   }
   return success;
 }
Exemplo n.º 12
0
 /**
  * Find Price List Version and update context
  *
  * @param M_PriceList_ID price list
  * @return M_PriceList_Version_ID price list version
  */
 private int findPLV(int M_PriceList_ID) {
   Timestamp priceDate = null;
   //	Sales Order Date
   String dateStr = Env.getContext(Env.getCtx(), p_WindowNo, "DateOrdered");
   if (dateStr != null && dateStr.length() > 0)
     priceDate = Env.getContextAsDate(Env.getCtx(), p_WindowNo, "DateOrdered");
   else //	Invoice Date
   {
     dateStr = Env.getContext(Env.getCtx(), p_WindowNo, "DateInvoiced");
     if (dateStr != null && dateStr.length() > 0)
       priceDate = Env.getContextAsDate(Env.getCtx(), p_WindowNo, "DateInvoiced");
   }
   //	Today
   if (priceDate == null) priceDate = new Timestamp(System.currentTimeMillis());
   //
   log.config("M_PriceList_ID=" + M_PriceList_ID + " - " + priceDate);
   int retValue = 0;
   String sql =
       "SELECT plv.M_PriceList_Version_ID, plv.ValidFrom "
           + "FROM M_PriceList pl, M_PriceList_Version plv "
           + "WHERE pl.M_PriceList_ID=plv.M_PriceList_ID"
           + " AND plv.IsActive='Y'"
           + " AND pl.M_PriceList_ID=? " //	1
           + "ORDER BY plv.ValidFrom DESC";
   //	find newest one
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, null);
     pstmt.setInt(1, M_PriceList_ID);
     rs = pstmt.executeQuery();
     while (rs.next() && retValue == 0) {
       Timestamp plDate = rs.getTimestamp(2);
       if (!priceDate.before(plDate)) retValue = rs.getInt(1);
     }
   } catch (SQLException e) {
     log.log(Level.SEVERE, sql, e);
   } finally {
     DB.close(rs, pstmt);
     rs = null;
     pstmt = null;
   }
   Env.setContext(Env.getCtx(), p_WindowNo, "M_PriceList_Version_ID", retValue);
   return retValue;
 } //	findPLV
  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);
      }
    }
  }
Exemplo n.º 14
0
 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;
 }
 /**
  * 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;
   }
 }
Exemplo n.º 16
0
  /**
   * Go through all classes that have classconfig.studentEmailIntervalDays > 0 (which means this
   * class is configured so students receive a status report every N days). Check the
   * class.lastStudentReportSent date and if it's time to send a report, email the students a status
   * report about their activity.
   */
  private void reportClassStatus() throws SQLException, IOException {
    ResultSet rs = null;
    PreparedStatement stmt = null;
    try {
      String q =
          "select c.id, c.lastStudentReportSent, f.studentEmailIntervalDays, f.studentEmailPeriodDays from classconfig f, class c"
              + " where c.id=f.classId and f.studentEmailIntervalDays > 0";
      stmt = conn.prepareStatement(q);
      rs = stmt.executeQuery();
      Timestamp now = new Timestamp(System.currentTimeMillis());
      while (rs.next()) {
        int classId = rs.getInt(1);
        Timestamp lastReportTime = rs.getTimestamp(2);
        int interval = rs.getInt(3);
        int period = rs.getInt(4);
        // default time is set at 2000-01-01.   If it's that, then we want to send email
        Calendar cal = Calendar.getInstance();
        cal.set(2000, 0, 2, 0, 0, 0);
        Date d = cal.getTime();
        Timestamp sentinel = new Timestamp(d.getTime());

        if (lastReportTime.before(sentinel))
          // report on last <period> days of activity
          new StudentStatusEmail(classId, period).sendEmail(conn, mailServer, false);
        else {
          long msDiff = now.getTime() - lastReportTime.getTime();
          long dayDiff = msDiff / (24 * 60 * 60 * 1000);
          if (dayDiff > interval)
            // hardwired to report on last 7 days of activity
            new ClassStatusEmail(classId, period).sendEmail(conn, mailServer);
        }
      }
    } finally {
      if (stmt != null) stmt.close();
      if (rs != null) rs.close();
    }
  }
Exemplo n.º 17
0
 private Boolean isAccountLocked(
     Boolean accountLocked, Timestamp accountLockExpiryDttm, String username, Integer userid) {
   Timestamp currentDttm = new Timestamp(System.currentTimeMillis());
   if (accountLocked) {
     // If current date time is less than Account lock expire date time
     // then the account is locked hence return true
     if (currentDttm.before(accountLockExpiryDttm)) {
       // log user for account locked
       saveUserAccessLog(
           "139003",
           messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked"),
           username,
           userid);
       return true;
     } else {
       // call stored proc "ExpiredLockAccount"
       String url = expired_user_lock_account + "/" + username;
       LOGGER.debug(url);
       restTemplate.getForObject(url, Boolean.class);
       return false;
     }
   }
   return false;
 }
  private String getFeedByPeriod(String extraURI, RSSRequest rssRequest) {
    IWContext iwc = getIWContext(rssRequest);
    String uri = extraURI.substring("period/".length(), extraURI.length());
    String feedFile = "period_" + getName(uri) + iwc.getLocale().getLanguage() + ".xml";

    if (rssFileURIsCacheList.contains(feedFile)) return PATH_TO_FEED_PARENT_FOLDER + feedFile;

    String period = extraURI.substring("period/".length());
    String fromStr = period.substring(0, DATE_LENGTH);
    String toStr = period.substring(DATE_LENGTH + 1, period.length() - 1);
    Timestamp fromTmst = getTimeStampFromString(fromStr);
    Timestamp toTmst = getTimeStampFromString(toStr);

    if (toTmst.before(fromTmst))
      return getFeed(INCORRECT_PERIOD_TITLE, INCORRECT_PERIOD_FILE, null, rssRequest, iwc);
    CalBusiness calendar = new CalBusinessBean();

    Collection entries = calendar.getEntriesBetweenTimestamps(fromTmst, toTmst);
    if (entries.isEmpty())
      return getFeed(NO_ENTRIES_FOUND_TITLE, NO_ENTRIES_FOUND_FILE, null, rssRequest, iwc);
    String title = fromStr + "-" + toStr;

    return getFeed(title, feedFile, entries, rssRequest, iwc);
  }
Exemplo n.º 19
0
  public static SearchResponse fetchImagesBasedOnUserQuery(final SearchRequest req)
      throws SQLException, IOException, PropertyVetoException, ClassNotFoundException,
          ParseException {
    final String query = prepareFilters(req);
    final Connection conn = DataSource.getInstance().getConnection();
    final PreparedStatement stmt = conn.prepareStatement(query);
    int index = 1;

    final Timestamp startDate = DbUtil.convertStringToSql(req.getDateStart());
    final Timestamp endDate = DbUtil.convertStringToSql(req.getDateEnd());

    // Fill date filters
    stmt.setTimestamp(index++, startDate);
    stmt.setTimestamp(index++, endDate);
    // stmt.setTimestamp(index++, startDate);
    // stmt.setTimestamp(index++, endDate);

    // Fill user name filters
    if (req.getUserList() != null && req.getUserList().size() > 0) {
      for (final String user : req.getUserList()) stmt.setString(index++, user);
    }

    // Fill location filters
    if (req.getLocationList() != null && req.getLocationList().size() > 0) {
      for (final String location : req.getLocationList()) stmt.setString(index++, location);
    }

    System.out.println(stmt);
    ResultSet rs = stmt.executeQuery();
    if (!rs.next()) {
      conn.close();
      throw new SQLException("Returned empty set.");
    } else {
      final LinkedList<User> userList = new LinkedList<User>();
      List<Image> imgList = new ArrayList<Image>();
      List<ImageSet> imgSet = new ArrayList<ImageSet>();
      String lastSeenUser = null;
      Timestamp lastSeenDay = null;
      do {
        final String sessionId = rs.getString("id");
        final String userId = rs.getString("userId");
        final String location = rs.getString("location");
        final List<String> s3Imgs = S3.getImages(userId + "/" + sessionId + "/");

        for (final String s3Image : s3Imgs) {
          final String[] keys = s3Image.split("_");
          final String imageId = keys[0];
          final Timestamp snapedAt =
              DbUtil.parseTimeStamp(keys[2], keys[3], keys[4], keys[5], keys[6], keys[7]);

          if (startDate.before(snapedAt) && snapedAt.before(endDate)) {

            if (lastSeenUser == null || !userId.equals(lastSeenUser)) {
              if (lastSeenUser != null) {
                imgSet.add(
                    new ImageSet(
                        DbUtil.convertTimestampToStringWithoutTime(lastSeenDay),
                        DbUtil.cloneImage(imgList),
                        imgList.size()));
                userList.add(new User(lastSeenUser, DbUtil.cloneImageSet(imgSet), imgSet.size()));
                lastSeenDay = null;
              }
              lastSeenUser = userId;
              imgSet.clear();
            }

            if (lastSeenDay == null || DbUtil.isDifferentDay(lastSeenDay, snapedAt)) {
              if (lastSeenDay != null)
                imgSet.add(
                    new ImageSet(
                        DbUtil.convertTimestampToStringWithoutTime(lastSeenDay),
                        DbUtil.cloneImage(imgList),
                        imgList.size()));
              lastSeenDay = snapedAt;
              imgList.clear();
            }

            // Get image properties.
            final Image image = new Image();
            image.setImageId(imageId);
            image.setSnapedAt(DbUtil.convertTimestampToString(snapedAt));
            image.setLocation(location);
            image.setResourcePath(
                AppGlobals.CLOUD_FRONT_PREFIX + "/" + userId + "/" + sessionId + "/" + s3Image);
            imgList.add(image);
          }
        }
      } while (rs.next());
      imgSet.add(
          new ImageSet(
              DbUtil.convertTimestampToStringWithoutTime(lastSeenDay),
              DbUtil.cloneImage(imgList),
              imgList.size()));
      userList.add(new User(lastSeenUser, imgSet, imgSet.size()));
      conn.close();
      return new SearchResponse("200", "Successfully fetched records.", userList);
    }
  }
Exemplo n.º 20
0
  /**
   * 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
Exemplo n.º 21
0
 /**
  * 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
Exemplo n.º 22
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;
  }
Exemplo n.º 23
0
  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_:";
  }
Exemplo n.º 24
0
  /**
   * 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";
  }
Exemplo n.º 25
0
  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";
  }
Exemplo n.º 26
0
  public static void indexKeywords(GenericValue product, boolean doAll)
      throws GenericEntityException {
    if (product == null) return;
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();

    if (!doAll) {
      if ("N".equals(product.getString("autoCreateKeywords"))) {
        return;
      }
      if ("Y".equals(product.getString("isVariant"))
          && "true"
              .equals(UtilProperties.getPropertyValue("prodsearch", "index.ignore.variants"))) {
        return;
      }
      Timestamp salesDiscontinuationDate = product.getTimestamp("salesDiscontinuationDate");
      if (salesDiscontinuationDate != null
          && salesDiscontinuationDate.before(nowTimestamp)
          && "true"
              .equals(
                  UtilProperties.getPropertyValue(
                      "prodsearch", "index.ignore.discontinued.sales"))) {
        return;
      }
    }

    Delegator delegator = product.getDelegator();
    if (delegator == null) return;
    String productId = product.getString("productId");

    // get these in advance just once since they will be used many times for the multiple strings to
    // index
    String separators = KeywordSearchUtil.getSeparators();
    String stopWordBagOr = KeywordSearchUtil.getStopWordBagOr();
    String stopWordBagAnd = KeywordSearchUtil.getStopWordBagAnd();
    boolean removeStems = KeywordSearchUtil.getRemoveStems();
    Set<String> stemSet = KeywordSearchUtil.getStemSet();

    Map<String, Long> keywords = new TreeMap<String, Long>();
    List<String> strings = FastList.newInstance();

    int pidWeight = 1;
    try {
      pidWeight =
          Integer.parseInt(
              UtilProperties.getPropertyValue("prodsearch", "index.weight.Product.productId", "0"));
    } catch (Exception e) {
      Debug.logWarning("Could not parse weight number: " + e.toString(), module);
    }
    keywords.put(product.getString("productId").toLowerCase(), Long.valueOf(pidWeight));

    // Product fields - default is 0 if not found in the properties file
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.Product.productName", "0"))) {
      addWeightedKeywordSourceString(product, "productName", strings);
    }
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.Product.internalName", "0"))) {
      addWeightedKeywordSourceString(product, "internalName", strings);
    }
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue("prodsearch", "index.weight.Product.brandName", "0"))) {
      addWeightedKeywordSourceString(product, "brandName", strings);
    }
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.Product.description", "0"))) {
      addWeightedKeywordSourceString(product, "description", strings);
    }
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.Product.longDescription", "0"))) {
      addWeightedKeywordSourceString(product, "longDescription", strings);
    }

    // ProductFeatureAppl
    if (!"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductFeatureAndAppl.description", "0"))
        || !"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductFeatureAndAppl.abbrev", "0"))
        || !"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductFeatureAndAppl.idCode", "0"))) {
      // get strings from attributes and features
      List<GenericValue> productFeatureAndAppls =
          delegator.findByAnd("ProductFeatureAndAppl", UtilMisc.toMap("productId", productId));
      for (GenericValue productFeatureAndAppl : productFeatureAndAppls) {
        addWeightedKeywordSourceString(productFeatureAndAppl, "description", strings);
        addWeightedKeywordSourceString(productFeatureAndAppl, "abbrev", strings);
        addWeightedKeywordSourceString(productFeatureAndAppl, "idCode", strings);
      }
    }

    // ProductAttribute
    if (!"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductAttribute.attrName", "0"))
        || !"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductAttribute.attrValue", "0"))) {
      List<GenericValue> productAttributes =
          delegator.findByAnd("ProductAttribute", UtilMisc.toMap("productId", productId));
      for (GenericValue productAttribute : productAttributes) {
        addWeightedKeywordSourceString(productAttribute, "attrName", strings);
        addWeightedKeywordSourceString(productAttribute, "attrValue", strings);
      }
    }

    // GoodIdentification
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.GoodIdentification.idValue", "0"))) {
      List<GenericValue> goodIdentifications =
          delegator.findByAnd("GoodIdentification", UtilMisc.toMap("productId", productId));
      for (GenericValue goodIdentification : goodIdentifications) {
        addWeightedKeywordSourceString(goodIdentification, "idValue", strings);
      }
    }

    // Variant Product IDs
    if ("Y".equals(product.getString("isVirtual"))) {
      if (!"0"
          .equals(
              UtilProperties.getPropertyValue(
                  "prodsearch", "index.weight.Variant.Product.productId", "0"))) {
        List<GenericValue> variantProductAssocs =
            delegator.findByAnd(
                "ProductAssoc",
                UtilMisc.toMap("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT"));
        variantProductAssocs = EntityUtil.filterByDate(variantProductAssocs);
        for (GenericValue variantProductAssoc : variantProductAssocs) {
          int weight = 1;
          try {
            weight =
                Integer.parseInt(
                    UtilProperties.getPropertyValue(
                        "prodsearch", "index.weight.Variant.Product.productId", "0"));
          } catch (Exception e) {
            Debug.logWarning("Could not parse weight number: " + e.toString(), module);
          }
          for (int i = 0; i < weight; i++) {
            strings.add(variantProductAssoc.getString("productIdTo"));
          }
        }
      }
    }

    String productContentTypes =
        UtilProperties.getPropertyValue("prodsearch", "index.include.ProductContentTypes");
    for (String productContentTypeId : productContentTypes.split(",")) {
      int weight = 1;
      try {
        // this is defaulting to a weight of 1 because you specified you wanted to index this type
        weight =
            Integer.parseInt(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductContent." + productContentTypeId, "1"));
      } catch (Exception e) {
        Debug.logWarning("Could not parse weight number: " + e.toString(), module);
      }

      List<GenericValue> productContentAndInfos =
          delegator.findByAnd(
              "ProductContentAndInfo",
              UtilMisc.toMap("productId", productId, "productContentTypeId", productContentTypeId),
              null);
      for (GenericValue productContentAndInfo : productContentAndInfos) {
        addWeightedDataResourceString(productContentAndInfo, weight, strings, delegator, product);

        List<GenericValue> alternateViews =
            productContentAndInfo.getRelated(
                "ContentAssocDataResourceViewTo",
                UtilMisc.toMap("caContentAssocTypeId", "ALTERNATE_LOCALE"),
                UtilMisc.toList("-caFromDate"));
        alternateViews =
            EntityUtil.filterByDate(
                alternateViews, UtilDateTime.nowTimestamp(), "caFromDate", "caThruDate", true);
        for (GenericValue thisView : alternateViews) {
          addWeightedDataResourceString(thisView, weight, strings, delegator, product);
        }
      }
    }
    if (UtilValidate.isNotEmpty(strings)) {
      for (String str : strings) {
        // call process keywords method here
        KeywordSearchUtil.processKeywordsForIndex(
            str, keywords, separators, stopWordBagAnd, stopWordBagOr, removeStems, stemSet);
      }
    }

    List<GenericValue> toBeStored = FastList.newInstance();
    int keywordMaxLength =
        Integer.parseInt(
            UtilProperties.getPropertyValue("prodsearch", "product.keyword.max.length"));
    for (Map.Entry<String, Long> entry : keywords.entrySet()) {
      if (entry.getKey().length() <= keywordMaxLength) {
        GenericValue productKeyword =
            delegator.makeValue(
                "ProductKeyword",
                UtilMisc.toMap(
                    "productId",
                    product.getString("productId"),
                    "keyword",
                    entry.getKey(),
                    "keywordTypeId",
                    "KWT_KEYWORD",
                    "relevancyWeight",
                    entry.getValue()));
        toBeStored.add(productKeyword);
      }
    }
    if (toBeStored.size() > 0) {
      if (Debug.verboseOn())
        Debug.logVerbose(
            "[KeywordIndex.indexKeywords] Storing "
                + toBeStored.size()
                + " keywords for productId "
                + product.getString("productId"),
            module);

      if ("true"
          .equals(
              UtilProperties.getPropertyValue("prodsearch", "index.delete.on_index", "false"))) {
        // delete all keywords if the properties file says to
        delegator.removeByAnd(
            "ProductKeyword", UtilMisc.toMap("productId", product.getString("productId")));
      }

      delegator.storeAll(toBeStored);
    }
  }
Exemplo n.º 27
0
  public static Map<String, Object> finAccountCapture(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue authTrans = (GenericValue) context.get("authTrans");
    BigDecimal amount = (BigDecimal) context.get("captureAmount");
    String currency = (String) context.get("currency");

    // get the authorization transaction
    if (authTrans == null) {
      authTrans = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
    }
    if (authTrans == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotCapture", locale));
    }

    // get the auth record
    String finAccountAuthId = authTrans.getString("referenceNum");
    GenericValue finAccountAuth;
    try {
      finAccountAuth =
          EntityQuery.use(delegator)
              .from("FinAccountAuth")
              .where("finAccountAuthId", finAccountAuthId)
              .queryOne();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    Debug.logInfo(
        "Financial account capture ["
            + finAccountAuth.get("finAccountId")
            + "] for the amount of $"
            + amount
            + " Tx #"
            + finAccountAuth.get("finAccountAuthId"),
        module);

    // get the financial account
    GenericValue finAccount;
    try {
      finAccount = finAccountAuth.getRelatedOne("FinAccount", false);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    // make sure authorization has not expired
    Timestamp authExpiration = finAccountAuth.getTimestamp("thruDate");
    if ((authExpiration != null) && (authExpiration.before(UtilDateTime.nowTimestamp()))) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountAuthorizationExpired",
              UtilMisc.toMap(
                  "paymentGatewayResponseId",
                  authTrans.getString("paymentGatewayResponseId"),
                  "authExpiration",
                  authExpiration),
              locale));
    }

    // make sure the fin account itself has not expired
    if ((finAccount.getTimestamp("thruDate") != null)
        && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountExpired",
              UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")),
              locale));
    }
    String finAccountId = finAccount.getString("finAccountId");

    // need the product store ID & party ID
    String orderId = orderPaymentPreference.getString("orderId");
    String productStoreId = null;
    String partyId = null;
    if (orderId != null) {
      OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
      productStoreId = orh.getProductStoreId();

      GenericValue billToParty = orh.getBillToParty();
      if (billToParty != null) {
        partyId = billToParty.getString("partyId");
      }
    }

    // BIG NOTE: make sure the expireFinAccountAuth and finAccountWithdraw services are done in the
    // SAME TRANSACTION
    // (i.e. no require-new-transaction in either of them AND no running async)

    // cancel the authorization before doing the withdraw to avoid problems with way negative
    // available amount on account; should happen in same transaction to avoid conflict problems
    Map<String, Object> releaseResult;
    try {
      releaseResult =
          dispatcher.runSync(
              "expireFinAccountAuth",
              UtilMisc.<String, Object>toMap(
                  "userLogin", userLogin, "finAccountAuthId", finAccountAuthId));
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(releaseResult)) {
      return releaseResult;
    }

    // build the withdraw context
    Map<String, Object> withdrawCtx = new HashMap<String, Object>();
    withdrawCtx.put("finAccountId", finAccountId);
    withdrawCtx.put("productStoreId", productStoreId);
    withdrawCtx.put("currency", currency);
    withdrawCtx.put("partyId", partyId);
    withdrawCtx.put("orderId", orderId);
    withdrawCtx.put("amount", amount);
    withdrawCtx.put("reasonEnumId", "FATR_PURCHASE");
    withdrawCtx.put("requireBalance", Boolean.FALSE); // for captures; if auth passed, allow
    withdrawCtx.put("userLogin", userLogin);

    // call the withdraw service
    Map<String, Object> withdrawResp;
    try {
      withdrawResp = dispatcher.runSync("finAccountWithdraw", withdrawCtx);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(withdrawResp)) {
      return withdrawResp;
    }

    // create the capture response
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Boolean processResult = (Boolean) withdrawResp.get("processResult");
    BigDecimal withdrawAmount = (BigDecimal) withdrawResp.get("amount");
    String referenceNum = (String) withdrawResp.get("referenceNum");
    result.put("captureResult", processResult);
    result.put("captureRefNum", referenceNum);
    result.put("captureCode", "C");
    result.put("captureFlag", "1");
    result.put("captureAmount", withdrawAmount);

    return result;
  }
Exemplo n.º 28
0
 protected void my_order_query(
     HttpServletRequest paramHttpServletRequest,
     HttpServletResponse paramHttpServletResponse,
     String paramString1,
     ResponseResult paramResponseResult,
     String paramString2) {
   if (this.log.isDebugEnabled()) {
     this.log.debug("Entering 'my_order_query' method ");
   }
   int i = 0;
   String str1 = "";
   String str2 = "";
   long l1 = 0L;
   try {
     String str3 = getLogonType(paramString2);
     str2 = getValueByTagName(paramString1, "USER_ID");
     if ("".equals(str2)) {
       str2 = getValueByTagName(paramString1, "TRADER_ID");
     }
     international((String) lanaguages.get(str2));
     String str4 = getValueByTagName(paramString1, "BUY_SELL");
     Short localShort = (str4.equals("")) || (str4.equals("0")) ? null : new Short(str4);
     String str5 = getValueByTagName(paramString1, "ORDER_NO");
     Long localLong = (str5.equals("")) || (str5.equals("0")) ? null : new Long(str5);
     String str6 = getValueByTagName(paramString1, "COMMODITY_ID");
     String str7 = getValueByTagName(paramString1, "STARTNUM");
     String str8 = getValueByTagName(paramString1, "RECCNT");
     String str9 = getValueByTagName(paramString1, "SORTFLD");
     String str10 = getValueByTagName(paramString1, "ISDESC") == "" ? "0" : "1";
     String str11 = getValueByTagName(paramString1, "UT");
     int j = (str11 == null) || ("0".equals(str11)) || ("".equals(str11.trim())) ? 1 : 0;
     String str12 = j != 0 ? "queryAll" : str11;
     SortCondition localSortCondition = new SortCondition();
     localSortCondition.setStartNu(str7);
     localSortCondition.setIsdesc(Integer.parseInt(str10));
     localSortCondition.setReccnt(str8);
     localSortCondition.setSortfLD((String) this.orderKeyMap.get(str9));
     long l2 = parseLong(getValueByTagName(paramString1, "SESSION_ID"));
     if (!isLogon(paramHttpServletRequest, str2, l2, str3)) {
       i = -201;
       str1 = this.properties.getProperty("-205");
     } else {
       OrdersManager localOrdersManager = (OrdersManager) getBean("ordersManager");
       Orders localOrders = new Orders();
       Privilege localPrivilege = getSessionBean(paramHttpServletRequest);
       if (PrivilegeController.checkSuperTrader(localPrivilege)) {
         localOrders.setSuperTrader("A");
       }
       localOrders.setBS_Flag(localShort);
       localOrders.setA_OrderNo(localLong);
       localOrders.setTraderID(str2);
       localOrders.setUpdateTime(str12);
       localOrders.setCommodityID(str6);
       List localList =
           localOrdersManager.my_order_query(localOrders, localPrivilege, localSortCondition);
       Timestamp localObject = null;
       for (int k = 0; k < localList.size(); k++) {
         Timestamp localTimestamp = null;
         Map localMap = (Map) localList.get(k);
         if (localMap.containsKey("UPDATETIME")) {
           localTimestamp = (Timestamp) localMap.get("UPDATETIME");
         }
         if (localObject == null) {
           localObject = localTimestamp;
         } else if (localObject.before(localTimestamp)) {
           localObject = localTimestamp;
         }
       }
       l1 =
           localObject == null ? parseLong("".equals(str11) ? "0" : str11) : localObject.getTime();
       if (localList == null) {
         i = -202;
         str1 = this.properties.getProperty("-208");
       } else if (localList.size() == 0) {
         i = 0;
         str1 = this.properties.getProperty("-200");
       } else {
         paramResponseResult.setResultList(localList);
       }
     }
   } catch (ConnectException localConnectException) {
     this.log.error("my_order_query rmi conection exception" + localConnectException);
     i = -202;
     str1 = this.properties.getProperty("-202");
     initRMI();
   } catch (RemoteException localRemoteException) {
     this.log.error("my_order_query remoteerror:" + localRemoteException);
     errorException(localRemoteException);
     i = -204;
     str1 = this.properties.getProperty("-204");
   } catch (Exception localException) {
     this.log.error("my_order_query error:" + localException);
     errorException(localException);
     i = -203;
     str1 = this.properties.getProperty("-203");
   }
   paramResponseResult.setRetCode(i);
   paramResponseResult.setMessage(str1);
   paramResponseResult.setUserID(str2);
   if ("mobile".equals(paramString2)) {
     this.mobileServlet.renderXML(
         paramHttpServletResponse, ResponseXml.my_order_query(paramResponseResult, l1));
   } else {
     renderXML(paramHttpServletResponse, ResponseXml.my_order_query(paramResponseResult, l1));
   }
 }