Java Code Examples for java.text.DecimalFormat#getInstance()

The following examples show how to use java.text.DecimalFormat#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ShowTransactionsForm.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(String o1, String o2) {
    try {
        if (o1 == null) {
            if (o2 == null) {
                return 0;
            } else {
                return 1;
            }
        } else {
            if (o2 == null) {
                return -1;
            }
        }
        DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(LocaliserUtils.getLocale());
        formatter.setParseBigDecimal(true);

        // Convert spaces to non breakable space.
        o1 = o1.replaceAll(" ", "\u00A0");
        o2 = o2.replaceAll(" ", "\u00A0");

        BigDecimal parsedO1 = (BigDecimal) formatter.parse(o1);
        BigDecimal parsedO2 = (BigDecimal) formatter.parse(o2);
        return parsedO1.compareTo(parsedO2);
    } catch (NumberFormatException nfe) {
        return o1.compareTo(o2);
    } catch (ParseException e) {
        return o1.compareTo(o2);
    }
}
 
Example 2
Source File: ExecutionTimeFormatter.java    From quickperf with Apache License 2.0 5 votes vote down vote up
private DecimalFormat buildFormatWithSpaceGroupingSeparator() {
    DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.ENGLISH);
    DecimalFormatSymbols symbols = decimalFormat.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');
    decimalFormat.setDecimalFormatSymbols(symbols);
    return decimalFormat;
}
 
Example 3
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_formatDouble_roundingUnnecessaryArithmeticException() {
    DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
    decimalFormat.setMaximumFractionDigits(0);
    decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY);

    try {
        // when rounding is needed, but RoundingMode is set to RoundingMode.UNNECESSARY,
        // throw ArithmeticException
        decimalFormat.format(11.5, new StringBuffer(), new FieldPosition(0));
        fail("ArithmeticException expected");
    } catch (ArithmeticException e) {
        // expected
    }
}
 
Example 4
Source File: UITools.java    From sourcerabbit-gcode-sender with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the system decimal separator (',' or '.')
 *
 * @return
 */
public static String getSystemDecimalSeparator()
{
    // Get system Decimal separator
    DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance();
    DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
    return String.valueOf(symbols.getDecimalSeparator());
}
 
Example 5
Source File: UiUtils.java    From tindroid with Apache License 2.0 5 votes vote down vote up
static String bytesToHumanSize(long bytes) {
    if (bytes <= 0) {
        return "0 Bytes";
    }

    String[] sizes = new String[]{"Bytes", "KB", "MB", "GB", "TB"};
    int bucket = (63 - Long.numberOfLeadingZeros(bytes)) / 10;
    double count = bytes / Math.pow(1024, bucket);
    int roundTo = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;
    NumberFormat fmt = DecimalFormat.getInstance();
    fmt.setMaximumFractionDigits(roundTo);
    return fmt.format(count) + " " + sizes[bucket];
}
 
Example 6
Source File: XMLSecureParsingTest.java    From development with Apache License 2.0 5 votes vote down vote up
private void assertThatMaxEntitiesExceeded(SAXParseException exception) {
    DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
    df.applyPattern("##,###");
    // Java7u21 and before
    String maxEntitiesExceededMessage_le21 = df.format(64000);
    // after Java7u21
    String maxEntitiesExceededMessage_gt21 = "64000";

    assertThat(
            exception.getMessage(),
            either(containsString(maxEntitiesExceededMessage_le21)).or(
                    containsString(maxEntitiesExceededMessage_gt21)));
}
 
Example 7
Source File: MiscUtils.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates Decimal/Date format depending on data field type
 * 
 * @param formatType
 *            field type; for <i>DateDataField</i> there is created DateFormat , for all numeric fields there is
 *            created DecimalFormat, for other fields returns null
 * @param locale
 *            locale in Clover internat format
 * @param format
 *            format string
 * @return DecimalFormat, DateFormat or null
 */
public static Format createFormatter(char formatType, String locale, String format) {
	Locale loc = createLocale(locale);
	if (format != null || locale != null) {
		switch (formatType) {
		case DataFieldMetadata.DATE_FIELD:
		case DataFieldMetadata.DATETIME_FIELD:
			return new SimpleDateFormat(format, loc);
		case DataFieldMetadata.DECIMAL_FIELD:
		case DataFieldMetadata.NUMERIC_FIELD:
		case DataFieldMetadata.INTEGER_FIELD:
		case DataFieldMetadata.LONG_FIELD:
			return new DecimalFormat(format, new DecimalFormatSymbols(loc));
		}
	} else {
		switch (formatType) {
		case DataFieldMetadata.DATE_FIELD:
		case DataFieldMetadata.DATETIME_FIELD:
			return DateFormat.getDateInstance(DateFormat.DEFAULT, loc);
		case DataFieldMetadata.DECIMAL_FIELD:
		case DataFieldMetadata.NUMERIC_FIELD:
		case DataFieldMetadata.INTEGER_FIELD:
		case DataFieldMetadata.LONG_FIELD:
			return DecimalFormat.getInstance(loc);
		}
	}
	return null;
}
 
Example 8
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_setMaximumFractionDigitsAffectsRoundingMode() throws Exception {
    DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
    df.setMaximumFractionDigits(0);
    df.setRoundingMode(RoundingMode.HALF_UP);
    assertEquals("-0", df.format(-0.2));
    df.setMaximumFractionDigits(1);
    assertEquals("-0.2", df.format(-0.2));
}
 
Example 9
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_getRoundingMode() {
    // get the default RoundingMode of this DecimalFormat
    DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.US);

    // the default RoundingMode is HALF_EVEN
    assertEquals("Incorrect default RoundingMode",
            decimalFormat.getRoundingMode(), RoundingMode.HALF_EVEN);

    // set RoundingMode.HALF_DOWN of this DecimalFormat
    decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
    assertEquals("Returned incorrect RoundingMode",
            decimalFormat.getRoundingMode(), RoundingMode.HALF_DOWN);

}
 
Example 10
Source File: HtmlField.java    From jspoon with MIT License 5 votes vote down vote up
private BigDecimal getBigDecimal(String value) {
    try {
        DecimalFormat decimalFormat = (spec.getFormat() == null)
                ? (DecimalFormat) DecimalFormat.getInstance(spec.getLocale())
                        : new DecimalFormat(spec.getFormat());

        decimalFormat.setParseBigDecimal(true);
        return (BigDecimal) decimalFormat.parse(value);
    }
    catch (ParseException e) {
        throw new BigDecimalParseException(value, spec.getFormat(), spec.getLocale());
    }

}
 
Example 11
Source File: StackTreeTest.java    From mjprof with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static char getSeparator() {
           DecimalFormat format= (DecimalFormat) DecimalFormat.getInstance();
            DecimalFormatSymbols symbols=format.getDecimalFormatSymbols();
            char sep=symbols.getDecimalSeparator();
            return sep;
}
 
Example 12
Source File: ExcelConverterSimpleSpreadSheetCellDAOTest.java    From hadoopoffice with Apache License 2.0 4 votes vote down vote up
@Test
public void getSpreadSheetCellDAOfromSimpleDataType() throws ParseException {
 	// configure converter
		SimpleDateFormat dateFormat = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
		DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
		ExcelConverterSimpleSpreadSheetCellDAO converter = new ExcelConverterSimpleSpreadSheetCellDAO(dateFormat,decimalFormat);
		// test some rows
		Object[] rowA = new Object[13];
		rowA[0] = new Boolean(true);
		rowA[1] = new Byte((byte) 100);
		rowA[2] = new Short((short) 1000);
		rowA[3] = new Integer(32000);
		rowA[4] = new Long(65536L);
		rowA[5] = new Double(2.5);
		rowA[6] = new Float(3.5f);
		rowA[7] = new BigDecimal(1.5);
		rowA[8] = dateFormat.parse("1/13/2018");
		rowA[9] = new java.sql.Date(dateFormat.parse("1/13/2018").getTime());
		rowA[10] = new Timestamp(dateFormat.parse("1/13/2018").getTime());
		rowA[11] = "This is a test";
		rowA[12] = null;
		SpreadSheetCellDAO[] actual = converter.getSpreadSheetCellDAOfromSimpleDataType(rowA, "testsheet", 0);
		assertEquals("",actual[0].getFormattedValue(),"Formatted Value is empty");
		assertEquals("",actual[0].getComment(),"Comment is empty");
		assertEquals("true",actual[0].getFormula(),"Formula contains data type");
		assertEquals("A1",actual[0].getAddress(),"Address is correct");
		assertEquals("",actual[1].getFormattedValue(),"Formatted Value is empty");
		assertEquals("",actual[1].getComment(),"Comment is empty");
		assertEquals("100",actual[1].getFormula(),"Formula contains data type");
		assertEquals("B1",actual[1].getAddress(),"Address is correct");
		assertEquals("",actual[2].getFormattedValue(),"Formatted Value is empty");
		assertEquals("",actual[2].getComment(),"Comment is empty");
		assertEquals("1000",actual[2].getFormula(),"Formula contains data type");
		assertEquals("C1",actual[2].getAddress(),"Address is correct");
		assertEquals("",actual[3].getFormattedValue(),"Formatted Value is empty");
		assertEquals("",actual[3].getComment(),"Comment is empty");
		assertEquals("32000",actual[3].getFormula(),"Formula contains data type");
		assertEquals("D1",actual[3].getAddress(),"Address is correct");
		assertEquals("",actual[4].getFormattedValue(),"Formatted Value is empty");
		assertEquals("",actual[4].getComment(),"Comment is empty");
		assertEquals("65536",actual[4].getFormula(),"Formula contains data type");
		assertEquals("E1",actual[4].getAddress(),"Address is correct");
		assertEquals("",actual[5].getFormattedValue(),"Formatted Value is empty");
		assertEquals("",actual[5].getComment(),"Comment is empty");
		assertEquals("2.5",actual[5].getFormula(),"Formula contains data type");
		assertEquals("F1",actual[5].getAddress(),"Address is correct");
		assertEquals("",actual[6].getFormattedValue(),"Formatted Value is empty");
		assertEquals("",actual[6].getComment(),"Comment is empty");
		assertEquals("3.5",actual[6].getFormula(),"Formula contains data type");
		assertEquals("G1",actual[6].getAddress(),"Address is correct");
		assertEquals("",actual[7].getFormattedValue(),"Formatted Value is empty");
		assertEquals("",actual[7].getComment(),"Comment is empty");
		assertEquals("1.5",actual[7].getFormula(),"Formula contains data type");
		assertEquals("H1",actual[7].getAddress(),"Address is correct");
		assertEquals("1/13/18",actual[8].getFormattedValue(),"Formatted Value contains data type");
		assertEquals("",actual[8].getComment(),"Comment is empty");
		assertEquals("",actual[8].getFormula(),"Formula is empty");
		assertEquals("I1",actual[8].getAddress(),"Address is correct");
		assertEquals("1/13/18",actual[9].getFormattedValue(),"Formatted Value contains data type");
		assertEquals("",actual[9].getComment(),"Comment is empty");
		assertEquals("",actual[9].getFormula(),"Formula is empty");
		assertEquals("J1",actual[9].getAddress(),"Address is correct");
		assertEquals("2018-01-13 00:00:00.0",actual[10].getFormattedValue(),"Formatted Value contains data type");
		assertEquals("",actual[10].getComment(),"Comment is empty");
		assertEquals("",actual[10].getFormula(),"Formula is empty");
		assertEquals("K1",actual[10].getAddress(),"Address is correct");
		assertEquals("This is a test",actual[11].getFormattedValue(),"Formatted Value contains data");
		assertEquals("",actual[11].getComment(),"Comment is empty");
		assertEquals("",actual[11].getFormula(),"Formula is empty");
		assertEquals("L1",actual[11].getAddress(),"Address is correct");
		assertNull(actual[12],"Null values stay null");
}
 
Example 13
Source File: Contrast.java    From KEEL with GNU General Public License v3.0 4 votes vote down vote up
/**
    * <p>
    * In this method, the contrast estimation is computed
 *
 * @param results Array with the results of the methods
 * @param algorithmName Array with the name of the methods employed
 *
 * @return A string with the contents of the test in LaTeX format
    */
private static String computeBody(double[][] results, String algorithmName[]) {
	
	String output="";
	double CE [][][];
	double medians [][];
	double estimators [];
	
	DecimalFormat nf = (DecimalFormat) DecimalFormat.getInstance();
	nf.setMaximumFractionDigits(3);
	nf.setMinimumFractionDigits(0);

	DecimalFormatSymbols dfs = nf.getDecimalFormatSymbols();
	dfs.setDecimalSeparator('.');
	nf.setDecimalFormatSymbols(dfs);

	int numAlg= algorithmName.length;
	int nDatasets = results[0].length;
	
	/** CONTRAST ESTIMATION *******************************************************************************************/
    CE = new double[numAlg][numAlg][nDatasets];
    for (int i=0; i<numAlg; i++) {
    	for (int j=i+1; j<numAlg; j++) {
    		for (int k=0; k<nDatasets; k++) {
    			CE[i][j][k] = results[i][k] - results[j][k];
    		}
    	}
    }

    medians = new double[numAlg][numAlg];
    for (int i=0; i<numAlg; i++) {
    	for (int j=i+1; j<numAlg; j++) {
    		Arrays.sort(CE[i][j]);
    		if (CE[i][j].length % 2 == 1) {
    			medians[i][j] = CE[i][j][nDatasets/2];
    		} else {
    			medians[i][j] = (CE[i][j][nDatasets/2] + CE[i][j][(nDatasets/2)-1]) / 2.0;	    			
    		}
    	}
    }
    
    estimators = new double[numAlg];
    Arrays.fill(estimators, 0);
    for (int i=0; i<numAlg; i++) {
    	for (int j=0; j<numAlg; j++) {
	    		estimators[i] += medians[i][j] - medians[j][i];
    	}
    	estimators[i] /= numAlg;
    }
	
	
	
    /** PRINT THE CONTRAST ESTIMATION*/
	
    output +="\\begin{table}[!htp]\n\\centering\\scriptsize\n" + "\\begin{tabular}{\n";
       for (int i=0; i<numAlg+1; i++) {
       	output +="|r";
       }
       output +="|}\n\\hline\n" + " \n";
       for (int i=0; i<numAlg; i++) {
       	output +="&" + algorithmName[i];
       }        
       output +="\\\\\n\\hline\n";
       for (int i=0; i<numAlg; i++) {
       	output +=algorithmName[i];
       	for (int j=0; j<numAlg; j++) {
       		 output +="& "+nf.format(estimators[i] - estimators[j]);
       	}
       	output +="\\\\\n\\hline\n";
       }

       output +="\n" + "\\end{tabular}\n" + "\\caption{Contrast Estimation}\n\\end{table}\n";

	output += "\n\\end{landscape}\n\\end{document}";
       return output;
	
   }
 
Example 14
Source File: DoubleUtil.java    From android-kline with Apache License 2.0 4 votes vote down vote up
public static String formatDecimal(Double d) {
    NumberFormat instance = DecimalFormat.getInstance();
    instance.setMinimumFractionDigits(0);
    instance.setMaximumFractionDigits(8);
    return instance.format(d).replace(",", "");
}
 
Example 15
Source File: CSVImporter.java    From chronix.server with Apache License 2.0 4 votes vote down vote up
/***
 * /**
 * Reads csv data from the resources dir 'timeSeries' and imports them to Chronix.
 *
 * @param chronix the chronix client
 * @param solr    the solr connection
 * @throws URISyntaxException if the file could not converted to a uri
 * @throws IOException        if the time series could not added to solr
 */
public static void readAndImportCSV(ChronixClient<MetricTimeSeries, SolrClient, SolrQuery> chronix, HttpSolrClient solr) throws URISyntaxException, IOException {
    URL url = CSVImporter.class.getResource("/timeSeries");

    File tsDir = new File(url.toURI());
    File[] files = tsDir.listFiles();

    if (files == null) {
        LOGGER.warn("No files found. Returning");
        return;
    }
    Arrays.sort(files);

    DateTimeFormatter sdf = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss.SSS");

    for (File file : files) {
        LOGGER.info("Processing file {}", file);
        Map<Integer, MetricTimeSeries> documents = new HashMap<>();

        String[] attributes = file.getName().split("_");
        NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);

        AtomicInteger filePoints = new AtomicInteger(0);
        final AtomicBoolean onlyOnce = new AtomicBoolean(true);

        Files.lines(file.toPath()).forEach(line -> {
            String[] fields = line.split(";");

            //Its the first line of a csv file
            if ("Date".equals(fields[0])) {
                if (onlyOnce.get()) {

                    for (int j = 1; j < fields.length; j++) {
                        MetricTimeSeries ts = new MetricTimeSeries.Builder(fields[j], "metric")
                                .attribute("host", attributes[0])
                                .attribute("source", attributes[1])
                                .attribute("group", attributes[2])

                                //Add some generic fields an values
                                .attribute("myIntField", 5)
                                .attribute("myLongField", 8L)
                                .attribute("myDoubleField", 5.5D)
                                .attribute("myByteField", BYTES)
                                .attribute("myStringList", LIST_STRING_FIELD)
                                .attribute("myIntList", LIST_INT_FIELD)
                                .attribute("myLongList", LIST_LONG_FIELD)
                                .attribute("myDoubleList", LIST_DOUBLE_FIELD)
                                .attribute("dynamic_s", "dynamic_string")
                                .build();
                        documents.put(j, ts);

                    }
                }
            } else {
                //First field is the timestamp: 26.08.2013 00:00:17.361
                try {
                    long date = LocalDateTime.parse(fields[0], sdf).toInstant(ZoneOffset.UTC).toEpochMilli();

                    for (int j = 1; j < fields.length; j++) {

                        double value = nf.parse(fields[j]).doubleValue();

                        documents.get(j).add(date, value);
                    }
                    filePoints.addAndGet(fields.length);

                } catch (ParseException e) {
                    LOGGER.error("Could not parse date: " + fields[0]);
                }

            }
            onlyOnce.set(false);
        });
        chronix.add(documents.values(), solr);
    }
}
 
Example 16
Source File: Contrast.java    From KEEL with GNU General Public License v3.0 4 votes vote down vote up
/**
    * <p>
    * In this method, the contrast estimation is computed
 *
 * @param results Array with the results of the methods
 * @param algorithmName Array with the name of the methods employed
 *
 * @return A string with the contents of the test in LaTeX format
    */
private String computeBody(double[][] results, String algorithmName[]) {
	
	String output="";
	double CE [][][];
	double medians [][];
	double estimators [];
	
	DecimalFormat nf = (DecimalFormat) DecimalFormat.getInstance();
	nf.setMaximumFractionDigits(3);
	nf.setMinimumFractionDigits(0);

	DecimalFormatSymbols dfs = nf.getDecimalFormatSymbols();
	dfs.setDecimalSeparator('.');
	nf.setDecimalFormatSymbols(dfs);

	int numAlg= algorithmName.length;
	int nDatasets = results[0].length;
	
	/** CONTRAST ESTIMATION *******************************************************************************************/
    CE = new double[numAlg][numAlg][nDatasets];
    for (int i=0; i<numAlg; i++) {
    	for (int j=i+1; j<numAlg; j++) {
    		for (int k=0; k<nDatasets; k++) {
    			CE[i][j][k] = results[i][k] - results[j][k];
    		}
    	}
    }

    medians = new double[numAlg][numAlg];
    for (int i=0; i<numAlg; i++) {
    	for (int j=i+1; j<numAlg; j++) {
    		Arrays.sort(CE[i][j]);
    		if (CE[i][j].length % 2 == 1) {
    			medians[i][j] = CE[i][j][nDatasets/2];
    		} else {
    			medians[i][j] = (CE[i][j][nDatasets/2] + CE[i][j][(nDatasets/2)-1]) / 2.0;	    			
    		}
    	}
    }
    
    estimators = new double[numAlg];
    Arrays.fill(estimators, 0);
    for (int i=0; i<numAlg; i++) {
    	for (int j=0; j<numAlg; j++) {
	    		estimators[i] += medians[i][j] - medians[j][i];
    	}
    	estimators[i] /= numAlg;
    }
	
	
	
    /** PRINT THE CONTRAST ESTIMATION*/
	
    output +="\\begin{table}[!htp]\n\\centering\\scriptsize\n" + "\\begin{tabular}{\n";
       for (int i=0; i<numAlg+1; i++) {
       	output +="|r";
       }
       output +="|}\n\\hline\n" + " \n";
       for (int i=0; i<numAlg; i++) {
       	output +="&" + algorithmName[i];
       }        
       output +="\\\\\n\\hline\n";
       for (int i=0; i<numAlg; i++) {
       	output +=algorithmName[i];
       	for (int j=0; j<numAlg; j++) {
       		 output +="& "+nf.format(estimators[i] - estimators[j]);
       	}
       	output +="\\\\\n\\hline\n";
       }

       output +="\n" + "\\end{tabular}\n" + "\\caption{Contrast Estimation}\n\\end{table}\n";

	output += "\n\\end{landscape}\n\\end{document}";
       return output;
	
   }
 
Example 17
Source File: PrimitiveFloatConverter.java    From vraptor4 with Apache License 2.0 4 votes vote down vote up
protected NumberFormat getNumberFormat() {
	return DecimalFormat.getInstance(locale);
}
 
Example 18
Source File: FlinkSimpleExcelFileInputFormatTest.java    From hadoopoffice with Apache License 2.0 4 votes vote down vote up
@Test
public void readSimpleExcel2013() throws IOException, ParseException {
	ClassLoader classLoader = getClass().getClassLoader();
	String fileName = "testsimple.xlsx";
	String fileNameSpreadSheet = classLoader.getResource(fileName).getFile();
	Path file = new Path(fileNameSpreadSheet);
	FileInputSplit spreadSheetInputSplit = new FileInputSplit(0, file, 0, -1, null);
	HadoopOfficeReadConfiguration hocr = new HadoopOfficeReadConfiguration();
	SimpleDateFormat dateFormat = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
	DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
	hocr.setLocale(Locale.GERMAN);
	hocr.setReadHeader(true);
	hocr.setSimpleDateFormat(dateFormat);
	hocr.setSimpleDecimalFormat(decimalFormat);
	SimpleExcelFlinkFileInputFormat inputFormat = new SimpleExcelFlinkFileInputFormat(hocr, -1);
	inputFormat.open(spreadSheetInputSplit);
	assertFalse(inputFormat.reachedEnd(), "End not reached");
	Object[] reuse = new Object[0];
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	// check header
	String[] header = inputFormat.getHeader();
	assertEquals("decimalsc1", header[0], "Correct Header Column");
	assertEquals("booleancolumn", header[1], "Correct Header Column");
	assertEquals("datecolumn", header[2], "Correct Header Column");
	assertEquals("stringcolumn", header[3], "Correct Header Column");
	assertEquals("decimalp8sc3", header[4], "Correct Header Column");
	assertEquals("bytecolumn", header[5], "Correct Header Column");
	assertEquals("shortcolumn", header[6], "Correct Header Column");
	assertEquals("intcolumn", header[7], "Correct Header Column");
	assertEquals("longcolumn", header[8], "Correct Header Column");

	// check data
	Object[] simpleRow1 = inputFormat.nextRecord(reuse);

	assertEquals(new BigDecimal("1.00"), simpleRow1[0], "A2 = 1.00");
	assertTrue((Boolean) simpleRow1[1], "B2 = TRUE");
	assertEquals(sdf.parse("2017-01-01"), simpleRow1[2], "C2 = 2017-01-01");
	assertEquals("This is a text", simpleRow1[3], "D2 = This is a text");
	assertEquals(new BigDecimal("10.000"), simpleRow1[4], "E2 = 10.000");
	assertEquals((byte) 3, simpleRow1[5], "F2 = 3");
	assertEquals((short) 3, simpleRow1[6], "G2 = 3");
	assertEquals((int) 100, simpleRow1[7], "H2 = 100");
	assertEquals(65335L, simpleRow1[8], "I2 = 65335");
	Object[] simpleRow2 = inputFormat.nextRecord(reuse);

	assertEquals(new BigDecimal("1.50"), simpleRow2[0], "A3 = 1.50");
	assertFalse((Boolean) simpleRow2[1], "B3 = FALSE");
	assertEquals(sdf.parse("2017-02-28"), simpleRow2[2], "C3 = 2017-02-28");
	assertEquals("Another String", simpleRow2[3], "D3 = Another String");
	assertEquals(new BigDecimal("2.334"), simpleRow2[4], "E3 = 2.334");
	assertEquals((byte) 5, simpleRow2[5], "F3 = 5");
	assertEquals((short) 4, simpleRow2[6], "G3 = 4");
	assertEquals((int) 65335, simpleRow2[7], "H3 = 65335");
	assertEquals(1L, simpleRow2[8], "I3 = 1");
	Object[] simpleRow3 = inputFormat.nextRecord(reuse);

	assertEquals(new BigDecimal("3.40"), simpleRow3[0], "A4 = 3.40");
	assertFalse((Boolean) simpleRow3[1], "B4 = FALSE");
	assertEquals(sdf.parse("2000-02-29"), simpleRow3[2], "C4 = 2000-02-29");
	assertEquals("10", simpleRow3[3], "D4 = 10");
	assertEquals(new BigDecimal("4.500"), simpleRow3[4], "E4 = 4.500");
	assertEquals((byte) -100, simpleRow3[5], "F4 = -100");
	assertEquals((short) 5, simpleRow3[6], "G4 = 5");
	assertEquals((int) 1, simpleRow3[7], "H4 = 1");
	assertEquals(250L, simpleRow3[8], "I4 = 250");
	Object[] simpleRow4 = inputFormat.nextRecord(reuse);
	assertEquals(new BigDecimal("5.50"), simpleRow4[0], "A5 = 5.50");
	assertFalse((Boolean) simpleRow4[1], "B5 = FALSE");
	assertEquals(sdf.parse("2017-03-01"), simpleRow4[2], "C5 = 2017-03-01");
	assertEquals("test3", simpleRow4[3], "D5 = test3");
	assertEquals(new BigDecimal("11.000"), simpleRow4[4], "E5 = 11.000");
	assertEquals((byte) 2, simpleRow4[5], "F5 = 2");
	assertEquals((short) 250, simpleRow4[6], "G5 = 250");
	assertEquals((int) 250, simpleRow4[7], "H5 = 250");
	assertEquals(10L, simpleRow4[8], "I5 = 10");
	Object[] simpleRow5 = inputFormat.nextRecord(reuse);
	assertNull(simpleRow5[0], "A6 = null");
	assertNull(simpleRow5[1], "B6 = null");
	assertNull(simpleRow5[2], "C6 = null");
	assertEquals("test4", simpleRow5[3], "D6 = test4");
	assertEquals(new BigDecimal("100.000"), simpleRow5[4], "E6 = 100.000");
	assertEquals((byte) 3, simpleRow5[5], "F6 = 3");
	assertEquals((short) 3, simpleRow5[6], "G6 = 3");
	assertEquals((int) 5, simpleRow5[7], "H6 = 5");
	assertEquals(3147483647L, simpleRow5[8], "I6 = 3147483647");
	Object[] simpleRow6 = inputFormat.nextRecord(reuse);
	assertEquals(new BigDecimal("3.40"), simpleRow6[0], "A7 = 3.40");
	assertTrue((Boolean) simpleRow6[1], "B7 = TRUE");
	assertEquals(sdf.parse("2017-03-01"), simpleRow6[2], "C7 = 2017-03-01");
	assertEquals("test5", simpleRow6[3], "D7 = test5");
	assertEquals(new BigDecimal("10000.500"), simpleRow6[4], "E6 = 10000.500");
	assertEquals((byte) 120, simpleRow6[5], "F7 = 120");
	assertEquals((short) 100, simpleRow6[6], "G7 = 100");
	assertEquals((int) 10000, simpleRow6[7], "H7 = 10000");
	assertEquals(10L, simpleRow6[8], "I6 = 10");
	inputFormat.nextRecord(reuse);
	assertTrue(inputFormat.reachedEnd(), "End reached");
}
 
Example 19
Source File: ScriptHelper.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public String formatNumber(final Number numberValue, final String formatPattern, final String language) {
	final Locale locale = Locale.forLanguageTag(language);
	final DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(locale);
	format.applyPattern(formatPattern);
	return format.format(numberValue);
}
 
Example 20
Source File: MessageListener.java    From development with Apache License 2.0 4 votes vote down vote up
public void beforePhase(PhaseEvent event) {
    FacesContext fc = event.getFacesContext();
    ServletRequest request = (ServletRequest) fc.getExternalContext()
            .getRequest();
    UIViewRoot root = fc.getViewRoot();
    resetColor(root.getChildren());
    List<String> additionalErrorElements = new ArrayList<String>();
    Set<String> sectionsToExpand = new HashSet<String>();
    Iterator<String> clientIds = fc.getClientIdsWithMessages();
    while (clientIds.hasNext()) {
        String clientId = clientIds.next();
        if (canIgnoreClientId(clientId)) {
            // skip, since it is not associated with a specific field
            continue;
        }
        if (request.getAttribute(ATTRIBUTE_FIRST_ERROR_ELEMENT) == null) {
            // set focus to first component only
            request.setAttribute(ATTRIBUTE_FIRST_ERROR_ELEMENT, clientId);
        }
        UIComponent uiComponent = root.findComponent(clientId);
        String sectionId = null;
        if (uiComponent != null) {
            sectionId = getSectionId(uiComponent);
            uiComponent.getAttributes().put(ATTRIBUTE_STYLE, STYLE_ERROR);
            Object object = uiComponent.getAttributes().get("connectedTo");
            if (object != null) {
                UIComponent connected = root.findComponent(object
                        .toString());
                if (connected != null) {
                    connected.getAttributes().put(ATTRIBUTE_STYLE,
                            STYLE_ERROR);
                }
            }
            if (uiComponent instanceof UISelectBoolean) {
                uiComponent.getAttributes().put(ATTRIBUTE_STYLE,
                        STYLE_CHECKBOX_ERROR);
            } else if (uiComponent instanceof UICalendar) {
                additionalErrorElements.add(clientId + "InputDate");
            } else {
                uiComponent.getAttributes().put(ATTRIBUTE_STYLE,
                        STYLE_ERROR);
            }
        } else {
            sectionId = getTableSectionId(clientId, root);
            // if the element is part of a data table we must change the
            // style from javascript
            additionalErrorElements.add(clientId);
        }
        if (sectionId != null) {
            sectionsToExpand.add(sectionId);
        }
    }
    request.setAttribute(ATTRIBUTE_ADDITIONAL_ERROR_ELEMENTS,
            additionalErrorElements);
    if (!sectionsToExpand.isEmpty()) {
        request.setAttribute(OpenStateBean.SECTIONS_TO_EXPAND,
                sectionsToExpand);
    }
    if (request.getAttribute(ATTRIBUTE_FIRST_ERROR_ELEMENT) != null) {
        JSFUtils.addMessage(null, FacesMessage.SEVERITY_ERROR,
                BaseBean.ERROR_TEXT_FIELDS, null);
    }

    if (request.getAttribute(FILEUPLOAD_EXCEPTION) != null) {
        // The upload of one or a bunch of files failed because either one
        // of the files exceeds the value of "uploadMaxFileSize" or the size
        // of all files exceeds the value of "uploadMaxSize". If
        // "uploadMaxSize" if not set => uploadMaxSize = uploadMaxFileSize

        Integer maxSize = (Integer) request
                .getAttribute(FILEUPLOAD_MAX_SIZE);

        if (maxSize == null) {
            // The attribute indicating the maximum allowed size was not set
            JSFUtils.addMessage(null, FacesMessage.SEVERITY_ERROR,
                    BaseBean.ERROR_UPLOAD_SIZE_LIMIT_EXCEEDED, null);
        } else {
            // Calculate a more handy megabyte value and bring it to a nice
            // format
            Locale viewLocale = JSFUtils.getViewLocale();
            DecimalFormat df = (DecimalFormat) DecimalFormat
                    .getInstance(viewLocale);
            df.applyPattern("#0.00");

            double maxValueMb = maxSize.intValue() / (1024.0 * 1024.0);

            JSFUtils.addMessage(null, FacesMessage.SEVERITY_ERROR,
                    BaseBean.ERROR_UPLOAD_SIZE_LIMIT_EXCEEDED_KNOWNMAX,
                    new Object[] { df.format(maxValueMb) });
        }
    }
}