/* goodB2G1() - use badsource and goodsink by changing second privateReturnsTrue() to privateReturnsFalse() */
  private void goodB2G1() throws Throwable {
    long data;
    if (privateReturnsTrue()) {
      /* POTENTIAL FLAW: Use the maximum size of the data type */
      data = Long.MAX_VALUE;
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = 0L;
    }

    if (privateReturnsFalse()) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      /* FIX: Add a check to prevent an overflow from occurring */
      /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
      if ((data != Integer.MIN_VALUE)
          && (data != Long.MIN_VALUE)
          && (Math.abs(data) <= (long) Math.sqrt(Long.MAX_VALUE))) {
        long result = (long) (data * data);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform squaring.");
      }
    }
  }
Beispiel #2
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();
  }
  /* goodB2G1() - use badsource and goodsink by changing second IO.staticReturnsTrue() to IO.staticReturnsFalse() */
  private void goodB2G1() throws Throwable {
    int data;
    if (IO.staticReturnsTrue()) {
      data = Integer.MIN_VALUE; /* Initialize data */
      /* retrieve the property */
      {
        Properties properties = new Properties();
        FileInputStream streamFileInput = null;
        try {
          streamFileInput = new FileInputStream("../common/config.properties");
          properties.load(streamFileInput);
          /* POTENTIAL FLAW: Read data from a .properties file */
          String stringNumber = properties.getProperty("data");
          if (stringNumber != null) // avoid NPD incidental warnings
          {
            try {
              data = Integer.parseInt(stringNumber.trim());
            } catch (NumberFormatException exceptNumberFormat) {
              IO.logger.log(
                  Level.WARNING,
                  "Number format exception parsing data from string",
                  exceptNumberFormat);
            }
          }
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading object */
          try {
            if (streamFileInput != null) {
              streamFileInput.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = 0;
    }

    if (IO.staticReturnsFalse()) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      /* FIX: Add a check to prevent an overflow from occurring */
      /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
      if ((data != Integer.MIN_VALUE)
          && (data != Long.MIN_VALUE)
          && (Math.abs(data) <= (long) Math.sqrt(Integer.MAX_VALUE))) {
        int result = (int) (data * data);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform squaring.");
      }
    }
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    int data;

    data = Integer.MIN_VALUE; /* Initialize data */

    /* POTENTIAL FLAW: Read data from a querystring using getParameter() */
    {
      String stringNumber = request.getParameter("name");

      try {
        data = Integer.parseInt(stringNumber.trim());
      } catch (NumberFormatException exceptNumberFormat) {
        IO.logger.log(
            Level.WARNING,
            "Number format exception reading data from parameter 'name'",
            exceptNumberFormat);
      }
    }

    /* FIX: Add a check to prevent an overflow from occurring */
    /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
    if ((data != Integer.MIN_VALUE)
        && (data != Long.MIN_VALUE)
        && (Math.abs(data) <= (long) Math.sqrt(Integer.MAX_VALUE))) {
      int result = (int) (data * data);
      IO.writeLine("result: " + result);
    } else {
      IO.writeLine("data value is too large to perform squaring.");
    }
  }
  /* goodB2G1() - use badsource and goodsink by changing second PRIVATE_STATIC_FINAL_FIVE==5 to PRIVATE_STATIC_FINAL_FIVE!=5 */
  private void goodB2G1() throws Throwable {
    short data;
    if (PRIVATE_STATIC_FINAL_FIVE == 5) {
      /* POTENTIAL FLAW: Use a random value */
      data =
          (short)
              ((new java.security.SecureRandom()).nextInt(1 + Short.MAX_VALUE - Short.MIN_VALUE)
                  + Short.MIN_VALUE);
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = 0;
    }

    if (PRIVATE_STATIC_FINAL_FIVE != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      /* FIX: Add a check to prevent an overflow from occurring */
      /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
      if ((data != Integer.MIN_VALUE)
          && (data != Long.MIN_VALUE)
          && (Math.abs(data) <= (long) Math.sqrt(Short.MAX_VALUE))) {
        short result = (short) (data * data);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform squaring.");
      }
    }
  }
  private void goodB2GSink(byte data) throws Throwable {

    /* FIX: Add a check to prevent an overflow from occurring */
    /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
    if ((data != Integer.MIN_VALUE)
        && (data != Long.MIN_VALUE)
        && (Math.abs(data) <= (long) Math.sqrt(Byte.MAX_VALUE))) {
      byte result = (byte) (data * data);
      IO.writeLine("result: " + result);
    } else {
      IO.writeLine("data value is too large to perform squaring.");
    }
  }
 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);
 }
  /* goodB2G() - use BadSource and GoodSink */
  public void goodB2GSink(HashMap<Integer, Long> dataHashMap) throws Throwable {
    long data = dataHashMap.get(2);

    /* FIX: Add a check to prevent an overflow from occurring */
    /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
    if ((data != Integer.MIN_VALUE)
        && (data != Long.MIN_VALUE)
        && (Math.abs(data) <= (long) Math.sqrt(Long.MAX_VALUE))) {
      long result = (long) (data * data);
      IO.writeLine("result: " + result);
    } else {
      IO.writeLine("data value is too large to perform squaring.");
    }
  }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2GSink(int data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    /* FIX: Add a check to prevent an overflow from occurring */
    /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
    if ((data != Integer.MIN_VALUE)
        && (data != Long.MIN_VALUE)
        && (Math.abs(data) <= (long) Math.sqrt(Integer.MAX_VALUE))) {
      int result = (int) (data * data);
      IO.writeLine("result: " + result);
    } else {
      IO.writeLine("data value is too large to perform squaring.");
    }
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G() throws Throwable {
    int data = (new CWE190_Integer_Overflow__int_Environment_square_61b()).goodB2GSource();

    /* FIX: Add a check to prevent an overflow from occurring */
    /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
    if ((data != Integer.MIN_VALUE)
        && (data != Long.MIN_VALUE)
        && (Math.abs(data) <= (long) Math.sqrt(Integer.MAX_VALUE))) {
      int result = (int) (data * data);
      IO.writeLine("result: " + result);
    } else {
      IO.writeLine("data value is too large to perform squaring.");
    }
  }
 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_);
 }
Beispiel #12
0
  public String createUID() {
    Long num;
    String uid;

    uid = "";
    num = new Date().getTime();
    while (num > 0) {
      uid += UIDMap[(int) (num % 62)];
      num /= 62;
    }

    uid += Math.round(Math.random() * 9.0);

    return uid;
  }
 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));
       }
     }
   }
 }
  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;
  }
Beispiel #15
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();
  }
Beispiel #16
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());
     }
     ;
   }
 }
  /* goodB2G() - use BadSource and GoodSink */
  public void goodB2GSink(byte[] dataSerialized) throws Throwable {
    /* unserialize data */
    ByteArrayInputStream streamByteArrayInput = null;
    ObjectInputStream streamObjectInput = null;

    try {
      streamByteArrayInput = new ByteArrayInputStream(dataSerialized);
      streamObjectInput = new ObjectInputStream(streamByteArrayInput);
      int data = (Integer) streamObjectInput.readObject();

      /* FIX: Add a check to prevent an overflow from occurring */
      /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
      if ((data != Integer.MIN_VALUE)
          && (data != Long.MIN_VALUE)
          && (Math.abs(data) <= (long) Math.sqrt(Integer.MAX_VALUE))) {
        int result = (int) (data * data);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform squaring.");
      }

    } catch (IOException exceptIO) {
      IO.logger.log(Level.WARNING, "IOException in deserialization", exceptIO);
    } catch (ClassNotFoundException exceptClassNotFound) {
      IO.logger.log(
          Level.WARNING, "ClassNotFoundException in deserialization", exceptClassNotFound);
    } finally {
      /* clean up stream reading objects */
      try {
        if (streamObjectInput != null) {
          streamObjectInput.close();
        }
      } catch (IOException exceptIO) {
        IO.logger.log(Level.WARNING, "Error closing ObjectInputStream", exceptIO);
      }

      try {
        if (streamByteArrayInput != null) {
          streamByteArrayInput.close();
        }
      } catch (IOException exceptIO) {
        IO.logger.log(Level.WARNING, "Error closing ByteArrayInputStream", exceptIO);
      }
    }
  }
Beispiel #18
0
 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));
 }
 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();
 }
Beispiel #20
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);
 }
  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>");
 }
Beispiel #24
0
 public void processAlgorithm() {
   List<List<Double>> testData = data.getTestData();
   int testNum = data.getTestNum();
   long begin = System.currentTimeMillis();
   for (int i = 0; i < testNum; i++) {
     List<Double> test = testData.get(i);
     result[i][0] = Arith.convertsToInt(test.get(0));
     result[i][1] = Math.round(Float.parseFloat((knn(data.getTrainData(), test, 3))));
     if (result[i][0] != result[i][1]) {
       ma.setWrong(ma.getWrong() + 1);
     }
   }
   long end = System.currentTimeMillis();
   ma.setTime(begin, end);
   ma.setAccuracyRate(ma.getWrong(), testNum);
   ma.setErrorRate(ma.getWrong(), testNum);
 }
Beispiel #25
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;
  }
Beispiel #26
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");
    }
  }
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();

    //	String id = request.getParameter("id");
    //  MediaFile mediaFile = mediaFileService.getMediaFile(path);

    int listOffset = DEFAULT_LIST_OFFSET;
    int listSize = DEFAULT_LIST_SIZE;
    String listType = DEFAULT_LIST_TYPE;

    User user = securityService.getCurrentUser(request);
    String username = user.getUsername();
    UserSettings userSettings = settingsService.getUserSettings(username);
    int userGroupId = securityService.getCurrentUserGroupId(request);

    if (request.getParameter("listOffset") != null) {
      listOffset =
          Math.max(
              0, Math.min(Integer.parseInt(request.getParameter("listOffset")), MAX_LIST_OFFSET));
    }

    if (request.getParameter("listSize") != null) {
      listSize =
          Math.max(0, Math.min(Integer.parseInt(request.getParameter("listSize")), MAX_LIST_SIZE));
    }

    if (request.getParameter("listType") != null) {
      listType = String.valueOf(request.getParameter("listType"));
    }
    List<MediaFile> songs;
    if ("topplayed".equals(listType)) {
      songs = mediaFileDao.getTopPlayedCountForUser(listOffset, listSize, username);
    } else if ("otheruser".equals(listType)) {
      songs = mediaFileDao.getLastPlayedCountForAllUser(listOffset, listSize, userGroupId);
    } else if ("overall".equals(listType)) {
      songs = mediaFileDao.getTopPlayedCountForAllUser(listOffset, listSize, userGroupId);
    } else if ("lastplayed".equals(listType)) {
      songs = mediaFileDao.getLastPlayedCountForUser(listOffset, listSize, username);
    } else {
      songs = mediaFileDao.getLastPlayedCountForAllUser(0, 1, userGroupId);
    }

    mediaFileService.populateStarredDate(songs, username);
    map.put("user", user);
    map.put("songs", songs);

    map.put("partyModeEnabled", userSettings.isPartyModeEnabled());
    map.put("player", playerService.getPlayer(request, response));

    map.put("listOffset", listOffset);
    map.put("listSize", listSize);
    map.put("listType", listType);

    //  map.put("starred", mediaFileService.getMediaFileStarredDate(dir.getId(), username) != null);

    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
  }
  /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
  private void goodB2G2() throws Throwable {
    int data;
    if (PRIVATE_STATIC_FINAL_FIVE == 5) {
      data = Integer.MIN_VALUE; /* Initialize data */
      {
        File file = new File("C:\\data.txt");
        FileInputStream streamFileInput = null;
        InputStreamReader readerInputStream = null;
        BufferedReader readerBuffered = null;
        try {
          /* read string from file into data */
          streamFileInput = new FileInputStream(file);
          readerInputStream = new InputStreamReader(streamFileInput, "UTF-8");
          readerBuffered = new BufferedReader(readerInputStream);
          /* POTENTIAL FLAW: Read data from a file */
          /* This will be reading the first "line" of the file, which
           * could be very long if there are little or no newlines in the file */
          String stringNumber = readerBuffered.readLine();
          if (stringNumber != null) /* avoid NPD incidental warnings */ {
            try {
              data = Integer.parseInt(stringNumber.trim());
            } catch (NumberFormatException exceptNumberFormat) {
              IO.logger.log(
                  Level.WARNING,
                  "Number format exception parsing data from string",
                  exceptNumberFormat);
            }
          }
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          /* Close stream reading objects */
          try {
            if (readerBuffered != null) {
              readerBuffered.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStream != null) {
              readerInputStream.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }

          try {
            if (streamFileInput != null) {
              streamFileInput.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = 0;
    }

    if (PRIVATE_STATIC_FINAL_FIVE == 5) {
      /* FIX: Add a check to prevent an overflow from occurring */
      /* NOTE: Math.abs of the minimum int or long will return that same value, so we must check for it */
      if ((data != Integer.MIN_VALUE)
          && (data != Long.MIN_VALUE)
          && (Math.abs(data) <= (long) Math.sqrt(Integer.MAX_VALUE))) {
        int result = (int) (data * data);
        IO.writeLine("result: " + result);
      } else {
        IO.writeLine("data value is too large to perform squaring.");
      }
    }
  }
Beispiel #29
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;
  }
Beispiel #30
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");
    }
  }