Example usage for java.lang Number longValue

List of usage examples for java.lang Number longValue

Introduction

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

Prototype

public abstract long longValue();

Source Link

Document

Returns the value of the specified number as a long .

Usage

From source file:javadz.beanutils.converters.NumberConverter.java

/**
 * Convert any Number object to the specified type for this
 * <i>Converter</i>.//www .j  av a  2  s.  com
 * <p>
 * This method handles conversion to the following types:
 * <ul>
 *     <li><code>java.lang.Byte</code></li>
 *     <li><code>java.lang.Short</code></li>
 *     <li><code>java.lang.Integer</code></li>
 *     <li><code>java.lang.Long</code></li>
 *     <li><code>java.lang.Float</code></li>
 *     <li><code>java.lang.Double</code></li>
 *     <li><code>java.math.BigDecimal</code></li>
 *     <li><code>java.math.BigInteger</code></li>
 * </ul>
 * @param sourceType The type being converted from
 * @param targetType The Number type to convert to
 * @param value The Number to convert.
 *
 * @return The converted value.
 */
private Number toNumber(Class sourceType, Class targetType, Number value) {

    // Correct Number type already
    if (targetType.equals(value.getClass())) {
        return value;
    }

    // Byte
    if (targetType.equals(Byte.class)) {
        long longValue = value.longValue();
        if (longValue > Byte.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        if (longValue < Byte.MIN_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too small " + toString(targetType));
        }
        return new Byte(value.byteValue());
    }

    // Short
    if (targetType.equals(Short.class)) {
        long longValue = value.longValue();
        if (longValue > Short.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        if (longValue < Short.MIN_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too small " + toString(targetType));
        }
        return new Short(value.shortValue());
    }

    // Integer
    if (targetType.equals(Integer.class)) {
        long longValue = value.longValue();
        if (longValue > Integer.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        if (longValue < Integer.MIN_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too small " + toString(targetType));
        }
        return new Integer(value.intValue());
    }

    // Long
    if (targetType.equals(Long.class)) {
        return new Long(value.longValue());
    }

    // Float
    if (targetType.equals(Float.class)) {
        if (value.doubleValue() > Float.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        return new Float(value.floatValue());
    }

    // Double
    if (targetType.equals(Double.class)) {
        return new Double(value.doubleValue());
    }

    // BigDecimal
    if (targetType.equals(BigDecimal.class)) {
        if (value instanceof Float || value instanceof Double) {
            return new BigDecimal(value.toString());
        } else if (value instanceof BigInteger) {
            return new BigDecimal((BigInteger) value);
        } else {
            return BigDecimal.valueOf(value.longValue());
        }
    }

    // BigInteger
    if (targetType.equals(BigInteger.class)) {
        if (value instanceof BigDecimal) {
            return ((BigDecimal) value).toBigInteger();
        } else {
            return BigInteger.valueOf(value.longValue());
        }
    }

    String msg = toString(getClass()) + " cannot handle conversion to '" + toString(targetType) + "'";
    if (log().isWarnEnabled()) {
        log().warn("    " + msg);
    }
    throw new ConversionException(msg);

}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Casts provided number value to desired number type.
 *
 * @param num/*from  w ww .  j  av a  2 s.co  m*/
 *            number value to cast
 * @param clazz
 *            number class to cast number to
 * @param <T>
 *            desired number type
 * @return number value cast to desired numeric type
 */
@SuppressWarnings("unchecked")
public static <T extends Number> T castNumber(Number num, Class<T> clazz) {
    Number cNum = 0;

    if (clazz.isAssignableFrom(Long.class)) {
        cNum = num.longValue();
    } else if (clazz.isAssignableFrom(Integer.class)) {
        cNum = num.intValue();
    } else if (clazz.isAssignableFrom(Byte.class)) {
        cNum = num.byteValue();
    } else if (clazz.isAssignableFrom(Float.class)) {
        cNum = num.floatValue();
    } else if (clazz.isAssignableFrom(Double.class)) {
        cNum = num.doubleValue();
    } else if (clazz.isAssignableFrom(Short.class)) {
        cNum = num.shortValue();
    }

    return (T) cNum;
}

From source file:com.opera.core.systems.scope.services.ums.EcmaScriptDebugger.java

protected Object parseNumber(String value) {
    Number number;
    try {/* w ww  .  j  a v a 2s . c  o  m*/
        number = NumberFormat.getInstance().parse(value);
        if (number instanceof Long)
            return number.longValue();
        else
            return number.doubleValue();
    } catch (ParseException e) {
        throw new WebDriverException("The result from the script can not be parsed");
    }
}

From source file:io.fabric8.apiman.rest.Kubernetes2ApimanFilter.java

/**
 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
 *///from  w ww .  j  a  va  2s . c om
@Override
public void init(FilterConfig config) throws ServletException {
    // maximum 10000 tokens in the cache
    Number nsCacheMaxsize = Systems.getEnvVarOrSystemProperty(NS_CACHE_MAXSIZE, 10000);
    // cache for 60  min
    Number nsTTL = Systems.getEnvVarOrSystemProperty(NS_TTL, 10);
    if (nsCache == null) {
        nsCache = CacheBuilder.newBuilder().concurrencyLevel(4) // allowed concurrency among update operations
                .maximumSize(nsCacheMaxsize.longValue()).expireAfterWrite(nsTTL.longValue(), TimeUnit.MINUTES)
                .build(new CacheLoader<String, ApimanInfo>() {
                    public ApimanInfo load(String authToken) throws Exception {
                        return syncKubernetesToApiman(authToken);
                    }
                });
    }
    boolean isTestMode = getSystemPropertyOrEnvVar(ApimanStarter.APIMAN_TESTMODE, false);
    if (!isTestMode && !isWatching) {
        watchNamespaces();
    }

}

From source file:net.solarnetwork.node.power.impl.sma.sunnynet.SMASunnyNetPowerDatumDataSource.java

@Override
public GeneralNodeACEnergyDatum conductConversation(ConversationalDataCollector dataCollector) {
    SmaPacket req = null;/*  www.  j  a v  a 2s .co  m*/
    SmaPacket resp = null;
    if (this.smaAddress < 0 || this.channelMap == null) {
        // Issue NetStart command to find SMA address
        req = writeCommand(dataCollector, SmaCommand.NetStart, 0, 0, SmaControl.RequestGroup,
                SmaPacket.EMPTY_DATA);
        resp = decodeResponse(dataCollector, req);
        if (log.isTraceEnabled()) {
            log.trace("Got decoded NetStart response: " + resp);
        }
        if (!resp.isValid()) {
            log.warn("Invalid response to NetStart command, cannot continue: " + resp);
            return null;
        }
        // TODO handle multiple device responses, for now we only accept one

        // Issue GetChannelInfo command, to get full list of available channels
        // This returns a lot of data... so we just do it once and cache the 
        // results for subsequent use
        this.smaAddress = resp.getSrcAddress();
        req = writeCommand(dataCollector, SmaCommand.GetChannelInfo, this.smaAddress, 0,
                SmaControl.RequestSingle, SmaPacket.EMPTY_DATA);
        resp = decodeResponse(dataCollector, req);
        if (!resp.isValid()) {
            log.warn("Invalid response to GetChannelInfo command, cannot continue: " + resp);
            return null;
        }
        Map<String, SmaChannel> channels = getSmaChannelMap(resp);
        if (log.isTraceEnabled()) {
            log.trace("Got decoded GetChannelInfo response: " + resp + ", with " + channels.size()
                    + " channels decoded");
        }
        this.channelMap = channels;
    }

    // Issue SynOnline command
    int pollTime = (int) Math.ceil(System.currentTimeMillis() / 1000.0);
    req = writeProclamation(dataCollector, SmaCommand.SynOnline, 0, 0, SmaControl.RequestGroup,
            SmaUtils.littleEndianBytes(pollTime));

    // pause for a few secs, as first channel may not respond otherwise
    try {
        Thread.sleep(this.synOnlineWaitMs);
    } catch (InterruptedException e) {
        // ignore this one
    }

    GeneralNodeACEnergyDatum datum = new GeneralNodeACEnergyDatum();
    datum.setSourceId(this.sourceId);

    // Issue GetData command for each channel we're interested in
    Number pvVolts = getNumericDataValue(dataCollector, this.pvVoltsChannelName, Float.class);
    Number pvAmps = getNumericDataValue(dataCollector, this.pvAmpsChannelName, Float.class);
    if (pvVolts != null && pvAmps != null) {
        datum.setWatts(Math.round(pvVolts.floatValue() * pvAmps.floatValue()));
    }

    Number wh = getNumericDataValue(dataCollector, this.kWhChannelName, Double.class);
    if (wh != null) {
        datum.setWattHourReading(wh.longValue());
    }

    return datum;
}

From source file:email.schaal.ocreader.ListActivity.java

@Override
public void onLoadMore(@NonNull TreeItem treeItem) {
    final Number minId = getRealm().where(TemporaryFeed.class).findFirst().getItems().where().min(Item.ID);

    // minId is null if there are no feed items in treeItem
    SyncService.startLoadMore(this, treeItem.getId(), minId != null ? minId.longValue() : 0,
            treeItem instanceof Feed);
}

From source file:de.tuberlin.uebb.jbop.optimizer.arithmetic.ArithmeticExpressionInterpreter.java

private AbstractInsnNode handleDiv(final int opcode, final Number one, final Number two) {
    final Number number;
    switch (opcode) {
    case IDIV:// ww  w  . j a v a 2  s  .c  om
        number = Integer.valueOf(one.intValue() / two.intValue());
        break;
    case DDIV:
        number = Double.valueOf(one.doubleValue() / two.doubleValue());
        break;
    case FDIV:
        number = Float.valueOf(one.floatValue() / two.floatValue());
        break;
    case LDIV:
        number = Long.valueOf(one.longValue() / two.longValue());
        break;
    default:
        return null;
    }
    return NodeHelper.getInsnNodeFor(number);
}

From source file:de.tuberlin.uebb.jbop.optimizer.arithmetic.ArithmeticExpressionInterpreter.java

private AbstractInsnNode handleMul(final int opcode, final Number one, final Number two) {
    final Number number;
    switch (opcode) {
    case IMUL://from ww  w.  j  a  va  2s .co m
        number = Integer.valueOf(one.intValue() * two.intValue());
        break;
    case DMUL:
        number = Double.valueOf(one.doubleValue() * two.doubleValue());
        break;
    case FMUL:
        number = Float.valueOf(one.floatValue() * two.floatValue());
        break;
    case LMUL:
        number = Long.valueOf(one.longValue() * two.longValue());
        break;
    default:
        return null;
    }
    return NodeHelper.getInsnNodeFor(number);
}

From source file:de.tuberlin.uebb.jbop.optimizer.arithmetic.ArithmeticExpressionInterpreter.java

private AbstractInsnNode handleSub(final int opcode, final Number one, final Number two) {
    final Number number;
    switch (opcode) {
    case ISUB:/*  w  ww  .  ja v a2  s  . c o m*/
        number = Integer.valueOf(one.intValue() - two.intValue());
        break;
    case DSUB:
        number = Double.valueOf(one.doubleValue() - two.doubleValue());
        break;
    case FSUB:
        number = Float.valueOf(one.floatValue() - two.floatValue());
        break;
    case LSUB:
        number = Long.valueOf(one.longValue() - two.longValue());
        break;
    default:
        return null;
    }
    return NodeHelper.getInsnNodeFor(number);
}

From source file:de.tuberlin.uebb.jbop.optimizer.arithmetic.ArithmeticExpressionInterpreter.java

private AbstractInsnNode handleAdd(final int opcode, final Number one, final Number two) {
    final Number number;
    switch (opcode) {
    case IADD://w  w  w.jav  a2 s .  c o  m
        number = Integer.valueOf(one.intValue() + two.intValue());
        break;
    case DADD:
        number = Double.valueOf(one.doubleValue() + two.doubleValue());
        break;
    case FADD:
        number = Float.valueOf(one.floatValue() + two.floatValue());
        break;
    case LADD:
        number = Long.valueOf(one.longValue() + two.longValue());
        break;
    default:
        return null;
    }
    return NodeHelper.getInsnNodeFor(number);
}