Example usage for java.lang Long compare

List of usage examples for java.lang Long compare

Introduction

In this page you can find the example usage for java.lang Long compare.

Prototype

public static int compare(long x, long y) 

Source Link

Document

Compares two long values numerically.

Usage

From source file:com.jeans.iservlet.controller.impl.ExportController.java

/**
 * ???//from www. j  a  v  a2  s .  com
 * 
 * @return
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST, value = "/systems")
public ResponseEntity<byte[]> exportITSystems() throws IOException {
    StringBuilder fn = new StringBuilder(getCurrentCompany().getName());
    fn.append(" - ??(");
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("?");
    // ?
    // 
    // ?10??
    Font tFont = sheet.getWorkbook().createFont();
    tFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    tFont.setFontName("");
    tFont.setFontHeightInPoints((short) 10);
    // ?????????
    CellStyle cellStyleTitle = sheet.getWorkbook().createCellStyle();
    cellStyleTitle.setAlignment(CellStyle.ALIGN_CENTER);
    cellStyleTitle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    cellStyleTitle.setFont(tFont);
    cellStyleTitle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
    cellStyleTitle.setWrapText(false);
    // 20
    Row row = sheet.createRow(0);
    row.setHeightInPoints(20);
    Cell cell = null;
    for (int i = 0; i < ITSYSTEM_HEADERS.length; i++) {
        cell = row.createCell(i, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleTitle);
        cell.setCellValue(ITSYSTEM_HEADERS[i]);
        sheet.setColumnWidth(i, ITSYSTEM_HEADERS_WIDTH[i] * 256);
    }
    // ?????->?->????
    List<ITSystem> systems = new ArrayList<ITSystem>(systService.listSystems(getCurrentCompany(), null, null));
    Collections.sort(systems, new Comparator<ITSystem>() {

        @Override
        public int compare(ITSystem o1, ITSystem o2) {
            int ret = o1.getType().ordinal() - o2.getType().ordinal();
            if (ret == 0) {
                ret = Long.compare(o1.getOwner().getId(), o2.getOwner().getId());
                if (ret == 0) {
                    ret = Collator.getInstance(java.util.Locale.CHINA).compare(o1.getName(), o2.getName());
                }
            }
            return ret;
        }

    });
    // ??
    DataFormat df = sheet.getWorkbook().createDataFormat();
    // ?10?
    Font font = sheet.getWorkbook().createFont();
    font.setFontName("");
    font.setFontHeightInPoints((short) 10);
    // ?1???????
    CellStyle cellStyleString = sheet.getWorkbook().createCellStyle();
    cellStyleString.setAlignment(CellStyle.ALIGN_CENTER);
    cellStyleString.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    cellStyleString.setFont(font);
    cellStyleString.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
    cellStyleString.setWrapText(false);
    // ?2????(yyyyMMdd)???
    CellStyle cellStyleDate = sheet.getWorkbook().createCellStyle();
    cellStyleDate.setAlignment(CellStyle.ALIGN_CENTER);
    cellStyleDate.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    cellStyleDate.setFont(font);
    cellStyleDate.setDataFormat(df.getFormat("yyyyMMdd"));
    cellStyleDate.setWrapText(false);
    // ?3??????(#)???
    CellStyle cellStyleQuantity = sheet.getWorkbook().createCellStyle();
    cellStyleQuantity.setAlignment(CellStyle.ALIGN_CENTER);
    cellStyleQuantity.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    cellStyleQuantity.setFont(font);
    cellStyleQuantity.setDataFormat(df.getFormat("0"));
    cellStyleQuantity.setWrapText(false);
    // ?4?????(#,##0.00_ )???
    CellStyle cellStyleCost = sheet.getWorkbook().createCellStyle();
    cellStyleCost.setAlignment(CellStyle.ALIGN_RIGHT);
    cellStyleCost.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    cellStyleCost.setFont(font);
    cellStyleCost.setDataFormat(df.getFormat("#,##0.00_ "));
    cellStyleCost.setWrapText(false);
    // sheet
    int rowNumber = 1;
    for (ITSystem system : systems) {
        // 20
        row = sheet.createRow(rowNumber);
        row.setHeightInPoints(20);
        // ?
        Set<SystemBranch> branches = system.getBranches();
        SystemBranch localBranch = null; // ??
        long localId = 0;
        if (getCurrentCompany().getLevel() == Company.BRANCH) {
            localId = getCurrentCompany().getSuperior().getId();
        } else {
            localId = getCurrentCompany().getId();
        }
        BigDecimal cost = new BigDecimal("0.0"); // 
        for (SystemBranch branch : branches) {
            cost.add(branch.getCost());
            if (branch.getCompany().getId() == localId) {
                localBranch = branch;
            }
        }
        boolean branched = (localBranch != null); // ?
        boolean owned = system.getOwner().getId() == getCurrentCompany().getId(); // ?????
        // 
        // 
        cell = row.createCell(0, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getType().getTitle());
        // ??
        cell = row.createCell(1, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getName());
        // 
        cell = row.createCell(2, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getAlias());
        // /?
        cell = row.createCell(3, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getModelOrVersion());
        // 
        cell = row.createCell(4, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getBrief());
        // ?
        cell = row.createCell(5, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(ITSYSTEM_sLevel[system.getSecurityLevel()]);
        // ???
        cell = row.createCell(6, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getSecurityCode());
        // ?
        cell = row.createCell(7, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getUsersBrief());
        // 
        cell = row.createCell(8, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(null == system.getProvider() ? "" : system.getProvider().getAlias());
        // ?
        cell = row.createCell(9, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getOwner().getAlias());
        // 
        cell = row.createCell(10, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getScope().getTitle(system.getOwner().getLevel()));
        // 
        cell = row.createCell(11, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(system.getDeploy().getTitle());
        // 
        cell = row.createCell(12, Cell.CELL_TYPE_STRING);
        cell.setCellStyle(cellStyleString);
        cell.setCellValue(branched ? "" : "");
        if (branched) {
            // ?()
            cell = row.createCell(13, Cell.CELL_TYPE_NUMERIC);
            cell.setCellStyle(cellStyleCost);
            cell.setCellValue(localBranch.getCost().doubleValue());
            // ?
            cell = row.createCell(14, Cell.CELL_TYPE_STRING);
            cell.setCellStyle(cellStyleString);
            cell.setCellValue(localBranch.getStage().getTitle());
            // ?
            cell = row.createCell(15, Cell.CELL_TYPE_NUMERIC);
            cell.setCellStyle(cellStyleDate);
            Date ct = localBranch.getConstructedTime();
            if (null != ct) {
                cell.setCellValue(ct);
            }
            // ?
            cell = row.createCell(16, Cell.CELL_TYPE_NUMERIC);
            cell.setCellStyle(cellStyleDate);
            Date at = localBranch.getAbandonedTime();
            if (null != at) {
                cell.setCellValue(at);
            }
        }
        // ??
        cell = row.createCell(17, Cell.CELL_TYPE_NUMERIC);
        cell.setCellStyle(cellStyleQuantity);
        cell.setCellValue(system.getFreeMaintainMonths());
        if (owned) {
            // 
            cell = row.createCell(18, Cell.CELL_TYPE_NUMERIC);
            cell.setCellStyle(cellStyleQuantity);
            cell.setCellValue(branches.size());
            // ?)
            cell = row.createCell(19, Cell.CELL_TYPE_NUMERIC);
            cell.setCellStyle(cellStyleCost);
            cell.setCellValue(cost.doubleValue());
            // ??
            cell = row.createCell(20, Cell.CELL_TYPE_STRING);
            cell.setCellStyle(cellStyleString);
            cell.setCellValue(system.getStage().getTitle());
            // ?
            cell = row.createCell(21, Cell.CELL_TYPE_NUMERIC);
            cell.setCellStyle(cellStyleDate);
            Date ct = system.getConstructedTime();
            if (null != ct) {
                cell.setCellValue(ct);
            }
            // ?
            cell = row.createCell(22, Cell.CELL_TYPE_NUMERIC);
            cell.setCellStyle(cellStyleDate);
            Date at = system.getAbandonedTime();
            if (null != at) {
                cell.setCellValue(at);
            }
        }
        rowNumber++;
    }

    fn.append((new SimpleDateFormat("yyyyMMdd")).format(new Date())).append(").xlsx");
    String filename = null;
    if (isIE()) {
        filename = URLEncoder.encode(fn.toString(), "UTF-8").replaceAll("\\+", "%20");
    } else {
        filename = new String(fn.toString().getBytes("UTF-8"), "iso8859-1");
    }
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-disposition", "attachment; filename=" + filename);
    BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream(), 4096);
    wb.write(out);
    wb.close();
    out.close();
    return null;
}

From source file:org.apache.nifi.provenance.MiNiFiPersistentProvenanceRepository.java

/**
 * <p>/*from ww  w  .j a  v  a  2  s  .  co m*/
 * Merges all of the given Journal Files into a single, merged Provenance Event Log File. As these records are merged, they will be compressed, if the repository is configured to compress records
 * </p>
 * <p>
 * <p>
 * If the repository is configured to compress the data, the file written to may not be the same as the <code>suggestedMergeFile</code>, as a filename extension of '.gz' may be appended. If the
 * journals are successfully merged, the file that they were merged into will be returned. If unable to merge the records (for instance, because the repository has been closed or because the list
 * of journal files was empty), this method will return <code>null</code>.
 * </p>
 *
 * @param journalFiles       the journal files to merge
 * @param suggestedMergeFile the file to write the merged records to
 * @param eventReporter      the event reporter to report any warnings or errors to; may be null.
 * @return the file that the given journals were merged into, or <code>null</code> if no records were merged.
 * @throws IOException if a problem occurs writing to the mergedFile, reading from a journal
 */
File mergeJournals(final List<File> journalFiles, final File suggestedMergeFile,
        final EventReporter eventReporter) throws IOException {
    if (this.closed.get()) {
        logger.info("Provenance Repository has been closed; will not merge journal files to {}",
                suggestedMergeFile);
        return null;
    }

    if (journalFiles.isEmpty()) {
        logger.debug("Couldn't merge journals: Journal Files is empty; won't merge journals");
        return null;
    }

    Collections.sort(journalFiles, new Comparator<File>() {
        @Override
        public int compare(final File o1, final File o2) {
            final String suffix1 = StringUtils.substringAfterLast(o1.getName(), ".");
            final String suffix2 = StringUtils.substringAfterLast(o2.getName(), ".");

            try {
                final int journalIndex1 = Integer.parseInt(suffix1);
                final int journalIndex2 = Integer.parseInt(suffix2);
                return Integer.compare(journalIndex1, journalIndex2);
            } catch (final NumberFormatException nfe) {
                return o1.getName().compareTo(o2.getName());
            }
        }
    });

    final String firstJournalFile = journalFiles.get(0).getName();
    final String firstFileSuffix = StringUtils.substringAfterLast(firstJournalFile, ".");
    final boolean allPartialFiles = firstFileSuffix.equals("0");

    // check if we have all of the "partial" files for the journal.
    if (allPartialFiles) {
        if (suggestedMergeFile.exists()) {
            // we have all "partial" files and there is already a merged file. Delete the data from the index
            // because the merge file may not be fully merged. We will re-merge.
            logger.warn("Merged Journal File {} already exists; however, all partial journal files also exist "
                    + "so assuming that the merge did not finish. Repeating procedure in order to ensure consistency.");

            // Since we only store the file's basename, block offset, and event ID, and because the newly created file could end up on
            // a different Storage Directory than the original, we need to ensure that we delete both the partially merged
            // file and the TOC file. Otherwise, we could get the wrong copy and have issues retrieving events.
            if (!suggestedMergeFile.delete()) {
                logger.error(
                        "Failed to delete partially written Provenance Journal File {}. This may result in events from this journal "
                                + "file not being able to be displayed. This file should be deleted manually.",
                        suggestedMergeFile);
            }

            final File tocFile = TocUtil.getTocFile(suggestedMergeFile);
            if (tocFile.exists() && !tocFile.delete()) {
                logger.error(
                        "Failed to delete .toc file {}; this may result in not being able to read the Provenance Events from the {} Journal File. "
                                + "This can be corrected by manually deleting the {} file",
                        tocFile, suggestedMergeFile, tocFile);
            }
        }
    } else {
        logger.warn("Cannot merge journal files {} because expected first file to end with extension '.0' "
                + "but it did not; assuming that the files were already merged but only some finished deletion "
                + "before restart. Deleting remaining partial journal files.", journalFiles);

        for (final File file : journalFiles) {
            if (!file.delete() && file.exists()) {
                logger.warn(
                        "Failed to delete unneeded journal file {}; this file should be cleaned up manually",
                        file);
            }
        }

        return null;
    }

    final long startNanos = System.nanoTime();

    // Map each journal to a RecordReader
    final List<RecordReader> readers = new ArrayList<>();
    int records = 0;

    final boolean isCompress = configuration.isCompressOnRollover();
    final File writerFile = isCompress
            ? new File(suggestedMergeFile.getParentFile(), suggestedMergeFile.getName() + ".gz")
            : suggestedMergeFile;

    try {
        for (final File journalFile : journalFiles) {
            try {
                // Use MAX_VALUE for number of chars because we don't want to truncate the value as we write it
                // out. This allows us to later decide that we want more characters and still be able to retrieve
                // the entire event.
                readers.add(RecordReaders.newRecordReader(journalFile, null, Integer.MAX_VALUE));
            } catch (final EOFException eof) {
                // there's nothing here. Skip over it.
            } catch (final IOException ioe) {
                logger.warn("Unable to merge {} with other Journal Files due to {}", journalFile,
                        ioe.toString());
                if (logger.isDebugEnabled()) {
                    logger.warn("", ioe);
                }

                if (eventReporter != null) {
                    eventReporter.reportEvent(Severity.ERROR, EVENT_CATEGORY, "re " + ioe.toString());
                }
            }
        }

        // Create a Map so that the key is the next record available from a reader and the value is the Reader from which
        // the record came. This sorted map is then used so that we are able to always get the first entry, which is the next
        // lowest record id
        final SortedMap<StandardProvenanceEventRecord, RecordReader> recordToReaderMap = new TreeMap<>(
                new Comparator<StandardProvenanceEventRecord>() {
                    @Override
                    public int compare(final StandardProvenanceEventRecord o1,
                            final StandardProvenanceEventRecord o2) {
                        return Long.compare(o1.getEventId(), o2.getEventId());
                    }
                });

        long minEventId = 0L;
        long earliestTimestamp = System.currentTimeMillis();
        for (final RecordReader reader : readers) {
            StandardProvenanceEventRecord record = null;

            try {
                record = reader.nextRecord();
            } catch (final EOFException eof) {
            } catch (final Exception e) {
                logger.warn("Failed to generate Provenance Event Record from Journal due to " + e
                        + "; it's possible that the record wasn't "
                        + "completely written to the file. This record will be skipped.");
                if (logger.isDebugEnabled()) {
                    logger.warn("", e);
                }

                if (eventReporter != null) {
                    eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY,
                            "Failed to read Provenance Event Record from Journal due to " + e
                                    + "; it's possible that hte record wasn't completely written to the file. This record will be skipped.");
                }
            }

            if (record == null) {
                continue;
            }

            if (record.getEventTime() < earliestTimestamp) {
                earliestTimestamp = record.getEventTime();
            }

            if (record.getEventId() < minEventId) {
                minEventId = record.getEventId();
            }

            recordToReaderMap.put(record, reader);
        }

        // loop over each entry in the map, persisting the records to the merged file in order, and populating the map
        // with the next entry from the journal file from which the previous record was written.
        try (final RecordWriter writer = RecordWriters.newSchemaRecordWriter(writerFile,
                configuration.isCompressOnRollover(), true)) {
            writer.writeHeader(minEventId);

            while (!recordToReaderMap.isEmpty()) {
                final Map.Entry<StandardProvenanceEventRecord, RecordReader> entry = recordToReaderMap
                        .entrySet().iterator().next();
                final StandardProvenanceEventRecord record = entry.getKey();
                final RecordReader reader = entry.getValue();

                writer.writeRecord(record, record.getEventId());
                final int blockIndex = writer.getTocWriter().getCurrentBlockIndex();

                records++;

                // Remove this entry from the map
                recordToReaderMap.remove(record);

                // Get the next entry from this reader and add it to the map
                StandardProvenanceEventRecord nextRecord = null;

                try {
                    nextRecord = reader.nextRecord();
                } catch (final EOFException eof) {
                }

                if (nextRecord != null) {
                    recordToReaderMap.put(nextRecord, reader);
                }
            }
        }
    } finally {
        for (final RecordReader reader : readers) {
            try {
                reader.close();
            } catch (final IOException ioe) {
            }
        }
    }

    // Success. Remove all of the journal files, as they're no longer needed, now that they've been merged.
    for (final File journalFile : journalFiles) {
        if (!journalFile.delete() && journalFile.exists()) {
            logger.warn("Failed to remove temporary journal file {}; this file should be cleaned up manually",
                    journalFile.getAbsolutePath());

            if (eventReporter != null) {
                eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY,
                        "Failed to remove temporary journal file " + journalFile.getAbsolutePath()
                                + "; this file should be cleaned up manually");
            }
        }

        final File tocFile = getTocFile(journalFile);
        if (!tocFile.delete() && tocFile.exists()) {
            logger.warn(
                    "Failed to remove temporary journal TOC file {}; this file should be cleaned up manually",
                    tocFile.getAbsolutePath());

            if (eventReporter != null) {
                eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY,
                        "Failed to remove temporary journal TOC file " + tocFile.getAbsolutePath()
                                + "; this file should be cleaned up manually");
            }
        }
    }

    if (records == 0) {
        writerFile.delete();
        logger.debug("Couldn't merge journals: No Records to merge");
        return null;
    } else {
        final long nanos = System.nanoTime() - startNanos;
        final long millis = TimeUnit.MILLISECONDS.convert(nanos, TimeUnit.NANOSECONDS);
        logger.info(
                "Successfully merged {} journal files ({} records) into single Provenance Log File {} in {} milliseconds",
                journalFiles.size(), records, suggestedMergeFile, millis);
    }

    return writerFile;
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtTargetResourceTest.java

@Test
@Description("Verifies that the API returns the status list with expected content sorted by reportedAt field.")
public void getMultipleActionStatusSortedByReportedAt() throws Exception {
    final String knownTargetId = "targetId";
    final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
    final List<ActionStatus> actionStatus = deploymentManagement.findActionStatusByAction(PAGE, action.getId())
            .getContent().stream().sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId()))
            .collect(Collectors.toList());

    // descending order
    mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
            + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/"
            + MgmtRestConstants.TARGET_V1_ACTION_STATUS).param(MgmtRestConstants.REQUEST_PARAMETER_SORTING,
                    "REPORTEDAT:DESC"))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(1).getId().intValue())))
            .andExpect(jsonPath("content.[0].type", equalTo("canceling")))
            .andExpect(jsonPath("content.[0].messages",
                    hasItem("Update Server: cancel obsolete action due to new update")))
            .andExpect(jsonPath("content.[0].reportedAt", equalTo(actionStatus.get(1).getCreatedAt())))
            .andExpect(jsonPath("content.[1].id", equalTo(actionStatus.get(0).getId().intValue())))
            .andExpect(jsonPath("content.[1].type", equalTo("running")))
            .andExpect(jsonPath("content.[1].reportedAt", equalTo(actionStatus.get(0).getCreatedAt())))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(2)))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(2)))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(2)));

    // ascending order
    mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
            + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/"
            + MgmtRestConstants.TARGET_V1_ACTION_STATUS).param(MgmtRestConstants.REQUEST_PARAMETER_SORTING,
                    "REPORTEDAT:ASC"))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(jsonPath("content.[1].id", equalTo(actionStatus.get(1).getId().intValue())))
            .andExpect(jsonPath("content.[1].type", equalTo("canceling")))
            .andExpect(jsonPath("content.[1].messages",
                    hasItem("Update Server: cancel obsolete action due to new update")))
            .andExpect(jsonPath("content.[1].reportedAt", equalTo(actionStatus.get(1).getCreatedAt())))
            .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(0).getId().intValue())))
            .andExpect(jsonPath("content.[0].type", equalTo("running")))
            .andExpect(jsonPath("content.[0].reportedAt", equalTo(actionStatus.get(0).getCreatedAt())))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(2)))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(2)))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(2)));
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtTargetResourceTest.java

@Test
@Description("Verifies that the API returns the status list with expected content split into two pages.")
public void getMultipleActionStatusWithPagingLimitRequestParameter() throws Exception {
    final String knownTargetId = "targetId";

    final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
    final List<ActionStatus> actionStatus = deploymentManagement.findActionStatusByAction(PAGE, action.getId())
            .getContent().stream().sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId()))
            .collect(Collectors.toList());

    // Page 1//from  www.  j av  a 2  s  .  c om
    mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
            + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/"
            + MgmtRestConstants.TARGET_V1_ACTION_STATUS).param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT,
                    String.valueOf(1)))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(1).getId().intValue())))
            .andExpect(jsonPath("content.[0].type", equalTo("canceling")))
            .andExpect(jsonPath("content.[0].messages",
                    hasItem("Update Server: cancel obsolete action due to new update")))
            .andExpect(jsonPath("content.[0].reportedAt", equalTo(actionStatus.get(1).getCreatedAt())))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(2)))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(1)))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(1)));

    // Page 2
    mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
            + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/"
            + MgmtRestConstants.TARGET_V1_ACTION_STATUS)
                    .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1))
                    .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1)))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(0).getId().intValue())))
            .andExpect(jsonPath("content.[0].type", equalTo("running")))
            .andExpect(jsonPath("content.[0].reportedAt", equalTo(actionStatus.get(0).getCreatedAt())))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(2)))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(1)))
            .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(1)));
}

From source file:org.apache.nifi.provenance.MiNiFiPersistentProvenanceRepository.java

/**
 * @return a List of all Provenance Event Log Files, sorted in ascending order by the first Event ID in each file
 *//*from   w  ww . j  a  v  a 2  s .  co  m*/
private List<File> getSortedLogFiles() {
    final List<Path> paths = new ArrayList<>(getAllLogFiles());
    Collections.sort(paths, new Comparator<Path>() {
        @Override
        public int compare(final Path o1, final Path o2) {
            return Long.compare(getFirstEventId(o1.toFile()), getFirstEventId(o2.toFile()));
        }
    });

    final List<File> files = new ArrayList<>(paths.size());
    for (final Path path : paths) {
        files.add(path.toFile());
    }
    return files;
}

From source file:org.apache.carbondata.core.scan.filter.FilterUtil.java

public static int compareFilterKeyBasedOnDataType(String dictionaryVal, String memberVal, DataType dataType) {
    try {//from ww  w  . ja  v  a2s . c o m
        if (dataType == DataTypes.BOOLEAN) {
            return Boolean.compare((Boolean.parseBoolean(dictionaryVal)), (Boolean.parseBoolean(memberVal)));
        } else if (dataType == DataTypes.SHORT) {
            return Short.compare((Short.parseShort(dictionaryVal)), (Short.parseShort(memberVal)));
        } else if (dataType == DataTypes.INT) {
            return Integer.compare((Integer.parseInt(dictionaryVal)), (Integer.parseInt(memberVal)));
        } else if (dataType == DataTypes.DOUBLE) {
            return Double.compare((Double.parseDouble(dictionaryVal)), (Double.parseDouble(memberVal)));
        } else if (dataType == DataTypes.LONG) {
            return Long.compare((Long.parseLong(dictionaryVal)), (Long.parseLong(memberVal)));
        } else if (dataType == DataTypes.BOOLEAN) {
            return Boolean.compare((Boolean.parseBoolean(dictionaryVal)), (Boolean.parseBoolean(memberVal)));
        } else if (dataType == DataTypes.DATE || dataType == DataTypes.TIMESTAMP) {
            String format = CarbonUtil.getFormatFromProperty(dataType);
            SimpleDateFormat parser = new SimpleDateFormat(format);
            Date dateToStr;
            Date dictionaryDate;
            dateToStr = parser.parse(memberVal);
            dictionaryDate = parser.parse(dictionaryVal);
            return dictionaryDate.compareTo(dateToStr);
        } else if (DataTypes.isDecimal(dataType)) {
            java.math.BigDecimal javaDecValForDictVal = new java.math.BigDecimal(dictionaryVal);
            java.math.BigDecimal javaDecValForMemberVal = new java.math.BigDecimal(memberVal);
            return javaDecValForDictVal.compareTo(javaDecValForMemberVal);
        } else {
            return -1;
        }
    } catch (ParseException | NumberFormatException e) {
        return -1;
    }
}

From source file:org.cgiar.ccafs.marlo.action.summaries.ReportingSummaryAction.java

private TypedTableModel getActivitiesReportingTableModel() {
    TypedTableModel model = new TypedTableModel(
            new String[] { "activity_id", "title", "description", "start_date", "end_date", "institution",
                    "activity_leader", "status", "overall" },
            new Class[] { Long.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class },
            0);//w  w w. java2s.c  om
    SimpleDateFormat formatter = new SimpleDateFormat("MMM yyyy");
    if (!project.getActivities().isEmpty()) {
        for (Activity activity : project.getActivities().stream()
                .sorted((d1, d2) -> Long.compare(d1.getId(), d2.getId()))
                .filter(a -> a.isActive() && a.getActivityStatus() != null
                        && (a.getActivityStatus() == 2 || a.getActivityStatus() == 4
                                || a.getActivityStatus() == 3)
                        && a.getStartDate() != null && a.getEndDate() != null && a.getPhase() != null
                        && a.getPhase().equals(this.getSelectedPhase()))
                .collect(Collectors.toList())) {
            // Filter by date
            Calendar cal = Calendar.getInstance();
            cal.setTime(activity.getStartDate());
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(activity.getEndDate());
            if (cal.get(Calendar.YEAR) >= this.getSelectedYear()
                    || cal2.get(Calendar.YEAR) >= this.getSelectedYear()) {
                String institution = null;
                String activityLeader = null;
                String status = null;
                String startDate = null;
                String endDate = null;
                String overall = null;
                if (activity.getStartDate() != null) {
                    startDate = formatter.format(activity.getStartDate());
                }
                if (activity.getEndDate() != null) {
                    endDate = formatter.format(activity.getEndDate());
                }
                if (activity.getProjectPartnerPerson() != null
                        && activity.getProjectPartnerPerson().isActive()) {
                    institution = activity.getProjectPartnerPerson().getProjectPartner().getInstitution()
                            .getComposedName();
                    activityLeader = activity.getProjectPartnerPerson().getUser().getComposedName() + "\n&lt;"
                            + activity.getProjectPartnerPerson().getUser().getEmail() + "&gt;";
                }
                status = ProjectStatusEnum.getValue(activity.getActivityStatus().intValue()).getStatus();
                // Reporting
                if (activity.getActivityProgress() != null && !activity.getActivityProgress().isEmpty()) {
                    overall = activity.getActivityProgress();
                }
                model.addRow(new Object[] { activity.getId(), activity.getTitle(), activity.getDescription(),
                        startDate, endDate, institution, activityLeader, status, overall });
            }
        }
    }
    return model;
}

From source file:org.cgiar.ccafs.marlo.action.summaries.ReportingSummaryAction.java

private TypedTableModel getActivitiesTableModel() {
    TypedTableModel model = new TypedTableModel(
            new String[] { "activity_id", "title", "description", "start_date", "end_date", "institution",
                    "activity_leader", "status", "deliverables" },
            new Class[] { Long.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class },
            0);//  w  w  w .j  a  v  a2  s .c om
    SimpleDateFormat formatter = new SimpleDateFormat("MMM yyyy");
    if (!project.getActivities().isEmpty()) {
        for (Activity activity : project.getActivities().stream()
                .sorted((d1, d2) -> Long.compare(d1.getId(), d2.getId()))
                .filter(a -> a.isActive() && (a.getActivityStatus() == 2 || a.getActivityStatus() == 4)
                        && a.getPhase() != null && a.getPhase().equals(this.getSelectedPhase()))
                .collect(Collectors.toList())) {
            String institution = null;
            String activityLeader = null;
            String status = null;
            String startDate = null;
            String endDate = null;
            String deliverables = "";
            if (activity.getStartDate() != null) {
                startDate = formatter.format(activity.getStartDate());
            }
            if (activity.getEndDate() != null) {
                endDate = formatter.format(activity.getEndDate());
            }
            if (activity.getProjectPartnerPerson() != null) {
                institution = activity.getProjectPartnerPerson().getProjectPartner().getInstitution()
                        .getComposedName();
                activityLeader = activity.getProjectPartnerPerson().getUser().getComposedName() + "\n&lt;"
                        + activity.getProjectPartnerPerson().getUser().getEmail() + "&gt;";
            }
            List<DeliverableActivity> deliverableActivityList = activity.getDeliverableActivities().stream()
                    .filter(da -> da.isActive() && da.getPhase() != null
                            && da.getPhase().equals(this.getSelectedPhase()))
                    .collect(Collectors.toList());
            if (deliverableActivityList != null && !deliverableActivityList.isEmpty()) {
                for (DeliverableActivity deliverableActivity : deliverableActivityList) {
                    String deliverableTitle = "";
                    if (deliverableActivity.getDeliverable().getDeliverableInfo(this.getSelectedPhase())
                            .getTitle() != null) {
                        deliverableTitle = deliverableActivity.getDeliverable()
                                .getDeliverableInfo(this.getSelectedPhase()).getTitle();
                    } else {
                        deliverableTitle = "&lt;Not Defined&gt;";
                    }
                    if (deliverables.isEmpty()) {
                        deliverables = "? D" + deliverableActivity.getDeliverable().getId() + ": "
                                + deliverableTitle;
                    } else {
                        deliverables += "<br>? D" + deliverableActivity.getDeliverable().getId() + ": "
                                + deliverableTitle;
                    }
                }
            }
            status = ProjectStatusEnum.getValue(activity.getActivityStatus().intValue()).getStatus();
            model.addRow(new Object[] { activity.getId(), activity.getTitle(), activity.getDescription(),
                    startDate, endDate, institution, activityLeader, status, deliverables });
        }
    }
    return model;
}

From source file:org.apache.nifi.cluster.manager.impl.WebClusterManager.java

private void mergeProvenanceQueryResults(final ProvenanceDTO provenanceDto,
        final Map<NodeIdentifier, ProvenanceDTO> resultMap, final Set<NodeResponse> problematicResponses) {
    final ProvenanceResultsDTO results = provenanceDto.getResults();
    final ProvenanceRequestDTO request = provenanceDto.getRequest();
    final List<ProvenanceEventDTO> allResults = new ArrayList<>(1024);

    final Set<String> errors = new HashSet<>();
    Date oldestEventDate = new Date();
    int percentageComplete = 0;
    boolean finished = true;

    long totalRecords = 0;
    for (final Map.Entry<NodeIdentifier, ProvenanceDTO> entry : resultMap.entrySet()) {
        final NodeIdentifier nodeIdentifier = entry.getKey();
        final String nodeAddress = nodeIdentifier.getApiAddress() + ":" + nodeIdentifier.getApiPort();

        final ProvenanceDTO nodeDto = entry.getValue();
        final ProvenanceResultsDTO nodeResultDto = nodeDto.getResults();
        if (nodeResultDto != null && nodeResultDto.getProvenanceEvents() != null) {
            // increment the total number of records
            totalRecords += nodeResultDto.getTotalCount();

            // populate the cluster identifier
            for (final ProvenanceEventDTO eventDto : nodeResultDto.getProvenanceEvents()) {
                eventDto.setClusterNodeId(nodeIdentifier.getId());
                eventDto.setClusterNodeAddress(nodeAddress);
                // add node identifier to the event's id so that it is unique across cluster
                eventDto.setId(nodeIdentifier.getId() + eventDto.getId());
                allResults.add(eventDto);
            }//  w  ww.j av a2 s.c om
        }

        if (nodeResultDto.getOldestEvent() != null && nodeResultDto.getOldestEvent().before(oldestEventDate)) {
            oldestEventDate = nodeResultDto.getOldestEvent();
        }

        if (nodeResultDto.getErrors() != null) {
            for (final String error : nodeResultDto.getErrors()) {
                errors.add(nodeAddress + " -- " + error);
            }
        }

        percentageComplete += nodeDto.getPercentCompleted();
        if (!nodeDto.isFinished()) {
            finished = false;
        }
    }
    percentageComplete /= resultMap.size();

    // consider any problematic responses as errors
    for (final NodeResponse problematicResponse : problematicResponses) {
        final NodeIdentifier problemNode = problematicResponse.getNodeId();
        final String problemNodeAddress = problemNode.getApiAddress() + ":" + problemNode.getApiPort();
        errors.add(String.format("%s -- Request did not complete successfully (Status code: %s)",
                problemNodeAddress, problematicResponse.getStatus()));
    }

    // Since we get back up to the maximum number of results from each node, we need to sort those values and then
    // grab only the first X number of them. We do a sort based on time, such that the newest are included.
    // If 2 events have the same timestamp, we do a secondary sort based on Cluster Node Identifier. If those are
    // equal, we perform a terciary sort based on the the event id
    Collections.sort(allResults, new Comparator<ProvenanceEventDTO>() {
        @Override
        public int compare(final ProvenanceEventDTO o1, final ProvenanceEventDTO o2) {
            final int eventTimeComparison = o1.getEventTime().compareTo(o2.getEventTime());
            if (eventTimeComparison != 0) {
                return -eventTimeComparison;
            }

            final String nodeId1 = o1.getClusterNodeId();
            final String nodeId2 = o2.getClusterNodeId();
            final int nodeIdComparison;
            if (nodeId1 == null && nodeId2 == null) {
                nodeIdComparison = 0;
            } else if (nodeId1 == null) {
                nodeIdComparison = 1;
            } else if (nodeId2 == null) {
                nodeIdComparison = -1;
            } else {
                nodeIdComparison = -nodeId1.compareTo(nodeId2);
            }

            if (nodeIdComparison != 0) {
                return nodeIdComparison;
            }

            return -Long.compare(o1.getEventId(), o2.getEventId());
        }
    });

    final int maxResults = request.getMaxResults().intValue();
    final List<ProvenanceEventDTO> selectedResults;
    if (allResults.size() < maxResults) {
        selectedResults = allResults;
    } else {
        selectedResults = allResults.subList(0, maxResults);
    }

    // include any errors
    if (errors.size() > 0) {
        results.setErrors(errors);
    }

    results.setTotalCount(totalRecords);
    results.setTotal(FormatUtils.formatCount(totalRecords));
    results.setProvenanceEvents(selectedResults);
    results.setOldestEvent(oldestEventDate);
    results.setGenerated(new Date());
    provenanceDto.setPercentCompleted(percentageComplete);
    provenanceDto.setFinished(finished);
}

From source file:org.cgiar.ccafs.marlo.action.summaries.ReportingSummaryAction.java

private TypedTableModel getDeliverablesTableModel() {
    TypedTableModel model = new TypedTableModel(
            new String[] { "deliverable_id", "title", "deliv_type", "deliv_sub_type", "deliv_status",
                    "deliv_year", "key_output", "leader", "institution", "funding_sources", "cross_cutting" },
            new Class[] { Long.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class },
            0);//  ww w  .  j  a  v a  2  s.  c  o  m
    if (!project.getDeliverables().isEmpty()) {
        for (Deliverable deliverable : project.getDeliverables().stream()
                .sorted((d1, d2) -> Long.compare(d1.getId(), d2.getId()))
                .filter(d -> d.isActive() && d.getDeliverableInfo(this.getSelectedPhase()) != null && ((d
                        .getDeliverableInfo().getStatus() == null
                        && d.getDeliverableInfo().getYear() == this.getSelectedYear())
                        || (d.getDeliverableInfo().getStatus() != null
                                && d.getDeliverableInfo().getStatus().intValue() == Integer
                                        .parseInt(ProjectStatusEnum.Extended.getStatusId())
                                && d.getDeliverableInfo().getNewExpectedYear() != null
                                && d.getDeliverableInfo().getNewExpectedYear() == this.getSelectedYear())
                        || (d.getDeliverableInfo().getStatus() != null
                                && d.getDeliverableInfo().getYear() == this.getSelectedYear()
                                && d.getDeliverableInfo().getStatus().intValue() == Integer
                                        .parseInt(ProjectStatusEnum.Ongoing.getStatusId()))
                        || (d.getDeliverableInfo().getStatus() != null
                                && d.getDeliverableInfo().getStatus().intValue() == Integer
                                        .parseInt(ProjectStatusEnum.Complete.getStatusId())
                                && ((d.getDeliverableInfo().getNewExpectedYear() != null && d
                                        .getDeliverableInfo().getNewExpectedYear() == this.getSelectedYear())
                                        || (d.getDeliverableInfo().getNewExpectedYear() == null && d
                                                .getDeliverableInfo().getYear() == this.getSelectedYear())))))
                .collect(Collectors.toList())) {
            String delivType = null;
            String delivSubType = null;
            String delivStatus = deliverable.getDeliverableInfo(this.getSelectedPhase())
                    .getStatusName(this.getSelectedPhase());
            String delivYear = null;
            String keyOutput = "";
            String leader = null;
            String institution = null;
            String fundingSources = "";
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getDeliverableType() != null) {
                delivSubType = deliverable.getDeliverableInfo(this.getSelectedPhase()).getDeliverableType()
                        .getName();
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getDeliverableType()
                        .getDeliverableCategory() != null) {
                    delivType = deliverable.getDeliverableInfo(this.getSelectedPhase()).getDeliverableType()
                            .getDeliverableCategory().getName();
                }
            }
            if (delivStatus.equals("")) {
                delivStatus = null;
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getYear() != 0) {
                delivYear = "" + deliverable.getDeliverableInfo(this.getSelectedPhase()).getYear();
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrpClusterKeyOutput() != null) {
                keyOutput += "? ";
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrpClusterKeyOutput()
                        .getCrpClusterOfActivity().getCrpProgram() != null) {
                    keyOutput += deliverable.getDeliverableInfo(this.getSelectedPhase())
                            .getCrpClusterKeyOutput().getCrpClusterOfActivity().getCrpProgram().getAcronym()
                            + " - ";
                }
                keyOutput += deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrpClusterKeyOutput()
                        .getKeyOutput();
            }
            // Get partner responsible and institution
            List<DeliverablePartnership> deliverablePartnershipResponsibles = deliverablePartnershipManager
                    .findByDeliverablePhaseAndType(deliverable.getId(), this.getSelectedPhase().getId(),
                            DeliverablePartnershipTypeEnum.RESPONSIBLE.getValue());
            if (deliverablePartnershipResponsibles != null && deliverablePartnershipResponsibles.size() > 0) {
                if (deliverablePartnershipResponsibles.size() > 1) {
                    LOG.warn("There are more than 1 deliverable responsibles for D" + deliverable.getId()
                            + ". Phase: " + this.getSelectedPhase().toString());
                    deliverablePartnershipResponsibles.sort((d1, d2) -> d1.getProjectPartnerPerson().getId()
                            .compareTo(d2.getProjectPartnerPerson().getId()));
                }
                DeliverablePartnership responisble = deliverablePartnershipResponsibles.get(0);

                if (responisble != null) {
                    if (responisble.getProjectPartnerPerson() != null) {
                        ProjectPartnerPerson responsibleppp = responisble.getProjectPartnerPerson();
                        leader = responsibleppp.getUser().getComposedName() + "<br>&lt;"
                                + responsibleppp.getUser().getEmail() + "&gt;";
                        if (responsibleppp.getProjectPartner() != null) {
                            if (responsibleppp.getProjectPartner().getInstitution() != null) {
                                institution = responsibleppp.getProjectPartner().getInstitution()
                                        .getComposedName();
                            }
                        }
                    }
                }
            }
            // Get funding sources if exist
            for (DeliverableFundingSource dfs : deliverable.getDeliverableFundingSources().stream().filter(
                    d -> d.isActive() && d.getPhase() != null && d.getPhase().equals(this.getSelectedPhase()))
                    .collect(Collectors.toList())) {
                fundingSources += "? " + "(" + dfs.getFundingSource().getId() + ") - "
                        + dfs.getFundingSource().getFundingSourceInfo(this.getSelectedPhase()).getTitle()
                        + "<br>";
            }
            if (fundingSources.isEmpty()) {
                fundingSources = null;
            }
            // Get cross_cutting dimension
            String crossCutting = "";
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingNa() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingNa() == true) {
                    crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? N/A <br>";
                }
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingGender() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingGender() == true) {
                    Long scoring = deliverable.getDeliverableInfo().getCrossCuttingScoreGender();
                    if (scoring != null) {
                        CrossCuttingScoring crossCuttingScoring = crossCuttingScoringManager
                                .getCrossCuttingScoringById(scoring);
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Gender ("
                                + crossCuttingScoring.getDescription() + ")<br>";
                    } else {
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Gender <br>";
                    }
                }
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingYouth() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingYouth() == true) {
                    Long scoring = deliverable.getDeliverableInfo().getCrossCuttingScoreYouth();
                    if (scoring != null) {
                        CrossCuttingScoring crossCuttingScoring = crossCuttingScoringManager
                                .getCrossCuttingScoringById(scoring);
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Youth ("
                                + crossCuttingScoring.getDescription() + ")<br>";
                    } else {
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Youth <br>";
                    }
                }
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingCapacity() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingCapacity() == true) {
                    Long scoring = deliverable.getDeliverableInfo().getCrossCuttingScoreCapacity();
                    if (scoring != null) {
                        CrossCuttingScoring crossCuttingScoring = crossCuttingScoringManager
                                .getCrossCuttingScoringById(scoring);
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Capacity Development ("
                                + crossCuttingScoring.getDescription() + ")<br>";
                    } else {
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Capacity Development <br>";
                    }
                }
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingGender() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingGender() == true) {
                    if (deliverable.getDeliverableGenderLevels() == null
                            || deliverable.getDeliverableGenderLevels().isEmpty()) {
                        crossCutting += "<br><b>Gender level(s):</b><br>&nbsp;&nbsp;&nbsp;&nbsp;&lt;Not Defined&gt;";
                    } else {
                        crossCutting += "<br><b>Gender level(s): </b><br>";
                        for (DeliverableGenderLevel dgl : deliverable.getDeliverableGenderLevels().stream()
                                .filter(dgl -> dgl.isActive() && dgl.getPhase() != null
                                        && dgl.getPhase().equals(this.getSelectedPhase()))
                                .collect(Collectors.toList())) {
                            if (dgl.getGenderLevel() != 0.0) {
                                crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? " + genderTypeManager
                                        .getGenderTypeById(dgl.getGenderLevel()).getDescription() + "<br>";
                            }
                        }
                    }
                }
            }
            if (crossCutting.isEmpty()) {
                crossCutting = null;
            }
            if (keyOutput.isEmpty()) {
                keyOutput = null;
            }
            model.addRow(new Object[] { deliverable.getId(),
                    deliverable.getDeliverableInfo(this.getSelectedPhase()).getTitle(), delivType, delivSubType,
                    delivStatus, delivYear, keyOutput, leader, institution, fundingSources, crossCutting });
        }
    }
    return model;
}