Example usage for java.lang Number intValue

List of usage examples for java.lang Number intValue

Introduction

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

Prototype

public abstract int intValue();

Source Link

Document

Returns the value of the specified number as an int .

Usage

From source file:NumberUtils.java

/**
 * Convert the given number into an instance of the given target class.
 *
 * @param number      the number to convert
 * @param targetClass the target class to convert to
 * @return the converted number/*from w  ww .j  a  v a  2  s  .  c  o m*/
 * @throws IllegalArgumentException if the target class is not supported
 *                                  (i.e. not a standard Number subclass as included in the JDK)
 * @see java.lang.Byte
 * @see java.lang.Short
 * @see java.lang.Integer
 * @see java.lang.Long
 * @see java.math.BigInteger
 * @see java.lang.Float
 * @see java.lang.Double
 * @see java.math.BigDecimal
 */
public static Number convertNumberToTargetClass(Number number, Class targetClass)
        throws IllegalArgumentException {

    if (targetClass.isInstance(number)) {
        return number;
    } else if (targetClass.equals(Byte.class)) {
        long value = number.longValue();
        if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return number.byteValue();
    } else if (targetClass.equals(Short.class)) {
        long value = number.longValue();
        if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return number.shortValue();
    } else if (targetClass.equals(Integer.class)) {
        long value = number.longValue();
        if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return number.intValue();
    } else if (targetClass.equals(Long.class)) {
        return number.longValue();
    } else if (targetClass.equals(Float.class)) {
        return number.floatValue();
    } else if (targetClass.equals(Double.class)) {
        return number.doubleValue();
    } else if (targetClass.equals(BigInteger.class)) {
        return BigInteger.valueOf(number.longValue());
    } else if (targetClass.equals(BigDecimal.class)) {
        // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double)
        // (see BigDecimal javadoc for details)
        return new BigDecimal(number.toString());
    } else {
        throw new IllegalArgumentException("Could not convert number [" + number + "] of type ["
                + number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]");
    }
}

From source file:com.espertech.esper.epl.parse.ASTContextHelper.java

public static CreateContextDesc walkCreateContext(Tree parent, Map<Tree, ExprNode> astExprNodeMap,
        Map<Tree, EvalFactoryNode> astPatternNodeMap, PropertyEvalSpec propertyEvalSpec,
        FilterSpecRaw filterSpec) {//from  ww  w. j av a2  s  .  co  m
    String contextName = parent.getChild(0).getText();
    Tree detailParent = parent.getChild(1);

    ContextDetail contextDetail;

    // temporal fixed (start+end) and overlapping (initiated/terminated)
    if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_INIT
            || detailParent.getType() == EsperEPL2Ast.CREATE_CTX_FIXED) {
        ContextDetailCondition startEndpoint;
        if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_FIXED) {
            if (detailParent.getChild(0).getType() == EsperEPL2Ast.IDENT) {
                String ident = detailParent.getChild(0).getText().toLowerCase();
                if (!ident.equals("now")) {
                    throw new ASTWalkException(
                            "Expected 'now' keyword after '@', found '" + ident + "' instead");
                }
                startEndpoint = new ContextDetailConditionImmediate();
            } else {
                startEndpoint = getContextCondition(detailParent.getChild(0), astExprNodeMap, astPatternNodeMap,
                        propertyEvalSpec, false);
            }
        } else {
            boolean immediate = false;
            if (detailParent.getChild(detailParent.getChildCount() - 1).getType() == EsperEPL2Ast.IDENT) {
                String ident = detailParent.getChild(detailParent.getChildCount() - 1).getText().toLowerCase();
                if (!ident.equals("now")) {
                    throw new ASTWalkException(
                            "Expected 'now' keyword after '@', found '" + ident + "' instead");
                }
                immediate = true;
            }
            startEndpoint = getContextCondition(detailParent.getChild(0), astExprNodeMap, astPatternNodeMap,
                    propertyEvalSpec, immediate);
        }
        ContextDetailCondition endEndpoint = getContextCondition(detailParent.getChild(1), astExprNodeMap,
                astPatternNodeMap, propertyEvalSpec, false);
        boolean overlapping = detailParent.getType() == EsperEPL2Ast.CREATE_CTX_INIT;
        contextDetail = new ContextDetailInitiatedTerminated(startEndpoint, endEndpoint, overlapping);
    }
    // categorized
    else if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_CAT) {
        List<ContextDetailCategoryItem> items = new ArrayList<ContextDetailCategoryItem>();
        for (int i = 0; i < detailParent.getChildCount() - 1; i++) {
            Tree categoryParent = detailParent.getChild(i);
            ExprNode exprNode = astExprNodeMap.remove(categoryParent.getChild(0));
            String name = categoryParent.getChild(1).getText();
            items.add(new ContextDetailCategoryItem(exprNode, name));
        }
        filterSpec = ASTExprHelper.walkFilterSpec(detailParent.getChild(detailParent.getChildCount() - 1),
                propertyEvalSpec, astExprNodeMap);
        contextDetail = new ContextDetailCategory(items, filterSpec);
    }
    // partitioned
    else if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_PART) {
        List<ContextDetailPartitionItem> rawSpecs = new ArrayList<ContextDetailPartitionItem>();
        for (int i = 0; i < detailParent.getChildCount(); i++) {

            Tree partitionParent = detailParent.getChild(i);
            filterSpec = ASTExprHelper.walkFilterSpec(partitionParent.getChild(0), propertyEvalSpec,
                    astExprNodeMap);
            propertyEvalSpec = null;

            List<String> propertyNames = new ArrayList<String>();
            for (int j = 1; j < partitionParent.getChildCount(); j++) {
                String propertyName = ASTFilterSpecHelper.getPropertyName(partitionParent.getChild(j), 0);
                propertyNames.add(propertyName);
            }

            rawSpecs.add(new ContextDetailPartitionItem(filterSpec, propertyNames));
        }
        contextDetail = new ContextDetailPartitioned(rawSpecs);
    }
    // partitioned
    else if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_COAL) {
        List<ContextDetailHashItem> rawSpecs = new ArrayList<ContextDetailHashItem>();
        int count = 0;
        for (int i = 0; i < detailParent.getChildCount(); i++) {
            Tree hashItemParent = detailParent.getChild(i);
            if (hashItemParent.getType() == EsperEPL2Ast.COALESCE) {
                count++;
                ExprChainedSpec func = ASTLibHelper.getLibFunctionChainSpec(hashItemParent.getChild(0),
                        astExprNodeMap);
                filterSpec = ASTExprHelper.walkFilterSpec(hashItemParent.getChild(1), propertyEvalSpec,
                        astExprNodeMap);
                propertyEvalSpec = null;
                rawSpecs.add(new ContextDetailHashItem(func, filterSpec));
            }
        }

        String granularity = detailParent.getChild(count).getText();
        if (!granularity.toLowerCase().equals("granularity")) {
            throw new ASTWalkException("Expected 'granularity' keyword after list of coalesce items, found '"
                    + granularity + "' instead");
        }
        Number num = (Number) ASTConstantHelper.parse(detailParent.getChild(count + 1));
        String preallocateStr = detailParent.getChildCount() - 1 < count + 2 ? null
                : detailParent.getChild(count + 2).getText();
        if (preallocateStr != null && !preallocateStr.toLowerCase().equals("preallocate")) {
            throw new ASTWalkException("Expected 'preallocate' keyword after list of coalesce items, found '"
                    + preallocateStr + "' instead");
        }
        if (!JavaClassHelper.isNumericNonFP(num.getClass())
                || JavaClassHelper.getBoxedType(num.getClass()) == Long.class) {
            throw new ASTWalkException(
                    "Granularity provided must be an int-type number, received " + num.getClass() + " instead");
        }

        contextDetail = new ContextDetailHash(rawSpecs, num.intValue(), preallocateStr != null);
    } else if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_NESTED) {
        List<CreateContextDesc> contexts = new ArrayList<CreateContextDesc>();
        for (int i = 0; i < detailParent.getChildCount(); i++) {
            Tree parentCreate = detailParent.getChild(i);
            if (parentCreate.getType() != EsperEPL2Ast.CREATE_CTX) {
                throw new IllegalStateException(
                        "Child to nested context is not a context-create but type " + parentCreate.getType());
            }
            contexts.add(walkCreateContext(parentCreate, astExprNodeMap, astPatternNodeMap, propertyEvalSpec,
                    filterSpec));
        }
        contextDetail = new ContextDetailNested(contexts);
    } else {
        throw new IllegalStateException("Unrecognized context detail type '" + detailParent.getType() + "'");
    }

    return new CreateContextDesc(contextName, contextDetail);
}

From source file:org.jongo.CommandTest.java

@Test
public void canRunACommandWithParameter() throws Exception {

    collection.withWriteConcern(WriteConcern.SAFE).insert("{test:1}");

    DBObject result = jongo.runCommand("{ count: #}", "friends").map(new RawResultHandler<DBObject>());

    Number n = (Number) result.get("n");
    assertThat(n.intValue()).isEqualTo(1);
}

From source file:com.branded.holdings.qpc.repository.jdbc.JdbcVisitRepositoryImpl.java

@Override
public void save(Visit visit) throws DataAccessException {
    if (visit.isNew()) {
        Number newKey = this.insertVisit.executeAndReturnKey(createVisitParameterSource(visit));
        visit.setId(newKey.intValue());
    } else {/*from w  w  w  .jav a  2  s .c  o  m*/
        throw new UnsupportedOperationException("Visit update not supported");
    }
}

From source file:com.bstek.dorado.data.variant.DefaultVariantConvertor.java

public int toInt(Object object) {
    Number n = (Number) intDateType.convertFromObject(object);
    return n.intValue();
}

From source file:com.sixrr.metrics.ui.charts.PieChartDialog.java

private JFreeChart createChart(PieDataset dataset) {
    final String title = getTitle();
    final PiePlot plot = new PiePlot(dataset);
    plot.setInsets(new Insets(0, 5, 5, 5));
    final int numItems = dataset.getItemCount();
    int total = 0;
    for (int i = 0; i < numItems; i++) {
        final Number value = dataset.getValue(i);
        total += value.intValue();
    }// ww  w  . j  av  a 2 s. c o m
    final PieItemLabelGenerator tooltipGenerator = new PieChartTooltipGenerator(total);
    plot.setItemLabelGenerator(tooltipGenerator);
    plot.setURLGenerator(null);
    return new JFreeChart(title, JFreeChartConstants.DEFAULT_TITLE_FONT, plot, false);
}

From source file:com.catt.mobile.repository.jdbc.JdbcAccountRepositoryImpl.java

@Override
public void save(Account account) throws DataAccessException {
    BeanPropertySqlParameterSource parameterSource = new BeanPropertySqlParameterSource(account);
    if (account.isNew()) {
        Number newKey = this.insertAccount.executeAndReturnKey(parameterSource);
        account.setId(newKey.intValue());
    } else {/*from  w w  w  . j  ava 2s. c  o m*/
        this.namedParameterJdbcTemplate.update("UPDATE account SET name=:name, address=:address, "
                + "email=:email, telephone=:telephone WHERE id=:id", parameterSource);
    }
}

From source file:com.branded.holdings.qpc.repository.jdbc.JdbcTopicRepositoryImpl.java

@Override
public void save(Topic topic) throws DataAccessException {
    if (topic.isNew()) {
        Number newKey = this.insertTopic.executeAndReturnKey(createTopicParameterSource(topic));
        topic.setId(newKey.intValue());
    } else {/*  w ww  .  ja va  2  s  .  c  o m*/
        this.namedParameterJdbcTemplate.update(
                "UPDATE topic SET  type_id=:type_id, description=:description, weight=:weight" + "WHERE id=:id",
                createTopicParameterSource(topic));
    }
}

From source file:MutableInt.java

public MutableInt(Number value) {
    super();
    this._value = value.intValue();
}

From source file:biomine.bmvis2.pipeline.SizeSliderOperation.java

@Override
public void fromJSON(JSONObject o) throws Exception {
    Number n = (Number) o.get("target");
    this.targetSize = n.intValue();
}