Example usage for java.text NumberFormat setMaximumFractionDigits

List of usage examples for java.text NumberFormat setMaximumFractionDigits

Introduction

In this page you can find the example usage for java.text NumberFormat setMaximumFractionDigits.

Prototype

public void setMaximumFractionDigits(int newValue) 

Source Link

Document

Sets the maximum number of digits allowed in the fraction portion of a number.

Usage

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

@Override
@SuppressWarnings("unchecked")
public void sube(byte[] datos, Usuario usuario, OutputStream out, Integer codigoInicial) {
    Date inicio = new Date();
    int idx = 5;//from   w w  w.j  av a  2 s.c  o m
    int i = 0;
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yy");
    SimpleDateFormat sdf3 = new SimpleDateFormat("dd-MM-yy");

    MathContext mc = new MathContext(16, RoundingMode.HALF_UP);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMaximumFractionDigits(0);
    nf.setMinimumIntegerDigits(5);

    Transaction tx = null;
    try {
        String ejercicioId = "001-2012";
        Map<String, CentroCosto> centrosDeCosto = new HashMap<>();
        Map<String, TipoActivo> tipos = new HashMap<>();
        Query tipoActivoQuery = currentSession()
                .createQuery("select ta from TipoActivo ta " + "where ta.empresa.id = :empresaId "
                        + "and ta.cuenta.id.ejercicio.id.idEjercicio = :ejercicioId "
                        + "and ta.cuenta.id.ejercicio.id.organizacion.id = :organizacionId");
        log.debug("empresaId: {}", usuario.getEmpresa().getId());
        log.debug("ejercicioId: {}", ejercicioId);
        log.debug("organizacionId: {}", usuario.getEmpresa().getOrganizacion().getId());
        tipoActivoQuery.setLong("empresaId", usuario.getEmpresa().getId());
        tipoActivoQuery.setString("ejercicioId", ejercicioId);
        tipoActivoQuery.setLong("organizacionId", usuario.getEmpresa().getOrganizacion().getId());
        List<TipoActivo> listaTipos = tipoActivoQuery.list();
        for (TipoActivo tipoActivo : listaTipos) {
            tipos.put(tipoActivo.getCuenta().getId().getIdCtaMayor(), tipoActivo);
        }
        log.debug("TIPOS: {}", tipos);

        Query proveedorQuery = currentSession().createQuery(
                "select p from Proveedor p where p.empresa.id = :empresaId and p.nombre = :nombreEmpresa");
        proveedorQuery.setLong("empresaId", usuario.getEmpresa().getId());
        proveedorQuery.setString("nombreEmpresa", usuario.getEmpresa().getNombre());
        Proveedor proveedor = (Proveedor) proveedorQuery.uniqueResult();

        Query codigoDuplicadoQuery = currentSession()
                .createQuery("select a from Activo a where a.empresa.id = :empresaId and a.codigo = :codigo");

        XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(datos));
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet ccostoFantasma = wb.createSheet("CCOSTO-FANTASMAS");
        int ccostoFantasmaRow = 0;
        XSSFSheet sinCCosto = wb.createSheet("SIN-CCOSTO");
        int sinCCostoRow = 0;
        XSSFSheet codigoAsignado = wb.createSheet("CODIGO-ASIGNADO");
        int codigoAsignadoRow = 0;
        XSSFSheet fechaInvalida = wb.createSheet("FECHA-INVALIDA");
        int fechaInvalidaRow = 0;
        XSSFSheet sinCosto = wb.createSheet("SIN-COSTO");
        int sinCostoRow = 0;

        tx = currentSession().beginTransaction();
        for (idx = 0; idx <= 5; idx++) {
            XSSFSheet sheet = workbook.getSheetAt(idx);

            int rows = sheet.getPhysicalNumberOfRows();
            for (i = 2; i < rows; i++) {
                log.debug("Leyendo pagina {} renglon {}", idx, i);
                XSSFRow row = sheet.getRow(i);
                if (row.getCell(0) == null) {
                    break;
                }
                String nombreGrupo = row.getCell(0).getStringCellValue().trim();
                TipoActivo tipoActivo = tipos.get(nombreGrupo);
                if (tipoActivo != null) {
                    String cuentaCCosto = row.getCell(2).toString().trim();
                    if (StringUtils.isNotBlank(cuentaCCosto)) {
                        CentroCosto centroCosto = centrosDeCosto.get(cuentaCCosto);
                        if (centroCosto == null) {
                            Query ccostoQuery = currentSession().createQuery("select cc from CentroCosto cc "
                                    + "where cc.id.ejercicio.id.idEjercicio = :ejercicioId "
                                    + "and cc.id.ejercicio.id.organizacion.id = :organizacionId "
                                    + "and cc.id.idCosto like :idCosto");
                            ccostoQuery.setString("ejercicioId", ejercicioId);
                            ccostoQuery.setLong("organizacionId",
                                    usuario.getEmpresa().getOrganizacion().getId());
                            ccostoQuery.setString("idCosto", "1.01." + cuentaCCosto);
                            ccostoQuery.setMaxResults(1);
                            List<CentroCosto> listaCCosto = ccostoQuery.list();
                            if (listaCCosto != null && listaCCosto.size() > 0) {
                                centroCosto = listaCCosto.get(0);
                            }
                            if (centroCosto == null) {
                                XSSFRow renglon = ccostoFantasma.createRow(ccostoFantasmaRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9).setCellValue(row.getCell(8).toString());
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                continue;
                            }
                            centrosDeCosto.put(cuentaCCosto, centroCosto);
                        }
                        String poliza = null;
                        switch (row.getCell(4).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            poliza = row.getCell(4).toString();
                            poliza = StringUtils.removeEnd(poliza, ".0");
                            log.debug("POLIZA-N: {}", poliza);
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            poliza = row.getCell(4).getStringCellValue().trim();
                            log.debug("POLIZA-S: {}", poliza);
                            break;
                        }
                        Boolean seguro = false;
                        if (row.getCell(5) != null && StringUtils.isNotBlank(row.getCell(5).toString())) {
                            seguro = true;
                        }
                        Boolean garantia = false;
                        if (row.getCell(6) != null && StringUtils.isNotBlank(row.getCell(6).toString())) {
                            garantia = true;
                        }
                        Date fechaCompra = null;
                        if (row.getCell(7) != null) {
                            log.debug("VALIDANDO FECHA");
                            XSSFCell cell = row.getCell(7);
                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_NUMERIC:
                                log.debug("ES NUMERIC");
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    log.debug("ES FECHA");
                                    fechaCompra = cell.getDateCellValue();
                                } else if (DateUtil.isCellInternalDateFormatted(cell)) {
                                    log.debug("ES FECHA INTERNAL");
                                    fechaCompra = cell.getDateCellValue();
                                } else {
                                    BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
                                    bd = stripTrailingZeros(bd);

                                    log.debug("CONVIRTIENDO DOUBLE {} - {}",
                                            DateUtil.isValidExcelDate(bd.doubleValue()), bd);
                                    fechaCompra = HSSFDateUtil.getJavaDate(bd.longValue(), true);
                                    log.debug("Cal: {}", fechaCompra);
                                }
                                break;
                            case Cell.CELL_TYPE_FORMULA:
                                log.debug("ES FORMULA");
                                CellValue cellValue = evaluator.evaluate(cell);
                                switch (cellValue.getCellType()) {
                                case Cell.CELL_TYPE_NUMERIC:
                                    if (DateUtil.isCellDateFormatted(cell)) {
                                        fechaCompra = DateUtil.getJavaDate(cellValue.getNumberValue(), true);
                                    }
                                }
                            }
                        }
                        if (row.getCell(7) != null && fechaCompra == null) {
                            String fechaCompraString;
                            if (row.getCell(7).getCellType() == Cell.CELL_TYPE_STRING) {
                                fechaCompraString = row.getCell(7).getStringCellValue();
                            } else {
                                fechaCompraString = row.getCell(7).toString().trim();
                            }
                            try {
                                fechaCompra = sdf.parse(fechaCompraString);
                            } catch (ParseException e) {
                                try {
                                    fechaCompra = sdf2.parse(fechaCompraString);
                                } catch (ParseException e2) {
                                    try {
                                        fechaCompra = sdf3.parse(fechaCompraString);
                                    } catch (ParseException e3) {
                                        // no se pudo convertir
                                    }
                                }
                            }
                        }

                        if (fechaCompra == null) {
                            XSSFRow renglon = fechaInvalida.createRow(fechaInvalidaRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        String codigo = null;
                        switch (row.getCell(8).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            codigo = row.getCell(8).toString();
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            codigo = row.getCell(8).getStringCellValue().trim();
                            break;
                        }
                        if (StringUtils.isBlank(codigo)) {
                            codigo = nf.format(codigoInicial);
                            XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(codigoInicial);
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            codigoInicial++;
                        } else {
                            // busca codigo duplicado
                            if (codigo.contains(".")) {
                                codigo = codigo.substring(0, codigo.lastIndexOf("."));
                                log.debug("CODIGO: {}", codigo);
                            }

                            codigoDuplicadoQuery.setLong("empresaId", usuario.getEmpresa().getId());
                            codigoDuplicadoQuery.setString("codigo", codigo);
                            Activo activo = (Activo) codigoDuplicadoQuery.uniqueResult();
                            if (activo != null) {
                                XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9).setCellValue(codigo + "-" + nf.format(codigoInicial));
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                codigo = nf.format(codigoInicial);
                                codigoInicial++;
                            }
                        }
                        String descripcion = null;
                        if (row.getCell(9) != null) {
                            switch (row.getCell(9).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                descripcion = row.getCell(9).toString();
                                descripcion = StringUtils.removeEnd(descripcion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                descripcion = row.getCell(9).getStringCellValue().trim();
                                break;
                            default:
                                descripcion = row.getCell(9).toString().trim();
                            }
                        }
                        String marca = null;
                        if (row.getCell(10) != null) {
                            switch (row.getCell(10).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                marca = row.getCell(10).toString();
                                marca = StringUtils.removeEnd(marca, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                marca = row.getCell(10).getStringCellValue().trim();
                                break;
                            default:
                                marca = row.getCell(10).toString().trim();
                            }
                        }
                        String modelo = null;
                        if (row.getCell(11) != null) {
                            switch (row.getCell(11).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                modelo = row.getCell(11).toString();
                                modelo = StringUtils.removeEnd(modelo, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                modelo = row.getCell(11).getStringCellValue().trim();
                                break;
                            default:
                                modelo = row.getCell(11).toString().trim();
                            }
                        }
                        String serie = null;
                        if (row.getCell(12) != null) {
                            switch (row.getCell(12).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                serie = row.getCell(12).toString();
                                serie = StringUtils.removeEnd(serie, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                serie = row.getCell(12).getStringCellValue().trim();
                                break;
                            default:
                                serie = row.getCell(12).toString().trim();
                            }
                        }
                        String responsable = null;
                        if (row.getCell(13) != null) {
                            switch (row.getCell(13).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                responsable = row.getCell(13).toString();
                                responsable = StringUtils.removeEnd(responsable, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                responsable = row.getCell(13).getStringCellValue().trim();
                                break;
                            default:
                                responsable = row.getCell(13).toString().trim();
                            }
                        }

                        String ubicacion = null;
                        if (row.getCell(14) != null) {
                            switch (row.getCell(14).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                ubicacion = row.getCell(14).toString();
                                ubicacion = StringUtils.removeEnd(ubicacion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                ubicacion = row.getCell(14).getStringCellValue().trim();
                                break;
                            default:
                                ubicacion = row.getCell(14).toString().trim();
                            }
                        }
                        BigDecimal costo = null;
                        switch (row.getCell(15).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            costo = new BigDecimal(row.getCell(15).getNumericCellValue(), mc);
                            log.debug("COSTO-N: {} - {}", costo, row.getCell(15).getNumericCellValue());
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            costo = new BigDecimal(row.getCell(15).toString(), mc);
                            log.debug("COSTO-S: {} - {}", costo, row.getCell(15).toString());
                            break;
                        case XSSFCell.CELL_TYPE_FORMULA:
                            costo = new BigDecimal(
                                    evaluator.evaluateInCell(row.getCell(15)).getNumericCellValue(), mc);
                            log.debug("COSTO-F: {}", costo);
                        }
                        if (costo == null) {
                            XSSFRow renglon = sinCosto.createRow(sinCostoRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        Activo activo = new Activo(fechaCompra, seguro, garantia, poliza, codigo, descripcion,
                                marca, modelo, serie, responsable, ubicacion, costo, tipoActivo, centroCosto,
                                proveedor, usuario.getEmpresa());
                        this.crea(activo, usuario);

                    } else {
                        XSSFRow renglon = sinCCosto.createRow(sinCCostoRow++);
                        renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                        renglon.createCell(1).setCellValue(row.getCell(0).toString());
                        renglon.createCell(2).setCellValue(row.getCell(1).toString());
                        renglon.createCell(3).setCellValue(row.getCell(2).toString());
                        renglon.createCell(4).setCellValue(row.getCell(3).toString());
                        renglon.createCell(5).setCellValue(row.getCell(4).toString());
                        renglon.createCell(6).setCellValue(row.getCell(5).toString());
                        renglon.createCell(7).setCellValue(row.getCell(6).toString());
                        renglon.createCell(8).setCellValue(row.getCell(7).toString());
                        renglon.createCell(9).setCellValue(row.getCell(8).toString());
                        renglon.createCell(10).setCellValue(row.getCell(9).toString());
                        renglon.createCell(11).setCellValue(row.getCell(10).toString());
                        renglon.createCell(12).setCellValue(row.getCell(11).toString());
                        renglon.createCell(13).setCellValue(row.getCell(12).toString());
                        renglon.createCell(14).setCellValue(row.getCell(13).toString());
                        renglon.createCell(15).setCellValue(row.getCell(14).toString());
                        renglon.createCell(16).setCellValue(row.getCell(15).toString());
                        continue;
                    }
                } else {
                    throw new RuntimeException(
                            "(" + idx + ":" + i + ") No se encontro el tipo de activo " + nombreGrupo);
                }
            }
        }
        tx.commit();
        log.debug("################################################");
        log.debug("################################################");
        log.debug("TERMINO EN {} MINS", (new Date().getTime() - inicio.getTime()) / (1000 * 60));
        log.debug("################################################");
        log.debug("################################################");

        wb.write(out);
    } catch (IOException | RuntimeException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        log.error("Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
        throw new RuntimeException(
                "Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
    }
}

From source file:org.kuali.kfs.gl.batch.service.impl.ScrubberProcessImpl.java

/**
 * Generate the flag for the end of specific descriptions. This will be used in the demerger step
 *//*from   w  w w  . ja v  a 2  s.c o  m*/
protected void setOffsetString() {

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(0);
    nf.setMaximumIntegerDigits(2);
    nf.setMinimumFractionDigits(0);
    nf.setMinimumIntegerDigits(2);

    offsetString = COST_SHARE_TRANSFER_ENTRY_IND + nf.format(runCal.get(Calendar.MONTH) + 1)
            + nf.format(runCal.get(Calendar.DAY_OF_MONTH));
}

From source file:org.sakaiproject.content.tool.ListItem.java

/**
 * Utility method to get a verbose filesize string.
 * @param size_long The size to be displayed (bytes).
 * @return A long human readable filesize.
 *///  w w  w  .  j  a  v a  2s.c om
public static String formatLongSize(long size_long) {
    // This method needs to be moved somewhere more sensible.
    String sizzle = "";
    NumberFormat formatter = NumberFormat.getInstance(rb.getLocale());
    formatter.setMaximumFractionDigits(1);
    if (size_long > 700000000L) {
        String[] argyles = { formatter.format(1.0 * size_long / (1024L * 1024L * 1024L)),
                formatter.format(size_long) };
        sizzle = rb.getFormattedMessage("size.gbytes", argyles);
    } else if (size_long > 700000L) {
        String[] argyles = { formatter.format(1.0 * size_long / (1024L * 1024L)), formatter.format(size_long) };
        sizzle = rb.getFormattedMessage("size.mbytes", argyles);
    } else if (size_long > 700L) {
        String[] argyles = { formatter.format(1.0 * size_long / 1024L), formatter.format(size_long) };
        sizzle = rb.getFormattedMessage("size.kbytes", argyles);
    } else {
        String[] args = { formatter.format(size_long) };
        sizzle = rb.getFormattedMessage("size.bytes", args);
    }
    return sizzle;
}

From source file:org.sakaiproject.content.tool.ListItem.java

/**
 * Utility method to get a nice short filesize string.
 * @param size_long The size to be displayed (bytes).
 * @return A short human readable filesize.
 *//*w w w .  ja  va  2 s.co  m*/
public static String formatSize(long size_long) {
    // This method needs to be moved somewhere more sensible.
    String size = "";
    NumberFormat formatter = NumberFormat.getInstance(rb.getLocale());
    formatter.setMaximumFractionDigits(1);
    if (size_long > 700000000L) {
        String[] args = { formatter.format(1.0 * size_long / (1024L * 1024L * 1024L)) };
        size = rb.getFormattedMessage("size.gb", args);
    } else if (size_long > 700000L) {
        String[] args = { formatter.format(1.0 * size_long / (1024L * 1024L)) };
        size = rb.getFormattedMessage("size.mb", args);

    } else if (size_long > 700L) {
        String[] args = { formatter.format(1.0 * size_long / 1024L) };
        size = rb.getFormattedMessage("size.kb", args);
    } else {
        String[] args = { formatter.format(size_long) };
        size = rb.getFormattedMessage("size.bytes", args);
    }
    return size;
}

From source file:com.aol.framework.helper.report.CustomizedReporter.java

synchronized private void generateTestExecutionStatus(boolean emailable, List<ISuite> suites,
        PrintWriter f_out) {//  w w w.j  a  v  a2 s .c om
    String testName = "";

    int totalPassedMethods = 0;
    int totalFailedMethods = 0;
    int totalSkippedMethods = 0;
    int totalSkippedConfigurationMethods = 0;
    int totalFailedConfigurationMethods = 0;
    int totalAutomationErrors = 0;
    int totalMethods = 0;

    int suite_totalPassedMethods = 0;
    int suite_totalFailedMethods = 0;
    int suite_totalSkippedMethods = 0;
    int suite_totalAutomationErrors = 0;

    String suite_passPercentage = "";
    String suiteName = "";

    ITestContext overview = null;
    HashMap<String, String> dashboardReportMap = new HashMap<String, String>();

    String dashboardAppGroup = "";

    for (ISuite suite : suites) {
        suiteName = suite.getName();
        TestHelper.logger.info(">> " + suiteName + " <<");
        Map<String, ISuiteResult> tests = suite.getResults();
        NumberFormat nf = NumberFormat.getInstance();

        for (ISuiteResult r : tests.values()) {
            overview = r.getTestContext();
            testName = overview.getName();

            totalPassedMethods = overview.getPassedTests().getAllMethods().size();
            totalFailedMethods = overview.getFailedTests().getAllMethods().size();
            totalAutomationErrors = overview.getFailedButWithinSuccessPercentageTests().getAllMethods().size();
            totalSkippedMethods = overview.getSkippedTests().getAllMethods().size();
            totalFailedConfigurationMethods = overview.getFailedConfigurations().getAllMethods().size(); // this should be 0 as redirected to automation error
            // totalMethods = overview.getAllTestMethods().length;
            totalMethods = totalPassedMethods + totalFailedMethods;

            nf.setMaximumFractionDigits(2);
            nf.setGroupingUsed(true);

            String includedModule = "";
            String includedGroup = "";

            ITestNGMethod[] allTestMethods = overview.getAllTestMethods();
            for (ITestNGMethod testngMethod : allTestMethods) {
                String[] modules = testngMethod.getGroups();
                for (String module : modules) {
                    for (String moduleName : TestHelper.MODULES) {
                        if (module.equalsIgnoreCase(moduleName)) {
                            if (!(includedModule.contains(module))) {
                                includedModule = includedModule + " " + module;
                            }
                        }
                    }
                    for (String groupName : TestHelper.TEST_GROUPS) {
                        if (module.equalsIgnoreCase(groupName)) {
                            if (!(includedGroup.contains(module))) {
                                includedGroup = includedGroup + " " + module;
                            }
                        }
                    }
                }
            }

            String[] nodeInfo = getNodeInfo(overview, testName);

            String browser = nodeInfo[1];
            String browser_version = nodeInfo[2];
            String platform = nodeInfo[0];
            //String nodeIp = nodeInfo[3];

            if (platform == null || platform.trim().length() == 0) {
                platform = "N/A";
            }

            if (browser_version == null || browser_version.trim().length() == 0) {
                browser_version = "N/A";
            }

            if (browser == null || browser.trim().length() == 0) {
                browser = "N/A";
            }

            if (!(dashboardReportMap.containsKey(includedModule))) {
                if (browser_version.equalsIgnoreCase("N/A")) {
                    browser_version = "";
                }
                dashboardReportMap.put(includedModule,
                        "os1~" + platform + "|browser1~" + browser + browser_version + "|testcase_count_1~"
                                + totalMethods + "|pass_count_1~" + totalPassedMethods + "|fail_count_1~"
                                + totalFailedMethods + "|skip_count_1~" + totalSkippedMethods
                                + "|skip_conf_count_1~" + totalSkippedConfigurationMethods
                                + "|fail_conf_count_1~" + totalFailedConfigurationMethods
                                + "|fail_automation_count_1~" + totalAutomationErrors);

            } else {
                for (String key : dashboardReportMap.keySet()) {

                    if (key.equalsIgnoreCase(includedModule)) {
                        if (browser_version.equalsIgnoreCase("N/A")) {
                            browser_version = "";
                        }
                        String value = dashboardReportMap.get(key);
                        int index = StringUtils.countMatches(value, "#") + 1;

                        index += 1;

                        value = value + "#" + "os" + index + "~" + platform + "|browser" + index + "~" + browser
                                + browser_version + "|testcase_count_" + index + "~" + totalMethods
                                + "|pass_count_" + index + "~" + totalPassedMethods + "|fail_count_" + index
                                + "~" + totalFailedMethods + "|skip_count_" + index + "~" + totalSkippedMethods
                                + "|skip_conf_count_" + index + "~" + totalSkippedConfigurationMethods
                                + "|fail_conf_count_" + index + "~" + totalFailedConfigurationMethods
                                + "|fail_automation_count_~" + totalAutomationErrors;
                        dashboardReportMap.put(key, value);
                    }
                }
            }

            dashboardAppGroup = includedGroup;
            suite_totalPassedMethods += totalPassedMethods;
            suite_totalFailedMethods += totalFailedMethods;
            suite_totalAutomationErrors += totalAutomationErrors;
            suite_totalSkippedMethods += totalSkippedMethods;

            suite_passPercentage = getPercentage(nf, suite_totalPassedMethods,
                    suite_totalPassedMethods + suite_totalFailedMethods);

        }

    }

    if (!doneOutputToConsole) {
        //**************************** report to console as status ******************

        int suite_totalTestedMethods = suite_totalPassedMethods + suite_totalFailedMethods;

        System.out.println("[TOTAL_METHODS]: " + (suite_totalTestedMethods));

        System.out.println("[PASSED_METHODS]: " + suite_totalPassedMethods);
        if (suite_totalFailedMethods > 0 || suite_totalPassedMethods == 0)
            System.out.println("[FAILED_METHODS]: " + suite_totalFailedMethods);
        if (suite_totalAutomationErrors > 0)
            System.out.println("[AUTOMATION_ERRORS]: " + suite_totalAutomationErrors);
        if (suite_totalSkippedMethods > 0)
            System.out.println("[SKIPPED_METHODS]: " + suite_totalSkippedMethods);

        System.out.println("[PASSED%]: " + suite_passPercentage);

        TestHelper.setReportProperties(suite_totalTestedMethods, suite_totalPassedMethods,
                suite_totalFailedMethods, suite_totalSkippedMethods, suite_passPercentage,
                suite_totalAutomationErrors);
        //********************************************************************************
    }

    StringBuilder dashboardResults = new StringBuilder();
    if (!emailable) {
        dashboardResults.append(
                "<table id=\"myTable\" width=\"100%\" cellspacing=0 cellpadding=0 class=\"tablesorter\">");
    } else {
        dashboardResults.append("<table " + classParam + " cellspacing=\"0\" cellpadding=\"0\" width=\"91%\">");
    }
    dashboardResults
            // .append("<thead><tr> <th>Test Name</th><th>"
            .append("<thead><tr> <th>Module Name</th><th>" + " # Unique TestCases</th><th>"
                    + " # Combinations</th><th>" + " # Passed</th><th>" + " # Failed</th><th>"
                    + " # Warning</th><th>" + " # Skipped</th><th>" + "# Total</th><th>"
                    + "Success Rate</th> </tr> </thead> <tbody>");

    int total_browser_combinations = 0;
    int total_unique_testcases = 0;

    for (String key : dashboardReportMap.keySet()) {

        String fileName = key.trim() + "-Overall" + "-customized-report.html";
        if (!emailable) {

            try {
                generateModuleOverallTestReport(testName, key, suites, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String value = dashboardReportMap.get(key);
        String[] values = value.split("#");

        int testcase_count = 0; //*******************************************
        int pass_count = 0;
        int fail_count = 0;
        int fail_automation_count = 0;
        int skip_count = 0;
        int skip_conf_count = 0;
        int fail_conf_count = 0;
        String appKey = "TEST_APP";
        String appName = TestHelper.getTestConfig(appKey);

        if (dashboardAppGroup.contains("Smoke") && !appName.equalsIgnoreCase("webmail")) {
            appName = appName + "_" + "Smoke";

        } else if (dashboardAppGroup.contains("Regression")) {
            appName = appName + "_" + "Regression";
        }

        String dashboardModule = key;
        //
        //            if (dashboardModule.contains("Compose"))
        //            {
        //                dashboardModule = dashboardModule.replace("Compose", "ComposeMail");
        //            } else if (dashboardModule.contains("Read"))
        //            {
        //                dashboardModule = dashboardModule.replace("Read", "ReadMail");
        //            }

        // int countMatches = StringUtils.countMatches(value, "#") + 1;

        for (String val : values) {

            String[] tokens = val.split("\\|");
            for (String token : tokens) {
                if (token.contains("testcase_count")) {
                    testcase_count = testcase_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("pass_count")) {
                    pass_count = pass_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("fail_count")) {
                    fail_count = fail_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("fail_automation_count")) {
                    fail_automation_count = fail_automation_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("skip_count")) {
                    skip_count = skip_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("skip_conf_count")) {
                    skip_conf_count = skip_conf_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("fail_conf_count")) {
                    fail_conf_count = fail_conf_count + Integer.parseInt(token.split("~")[1]);
                }
            }

            testcase_count -= skip_count + skip_conf_count + fail_conf_count;
        }

        NumberFormat nformat = NumberFormat.getInstance();
        nformat.setMaximumFractionDigits(2);
        nformat.setGroupingUsed(true);
        String passPercent = getPercentage(nformat, pass_count, pass_count + fail_count);

        String finalStr = "[";
        String[] val = dashboardReportMap.get(key).split("#");

        int unique_testcase = 0;

        int limit = val.length - 1;
        for (int i = 0; i < val.length; i++) {//TODO - unique_testcase is the max num cases among tests, not the total for the module across tests - Steven
            String testCaseCount = (val[i].split("\\|")[2]).split("~")[1];
            int next = Integer.parseInt(testCaseCount);
            if (next > unique_testcase) {
                unique_testcase = next;
            }
            finalStr = finalStr + testCaseCount + " T * 1 B]";
            if (i != limit) {
                finalStr += " + [";
            }
        }
        //unique_testcase = 
        String finalString = "";
        //            if ((unique_testcase * values.length) != (pass_count + fail_count + skip_count))
        //            {
        //                finalString = "<a href=\"#\" title=\"" + finalStr + "\">" + (pass_count + fail_count + skip_count)
        //                        + "</a>";
        //                
        //            } else
        {
            finalString = String.valueOf((pass_count + fail_count + fail_automation_count + skip_count));
        }

        String passCount = "";
        String failCount = "";
        String automationErrorCount = "";
        String skipCount = "";

        if (pass_count > 0) {
            passCount = "<td bgcolor=\"" + passColor + "\"><font color=\"white\"><b>" + pass_count
                    + "</b></font></td>";
        } else {
            passCount = "<td>" + pass_count + "</td>";
        }

        if (fail_count > 0) {
            failCount = "<td bgcolor=\"" + failColor + "\"><font color=\"white\"><b>" + fail_count
                    + "</b></font></td>";
        } else {
            failCount = "<td>" + fail_count + "</td>";
        }
        if (fail_automation_count > 0) {
            automationErrorCount = "<td bgcolor=\"" + warnColor + "\"><font color=\"white\"><b>"
                    + fail_automation_count + "</b></font></td>";
        } else {
            automationErrorCount = "<td>" + fail_automation_count + "</td>";
        }

        if (skip_count > 0) {
            skipCount = "<td bgcolor=\"" + skipColor + "\"><font color=\"white\"><b>" + skip_count
                    + "</b></font></td>";
        } else {
            skipCount = "<td>" + skip_count + "</td>";
        }
        if (!emailable || !disableCss) {
            dashboardResults.append("<tr><td><b><a href='" + TestHelper.jenkinsBuildUrl
                    + TestHelper.jenkinsCustomReportTitle + TestHelper.customReportDirLink + fileName + "'>"
                    + dashboardModule + "</b></td><td>"
                    // + testName + "</b></td><td>"  
                    + unique_testcase + "</td><td>" + values.length + "</td>" + passCount + failCount
                    + automationErrorCount + skipCount + "<td>" + finalString + "</td><td><font color=\""
                    + passPercentageColor + "\"><b>" + passPercent + " %" + "</b></font></td></tr>");
        } else {
            dashboardResults.append("<tr><td><b>" + dashboardModule + "</b></td><td>"
            //+ testName + "</b></td><td>"  
                    + unique_testcase + "</td><td>" + values.length + "</td><td>" + pass_count + "</td><td>"
                    + fail_count + "</td><td>" + fail_automation_count + "</td><td>" + skip_count + "</td><td>"
                    + finalString + "</td><td><b>" + passPercent + " %" + "</td></tr>");
        }
        if (total_browser_combinations < values.length) {
            total_browser_combinations = values.length;
        }

        total_unique_testcases += unique_testcase;
    }

    dashboardResults.append("</tbody></table>");

    if (!emailable || !disableCss) {
        String suite_pass = "";
        String suite_fail = "";
        String suite_automation_error = "";
        String suite_skip = "";

        if (suite_totalPassedMethods > 0) {
            suite_pass = "<td bgcolor=\"" + passColor + "\"><font color=\"white\"><b>"
                    + suite_totalPassedMethods + "</b></font></td>";
        } else {
            suite_pass = "<td>" + suite_totalPassedMethods + "</td>";
        }

        if (suite_totalFailedMethods > 0) {
            suite_fail = "<td bgcolor=\"" + failColor + "\"><font color=\"white\"><b>"
                    + suite_totalFailedMethods + "</b></font></td>";
        } else {
            suite_fail = "<td>" + suite_totalFailedMethods + "</td>";
        }
        if (suite_totalAutomationErrors > 0) {
            suite_automation_error = "<td bgcolor=\"" + warnColor + "\"><font color=\"white\"><b>"
                    + suite_totalAutomationErrors + "</b></font></td>";
        } else {
            suite_automation_error = "<td>" + suite_totalAutomationErrors + "</td>";
        }
        if (suite_totalSkippedMethods > 0) {
            suite_skip = "<td bgcolor=\"" + skipColor + "\"><font color=\"white\"><b>"
                    + suite_totalSkippedMethods + "</b></font></td>";
        } else {
            suite_skip = "<td>" + suite_totalSkippedMethods + "</td>";
        }

        // Summary Table
        f_out.println("<p><b>Overall Execution Summary</b></p>");

        if (!emailable) {
            f_out.println("<table class=\"tablesorter\" width=\"100%\">");
        } else {
            f_out.println("<table " + classParam + "  cellspacing=\"0\" cellpadding=\"0\" width=\"91%\">");
        }
        f_out.println(//"<table class=\"param\" width=\"100%\">"+
                "<thead><tr><th>Test Suite Name</th><th>" + "# Unique TestCases</th><th>"
                        + "# Combinations</th> <th>" + "# Passed</th> <th>" + "# Failed</th> <th>"
                        + "# Warning</th> <th>" + "# Skipped</th><th>" + "# Total</th> <th>"
                        + "Success Rate</th> </tr> </thead>" + " <tbody> <tr><td><b>" + suiteName
                        + "</b></td><td>" + total_unique_testcases + "</td><td>" + total_browser_combinations
                        + "</td>" + suite_pass + suite_fail + suite_automation_error + suite_skip + "<td>"
                        + (suite_totalPassedMethods + suite_totalFailedMethods + suite_totalSkippedMethods
                                + suite_totalAutomationErrors)
                        + "</td><td><font color=\"" + passPercentageColor + "\"><b>" + suite_passPercentage
                        + " %" + "</b></font></td></tr></tbody></table>");
    } else {
        f_out.println("<b><font color=\"" + titleColor + "\">Overall Execution Summary</font></b><br/><br/>");
        f_out.println("<table " + classParam + "  cellspacing=\"0\" cellpadding=\"0\" width=\"91%\">"
                + "<thead><tr><th>Test Suite Name</th><th>" + "# Unique TestCases</th><th>"
                + "# Combinations</th> <th>" + "# Passed</th> <th>" + "# Failed</th> <th>"
                + "# Warning</th> <th>" + "# Skipped</th><th>" + "# Total</th> <th>"
                + "Success Rate</th> </tr> </thead>" + " <tbody> <tr><td><b>" + suiteName + "</b></td><td>"
                + total_unique_testcases + "</td><td>" + total_browser_combinations + "</td><td>"
                + suite_totalPassedMethods + "</td><td>" + suite_totalFailedMethods + "</td><td>"
                + suite_totalAutomationErrors + "</td><td>" + suite_totalSkippedMethods + "</td><td>"
                + (suite_totalPassedMethods + suite_totalFailedMethods + suite_totalSkippedMethods
                        + suite_totalAutomationErrors)
                + "</td><td>" + suite_passPercentage + " %" + "</td></tr></tbody></table>");

    }
    f_out.flush();

    f_out.println("<br/>");
    f_out.println("<p><b>Modulewise Execution Summary</b></p>");
    f_out.println(dashboardResults);
    //        if(!emailable){
    //        f_out.println("<br/><h4>Legend:</h4>");
    //        f_out.print("<ul>");
    //        f_out.println("<li>T: Unique Testcase</li>");
    //        f_out.println("<li>B: Unique Browser Combination</li>");
    //        f_out.print("</ul>");
    //        }else{
    f_out.println("<br/><br/><br/><br/>");
    //        }
    f_out.flush();
}

From source file:com.ah.be.admin.adminOperateImpl.BeOperateHMCentOSImpl.java

private static BeFileInfo getFileInfo(File fInput) {
    if (null == fInput) {
        return null;
    }/*from  ww w.  j  av  a  2 s .  c  om*/

    SimpleDateFormat stmp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String strFileTime = stmp.format(new Date(fInput.lastModified()));

    double dFileSize = fInput.length();

    NumberFormat nbf = NumberFormat.getInstance();

    nbf.setMaximumFractionDigits(2);

    nbf.setMaximumFractionDigits(2);

    String strFileSize = nbf.format(dFileSize / 1024);

    BeFileInfo oFileInfo = new BeFileInfo();

    oFileInfo.setFileName(fInput.getName());

    oFileInfo.setFileSize(strFileSize);

    oFileInfo.setCreateTime(strFileTime);

    return oFileInfo;
}

From source file:com.ah.be.admin.adminOperateImpl.BeOperateHMCentOSImpl.java

public static List<BeCAFileInfo> getCAFileInfoList(String strDomainName) {
    try {/*from w  w w.jav  a2  s. c  o  m*/
        File oFileTmp = new File(BeAdminCentOSTools.AH_CERTIFICAT_PFEFIX + strDomainName
                + BeAdminCentOSTools.AH_CERTIFICATE_HOME);

        List<File> oFileInfoList = HmBeOsUtil.getFilesFromFolder(oFileTmp, false);

        List<BeCAFileInfo> oFileList = new ArrayList<BeCAFileInfo>();

        if (null == oFileInfoList) {
            return null;
        }

        for (File oTmp : oFileInfoList) {
            String strFileName = oTmp.getName();

            if (strFileName.endsWith(BeAdminCentOSTools.AH_NMS_HM_CSR_TAIL)
                    || strFileName.endsWith(BeAdminCentOSTools.AH_NMS_HM_PSD_TAIL)
                    || strFileName.endsWith(BeAdminCentOSTools.AH_NMS_HM_SRL_TAIL)
                    || strFileName.endsWith("conf")) {
                continue;
            }

            SimpleDateFormat stmp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String strFileTime = stmp.format(new Date(oTmp.lastModified()));

            double dFileSize = oTmp.length();

            NumberFormat nbf = NumberFormat.getInstance();

            nbf.setMaximumFractionDigits(2);

            nbf.setMaximumFractionDigits(2);

            String strFileSize = nbf.format(dFileSize / 1024);

            BeCAFileInfo oFileInfo = new BeCAFileInfo();

            oFileInfo.setFileName(strFileName);

            oFileInfo.setFileSize(strFileSize);

            oFileInfo.setCreateTime(strFileTime);

            oFileInfo.setDomainName(strDomainName);

            oFileList.add(oFileInfo);
        }

        return oFileList;
    } catch (Exception ex) {
        // add debug log
        DebugUtil.adminDebugWarn("BeOperateHMCentOSImpl.getCAFileInfoList() catch exception", ex);

        return null;
    }
}

From source file:com.naryx.tagfusion.cfm.tag.awt.cfCHART.java

private JFreeChart renderPieChart(cfSession _Session, cfCHARTInternalData chartData,
        List<cfCHARTSERIESData> series, String tipStyle, String drillDownUrl) throws cfmRunTimeException {
    // Retrieve the attributes of the chart
    String backgroundColorStr = getDynamic(_Session, "BACKGROUNDCOLOR").toString();
    Color backgroundColor = convertStringToColor(backgroundColorStr);

    String foregroundColorStr = getDynamic(_Session, "FOREGROUNDCOLOR").toString();
    Color foregroundColor = convertStringToColor(foregroundColorStr);

    String labelFormat = getDynamic(_Session, "LABELFORMAT").toString().toLowerCase();
    if (!labelFormat.equals("number") && !labelFormat.equals("currency") && !labelFormat.equals("percent"))
        throw newRunTimeException(
                "The labelFormat value '" + labelFormat + "' is not supported with pie charts");

    String pieSliceStyle = getDynamic(_Session, "PIESLICESTYLE").toString().toLowerCase();

    String title = null;/*from w w w .  jav  a  2s .co m*/
    if (containsAttribute("TITLE"))
        title = getDynamic(_Session, "TITLE").toString();

    Font font = getFont(_Session);

    cfCHARTSERIESData seriesData = series.get(0);

    boolean bShow3D = getDynamic(_Session, "SHOW3D").getBoolean();
    if (bShow3D && !seriesData.getType().equals("pie"))
        throw newRunTimeException("Only bar, line, horizontal bar and pie charts can be displayed in 3D");

    boolean bShowBorder = getDynamic(_Session, "SHOWBORDER").getBoolean();

    boolean bShowLegend = true; // default to true for pie charts
    if (containsAttribute("SHOWLEGEND"))
        bShowLegend = getDynamic(_Session, "SHOWLEGEND").getBoolean();

    // Get the plot for the chart and configure it
    PiePlot plot = getPiePlot(series, pieSliceStyle, bShow3D);
    setBackgroundImage(_Session, plot, chartData.getImageData());
    plot.setBackgroundPaint(backgroundColor);
    plot.setLabelBackgroundPaint(backgroundColor);
    plot.setLabelShadowPaint(backgroundColor);

    // Set the labels color
    plot.setLabelPaint(convertStringToColor(seriesData.getDataLabelColor()));

    // Set the labels font
    plot.setLabelFont(getFont(seriesData.getDataLabelFont(), seriesData.getDataLabelFontBold(),
            seriesData.getDataLabelFontItalic(), seriesData.getDataLabelFontSize()));

    String dataLabelStyle = seriesData.getDataLabelStyle();

    NumberFormat percentInstance = NumberFormat.getPercentInstance();
    percentInstance.setMaximumFractionDigits(3);

    NumberFormat numberFormat = null;
    if (labelFormat.equals("number")) {
        // Only display the value in the Label as a number
        numberFormat = NumberFormat.getInstance();
        if (dataLabelStyle.equals("none"))
            plot.setLabelGenerator(null);
        else if (dataLabelStyle.equals("value"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{1}"));
        else if (dataLabelStyle.equals("rowlabel"))
            plot.setLabelGenerator(
                    new org.jfree.chart.labels.StandardPieSectionLabelGenerator(seriesData.getSeriesLabel()));
        else if (dataLabelStyle.equals("columnlabel"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0}"));
        else if (dataLabelStyle.equals("pattern"))
            plot.setLabelGenerator(
                    new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0} {1} ({2} of {3})"));
        else {
            String pattern = java.text.MessageFormat.format(dataLabelStyle,
                    new Object[] { seriesData.getSeriesLabel(), "{0}", "{1}", "{2}", "{3}" });
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(pattern));
        }
    } else if (labelFormat.equals("currency")) {
        // Only display the value in the Label as a currency
        numberFormat = NumberFormat.getCurrencyInstance();
        if (dataLabelStyle.equals("none"))
            plot.setLabelGenerator(null);
        else if (dataLabelStyle.equals("value"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{1}",
                    NumberFormat.getCurrencyInstance(), percentInstance));
        else if (dataLabelStyle.equals("rowlabel"))
            plot.setLabelGenerator(
                    new org.jfree.chart.labels.StandardPieSectionLabelGenerator(seriesData.getSeriesLabel()));
        else if (dataLabelStyle.equals("columnlabel"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0}"));
        else if (dataLabelStyle.equals("pattern"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(
                    "{0} {1} ({2} of {3})", NumberFormat.getCurrencyInstance(), percentInstance));
        else {
            String pattern = java.text.MessageFormat.format(dataLabelStyle,
                    new Object[] { seriesData.getSeriesLabel(), "{0}", "{1}", "{2}", "{3}" });
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(pattern,
                    NumberFormat.getCurrencyInstance(), percentInstance));
        }
    } else if (labelFormat.equals("percent")) {
        // Only display the value in the Label as a percent
        numberFormat = percentInstance;
        if (dataLabelStyle.equals("none"))
            plot.setLabelGenerator(null);
        else if (dataLabelStyle.equals("value"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{1}",
                    percentInstance, percentInstance));
        else if (dataLabelStyle.equals("rowlabel"))
            plot.setLabelGenerator(
                    new org.jfree.chart.labels.StandardPieSectionLabelGenerator(seriesData.getSeriesLabel()));
        else if (dataLabelStyle.equals("columnlabel"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0}"));
        else if (dataLabelStyle.equals("pattern"))
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(
                    "{0} {1} ({2} of {3})", percentInstance, percentInstance));
        else {
            String pattern = java.text.MessageFormat.format(dataLabelStyle,
                    new Object[] { seriesData.getSeriesLabel(), "{0}", "{1}", "{2}", "{3}" });
            plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(pattern,
                    percentInstance, percentInstance));
        }
    }

    if (!tipStyle.equals("none")) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator(
                StandardPieToolTipGenerator.DEFAULT_SECTION_LABEL_FORMAT, numberFormat, numberFormat));
    }

    if (drillDownUrl != null) {
        plot.setURLGenerator(new com.newatlanta.bluedragon.PieURLGenerator(drillDownUrl, numberFormat));
    }

    // Get the chart and configure it
    JFreeChart chart = new JFreeChart(null, null, plot, false);
    chart.setBorderVisible(bShowBorder);
    chart.setBackgroundPaint(backgroundColor);
    setTitle(chart, title, font, foregroundColor, chartData.getTitles());
    setLegend(chart, bShowLegend, font, foregroundColor, backgroundColor, chartData.getLegendData());

    return chart;
}

From source file:de.innovationgate.wga.server.api.WGA.java

/**
 * Returns an OpenWGA number format/*  w  w w  . j  a v a 2  s .  c  o m*/
 * @param pattern The number format pattern
 * @param locale A locale to use for locale-dependent number parts. Specify null to let the current WebTML context choose the locale.
 * @throws WGException
 */
public NumberFormat getNumberFormat(String pattern, Locale locale) throws WGException {

    // Select language for language dependent number formats
    if (locale == null) {
        locale = chooseLocale(locale);
    }

    if (WGUtils.isEmpty(pattern)) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
        numberFormat.setMaximumFractionDigits(Integer.MAX_VALUE);
        numberFormat.setMaximumIntegerDigits(Integer.MAX_VALUE);
        return numberFormat;
    }

    // For default pattern
    if (pattern.toLowerCase().equals("decimal")) {
        return NumberFormat.getNumberInstance(locale);
    }

    // Custom pattern
    return new DecimalFormat(pattern, new DecimalFormatSymbols(locale));

}