/**
   * Deletes a meeting from the database
   *
   * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for the
   * HTTP GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void deletemeetingAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    if (req.getMethod() == HttpMethod.Get) {

      // Get the meeting
      int meetingId = Integer.parseInt(req.getParameter("meetingId"));
      MeetingManager meetingMan = new MeetingManager();
      Meeting meeting = meetingMan.get(meetingId);
      meetingMan.deleteMeeting(meetingId);

      // Update the User Session to remove meeting
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      List<Meeting> adminMeetings = userSession.getUser().getMeetings();

      for (int i = 0; i < adminMeetings.size(); i++) {
        Meeting m = adminMeetings.get(i);
        if (m.getId() == meeting.getId()) {
          adminMeetings.remove(i);
          break;
        }
      }

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } else if (req.getMethod() == HttpMethod.Post) {
      httpNotFound(req, res);
    }
  }
  public void test(List<Datum> testData) {
    File file = new File("../baseline.out");

    // if file doesnt exists, then create it
    try {
      if (!file.exists()) {
        file.createNewFile();
      }

      FileWriter fw = new FileWriter(file.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);

      for (int i = 0; i < testData.size(); i++) {
        String testWord = testData.get(i).word;
        String trueLabel = testData.get(i).label;
        String predictedLabel = "O";
        for (int j = 0; j < trainData.size(); j++) {
          if (testWord.equals(trainData.get(j).word)) {
            predictedLabel = trainData.get(j).label;
            break;
          }
        }
        // write result to text file
        bw.write(testWord + "\t" + trueLabel + "\t" + predictedLabel + "\n");
      }
      bw.close();
    } catch (Exception e) {
    }
  }
  private MarketSnapshot toMarketDepth(String line) throws JBookTraderException, ParseException {
    List<String> tokens = fastSplit(line);

    if (tokens.size() != COLUMNS) {
      String msg = "The line should contain exactly " + COLUMNS + " comma-separated columns.";
      throw new JBookTraderException(msg);
    }

    String dateTime = tokens.get(0) + tokens.get(1);
    String dateTimeWithoutSeconds = dateTime.substring(0, 10);

    if (dateTimeWithoutSeconds.equals(previousDateTimeWithoutSeconds)) {
      // only seconds need to be set
      int milliSeconds = 1000 * Integer.parseInt(dateTime.substring(10));
      long previousMilliSeconds = previousTime % 60000;
      time = previousTime + (milliSeconds - previousMilliSeconds);
    } else {
      time = sdf.parse(dateTime).getTime();
      previousDateTimeWithoutSeconds = dateTimeWithoutSeconds;
    }

    if (time <= previousTime) {
      String msg =
          "Timestamp of this line is before or the same as the timestamp of the previous line.";
      throw new JBookTraderException(msg);
    }

    double balance = Double.parseDouble(tokens.get(2));
    double price = Double.parseDouble(tokens.get(3));
    int volume = Integer.parseInt(tokens.get(4));
    return new MarketSnapshot(time, balance, price, volume);
  }
 public String getPackedVersionString() {
   ICFLibAnyObj scopeDef;
   ICFBamVersionObj versionLeafDef = getVersionLeaf();
   List<String> invertedNodeNames = new ArrayList<String>();
   while (versionLeafDef != null) {
     invertedNodeNames.add(getVersionStringForLeafDef(versionLeafDef));
     scopeDef = versionLeafDef.getObjScope();
     if (scopeDef == null) {
       versionLeafDef = null;
     } else if (scopeDef instanceof ICFBamMinorVersionObj) {
       versionLeafDef = (ICFBamMinorVersionObj) scopeDef;
     } else if (scopeDef instanceof ICFBamMajorVersionObj) {
       versionLeafDef = (ICFBamMajorVersionObj) scopeDef;
     } else if (scopeDef instanceof ICFBamVersionObj) {
       versionLeafDef = (ICFBamVersionObj) scopeDef;
     } else {
       versionLeafDef = null;
     }
   }
   String ret = "";
   for (int idx = invertedNodeNames.size() - 1; idx >= 0; idx--) {
     if (ret.length() == 0) {
       ret = invertedNodeNames.get(idx);
     } else {
       ret = ret + invertedNodeNames.get(idx);
     }
   }
   return (ret);
 }
Esempio n. 5
0
 /**
  * Get the total value for the index. All indexes must be numbers. The list must be a list of
  * String arrays.
  *
  * @param list List: the list to average
  * @param precision int: the result decimal precision
  * @return String[]: the averages as strings
  */
 public static String[] averageAll(List list, int precision) {
   String[] tmp = (String[]) list.get(0);
   String[] res = new String[tmp.length];
   double[] d = new double[tmp.length];
   for (int i = 0; i < d.length; i++) {
     d[i] = 0.0;
   }
   int size = list.size();
   for (int i = 0; i < size; i++) {
     String[] sa = (String[]) list.get(i);
     for (int j = 0; j < sa.length; j++) {
       if (!sa[j].equals("")) {
         d[j] += Double.parseDouble(sa[j]);
       }
     }
   }
   NumberFormat nf = NumberFormat.getInstance();
   nf.setMaximumFractionDigits(precision);
   nf.setMinimumFractionDigits(precision);
   nf.setMinimumIntegerDigits(1);
   for (int i = 0; i < d.length; i++) {
     res[i] = nf.format(d[i] / size);
   }
   return res;
 }
Esempio n. 6
0
 /**
  * Return a string that describes the statistics for the top n entries, sorted by descending
  * order of total time spent dealing with the query. This will always include the totals entry
  * in the first position.
  *
  * @param n the desired number of entries to describe
  * @return a string describing the statistics for the top n entries
  */
 public synchronized String toStringTop(int n) {
   StringBuilder out = new StringBuilder();
   List<Entry> list = entries();
   if (list.isEmpty()) return "<no queries executed>";
   Collections.sort(list, TOTAL_TIME_DESCENDING);
   int maxCountLength = COUNT_FORMAT.format(list.get(0).numQueries).length();
   double totalDuration = list.get(0).queryTime;
   for (Entry entry : list.subList(0, Math.min(n, list.size())))
     out.append(entry.toString(maxCountLength, totalDuration)).append('\n');
   return out.toString();
 }
Esempio n. 7
0
 {
     //create out of bounds exception emailList.get(-1)
     if (emailList.get(i) == emailList.get(i-1))
     {
         dupEmailCount++;
     }
     else
     {
         //insert domain email, dupEmailCount into hashtable
         domainCount.put(emailList.get(i), dupEmailCount);
         dupEmailCount = 0;
     }
 }
  private void swap(List y, List z, Random rdm) {
    int count = 0;
    for (int i = 0; i < y.size(); i++) {
      double p = rdm.nextDouble();
      if (p < 0.5) {
        Object t = y.get(i);
        y.set(i, z.get(i));
        z.set(i, t);
        count++;
      }
    } // end for i

    // logger.info("swapped " + count + " out of " + y.size());
  } // end swap
  private List copy(List in) {
    List out = new ArrayList();

    for (int i = 0; i < in.size(); i++) out.add(in.get(i));

    return out;
  } // end copy
Esempio n. 10
0
  public void removeNotLastModifications() {
    List<String> uniquePaths = getUniquePaths();
    for (String path : uniquePaths) {
      int lastRevision = getLastModificationRevisionForPath(path);

      int count = logEntries.size();
      int i = 0;

      while (i < count) {
        LogEntry entry = logEntries.get(i);

        if (entry.getRevision() < lastRevision) {
          entry.removeEntriesWithPath(path);
          if (entry.isEmpty()) {
            logEntries.remove(entry);
            count--;
            i--;
          }
        }

        i++;
      }
    }

    isOrdered = false;
  }
Esempio n. 11
0
    public CharPos charat(Coord c) {
      if (c.y < -sb.val) {
        if (msgs.size() < 1) return (null);
        Message msg = msgs.get(0);
        if (!(msg.text() instanceof RichText)) return (null);
        RichText.TextPart fp = null;
        for (RichText.Part part = ((RichText) msg.text()).parts; part != null; part = part.next) {
          if (part instanceof RichText.TextPart) {
            fp = (RichText.TextPart) part;
            break;
          }
        }
        if (fp == null) return (null);
        return (new CharPos(msg, fp, TextHitInfo.leading(0)));
      }

      Coord hc = new Coord();
      Message msg = messageat(c, hc);
      if ((msg == null) || !(msg.text() instanceof RichText)) return (null);
      RichText rt = (RichText) msg.text();
      RichText.Part p = rt.partat(hc);
      if (p == null) {
        RichText.TextPart lp = null;
        for (RichText.Part part = ((RichText) msg.text()).parts; part != null; part = part.next) {
          if (part instanceof RichText.TextPart) lp = (RichText.TextPart) part;
        }
        if (lp == null) return (null);
        return (new CharPos(msg, lp, TextHitInfo.trailing(lp.end - lp.start - 1)));
      }
      if (!(p instanceof RichText.TextPart)) return (null);
      RichText.TextPart tp = (RichText.TextPart) p;
      return (new CharPos(msg, tp, tp.charat(hc)));
    }
Esempio n. 12
0
  public void removeEntriesWithPathForAuthor(String path, String author) {
    if (logEntries == null || logEntries.isEmpty()) {
      return;
    }

    int count = logEntries.size();
    int i = 0;

    while (i < count) {
      LogEntry logEntry = logEntries.get(i);
      if (!logEntry.getAuthor().equals(author)) {
        i++;
        continue;
      }

      logEntry.removeEntriesWithPath(path);
      if (logEntry.isEmpty()) {
        logEntries.remove(logEntry);
        count--;
        continue;
      }

      i++;
    }

    isOrdered = false;
  }
Esempio n. 13
0
  /**
   * Returns the index of the source contact, in the list of recent messages.
   *
   * @param messageSourceContact
   * @return
   */
  int getIndex(MessageSourceContact messageSourceContact) {
    synchronized (recentMessages) {
      for (int i = 0; i < recentMessages.size(); i++)
        if (recentMessages.get(i).equals(messageSourceContact)) return i;

      return -1;
    }
  }
Esempio n. 14
0
  public int getMaxLogEntryRevision() {
    if (isEmpty()) {
      return -1;
    }

    List<LogEntry> logEntries = getOrderedLogEntries();

    return logEntries.get(logEntries.size() - 1).getRevision();
  }
Esempio n. 15
0
  /** Prints the properties of the class for debugging purpose. */
  @Override
  public String toString() {
    String result = "";
    result += "recurFrequency: " + String.format("%#02x", this.recurFrequency) + "\n";
    result += "patternType: " + String.format("%#02x", this.patternType.getValue()) + "\n";
    result += "calendarType: " + String.format("%#02x", this.calendarType) + "\n";
    result += "endType: " + String.format("%#04x", this.endType) + "\n";

    result += "period: " + this.period + "\n";
    result += "occurenceCount: " + String.format("%#04x", this.occurenceCount) + "\n";
    result += "patternSpecific1: " + String.format("%#04x", this.patternSpecific1) + "\n";
    result += "patternSpecific2: " + String.format("%#04x", this.patternSpecific2) + "\n";
    result += "startDate hex: " + String.format("%#04x", this.startDate) + "\n";
    result += "endDate hex: " + String.format("%#04x", this.endDate) + "\n";

    result +=
        "startDate: "
            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(windowsTimeToDateObject(this.startDate))
            + "\n";
    result +=
        "endDate: "
            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(windowsTimeToDateObject(this.endDate))
            + "\n";

    for (int i = 0; i < modifiedInstanceCount; i++) {
      result +=
          "modified Instance date hex: " + String.format("%#04x", this.modifiedInstances[i]) + "\n";

      result +=
          "modified Instance date: "
              + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z")
                  .format(windowsTimeToDateObject(this.modifiedInstances[i]))
              + "\n";
    }

    for (int i = 0; i < deletedInstanceCount; i++) {
      result +=
          "deleted Instance date: "
              + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(deletedInstances.get(i))
              + "\n";
    }
    result += "patternSpecific2: " + String.format("%#04x", this.patternSpecific2) + "\n";

    result += "\n\n =====================Exeptions====================\n\n";

    for (ExceptionInfo info : exceptionInfo) {
      result += info.toString() + "\n\n";
    }
    return result;
  }
  /** Method to show the frame sequence */
  public void show() {
    if (shown != true) {
      // set it to true
      shown = true;

      // if there is a picture show the last one
      if (pictureList.size() > 0)
        pictureFrame = new PictureFrame((Picture) pictureList.get(pictureList.size() - 1));
      else
        System.out.println(
            "There are no frames to show yet.  When you add a frame it will be shown");
    }
  }
Esempio n. 17
0
 /**
  * Get the average value for the index. The list must be a list of String arrays.
  *
  * @param list List: the list to average
  * @param index int: the index to average
  * @param precision int: the result decimal precision
  * @return String: the average as a string
  */
 public static String average(List list, int index, int precision) {
   double d = 0.0;
   int size = list.size();
   for (int i = 0; i < size; i++) {
     String[] sa = (String[]) list.get(i);
     if (!sa[index].equals("")) {
       d += Double.parseDouble(sa[index]);
     }
   }
   NumberFormat nf = NumberFormat.getInstance();
   nf.setMaximumFractionDigits(precision);
   nf.setMinimumFractionDigits(precision);
   nf.setMinimumIntegerDigits(1);
   return nf.format(d / size);
 }
Esempio n. 18
0
  public StringBuilder listToCSV(List list) {
    StringBuilder csv = new StringBuilder();
    csv.append(
        "Work Product,,Name,State,Owner,Plan Estimate,Task Estimate,Task Remaining,Time Spent\n");

    for (int i = 0; i < list.size(); i++) {
      Map map = (Map) list.get(i);
      String type = (String) map.get("type");
      String formattedId = (String) map.get("formattedId");
      String name = (String) map.get("name");
      String taskStatus = (String) map.get("taskStatus");
      String owner = (String) map.get("owner");
      String planEstimate = (String) map.get("planEstimate");
      String taskEstimateTotal = (String) map.get("taskEstimateTotal");
      String taskRemainingTotal = (String) map.get("taskRemainingTotal");
      String taskTimeSpentTotal = (String) map.get("taskTimeSpentTotal");

      if ("task".equals(type)) {
        csv.append("," + formattedId + ",");
      } else if ("userstory".equals(type)) {
        csv.append(formattedId + ",,");
      } else if ("iteration".equals(type)) {
        csv.append(",,");
      }

      if (planEstimate == null) {
        planEstimate = "";
      }

      if (taskEstimateTotal == null) {
        taskEstimateTotal = "";
      }

      if (taskRemainingTotal == null) {
        taskRemainingTotal = "";
      }

      csv.append("\"" + name + "\",");
      csv.append(taskStatus + ",");
      csv.append(owner + ",");
      csv.append(planEstimate + ",");
      csv.append(taskEstimateTotal + ",");
      csv.append(taskRemainingTotal + ",");
      csv.append(taskTimeSpentTotal + "\n");
    }

    return csv;
  }
Esempio n. 19
0
 /**
  * Gets and formats the names of the peers in the call.
  *
  * @param maxLength maximum length of the filename
  * @return the name of the peer in the call formated
  */
 private String getCallPeerName(int maxLength) {
   List<CallPeer> callPeers = call.getConference().getCallPeers();
   CallPeer callPeer = null;
   String peerName = "";
   if (!callPeers.isEmpty()) {
     callPeer = callPeers.get(0);
     if (callPeer != null) {
       peerName = callPeer.getDisplayName();
       peerName = peerName.replaceAll("[^\\da-zA-Z\\_\\-@\\.]", "");
       if (peerName.length() > maxLength) {
         peerName = peerName.substring(0, maxLength);
       }
     }
   }
   return peerName;
 }
Esempio n. 20
0
  public StringBuilder listToCSVForUserView(List list) {
    StringBuilder csv = new StringBuilder();

    csv.append(
        "Project,Iteration,Work Product,Name,State,Owner,Task Estimate,Task Remaining,Time Spent\n");

    for (int i = 0; i < list.size(); i++) {
      Map map = (Map) list.get(i);
      String projectName = (String) map.get("projectName");
      String iterationName = (String) map.get("iterationName");
      String formattedId = (String) map.get("taskFormattedId");
      String taskName = (String) map.get("taskName");
      String taskState = (String) map.get("taskState");
      String owner = (String) map.get("owner");
      String taskEstimate = (String) map.get("taskEstimate");
      String taskRemaining = (String) map.get("taskRemaining");
      String taskTimeSpent = (String) map.get("hours");

      if (taskEstimate == null) {
        taskEstimate = "";
      }

      if (taskRemaining == null) {
        taskRemaining = "";
      }

      csv.append("" + projectName + ",");
      csv.append("\"" + iterationName + "\",");
      csv.append(formattedId + ",");
      csv.append(taskName + ",");
      csv.append(taskState + ",");
      csv.append(owner + ",");
      csv.append(taskEstimate + ",");
      csv.append(taskRemaining + ",");
      csv.append(taskTimeSpent + "\n");
    }

    return csv;
  }
Esempio n. 21
0
  public void removeEntriesWithPath(String path) {
    if (logEntries == null || logEntries.isEmpty()) {
      return;
    }

    int count = logEntries.size();
    int i = 0;

    while (i < count) {
      LogEntry logEntry = logEntries.get(i);
      logEntry.removeEntriesWithPath(path);

      if (logEntry.isEmpty()) {
        logEntries.remove(logEntry);
        count--;
        continue;
      }

      i++;
    }

    isOrdered = false;
  }
Esempio n. 22
0
  /**
   * A provider has been removed.
   *
   * @param provider the ProtocolProviderService that has been unregistered.
   */
  void handleProviderRemoved(ProtocolProviderService provider) {
    // lets remove the recent messages for this provider, and update
    // with recent messages for the available providers
    synchronized (recentMessages) {
      if (provider != null) {
        List<ComparableEvtObj> removedItems = new ArrayList<ComparableEvtObj>();
        for (ComparableEvtObj msc : recentMessages) {
          if (msc.getProtocolProviderService().equals(provider)) removedItems.add(msc);
        }

        recentMessages.removeAll(removedItems);
        if (!recentMessages.isEmpty())
          oldestRecentMessage = recentMessages.get(recentMessages.size() - 1).getTimestamp();
        else oldestRecentMessage = null;

        if (recentQuery != null) {
          for (ComparableEvtObj msc : removedItems) {
            recentQuery.fireContactRemoved(msc);
          }
        }
      }

      // handleProviderRemoved can be invoked due to stopped
      // history service, if this is the case we do not want to
      // update messages
      if (!this.messageHistoryService.isHistoryLoggingEnabled()) return;

      // lets do the same as we enable provider
      // for all registered providers and finally fire events
      List<ComparableEvtObj> contactsToAdd = new ArrayList<ComparableEvtObj>();
      for (ProtocolProviderService pps : messageHistoryService.getCurrentlyAvailableProviders()) {
        contactsToAdd.addAll(getCachedRecentMessages(pps, true));
      }

      addNewRecentMessages(contactsToAdd);
    }
  }
Esempio n. 23
0
  @RequestMapping(
      value = "/getCityApi",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String getCityApi(
      HttpServletRequest request,
      @RequestParam(value = "locationname") String locationname,
      ModelMap model) {

    Map<Object, Object> map = new HashMap<Object, Object>();
    JSONArray jSONArray = new JSONArray();
    try {
      String status = "active";
      List<City> cityList = cityService.getCityApi(locationname, status);
      if (cityList != null && cityList.size() > 0) {
        for (int i = 0; i < cityList.size(); i++) {
          City city = (City) cityList.get(i);
          String cityName = (String) city.getCity();
          String stateName = (String) city.getState();

          int ID = (Integer) (city.getId());
          JSONObject jSONObject = new JSONObject();

          jSONObject.put("id", ID);
          jSONObject.put("text", cityName);
          jSONArray.put(jSONObject);
        }
        utilities.setSuccessResponse(response, jSONArray.toString());
      } else {
        throw new ConstException(ConstException.ERR_CODE_NO_DATA, ConstException.ERR_MSG_NO_DATA);
      }
    } catch (Exception ex) {
      logger.error("getCity :" + ex.getMessage());
      utilities.setErrResponse(ex, response);
    }
    model.addAttribute("model", jSONArray.toString());
    return "home";
  }
Esempio n. 24
0
 public void draw(GOut g) {
   g.chcolor(64, 64, 64, 192);
   g.frect(Coord.z, sz);
   int i = s;
   int y = 0;
   synchronized (chls) {
     while (i < chls.size()) {
       DarkChannel ch = chls.get(i);
       if (ch.chan == sel) {
         g.chcolor(128, 128, 192, 255);
         g.frect(new Coord(0, y), new Coord(sz.x, 19));
       }
       g.chcolor(255, 255, 255, 255);
       if ((ch.rname == null) || !ch.rname.text.equals(ch.chan.name()))
         ch.rname = nf.render(ch.chan.name());
       g.aimage(ch.rname.tex(), new Coord(sz.x / 2, y + 10), 0.5, 0.5);
       g.line(new Coord(5, y + 19), new Coord(sz.x - 5, y + 19), 1);
       y += 20;
       if (y >= sz.y) break;
       i++;
     }
   }
   g.chcolor();
 }
Esempio n. 25
0
  /**
   * Calculates and creates the next calendar item.
   *
   * @param previousStartDate the start date of the previous occurrence.
   * @param previousEndDate the end date of the previous occurrence.
   * @return the new calendar item or null if there are no more calendar items from that recurrent
   *     series.
   */
  public CalendarItemTimerTask next(Date previousStartDate, Date previousEndDate) {
    if (dateOutOfRange(new Date())) {
      return null;
    }
    Date startDate = previousStartDate;
    Date endDate = null;
    boolean executeNow = false;
    long duration = sourceTask.getEndDate().getTime() - sourceTask.getStartDate().getTime();
    switch (patternType) {
      case Day:
        {
          startDate = new Date(startDate.getTime() + period * 60000);
          endDate = new Date(previousEndDate.getTime() + period * 60000);
          Date currentDate = new Date();
          if (endDate.before(currentDate)) {
            long offset = currentDate.getTime() - endDate.getTime();
            offset -= offset % (period * 60000);
            if (endDate.getTime() + offset < currentDate.getTime()) {
              offset += period * 60000;
            }

            startDate = new Date(startDate.getTime() + offset);
          }

          Calendar cal = Calendar.getInstance();
          cal.setTime(startDate);
          Calendar cal2 = (Calendar) cal.clone();
          cal.set(Calendar.HOUR_OF_DAY, 0);
          cal.set(Calendar.MINUTE, 0);
          cal.set(Calendar.SECOND, 0);
          cal.set(Calendar.MILLISECOND, 0);
          while (deletedInstances.contains(cal.getTime())) {
            cal.add(Calendar.MINUTE, period);
            cal2.add(Calendar.MINUTE, period);
          }

          if (dateOutOfRange(cal.getTime())) {
            return null;
          }
          startDate = cal2.getTime();
          endDate = new Date(startDate.getTime() + duration);
          if (startDate.before(currentDate)) {
            executeNow = true;
          }

          return new CalendarItemTimerTask(
              sourceTask.getStatus(), startDate, endDate, sourceTask.getId(), executeNow, this);
        }
      case Week:
        {
          Calendar cal = Calendar.getInstance();
          /** The enum for the firstDow field is the same as Calendar day of week enum + 1 day */
          cal.setFirstDayOfWeek(firstDow + 1);
          cal.setTime(startDate);
          int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
          int index = allowedDaysOfWeek.indexOf(dayOfWeek);
          if (++index < allowedDaysOfWeek.size()) {
            cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(index));
            startDate = cal.getTime();
            endDate = new Date(startDate.getTime() + duration);
          } else {
            cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(0));
            cal.add(Calendar.WEEK_OF_YEAR, period);
            startDate = cal.getTime();
            endDate = new Date(startDate.getTime() + duration);
          }
          Date currentDate = new Date();
          if (endDate.before(currentDate)) {
            cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(0));
            endDate = new Date(cal.getTimeInMillis() + duration);
            long offset = (currentDate.getTime() - endDate.getTime());

            // 1 week = 604800000 is milliseconds
            offset -= offset % (period * 604800000);
            if (endDate.getTime() + offset < currentDate.getTime()) {
              cal.add(Calendar.WEEK_OF_YEAR, (int) (offset / (period * 604800000)));
              int i = 1;
              while (((cal.getTimeInMillis() + duration) < (currentDate.getTime()))) {
                if (i == allowedDaysOfWeek.size()) {
                  cal.add(Calendar.WEEK_OF_YEAR, period);
                  i = 0;
                }
                cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(i));
                i++;
              }

              startDate = cal.getTime();
            } else {
              startDate = new Date(cal.getTimeInMillis() + offset);
            }
          }

          cal.setTime(startDate);
          Calendar cal2 = (Calendar) cal.clone();
          cal.set(Calendar.HOUR_OF_DAY, 0);
          cal.set(Calendar.MINUTE, 0);
          cal.set(Calendar.SECOND, 0);
          cal.set(Calendar.MILLISECOND, 0);
          dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
          index = allowedDaysOfWeek.indexOf(dayOfWeek) + 1;
          while (deletedInstances.contains(cal.getTime())) {
            if (index >= allowedDaysOfWeek.size()) {
              index = 0;
              cal.add(Calendar.WEEK_OF_YEAR, period);
              cal2.add(Calendar.WEEK_OF_YEAR, period);
            }
            cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(index));
            cal2.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(index));
            index++;
          }
          startDate = cal2.getTime();
          endDate = new Date(startDate.getTime() + duration);
          if (dateOutOfRange(endDate)) return null;
          if (startDate.before(currentDate)) {
            executeNow = true;
          }

          return new CalendarItemTimerTask(
              sourceTask.getStatus(), startDate, endDate, sourceTask.getId(), executeNow, this);
        }
      case Month:
      case MonthEnd:
      case HjMonth:
      case HjMonthEnd:
        {
          return nextMonth(startDate, endDate, false);
        }
      case MonthNth:
      case HjMonthNth:
        {
          if (patternSpecific1 == 0x7f && patternSpecific2 == 0x05) {
            return nextMonth(startDate, endDate, true);
          }

          return nextMonthN(startDate, endDate);
        }
    }
    return null;
  }
Esempio n. 26
0
  public void printCellData(
      List<List<String>> dataHolder) { // test function to print data to standard output
    String name = null; // name of current item
    String previousName = null; // name of previous item
    String cell = null; // string to hold cell value
    int size; // number of cells in row
    int index; // index of start of white space and extra text
    String line = null; // line of output for each row
    String msrp = null; // value of msrp for row

    for (int i = 0; i < dataHolder.size(); i++) { // for each row in sheet
      List<String> row = dataHolder.get(i); // get current row
      size = row.size(); // number of cells
      line = "";
      if (size > 8) { // if row has at least 8 cells
        msrp = row.get(7); // get msrp column
        if (msrp != null
            && (AdminUtilities.isNumeric(msrp.trim())
                || msrp.trim()
                    .equals(
                        "mkt"))) { // check to see if this is a row with an item in it, otherwise
                                   // skip it
          name = row.get(0); // get name from 1st cell
          index = name.indexOf("          "); // index of extra white space and text
          if (index > -1) { // if there is extra white space and text
            name = name.substring(0, index); // strip extra white space and text from name
          } else {
            index = name.indexOf("       ("); // index of extra white space and parenthesis
            if (index > -1) { // if there is extra white space and parenthesis
              name = name.substring(0, index); // strip extra white space and parenthesis from name
            }
          }
          if (name.length()
              == 0) { // if name isn't there, this is a duplicate item of the previous row in case
                      // quantity
            name = previousName;
          }
          line = AdminUtilities.toProperCase(name) + ", ";
          for (int j = 1; j < row.size(); j++) { // for each cell in row
            cell = row.get(j);
            if (j == 4) {
              try {
                cell =
                    Integer.toString(
                        (int)
                            Double.parseDouble(
                                cell)); // if this has an extraneous .0 because of import from excel
                                        // sheet, remove
              } catch (NumberFormatException nfe) {
              }
            }
            if (cell != null
                && cell.length() > 0
                && !cell.trim().equals("^ ^")
                && !cell.trim().equals("####")) {
              line = line + cell.trim() + ", ";
            }
          }
          System.out.println(line.substring(0, line.length() - 2));
          previousName = name;
        }
      }
    }
  }
Esempio n. 27
0
  public List<UploadLog> uploadInvoice(String fileName) { // upload products to database

    String line;
    List<String> dataHolder =
        pdfExtractorUtility.extractOrder(fileName); // extract data from given fileName
    int lineNum = 1;
    List<VendorInventory> inventory = new ArrayList<VendorInventory>();
    List<VendorInventory> insertionErrors = new ArrayList<VendorInventory>();
    List<UploadLog> errorLogs = new ArrayList<UploadLog>();
    VendorOrder vendorOrder;
    Product product;
    String[] splitLine;
    String vendorId;
    int quantity;
    double weight = 0;
    double price;
    double credit = 0;
    double deliveryFee = 0;
    double totalPrice = 0;
    Date orderDate = null;
    Date deliveryDate = null;
    Date currentDate = null;
    String vendorOrderId = null;
    String weightString;
    SimpleDateFormat dateFormat;
    boolean found = false;
    boolean firstDate = true;
    for (int i = 0; i < dataHolder.size(); i++) { // for each row in sheet
      line = dataHolder.get(i).trim(); // get current row
      log.debug(line);
      splitLine = line.split("^" + lineNum + "\\s{4}");
      if (splitLine.length > 1) { // this is an item line
        lineNum++;
        if (line.contains(" 8338 ")) { // ignore line for Oma's info packet
          continue;
        }

        if (line.contains(" SRVCRG ")) { // add this charge to order charges table
          splitLine = line.split("^.+?(?=\\d+\\.\\d{2}$)");
          deliveryFee = Double.parseDouble(splitLine[1]);
          continue;
        }
        line = splitLine[1]; // set line equal to everything after line number
        splitLine = line.split("(?<=\\d{2,4}\\w{0,2})\\s+", 2);
        vendorId = splitLine[0]; // set vendor id to first piece of split
        line = splitLine[1]; // set line equal to rest of split
        splitLine = line.split("\\d+\\.\\d{2}\\s+", 2);
        line = splitLine[1]; // remove quantity ordered
        splitLine = line.split("(?<=\\d+\\.\\d{2})\\s", 2);
        quantity =
            (int) Double.parseDouble(splitLine[0]); // set quantity received to first piece of split
        line = splitLine[1]; // set line equal to rest of split
        splitLine = line.split("^.+?(?=\\d+\\.?\\d*\\s+-?\\d+\\.\\d{2})", 2);
        line = splitLine[1]; // remove bill by label and product name along with trailing spaces
        splitLine = line.split("\\s+(?=-?\\d+\\.\\d{2}\\s+-?\\d+\\.\\d{2}$)", 2);
        weightString = splitLine[0]; // number representing either quantity or exact weight
        if (weightString.contains(".")) { // this is an exact weight
          weight = Double.parseDouble(weightString);
        } else {
          weight = 0;
        }
        line = splitLine[1];
        splitLine = line.split("(?<=\\d+\\.\\d{2})\\s+", 2);
        price = Double.parseDouble(splitLine[0]); // set price each
        if (price < 0) { // this is a credit, add to credits
          if (weight != 0) {
            credit =
                credit
                    + (new BigDecimal(price * weight)
                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                        .doubleValue());
          } else {
            credit =
                credit
                    + (new BigDecimal(price * quantity)
                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                        .doubleValue());
          }
          continue;
        } else { // this is a billed item, add to total bill
          if (weight != 0) {
            totalPrice =
                totalPrice
                    + (new BigDecimal(price * weight)
                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                        .doubleValue());
            log.debug(
                "item price so far: "
                    + (new BigDecimal(price * weight).setScale(2, BigDecimal.ROUND_HALF_UP)));
          } else {
            totalPrice =
                totalPrice
                    + (new BigDecimal(price * quantity)
                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                        .doubleValue());
            log.debug(
                "item price so far: "
                    + (new BigDecimal(price * quantity).setScale(2, BigDecimal.ROUND_HALF_UP)));
          }
        }
        log.debug("total price so far: " + totalPrice);
        product = new Product();
        product.setVendorId(vendorId);
        inventory.add(new VendorInventory(product, quantity, weight, price, false));
      } else {
        if (line.contains("JPEELE")
            && !found) { // this is line than contains order and delivery dates and order id
          dateFormat = new SimpleDateFormat("M/d/yy");
          found = true;
          splitLine = line.trim().split("\\s+");
          for (String split : splitLine) {
            log.debug(split);
            if (split.contains("/")) {
              try {
                currentDate = dateFormat.parse(split);
              } catch (ParseException pe) {
                log.error("Unable to parse date", pe);
              }
              if (firstDate) {
                firstDate = false;
                orderDate = currentDate;
              } else {
                deliveryDate = currentDate;
              }
            } else if (!firstDate) { // this is order id
              vendorOrderId = split;
            }
          }
          log.debug(
              "Order Date= "
                  + orderDate
                  + "Delivery Date= "
                  + deliveryDate
                  + "Vendor Order Id= "
                  + vendorOrderId);
        }
      }
    }
    String logDescription;
    List<String> headers;
    List<List<String>> logData;
    String orderId;
    log.debug("credit: " + credit);
    log.debug("total price: " + (totalPrice + deliveryFee + credit));
    vendorOrder =
        new VendorOrder(
            credit * -1,
            deliveryFee,
            totalPrice + deliveryFee + credit,
            ProductGroup.OMAS,
            "Received",
            orderDate,
            deliveryDate,
            vendorOrderId);
    if ((vendorOrder = orderUtility.updateVendorOrder(vendorOrder)) == null) {
      logDescription = "Unable to upload vendor order information.";
      headers = Arrays.asList("Credit", "Delivery Fee", "Total Cost", "Status");
      logData = new ArrayList<List<String>>();
      logData.add(
          Arrays.asList(
              String.format("$%.2f", credit),
              String.format("$%.2f", deliveryFee),
              String.format("$%.2f", totalPrice),
              "Received"));
      errorLogs.add(new UploadLog(logDescription, headers, logData));
    } else if (vendorOrder.getId() == null) {
      logDescription = "You are attempting to upload a duplicate order.";
      headers = Arrays.asList("Vendor Order Id");
      logData = new ArrayList<List<String>>();
      logData.add(Arrays.asList(vendorOrderId));
      errorLogs.add(new UploadLog(logDescription, headers, logData));
    } else {
      orderId = vendorOrder.getId();
      for (VendorInventory vendorInventory : inventory) {
        if (productUtility.updateVendorInventoryItems(
                Arrays.asList(vendorInventory),
                Integer.parseInt(orderId),
                null,
                VendorOrder.STATUS.get("Received"))
            == null) {
          insertionErrors.add(vendorInventory);
        }
      }
      if (insertionErrors.size() > 0) {
        logDescription = "Vendor order items that were not uploaded properly.";
        headers = Arrays.asList("Vendor Id", "Quantity", "Weight", "Cost");
        logData = new ArrayList<List<String>>();
        for (VendorInventory vendorInventory : insertionErrors) {
          logData.add(
              Arrays.asList(
                  vendorInventory.getProduct().getVendorId(),
                  Double.toString(vendorInventory.getQuantity()),
                  vendorInventory.getCostFormatted()));
        }
        errorLogs.add(new UploadLog(logDescription, headers, logData));
      }
      log.debug(credit + ", " + deliveryFee);
    }
    return errorLogs; // this should be report of orphaned products/inventory
  }
Esempio n. 28
0
  /** upload product data to database from String containing file and return report */
  public List<UploadLog> uploadProducts(String fileName) { // upload products to database
    List<List<String>> dataHolder =
        excelExtractorUtility.extractProducts(fileName); // extract products
    String name = null; // name of current item
    String previousName = null; // name of previous item
    int size; // number of cells in row
    int index; // index of start of white space and extra text
    String msrp = null; // value of msrp for row	
    String id = null; // id for item
    String billBy = null; // unit to bill by
    String orderBy = null; // unit to order by
    String estimatedWeight = null; // estimated weight of item
    String[] estimatedRange = null; // holds the two numbers for estimatedWeight if it's a range
    List<Product> errorProducts = new ArrayList<Product>(); // products that didn't upload
    List<Product> products = new ArrayList<Product>(); // list of products to upload
    Product product = null;
    String defaultWeight = "0";
    String defaultCaseWeight = "0";
    String[] estimatedQuantityWeight;
    String[] nameSplit;
    String remainingName;
    String[] remainingNameSplit;
    String[] fraction;
    boolean mix = false;
    String mixString = null;
    for (int i = 0; i < dataHolder.size(); i++) { // for each row in sheet
      List<String> row = dataHolder.get(i); // get current row
      size = row.size(); // number of cells
      name = row.get(0); // get name from 1st cell
      if (name != null) {
        if (name.contains("Freeze Dried Treats")) {
          defaultWeight = ".25";
          defaultCaseWeight = "3.0";
        }
        if (name.contains("TEMPTINGS")) {
          defaultWeight = ".125";
          defaultCaseWeight = "0";
        }
        if (name.contains("Dr. Harveys Treats")) {
          defaultWeight = "0";
          defaultCaseWeight = "0";
        }
        if (name.contains("MIXES")) {
          mix = true;
        }
        if (name.contains("CHICKEN")) {
          mix = false;
        }
      }
      if (size > 10) { // if row has at least 10 cells
        msrp = row.get(7); // get msrp column
        if (msrp != null
            && (AdminUtilities.isNumeric(msrp.trim())
                || msrp.trim()
                    .contains(
                        "mkt"))) { // check to see if this is a row with an item in it, otherwise
                                   // skip it
          name =
              name.replaceAll(
                  new Character((char) 8237).toString(), ""); // remove weird special character
          name = name.replaceAll(" +", " ");
          index = name.toUpperCase().indexOf("(GREAT");
          if (index >= 0) {
            name = name.substring(0, index);
          }
          index = name.toUpperCase().indexOf("SPECIAL ORDER");
          if (index >= 0) {
            name = name.substring(0, index);
          }
          index = name.toUpperCase().indexOf("ORDER BY THE TUBE");
          if (index >= 0) {
            name = name.substring(0, index);
          }
          index = name.toUpperCase().indexOf("CALL FOR AVAILABILITY");
          if (index >= 0) {
            name = name.substring(0, index);
          }
          if (name.length()
              == 0) { // if name isn't there, this is a duplicate item of the previous row in case
                      // quantity
            name = previousName;
          }
          billBy = AdminUtilities.formatUnit(row.get(6)); // replace unit abbr if necessary
          orderBy =
              AdminUtilities.formatUnit(row.get(5)); // replace unit abbr if necessary       		
          // get estimated weight if applicable
          estimatedWeight = "0";
          if (name.toUpperCase().contains("LB")) {
            if (name.matches("(?i)^.*\\s+\\d+\\s+\\d+/\\d+\\s*lb.*$")) {
              nameSplit = name.split("(?i)\\s*lbs?\\.?"); // remove lb and any leading spaces
              // nameSplit = name.split("\\s*lb(?!.*\\d+\\s*/\\s*\\d)"); //remove lb and any leading
              // spaces
              name = nameSplit[0];
              estimatedWeight =
                  name; // temporarily set estimated weight to name, we will trim off name shortly
              name =
                  name.split("(?i)\\s+\\d+\\s+\\d+/\\d+.*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" +", " "); // remove white space from estimated weight
              estimatedWeight = estimatedWeight.trim();
              estimatedRange = estimatedWeight.split(" ");
              fraction = estimatedRange[1].split("/");
              estimatedWeight =
                  Double.toString(
                      Double.parseDouble(estimatedRange[0])
                          + Double.parseDouble(fraction[0]) / Double.parseDouble(fraction[1]));
            } else if (name.matches("(?i)^.*\\d+\\.?\\d*\\s*/\\s*\\d+\\.?\\d*\\s*lb.*$")) {
              nameSplit =
                  name.split(
                      "(?i)\\s*lbs?\\.?(?!.*\\d+\\s*/\\s*\\d\\.?\\d*)"); // remove lb and any
                                                                         // leading spaces
              // nameSplit = name.split("\\s*lb(?!.*\\d+\\s*/\\s*\\d)"); //remove lb and any leading
              // spaces
              name = nameSplit[0];
              estimatedWeight =
                  name; // temporarily set estimated weight to name, we will trim off name shortly
              name =
                  name.split("(?i)\\s+\\d+\\.?\\d*\\s*/\\s*\\d*\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              estimatedRange = estimatedWeight.split("/"); // split the two numbers into an array
              estimatedWeight =
                  Double.toString(
                      Double.parseDouble(estimatedRange[0])
                          * Double.parseDouble(
                              estimatedRange[1])); // multiply the two numbers    					
            } else {
              nameSplit = name.split("(?i)\\s*lbs?\\.?"); // remove lb and any leading spaces
              // nameSplit = name.split("\\s*lb"); //remove lb and any leading spaces
              name = nameSplit[0];
              estimatedWeight =
                  name; // temporarily set estimated weight to name, we will trim off name shortly
              name =
                  name.split("(?i)\\s+\\d+\\.?\\d*\\s*-?\\s*\\d*\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              if (estimatedWeight.contains("-")) { // this is a range, average the two numbers
                estimatedRange = estimatedWeight.split("-"); // split the two numbers into an array
                estimatedWeight =
                    Double.toString(
                        ((Double.parseDouble(estimatedRange[0])
                                + Double.parseDouble(estimatedRange[1])))
                            / 2); // average the two numbers
              }
              if (nameSplit.length > 1) {
                remainingName = nameSplit[1];
              } else {
                remainingName = "";
              }
              if (mix) {
                remainingNameSplit = remainingName.trim().split(" ");
                if (remainingNameSplit.length > 1
                    && remainingNameSplit[0].equals(remainingNameSplit[1])) { // 1lb mix, ignore
                  mixString = "";
                } else if (remainingName.contains("(")
                    && remainingName.contains("-")) { // 2lb mix with list of vegetables
                  mixString = remainingName.trim();
                  product.setProductName(
                      product.getProductName()
                          + "- "
                          + AdminUtilities.toProperCase(
                              mixString)); // set name of 1lb package appropriately
                  name =
                      name + "- "
                          + mixString; // set name of 2lb package
                } else if (remainingName.contains("BOX")) { // 10 lb box
                  name =
                      name
                          + " "
                          + remainingName
                          + " "
                          + mixString.substring(mixString.indexOf(" "));
                } else { // 5 or 10 pound mix
                  name = name + "- " + mixString;
                }
              } else {
                name = name + " " + remainingName.trim();
              }
            }
          } else if (name.contains("#")) {
            nameSplit = name.split("\\s*#"); // remove lb and any leading spaces
            // nameSplit = name.split("\\s*lb(?!.*\\d+\\s*/\\s*\\d)"); //remove lb and any leading
            // spaces
            name = nameSplit[0];
            estimatedWeight =
                name; // temporarily set estimated weight to name, we will trim off name shortly
            if (name.contains("/")) {
              name =
                  name.split("\\s+\\d+\\.?\\d*\\s*/\\s*\\d*\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              estimatedRange = estimatedWeight.split("/"); // split the two numbers into an array
              estimatedWeight =
                  Integer.toString(
                      Integer.parseInt(estimatedRange[0])
                          * Integer.parseInt(estimatedRange[1])); // multiply the two numbers
            } else {
              name =
                  name.split("\\s+\\d+\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
            }
            if (nameSplit.length > 1) {
              name = name + " " + nameSplit[1].trim();
            }
          } else if (name.toUpperCase().contains(" OZ")) {
            nameSplit = name.split("(?i)\\s*oz\\.?"); // remove lb and any leading spaces
            // nameSplit = name.split("\\s*lb(?!.*\\d+\\s*/\\s*\\d)"); //remove lb and any leading
            // spaces
            name = nameSplit[0];
            estimatedWeight =
                name; // temporarily set estimated weight to name, we will trim off name shortly
            if (name.matches("^.*\\s+\\d+\\.?\\d*\\s*-\\s*\\d*\\.?\\d*$")) {
              name =
                  name.split("\\s+\\d+\\.?\\d*\\s*-\\s*\\d*\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              estimatedRange = estimatedWeight.split("-"); // split the two numbers into an array
              estimatedWeight =
                  Double.toString(
                      ((double)
                              (Integer.parseInt(estimatedRange[0])
                                  + Integer.parseInt(estimatedRange[1])))
                          / 32); // average two numbers
            } else {
              name =
                  name.split("\\s+\\d+\\.?\\d*$")[
                      0]; // split off estimated weight or weight range from rest of name
              estimatedWeight =
                  estimatedWeight.substring(name.length()); // trim name from estimatedWeight
              estimatedWeight =
                  estimatedWeight.replaceAll(" ", ""); // remove white space from estimated weight
              estimatedWeight = Double.toString(Double.parseDouble(estimatedWeight) / 16);
            }
            if (nameSplit.length > 1) {
              name = name + " " + nameSplit[1].trim();
            }
          } else if (name.contains("mg. ")) {
            nameSplit = name.split("\\s+(?=\\d+-\\d+\\s+mg)"); // remove everything before weight
            estimatedWeight = nameSplit[1];
            name = nameSplit[0];
            estimatedWeight =
                estimatedWeight.split("\\s+mg")[0]; // remove everything after weight       				
            estimatedQuantityWeight = estimatedWeight.split("-");
            estimatedWeight =
                Double.toString(
                    ((double)
                            (Integer.parseInt(estimatedQuantityWeight[0])
                                * Integer.parseInt(estimatedQuantityWeight[1])
                                / 4480))
                        / 100);
          } else if (name.contains("gm. ")) {
            nameSplit = name.split("\\s+(?=\\d+\\s+gm)");
            estimatedWeight = nameSplit[1]; // remove everything before weight
            name = nameSplit[0];
            estimatedWeight =
                estimatedWeight.split("\\s+gm")[0]; // remove everything after weight     				
          } else if (!defaultWeight.equals("0")
              && billBy != "Case"
              && estimatedWeight.equals(
                  "0")) { // this is a set weight for items sold individually for the whole group of
                          // products
            estimatedWeight = defaultWeight;
          } else if (!defaultCaseWeight.equals("0")
              && billBy == "Case"
              && estimatedWeight.equals(
                  "0")) { // this is a set weight for items sold by the case for the whole group of
                          // products
            estimatedWeight = defaultCaseWeight;
          }
          id = row.get(4);
          try {
            id =
                Integer.toString(
                    (int)
                        Double.parseDouble(
                            id)); // if this has an extraneous .0 because of import from excel
                                  // sheet, remove
          } catch (NumberFormatException nfe) {
          }
          double msrpDouble = 0;
          if (!msrp.contains("mkt")) {
            msrpDouble = Double.parseDouble(msrp);
          }
          try {
            product =
                new Product(
                    AdminUtilities.toProperCase(name),
                    msrpDouble,
                    orderBy,
                    billBy,
                    Double.parseDouble(estimatedWeight),
                    "",
                    id);
          } catch (Exception e) {
            log.error("Unable to add product " + name, e);
          }
          products.add(product);
          previousName = name;
        }
      }
    }
    for (Product uploadProduct : products) {
      if (productUtility.updateProduct(uploadProduct) == null) { // update product in database
        errorProducts.add(uploadProduct);
      }
    }
    List<UploadLog> uploadLogs =
        productUtility
            .generateProductErrorReport(); // report of items that don't have uploaded info from
                                           // Excel file
    if (errorProducts.size() != 0) {
      String logDescription = "Products that failed in upload to Database";
      List<String> headings =
          Arrays.asList(
              "Vendor Id", "Name", "price", "Order By", "Bill By", "Estimated Weight", "Vendor");
      List<List<String>> logRows = new ArrayList<List<String>>();
      for (Product errorProduct : errorProducts) {

        logRows.add(
            Arrays.asList(
                errorProduct.getVendorId(),
                errorProduct.getProductName(),
                Double.toString(errorProduct.getPrice()),
                errorProduct.getOrderBy(),
                errorProduct.getBillBy(),
                Double.toString(errorProduct.getEstimatedWeight()),
                ProductGroup.OMAS)); // add information about each product with error to log
      }
      uploadLogs.add(new UploadLog(logDescription, headings, logRows));
    }
    return uploadLogs;
  }
 private MetaProperty getMetaProperty(int i) {
   return (MetaProperty) metaProperties.get(i);
 }
Esempio n. 30
0
  // public List getUserStoryList(String sessionId,String iterationId,ServletOutputStream out) {
  public List getUserStoryList(String sessionId, String iterationId, PrintWriter out) {

    List<Map> list = new ArrayList<Map>();

    statusMap.put(sessionId, "0");

    try {

      String apiURL =
          rallyApiHost
              + "/hierarchicalrequirement?"
              + "query=(Iteration%20=%20"
              + rallyApiHost
              + "/iteration/"
              + iterationId
              + ")&fetch=true&start=1&pagesize=100";

      log.info("getUserStoryList apiURL=" + apiURL);

      String responseXML = getRallyXML(apiURL);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      int totalSteps = xlist.size() + 1;
      int currentStep = 0;

      List taskRefLink = new ArrayList();

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {
        double totalTimeSpent = 0.0D;

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String planEstimate = item.getChildText("PlanEstimate");
        String formattedId = item.getChildText("FormattedID");

        String taskActualTotal = item.getChildText("TaskActualTotal");
        String taskEstimateTotal = item.getChildText("TaskEstimateTotal");
        String taskRemainingTotal = item.getChildText("TaskRemainingTotal");
        String scheduleState = item.getChildText("ScheduleState");

        Element ownerElement = item.getChild("Owner");

        String owner = "";
        String ownerRef = "";

        if (ownerElement != null) {
          owner = ownerElement.getAttributeValue("refObjectName");
        }

        Element taskElements = item.getChild("Tasks");
        // List taskElementList=taskElements.getContent();
        List taskElementList = taskElements.getChildren();

        List taskList = new ArrayList();

        log.info("taskElements.getChildren=" + taskElements);
        log.info("taskList=" + taskElementList);

        for (int i = 0; i < taskElementList.size(); i++) {
          Element taskElement = (Element) taskElementList.get(i);

          String taskRef = taskElement.getAttributeValue("ref");

          String[] objectIdArr = taskRef.split("/");
          String objectId = objectIdArr[objectIdArr.length - 1];

          log.info("objectId=" + objectId);

          // Map taskMap=getTaskMap(taskRef);
          Map taskMap = getTaskMapBatch(objectId);

          double taskTimeSpentTotal =
              Double.parseDouble((String) taskMap.get("taskTimeSpentTotal"));
          totalTimeSpent += taskTimeSpentTotal;
          taskList.add(taskMap);
        }

        map.put("type", "userstory");
        map.put("formattedId", formattedId);
        map.put("name", name);
        map.put("taskStatus", scheduleState);
        map.put("owner", owner);
        map.put("planEstimate", planEstimate);
        map.put("taskEstimateTotal", taskEstimateTotal);
        map.put("taskRemainingTotal", taskRemainingTotal);
        map.put("taskTimeSpentTotal", "" + totalTimeSpent);

        list.add(map);
        list.addAll(taskList);

        ++currentStep;
        double percentage = 100.0D * currentStep / totalSteps;
        String status = "" + Math.round(percentage);
        statusMap.put(sessionId, status);

        out.println("<script>parent.updateProcessStatus('" + status + "%')</script>" + status);
        out.flush();
        log.info("out.flush..." + status);

        // log.info("status="+status+" sessionId="+sessionId);
        // log.info("L1 statusMap="+statusMap+" "+statusMap.hashCode());

      }

      double planEstimate = 0.0D;
      double taskEstimateTotal = 0.0D;
      double taskRemainingTotal = 0.0D;
      double taskTimeSpentTotal = 0.0D;
      Map iterationMap = new HashMap();
      for (Map map : list) {
        String type = (String) map.get("type");

        String planEstimateStr = (String) map.get("planEstimate");

        log.info("planEstimateStr=" + planEstimateStr);

        if ("userstory".equals(type)) {

          if (planEstimateStr != null) {
            planEstimate += Double.parseDouble(planEstimateStr);
          }
          taskEstimateTotal += Double.parseDouble((String) map.get("taskEstimateTotal"));
          taskRemainingTotal += Double.parseDouble((String) map.get("taskRemainingTotal"));
          taskTimeSpentTotal += Double.parseDouble((String) map.get("taskTimeSpentTotal"));
        }
      }

      apiURL = rallyApiHost + "/iteration/" + iterationId + "?fetch=true";
      log.info("iteration apiURL=" + apiURL);
      responseXML = getRallyXML(apiURL);

      bSAX = new org.jdom.input.SAXBuilder();
      doc = bSAX.build(new StringReader(responseXML));
      root = doc.getRootElement();

      xpath = XPath.newInstance("//Iteration");
      xlist = xpath.selectNodes(root);

      String projName = "";
      String iterName = "";
      String iterState = "";

      iter = xlist.iterator();
      while (iter.hasNext()) {
        Element item = (Element) iter.next();

        iterName = item.getChildText("Name");
        iterState = item.getChildText("State");
        Element projElement = item.getChild("Project");
        projName = projElement.getAttributeValue("refObjectName");
      }

      iterationMap.put("type", "iteration");
      iterationMap.put("formattedId", "");
      iterationMap.put("name", projName + " - " + iterName);
      iterationMap.put("taskStatus", iterState);
      iterationMap.put("owner", "");

      iterationMap.put("planEstimate", "" + planEstimate);
      iterationMap.put("taskEstimateTotal", "" + taskEstimateTotal);
      iterationMap.put("taskRemainingTotal", "" + taskRemainingTotal);
      iterationMap.put("taskTimeSpentTotal", "" + taskTimeSpentTotal);

      list.add(0, iterationMap);

      statusMap.put(sessionId, "100");

      log.info("L2 statusMap=" + statusMap);

      log.info("L2 verify=" + getProcessStatus(sessionId));
      log.info("-----------");

      // String jsonData=JsonUtil.encodeObj(list);
      String jsonData = JSONValue.toJSONString(list);

      out.println("<script>parent.tableResult=" + jsonData + "</script>");
      out.println("<script>parent.showTableResult()</script>");

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }