Example usage for java.text DecimalFormatSymbols setGroupingSeparator

List of usage examples for java.text DecimalFormatSymbols setGroupingSeparator

Introduction

In this page you can find the example usage for java.text DecimalFormatSymbols setGroupingSeparator.

Prototype

public void setGroupingSeparator(char groupingSeparator) 

Source Link

Document

Sets the character used for thousands separator.

Usage

From source file:org.openbravo.erpCommon.utility.Utility.java

/**
 * Returns a DecimalFormat for the given formatting type contained in the Format.xml file
 *//*from  w ww .  jav a2s.co m*/
public static DecimalFormat getFormat(VariablesSecureApp vars, String typeName) {
    String format = vars.getSessionValue("#FormatOutput|" + typeName);
    String decimal = vars.getSessionValue("#DecimalSeparator|" + typeName);
    String group = vars.getSessionValue("#GroupSeparator|" + typeName);
    DecimalFormat numberFormatDecimal = null;
    if (format != null && !format.equals("") && decimal != null && !decimal.equals("") && group != null
            && !group.equals("")) {
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setDecimalSeparator(decimal.charAt(0));
        dfs.setGroupingSeparator(group.charAt(0));
        numberFormatDecimal = new DecimalFormat(format, dfs);
    }
    return numberFormatDecimal;
}

From source file:it.greenvulcano.gvesb.datahandling.dbo.DBOCallSP.java

/**
 * @see org.xml.sax.ContentHandler#endElement(java.lang.String,
 *      java.lang.String, java.lang.String)
 *//* www  .  ja v  a2 s . c  o m*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    if (ROW_NAME.equals(localName)) {
        if (!currCriticalError) {
            executeStatement();
        } else {
            rowDisc++;
            // aggiunta DiscardCause al dhr...
            String msg = currentXSLMessage;

            dhr.addDiscardCause(new DiscardCause(rowCounter, msg));

            resultMessage.append("Data error on row ").append(rowCounter).append(": ").append(msg);
            resultMessage.append("SQL Statement Informations:\n").append(sqlStatementInfo);
            resultMessage.append("Record parameters:\n").append(dumpCurrentRowFields());
            resultStatus = STATUS_PARTIAL;
        }
    } else if (COL_NAME.equals(localName)) {
        CallableStatement cs = (CallableStatement) sqlStatementInfo.getStatement();
        try {
            if (!outOnly) {
                colDataExpecting = false;
                String text = textBuffer.toString();
                if ((currentUUID != null) && (currentUUID.trim().length() > 0) && (text.length() == 0)) {
                    text = uuids.get(currentUUID);
                    if (text == null) {
                        text = currentUUID;
                    }
                }
                if (TIMESTAMP_TYPE.equals(currType) || DATE_TYPE.equals(currType)
                        || TIME_TYPE.equals(currType)) {
                    if (text.equals("")) {
                        if (TIMESTAMP_TYPE.equals(currType))
                            setNull(cs, Types.TIMESTAMP);
                        else if (DATE_TYPE.equals(currType))
                            setNull(cs, Types.DATE);
                        else
                            setNull(cs, Types.TIME);
                        currentRowFields.add(null);
                    } else {
                        dateFormatter.applyPattern(currDateFormat);
                        Date formattedDate = dateFormatter.parse(text);
                        if (TIMESTAMP_TYPE.equals(currType)) {
                            Timestamp ts = new Timestamp(formattedDate.getTime());
                            setTimestamp(cs, ts);
                            currentRowFields.add(ts);
                        } else if (DATE_TYPE.equals(currType)) {
                            java.sql.Date d = new java.sql.Date(formattedDate.getTime());
                            setDate(cs, d);
                            currentRowFields.add(d);
                        } else {
                            java.sql.Time t = new java.sql.Time(formattedDate.getTime());
                            setTime(cs, t);
                            currentRowFields.add(t);
                        }
                    }
                } else if (INTEGER_TYPE.equals(currType) || SMALLINT_TYPE.equals(currType)
                        || BIGINT_TYPE.equals(currType)) {
                    if (text.equals("")) {
                        if (INTEGER_TYPE.equals(currType))
                            setNull(cs, Types.INTEGER);
                        else if (SMALLINT_TYPE.equals(currType))
                            setNull(cs, Types.SMALLINT);
                        else
                            setNull(cs, Types.BIGINT);
                        currentRowFields.add(null);
                    } else {
                        if (INTEGER_TYPE.equals(currType))
                            setInt(cs, Integer.parseInt(text, 10));
                        else if (SMALLINT_TYPE.equals(currType))
                            setShort(cs, Short.parseShort(text, 10));
                        else
                            setLong(cs, Long.parseLong(text, 10));
                        currentRowFields.add(text);
                    }
                } else if (FLOAT_TYPE.equals(currType) || DOUBLE_TYPE.equals(currType)
                        || DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) {
                    if (text.equals("")) {
                        if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType))
                            setNull(cs, Types.NUMERIC);
                        else if (FLOAT_TYPE.equals(currType))
                            setNull(cs, Types.FLOAT);
                        else
                            setNull(cs, Types.DOUBLE);
                        currentRowFields.add(null);
                    } else {
                        DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols();
                        dfs.setDecimalSeparator(currDecSeparator.charAt(0));
                        dfs.setGroupingSeparator(currGroupSeparator.charAt(0));
                        numberFormatter.setDecimalFormatSymbols(dfs);
                        numberFormatter.applyPattern(currNumberFormat);
                        boolean isBigDecimal = numberFormatter.isParseBigDecimal();
                        try {
                            numberFormatter.setParseBigDecimal(true);
                            BigDecimal formattedNumber = (BigDecimal) numberFormatter.parse(text);
                            if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) {
                                setBigDecimal(cs, formattedNumber);
                                currentRowFields.add(formattedNumber);
                            } else if (FLOAT_TYPE.equals(currType)) {
                                setFloat(cs, formattedNumber.floatValue());
                                currentRowFields.add(formattedNumber.floatValue());
                            } else {
                                setDouble(cs, formattedNumber.doubleValue());
                                currentRowFields.add(formattedNumber.doubleValue());
                            }
                        } finally {
                            numberFormatter.setParseBigDecimal(isBigDecimal);
                        }
                    }
                } else if (LONG_STRING_TYPE.equals(currType) || LONG_NSTRING_TYPE.equals(currType)) {
                    if (text.equals("")) {
                        if (LONG_STRING_TYPE.equals(currType))
                            setNull(cs, Types.CLOB);
                        else
                            setNull(cs, Types.NCLOB);
                        currentRowFields.add(null);
                    } else {
                        if (LONG_STRING_TYPE.equals(currType)) {
                            setCharacterStream(cs, new StringReader(text));
                            currentRowFields.add(text);
                        } else {
                            setNCharacterStream(cs, new StringReader(text));
                            currentRowFields.add(text);
                        }
                    }
                } else if (BASE64_TYPE.equals(currType)) {
                    if (text.equals("")) {
                        setNull(cs, Types.BLOB);
                        currentRowFields.add(null);
                    } else {
                        byte[] data = text.getBytes();
                        data = Base64.getDecoder().decode(data);
                        ByteArrayInputStream bais = new ByteArrayInputStream(data);
                        setBinaryStream(cs, bais, data.length);
                        currentRowFields.add(text);
                    }
                } else if (BINARY_TYPE.equals(currType)) {
                    if (text.equals("")) {
                        setNull(cs, Types.BLOB);
                        currentRowFields.add(null);
                    } else {
                        byte[] data = text.getBytes();
                        ByteArrayInputStream bais = new ByteArrayInputStream(data);
                        setBinaryStream(cs, bais, data.length);
                        currentRowFields.add(text);
                    }
                } else if (BOOLEAN_TYPE.equals(currType)) {
                    if (text.equals("")) {
                        setNull(cs, Types.BOOLEAN);
                        currentRowFields.add(null);
                    } else {
                        setBoolean(cs, TextUtils.parseBoolean(text));
                        currentRowFields.add(text);
                    }
                } else if (XML_TYPE.equals(currType)) {
                    if (text.equals("")) {
                        setNull(cs, Types.SQLXML);
                        currentRowFields.add(null);
                    } else {
                        SQLXML xml = cs.getConnection().createSQLXML();
                        xml.setString(text);
                        setSQLXML(cs, xml);
                        currentRowFields.add(text);
                    }
                } else if (NSTRING_TYPE.equals(currType)) {
                    if (text.equals("")) {
                        setNull(cs, Types.NVARCHAR);
                        currentRowFields.add(null);
                    } else {
                        setNString(cs, text);
                        currentRowFields.add(text);
                    }
                } else {
                    if (text.equals("")) {
                        setNull(cs, Types.VARCHAR);
                        currentRowFields.add(null);
                    } else {
                        setString(cs, text);
                        currentRowFields.add(text);
                    }
                }
            } else {
                currentRowFields.add(currentUUID);
            }
        } catch (ParseException exc) {
            throw new SAXException(exc);
        } catch (SQLException exc) {
            OracleExceptionHandler.handleSQLException(exc);
            throw new SAXException(exc);
        }
    }
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public get_geocaches_ret get_geocaches_v2(Coordinate[] location, int count_p, int max_p, int rec_depth,
        Handler h, int zoom_level) {
    this.main_aagtl.set_bar_slow(h, "get geocaches", "downloading ...", count_p, max_p, true);

    if (zoom_level > 16) {
        zoom_level = 16;//from w w w.j av  a  2s.c  om
    } else if (zoom_level < 6) {
        zoom_level = 6;
    }

    get_geocaches_ret rr2 = new get_geocaches_ret();
    Coordinate c1 = location[0];
    Coordinate c2 = location[1];

    String zoomlevel_ = "" + zoom_level;

    // use "." as comma seperator!!
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator(',');
    DecimalFormat format_lat_lon = new DecimalFormat("#.#####", otherSymbols);
    // use "." as comma seperator!!

    // http://www.geocaching.com/map/default.aspx?ll=48.22607,16.36997
    // GET http://www.geocaching.com/map/default.aspx?ll=48.22607,16.36997 HTTP/1.1
    String lat_str = format_lat_lon.format((c1.lat + c2.lat) / 2);
    String lon_str = format_lat_lon.format((c1.lon + c2.lon) / 2);
    //String url = "http://www.geocaching.com/map/?ll=" + lat_str + "," + lon_str + "&z=" + zoomlevel_;
    String url = "http://www.geocaching.com/map/default.aspx?ll=" + lat_str + "," + lon_str;
    System.out.println("url=" + url);

    List<NameValuePair> values_list = new ArrayList<NameValuePair>();
    //*values_list.add(new BasicNameValuePair("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"));
    //*values_list.add(new BasicNameValuePair("Pragma", "no-cache"));
    // values_list.add(new BasicNameValuePair("Referer","http://www.geocaching.com/map/default.aspx"));
    //ByteArrayOutputStream bs = new ByteArrayOutputStream();
    String the_page = get_reader_stream(url, values_list, null, true);
    //String the_page = getUrlData(url);

    //System.out.println(the_page);

    // get values --------------------------
    // get values --------------------------
    // Groundspeak.Map.UserSession('xxxx', 
    Pattern p = Pattern.compile("Groundspeak\\.Map\\.UserSession.'([^']*)'");
    Matcher m = p.matcher(the_page);
    Boolean has_found = true;
    String kk_ = "";
    try {
        has_found = m.find();
        kk_ = m.group(1);
    } catch (Exception e3) {
        e3.printStackTrace();
    }
    System.out.println("kk=" + kk_);

    // sessionToken:'
    p = Pattern.compile("sessionToken:'([^']*)'");
    m = p.matcher(the_page);
    has_found = m.find();
    String sess_token_ = m.group(1);

    System.out.println("sess_token=" + sess_token_);
    // get values --------------------------
    // get values --------------------------

    java.util.Date date = new java.util.Date();
    System.out.println("ts=" + date.getTime());

    String timestamp_ = "" + date.getTime(); // ..seconds..

    // lat, lon -> tile
    Coordinate coord = new Coordinate((c1.lat + c2.lat) / 2, (c1.lon + c2.lon) / 2);
    double[] tile = main_aagtl.rose.deg2num_give_zoom(coord, zoom_level);
    String xtile_num = "" + ((int) tile[0]);
    String ytile_num = "" + ((int) tile[1]);
    // lat, lon -> tile

    // X-Requested-With: XMLHttpRequest
    //Referer: http://www.geocaching.com/map/default.aspx?ll=48.22607,16.36997
    values_list = new ArrayList<NameValuePair>();
    //values_list.add(new BasicNameValuePair("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"));
    //values_list.add(new BasicNameValuePair("Pragma", "no-cache"));
    //values_list.add(new BasicNameValuePair("X-Requested-With", "XMLHttpRequest"));
    //values_list.add(new BasicNameValuePair("Referer", "http://www.geocaching.com/map/default.aspx?ll=" + lat_str + "," + lon_str));

    String url2 = "http://www.geocaching.com/map/map.info?x=" + xtile_num + "&y=" + ytile_num + "&z="
            + zoomlevel_ + "&k=" + kk_ + "&st=" + sess_token_ + "&ep=1&_=" + timestamp_;

    System.out.println("url2=" + url2);

    the_page = get_reader_stream(url2, values_list, null, true);
    // the_page = getUrlData(url2);
    try {
        System.out.println(the_page);
    } catch (Exception e3) {

    }

    // we need to add one, in any case!
    count_p = count_p + 1;
    get_geocaches_ret r = new get_geocaches_ret();
    r.count_p = count_p;
    r.points = null;
    return r;
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public get_geocaches_ret get_geocaches_v3(Coordinate[] location, int count_p, int max_p, int rec_depth,
        Handler h, int zoom_level) {
    this.main_aagtl.set_bar_slow(h, "get geocaches", "downloading ...", count_p, max_p, true);

    Coordinate c1 = location[0];// w  w  w. j a  v a 2 s .c o m
    Coordinate c2 = location[1];

    Coordinate center = new Coordinate((c1.lat + c2.lat) / 2, (c1.lon + c2.lon) / 2);
    double dist = (center.distance_to(c1) / 1000) / 2;
    //System.out.println("distance is " + dist + " meters");

    if (dist > 100) {
        // dist too large
        count_p = count_p + 1;
        get_geocaches_ret r = new get_geocaches_ret();
        r.count_p = count_p;
        r.points = null;
        return r;
    }

    // use "." as comma seperator!!
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator(',');
    DecimalFormat format_lat_lon = new DecimalFormat("#.#####", otherSymbols);
    // use "." as comma seperator!!

    String lat_str = format_lat_lon.format(center.lat);
    String lon_str = format_lat_lon.format(center.lon);
    String dist_str = format_lat_lon.format(dist);
    String url = "http://www.geocaching.com/seek/nearest.aspx?lat=" + lat_str + "&lng=" + lon_str + "&dist="
            + dist_str;
    //System.out.println("url=" + url);

    List<NameValuePair> values_list = new ArrayList<NameValuePair>();
    //values_list.add(new BasicNameValuePair("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"));
    //values_list.add(new BasicNameValuePair("Pragma", "no-cache"));
    // ByteArrayOutputStream bs = new ByteArrayOutputStream();
    String the_page = get_reader_stream(url, values_list, null, true);

    get_geocaches_ret r2 = new get_geocaches_ret();
    r2.count_p = count_p;
    r2.points = null;

    Boolean cont = true;
    Source source = null;

    List<GeocacheCoordinate> gc_list = new ArrayList<GeocacheCoordinate>();
    count_p = 0;
    max_p = 0;
    while (cont) {
        source = new Source(the_page);
        List<? extends Segment> segments = (source
                .getFirstElement("id", "ctl00_ContentBody_ResultsPanel", false).getContent()
                .getFirstElement("class", "PageBuilderWidget", false).getContent().getAllElements("b"));
        if (segments.size() < 3) {
            // no results
            return r2;
        }

        int count = Integer.parseInt(segments.get(0).getTextExtractor().toString());
        int page_current = Integer.parseInt(segments.get(1).getTextExtractor().toString());
        int page_max = Integer.parseInt(segments.get(2).getTextExtractor().toString());
        //System.out.println("count=" + count + " cur=" + page_current + " max=" + page_max);
        max_p = count;

        String guid = "";
        String gccode = "";
        Boolean disabled = false;
        List<? extends Segment> segments2 = (source.getFirstElement("class", "SearchResultsTable Table", false)
                .getContent().getAllElements(HTMLElementName.TR));
        // displaySegments(segments2);
        try {
            for (Segment s_ : segments2) {
                guid = "";
                disabled = false;
                gccode = null;
                try {
                    List<? extends Segment> segments3 = s_.getAllElements("class", "Merge", false);
                    // displaySegments(segments2);
                    guid = segments3.get(0).getFirstElement(HTMLElementName.A).getAttributeValue("href");
                    guid = guid.split("guid=", 3)[1];
                    //System.out.println("guid=:" + guid);

                    try {
                        // <a href="/seek/cache_details.aspx?guid=d9dbf39a-e2e6-4640-b951-d1d6307b16bd" class="lnk  Strike"><span>Cineasten sehen mehr</span></a>
                        if (segments3.get(1).getFirstElement(HTMLElementName.A).getAttributeValue("class")
                                .equalsIgnoreCase("lnk  Strike")) {
                            // System.out.println("disabled=:" + disabled);
                            disabled = true;
                        }
                    } catch (Exception e3) {
                    }

                    gccode = segments3.get(1).getFirstElement("class", "small", false).getTextExtractor()
                            .toString();
                    gccode = gccode.split("\\|")[1].trim();
                    //System.out.println("gccode=:" + gccode);
                } catch (Exception e2) {
                    e2.printStackTrace();
                }

                if (gccode != null) {
                    GeocacheCoordinate c__ = null;
                    c__ = new GeocacheCoordinate(0, 0, gccode);
                    if (disabled) {
                        c__.status = GeocacheCoordinate.STATUS_DISABLED;
                    }

                    String url2 = "http://www.geocaching.com/seek/cdpf.aspx?guid=" + guid;
                    //System.out.println("url=" + url);

                    values_list = new ArrayList<NameValuePair>();
                    //values_list.add(new BasicNameValuePair("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"));
                    //values_list.add(new BasicNameValuePair("Pragma", "no-cache"));
                    // bs = new ByteArrayOutputStream();
                    String the_page2 = get_reader_stream(url2, values_list, null, true);
                    c__ = CacheDownloader.__parse_cache_page_print(the_page2, c__);
                    if (c__ != null) {
                        gc_list.add(c__);
                        count_p = count_p + 1;
                        this.main_aagtl.set_bar_slow(h, "get geocaches", c__.title, count_p, max_p, true);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        cont = false;

        // ----------- check for paging ----------------
        // ----------- and run through pages -----------
        //
        if (page_current < page_max) {
            FormFields formFields = source.getFormFields();
            String vs1 = null;
            try {
                vs1 = formFields.getValues("__VIEWSTATE1").get(0);
            } catch (Exception e) {

            }
            String vs = null;
            try {
                vs = formFields.getValues("__VIEWSTATE").get(0);
            } catch (Exception e) {

            }

            //System.out.println("vs=" + vs);
            //System.out.println("vs1=" + vs1);

            List<NameValuePair> values_list2 = new ArrayList<NameValuePair>();
            values_list2.add(new BasicNameValuePair("__EVENTTARGET", "ctl00$ContentBody$pgrTop$ctl08"));
            values_list2.add(new BasicNameValuePair("__VIEWSTATEFIELDCOUNT", "2"));
            values_list2.add(new BasicNameValuePair("__VIEWSTATE", vs));
            values_list2.add(new BasicNameValuePair("__VIEWSTATE1", vs1));
            // ByteArrayOutputStream bs = new ByteArrayOutputStream();
            the_page = get_reader_stream(url, values_list2, null, true);
            cont = true;
        }
        // ----------- check for paging ----------------
        // ----------- and run through pages -----------
    }

    int jk;
    r2.count_p = gc_list.size();
    r2.points = new GeocacheCoordinate[gc_list.size()];

    for (jk = 0; jk < gc_list.size(); jk++) {
        r2.points[jk] = gc_list.get(jk);
    }
    // gc_list.clear();

    return r2;
}

From source file:org.openbravo.erpCommon.utility.Utility.java

/**
 * Gets the number format for the organization country.
 * /*from  w  ww .j  a v a  2  s.  c  o  m*/
 * @param orgid
 *          ID of the organization.
 * @param defaultDecimalFormat
 *          Default decimal format.
 * 
 * @return DecimalFormat for the number representation defined for the country.
 */
public static DecimalFormat getCountryNumberFormat(String orgid, DecimalFormat defaultDecimalFormat) {
    try {
        OBContext.setAdminMode(true);
        Country country = getCountryFromOrgId(orgid);
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        if (country.getDecimalseparator() != null)
            symbols.setDecimalSeparator(country.getDecimalseparator().equals("C") ? ',' : '.');
        if (country.getGroupingseparator() != null)
            symbols.setGroupingSeparator(country.getGroupingseparator().equals("C") ? ',' : '.');
        if (country.getNumericmask() != null) {
            DecimalFormat numberFormat = new DecimalFormat(country.getNumericmask());
            numberFormat.setDecimalFormatSymbols(symbols);
            return numberFormat;
        } else {
            if (country.getDecimalseparator() != null || country.getNumericmask() != null) {
                defaultDecimalFormat.setDecimalFormatSymbols(symbols);
            }
            return defaultDecimalFormat;
        }
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.orcid.core.manager.impl.OrcidProfileManagerImpl.java

/**
 * Replace the funding amount string into the desired format
 * /*from w ww .  j a v a 2 s  . co  m*/
 * @param updatedOrcidProfile
 *            The profile containing the new funding
 * */
private void setFundingAmountsWithTheCorrectFormat(OrcidProfile updatedOrcidProfile)
        throws IllegalArgumentException {
    FundingList fundings = updatedOrcidProfile.retrieveFundings();

    for (Funding funding : fundings.getFundings()) {
        // If the amount is not empty, update it
        if (funding.getAmount() != null && StringUtils.isNotBlank(funding.getAmount().getContent())) {
            String amount = funding.getAmount().getContent();
            Locale locale = localeManager.getLocale();
            ParsePosition parsePosition = new ParsePosition(0);
            DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale);
            DecimalFormatSymbols symbols = numberFormat.getDecimalFormatSymbols();
            /**
             * When spaces are allowed, the grouping separator is the
             * character 160, which is a non-breaking space So, lets change
             * it so it uses the default space as a separator
             * */
            if (symbols.getGroupingSeparator() == 160) {
                symbols.setGroupingSeparator(' ');
            }
            numberFormat.setDecimalFormatSymbols(symbols);
            Number number = numberFormat.parse(amount, parsePosition);
            String formattedAmount = number.toString();
            if (parsePosition.getIndex() != amount.length()) {
                double example = 1234567.89;
                NumberFormat numberFormatExample = NumberFormat.getNumberInstance(localeManager.getLocale());
                throw new IllegalArgumentException(
                        "The amount: " + amount + " doesn'n have the right format, it should use the format: "
                                + numberFormatExample.format(example));
            }
            funding.getAmount().setContent(formattedAmount);
        }
    }
}

From source file:be.ibridge.kettle.trans.step.textfileinput.TextFileInput.java

public static final Value convertValue(String pol, String field_name, int field_type, String field_format,
        int field_length, int field_precision, String num_group, String num_decimal, String num_currency,
        String nullif, String ifNull, int trim_type, DecimalFormat ldf, DecimalFormatSymbols ldfs,
        SimpleDateFormat ldaf, DateFormatSymbols ldafs) throws Exception {
    Value value = new Value(field_name, field_type); // build a value!

    // If no nullif field is supplied, take the default.
    String null_value = nullif;/*from w ww  .j  a v a2s.c om*/
    if (null_value == null) {
        switch (field_type) {
        case Value.VALUE_TYPE_BOOLEAN:
            null_value = Const.NULL_BOOLEAN;
            break;
        case Value.VALUE_TYPE_STRING:
            null_value = Const.NULL_STRING;
            break;
        case Value.VALUE_TYPE_BIGNUMBER:
            null_value = Const.NULL_BIGNUMBER;
            break;
        case Value.VALUE_TYPE_NUMBER:
            null_value = Const.NULL_NUMBER;
            break;
        case Value.VALUE_TYPE_INTEGER:
            null_value = Const.NULL_INTEGER;
            break;
        case Value.VALUE_TYPE_DATE:
            null_value = Const.NULL_DATE;
            break;
        case Value.VALUE_TYPE_BINARY:
            null_value = Const.NULL_BINARY;
            break;
        default:
            null_value = Const.NULL_NONE;
            break;
        }
    }
    String null_cmp = Const.rightPad(new StringBuffer(null_value), pol.length());

    if (pol == null || pol.length() == 0 || pol.equalsIgnoreCase(null_cmp)) {
        if (ifNull != null && ifNull.length() != 0)
            pol = ifNull;
    }

    if (pol == null || pol.length() == 0 || pol.equalsIgnoreCase(null_cmp)) {
        value.setNull();
    } else {
        if (value.isNumeric()) {
            try {
                StringBuffer strpol = new StringBuffer(pol);

                switch (trim_type) {
                case TextFileInputMeta.TYPE_TRIM_LEFT:
                    while (strpol.length() > 0 && strpol.charAt(0) == ' ')
                        strpol.deleteCharAt(0);
                    break;
                case TextFileInputMeta.TYPE_TRIM_RIGHT:
                    while (strpol.length() > 0 && strpol.charAt(strpol.length() - 1) == ' ')
                        strpol.deleteCharAt(strpol.length() - 1);
                    break;
                case TextFileInputMeta.TYPE_TRIM_BOTH:
                    while (strpol.length() > 0 && strpol.charAt(0) == ' ')
                        strpol.deleteCharAt(0);
                    while (strpol.length() > 0 && strpol.charAt(strpol.length() - 1) == ' ')
                        strpol.deleteCharAt(strpol.length() - 1);
                    break;
                default:
                    break;
                }
                pol = strpol.toString();

                if (value.isNumber()) {
                    if (field_format != null) {
                        ldf.applyPattern(field_format);

                        if (num_decimal != null && num_decimal.length() >= 1)
                            ldfs.setDecimalSeparator(num_decimal.charAt(0));
                        if (num_group != null && num_group.length() >= 1)
                            ldfs.setGroupingSeparator(num_group.charAt(0));
                        if (num_currency != null && num_currency.length() >= 1)
                            ldfs.setCurrencySymbol(num_currency);

                        ldf.setDecimalFormatSymbols(ldfs);
                    }

                    value.setValue(ldf.parse(pol).doubleValue());
                } else {
                    if (value.isInteger()) {
                        value.setValue(Long.parseLong(pol));
                    } else {
                        if (value.isBigNumber()) {
                            value.setValue(new BigDecimal(pol));
                        } else {
                            throw new KettleValueException("Unknown numeric type: contact vendor!");
                        }
                    }
                }
            } catch (Exception e) {
                throw (e);
            }
        } else {
            if (value.isString()) {
                value.setValue(pol);
                switch (trim_type) {
                case TextFileInputMeta.TYPE_TRIM_LEFT:
                    value.ltrim();
                    break;
                case TextFileInputMeta.TYPE_TRIM_RIGHT:
                    value.rtrim();
                    break;
                case TextFileInputMeta.TYPE_TRIM_BOTH:
                    value.trim();
                    break;
                default:
                    break;
                }
                if (pol.length() == 0)
                    value.setNull();
            } else {
                if (value.isDate()) {
                    try {
                        if (field_format != null) {
                            ldaf.applyPattern(field_format);
                            ldaf.setDateFormatSymbols(ldafs);
                        }

                        value.setValue(ldaf.parse(pol));
                    } catch (Exception e) {
                        throw (e);
                    }
                } else {
                    if (value.isBinary()) {
                        value.setValue(pol.getBytes());
                    }
                }
            }
        }
    }

    value.setLength(field_length, field_precision);

    return value;
}