@Test
  public void testLoadSave() throws IOException {
    Database db = new Database("test", "test.dbl");
    Table t1 = new Table("tname");

    t1.addColumn("A", CharField.class);
    t1.addColumn("B", DateField.class);
    Row r1 = t1.getRowSkeleton();

    Calendar calendar = Calendar.getInstance();
    calendar.set(70, 0, 0);
    Date date = calendar.getTime();

    r1.insert(1, Cell.makeCell(date));
    r1.insert(0, Cell.makeCell("text0"));

    t1.addRow(r1);
    db.addTable(t1);

    db.saveToStorage();
    db = new Database("test", "test.dbl");
    db.loadFromStorage();

    db.loadFromStorage();
    System.out.println(db);
    System.out.println(t1);

    assertTrue(db.getTable("tname").getHeader().equalsModel(t1.getHeader()));
    assertTrue(db.getTable("tname").row(0).at(0).getStringData().equals("text0"));
    assertEquals(
        db.getTable("tname").row(0).at(1).getStringData(), Cell.makeCell(date).getStringData());
    assertEquals(1, t1.size());
  }
Exemple #2
0
 @Test
 public void testGetBytes() throws Exception {
   List<Query.Type> types =
       Arrays.asList(
           Query.Type.TEXT,
           Query.Type.BLOB,
           Query.Type.VARCHAR,
           Query.Type.VARBINARY,
           Query.Type.CHAR,
           Query.Type.BINARY,
           Query.Type.BIT);
   for (Query.Type type : types) {
     try (Cursor cursor =
         new SimpleCursor(
             QueryResult.newBuilder()
                 .addFields(Field.newBuilder().setName("col1").setType(type).build())
                 .addFields(Field.newBuilder().setName("null").setType(type).build())
                 .addRows(
                     Query.Row.newBuilder()
                         .addLengths("hello world".length())
                         .addLengths(-1) // SQL NULL
                         .setValues(ByteString.copyFromUtf8("hello world")))
                 .build())) {
       Row row = cursor.next();
       Assert.assertNotNull(row);
       Assert.assertArrayEquals("hello world".getBytes("UTF-8"), row.getBytes("col1"));
       Assert.assertFalse(row.wasNull());
       Assert.assertEquals(null, row.getBytes("null"));
       Assert.assertTrue(row.wasNull());
     }
   }
 }
 public List<Row> getInvalidRows() {
   List<Row> invalidRows = new ArrayList<Row>();
   for (Row row : rows) {
     if (!row.isValid()) invalidRows.add(row);
   }
   return invalidRows;
 }
Exemple #4
0
 public int addRow(List<String> list) {
   Row row = new Row();
   rows.add(row);
   tableNode.getChildren().add(row.getRowNode());
   for (String s : list) row.appendCell(s == null ? "" : Utils.escapeHTML(s));
   return rows.size() - 1;
 }
Exemple #5
0
 @Test
 public void testGetBigDecimal() throws Exception {
   List<Query.Type> types = Arrays.asList(Query.Type.DECIMAL);
   for (Query.Type type : types) {
     try (Cursor cursor =
         new SimpleCursor(
             QueryResult.newBuilder()
                 .addFields(Field.newBuilder().setName("col1").setType(type).build())
                 .addFields(Field.newBuilder().setName("null").setType(type).build())
                 .addRows(
                     Query.Row.newBuilder()
                         .addLengths("1234.56789".length())
                         .addLengths(-1) // SQL NULL
                         .setValues(ByteString.copyFromUtf8("1234.56789")))
                 .build())) {
       Row row = cursor.next();
       Assert.assertNotNull(row);
       Assert.assertEquals(
           new BigDecimal(BigInteger.valueOf(123456789), 5), row.getBigDecimal("col1"));
       Assert.assertFalse(row.wasNull());
       Assert.assertEquals(null, row.getBigDecimal("null"));
       Assert.assertTrue(row.wasNull());
     }
   }
 }
  private RowModel mapsXmlRowToRowModel(
      List<ColumnMetadata> columnMetaData,
      Row xmlRow,
      ComparatorType keyType,
      GenericTypeEnum[] typesBelongingCompositeTypeForKeyType,
      ComparatorType comparatorType,
      GenericTypeEnum[] typesBelongingCompositeTypeForComparatorType,
      ComparatorType subComparatorType,
      ComparatorType defaultColumnValueType) {
    RowModel row = new RowModel();

    row.setKey(
        TypeExtractor.constructGenericType(
            xmlRow.getKey(), keyType, typesBelongingCompositeTypeForKeyType));

    row.setColumns(
        mapXmlColumnsToColumnsModel(
            columnMetaData,
            xmlRow.getColumn(),
            comparatorType,
            typesBelongingCompositeTypeForComparatorType,
            defaultColumnValueType));
    row.setSuperColumns(
        mapXmlSuperColumnsToSuperColumnsModel(
            columnMetaData,
            xmlRow.getSuperColumn(),
            comparatorType,
            subComparatorType,
            defaultColumnValueType));
    return row;
  }
  /**
   * Set value to the element. The value will not be set if any of the following exceptions happen
   *
   * <p>Sets a value to the element.
   *
   * <p>If val = null, it removes the existing value in the element.
   *
   * <p>Throws OutOfBoundaryException if the input value is invalid (outside the valid alphabet
   * range).
   *
   * <p>Throws DuplicateException if the new value conflicts with one or more of the sequences that
   * the element is associated with.
   *
   * @param val the value to be set. Null if you want to empty the element.
   * @throws OutOfBoundaryException The entered value is out-of-boundary
   * @throws DuplicateException The entered value conflicts with some of the related sequences. The
   *     information of the conflicts is included in the DuplicateException object.
   */
  public void setVal(Character val) throws OutOfBoundaryException, DuplicateException {
    if (val == null) this.val = -1;
    else {
      if (!super.getAlphabet().isValidChar(val)) throw new OutOfBoundaryException();
      // TODO DuplicateException
      ArrayList<Character> notExistedVal = getCandidates();
      if (!notExistedVal.contains(val)) {
        List<Sequence> seq = new ArrayList<Sequence>();
        List<Element> conflictEleList = new ArrayList<Element>();

        if (box.findElement(val) != null) {
          seq.add(box);
          conflictEleList.add(box.findElement(val));
        }
        if (row.findElement(val) != null) {
          seq.add(row);
          conflictEleList.add(row.findElement(val));
        }
        if (col.findElement(val) != null) {
          seq.add(col);
          conflictEleList.add(col.findElement(val));
        }
        throw new DuplicateException(seq, conflictEleList);
      }

      // for(int i=0;i<existedVal.size();i++)
      // if(val == existedVal.get(i))
      // throw new DuplicateException(null,null);
      this.val = getAlphabet().getPosition(val);
    }
  }
Exemple #8
0
  private Row getRow() throws HTMLReaderException {
    Row row = null;
    Row.Type type = null;

    while (current != null && !current.matchesStart("tr")) nextToken();

    if (current != null) nextToken();

    while (current != null && !current.matchesEnd("tr")) {
      if (type == null) {
        type = current.getText().equalsIgnoreCase("th") ? Row.Type.Header : Row.Type.Data;
        row = new Row();
        row.setType(type);
      }
      if (type == Row.Type.Header) {
        if (!current.matchesStart("th"))
          throw new HTMLReaderException("Expected <th> found " + current.getText());
      } else if (!current.matchesStart("td"))
        throw new HTMLReaderException("Expected <td> found " + current.getText());
      nextToken();

      if (current == null) throw new HTMLReaderException("Table incomplete");
      if (cellCreator == null) {
        row.addColumn(current.getType() == Element.Type.Text ? current.getText() : "");
      } else row.addColumn(cellCreator.getValue(this));

      if (current.getType() == Element.Type.End) nextToken();
    }
    return row;
  }
    public String getString(int column) {
      // if we're returning one of the columns in the underlying database column
      // then do so here
      if (column < mColumnCount) {
        return mDatabaseCursor.getString(column);
      }

      // otherwise we're returning one of the synthetic columns.
      // the constants like INTENT_DATA_COLUMN are offsets relative to
      // mColumnCount.
      Row row = mRows.get(mCurrentRow);
      switch (column - mColumnCount) {
        case INTENT_DATA_COLUMN:
          Uri.Builder b = Uri.parse("content://mms-sms/search").buildUpon();
          b = b.appendQueryParameter("pattern", row.getSnippet());
          Uri u = b.build();
          return u.toString();
        case INTENT_ACTION_COLUMN:
          return Intent.ACTION_SEARCH;
        case INTENT_EXTRA_DATA_COLUMN:
          return row.getSnippet();
        case INTENT_TEXT_COLUMN:
          return row.getSnippet();
        default:
          return null;
      }
    }
  private void renderRow(
      XhtmlNode table, Row r, int indent, List<Boolean> indents, String imagePath)
      throws IOException {
    XhtmlNode tr = table.addTag("tr");
    String color = "white";
    if (r.getColor() != null) color = r.getColor();
    tr.setAttribute(
        "style", "border: 0px; padding:0px; vertical-align: top; background-color: " + color + ";");
    boolean first = true;
    for (Cell t : r.getCells()) {
      renderCell(
          tr,
          t,
          "td",
          first ? r.getIcon() : null,
          first ? r.getHint() : null,
          first ? indents : null,
          !r.getSubRows().isEmpty(),
          first ? r.getAnchor() : null,
          color,
          imagePath);
      first = false;
    }
    table.addText("\r\n");

    for (int i = 0; i < r.getSubRows().size(); i++) {
      Row c = r.getSubRows().get(i);
      List<Boolean> ind = new ArrayList<Boolean>();
      ind.addAll(indents);
      if (i == r.getSubRows().size() - 1) ind.add(true);
      else ind.add(false);
      renderRow(table, c, indent + 1, ind, imagePath);
    }
  }
 @Override
 public void writeRow(List<?> row) {
   Row record = sheet.createRow(sheet.getLastRowNum() + 1);
   for (int i = 0; i < row.size(); i++) {
     Cell cell = record.createCell(i);
     Object value = row.get(i);
     if (value == null) {
       cell.setCellValue("");
     } else if (value instanceof String) {
       cell.setCellType(Cell.CELL_TYPE_STRING);
       cell.setCellValue((String) value);
     } else if (value instanceof Number) {
       cell.setCellType(Cell.CELL_TYPE_NUMERIC);
       cell.setCellValue(converters.convert(value, Double.class));
     } else if (value instanceof Date || value instanceof DateTime || value instanceof Calendar) {
       cell.setCellType(Cell.CELL_TYPE_NUMERIC);
       cell.setCellStyle(dateCellStyle);
       cell.setCellValue(converters.convert(value, Date.class));
     } else if (value instanceof Boolean) {
       cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
       cell.setCellValue((Boolean) value);
     } else {
       cell.setCellType(Cell.CELL_TYPE_STRING);
       cell.setCellValue(converters.convert(value, String.class));
     }
   }
 }
  public void parseExcelData(String filepath)
      throws InvalidFormatException, IOException, ParseException {

    Sheet sheet = loadWorksheet(filepath);

    Iterator<Row> row_iter = sheet.iterator();

    // Check if first row is a header row
    if (row_iter.hasNext()) {
      Row header_row = row_iter.next();

      // if the first cell is numeric,
      // there is no header row, reset the iterator
      if (header_row.getCell(0).getCellType() == Cell.CELL_TYPE_NUMERIC)
        row_iter = sheet.iterator();
    }

    while (row_iter.hasNext()) {
      InterviewInstance current_instance = getInstance(row_iter.next());

      // if no interview is present, start one
      if (interviews.isEmpty()) interviews.add(new Interview(current_instance));

      // add to the current interview instance in the list
      // make a new interview if the interview ID doesn't match up
      if (!interviews.get(interviews.size() - 1).add(current_instance))
        interviews.add(new Interview(current_instance));
    }
  }
 void validateDataFrameWithBeans(Bean bean, DataFrame df) {
   StructType schema = df.schema();
   Assert.assertEquals(
       new StructField("a", DoubleType$.MODULE$, false, Metadata.empty()), schema.apply("a"));
   Assert.assertEquals(
       new StructField("b", new ArrayType(IntegerType$.MODULE$, true), true, Metadata.empty()),
       schema.apply("b"));
   ArrayType valueType = new ArrayType(DataTypes.IntegerType, false);
   MapType mapType = new MapType(DataTypes.StringType, valueType, true);
   Assert.assertEquals(new StructField("c", mapType, true, Metadata.empty()), schema.apply("c"));
   Assert.assertEquals(
       new StructField("d", new ArrayType(DataTypes.StringType, true), true, Metadata.empty()),
       schema.apply("d"));
   Row first = df.select("a", "b", "c", "d").first();
   Assert.assertEquals(bean.getA(), first.getDouble(0), 0.0);
   // Now Java lists and maps are converted to Scala Seq's and Map's. Once we get a Seq below,
   // verify that it has the expected length, and contains expected elements.
   Seq<Integer> result = first.getAs(1);
   Assert.assertEquals(bean.getB().length, result.length());
   for (int i = 0; i < result.length(); i++) {
     Assert.assertEquals(bean.getB()[i], result.apply(i));
   }
   @SuppressWarnings("unchecked")
   Seq<Integer> outputBuffer = (Seq<Integer>) first.getJavaMap(2).get("hello");
   Assert.assertArrayEquals(
       bean.getC().get("hello"),
       Ints.toArray(JavaConverters.seqAsJavaListConverter(outputBuffer).asJava()));
   Seq<String> d = first.getAs(3);
   Assert.assertEquals(bean.getD().size(), d.length());
   for (int i = 0; i < d.length(); i++) {
     Assert.assertEquals(bean.getD().get(i), d.apply(i));
   }
 }
Exemple #14
0
  /**
   * Compute width of a column based on a subset of the rows and return the result
   *
   * @param sheet the sheet to calculate
   * @param column 0-based index of the column
   * @param useMergedCells whether to use merged cells
   * @param firstRow 0-based index of the first row to consider (inclusive)
   * @param lastRow 0-based index of the last row to consider (inclusive)
   * @return the width in pixels
   */
  public static double getColumnWidth(
      Sheet sheet, int column, boolean useMergedCells, int firstRow, int lastRow) {
    AttributedString str;
    TextLayout layout;

    Workbook wb = sheet.getWorkbook();
    DataFormatter formatter = new DataFormatter();
    Font defaultFont = wb.getFontAt((short) 0);

    str = new AttributedString(String.valueOf(defaultChar));
    copyAttributes(defaultFont, str, 0, 1);
    layout = new TextLayout(str.getIterator(), fontRenderContext);
    int defaultCharWidth = (int) layout.getAdvance();

    double width = -1;
    for (int rowIdx = firstRow; rowIdx <= lastRow; ++rowIdx) {
      Row row = sheet.getRow(rowIdx);
      if (row != null) {

        Cell cell = row.getCell(column);

        if (cell == null) {
          continue;
        }

        double cellWidth = getCellWidth(cell, defaultCharWidth, formatter, useMergedCells);
        width = Math.max(width, cellWidth);
      }
    }
    return width;
  }
Exemple #15
0
 /** @param value the value to set */
 public void setValue(T value) {
   if (this.value != null) {
     parent.getParent().removeCellOfItem(value);
   }
   this.value = value;
   parent.getParent().setCellOfItem(value, this);
 }
  void deleteRows(Object[] list, int start, int limit, boolean commit) {

    for (int i = start; i < limit; i++) {
      RowAction rowact = (RowAction) list[i];

      if (rowact.type == RowActionBase.ACTION_DELETE_FINAL) {
        try {
          rowact.type = RowActionBase.ACTION_DELETE_COMMITTED;

          PersistentStore store = rowact.session.sessionData.getRowStore(rowact.table);
          Row row = rowact.memoryRow;

          if (row == null) {
            row = (Row) store.get(rowact.getPos(), false);
          }

          if (commit && rowact.table.hasLobColumn) {
            Object[] data = row.getData();

            rowact.session.sessionData.removeLobUsageCount(rowact.table, data);
          }

          store.delete(row);
          store.remove(row.getPos());
        } catch (HsqlException e) {

          //                    throw unexpectedException(e.getMessage());
        }
      }
    }
  }
  /** Insert a node into the index */
  void insert(Session session, Row row, int offset) throws HsqlException {

    Node n = getRoot(session);
    Node x = n;
    boolean isleft = true;
    int compare = -1;

    while (true) {
      if (n == null) {
        if (x == null) {
          setRoot(session, row.getNode(offset));

          return;
        }

        set(x, isleft, row.getNode(offset));

        break;
      }

      compare = compareRowUnique(session, row, n.getRow());

      if (compare == 0) {
        throw Trace.error(Trace.VIOLATION_OF_UNIQUE_INDEX, indexName.name);
      }

      isleft = compare < 0;
      x = n;
      n = child(x, isleft);
    }

    balance(session, x, isleft);
  }
Exemple #18
0
  public static String JsonStringFrom(Map map) throws IOException {
    JsonRecords jsonRecords = new JsonRecords();

    Page page = (Page) map.get("page");
    if (page != null) {
      jsonRecords.setPage(page.getCurrentPage());
      jsonRecords.setRecords(page.getTotalRows());
      jsonRecords.setTotal(page.getTotalPages());
    }
    List data = (List) map.get("data");
    if (data != null) {
      for (int i = 0; i < data.size(); i++) {
        Row row = new Row();

        Object cols = data.get(i);
        if (cols instanceof PropertyList) {
          row.getCell().addAll(((PropertyList) cols).getProperties());
          row.setId(((PropertyList) cols).getId());
        }

        jsonRecords.getRows().add(row);
      }
    }
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(jsonRecords);
  }
Exemple #19
0
  public void add(String type) {
    log.info("addRow");
    Cell cell1 = new Cell();
    cell1.setValue(0);

    Coll coll1 = new Coll();
    coll1.setIndex(0);
    coll1.setCell(cell1);

    ArrayList<Coll> aColl = new ArrayList<Coll>();
    aColl.add(coll1);

    Row row1 = new Row();
    row1.setIndex(0);
    row1.setColl(aColl);

    ArrayList<Row> aRow = new ArrayList<Row>();
    aRow.add(row1);

    Function f = new Function();
    f.setRow(aRow);
    f.setDescription("newFunction");
    f.setNameFirstArgument("x");
    f.setName("y");
    f.setType(type);
    getFunctions().add(f);
  }
Exemple #20
0
	public double getWidth(StringBounder stringBounder) {
		final TextBlock timeHeader = project.getTimeHeader(dayWith);
		final Row row = getMainRow();
		final TextBlock headers = row.header();
		return headers.calculateDimension(stringBounder).getWidth()
				+ timeHeader.calculateDimension(stringBounder).getWidth() + 1;
	}
Exemple #21
0
  public void format() {

    wb = new XSSFWorkbook();

    Map styles = createStyles(wb);
    Sheet sheet = wb.createSheet("Loan Calculator");
    sheet.setPrintGridlines(false);
    sheet.setDisplayGridlines(false);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    sheet.setColumnWidth(0, 768);
    sheet.setColumnWidth(1, 768);
    sheet.setColumnWidth(2, 2816);
    sheet.setColumnWidth(3, 3584);
    sheet.setColumnWidth(4, 3584);
    sheet.setColumnWidth(5, 3584);
    sheet.setColumnWidth(6, 3584);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(35F);
    for (int i = 1; i <= 7; i++)
      titleRow.createCell(i).setCellStyle((CellStyle) styles.get("title"));

    Cell titleCell = titleRow.getCell(2);
    titleCell.setCellValue("Simple");
  }
  @Test
  public void rotatedText() throws Exception {
    Workbook workbook = _testDataProvider.createWorkbook();
    fixFonts(workbook);
    Sheet sheet = workbook.createSheet();
    Row row = sheet.createRow(0);

    CellStyle style1 = workbook.createCellStyle();
    style1.setRotation((short) 90);

    Cell cell0 = row.createCell(0);
    cell0.setCellValue("Apache Software Foundation");
    cell0.setCellStyle(style1);

    Cell cell1 = row.createCell(1);
    cell1.setCellValue("Apache Software Foundation");

    for (int i = 0; i < 2; i++) sheet.autoSizeColumn(i);

    int w0 = sheet.getColumnWidth(0);
    int w1 = sheet.getColumnWidth(1);

    assertTrue(
        w0 * 5 < w1); // rotated text occupies at least five times less horizontal space than normal
    // text

    workbook.close();
  }
 public void initialize(
     Row row, Key hKey, SpatialColumnHandler spatialColumnHandler, long zValue) {
   pKeyAppends = 0;
   int indexField = 0;
   IndexRowComposition indexRowComp = index.indexRowComposition();
   while (indexField < indexRowComp.getLength()) {
     // handleSpatialColumn will increment pKeyAppends once for all spatial columns
     if (spatialColumnHandler != null
         && spatialColumnHandler.handleSpatialColumn(this, indexField, zValue)) {
       if (indexField == index.firstSpatialArgument()) {
         pKeyAppends++;
       }
     } else {
       if (indexRowComp.isInRowData(indexField)) {
         int position = indexRowComp.getFieldPosition(indexField);
         Column column = row.rowType().table().getColumnsIncludingInternal().get(position);
         ValueSource source = row.value(column.getPosition());
         pKeyTarget().append(source, column.getType());
       } else if (indexRowComp.isInHKey(indexField)) {
         PersistitKey.appendFieldFromKey(
             pKey(), hKey, indexRowComp.getHKeyPosition(indexField), index.getIndexName());
       } else {
         throw new IllegalStateException("Invalid IndexRowComposition: " + indexRowComp);
       }
       pKeyAppends++;
     }
     indexField++;
   }
 }
  public void parseData(
      final Sheet sheet,
      final int startRow,
      final int endColumn,
      final List<String> propertyNames,
      final Class clazzOfTestCase) {

    int rowCounter = startRow;

    while (!isBlank(sheet, rowCounter, endColumn)) {
      Row row = sheet.getRow(rowCounter - 1);
      for (int i = 0; i < endColumn; i++) {
        Cell cell = row.getCell(i);
        if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
          try {
            Method method = clazzOfTestCase.getMethod("set" + propertyNames.get(i), Object.class);
          } catch (NoSuchMethodException e) {
            e
                .printStackTrace(); // To change body of catch statement use File | Settings | File
                                    // Templates.
          }
        }
      }
    }
  }
Exemple #25
0
  public void testRowDeleteTypes() throws SQLException, NamingException {
    DatabaseConnValueContext dbvc = new BasicDatabaseConnValueContext();
    dbvc.setConnectionProvider(TestUtils.getConnProvider(this.getClass().getPackage().getName()));
    dbvc.setDefaultDataSource(this.getClass().getPackage().getName());

    final Table testTable = populatedSchema.getTables().getByName("Test_Retire");
    assertEquals(
        RowDeleteType.LOGICAL_CASCADE_CHILDREN, testTable.getRowDeleteType().getValueIndex());

    final Row testTableRow = testTable.createRow();
    final ColumnValues testTableRowValues = testTableRow.getColumnValues();
    testTableRowValues.getByName("text").setTextValue("Test 001");

    ConnectionContext cc = dbvc.getConnection(this.getClass().getPackage().getName(), true);
    testTable.insert(cc, testTableRow);

    cc.commitAndClose();

    cc = dbvc.getConnection(this.getClass().getPackage().getName(), true);
    testTable.delete(cc, testTableRow);
    cc.commitAndClose();

    cc = dbvc.getConnection(this.getClass().getPackage().getName(), true);
    assertEquals(
        1, testTable.getCount(cc)); // make sure the record is there (it's status should be updated)
    cc.commitAndClose();

    // TODO: add child cascade tests
  }
Exemple #26
0
  public static void generateTrainingDataFromFile(
      String
          fileLocation) // Requires that the original file had the metadata and requires that this
        // file is formated the same in first sheet
      {
    testDataLL = (LinkedList<String[]>) dataLL.clone();
    actualClassifications = (LinkedList<String>) classificationsLL.clone();

    FileInputStream file;
    try {
      file = new FileInputStream(new File(fileLocation));
      Workbook excelFile = new HSSFWorkbook(file);
      Sheet sheet1 = excelFile.getSheetAt(0); // Data sheet
      for (Row row : sheet1) {
        String data[] = new String[row.getPhysicalNumberOfCells() - 1];
        String classification = "";

        int offset =
            0; // Used so that we can declare an array of the size of the attributes without the
        // classification
        for (Cell cell : row) {
          int index = cell.getColumnIndex();
          if (classificationLocation != index) {
            data[index - offset] = cell.toString();
          } else {
            classification = cell.toString();
            offset++;
          }
        }

        // Even though data and classifications are not really used add it onto the end so it is
        // still complete for in the event they end up being used in a later version
        dataLL.add(data);
        classificationsLL.add(classification);

        trainingDataLL.add(data);
        knownClassifications.add(classification);

        // Check to see if we have seen that classification yet
        int occurrences = 0;
        for (int i = 0; i < classificationTypes.size() && occurrences == 0; i++) {
          if (classificationTypes.get(i).compareTo(classification) == 0) {
            occurrences = 1;
          }
        }
        if (occurrences == 0) {
          classificationTypes.add(classification);
        }
      }
      excelFile.close();
    } catch (FileNotFoundException e) {
      System.out.println("Error file not found");
      System.exit(0);
    } catch (IOException e) {
      System.out.println("Unable to read file, disk drive may be failing");
      e.printStackTrace();
      System.exit(0);
    }
  }
 private Company toCompany(final Row row) {
   final Company company = new Company();
   final Person person = new Person(row.getString("first_name"), row.getString("last_name"));
   company.setPerson(person);
   company.setAddress(row.getString("address"));
   company.setBrandOpinions(row.getMap("brand_opinions", String.class, String.class));
   return company;
 }
  Column(Row row, String name) {
    _row = row;
    _name = name;

    _columnOffset = _row.getLength();
    _nullOffset = _row.getNullOffset();
    _nullMask = _row.getNullMask();
  }
 private void parseRow(final Row row, final List<String> csvLines) {
   int lastCellNum = row.getLastCellNum();
   for (int i = zeroPos; i <= lastCellNum; i++) {
     Cell cell = row.getCell(i);
     if (cell != null) csvLines.add(parse(cell));
   }
   csvMap.put(row, csvLines);
 }
Exemple #30
0
  /**
   * Get the table with color information added
   *
   * @param gid ID of the table layout
   * @return rows with color information added
   */
  public Row[] getTableDataWithColor(String gid, boolean addColor) {
    final BigInteger[] cids = getCids(gid);
    final TableType table = getTable(gid);
    if (table == null) {
      return new Row[0];
    }
    final List<Row> tableData = new ArrayList<Row>();
    for (int i = 0; i < table.getRow().size(); i++) {
      final RowType rowType = table.getRow().get(i);
      final Row row = new Row();
      row.setOid(rowType.getOid());
      if (addColor) {
        row.setColor(lguiItem.getOIDToObject().getColorById(rowType.getOid()));
      }

      final BigInteger jobIdIndex = getColumnIndex(table, ILguiItem.JOB_ID);
      final Cell[] tableDataRow = new Cell[cids.length];
      String jobId = null;
      for (int j = 0; j < cids.length; j++) {
        for (final CellType cell : rowType.getCell()) {
          if (cell.getCid() != null && cell.getCid().equals(cids[j])) {
            tableDataRow[j] = new Cell(cell.getValue(), row);
            break;
          }
        }
        if (tableDataRow[j] == null) {
          tableDataRow[j] = new Cell(ILMLCoreConstants.QM, row);
        }
        if (cids[j].equals(jobIdIndex)) {
          jobId = tableDataRow[j].value;
        }
      }
      row.setCells(tableDataRow);
      if (jobId != null) {
        JobStatusData status = lguiItem.getUserJob(jobId);
        if (status == null) {
          final String queueName = getCellValue(table, rowType, ILguiItem.JOB_QUEUE_NAME);
          final String owner = getCellValue(table, rowType, ILguiItem.JOB_OWNER);
          final String state = getCellValue(table, rowType, ILguiItem.JOB_STATUS);
          final String[][] attrs = {
            {JobStatusData.MONITOR_ID_ATTR, lguiItem.getName()},
            {JobStatusData.QUEUE_NAME_ATTR, queueName},
            {JobStatusData.OWNER_ATTR, owner},
            {JobStatusData.STATE_ATTR, state}
          };
          status = new JobStatusData(jobId, attrs);
        } else if (status.isRemoved()) {
          /*
           * Skip rows that have been marked as "removed"
           */
          continue;
        }
        row.setJobStatusData(status);
      }
      tableData.add(row);
    }
    return tableData.toArray(new Row[tableData.size()]);
  }