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:com.erudika.para.utils.Utils.java

/**
 * Abbreviates an integer by adding a letter suffix at the end.
 * E.g. "M" for millions, "K" for thousands, etc.
 * @param number a big integer//  w w w  .j  a v  a2  s . co m
 * @param decPlaces decimal places
 * @return the rounded integer as a string
 */
public static String abbreviateInt(Number number, int decPlaces) {
    if (number == null) {
        return "";
    }
    String abbrevn = number.toString();
    // 2 decimal places => 100, 3 => 1000, etc
    decPlaces = (int) Math.pow(10, decPlaces);
    // Enumerate number abbreviations
    String[] abbrev = { "K", "M", "B", "T" };
    boolean done = false;
    // Go through the array backwards, so we do the largest first
    for (int i = abbrev.length - 1; i >= 0 && !done; i--) {
        // Convert array index to "1000", "1000000", etc
        int size = (int) Math.pow(10, (i + 1) * 3);
        // If the number is bigger or equal do the abbreviation
        if (size <= number.intValue()) {
            // Here, we multiply by decPlaces, round, and then divide by decPlaces.
            // This gives us nice rounding to a particular decimal place.
            number = Math.round(number.intValue() * decPlaces / size) / decPlaces;
            // Add the letter for the abbreviation
            abbrevn = number + abbrev[i];
            // We are done... stop
            done = true;
        }
    }
    return abbrevn;
}

From source file:com.scit.sling.test.MockValueMap.java

@SuppressWarnings("unchecked")
private <T> T convertType(Object o, Class<T> type) {
    if (o == null) {
        return null;
    }//from w w  w  .  j ava 2s .c om
    if (o.getClass().isArray() && type.isArray()) {
        if (type.getComponentType().isAssignableFrom(o.getClass().getComponentType())) {
            return (T) o;
        } else {
            // we need to convert the elements in the array
            Object array = Array.newInstance(type.getComponentType(), Array.getLength(o));
            for (int i = 0; i < Array.getLength(o); i++) {
                Array.set(array, i, convertType(Array.get(o, i), type.getComponentType()));
            }
            return (T) array;
        }
    }
    if (o.getClass().isAssignableFrom(type)) {
        return (T) o;
    }
    if (String.class.isAssignableFrom(type)) {
        // Format dates
        if (o instanceof Calendar) {
            return (T) formatDate((Calendar) o);
        } else if (o instanceof Date) {
            return (T) formatDate((Date) o);
        } else if (o instanceof DateTime) {
            return (T) formatDate((DateTime) o);
        }
        return (T) String.valueOf(o);
    } else if (o instanceof DateTime) {
        DateTime dt = (DateTime) o;
        if (Calendar.class.isAssignableFrom(type)) {
            return (T) dt.toCalendar(Locale.getDefault());
        } else if (Date.class.isAssignableFrom(type)) {
            return (T) dt.toDate();
        } else if (Number.class.isAssignableFrom(type)) {
            return convertType(dt.getMillis(), type);
        }
    } else if (o instanceof Number && Number.class.isAssignableFrom(type)) {
        if (Byte.class.isAssignableFrom(type)) {
            return (T) (Byte) ((Number) o).byteValue();
        } else if (Double.class.isAssignableFrom(type)) {
            return (T) (Double) ((Number) o).doubleValue();
        } else if (Float.class.isAssignableFrom(type)) {
            return (T) (Float) ((Number) o).floatValue();
        } else if (Integer.class.isAssignableFrom(type)) {
            return (T) (Integer) ((Number) o).intValue();
        } else if (Long.class.isAssignableFrom(type)) {
            return (T) (Long) ((Number) o).longValue();
        } else if (Short.class.isAssignableFrom(type)) {
            return (T) (Short) ((Number) o).shortValue();
        } else if (BigDecimal.class.isAssignableFrom(type)) {
            return (T) new BigDecimal(o.toString());
        }
    } else if (o instanceof Number && type.isPrimitive()) {
        final Number num = (Number) o;
        if (type == byte.class) {
            return (T) new Byte(num.byteValue());
        } else if (type == double.class) {
            return (T) new Double(num.doubleValue());
        } else if (type == float.class) {
            return (T) new Float(num.floatValue());
        } else if (type == int.class) {
            return (T) new Integer(num.intValue());
        } else if (type == long.class) {
            return (T) new Long(num.longValue());
        } else if (type == short.class) {
            return (T) new Short(num.shortValue());
        }
    } else if (o instanceof String && Number.class.isAssignableFrom(type)) {
        if (Byte.class.isAssignableFrom(type)) {
            return (T) new Byte((String) o);
        } else if (Double.class.isAssignableFrom(type)) {
            return (T) new Double((String) o);
        } else if (Float.class.isAssignableFrom(type)) {
            return (T) new Float((String) o);
        } else if (Integer.class.isAssignableFrom(type)) {
            return (T) new Integer((String) o);
        } else if (Long.class.isAssignableFrom(type)) {
            return (T) new Long((String) o);
        } else if (Short.class.isAssignableFrom(type)) {
            return (T) new Short((String) o);
        } else if (BigDecimal.class.isAssignableFrom(type)) {
            return (T) new BigDecimal((String) o);
        }
    }
    throw new NotImplementedException(
            "Can't handle conversion from " + o.getClass().getName() + " to " + type.getName());
}

From source file:org.tomitribe.tribestream.registryng.resources.EndpointHistoryResourceTest.java

@Test
public void loadRevisionHasPayload() {
    // Given: A random application
    final EndpointSearchResult searchResult = registry.withRetries(() -> {
        List<EndpointSearchResult> searchResults = getSearchPage().getResults().stream()
                .map(SearchResult::getEndpoints).flatMap(List::stream).collect(toList());
        final EndpointSearchResult result = searchResults.get(random.nextInt(searchResults.size()));
        assertNotNull("endpoint exists", em.find(Endpoint.class, result.getEndpointId()));
        return result;
    });/*from  w w w.ja  v a 2  s .co m*/

    final String applicationId = searchResult.getApplicationId();
    final String endpointId = searchResult.getEndpointId();

    final AuditReader auditReader = AuditReaderFactory.get(em);
    final Number revision = auditReader.getRevisions(Endpoint.class, endpointId).iterator().next();

    final String json = registry.target()
            .path("api/history/application/{applicationId}/endpoint/{endpointId}/{revision}")
            .resolveTemplate("applicationId", applicationId).resolveTemplate("endpointId", endpointId)
            .resolveTemplate("revision", revision.intValue()).request(MediaType.APPLICATION_JSON_TYPE)
            .get(EndpointWrapper.class).getJson();

    assertNotNull(json);
    assertFalse(json.trim().isEmpty());
    try { // valid it is json
        new ObjectMapper().readTree(json);
    } catch (final IOException e) {
        fail(e.getMessage());
    }
}

From source file:com.yifanlu.Kindle.JSONMenu.java

/**
 * Recursively reads the JSON data and converts it to a {@link LauncherAction} which contains either a
 * {@link LauncherScript} which executes a shell command when called or a {@link LauncherMenu} which contains
 * other {@link LauncherAction} items./*from  www  . ja v a  2s. c  o m*/
 *
 * @param json   The JSON object to parse
 * @param parent The menu to add the items to
 * @return The {@link LauncherAction} that is defined by the JSON data
 * @throws IOException if there are problems reading the JSON file
 */
protected LauncherAction jsonToAction(JSONObject json, LauncherMenu parent) throws IOException {
    String name = (String) json.get("name");
    Number priorityNum = (Number) json.get("priority");
    int priority;
    String action = (String) json.get("action");
    String params = (String) json.get("params");
    JSONArray items = (JSONArray) json.get("items");
    LauncherAction launcherAction;
    if (name == null)
        name = "No Text";
    if (priorityNum == null)
        priority = 0;
    else
        priority = priorityNum.intValue();
    if (items != null) {
        launcherAction = new LauncherMenu(name, priority, parent);
        KindleLauncher.LOG.debug(JSON_MENU_ITEM, new String[] { name, "submenu", "" }, "");
        Iterator it = items.iterator();
        while (it.hasNext()) {
            JSONObject itemObj = (JSONObject) it.next();
            ((LauncherMenu) launcherAction).addMenuItem(jsonToAction(itemObj, (LauncherMenu) launcherAction));
        }
    } else if (action != null) {
        if (params == null)
            params = "";
        File script;
        if (action.startsWith("/"))
            script = new File(action);
        else
            script = new File(mJsonFile.getParentFile(), action);
        launcherAction = new LauncherScript(name, priority, script, params);
        KindleLauncher.LOG.debug(JSON_MENU_ITEM, new String[] { name, action, params }, "");
    } else {
        throw new IOException("No valid action found for menu item: " + json.toJSONString());
    }
    return launcherAction;

}

From source file:de.perdoctus.ebikeconnect.gui.ActivitiesOverviewController.java

@FXML
public void initialize() {
    logger.info("Init!");

    NUMBER_FORMAT.setMaximumFractionDigits(2);

    webEngine = webView.getEngine();//from ww w  .  j  a v  a2  s .co m
    webEngine.load(getClass().getResource("/html/googleMap.html").toExternalForm());

    // Activity Headers
    activityDaysHeaderService.setOnSucceeded(event -> {
        activitiesTable.setItems(FXCollections.observableArrayList(activityDaysHeaderService.getValue()));
        activitiesTable.getSortOrder().add(tcDate);
        tcDate.setSortable(true);
    });
    activityDaysHeaderService.setOnFailed(
            event -> logger.error("Failed to obtain ActivityList!", activityDaysHeaderService.getException()));
    final ProgressDialog activityHeadersProgressDialog = new ProgressDialog(activityDaysHeaderService);
    activityHeadersProgressDialog.initModality(Modality.APPLICATION_MODAL);

    // Activity Details
    activityDetailsGroupService.setOnSucceeded(
            event -> this.currentActivityDetailsGroup.setValue(activityDetailsGroupService.getValue()));
    activityDetailsGroupService.setOnFailed(event -> logger.error("Failed to obtain ActivityDetails!",
            activityDaysHeaderService.getException()));
    final ProgressDialog activityDetailsProgressDialog = new ProgressDialog(activityDetailsGroupService);
    activityDetailsProgressDialog.initModality(Modality.APPLICATION_MODAL);

    // Gpx Export
    gpxExportService.setOnSucceeded(event -> gpxExportFinished());
    gpxExportService
            .setOnFailed(event -> handleError("Failed to generate GPX File", gpxExportService.getException()));

    tcxExportService.setOnSucceeded(event -> gpxExportFinished());
    tcxExportService
            .setOnFailed(event -> handleError("Failed to generate TCX File", tcxExportService.getException()));

    // ActivityTable
    tcDate.setCellValueFactory(param -> new SimpleObjectProperty<>(param.getValue().getDate()));
    tcDate.setCellFactory(param -> new LocalDateCellFactory());
    tcDate.setSortType(TableColumn.SortType.DESCENDING);

    tcDistance.setCellValueFactory(param -> new SimpleObjectProperty<>(param.getValue().getDistance() / 1000));
    tcDistance.setCellFactory(param -> new NumberCellFactory(1, "km"));

    tcDuration.setCellValueFactory(param -> new SimpleObjectProperty<>(param.getValue().getDrivingTime()));
    tcDuration.setCellFactory(param -> new DurationCellFactory());

    activitiesTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    activitiesTable.getSelectionModel().getSelectedItems()
            .addListener((ListChangeListener<ActivityHeaderGroup>) c -> {
                while (c.next()) {
                    if (c.wasRemoved()) {
                        for (ActivityHeaderGroup activityHeaderGroup : c.getRemoved()) {
                            lstSegments.getItems().removeAll(activityHeaderGroup.getActivityHeaders());
                        }

                    }
                    if (c.wasAdded()) {
                        for (ActivityHeaderGroup activityHeaderGroup : c.getAddedSubList()) {
                            if (activityHeaderGroup != null) { // WTF? Why can this be null!?
                                lstSegments.getItems().addAll(activityHeaderGroup.getActivityHeaders());
                            }
                        }
                    }

                }
                lstSegments.getItems().sort((o1, o2) -> o1.getStartTime().isAfter(o2.getStartTime()) ? 1 : 0);
            });

    activitiesTable.setOnMouseClicked(event -> {
        if (event.getClickCount() == 2) {
            lstSegments.getCheckModel().checkAll();
            openSelectedSections();
        }
    });

    // Segment List
    lstSegments
            .setCellFactory(listView -> new CheckBoxListCell<>(item -> lstSegments.getItemBooleanProperty(item),
                    new StringConverter<ActivityHeader>() {

                        @Override
                        public ActivityHeader fromString(String arg0) {
                            return null;
                        }

                        @Override
                        public String toString(ActivityHeader activityHeader) {
                            final String startTime = activityHeader.getStartTime().format(DATE_TIME_FORMATTER);
                            final String endTime = activityHeader.getEndTime().format(TIME_FORMATTER);
                            final double distance = activityHeader.getDistance() / 1000;
                            return startTime + " - " + endTime + " (" + NUMBER_FORMAT.format(distance) + " km)";
                        }

                    }));

    // -- Chart
    chartRangeSlider.setLowValue(0);
    chartRangeSlider.setHighValue(chartRangeSlider.getMax());

    xAxis.setAutoRanging(false);
    xAxis.lowerBoundProperty().bind(chartRangeSlider.lowValueProperty());
    xAxis.upperBoundProperty().bind(chartRangeSlider.highValueProperty());
    xAxis.tickUnitProperty().bind(
            chartRangeSlider.highValueProperty().subtract(chartRangeSlider.lowValueProperty()).divide(20));
    xAxis.setTickLabelFormatter(new StringConverter<Number>() {
        @Override
        public String toString(Number object) {
            final Duration duration = Duration.of(object.intValue(), ChronoUnit.SECONDS);
            return String.valueOf(DurationFormatter.formatHhMmSs(duration));
        }

        @Override
        public Number fromString(String string) {
            return null;
        }
    });

    chart.getChart().setOnScroll(event -> {
        final double scrollAmount = event.getDeltaY();
        chartRangeSlider.setLowValue(chartRangeSlider.getLowValue() + scrollAmount);
        chartRangeSlider.setHighValue(chartRangeSlider.getHighValue() - scrollAmount);
    });

    xAxis.setOnMouseMoved(event -> {
        if (getCurrentActivityDetailsGroup() == null) {
            return;
        }

        final Number valueForDisplay = xAxis.getValueForDisplay(event.getX());
        final List<Coordinate> trackpoints = getCurrentActivityDetailsGroup().getJoinedTrackpoints();
        final int index = valueForDisplay.intValue();
        if (index >= 0 && index < trackpoints.size()) {
            final Coordinate coordinate = trackpoints.get(index);
            if (coordinate.isValid()) {
                final LatLng latLng = new LatLng(coordinate);
                try {
                    webEngine.executeScript(
                            "updateMarkerPosition(" + objectMapper.writeValueAsString(latLng) + ");");
                } catch (JsonProcessingException e) {
                    e.printStackTrace(); //TODO clean up ugly code!!!!--------------
                }
            }
        }
    });

    // -- Current ActivityDetails
    this.currentActivityDetailsGroup.addListener((observable, oldValue, newValue) -> {
        if (newValue != null) {
            activityGroupChanged(newValue);
        }
    });
}

From source file:com.hortonworks.streamline.streams.cluster.register.impl.StormServiceRegistrar.java

private Pair<Component, List<ComponentProcess>> createNimbusComponent(Config config,
        Map<String, String> flatConfigMap) {
    if (!config.contains(PARAM_NIMBUS_SEEDS)) {
        throw new IllegalArgumentException("Required parameter " + PARAM_NIMBUS_SEEDS + " not present.");
    }/*from   w ww  .  j a v a  2s.c o m*/

    if (!config.contains(PARAM_NIMBUS_THRIFT_PORT)) {
        throw new IllegalArgumentException("Required parameter " + PARAM_NIMBUS_THRIFT_PORT + " not present.");
    }

    String nimbusSeeds;
    try {
        nimbusSeeds = config.getString(PARAM_NIMBUS_SEEDS);
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("Required parameter " + PARAM_NIMBUS_SEEDS + " should be a string.");
    }

    Number nimbusThriftPort = readNumberFromConfig(config, PARAM_NIMBUS_THRIFT_PORT);

    Component nimbus = new Component();
    nimbus.setName(COMPONENT_NIMBUS);

    List<ComponentProcess> componentProcesses = Arrays.stream(nimbusSeeds.split(",")).map(nimbusHost -> {
        ComponentProcess cp = new ComponentProcess();
        cp.setHost(nimbusHost);
        cp.setPort(nimbusThriftPort.intValue());
        return cp;
    }).collect(toList());

    return new Pair<>(nimbus, componentProcesses);
}

From source file:com.prowidesoftware.swift.model.field.Field99A.java

/**
 * Set the component3 from a Number object.
 * <br />/*from   w w  w  .j  ava2s  .  c  om*/
 * <em>If the component being set is a fixed length number, the argument will not be 
 * padded.</em> It is recommended for these cases to use the setComponent3(String) 
 * method.
 * 
 * @see #setComponent3(String)
 *
 * @param component3 the Number with the component3 content to set
 */
public Field99A setComponent3(java.lang.Number component3) {
    if (component3 != null) {
        setComponent(3, "" + component3.intValue());
    }
    return this;
}

From source file:com.pureinfo.srm.reports.table.data.institute.Index3Statitistic.java

private void addInt(Object[] _line, int _nIdx, Number _oValue) {
    if (_oValue == null)
        return;/*from  ww  w.  j a v  a 2 s. co m*/
    if (_line[_nIdx] == null || null == _line[_nIdx]) {
        _line[_nIdx] = _oValue;
    } else {
        Number num = (Number) _line[_nIdx];
        _line[_nIdx] = new Integer(_oValue.intValue() + num.intValue());
    }
}

From source file:eu.dasish.annotation.backend.dao.impl.JdbcAnnotationDaoTest.java

/**
 * Test of getInternalIDFromURI method, public Number
 * getInternalIDFromURI(UUID externalID);
 *///from ww  w  .j a  va2 s.co m
@Test
public void testGetInternalIDFRomHref() throws NotInDataBaseException {
    System.out.println("test getInternalIDFromHref");
    jdbcAnnotationDao.setResourcePath("/api/annotations/");
    String uri = "/api/annotations/00000000-0000-0000-0000-000000000021";
    Number result = jdbcAnnotationDao.getInternalIDFromHref(uri);
    assertEquals(1, result.intValue());
    assertEquals(1, result);
}

From source file:gov.nih.nci.caarray.dao.ArrayDaoImpl.java

/**
 * {@inheritDoc}/*  w  w  w .j  a  v a  2s  .c o m*/
 */
@Override
public boolean isArrayDesignLocked(final Long id) {
    final UnfilteredCallback u = new UnfilteredCallback() {
        @Override
        public Object doUnfiltered(Session s) {
            final BrowseCategory cat = BrowseCategory.ARRAY_DESIGNS;
            final StringBuffer sb = new StringBuffer();
            sb.append("SELECT COUNT(DISTINCT p) FROM ").append(Project.class.getName()).append(" p JOIN ")
                    .append(cat.getJoin()).append(" WHERE ").append(cat.getField()).append(".id = :id");
            final Query q = s.createQuery(sb.toString());
            q.setParameter("id", id);
            return q.uniqueResult();
        }
    };
    final Number count = (Number) getHibernateHelper().doUnfiltered(u);
    return count.intValue() > 0;
}