예제 #1
0
  // createPageString -
  // Create list of pages for search results
  private String createPageString(
      int numberOfItems, int itemsPerPage, int currentPage, String baseUrl) {
    StringBuffer pageString = new StringBuffer();

    // Calculate the total number of pages
    int totalPages = 1;
    if (numberOfItems > itemsPerPage) {
      double pages = Math.ceil(numberOfItems / (double) itemsPerPage);
      totalPages = (int) Math.ceil(pages);
    }

    //
    if (totalPages > 1) {
      for (int i = 1; i <= totalPages; i++) {
        if (i == currentPage) {
          pageString.append(i);
        } else {
          pageString.append("<a href=\"" + baseUrl + i + "\" title=\"" + i + "\">" + i + "</a>");
        }

        if (i != totalPages) pageString.append(" ");
      }
    } else {
      pageString.append("1");
    }

    return pageString.toString();
  }
 private WVirtualImage.Rect neighbourhood(long x, long y, int marginX, int marginY) {
   long x1 = x - marginX;
   if (this.imageWidth_ != Infinite) {
     x1 = Math.max((long) 0, x1);
   }
   long y1 = Math.max((long) 0, y - marginY);
   long x2 = x + this.viewPortWidth_ + marginX;
   if (this.imageWidth_ != Infinite) {
     x2 = Math.min(this.imageWidth_, x2);
   }
   long y2 = Math.min(this.imageHeight_, y + this.viewPortHeight_ + marginY);
   return new WVirtualImage.Rect(x1, y1, x2, y2);
 }
 private void internalScrollTo(long newX, long newY, boolean moveViewPort) {
   if (this.imageWidth_ != Infinite) {
     newX = Math.min(this.imageWidth_ - this.viewPortWidth_, Math.max((long) 0, newX));
   }
   if (this.imageHeight_ != Infinite) {
     newY = Math.min(this.imageHeight_ - this.viewPortHeight_, Math.max((long) 0, newY));
   }
   if (moveViewPort) {
     this.contents_.setOffsets(new WLength((double) -newX), EnumSet.of(Side.Left));
     this.contents_.setOffsets(new WLength((double) -newY), EnumSet.of(Side.Top));
   }
   this.generateGridItems(newX, newY);
   this.viewPortChanged_.trigger(this.currentX_, this.currentY_);
 }
예제 #4
0
  public JSONObject filterPlacesRandomly(
      JSONObject placesJSONObject, int finalPlacesNumberPerRequest, List<String> place_ids) {
    JSONObject initialJSON = (JSONObject) placesJSONObject.clone();
    JSONObject finalJSONObject = new JSONObject();
    int numberFields = placesJSONObject.size();
    int remainingPlaces = finalPlacesNumberPerRequest;
    int keywordsProcessed = 0;

    Set<String> keywords = initialJSON.keySet();

    for (String keyword : keywords) {
      JSONArray placesForKeyword = (JSONArray) initialJSON.get(keyword);
      JSONArray finalPlacesForKeyword = new JSONArray();
      int placesForKeywordSize = placesForKeyword.size();

      int maxPlacesToKeepInFinalJSON = remainingPlaces / (numberFields - keywordsProcessed);
      int placesToKeepInFinalJSON = Math.min(maxPlacesToKeepInFinalJSON, placesForKeywordSize);
      remainingPlaces -= placesToKeepInFinalJSON;

      for (int i = 0; i < placesToKeepInFinalJSON; i++) {
        int remainingPlacesInJSONArray = placesForKeyword.size();
        int randomElementPosInArray = (new Random()).nextInt(remainingPlacesInJSONArray);
        JSONObject temp = (JSONObject) placesForKeyword.remove(randomElementPosInArray);
        place_ids.add((String) temp.get("place_id"));
        finalPlacesForKeyword.add(temp);
      }

      finalJSONObject.put(keyword, finalPlacesForKeyword);
      keywordsProcessed++;
    }

    return finalJSONObject;
  }
예제 #5
0
  /*
  	Show context number lines of string before and after target line.
  	Add HTML formatting to bold the target line.
  */
  String showScriptContextHTML(String s, int lineNo, int context) {
    StringBuffer sb = new StringBuffer();
    BufferedReader br = new BufferedReader(new StringReader(s));

    int beginLine = Math.max(1, lineNo - context);
    int endLine = lineNo + context;
    for (int i = 1; i <= lineNo + context + 1; i++) {
      if (i < beginLine) {
        try {
          br.readLine();
        } catch (IOException e) {
          throw new RuntimeException(e.toString());
        }
        continue;
      }
      if (i > endLine) break;

      String line;
      try {
        line = br.readLine();
      } catch (IOException e) {
        throw new RuntimeException(e.toString());
      }

      if (line == null) break;
      if (i == lineNo) sb.append("<font color=\"red\">" + i + ": " + line + "</font><br/>");
      else sb.append(i + ": " + line + "<br/>");
    }

    return sb.toString();
  }
예제 #6
0
  /** For debugging. */
  public static void main(String[] args) throws Exception {
    final String usage = "NutchBean query";

    if (args.length == 0) {
      System.err.println(usage);
      System.exit(-1);
    }

    final Configuration conf = NutchConfiguration.create();
    final NutchBean bean = new NutchBean(conf);
    try {
      final Query query = Query.parse(args[0], conf);
      final Hits hits = bean.search(query, 10);
      System.out.println("Total hits: " + hits.getTotal());
      final int length = (int) Math.min(hits.getTotal(), 10);
      final Hit[] show = hits.getHits(0, length);
      final HitDetails[] details = bean.getDetails(show);
      final Summary[] summaries = bean.getSummary(details, query);

      for (int i = 0; i < hits.getLength(); i++) {
        System.out.println(" " + i + " " + details[i] + "\n" + summaries[i]);
      }
    } catch (Throwable t) {
      LOG.error("Exception occured while executing search: " + t, t);
      System.exit(1);
    }
    System.exit(0);
  }
 private int getLengthOfLongestValue(Enumeration<String> names) {
   int longest = 0;
   while (names.hasMoreElements()) {
     longest = Math.max(longest, names.nextElement().length());
   }
   return longest;
 }
예제 #8
0
 void expand(int row, int column, int rowSpan, int columnSpan) {
   int newNumRows = row + rowSpan;
   int curNumColumns = this.getColumnCount();
   int newNumColumns = Math.max(curNumColumns, column + columnSpan);
   if (newNumRows > this.getRowCount() || newNumColumns > curNumColumns) {
     if (newNumColumns == curNumColumns && this.getRowCount() >= this.headerRowCount_) {
       this.rowsAdded_ += newNumRows - this.getRowCount();
     } else {
       this.flags_.set(BIT_GRID_CHANGED);
     }
     this.repaint(EnumSet.of(RepaintFlag.RepaintInnerHtml));
     for (int r = this.getRowCount(); r < newNumRows; ++r) {
       this.rows_.add(new WTableRow(this, newNumColumns));
     }
     if (newNumColumns > curNumColumns) {
       for (int r = 0; r < this.getRowCount(); ++r) {
         WTableRow tr = this.rows_.get(r);
         tr.expand(newNumColumns);
       }
       for (int c = curNumColumns; c <= column; ++c) {
         this.columns_.add(new WTableColumn(this));
       }
     }
   }
 }
예제 #9
0
파일: SombreroData.java 프로젝트: sebap/jwt
 public Object getData(final WModelIndex index, int role) {
   if (role != ItemDataRole.DisplayRole) {
     return super.getData(index, role);
   }
   double delta_y = (this.yEnd_ - this.yStart_) / (this.getColumnCount() - 2);
   if (index.getRow() == 0) {
     if (index.getColumn() == 0) {
       return 0.0;
     }
     return this.yStart_ + (index.getColumn() - 1) * delta_y;
   }
   double delta_x = (this.xEnd_ - this.xStart_) / (this.getRowCount() - 2);
   if (index.getColumn() == 0) {
     if (index.getRow() == 0) {
       return 0.0;
     }
     return this.xStart_ + (index.getRow() - 1) * delta_x;
   }
   double x;
   double y;
   y = this.yStart_ + (index.getColumn() - 1) * delta_y;
   x = this.xStart_ + (index.getRow() - 1) * delta_x;
   return 4
       * Math.sin(Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)))
       / Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
 }
예제 #10
0
 private void expand(int row, int column, int rowSpan, int columnSpan) {
   int newRowCount = Math.max(this.getRowCount(), row + rowSpan);
   int newColumnCount = Math.max(this.getColumnCount(), column + columnSpan);
   int extraRows = newRowCount - this.getRowCount();
   int extraColumns = newColumnCount - this.getColumnCount();
   if (extraColumns > 0) {
     for (int a_row = 0; a_row < this.getRowCount(); ++a_row) {
       {
         int insertPos = this.grid_.items_.get(a_row).size();
         for (int ii = 0; ii < (extraColumns); ++ii)
           this.grid_.items_.get(a_row).add(insertPos + ii, new Grid.Item());
       }
       ;
     }
     {
       int insertPos = this.grid_.columns_.size();
       for (int ii = 0; ii < (extraColumns); ++ii)
         this.grid_.columns_.add(insertPos + ii, new Grid.Section());
     }
     ;
   }
   if (extraRows > 0) {
     {
       int insertPos = this.grid_.items_.size();
       for (int ii = 0; ii < (extraRows); ++ii)
         this.grid_.items_.add(insertPos + ii, new ArrayList<Grid.Item>());
     }
     ;
     for (int i = 0; i < extraRows; ++i) {
       final List<Grid.Item> items =
           this.grid_.items_.get(this.grid_.items_.size() - extraRows + i);
       {
         int insertPos = items.size();
         for (int ii = 0; ii < (newColumnCount); ++ii) items.add(insertPos + ii, new Grid.Item());
       }
       ;
     }
     {
       int insertPos = this.grid_.rows_.size();
       for (int ii = 0; ii < (extraRows); ++ii)
         this.grid_.rows_.add(insertPos + ii, new Grid.Section());
     }
     ;
   }
 }
예제 #11
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    // Skip oauth for local connections
    if (!"127.0.0.1".equals(servletRequest.getRemoteAddr())) {
      // Read the OAuth parameters from the request
      OAuthServletRequest request = new OAuthServletRequest(httpRequest);
      OAuthParameters params = new OAuthParameters();
      params.readRequest(request);

      String consumerKey = params.getConsumerKey();

      // Set the secret(s), against which we will verify the request
      OAuthSecrets secrets = new OAuthSecrets();
      secrets.setConsumerSecret(m_tokenStore.getToken(consumerKey));

      // Check that the timestamp has not expired
      String timestampStr = params.getTimestamp();
      if (timestampStr == null) {
        logger.warn("Missing OAuth headers");
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing OAuth headers");
        return;
      }

      long msgTime = Util.parseLong(timestampStr) * 1000L; // Message time is in seconds
      long currentTime = System.currentTimeMillis();

      // if the message is older than 5 min it is no good
      if (Math.abs(msgTime - currentTime) > 300000) {
        logger.warn(
            "OAuth message time out, msg time: " + msgTime + " current time: " + currentTime);
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Message expired");
        return;
      }

      // Verify the signature
      try {
        if (!OAuthSignature.verify(request, params, secrets)) {
          logger.warn("Invalid OAuth signature");

          httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth signature");
          return;
        }
      } catch (OAuthSignatureException e) {
        logger.warn("OAuth exception", e);

        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth request");
        return;
      }
    }

    filterChain.doFilter(servletRequest, servletResponse);
  }
 private void generateGridItems(long newX, long newY) {
   WVirtualImage.Rect newNb =
       this.neighbourhood(newX, newY, this.viewPortWidth_, this.viewPortHeight_);
   long i1 = newNb.x1 / this.gridImageSize_;
   long j1 = newNb.y1 / this.gridImageSize_;
   long i2 = newNb.x2 / this.gridImageSize_ + 1;
   long j2 = newNb.y2 / this.gridImageSize_ + 1;
   for (int invisible = 0; invisible < 2; ++invisible) {
     for (long i = i1; i < i2; ++i) {
       for (long j = j1; j < j2; ++j) {
         long key = this.gridKey(i, j);
         WImage it = this.grid_.get(key);
         if (it == null) {
           boolean v = this.visible(i, j);
           if (v && !(invisible != 0) || !v && invisible != 0) {
             long brx = i * this.gridImageSize_ + this.gridImageSize_;
             long bry = j * this.gridImageSize_ + this.gridImageSize_;
             brx = Math.min(brx, this.imageWidth_);
             bry = Math.min(bry, this.imageHeight_);
             WImage img =
                 this.createImage(
                     i * this.gridImageSize_,
                     j * this.gridImageSize_,
                     (int) (brx - i * this.gridImageSize_),
                     (int) (bry - j * this.gridImageSize_));
             img.setAttributeValue("onmousedown", "return false;");
             this.contents_.addWidget(img);
             img.setPositionScheme(PositionScheme.Absolute);
             img.setOffsets(new WLength((double) i * this.gridImageSize_), EnumSet.of(Side.Left));
             img.setOffsets(new WLength((double) j * this.gridImageSize_), EnumSet.of(Side.Top));
             this.grid_.put(key, img);
           }
         }
       }
     }
   }
   this.currentX_ = newX;
   this.currentY_ = newY;
   this.cleanGrid();
 }
예제 #13
0
 /**
  * Adds a layout item to the grid.
  *
  * <p>Adds the <i>item</i> at (<i>row</i>, <code>column</code>). If an item was already added to
  * that location, it is replaced (but not deleted).
  *
  * <p>An item may span several more rows or columns, which is controlled by <i>rowSpan</i> and
  * <code>columnSpan</code>.
  *
  * <p>The <code>alignment</code> specifies the vertical and horizontal alignment of the item. The
  * default value 0 indicates that the item is stretched to fill the entire grid cell. The
  * alignment can be specified as a logical combination of a horizontal alignment ( {@link
  * AlignmentFlag#AlignLeft}, {@link AlignmentFlag#AlignCenter}, or {@link
  * AlignmentFlag#AlignRight}) and a vertical alignment ( {@link AlignmentFlag#AlignTop}, {@link
  * AlignmentFlag#AlignMiddle}, or {@link AlignmentFlag#AlignBottom}).
  *
  * <p>
  *
  * @see WGridLayout#addLayout(WLayout layout, int row, int column, EnumSet alignment)
  * @see WGridLayout#addWidget(WWidget widget, int row, int column, EnumSet alignment)
  */
 public void addItem(
     WLayoutItem item,
     int row,
     int column,
     int rowSpan,
     int columnSpan,
     EnumSet<AlignmentFlag> alignment) {
   columnSpan = Math.max(1, columnSpan);
   rowSpan = Math.max(1, rowSpan);
   this.expand(row, column, rowSpan, columnSpan);
   final Grid.Item gridItem = this.grid_.items_.get(row).get(column);
   if (gridItem.item_ != null) {
     WLayoutItem oldItem = gridItem.item_;
     gridItem.item_ = null;
     this.updateRemoveItem(oldItem);
   }
   gridItem.item_ = item;
   gridItem.rowSpan_ = rowSpan;
   gridItem.colSpan_ = columnSpan;
   gridItem.alignment_ = EnumSet.copyOf(alignment);
   this.updateAddItem(item);
 }
예제 #14
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      Connection con =
          DriverManager.getConnection(Utility.connection, Utility.username, Utility.password);

      String email = request.getParameter("email_id");

      String number = "";
      boolean exists = false;
      String user_name = "";
      int user_id = -1;
      String str1 = "SELECT USER_ID,NAME,PHONE_NUMBER FROM USERS WHERE EMAIL_ID=?";
      PreparedStatement prep1 = con.prepareStatement(str1);
      prep1.setString(1, email);
      ResultSet rs1 = prep1.executeQuery();
      if (rs1.next()) {
        exists = true;
        user_id = rs1.getInt("USER_ID");
        user_name = rs1.getString("NAME");
        number = rs1.getString("PHONE_NUMBER");
      }
      int verification = 0;
      JSONObject data = new JSONObject();
      if (exists) {
        verification = (int) (Math.random() * 9535641 % 999999);
        System.out.println("Number " + number + "\nVerification: " + verification);
        SMSProvider.sendSMS(
            number, "Your One Time Verification Code for PeopleConnect Is " + verification);
      }

      data.put("user_name", user_name);
      data.put("user_id", user_id);
      data.put("verification_code", "" + verification);
      data.put("phone_number", number);

      String toSend = data.toJSONString();
      out.print(toSend);
      System.out.println(toSend);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
    }
  }
 private int[] getWidths(TableModel tableModel) {
   int[] widths = new int[tableModel.getColumnCount()];
   for (int r = 0;
       r < Math.min(tableModel.getRowCount(), 500);
       r++) { // 500 is not for performance, but for using only a sample of data with huge table
     for (int c = 0; c < tableModel.getColumnCount(); c++) {
       Object o = tableModel.getValueAt(r, c);
       if (o instanceof String) {
         String s = ((String) o).trim();
         if (s.length() > widths[c]) widths[c] = s.length();
       }
     }
   }
   return widths;
 }
 public void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   resp.getWriter().println("<HTML><BODY>");
   resp.getWriter().println(this + ": <br>");
   for (int c = 0; c < 10; c++) {
     resp.getWriter().println("Counter = " + counter + "<BR>");
     try {
       Thread.currentThread().sleep((long) Math.random() * 1000);
       counter++;
     } catch (InterruptedException exc) {
       exc.printStackTrace();
     }
   }
   resp.getWriter().println("</BODY></HTML>");
 }
예제 #17
0
  private static int getBackupVersion(String dirName, String fileName) {
    int maxN = 0;
    File dir = new File(dirName);
    if (!dir.exists()) return -1;

    String[] files = dir.list();
    if (null == files) return -1;

    for (String name : files) {
      if (name.indexOf(fileName) < 0) continue;
      int pos = name.indexOf('~');
      if (pos < 0) continue;
      String ver = name.substring(pos + 1);
      int n = 0;
      try {
        n = Integer.parseInt(ver);
      } catch (NumberFormatException e) {
        log.error("Format Integer error on backup filename= " + ver);
      }
      maxN = Math.max(n, maxN);
    }
    return maxN + 1;
  }
예제 #18
0
 long _getScopeTime() {
   long last = 0;
   for (File f : _initFlies) if (f.exists()) last = Math.max(last, f.lastModified());
   return last;
 }
예제 #19
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;
  }
예제 #20
0
  private void dnaCommand(HttpServletRequest req, DazzleResponse resp, DazzleDataSource dds)
      throws IOException, DataSourceException, ServletException, DazzleException {

    DazzleReferenceSource drs = (DazzleReferenceSource) dds;

    List segments = DazzleTools.getSegments(dds, req, resp);
    if (segments.size() == 0) {
      throw new DazzleException(
          DASStatus.STATUS_BAD_COMMAND_ARGUMENTS, "No segments specified for dna command");
    }

    // Fetch and validate the requests.

    Map segmentResults = new HashMap();
    for (Iterator i = segments.iterator(); i.hasNext(); ) {
      Segment seg = (Segment) i.next();

      try {
        Sequence seq = drs.getSequence(seg.getReference());
        if (seq.getAlphabet() != DNATools.getDNA()) {
          throw new DazzleException(
              DASStatus.STATUS_SERVER_ERROR,
              "Sequence " + seg.toString() + " is not in the DNA alphabet");
        }
        if (seg.isBounded()) {
          if (seg.getMin() < 1 || seg.getMax() > seq.length()) {
            throw new DazzleException(
                DASStatus.STATUS_BAD_COORDS,
                "Segment " + seg.toString() + " doesn't fit sequence of length " + seq.length());
          }
        }
        segmentResults.put(seg, seq);
      } catch (NoSuchElementException ex) {
        throw new DazzleException(DASStatus.STATUS_BAD_REFERENCE, ex);
      } catch (DataSourceException ex) {
        throw new DazzleException(DASStatus.STATUS_SERVER_ERROR, ex);
      }
    }

    //
    // Looks okay -- generate the response document
    //

    XMLWriter xw = resp.startDasXML("DASDNA", "dasdna.dtd");

    try {
      xw.openTag("DASDNA");
      for (Iterator i = segmentResults.entrySet().iterator(); i.hasNext(); ) {
        Map.Entry me = (Map.Entry) i.next();
        Segment seg = (Segment) me.getKey();
        Sequence seq = (Sequence) me.getValue();

        xw.openTag("SEQUENCE");
        xw.attribute("id", seg.getReference());
        xw.attribute("version", drs.getLandmarkVersion(seg.getReference()));
        if (seg.isBounded()) {
          xw.attribute("start", "" + seg.getStart());
          xw.attribute("stop", "" + seg.getStop());
        } else {
          xw.attribute("start", "" + 1);
          xw.attribute("stop", "" + seq.length());
        }

        SymbolList syms = seq;
        if (seg.isBounded()) {
          syms = syms.subList(seg.getMin(), seg.getMax());
        }
        if (seg.isInverted()) {
          syms = DNATools.reverseComplement(syms);
        }

        xw.openTag("DNA");
        xw.attribute("length", "" + syms.length());

        for (int pos = 1; pos <= syms.length(); pos += 60) {
          int maxPos = Math.min(syms.length(), pos + 59);
          xw.println(syms.subStr(pos, maxPos));
        }

        xw.closeTag("DNA");
        xw.closeTag("SEQUENCE");
      }
      xw.closeTag("DASDNA");
      xw.close();
    } catch (Exception ex) {
      throw new DazzleException(ex, "Error writing DNA document");
    }
  }
예제 #21
0
 protected void paintEvent(WPaintDevice paintDevice) {
   if (!(this.chart_ != null) || !this.chart_.cObjCreated_) {
     return;
   }
   if (this.chart_.getSeries(this.seriesColumn_).getType() != SeriesType.LineSeries
       && this.chart_.getSeries(this.seriesColumn_).getType() != SeriesType.CurveSeries) {
     if (this.getMethod() == WPaintedWidget.Method.HtmlCanvas) {
       StringBuilder ss = new StringBuilder();
       ss.append("jQuery.removeData(").append(this.getJsRef()).append(",'sobj');");
       ss.append("\nif (")
           .append(this.getObjJsRef())
           .append(") {")
           .append(this.getObjJsRef())
           .append(".canvas.style.cursor = 'auto';")
           .append("setTimeout(")
           .append(this.getObjJsRef())
           .append(".repaint,0);}\n");
       this.doJavaScript(ss.toString());
     }
     logger.error(
         new StringWriter()
             .append("WAxisSliderWidget is not associated with a line or curve series.")
             .toString());
     return;
   }
   WPainter painter = new WPainter(paintDevice);
   boolean horizontal = this.chart_.getOrientation() == Orientation.Vertical;
   double w = horizontal ? this.getWidth().getValue() : this.getHeight().getValue();
   double h = horizontal ? this.getHeight().getValue() : this.getWidth().getValue();
   boolean autoPadding = this.autoPadding_;
   if (autoPadding
       && EnumUtils.mask(paintDevice.getFeatures(), WPaintDevice.FeatureFlag.HasFontMetrics)
           .equals(0)
       && this.labelsEnabled_) {
     logger.error(
         new StringWriter()
             .append(
                 "setAutoLayout(): device does not have font metrics (not even server-side font metrics).")
             .toString());
     autoPadding = false;
   }
   if (autoPadding) {
     if (horizontal) {
       if (this.labelsEnabled_) {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Top));
         this.setSelectionAreaPadding(
             (int)
                 (this.chart_
                         .getAxis(Axis.XAxis)
                         .calcMaxTickLabelSize(paintDevice, Orientation.Vertical)
                     + 10),
             EnumSet.of(Side.Bottom));
         this.setSelectionAreaPadding(
             (int)
                 Math.max(
                     this.chart_
                             .getAxis(Axis.XAxis)
                             .calcMaxTickLabelSize(paintDevice, Orientation.Horizontal)
                         / 2,
                     10.0),
             EnumSet.of(Side.Left, Side.Right));
       } else {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Top));
         this.setSelectionAreaPadding(5, EnumSet.of(Side.Left, Side.Right, Side.Bottom));
       }
     } else {
       if (this.labelsEnabled_) {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Right));
         this.setSelectionAreaPadding(
             (int)
                 Math.max(
                     this.chart_
                             .getAxis(Axis.XAxis)
                             .calcMaxTickLabelSize(paintDevice, Orientation.Vertical)
                         / 2,
                     10.0),
             EnumSet.of(Side.Top, Side.Bottom));
         this.setSelectionAreaPadding(
             (int)
                 (this.chart_
                         .getAxis(Axis.XAxis)
                         .calcMaxTickLabelSize(paintDevice, Orientation.Horizontal)
                     + 10),
             EnumSet.of(Side.Left));
       } else {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Right));
         this.setSelectionAreaPadding(5, EnumSet.of(Side.Top, Side.Bottom, Side.Left));
       }
     }
   }
   double left =
       horizontal
           ? this.getSelectionAreaPadding(Side.Left)
           : this.getSelectionAreaPadding(Side.Top);
   double right =
       horizontal
           ? this.getSelectionAreaPadding(Side.Right)
           : this.getSelectionAreaPadding(Side.Bottom);
   double top =
       horizontal
           ? this.getSelectionAreaPadding(Side.Top)
           : this.getSelectionAreaPadding(Side.Right);
   double bottom =
       horizontal
           ? this.getSelectionAreaPadding(Side.Bottom)
           : this.getSelectionAreaPadding(Side.Left);
   double maxW = w - left - right;
   WRectF drawArea = new WRectF(left, 0, maxW, h);
   List<WAxis.Segment> segmentsBak =
       new ArrayList<WAxis.Segment>(this.chart_.getAxis(Axis.XAxis).segments_);
   double renderIntervalBak = this.chart_.getAxis(Axis.XAxis).renderInterval_;
   this.chart_
       .getAxis(Axis.XAxis)
       .prepareRender(
           horizontal ? Orientation.Horizontal : Orientation.Vertical, drawArea.getWidth());
   final WRectF chartArea = this.chart_.chartArea_;
   WRectF selectionRect = null;
   {
     double u =
         -this.chart_.xTransformHandle_.getValue().getDx()
             / (chartArea.getWidth() * this.chart_.xTransformHandle_.getValue().getM11());
     selectionRect = new WRectF(0, top, maxW, h - (top + bottom));
     this.transform_.setValue(
         new WTransform(
             1 / this.chart_.xTransformHandle_.getValue().getM11(), 0, 0, 1, u * maxW, 0));
   }
   WRectF seriesArea = new WRectF(left, top + 5, maxW, h - (top + bottom + 5));
   WTransform selectionTransform =
       this.hv(new WTransform(1, 0, 0, 1, left, 0).multiply(this.transform_.getValue()));
   WRectF rect = selectionTransform.map(this.hv(selectionRect));
   painter.fillRect(this.hv(new WRectF(left, top, maxW, h - top - bottom)), this.background_);
   painter.fillRect(rect, this.selectedAreaBrush_);
   final double TICK_LENGTH = 5;
   final double ANGLE1 = 15;
   final double ANGLE2 = 80;
   double tickStart = 0.0;
   double tickEnd = 0.0;
   double labelPos = 0.0;
   AlignmentFlag labelHFlag = AlignmentFlag.AlignCenter;
   AlignmentFlag labelVFlag = AlignmentFlag.AlignMiddle;
   final WAxis axis = this.chart_.getAxis(Axis.XAxis);
   if (horizontal) {
     tickStart = 0;
     tickEnd = TICK_LENGTH;
     labelPos = TICK_LENGTH;
     labelVFlag = AlignmentFlag.AlignTop;
   } else {
     tickStart = -TICK_LENGTH;
     tickEnd = 0;
     labelPos = -TICK_LENGTH;
     labelHFlag = AlignmentFlag.AlignRight;
   }
   if (horizontal) {
     if (axis.getLabelAngle() > ANGLE1) {
       labelHFlag = AlignmentFlag.AlignRight;
       if (axis.getLabelAngle() > ANGLE2) {
         labelVFlag = AlignmentFlag.AlignMiddle;
       }
     } else {
       if (axis.getLabelAngle() < -ANGLE1) {
         labelHFlag = AlignmentFlag.AlignLeft;
         if (axis.getLabelAngle() < -ANGLE2) {
           labelVFlag = AlignmentFlag.AlignMiddle;
         }
       }
     }
   } else {
     if (axis.getLabelAngle() > ANGLE1) {
       labelVFlag = AlignmentFlag.AlignBottom;
       if (axis.getLabelAngle() > ANGLE2) {
         labelHFlag = AlignmentFlag.AlignCenter;
       }
     } else {
       if (axis.getLabelAngle() < -ANGLE1) {
         labelVFlag = AlignmentFlag.AlignTop;
         if (axis.getLabelAngle() < -ANGLE2) {
           labelHFlag = AlignmentFlag.AlignCenter;
         }
       }
     }
   }
   EnumSet<AxisProperty> axisProperties = EnumSet.of(AxisProperty.Line);
   if (this.labelsEnabled_) {
     axisProperties.add(AxisProperty.Labels);
   }
   if (horizontal) {
     axis.render(
         painter,
         axisProperties,
         new WPointF(drawArea.getLeft(), h - bottom),
         new WPointF(drawArea.getRight(), h - bottom),
         tickStart,
         tickEnd,
         labelPos,
         EnumSet.of(labelHFlag, labelVFlag));
     WPainterPath line = new WPainterPath();
     line.moveTo(drawArea.getLeft() + 0.5, h - (bottom - 0.5));
     line.lineTo(drawArea.getRight(), h - (bottom - 0.5));
     painter.strokePath(line, this.chart_.getAxis(Axis.XAxis).getPen());
   } else {
     axis.render(
         painter,
         axisProperties,
         new WPointF(this.getSelectionAreaPadding(Side.Left) - 1, drawArea.getLeft()),
         new WPointF(this.getSelectionAreaPadding(Side.Left) - 1, drawArea.getRight()),
         tickStart,
         tickEnd,
         labelPos,
         EnumSet.of(labelHFlag, labelVFlag));
     WPainterPath line = new WPainterPath();
     line.moveTo(this.getSelectionAreaPadding(Side.Left) - 0.5, drawArea.getLeft() + 0.5);
     line.lineTo(this.getSelectionAreaPadding(Side.Left) - 0.5, drawArea.getRight());
     painter.strokePath(line, this.chart_.getAxis(Axis.XAxis).getPen());
   }
   WPainterPath curve = new WPainterPath();
   {
     WTransform t =
         new WTransform(1, 0, 0, 1, seriesArea.getLeft(), seriesArea.getTop())
             .multiply(
                 new WTransform(
                     seriesArea.getWidth() / chartArea.getWidth(),
                     0,
                     0,
                     seriesArea.getHeight() / chartArea.getHeight(),
                     0,
                     0))
             .multiply(new WTransform(1, 0, 0, 1, -chartArea.getLeft(), -chartArea.getTop()));
     if (!horizontal) {
       t.assign(
           new WTransform(
                   0,
                   1,
                   1,
                   0,
                   this.getSelectionAreaPadding(Side.Left)
                       - this.getSelectionAreaPadding(Side.Right)
                       - 5,
                   0)
               .multiply(t)
               .multiply(new WTransform(0, 1, 1, 0, 0, 0)));
     }
     curve.assign(t.map(this.chart_.pathForSeries(this.seriesColumn_)));
   }
   {
     WRectF leftHandle = this.hv(new WRectF(-5, top, 5, h - top - bottom));
     WTransform t =
         new WTransform(1, 0, 0, 1, left, -top)
             .multiply(
                 new WTransform()
                     .translate(this.transform_.getValue().map(selectionRect.getTopLeft())));
     painter.fillRect(this.hv(t).map(leftHandle), this.handleBrush_);
   }
   {
     WRectF rightHandle = this.hv(new WRectF(0, top, 5, h - top - bottom));
     WTransform t =
         new WTransform(1, 0, 0, 1, left, -top)
             .multiply(
                 new WTransform()
                     .translate(this.transform_.getValue().map(selectionRect.getTopRight())));
     painter.fillRect(this.hv(t).map(rightHandle), this.handleBrush_);
   }
   if (this.selectedSeriesPen_ != this.seriesPen_
       && !this.selectedSeriesPen_.equals(this.seriesPen_)) {
     WPainterPath clipPath = new WPainterPath();
     clipPath.addRect(this.hv(selectionRect));
     painter.setClipPath(selectionTransform.map(clipPath));
     painter.setClipping(true);
     painter.setPen(this.getSelectedSeriesPen());
     painter.drawPath(curve);
     WPainterPath leftClipPath = new WPainterPath();
     leftClipPath.addRect(
         this.hv(new WTransform(1, 0, 0, 1, -selectionRect.getWidth(), 0).map(selectionRect)));
     painter.setClipPath(
         this.hv(
                 new WTransform(1, 0, 0, 1, left, -top)
                     .multiply(
                         new WTransform()
                             .translate(
                                 this.transform_.getValue().map(selectionRect.getTopLeft()))))
             .map(leftClipPath));
     painter.setPen(this.getSeriesPen());
     painter.drawPath(curve);
     WPainterPath rightClipPath = new WPainterPath();
     rightClipPath.addRect(
         this.hv(new WTransform(1, 0, 0, 1, selectionRect.getWidth(), 0).map(selectionRect)));
     painter.setClipPath(
         this.hv(
                 new WTransform(1, 0, 0, 1, left - selectionRect.getRight(), -top)
                     .multiply(
                         new WTransform()
                             .translate(
                                 this.transform_.getValue().map(selectionRect.getTopRight()))))
             .map(rightClipPath));
     painter.drawPath(curve);
     painter.setClipping(false);
   } else {
     painter.setPen(this.getSeriesPen());
     painter.drawPath(curve);
   }
   if (this.getMethod() == WPaintedWidget.Method.HtmlCanvas) {
     WApplication app = WApplication.getInstance();
     StringBuilder ss = new StringBuilder();
     ss.append("new Wt3_3_5.WAxisSliderWidget(")
         .append(app.getJavaScriptClass())
         .append(",")
         .append(this.getJsRef())
         .append(",")
         .append(this.getObjJsRef())
         .append(",")
         .append("{chart:")
         .append(this.chart_.getCObjJsRef())
         .append(",transform:")
         .append(this.transform_.getJsRef())
         .append(",rect:function(){return ")
         .append(rect.getJsRef())
         .append("},drawArea:")
         .append(drawArea.getJsRef())
         .append(",series:")
         .append(this.seriesColumn_)
         .append("});");
     this.doJavaScript(ss.toString());
   }
   Utils.copyList(segmentsBak, this.chart_.getAxis(Axis.XAxis).segments_);
   this.chart_.getAxis(Axis.XAxis).renderInterval_ = renderIntervalBak;
 }
예제 #22
0
  /**
   * Write a file to the response stream. Handles Range requests.
   *
   * @param req request
   * @param res response
   * @param file must exists and not be a directory
   * @param contentType must not be null
   * @throws IOException or error
   */
  public static void returnFile(
      HttpServletRequest req, HttpServletResponse res, File file, String contentType)
      throws IOException {
    res.setContentType(contentType);

    // see if its a Range Request
    boolean isRangeRequest = false;
    long startPos = 0, endPos = Long.MAX_VALUE;
    String rangeRequest = req.getHeader("Range");
    if (rangeRequest != null) { // bytes=12-34 or bytes=12-
      int pos = rangeRequest.indexOf("=");
      if (pos > 0) {
        int pos2 = rangeRequest.indexOf("-");
        if (pos2 > 0) {
          String startString = rangeRequest.substring(pos + 1, pos2);
          String endString = rangeRequest.substring(pos2 + 1);
          startPos = Long.parseLong(startString);
          if (endString.length() > 0) endPos = Long.parseLong(endString) + 1;
          isRangeRequest = true;
        }
      }
    }

    // set content length
    long fileSize = file.length();
    long contentLength = fileSize;
    if (isRangeRequest) {
      endPos = Math.min(endPos, fileSize);
      contentLength = endPos - startPos;
    }

    if (contentLength > Integer.MAX_VALUE)
      res.addHeader(
          "Content-Length", Long.toString(contentLength)); // allow content length > MAX_INT
    else res.setContentLength((int) contentLength); // note HEAD only allows this

    String filename = file.getPath();
    boolean debugRequest = Debug.isSet("returnFile");
    if (debugRequest)
      log.debug(
          "returnFile(): filename = "
              + filename
              + " contentType = "
              + contentType
              + " contentLength = "
              + contentLength);

    // indicate we allow Range Requests
    res.addHeader("Accept-Ranges", "bytes");

    if (req.getMethod().equals("HEAD")) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, 0));
      return;
    }

    try {

      if (isRangeRequest) {
        // set before content is sent
        res.addHeader("Content-Range", "bytes " + startPos + "-" + (endPos - 1) + "/" + fileSize);
        res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

        FileCacheRaf.Raf craf = null;
        try {
          craf = fileCacheRaf.acquire(filename);
          IO.copyRafB(
              craf.getRaf(), startPos, contentLength, res.getOutputStream(), new byte[60000]);
          log.info(
              "returnFile(): "
                  + UsageLog.closingMessageForRequestContext(
                      HttpServletResponse.SC_PARTIAL_CONTENT, contentLength));
          return;
        } finally {
          if (craf != null) fileCacheRaf.release(craf);
        }
      }

      // Return the file
      ServletOutputStream out = res.getOutputStream();
      IO.copyFileB(file, out, 60000);
      res.flushBuffer();
      out.close();
      if (debugRequest) log.debug("returnFile(): returnFile ok = " + filename);
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, contentLength));
    }

    // @todo Split up this exception handling: those from file access vs those from dealing with
    // response
    //       File access: catch and res.sendError()
    //       response: don't catch (let bubble up out of doGet() etc)
    catch (FileNotFoundException e) {
      log.error("returnFile(): FileNotFoundException= " + filename);
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (java.net.SocketException e) {
      log.info("returnFile(): SocketException sending file: " + filename + " " + e.getMessage());
      log.info("returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0));
    } catch (IOException e) {
      String eName =
          e.getClass().getName(); // dont want compile time dependency on ClientAbortException
      if (eName.equals("org.apache.catalina.connector.ClientAbortException")) {
        log.info(
            "returnFile(): ClientAbortException while sending file: "
                + filename
                + " "
                + e.getMessage());
        log.info(
            "returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0));
        return;
      }

      log.error("returnFile(): IOException (" + e.getClass().getName() + ") sending file ", e);
      log.error(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      if (!res.isCommitted())
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending file: " + e.getMessage());
    }
  }
예제 #23
0
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();

    // All request in GET method must be certificated
    Object obj = session.getAttribute("device_id");

    if (!(obj instanceof Long)) {
      // Client must be login first, then use Mobile service
      response.setStatus(404);
      return;
    }

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Here is tracked's id
    Long device_id = (Long) obj;

    // Determine operation type
    String op = request.getParameter("op");
    if (op == null) op = "";

    // Get current track
    Long track_id = null;
    obj = session.getAttribute("track_id");
    if (obj instanceof Long) {
      track_id = (Long) obj;
    }

    if (op.equals("logout")) {
      // Client request a logout operation
      session.removeAttribute("device_id");
      session.removeAttribute("track_id");
      out.print("OK," + device_id);
    } else if (op.equals("latlng")) {
      // Client insert update it's location in latitude/longitude

      // If it's a first waypoint, create a new track
      if (track_id == null) {
        track_id = db.newTrack(device_id).getResult().getTrackID();
        session.setAttribute("track_id", track_id);
      }

      // Parse latitude, longitude from request
      double lat = Double.parseDouble(request.getParameter("lat"));
      double lng = Double.parseDouble(request.getParameter("lng"));

      long speed = -1L;
      try {
        // Try to get speed from request
        speed = Long.parseLong(request.getParameter("spd"));
      } catch (Exception ex) {
      }

      if (speed < 0) {
        // Client don't send speed to server
        try {
          // Calculate speed manually
          double lastLat = (Double) session.getAttribute("latitude");
          double lastLng = (Double) session.getAttribute("longitude");
          long time = (Long) session.getAttribute("time");
          long distance = Utils.getDistance(lastLat, lastLng, lat, lng);
          speed = distance * 1000 / Math.abs(time - System.currentTimeMillis());
        } catch (Exception ex) {
          speed = 0L;
        }
      }

      // Insert new point into server
      ServiceResult<CWaypoint> result = db.insertWaypoint(track_id, lat, lng, speed);
      CWaypoint cwaypoint = result.getResult();
      if (result.isOK()) {
        // OK,latitude,longitude,speed(m/s),time,trackid
        session.setAttribute("latitude", lat);
        session.setAttribute("longitude", lng);
        session.setAttribute("time", cwaypoint.getTime().getTime());
        out.print(
            "OK,"
                + cwaypoint.getLat()
                + ","
                + cwaypoint.getLng()
                + ","
                + cwaypoint.getSpeed()
                + ","
                + cwaypoint.getTime().getTime()
                + ","
                + cwaypoint.getTrackID());
      }
    } else if (op.equals("cellid")) {
      // Client send it's location by cellular technique
      if (track_id == null) {
        track_id = db.newTrack(device_id).getResult().getTrackID();
        session.setAttribute("track_id", track_id);
      }

      try {
        int cell = Integer.parseInt(request.getParameter("cell"));
        int lac = Integer.parseInt(request.getParameter("lac"));
        Geocode geocode = Utils.getLocation(cell, lac);
        out.println(geocode.getLatitude() + "," + geocode.getLongitude());
      } catch (Exception ex) {
      }

      // TODO Implements cellular method to calculate location of a mobile
      out.println("Not implement");
    } else if (op.equals("newtrack")) {
      // Client request to create a new track
      track_id = db.newTrack(device_id).getResult().getTrackID();
      session.setAttribute("track_id", track_id);
      out.print("OK," + track_id);
    } else if (op.equals("changepass")) {
      String newpass = request.getParameter("newpass");
      if (newpass != null) {
        CTracked ctracked = new CTracked();
        ctracked.setUsername(device_id);
        ctracked.setPassword(newpass);
        if (db.updateTracked(ctracked).isOK()) {
          out.println("OK," + device_id);
        }
      }
    } else if (op.equals("config")) {
      CTracked ctracked = db.getTracked(device_id).getResult();
      Integer interval = ctracked.getIntervalGps();
      if (interval == null) interval = 10;
      out.print("OK," + interval + ",");
      byte[] b = ctracked.getSchedule();
      if (b == null) {
        for (int i = 0; i < 23; i++) {
          out.print("1.");
        }
        out.println(1);
      } else {
        for (int i = 0; i < 23; i++) {
          out.print(b[i] + ".");
        }
        out.println(b[23]);
      }
    } else if (op.equals("amilogin")) {
      out.println("OK");
    }
  }
예제 #24
0
  private String processRequest(
      HttpServletRequest request, HttpServletResponse response, ConnectionPool conPool)
      throws Exception {
    // getting id parameters
    ParameterParser parameter = new ParameterParser(request);
    String bookID = parameter.getString(bookInterface.FIELD_ID, null);
    String sellerID = parameter.getString(bookInterface.FIELD_SELLERID, null);
    String message = parameter.getString(FIELD_MESSAGE, null);
    int codeID = parameter.getInt(bookInterface.FIELD_HIDDENID, 0);
    // get buyer's user object
    User user = (User) request.getSession().getAttribute(StringInterface.USERATTR);
    // security feauture:
    // if one of ids is missing or incorrect return false
    if (bookID == null
        || sellerID == null
        || codeID == 0
        || bookID.length() != booksTable.ID_LENGTH
        || sellerID.length() != usersTable.ID_LENGTH
        || codeID != Math.abs(bookID.hashCode())) {
      return "We were unable to find the book you specified! Please make sure that the book id is correct.";
    }
    if (user.getID().equals(sellerID)) {
      return "You may not purchase an item from yourself!";
    }
    // get connection
    Connection con = conPool.getConnection();
    try {
      booksTable book = generalUtils.getBook(bookID, con);
      /*security feauture:
       *check seller id == passed hidden id
       *book != null
       */
      if (book == null || !book.getSellerID().equals(sellerID)) {
        return "We were unable to find the book you specified! Please make sure that the book id is correct.";
      }
      usersTable sellerInfo = userUtils.getUserInfo(sellerID, con);
      usersTable buyerInfo = userUtils.getUserInfo(user.getID(), con);
      collegeTable college = getCollege(book.getCollegeID() + "", con);
      // if still here continue
      if (message == null) {
        request.setAttribute(ATTR_BOOK, book);
        request.setAttribute(ATTR_SELLER, sellerInfo);
        request.setAttribute(ATTR_BUYER, buyerInfo);
        request.setAttribute(ATTR_COLLEGE, college.getFull());
        RequestDispatcher rd = getServletContext().getRequestDispatcher(PATH_BUY_CONFIRM);
        rd.include(request, response);
        return null;
      } else if (buy(book, user, con)) {
        // sending email to buyer
        request.setAttribute(mailInterface.USERATTR, buyerInfo.getUsername());
        request.setAttribute(mailInterface.EMAILATTR, buyerInfo.getEmail());
        request.setAttribute(mailInterface.BOOKATTR, book);
        request.setAttribute("book_id", bookID);
        request.setAttribute("seller_id", sellerID);

        RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHBIDCONFIRMATION);
        rd.include(request, response);
        // sending email to seller
        request.setAttribute(ATTR_COLLEGE, college.getFull());
        request.setAttribute(mailInterface.USERATTR, sellerInfo.getUsername());
        request.setAttribute(mailInterface.EMAILATTR, sellerInfo.getEmail());
        request.setAttribute(mailInterface.MESSAGEATTR, message);
        request.setAttribute(mailInterface.BOOKATTR, book);
        request.setAttribute(mailInterface.MOREATTR, buyerInfo);

        request.setAttribute("book_id", bookID);
        request.setAttribute("buyer_id", user.getID());
        rd = getServletContext().getRequestDispatcher(PATHBOOKUPDATE);
        rd.include(request, response);
        // showing success message
        rd = getServletContext().getRequestDispatcher(PATH_BUY_SUCCESS);
        rd.include(request, response);
        return null;
      } else {
        throw new Exception("failed to process with buy");
      }
    } catch (Exception e) {
      throw e;
    } finally {
      // recycle
      conPool.free(con);
      con = null;
    }
  }