Example usage for org.apache.commons.lang StringUtils leftPad

List of usage examples for org.apache.commons.lang StringUtils leftPad

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils leftPad.

Prototype

public static String leftPad(String str, int size, String padStr) 

Source Link

Document

Left pad a String with a specified String.

Usage

From source file:com.primovision.lutransport.service.ImportMainSheetServiceImpl.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public List<String> importMainSheet(InputStream is) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");

    // initializing the InputStream from a file using
    // POIFSFileSystem, before converting the result
    // into an HSSFWorkbook instance
    System.out.println("***** Here step 2");
    HSSFWorkbook wb = null;// w  w w. j a  v  a  2 s. c o m
    StringBuffer buffer = null;
    List<String> list = new ArrayList<String>();
    List<Ticket> tickets = new ArrayList<Ticket>();
    // List<String> emptydatalist=new ArrayList<String>();
    int count = 1;
    int errorcount = 0;
    try {
        POIFSFileSystem fs = new POIFSFileSystem(is);
        ErrorData edata = new ErrorData();
        // FileWriter writer = new FileWriter("e:/errordata.txt");
        wb = new HSSFWorkbook(fs);
        // loop for every worksheet in the workbook
        int numOfSheets = wb.getNumberOfSheets();
        Map criterias = new HashMap();
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row = null;
        HSSFCell cell = null;
        Ticket ticket = null;
        Iterator rows = sheet.rowIterator();
        StringBuffer lineError;
        while (rows.hasNext()) {
            boolean error = false;
            buffer = new StringBuffer();
            int cellCount = 0;
            row = (HSSFRow) rows.next();
            if (count == 1) {
                count++;
                continue;
            }
            lineError = new StringBuffer("");
            try {
                ticket = new Ticket();
                ticket.setTicketStatus(1);
                ticket.setPayRollStatus(1);

                Object loadDateObj = getCellValue(row.getCell(0), true);
                if (loadDateObj == null) {
                    error = true;
                    lineError.append("Load Date,");
                } else if (loadDateObj instanceof Date) {
                    ticket.setLoadDate((Date) loadDateObj);
                } else {
                    String loadDateStr = loadDateObj.toString();
                    loadDateStr = StringUtils.trimToEmpty(loadDateStr);
                    Date loadDate = sdf.parse(loadDateStr);
                    ticket.setLoadDate(loadDate);
                }
                /*try {
                   Date loadDate = sdf.parse((String) getCellValue(row.getCell(0), true));
                   ticket.setLoadDate(loadDate);
                } catch (ParseException p) {
                   error = true;
                   lineError.append("Load Date,");
                }*/

                /*if (validDate(getCellValue(row.getCell(0))))
                   ticket.setLoadDate((Date) getCellValue(row.getCell(0)));
                else {
                   error = true;
                   lineError.append("Load Date,");
                }*/
                if (validTime((String) getCellValue(row.getCell(1)))) {
                    StringBuilder timeIn = new StringBuilder(
                            StringUtils.leftPad((String) getCellValue(row.getCell(1)), 4, '0'));
                    timeIn.insert(2, ':');
                    ticket.setTransferTimeIn(timeIn.toString());
                } else {
                    error = true;
                    lineError.append("Transfer Time In,");
                }
                if (validTime((String) getCellValue(row.getCell(2)))) {
                    StringBuilder timeOut = new StringBuilder(
                            StringUtils.leftPad((String) getCellValue(row.getCell(2)), 4, '0'));
                    timeOut.insert(2, ':');
                    ticket.setTransferTimeOut(timeOut.toString());
                } else {
                    error = true;
                    lineError.append("Transfer Time Out,");
                }
                try {
                    criterias.clear();
                    criterias.put("type", 1);
                    criterias.put("unit", Integer.parseInt((String) getCellValue(row.getCell(3))));
                    Vehicle vehicle = genericDAO.getByCriteria(Vehicle.class, criterias);
                    if (vehicle == null)
                        throw new Exception("no such truck");
                    else
                        ticket.setVehicle(vehicle);
                } catch (Exception ex) {
                    error = true;
                    lineError.append("Truck,");
                    log.warn(ex.getMessage());
                }
                try {
                    criterias.clear();
                    criterias.put("type", 2);
                    criterias.put("unit", Integer.parseInt((String) getCellValue(row.getCell(4))));
                    Vehicle vehicle = genericDAO.getByCriteria(Vehicle.class, criterias);
                    if (vehicle == null)
                        throw new Exception("no such trailer");
                    else
                        ticket.setTrailer(vehicle);
                } catch (Exception ex) {
                    error = true;
                    lineError.append("Trailer,");
                    log.warn(ex.getMessage());
                }

                Object unloadDateObj = getCellValue(row.getCell(5), true);
                if (unloadDateObj == null) {
                    error = true;
                    lineError.append("Unload Date,");
                } else if (unloadDateObj instanceof Date) {
                    ticket.setUnloadDate((Date) unloadDateObj);
                } else {
                    String unloadDateStr = unloadDateObj.toString();
                    unloadDateStr = StringUtils.trimToEmpty(unloadDateStr);
                    Date unloadDate = sdf.parse(unloadDateStr);
                    ticket.setUnloadDate(unloadDate);
                }
                /*try {
                   Date unloadDate = sdf.parse((String) getCellValue(row.getCell(5)));
                   ticket.setUnloadDate(unloadDate);
                } catch (ParseException p) {
                   error = true;
                   lineError.append("Unload Date,");
                }*/
                /*Object unloadDate = getCellValue(row.getCell(5));
                if (validDate(unloadDate))
                   ticket.setUnloadDate((Date) unloadDate);
                else {
                   error = true;
                   lineError.append("" + " Date,");
                }*/
                if (validTime((String) getCellValue(row.getCell(6)))) {
                    StringBuilder timeIn = new StringBuilder(
                            StringUtils.leftPad((String) getCellValue(row.getCell(6)), 4, '0'));
                    timeIn.insert(2, ':');
                    ticket.setLandfillTimeIn(timeIn.toString());
                } else {
                    error = true;
                    lineError.append("Landfill Time In,");
                }
                if (validTime((String) getCellValue(row.getCell(7)))) {
                    StringBuilder timeOut = new StringBuilder(
                            StringUtils.leftPad((String) getCellValue(row.getCell(7)), 4, '0'));
                    timeOut.insert(2, ':');
                    ticket.setLandfillTimeOut(timeOut.toString());
                } else {
                    error = true;
                    lineError.append("Landfill Time Out,");
                }
                try {
                    criterias.clear();
                    criterias.put("type", 1);
                    criterias.put("name", (String) getCellValue(row.getCell(8)));
                    Location location = genericDAO.getByCriteria(Location.class, criterias);
                    if (location == null)
                        throw new Exception("no such origin");
                    else
                        ticket.setOrigin(location);
                } catch (Exception ex) {
                    error = true;
                    lineError.append("Origin,");
                    // log.warn(ex.getMessage());
                }
                try {
                    ticket.setOriginTicket(Long.parseLong((String) getCellValue(row.getCell(9))));
                } catch (Exception ex) {
                    error = true;
                    lineError.append("Origin Ticket,");
                }
                try {
                    criterias.clear();
                    criterias.put("type", 2);
                    criterias.put("name", (String) getCellValue(row.getCell(10)));
                    Location location = genericDAO.getByCriteria(Location.class, criterias);
                    if (location == null)
                        throw new Exception("no such destination");
                    else
                        ticket.setDestination(location);
                } catch (Exception ex) {
                    error = true;
                    lineError.append("Destination,");
                    // log.warn(ex.getMessage());
                }

                // FOR CUSTOMER AND COMPANY_LACATION
                BillingRate billingRate = null;
                try {
                    criterias.clear();
                    criterias.put("type", 1);
                    criterias.put("name", (String) getCellValue(row.getCell(8)));
                    Location originid = genericDAO.getByCriteria(Location.class, criterias);

                    criterias.clear();
                    criterias.put("type", 2);
                    criterias.put("name", (String) getCellValue(row.getCell(10)));
                    Location destinationid = genericDAO.getByCriteria(Location.class, criterias);

                    if (originid != null && destinationid != null) {
                        // BillingRate billingRate = null;
                        String query = "select obj from BillingRate obj where transferStation="
                                + originid.getId() + " and landfill=" + destinationid.getId();
                        List<BillingRate> rates = genericDAO.executeSimpleQuery(query);

                        for (BillingRate rate : rates) {
                            if (rate.getRateUsing() == null) {
                                billingRate = rate;
                                break;
                            } else if (rate.getRateUsing() == 1) {
                                // calculation for a load date
                                if ((ticket.getLoadDate().getTime() >= rate.getValidFrom().getTime())
                                        && (ticket.getLoadDate().getTime() <= rate.getValidTo().getTime())) {
                                    billingRate = rate;
                                    break;
                                }
                            } else if (rate.getRateUsing() == 2) {
                                // calculation for a unload date
                                if ((ticket.getUnloadDate().getTime() >= rate.getValidFrom().getTime())
                                        && (ticket.getUnloadDate().getTime() <= rate.getValidTo().getTime())) {
                                    billingRate = rate;
                                    break;
                                }
                            }
                        }
                        if (billingRate != null) {
                            ticket.setCompanyLocation((billingRate.getCompanyLocation() != null)
                                    ? billingRate.getCompanyLocation()
                                    : null);
                            ticket.setCustomer(
                                    (billingRate.getCustomername() != null) ? billingRate.getCustomername()
                                            : null);
                        } else {
                            System.out.println("Customer and Company Location");

                        }
                        /*
                         * { error = true; lineError.append(
                         * "Rate is expired for this origin and destination,please contact to administrator,"
                         * ); }
                         */
                    }

                } catch (Exception ex) {
                    System.out.println("Customer and Company Location");
                    log.warn(ex.getMessage());
                }

                try {
                    ticket.setDestinationTicket(Long.parseLong((String) getCellValue(row.getCell(11))));
                } catch (Exception ex) {
                    error = true;
                    lineError.append("Destination Ticket,");
                }

                if (ticket.getOrigin() != null) {
                    if (reportService.checkDuplicate(ticket, "O")) {
                        lineError.append("Duplicate Origin Ticket,");
                        error = true;
                    }
                }

                if (ticket.getDestination() != null) {
                    if (reportService.checkDuplicate(ticket, "D")) {
                        lineError.append("Duplicates Dest. Ticket,");
                        error = true;
                    }

                }

                if (ticket.getUnloadDate() != null && ticket.getLoadDate() != null) {
                    if (ticket.getUnloadDate().before(ticket.getLoadDate())) {
                        lineError.append("Unload Date is before Load Date,");
                        error = true;
                    }
                }
                Double tgross = getValidAmount((String) getCellValue(row.getCell(12)));
                if (tgross != null)
                    ticket.setTransferGross(tgross);
                else {
                    error = true;
                    lineError.append("Transfer Gross,");
                }
                Double ttare = getValidAmount((String) getCellValue(row.getCell(13)));
                if (ttare != null)
                    ticket.setTransferTare(ttare);
                else {
                    lineError.append("Transfer Tare,");
                    error = true;
                }
                if (tgross != null && ttare != null) {
                    ticket.setTransferNet(tgross - ttare);
                    ticket.setTransferTons((tgross - ttare) / 2000);
                    /* if(billingRate.getBilledby().equals("bygallon")){ */
                    // Change to 8.35 - 28th Dec 2016
                    ticket.setGallons(ticket.getTransferNet() / 8.35);
                    // }
                }
                Double lgross = getValidAmount((String) getCellValue(row.getCell(16)));
                if (lgross != null)
                    ticket.setLandfillGross(lgross);
                else {
                    error = true;
                    lineError.append("Landfill Gross,");
                }
                Double ltare = getValidAmount((String) getCellValue(row.getCell(17)));
                if (ltare != null)
                    ticket.setLandfillTare(ltare);
                else {
                    lineError.append("Landfill Tare,");
                    error = true;
                }
                if (lgross != null && ltare != null) {
                    ticket.setLandfillNet(lgross - ltare);
                    ticket.setLandfillTons((lgross - ltare) / 2000);
                }
                String driverName = ((String) getCellValue(row.getCell(21)));
                Driver driver = null;
                try {
                    if (StringUtils.isEmpty(driverName))
                        throw new Exception("Invalid driver");
                    else {
                        // String[] names = driverName.split(" ");
                        criterias.clear();
                        /*
                         * criterias.put("firstName", names[1]);
                         * criterias.put("lastName", names[0]);
                         */
                        criterias.put("status", 1);
                        criterias.put("fullName", driverName);
                        driver = genericDAO.getByCriteria(Driver.class, criterias);
                        if (driver == null)
                            throw new Exception("Invalid driver");
                        ticket.setDriver(driver);
                        // ticket.setDriverCompany(driver.getCompany());
                    }
                } catch (Exception ex) {
                    error = true;
                    lineError.append("Driver,");
                }

                try {
                    String employeeCompanyName = ((String) getCellValue(row.getCell(23)));
                    if (StringUtils.isEmpty(employeeCompanyName))
                        throw new Exception("Invalid company");
                    else {
                        criterias.clear();
                        criterias.put("status", 1);
                        criterias.put("name", employeeCompanyName);
                        Location employeeCompany = genericDAO.getByCriteria(Location.class, criterias);
                        if (employeeCompany == null)
                            throw new Exception("Invalid company");
                        ticket.setDriverCompany(employeeCompany);
                    }
                } catch (Exception ex) {
                    error = true;
                    lineError.append("employee company,");
                }

                String subcontractor = ((String) getCellValue(row.getCell(20)));
                try {
                    if (!StringUtils.isEmpty(subcontractor)) {
                        /*
                         * if (driver != null && !"Subcontractor"
                         * .equalsIgnoreCase(driver .getLastName().trim()))
                         * { throw new Exception("Invalid subcontractor"); }
                         * 
                         * 
                         * else {
                         */
                        //String subcontractorMod = subcontractor.replace("&", "\"&\"");
                        criterias.clear();
                        criterias.put("name", subcontractor);
                        SubContractor contractor = genericDAO.getByCriteria(SubContractor.class, criterias);
                        if (contractor == null) {
                            throw new Exception("Invalid subcontractor");
                        } else {
                            ticket.setSubcontractor(contractor);
                        }
                        criterias.clear();
                    }
                    // }
                } catch (Exception ex) {
                    error = true;
                    lineError.append("Sub Contractor,");
                }

                Object billbatchDateObj = getCellValue(row.getCell(22), true);
                if (billbatchDateObj == null) {
                    error = true;
                    lineError.append("Bill Batch Date,");
                } else if (billbatchDateObj instanceof Date) {
                    ticket.setBillBatch((Date) billbatchDateObj);
                } else {
                    String billbatchDateStr = billbatchDateObj.toString();
                    billbatchDateStr = StringUtils.trimToEmpty(billbatchDateStr);
                    Date billbatchDate = sdf.parse(billbatchDateStr);
                    ticket.setBillBatch(billbatchDate);
                }
                /*try {
                   Date billBatch = sdf.parse((String) getCellValue(row.getCell(22)));
                   ticket.setBillBatch(billBatch);
                } catch (ParseException p) {
                   error = true;
                   lineError.append("Batch Date,");
                }*/

                /*Object billBatch = getCellValue(row.getCell(22));
                if (validDate(billBatch))
                   ticket.setBillBatch((Date) billBatch);
                else {
                   error = true;
                   lineError.append("Batch Date,");
                }*/
                try {
                    criterias.clear();
                    String locCode = (String) getCellValue(row.getCell(24));
                    if (StringUtils.isEmpty(locCode))
                        throw new Exception("Invalid terminal");
                    else {
                        criterias.put("code", locCode);
                        criterias.put("type", 4);
                    }
                    Location location = genericDAO.getByCriteria(Location.class, criterias);
                    if (location == null) {
                        throw new Exception("no such terminal");
                    } else {
                        criterias.clear();
                        criterias.put("status", 1);
                        criterias.put("fullName", driverName);
                        criterias.put("terminal", location);
                        Driver driverobj = genericDAO.getByCriteria(Driver.class, criterias);
                        if (driverobj == null) {
                            throw new Exception("Terminal does not match with driver");
                        } else {
                            ticket.setTerminal(location);
                        }
                    }
                } catch (Exception ex) {
                    error = true;
                    lineError.append("Terminal does not match with driver,");
                    log.warn(ex.getMessage());
                }
                try {
                    User user = genericDAO.getByUniqueAttribute(User.class, "username",
                            (String) getCellValue(row.getCell(25)));
                    if (user == null) {
                        throw new Exception("Invalid user");
                    } else {
                        ticket.setCreatedBy(user.getId());
                        ticket.setEnteredBy(user.getName());
                    }
                } catch (Exception ex) {
                    error = true;
                    lineError.append("User,");
                }
                if (!error) {
                    if (tickets.contains(ticket)) {
                        lineError.append("Duplicate Ticket,");
                        error = true;
                        errorcount++;
                    } else {
                        tickets.add(ticket);
                        //genericDAO.saveOrUpdate(ticket);
                    }
                } else {
                    errorcount++;
                }

            } catch (Exception ex) {
                error = true;
                log.warn(ex);
            }
            if (lineError.length() > 0) {
                System.out.println("Error :" + lineError.toString());
                list.add("Line " + count + ":" + lineError.toString() + "<br/>");
            }
            System.out.println("Record No :" + count);
            count++;
        }
    } catch (Exception e) {
        log.warn("Error in import customer :" + e);
    }
    if (errorcount == 0) {
        for (Ticket ticket : tickets) {
            genericDAO.saveOrUpdate(ticket);
        }
    }
    return list;
}

From source file:net.urosk.mifss.core.pools.FsContentPoolImpl.java

/**
* Creates left padded string from int to hex, splited in folder from 0-255
* in hex/*from w  ww . j a  v a2s  .co  m*/
* 
* @param id content id
* @return path in hex
*/
public String getHexStorePath(long id) {

    String s = Long.toHexString(id);
    s = s.toLowerCase();

    s = StringUtils.leftPad(s, hexPaddingLength, "0");

    String a = "";
    for (int i = 0; i < hexPaddingLength; i = i + 2) {
        a = a + s.substring(i, i + 2) + File.separator;
    }

    return a.substring(0, a.length() - 1);
}

From source file:ninja.text.TextImpl.java

@Override
public Text leftPad(int width, String padStr) {
    return Text.of(StringUtils.leftPad(data.toString(), width, padStr));
}

From source file:nl.nn.adapterframework.parameters.Parameter.java

/**
 * determines the raw value /* w  ww .ja va 2 s . c  o m*/
 * @param alreadyResolvedParameters
 * @return the raw value as object
 * @throws IbisException
 */
public Object getValue(ParameterValueList alreadyResolvedParameters, ParameterResolutionContext prc)
        throws ParameterException {
    Object result = null;
    log.debug("Calculating value for Parameter [" + getName() + "]");
    if (!configured) {
        throw new ParameterException("Parameter [" + getName() + "] not configured");
    }

    TransformerPool pool = getTransformerPool();
    if (pool != null) {
        try {
            Object transformResult = null;
            Source source = null;
            if (StringUtils.isNotEmpty(getValue())) {
                source = XmlUtils.stringToSourceForSingleUse(getValue(), prc.isNamespaceAware());
            } else if (StringUtils.isNotEmpty(getSessionKey())) {
                String sourceString;
                Object sourceObject = prc.getSession().get(getSessionKey());
                if (TYPE_LIST.equals(getType()) && sourceObject instanceof List) {
                    List<String> items = (List<String>) sourceObject;
                    XmlBuilder itemsXml = new XmlBuilder("items");
                    for (Iterator<String> it = items.iterator(); it.hasNext();) {
                        String item = it.next();
                        XmlBuilder itemXml = new XmlBuilder("item");
                        itemXml.setValue(item);
                        itemsXml.addSubElement(itemXml);
                    }
                    sourceString = itemsXml.toXML();
                } else if (TYPE_MAP.equals(getType()) && sourceObject instanceof Map) {
                    Map<String, String> items = (Map<String, String>) sourceObject;
                    XmlBuilder itemsXml = new XmlBuilder("items");
                    for (Iterator<String> it = items.keySet().iterator(); it.hasNext();) {
                        String item = it.next();
                        XmlBuilder itemXml = new XmlBuilder("item");
                        itemXml.addAttribute("name", item);
                        itemXml.setValue(items.get(item));
                        itemsXml.addSubElement(itemXml);
                    }
                    sourceString = itemsXml.toXML();
                } else {
                    sourceString = (String) sourceObject;
                }
                if (StringUtils.isNotEmpty(sourceString)) {
                    log.debug("Parameter [" + getName() + "] using sessionvariable [" + getSessionKey()
                            + "] as source for transformation");
                    source = XmlUtils.stringToSourceForSingleUse(sourceString, prc.isNamespaceAware());
                } else {
                    log.debug("Parameter [" + getName() + "] sessionvariable [" + getSessionKey()
                            + "] empty, no transformation will be performed");
                }
            } else if (StringUtils.isNotEmpty(getPattern())) {
                String sourceString = format(alreadyResolvedParameters, prc);
                if (StringUtils.isNotEmpty(sourceString)) {
                    log.debug("Parameter [" + getName() + "] using pattern [" + getPattern()
                            + "] as source for transformation");
                    source = XmlUtils.stringToSourceForSingleUse(sourceString, prc.isNamespaceAware());
                } else {
                    log.debug("Parameter [" + getName() + "] pattern [" + getPattern()
                            + "] empty, no transformation will be performed");
                }
            } else {
                source = prc.getInputSource();
            }
            if (source != null) {
                if (transformerPoolRemoveNamespaces != null) {
                    String rnResult = transformerPoolRemoveNamespaces.transform(source, null);
                    source = XmlUtils.stringToSource(rnResult);
                }
                transformResult = transform(source, prc);
            }
            if (!(transformResult instanceof String) || StringUtils.isNotEmpty((String) transformResult)) {
                result = transformResult;
            }
        } catch (Exception e) {
            throw new ParameterException(
                    "Parameter [" + getName() + "] exception on transformation to get parametervalue", e);
        }
    } else {
        if (StringUtils.isNotEmpty(getSessionKey())) {
            result = prc.getSession().get(getSessionKey());
        } else if (StringUtils.isNotEmpty(getPattern())) {
            result = format(alreadyResolvedParameters, prc);
        } else if (StringUtils.isNotEmpty(getValue())) {
            result = getValue();
        } else {
            result = prc.getInput();
        }
    }
    if (result != null) {
        if (log.isDebugEnabled()) {
            log.debug("Parameter [" + getName() + "] resolved to ["
                    + (isHidden() ? hide(result.toString()) : result) + "]");
        }
    } else {
        // if value is null then return specified default value
        StringTokenizer stringTokenizer = new StringTokenizer(getDefaultValueMethods(), ",");
        while (result == null && stringTokenizer.hasMoreElements()) {
            String token = stringTokenizer.nextToken();
            if ("defaultValue".equals(token)) {
                result = getDefaultValue();
            } else if ("sessionKey".equals(token)) {
                result = prc.getSession().get(getSessionKey());
            } else if ("pattern".equals(token)) {
                result = format(alreadyResolvedParameters, prc);
            } else if ("value".equals(token)) {
                result = getValue();
            } else if ("input".equals(token)) {
                result = prc.getInput();
            }
        }
        log.debug("Parameter [" + getName() + "] resolved to defaultvalue ["
                + (isHidden() ? hide(result.toString()) : result) + "]");
    }
    if (result != null && result instanceof String) {
        if (getMinLength() >= 0 && !TYPE_NUMBER.equals(getType())) {
            if (result.toString().length() < getMinLength()) {
                log.debug("Padding parameter [" + getName() + "] because length [" + result.toString().length()
                        + "] deceeds minLength [" + getMinLength() + "]");
                result = StringUtils.rightPad(result.toString(), getMinLength());
            }
        }
        if (getMaxLength() >= 0) {
            if (result.toString().length() > getMaxLength()) {
                log.debug("Trimming parameter [" + getName() + "] because length [" + result.toString().length()
                        + "] exceeds maxLength [" + getMaxLength() + "]");
                result = result.toString().substring(0, getMaxLength());
            }
        }
        if (TYPE_NODE.equals(getType())) {
            try {
                result = XmlUtils.buildNode((String) result, prc.isNamespaceAware());
                if (log.isDebugEnabled())
                    log.debug("final result [" + result.getClass().getName() + "][" + result + "]");
            } catch (DomBuilderException e) {
                throw new ParameterException(
                        "Parameter [" + getName() + "] could not parse result [" + result + "] to XML nodeset",
                        e);
            }
        }
        if (TYPE_DOMDOC.equals(getType())) {
            try {
                result = XmlUtils.buildDomDocument((String) result, prc.isNamespaceAware(), prc.isXslt2());
                if (log.isDebugEnabled())
                    log.debug("final result [" + result.getClass().getName() + "][" + result + "]");
            } catch (DomBuilderException e) {
                throw new ParameterException(
                        "Parameter [" + getName() + "] could not parse result [" + result + "] to XML document",
                        e);
            }
        }
        if (TYPE_DATE.equals(getType()) || TYPE_DATETIME.equals(getType()) || TYPE_TIMESTAMP.equals(getType())
                || TYPE_TIME.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result
                    + "] to date using formatString [" + getFormatString() + "]");
            DateFormat df = new SimpleDateFormat(getFormatString());
            try {
                result = df.parseObject((String) result);
            } catch (ParseException e) {
                throw new ParameterException("Parameter [" + getName() + "] could not parse result [" + result
                        + "] to Date using formatString [" + getFormatString() + "]", e);
            }
        }
        if (TYPE_XMLDATETIME.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result
                    + "] from xml dateTime to date");
            result = DateUtils.parseXmlDateTime((String) result);
        }
        if (TYPE_NUMBER.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result
                    + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator()
                    + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]");
            DecimalFormat df = new DecimalFormat();
            df.setDecimalFormatSymbols(decimalFormatSymbols);
            try {
                Number n = df.parse((String) result);
                result = n;
            } catch (ParseException e) {
                throw new ParameterException(
                        "Parameter [" + getName() + "] could not parse result [" + result
                                + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator()
                                + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]",
                        e);
            }
            if (getMinLength() >= 0 && result.toString().length() < getMinLength()) {
                log.debug("Adding leading zeros to parameter [" + getName() + "]");
                result = StringUtils.leftPad(result.toString(), getMinLength(), '0');
            }
        }
        if (TYPE_INTEGER.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result + "] to integer");
            try {
                Integer i = Integer.parseInt((String) result);
                result = i;
            } catch (NumberFormatException e) {
                throw new ParameterException(
                        "Parameter [" + getName() + "] could not parse result [" + result + "] to integer", e);
            }
        }
    }
    if (result != null) {
        if (getMinInclusive() != null || getMaxInclusive() != null) {
            if (getMinInclusive() != null) {
                if (((Number) result).floatValue() < minInclusive.floatValue()) {
                    log.debug("Replacing parameter [" + getName() + "] because value [" + result
                            + "] exceeds minInclusive [" + getMinInclusive() + "]");
                    result = minInclusive;
                }
            }
            if (getMaxInclusive() != null) {
                if (((Number) result).floatValue() > maxInclusive.floatValue()) {
                    log.debug("Replacing parameter [" + getName() + "] because value [" + result
                            + "] exceeds maxInclusive [" + getMaxInclusive() + "]");
                    result = maxInclusive;
                }
            }
        }
    }

    return result;
}

From source file:nl.nn.adapterframework.util.FileUtils.java

public static File getFreeFile(File file) {
    if (file.exists()) {
        String extension = FileUtils.getFileNameExtension(file.getPath());
        int count = 1;
        while (true) {
            String newFileName;/*from w w  w.j  av a 2 s  .com*/
            String countStr;
            if (count < 1000) {
                countStr = StringUtils.leftPad(("" + count), 3, "0");
            } else {
                countStr = "" + count;
            }
            if (extension != null) {
                newFileName = StringUtils.substringBeforeLast(file.getPath(), ".") + "_" + countStr + "."
                        + extension;
            } else {
                newFileName = file.getPath() + "_" + countStr;
            }
            File newFile = new File(newFileName);
            if (newFile.exists()) {
                count++;
            } else {
                return newFile;
            }
        }
    } else {
        return file;
    }
}

From source file:nl.strohalm.cyclos.controls.accounts.details.ScheduledPaymentReceiptAjaxAction.java

@Override
protected String resolveText(final ActionContext context, final ReceiptPrinterSettings receiptPrinterSettings) {
    final ScheduledPaymentForm form = context.getForm();
    final long paymentId = form.getPaymentId();
    final ScheduledPayment scheduledPayment = scheduledPaymentService.load(paymentId,
            ViewScheduledPaymentAction.FETCH);

    final LocalSettings localSettings = settingsService.getLocalSettings();
    final CalendarConverter dateTimeConverter = localSettings.getDateTimeConverter();
    final CalendarConverter dateConverter = localSettings.getDateConverter();
    final UnitsConverter unitsConverter = localSettings
            .getUnitsConverter(scheduledPayment.getFrom().getType().getCurrency().getPattern());

    final int installmentCount = scheduledPayment.getTransfers().size();
    final boolean singleInstallment = installmentCount == 1;

    final StringBuilder out = new StringBuilder();
    out.append(context.message("receipt.transfer.header", localSettings.getApplicationName())).append('\n');
    out.append(context.message("receipt.transfer.textBefore")).append('\n');
    out.append(context.message("receipt.transfer.from", ownerString(scheduledPayment.getFrom()))).append('\n');
    out.append(context.message("receipt.transfer.to", ownerString(scheduledPayment.getTo()))).append('\n');
    out.append(context.message("receipt.transfer.date", dateTimeConverter.toString(scheduledPayment.getDate())))
            .append('\n');
    out.append(//from  ww w.j a v  a2  s  .c o m
            context.message("receipt.transfer.amount", unitsConverter.toString(scheduledPayment.getAmount())))
            .append('\n');
    if (singleInstallment) {
        out.append(context.message("receipt.transfer.scheduledFor",
                dateConverter.toString(scheduledPayment.getTransfers().get(0).getDate()))).append('\n');
    }
    if (!singleInstallment) {
        final List<Transfer> installments = scheduledPayment.getTransfers();
        out.append(context.message("receipt.transfer.installments", installments.size())).append('\n');
        final int maxDigits = String.valueOf(installments.size()).length();
        for (int i = 0; i < installmentCount; i++) {
            final Transfer installment = installments.get(i);
            final String index = StringUtils.leftPad(String.valueOf(i + 1), maxDigits, '0');
            final String date = dateConverter.toString(installment.getDate());
            final String amount = unitsConverter.toString(installment.getAmount());
            out.append(context.message("receipt.transfer.installment", index, date, amount)).append('\n');
        }
    }
    if (StringUtils.isNotEmpty(receiptPrinterSettings.getPaymentAdditionalMessage())) {
        out.append('\n').append(receiptPrinterSettings.getPaymentAdditionalMessage()).append('\n');
    }
    out.append(context.message("receipt.transfer.textAfter"));
    return out.toString();
}

From source file:nl.strohalm.cyclos.utils.conversion.CardNumberConverter.java

public String toString(final BigInteger number) {
    if (number == null) {
        return null;
    }/*from  w  ww  .  jav  a2 s. co  m*/

    int numbers = 0;
    for (int i = 0; i < pattern.length(); i++) {
        final char c = pattern.charAt(i);
        if (ALLOWED_BOUNDARY_CHARS.indexOf(c) >= 0) {
            numbers++;
        }
    }

    final String data = StringUtils.leftPad(number.toString(), numbers, '0');
    final StringBuffer formatedCardNumber = new StringBuffer();

    int numberDigit = 0;
    for (int i = 0; i < pattern.length(); i++) {
        final char c = pattern.charAt(i);
        if (ALLOWED_BOUNDARY_CHARS.indexOf(c) >= 0) {
            formatedCardNumber.append(data.charAt(numberDigit));
            numberDigit++;
        } else {
            formatedCardNumber.append(c);
        }
    }

    return formatedCardNumber.toString();
}

From source file:nl.strohalm.cyclos.utils.conversion.FixedLengthNumberConverter.java

public String toString(final T object) {
    final BigDecimal number = CoercionHelper.coerce(BigDecimal.class, object);
    if (number == null) {
        return null;
    }/*from  ww  w  .j  a  v a  2  s . c o  m*/
    return StringUtils.leftPad(number.unscaledValue().toString(), precision, '0');
}

From source file:nl.strohalm.cyclos.utils.InternetAddressHelper.java

/**
 * Pads an address, filling with zeroes on the left. Example: 1.2.30.100 becomes 001.002.030.100
 *//*ww  w.ja v a 2 s  .  c  om*/
public static String padAddress(final String address) {
    if (!isSimpleIp(address)) {
        throw new IllegalArgumentException("Was expecting an IP address, but received \"" + address + "\"");
    }

    final String[] parts = StringUtils.split(address, '.');
    for (int i = 0; i < parts.length; i++) {
        parts[i] = StringUtils.leftPad(parts[i], 3, '0');
    }
    return StringUtils.join(parts, '.');
}

From source file:nl.toolforge.karma.console.KarmaConsole.java

/**
 * Gets the default prompt, constructed as follows : <code>HH:MM:SS [ Karma ]</code>
 *//*ww w. j  a v  a 2 s.co m*/
public String getPrompt() {

    Calendar now = Calendar.getInstance();

    String end = (commandContext.getCurrentManifest() == null ? "Karma"
            : commandContext.getCurrentManifest().getName());
    end = commandContext.getWorkingContext().getName() + "::" + end;
    return StringUtils.leftPad("" + now.get(Calendar.HOUR_OF_DAY), 2, "0") + ":"
            + StringUtils.leftPad("" + now.get(Calendar.MINUTE), 2, "0") + ":"
            + StringUtils.leftPad("" + now.get(Calendar.SECOND), 2, "0") + " [ " + end + " ] > ";
}