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:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java

public void doDispatch(UMOEvent event) throws Exception {
    StateAwareSocket socket = null;//from   w w w. j  av a 2s.  c  om
    boolean success = false;
    Exception exceptionWriting = null;
    String exceptionMessage = "";
    String endpointUri = event.getEndpoint().getEndpointURI().toString();

    MessageObject messageObject = messageObjectController.getMessageObjectFromEvent(event);
    if (messageObject == null) {
        return;
    }

    String host = replacer.replaceURLValues(endpointUri, messageObject);

    try {
        if (connector.isUsePersistentQueues()) {
            connector.putMessageInQueue(event.getEndpoint().getEndpointURI(), messageObject);
            return;
        } else {
            int retryCount = -1;
            int maxRetries = connector.getMaxRetryCount();
            while (!success && !disposed && (retryCount < maxRetries)) {

                monitoringController.updateStatus(connector, connectorType, Event.ATTEMPTING, socket);

                if (maxRetries != TcpConnector.KEEP_RETRYING_INDEFINETLY) {
                    retryCount++;
                }
                try {
                    if (!connector.isKeepSendSocketOpen()) {
                        socket = initSocket(host);

                        writeTemplatedData(socket, messageObject);
                        success = true;
                    } else {
                        socket = connectedSockets.get(host);

                        // Dispose the socket if the remote side closed it
                        if (socket != null && socket.remoteSideHasClosed()) {
                            doDispose(socket);
                            socket = null;
                        }

                        if (socket != null && !socket.isClosed()) {
                            try {
                                writeTemplatedData(socket, messageObject);
                                success = true;
                            } catch (Exception e) {
                                // if the connection was lost, try creating
                                // it again
                                doDispose(socket);
                                socket = initSocket(host);
                                writeTemplatedData(socket, messageObject);
                                success = true;
                            }
                        } else {
                            socket = initSocket(host);

                            writeTemplatedData(socket, messageObject);
                            success = true;
                        }
                    }
                } catch (Exception exs) {
                    if (retryCount < maxRetries) {
                        if (socket != null) {
                            doDispose(socket);
                        }
                        logger.warn("Can't connect to the endpoint: "
                                + channelController.getDeployedChannelById(connector.getChannelId()).getName()
                                + " - " + channelController.getDeployedDestinationName(connector.getName())
                                + " \r\nWaiting " + new Float(connector.getReconnectMillisecs() / 1000)
                                + " seconds before reconnecting... \r\n(" + exs + ")");
                        try {
                            Thread.sleep(connector.getReconnectMillisecs());
                        } catch (Throwable t) {
                            exceptionMessage = "Unable to send message. Too many retries";
                            logger.error("Sending interrupption. Payload not sent");
                            retryCount = maxRetries + 1;
                            exceptionWriting = exs;
                        }
                    } else {
                        exceptionMessage = "Unable to connect to destination";
                        logger.error("Can't connect to the endpoint: "
                                + channelController.getDeployedChannelById(connector.getChannelId()).getName()
                                + " - " + channelController.getDeployedDestinationName(connector.getName())
                                + " \r\nPayload not sent");
                        exceptionWriting = exs;
                    }
                }
            }
        }
    } catch (Exception exu) {
        exceptionMessage = exu.getMessage();
        alertController.sendAlerts(((MllpConnector) connector).getChannelId(), Constants.ERROR_408, null, exu);
        logger.error("Unknown exception dispatching " + exu);
        exceptionWriting = exu;
    } finally {

    }
    if (!success) {
        messageObjectController.setError(messageObject, Constants.ERROR_408, exceptionMessage, exceptionWriting,
                null);
        alertController.sendAlerts(((MllpConnector) connector).getChannelId(), Constants.ERROR_408,
                exceptionMessage, exceptionWriting);
    }
    if (success && (exceptionWriting == null)) {
        manageResponseAck(socket, host, messageObject);
        if (!connector.isKeepSendSocketOpen()) {
            monitoringController.updateStatus(connector, connectorType, Event.DISCONNECTED, socket);
            doDispose();
        }
    }
}

From source file:com.gisgraphy.importer.GeonamesZipCodeImporterTest.java

@Test
public void findFeatureExtendedThenBasicWithOutResult() {
    String lat = "3.5";
    String lng = "44";
    String accuracy = "5";
    String placeName = "place name";
    String countryCode = "FR";
    String adm1Name = "adm1name";
    String adm1Code = "adm1code";
    String adm2Name = "adm2name";
    String adm2Code = "adm2code";
    String adm3Name = "adm3name";
    String adm3COde = "adm3code";
    FulltextQuery fulltextQuery = new FulltextQuery(placeName + " " + adm1Name);
    fulltextQuery.limitToCountryCode(countryCode);
    fulltextQuery.withPlaceTypes(com.gisgraphy.fulltext.Constants.CITY_AND_CITYSUBDIVISION_PLACETYPE);

    GeonamesZipCodeSimpleImporter importer = new GeonamesZipCodeSimpleImporter() {

        @Override//from ww w .j ava  2 s  .  c om
        protected FulltextResultsDto doAFulltextSearch(String query, String countryCode) {
            count.append("_");
            return new FulltextResultsDto();
        }
    };
    String[] fields = { countryCode, "post", placeName, adm1Name, adm1Code, adm2Name, adm2Code, adm3Name,
            adm3COde, lat, lng, accuracy };
    Point point = GeolocHelper.createPoint(new Float(lng), new Float(lat));
    int maxDistance = importer.getAccurateDistance(new Integer(accuracy));
    Assert.assertNull(importer.findFeature(fields, point, maxDistance));
    Assert.assertEquals(2, count.toString().length());

}

From source file:blue.mixer.Channel.java

public void firePropertyChange(String propertyName, float oldVal, float newVal) {
    firePropertyChange(propertyName, new Float(oldVal), new Float(newVal));
}

From source file:com.player.BasicMP3Player.java

/**
 * Inits AudioInputStream and AudioFileFormat from the data source.
 * /*from w w  w .  ja v a2s .com*/
 * @throws BasicPlayerException
 */
private void initAudioInputStream() throws BasicPlayerException {
    try {
        reset();
        notifyEvent(BasicPlayerEvent.OPENING, getEncodedStreamPosition(), -1, m_dataSource);
        if (m_dataSource instanceof URL) {
            initAudioInputStream((URL) m_dataSource);
        } else if (m_dataSource instanceof File) {
            initAudioInputStream((File) m_dataSource);
        } else if (m_dataSource instanceof InputStream) {
            initAudioInputStream((InputStream) m_dataSource);
        }
        createLine();
        // Notify listeners with AudioFileFormat properties.
        Map properties = null;
        if (m_audioFileFormat instanceof TAudioFileFormat) {
            // Tritonus SPI compliant audio file format.
            properties = ((TAudioFileFormat) m_audioFileFormat).properties();
            // Clone the Map because it is not mutable.
            properties = deepCopy(properties);
        } else
            properties = new HashMap();
        // Add JavaSound properties.
        if (m_audioFileFormat.getByteLength() > 0)
            properties.put("audio.length.bytes", new Integer(m_audioFileFormat.getByteLength()));
        if (m_audioFileFormat.getFrameLength() > 0)
            properties.put("audio.length.frames", new Integer(m_audioFileFormat.getFrameLength()));
        if (m_audioFileFormat.getType() != null)
            properties.put("audio.type", (m_audioFileFormat.getType().toString()));
        // Audio format.
        AudioFormat audioFormat = m_audioFileFormat.getFormat();
        if (audioFormat.getFrameRate() > 0)
            properties.put("audio.framerate.fps", new Float(audioFormat.getFrameRate()));
        if (audioFormat.getFrameSize() > 0)
            properties.put("audio.framesize.bytes", new Integer(audioFormat.getFrameSize()));
        if (audioFormat.getSampleRate() > 0)
            properties.put("audio.samplerate.hz", new Float(audioFormat.getSampleRate()));
        if (audioFormat.getSampleSizeInBits() > 0)
            properties.put("audio.samplesize.bits", new Integer(audioFormat.getSampleSizeInBits()));
        if (audioFormat.getChannels() > 0)
            properties.put("audio.channels", new Integer(audioFormat.getChannels()));
        if (audioFormat instanceof TAudioFormat) {
            // Tritonus SPI compliant audio format.
            Map addproperties = ((TAudioFormat) audioFormat).properties();
            properties.putAll(addproperties);
        }
        Iterator it = m_listeners.iterator();
        while (it.hasNext()) {
            BasicPlayerListener bpl = (BasicPlayerListener) it.next();
            bpl.opened(m_dataSource, properties);
        }
        m_status = OPENED;
        notifyEvent(BasicPlayerEvent.OPENED, getEncodedStreamPosition(), -1, null);
    } catch (LineUnavailableException e) {
        throw new BasicPlayerException(e);
    } catch (UnsupportedAudioFileException e) {
        throw new BasicPlayerException(e);
    } catch (IOException e) {
        throw new BasicPlayerException(e);
    }
}

From source file:com.alibaba.otter.node.etl.common.db.utils.SqlUtils.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value
 * type.//from  w  w  w  . j  av a 2s. co m
 * <p>
 * Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>
 * Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * 
 * @param rs is the ResultSet holding the data
 * @param index is the column index
 * @param requiredType the required value type (may be <code>null</code>)
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 */
private static String getResultSetValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value = null;
    boolean wasNullCheck = false;

    // Explicitly extract typed value, as far as possible.
    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = Boolean.valueOf(rs.getBoolean(index));
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = new Byte(rs.getByte(index));
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = new Short(rs.getShort(index));
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = new Long(rs.getLong(index));
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = new Float(rs.getFloat(index));
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = new Double(rs.getDouble(index));
        wasNullCheck = true;
    } else if (java.sql.Time.class.equals(requiredType)) {
        // try {
        // value = rs.getTime(index);
        // } catch (SQLException e) {
        value = rs.getString(index);// ?string0000Time
        // if (value == null && !rs.wasNull()) {
        // value = "00:00:00"; //
        // mysqlzeroDateTimeBehavior=convertToNull0null
        // }
        // }
    } else if (java.sql.Timestamp.class.equals(requiredType) || java.sql.Date.class.equals(requiredType)) {
        // try {
        // value = convertTimestamp(rs.getTimestamp(index));
        // } catch (SQLException e) {
        // ?string0000-00-00 00:00:00Timestamp 
        value = rs.getString(index);
        // if (value == null && !rs.wasNull()) {
        // value = "0000:00:00 00:00:00"; //
        // mysqlzeroDateTimeBehavior=convertToNull0null
        // }
        // }
    } else if (BigDecimal.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (BigInteger.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (Blob.class.equals(requiredType)) {
        value = rs.getBlob(index);
    } else if (Clob.class.equals(requiredType)) {
        value = rs.getClob(index);
    } else if (byte[].class.equals(requiredType)) {
        try {
            byte[] bytes = rs.getBytes(index);
            if (bytes == null) {
                value = null;
            } else {
                value = new String(bytes, "ISO-8859-1");// binaryiso-8859-1
            }
        } catch (UnsupportedEncodingException e) {
            throw new SQLException(e);
        }
    } else {
        // Some unknown type desired -> rely on getObject.
        value = getResultSetValue(rs, index);
    }

    // Perform was-null check if demanded (for results that the
    // JDBC driver returns as primitives).
    if (wasNullCheck && (value != null) && rs.wasNull()) {
        value = null;
    }

    return (value == null) ? null : convertUtilsBean.convert(value);
}

From source file:dsd.dao.CalculatedDataDAO.java

private static Object[][] PrepareMultipleValuesForUpdate(List<CalculatedData> listOfData) {
    Object[][] valueArray = new Object[listOfData.size()][21];
    for (int i = 0; i < listOfData.size(); i++) {
        valueArray[i][0] = new Float(listOfData.get(i).getCalulcatedDataID());
        valueArray[i][1] = new Float(listOfData.get(i).getWindSpeed());
        valueArray[i][2] = new Float(listOfData.get(i).getWindDirection());
        valueArray[i][3] = new Float(listOfData.get(i).getWindSpeedMax());
        valueArray[i][4] = new Float(listOfData.get(i).getWindDirectionMax());
        valueArray[i][5] = new Float(listOfData.get(i).getHydrometer());
        valueArray[i][6] = new Float(listOfData.get(i).getHydrometerVariance());
        valueArray[i][7] = new Float(listOfData.get(i).getSonar());
        valueArray[i][8] = new Float(listOfData.get(i).getSonarVariance());
        valueArray[i][9] = new Float(listOfData.get(i).getSonarPercCorrect());
        valueArray[i][10] = new Float(listOfData.get(i).getSonarPercWrong());
        valueArray[i][11] = new Float(listOfData.get(i).getSonarPercOutOfWater());
        valueArray[i][12] = new Float(listOfData.get(i).getSonarPercError());
        valueArray[i][13] = new Float(listOfData.get(i).getSonarPercUncertain());
        valueArray[i][14] = new Float(listOfData.get(i).getSafetyFactor00());
        valueArray[i][15] = new Float(listOfData.get(i).getSafetyFactor01());
        valueArray[i][16] = new Float(listOfData.get(i).getSafetyFactor10());
        valueArray[i][17] = new Float(listOfData.get(i).getSafetyFactor11());
        valueArray[i][18] = new Float(listOfData.get(i).getWaterSpeed());
        valueArray[i][19] = new Float(listOfData.get(i).getWaterFlowRate());
        valueArray[i][20] = new Timestamp(listOfData.get(i).getTimestamp());
    }/*from w  w  w  .j  a  va 2s. c  om*/
    return valueArray;
}

From source file:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  Checks if the value can safely be converted to a float primitive.
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The locale to use to parse the number (system default if
 *      null)/*w  ww .j  a  v a2s .  c o m*/
 *@return the converted Float value.
 */
public static Float formatFloat(String value, Locale locale) {
    Float result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getInstance(locale);
        } else {
            formatter = NumberFormat.getInstance(Locale.getDefault());
        }
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error      and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= (Float.MAX_VALUE * -1) && num.doubleValue() <= Float.MAX_VALUE) {
                result = new Float(num.floatValue());
            }
        }
    }

    return result;
}

From source file:com.emc.plants.service.impl.ReportGeneratorBean.java

/** 
 * Run the report to get the top zip codes for a range of dates.
 *
 * @param startdate Start of date range.
 * @param enddate End of date range./*  ww  w .  j a  va  2 s. c  om*/
 * @param quantity Number of items to return in report.
 * @param reportFormat - Report format information.
 * @return Report containing results.
 */
@SuppressWarnings("unchecked")
public Report getTopSellingZipsForDates(java.util.Date startdate, java.util.Date enddate, int quantity,
        ReportFormat reportFormat) {
    Report report = null;
    Connection conn = null;
    ResultSet results = null;
    PreparedStatement sqlStatement = null;
    try {
        // Establish connection to datasource.
        String orderInfoTableName = "ORDER1";

        DataSource ds = (DataSource) Util.getInitialContext().lookup("jdbc/PlantsByWebSphereDataSource");
        conn = ds.getConnection();

        // Set sort order of ascending or descending.
        String sortOrder;
        if (reportFormat.isAscending())
            sortOrder = "ASC";
        else
            sortOrder = "DESC";

        // Set up where by clause.
        String startDateString = Long.toString(startdate.getTime());
        if (startDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - startDateString.length()), 14, startDateString);
            startDateString = sb.toString();
        }
        String endDateString = Long.toString(enddate.getTime());
        if (endDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - endDateString.length()), 14, endDateString);
            endDateString = sb.toString();
        }
        String whereString = " WHERE sellDate BETWEEN '" + startDateString + "' AND '" + endDateString + "' ";

        // Create SQL statement.
        String sqlString = "SELECT billZip, SUM(profit) AS PROFITS FROM " + orderInfoTableName + whereString
                + " GROUP BY billZip ORDER BY PROFITS " + sortOrder + ", billZip";

        Util.debug("sqlstring=" + sqlString + "=");
        sqlStatement = conn.prepareStatement(sqlString);
        results = sqlStatement.executeQuery();
        int i;

        // Initialize vectors to store data in.
        Vector[] vecs = new Vector[2];
        for (i = 0; i < vecs.length; i++) {
            vecs[i] = new Vector();
        }

        // Sift thru results.
        int count = 0;
        while ((results.next()) && (count < quantity)) {
            count++;
            i = 1;
            vecs[0].addElement(results.getString(i++));
            vecs[1].addElement(new Float(results.getFloat(i++)));
        }

        // Create report.
        report = new Report();
        report.setReportFieldByRow(Report.ORDER_BILLZIP, vecs[0]);
        report.setReportFieldByRow(Report.PROFITS, vecs[1]);
    } catch (NamingException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally { // Clean up.
        try {
            if (results != null)
                results.close();
        } catch (Exception ignore) {
        }

        try {
            if (sqlStatement != null)
                sqlStatement.close();
        } catch (Exception ignore) {
        }

        // Close Connection.
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ignore) {
        }
    }

    return report;
}

From source file:com.emc.plants.utils.Util.java

/**
 * Get the shipping method strings, including prices and times, in an array.
 * @return The shipping method strings, including prices and times, in an array.
 *//*from w  w  w .j a  v a2 s  . c  o m*/
static public String[] getFullShippingMethodStrings() {
    String[] shippingMethods = new String[SHIPPING_METHOD_STRINGS.length];
    for (int i = 0; i < shippingMethods.length; i++) {
        shippingMethods[i] = SHIPPING_METHOD_STRINGS[i] + " " + SHIPPING_METHOD_TIMES[i] + " " + NumberFormat
                .getCurrencyInstance(java.util.Locale.US).format(new Float(SHIPPING_METHOD_PRICES[i]));
    }
    return shippingMethods;
}

From source file:au.org.ala.delta.translation.dist.DistItemsFileWriter.java

private void encodeNumericAttribute(ByteBuffer work, int wordOffset, IdentificationKeyCharacter keyChar,
        NumericAttribute attribute) {/*  w w  w.j  av a 2 s  . c  om*/
    List<NumericRange> ranges = attribute.getNumericValue();
    List<Double> values = new ArrayList<Double>();

    for (NumericRange range : ranges) {
        values.add(range.middle());

    }
    double average = average(values);
    work.putFloat(wordOffset * 4, new Float(average));
}