Example usage for java.lang Float Float

List of usage examples for java.lang Float Float

Introduction

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

Prototype

@Deprecated(since = "9")
public Float(String s) throws NumberFormatException 

Source Link

Document

Constructs a newly allocated Float object that represents the floating-point value of type float represented by the string.

Usage

From source file:demo.config.PropertyConverter.java

/**
 * Convert the specified object into a Float.
 * //  w  w  w . j av a  2 s .co  m
 * @param value
 *            the value to convert
 * @return the converted value
 * @throws ConversionException
 *             thrown if the value cannot be converted to a Float
 */
public static Float toFloat(Object value) throws ConversionException {
    Number n = toNumber(value, Float.class);
    if (n instanceof Float) {
        return (Float) n;
    } else {
        return new Float(n.floatValue());
    }
}

From source file:Coordinate.java

/**
 * A method to add distance in an westerly direction to a coordinate
 *
 * @param latitude  a latitude coordinate in decimal notation
 * @param longitude a longitude coordinate in decimal notation
 * @param distance  the distance to add in metres
 *
 * @return          the new coordinate//from w  w  w  . j  a v  a 2 s. co m
 */
public static Coordinate addDistanceWest(float latitude, float longitude, int distance) {

    // check on the parameters
    if (isValidLatitude(latitude) == false || isValidLongitude(longitude) == false || distance <= 0) {
        throw new IllegalArgumentException("All parameters are required and must be valid");
    }

    // convert the distance from metres to kilometers
    float kilometers = distance / 1000;

    // calculate the new longitude
    double newLng = longitude - (distance / longitudeConstant(latitude));

    return new Coordinate(latitude, new Float(newLng).floatValue());
}

From source file:gov.nih.nci.system.web.struts.action.UpdateAction.java

public Object convertValue(Class klass, Object value) throws Exception {

    String fieldType = klass.getName();
    Object convertedValue = null;
    try {// w  w w  .j  a v a2s  .  c  o m
        if (fieldType.equals("java.lang.Long")) {
            convertedValue = new Long((String) value);
        } else if (fieldType.equals("java.lang.Integer")) {
            convertedValue = new Integer((String) value);
        } else if (fieldType.equals("java.lang.String")) {
            convertedValue = value;
        } else if (fieldType.equals("java.lang.Float")) {
            convertedValue = new Float((String) value);
        } else if (fieldType.equals("java.lang.Double")) {
            convertedValue = new Double((String) value);
        } else if (fieldType.equals("java.lang.Boolean")) {
            convertedValue = new Boolean((String) value);
        } else if (fieldType.equals("java.util.Date")) {
            SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
            convertedValue = format.parse((String) value);
        } else if (fieldType.equals("java.net.URI")) {
            convertedValue = new URI((String) value);
        } else if (fieldType.equals("java.lang.Character")) {
            convertedValue = new Character(((String) value).charAt(0));
        } else if (klass.isEnum()) {
            Class enumKlass = Class.forName(fieldType);
            convertedValue = Enum.valueOf(enumKlass, (String) value);
        } else {
            throw new Exception("type mismatch - " + fieldType);
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
        throw new Exception(e.getMessage());
    } catch (Exception ex) {
        log.error("ERROR : " + ex.getMessage());
        throw ex;
    }
    return convertedValue;
}

From source file:com.eurelis.opencms.workflows.ui.toolobject.WorkflowMenuItemLoader.java

/**
 * Check that the given value of position doesn't exist. If this one exists,
 * then create a new position and use it.
 * //  ww w .j a v a 2 s.  com
 * @param positionProperty
 *            the string value of the position given as property
 * @return the value that can be use to manage position (sure that it's not
 *         use)
 */
private float checkAnUpdatePosition(String positionProperty) {
    if (StringChecker.isNotNullOrEmpty(positionProperty)) {
        try {
            Float position = new Float(positionProperty);
            if (!_foundPosition.contains(position)) {
                // store new position
                _foundPosition.add(position);

                // return value
                return position.floatValue();
            }
        } catch (NumberFormatException e) {
            // do nothing, a default position will be set when outgoing if
        }
    }

    // get new Position and update property
    float newPosition = _lastPositionSet + 1;
    this._lastPositionSet = newPosition;

    // store the use position
    _foundPosition.add(new Float(newPosition));

    return newPosition;

}

From source file:com.salesmanager.core.util.ProductUtil.java

/**
 * Format like <blue>[if discount striked]SYMBOL BASEAMOUNT</blue> [if
 * discount <red>SYMBOL DISCOUNTAMOUNT</red>] [if discount <red>Save:
 * PERCENTAGE AMOUNT</red>] [if qty discount <red>Buy QTY save [if price qty
 * discount AMOUNT] [if percent qty discount PERCENT]</red>]
 * /*w  ww . j  av  a  2  s  .co m*/
 * @param ctx
 * @param view
 * @return
 */
public static String formatHTMLProductPriceWithAttributes(Locale locale, String currency, Product view,
        Collection attributes, boolean showDiscountDate) {

    if (currency == null) {
        log.error("Currency is null ...");
        return "-N/A-";
    }

    int decimalPlace = 2;

    String prefix = "";
    String suffix = "";

    Map currenciesmap = RefCache.getCurrenciesListWithCodes();
    Currency c = (Currency) currenciesmap.get(currency);

    // regular price
    BigDecimal bdprodprice = view.getProductPrice();

    // determine any properties prices
    BigDecimal attributesPrice = null;

    if (attributes != null) {
        Iterator i = attributes.iterator();
        while (i.hasNext()) {
            ProductAttribute attr = (ProductAttribute) i.next();
            if (!attr.isAttributeDisplayOnly() && attr.getOptionValuePrice().longValue() > 0) {
                if (attributesPrice == null) {
                    attributesPrice = new BigDecimal(0);
                }
                attributesPrice = attributesPrice.add(attr.getOptionValuePrice());
            }
        }
    }

    if (attributesPrice != null) {
        bdprodprice = bdprodprice.add(attributesPrice);// new price with
        // properties
    }

    // discount price
    java.util.Date spdate = null;
    java.util.Date spenddate = null;
    BigDecimal bddiscountprice = null;
    Special special = view.getSpecial();
    if (special != null) {
        bddiscountprice = special.getSpecialNewProductPrice();
        if (attributesPrice != null) {
            bddiscountprice = bddiscountprice.add(attributesPrice);// new
            // price
            // with
            // properties
        }
        spdate = special.getSpecialDateAvailable();
        spenddate = special.getExpiresDate();
    }

    // all other prices
    Set prices = view.getPrices();
    if (prices != null) {
        Iterator pit = prices.iterator();
        while (pit.hasNext()) {
            ProductPrice pprice = (ProductPrice) pit.next();
            if (pprice.isDefaultPrice()) {
                pprice.setLocale(locale);
                suffix = pprice.getPriceSuffix();
                bddiscountprice = null;
                spdate = null;
                spenddate = null;
                bdprodprice = pprice.getProductPriceAmount();
                if (attributesPrice != null) {
                    bdprodprice = bdprodprice.add(attributesPrice);// new
                    // price
                    // with
                    // properties
                }
                ProductPriceSpecial ppspecial = pprice.getSpecial();
                if (ppspecial != null) {
                    if (ppspecial.getProductPriceSpecialStartDate() != null
                            && ppspecial.getProductPriceSpecialEndDate() != null) {
                        spdate = ppspecial.getProductPriceSpecialStartDate();
                        spenddate = ppspecial.getProductPriceSpecialEndDate();
                    }
                    bddiscountprice = ppspecial.getProductPriceSpecialAmount();
                    if (bddiscountprice != null && attributesPrice != null) {
                        bddiscountprice = bddiscountprice.add(attributesPrice);// new price with
                        // properties
                    }
                }
                break;
            }
        }
    }

    double fprodprice = 0;
    ;
    if (bdprodprice != null) {
        fprodprice = bdprodprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    // regular price String
    String regularprice = CurrencyUtil.displayFormatedCssAmountWithCurrency(bdprodprice, currency);

    Date dt = new Date();

    // discount price String
    String discountprice = null;
    String savediscount = null;
    if (bddiscountprice != null && (spdate != null && spdate.before(new Date(dt.getTime()))
            && spenddate.after(new Date(dt.getTime())))) {

        double fdiscountprice = bddiscountprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();

        discountprice = CurrencyUtil.displayFormatedAmountWithCurrency(bddiscountprice, currency);

        double arith = fdiscountprice / fprodprice;
        double fsdiscount = 100 - arith * 100;

        Float percentagediscount = new Float(fsdiscount);

        savediscount = String.valueOf(percentagediscount.intValue());

    }

    StringBuffer p = new StringBuffer();
    p.append("<div class='product-price'>");
    if (discountprice == null) {
        p.append("<div class='product-price-price' style='width:50%;float:left;'>");
        p.append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</div>");
        p.append("<div class='product-line'>&nbsp;</div>");
    } else {
        p.append("<div style='width:50%;float:left;'>");
        p.append("<strike>").append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</strike>");
        p.append("</div>");
        p.append("<div style='width:50%;float:right;'>");
        p.append("<font color='red'>").append(discountprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</font>").append("<br>").append("<font color='red' style='font-size:75%;'>")
                .append(LabelUtil.getInstance().getText(locale, "label.generic.save")).append(": ")
                .append(savediscount)
                .append(LabelUtil.getInstance().getText(locale, "label.generic.percentsign")).append(" ")
                .append(LabelUtil.getInstance().getText(locale, "label.generic.off")).append("</font>");

        if (showDiscountDate && spenddate != null) {
            p.append("<br>").append(" <font style='font-size:65%;'>")
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.until")).append("&nbsp;")
                    .append(DateUtil.formatDate(spenddate)).append("</font>");
        }

        p.append("</div>").toString();
    }
    p.append("</div>");
    return p.toString();

}

From source file:edu.hawaii.soest.hioos.storx.StorXSource.java

/**
 * A method that processes the data object passed and flushes the
 * data to the DataTurbine given the sensor properties in the XMLConfiguration
 * passed in./*from  w  ww.  j  a  va2s . c  om*/
 *
 * @param xmlConfig - the XMLConfiguration object containing the list of
 *                    sensor properties
 * @param frameMap  - the parsed data as a HierarchicalMap object
 */
public boolean process(XMLConfiguration xmlConfig, HierarchicalMap frameMap) {

    logger.debug("StorXSource.process() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean success = false;

    try {

        // add channels of data that will be pushed to the server.  
        // Each sample will be sent to the Data Turbine as an rbnb frame.  Information
        // on each channel is found in the XMLConfiguration file (email.account.properties.xml)
        // and the StorXParser object (to get the data string)
        ChannelMap rbnbChannelMap = new ChannelMap(); // used to flush channels
        ChannelMap registerChannelMap = new ChannelMap(); // used to register channels
        int channelIndex = 0;

        // this.storXParser = new StorXParser(storXFrame);

        String sensorName = null;
        String sensorSerialNumber = null;
        String sensorDescription = null;
        boolean isImmersed = false;
        String calibrationURL = null;

        List sensorList = xmlConfig.configurationsAt("account.logger.sensor");

        for (Iterator sIterator = sensorList.iterator(); sIterator.hasNext();) {
            //  
            HierarchicalConfiguration sensorConfig = (HierarchicalConfiguration) sIterator.next();
            sensorSerialNumber = sensorConfig.getString("serialNumber");

            // find the correct sensor configuration properties
            if (sensorSerialNumber.equals(frameMap.get("serialNumber"))) {

                sensorName = sensorConfig.getString("name");
                sensorDescription = sensorConfig.getString("description");
                isImmersed = new Boolean(sensorConfig.getString("isImmersed")).booleanValue();
                calibrationURL = sensorConfig.getString("calibrationURL");

                // get a Calibration instance to interpret raw sensor values
                Calibration calibration = new Calibration();

                if (calibration.parse(calibrationURL)) {

                    // Build the RBNB channel map 

                    // get the sample date and convert it to seconds since the epoch
                    Date sampleDate = (Date) frameMap.get("date");
                    Calendar sampleDateTime = Calendar.getInstance();
                    sampleDateTime.setTime(sampleDate);
                    double sampleTimeAsSecondsSinceEpoch = (double) (sampleDateTime.getTimeInMillis() / 1000);
                    // and create a string formatted date
                    DATE_FORMAT.setTimeZone(TZ);
                    String sampleDateAsString = DATE_FORMAT.format(sampleDate).toString();

                    // get the sample data from the frame map
                    ByteBuffer rawFrame = (ByteBuffer) frameMap.get("rawFrame");
                    StorXFrame storXFrame = (StorXFrame) frameMap.get("parsedFrameObject");
                    String serialNumber = storXFrame.getSerialNumber();
                    int rawAnalogChannelOne = storXFrame.getAnalogChannelOne();
                    int rawAnalogChannelTwo = storXFrame.getAnalogChannelTwo();
                    int rawAnalogChannelThree = storXFrame.getAnalogChannelThree();
                    int rawAnalogChannelFour = storXFrame.getAnalogChannelFour();
                    int rawAnalogChannelFive = storXFrame.getAnalogChannelFive();
                    int rawAnalogChannelSix = storXFrame.getAnalogChannelSix();
                    int rawAnalogChannelSeven = storXFrame.getAnalogChannelSeven();
                    double rawInternalVoltage = new Float(storXFrame.getInternalVoltage()).doubleValue();

                    // apply calibrations to the observed data
                    double analogChannelOne = calibration.apply((double) rawAnalogChannelOne, isImmersed,
                            "AUX_1");
                    double analogChannelTwo = calibration.apply((double) rawAnalogChannelTwo, isImmersed,
                            "AUX_2");
                    double analogChannelThree = calibration.apply((double) rawAnalogChannelThree, isImmersed,
                            "AUX_3");
                    double analogChannelFour = calibration.apply((double) rawAnalogChannelFour, isImmersed,
                            "AUX_4");
                    double analogChannelFive = calibration.apply((double) rawAnalogChannelFive, isImmersed,
                            "AUX_5");
                    double analogChannelSix = calibration.apply((double) rawAnalogChannelSix, isImmersed,
                            "AUX_6");
                    double analogChannelSeven = calibration.apply((double) rawAnalogChannelSeven, isImmersed,
                            "AUX_7");
                    double internalVoltage = calibration.apply(rawInternalVoltage, isImmersed, "SV");

                    String sampleString = "";
                    sampleString += String.format("%s", serialNumber) + ", ";
                    sampleString += String.format("%5d", rawAnalogChannelOne) + ", ";
                    sampleString += String.format("%5d", rawAnalogChannelTwo) + ", ";
                    sampleString += String.format("%5d", rawAnalogChannelThree) + ", ";
                    sampleString += String.format("%5d", rawAnalogChannelFour) + ", ";
                    sampleString += String.format("%5d", rawAnalogChannelFive) + ", ";
                    sampleString += String.format("%5d", rawAnalogChannelSix) + ", ";
                    sampleString += String.format("%5d", rawAnalogChannelSeven) + ", ";
                    sampleString += String.format("%05.2f", internalVoltage) + ", ";
                    sampleString += sampleDateAsString;
                    sampleString += storXFrame.getTerminator();

                    // add the sample timestamp to the rbnb channel map
                    //registerChannelMap.PutTime(sampleTimeAsSecondsSinceEpoch, 0d);
                    rbnbChannelMap.PutTime(sampleTimeAsSecondsSinceEpoch, 0d);

                    // add the BinaryRawSatlanticFrameData channel to the channelMap
                    channelIndex = registerChannelMap.Add("BinaryRawSatlanticFrameData");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("BinaryRawSatlanticFrameData");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsByteArray(channelIndex, rawFrame.array());

                    // add the DecimalASCIISampleData channel to the channelMap
                    channelIndex = registerChannelMap.Add(getRBNBChannelName());
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add(getRBNBChannelName());
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, sampleString);

                    // add the serialNumber channel to the channelMap
                    channelIndex = registerChannelMap.Add("serialNumber");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("serialNumber");
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, serialNumber);

                    // add the analogChannelOne channel to the channelMap
                    channelIndex = registerChannelMap.Add("analogChannelOne");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("analogChannelOne");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { analogChannelOne });

                    // add the analogChannelTwo channel to the channelMap
                    channelIndex = registerChannelMap.Add("analogChannelTwo");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("analogChannelTwo");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { analogChannelTwo });

                    // add the analogChannelThree channel to the channelMap
                    channelIndex = registerChannelMap.Add("analogChannelThree");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("analogChannelThree");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { analogChannelThree });

                    // add the analogChannelFour channel to the channelMap
                    channelIndex = registerChannelMap.Add("analogChannelFour");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("analogChannelFour");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { analogChannelFour });

                    // add the analogChannelFive channel to the channelMap
                    channelIndex = registerChannelMap.Add("analogChannelFive");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("analogChannelFive");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { analogChannelFive });

                    // add the analogChannelSix channel to the channelMap
                    channelIndex = registerChannelMap.Add("analogChannelSix");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("analogChannelSix");
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { analogChannelSix });

                    // add the analogChannelSeven channel to the channelMap
                    channelIndex = registerChannelMap.Add("analogChannelSeven");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("analogChannelSeven");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { analogChannelSeven });

                    // add the internalVoltage channel to the channelMap
                    channelIndex = registerChannelMap.Add("internalVoltage");
                    registerChannelMap.PutUserInfo(channelIndex, "units=V");
                    channelIndex = rbnbChannelMap.Add("internalVoltage");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { internalVoltage });

                    // Now register the RBNB channels, and flush the rbnbChannelMap to the
                    // DataTurbine
                    getSource().Register(registerChannelMap);
                    getSource().Flush(rbnbChannelMap);
                    logger.info("Sample sent to the DataTurbine:" + sampleString);

                    registerChannelMap.Clear();
                    rbnbChannelMap.Clear();

                } else {

                    logger.info("Couldn't apply the calibration coefficients. " + "Skipping this sample.");

                } // end if()

            } // end if()

        } // end for()                                             

        //getSource.Detach();
        success = true;

    } catch (Exception sapie) {
        //} catch ( SAPIException sapie ) {
        // In the event of an RBNB communication  exception, log the exception, 
        // and allow execute() to return false, which will prompt a retry.
        success = false;
        sapie.printStackTrace();
        return success;

    }

    return success;
}

From source file:net.pflaeging.PortableSigner.SignCommandLine.java

/** Creates a new instance of CommandLine */
public SignCommandLine(String args[]) {
    langcodes = "";
    java.util.Enumeration<String> langCodes = ResourceBundle
            .getBundle("net/pflaeging/PortableSigner/SignatureblockLanguages").getKeys();

    while (langCodes.hasMoreElements()) {
        langcodes = langcodes + langCodes.nextElement() + "|";
    }/*from w  ww.j a va  2  s.co m*/
    langcodes = langcodes.substring(0, langcodes.length() - 1);
    //        System.out.println("Langcodes: " + langcodes);

    CommandLine cmd;
    Options options = new Options();
    options.addOption("t", true, rbi18n.getString("CLI-InputFile"));
    options.addOption("o", true, rbi18n.getString("CLI-OutputFile"));
    options.addOption("s", true, rbi18n.getString("CLI-SignatureFile"));
    options.addOption("p", true, rbi18n.getString("CLI-Password"));
    options.addOption("n", false, rbi18n.getString("CLI-WithoutGUI"));
    options.addOption("f", false, rbi18n.getString("CLI-Finalize"));
    options.addOption("h", false, rbi18n.getString("CLI-Help"));
    options.addOption("b", true, rbi18n.getString("CLI-SigBlock") + langcodes);
    options.addOption("i", true, rbi18n.getString("CLI-SigImage"));
    options.addOption("c", true, rbi18n.getString("CLI-SigComment"));
    options.addOption("r", true, rbi18n.getString("CLI-SigReason"));
    options.addOption("l", true, rbi18n.getString("CLI-SigLocation"));
    options.addOption("e", true, rbi18n.getString("CLI-EmbedSignature"));
    options.addOption("pwdfile", true, rbi18n.getString("CLI-PasswdFile"));
    options.addOption("ownerpwd", true, rbi18n.getString("CLI-OwnerPasswd"));
    options.addOption("ownerpwdfile", true, rbi18n.getString("CLI-OwnerPasswdFile"));
    options.addOption("z", false, rbi18n.getString("CLI-LastPage"));

    CommandLineParser parser = new PosixParser();
    HelpFormatter usage = new HelpFormatter();
    try {
        cmd = parser.parse(options, args);
        input = cmd.getOptionValue("t", "");
        output = cmd.getOptionValue("o", "");
        signature = cmd.getOptionValue("s", "");
        password = cmd.getOptionValue("p", "");
        nogui = cmd.hasOption("n");
        help = cmd.hasOption("h");
        finalize = !cmd.hasOption("f");
        sigblock = cmd.getOptionValue("b", "");
        sigimage = cmd.getOptionValue("i", "");
        comment = cmd.getOptionValue("c", "");
        reason = cmd.getOptionValue("r", "");
        location = cmd.getOptionValue("l", "");
        embedParams = cmd.getOptionValue("e", "");
        pwdFile = cmd.getOptionValue("pwdfile", "");
        ownerPwdString = cmd.getOptionValue("ownerpwd", "");
        ownerPwdFile = cmd.getOptionValue("ownerpwdfile", "");
        lastPage = !cmd.hasOption("z");

        if (cmd.getArgs().length != 0) {
            throw new ParseException(rbi18n.getString("CLI-UnknownArguments"));
        }
    } catch (ParseException e) {
        System.err.println(rbi18n.getString("CLI-WrongArguments"));
        usage.printHelp("PortableSigner", options);
        System.exit(3);
    }
    if (nogui) {
        if (input.equals("") || output.equals("") || signature.equals("")) {
            System.err.println(rbi18n.getString("CLI-MissingArguments"));
            usage.printHelp("PortableSigner", options);
            System.exit(2);
        }
        if (!help) {
            if (password.equals("")) {
                // password missing
                if (!pwdFile.equals("")) {
                    // read the password from the given file
                    try {
                        FileInputStream pwdfis = new FileInputStream(pwdFile);
                        byte[] pwd = new byte[1024];
                        password = "";
                        try {
                            do {
                                int r = pwdfis.read(pwd);
                                if (r < 0) {
                                    break;
                                }
                                password += new String(pwd);
                                password = password.trim();
                            } while (pwdfis.available() > 0);
                            pwdfis.close();
                        } catch (IOException ex) {
                        }
                    } catch (FileNotFoundException fnfex) {
                    }
                } else {
                    // no password file given, read from standard input
                    System.out.print(rbi18n.getString("CLI-MissingPassword"));
                    Console con = System.console();
                    if (con == null) {
                        byte[] pwd = new byte[1024];
                        password = "";
                        try {
                            do {
                                int r = System.in.read(pwd);
                                if (r < 0) {
                                    break;
                                }
                                password += new String(pwd);
                                password = password.trim();
                            } while (System.in.available() > 0);
                        } catch (IOException ex) {
                        }
                    } else {
                        // Console not null. Use it to read the password without echo
                        char[] pwd = con.readPassword();
                        if (pwd != null) {
                            password = new String(pwd);
                        }
                    }
                }
            }
            if (ownerPwdString.equals("") && ownerPwdFile.equals("")) {
                // no owner password or owner password file given, read from standard input
                System.out.print(rbi18n.getString("CLI-MissingOwnerPassword") + " ");
                Console con = System.console();
                if (con == null) {
                    byte[] pwd = new byte[1024];
                    String tmppassword = "";
                    try {
                        do {
                            int r = System.in.read(pwd);
                            if (r < 0) {
                                break;
                            }
                            tmppassword += new String(pwd, 0, r);
                            tmppassword = tmppassword.trim();
                        } while (System.in.available() > 0);
                    } catch (java.io.IOException ex) {
                        // TODO: perhaps notify the user
                    }
                    ownerPwd = tmppassword.getBytes();
                } else {
                    // Console not null. Use it to read the password without echo
                    char[] pwd = con.readPassword();
                    if (pwd != null) {
                        ownerPwd = new byte[pwd.length];
                        for (int i = 0; i < pwd.length; i++) {
                            ownerPwd[i] = (byte) pwd[i];
                        }
                    }
                }
            } else if (!ownerPwdString.equals("")) {
                ownerPwd = ownerPwdString.getBytes();
            } else if (!ownerPwdFile.equals("")) {
                try {
                    FileInputStream pwdfis = new FileInputStream(ownerPwdFile);
                    ownerPwd = new byte[0];
                    byte[] tmp = new byte[1024];
                    byte[] full;
                    try {
                        do {
                            int r = pwdfis.read(tmp);
                            if (r < 0) {
                                break;
                            }
                            // trim the length:
                            tmp = Arrays.copyOfRange(tmp, 0, r);
                            //System.arraycopy(tmp, 0, tmp, 0, r);
                            full = new byte[ownerPwd.length + tmp.length];
                            System.arraycopy(ownerPwd, 0, full, 0, ownerPwd.length);
                            System.arraycopy(tmp, 0, full, ownerPwd.length, tmp.length);
                            ownerPwd = full;
                        } while (pwdfis.available() > 0);
                        pwdfis.close();
                    } catch (IOException ex) {
                    }
                } catch (FileNotFoundException fnfex) {
                }
            }
        }

    }
    if (!embedParams.equals("")) {
        String[] parameter = null;
        parameter = embedParams.split(",");
        try {
            Float vPosF = new Float(parameter[0]), lMarginF = new Float(parameter[1]),
                    rMarginF = new Float(parameter[2]);
            vPos = vPosF.floatValue();
            lMargin = lMarginF.floatValue();
            rMargin = rMarginF.floatValue();
            noSigPage = true;
        } catch (NumberFormatException nfe) {
            System.err.println(rbi18n.getString("CLI-embedParameter-Error"));
            usage.printHelp("PortableSigner", options);
            System.exit(5);
        }
    }
    if (!(langcodes.contains(sigblock) || sigblock.equals(""))) {
        System.err.println(rbi18n.getString("CLI-Only-german-english") + langcodes);
        usage.printHelp("PortableSigner", options);
        System.exit(4);
    }
    if (help) {
        usage.printHelp("PortableSigner", options);
        System.exit(1);
    }
    //        System.err.println("CMDline: input: " + input);
    //        System.err.println("CMDline: output: " + output);
    //        System.err.println("CMDline: signature: " + signature);
    //        System.err.println("CMDline: password: " + password);
    //        System.err.println("CMDline: sigblock: " + sigblock);
    //        System.err.println("CMDline: sigimage: " + sigimage);
    //        System.err.println("CMDline: comment: " + comment);
    //        System.err.println("CMDline: reason: " + reason);
    //        System.err.println("CMDline: location: " + location);
    //        System.err.println("CMDline: pwdFile: " + pwdFile);
    //        System.err.println("CMDline: ownerPwdFile: " + ownerPwdFile);
    //        System.err.println("CMDline: ownerPwdString: " + ownerPwdString);
    //        System.err.println("CMDline: ownerPwd: " + ownerPwd.toString());
}

From source file:org.globus.workspace.cloud.client.util.CumulusParameterConvert.java

protected String prettyCount(long tb, int maxLen) {
    int ndx = 0;/*w w w. ja va  2s  . co m*/
    String suffix[] = { " B", "KB", "MB", "GB" };

    if (tb < 0) {
        return "Unknown";
    }

    float tbF = (float) tb;
    while (tbF > 10240.0f && ndx < suffix.length - 1) {
        ndx++;
        tbF = tbF / 1024.0f;
    }
    tb = (int) tbF;

    String rc = new Long(tb).toString();

    if (rc.length() > maxLen) {
        int endNdx = maxLen - 3;
        rc = rc.substring(0, endNdx) + "...";
    } else {
        // some silliness to get to 2 decimals
        if (rc.length() < maxLen - 2) {
            tb = (int) (tbF * 100.0f);
            tbF = (float) tb / 100.0f;
            rc = new Float(tbF).toString();
        }
        int spaceCount = maxLen - rc.length();
        for (int i = 0; i < spaceCount; i++) {
            rc = " " + rc;
        }
    }
    rc = rc + suffix[ndx];

    return rc;
}

From source file:com.discovery.darchrow.lang.ObjectUtil.java

/**
 * object to float.//  ww w . j a v  a 2s.c  o m
 * 
 * @param value
 *            the value
 * @return the float
 */
public static final Float toFloat(Object value) {
    if (Validator.isNullOrEmpty(value)) {
        return null;
    }

    if (value instanceof Float) {
        return (Float) value;
    }
    return new Float(value.toString());
}

From source file:es.caib.zkib.jxpath.util.BasicTypeConverter.java

/**
 * Convert null to a primitive type./* w  w w.  j a  v a2  s  .  c o m*/
 * @param toType destination class
 * @return a wrapper
 */
protected Object convertNullToPrimitive(Class toType) {
    if (toType == boolean.class) {
        return Boolean.FALSE;
    }
    if (toType == char.class) {
        return new Character('\0');
    }
    if (toType == byte.class) {
        return new Byte((byte) 0);
    }
    if (toType == short.class) {
        return new Short((short) 0);
    }
    if (toType == int.class) {
        return new Integer(0);
    }
    if (toType == long.class) {
        return new Long(0L);
    }
    if (toType == float.class) {
        return new Float(0.0f);
    }
    if (toType == double.class) {
        return new Double(0.0);
    }
    return null;
}