Example usage for java.lang Double longValue

List of usage examples for java.lang Double longValue

Introduction

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

Prototype

public long longValue() 

Source Link

Document

Returns the value of this Double as a long after a narrowing primitive conversion.

Usage

From source file:be.solidx.hot.test.TestScriptExecutors.java

@Test
public void testJSScriptExecutor1() throws Exception {
    JSScriptExecutor jsScriptExecutor = new JSScriptExecutor();
    Script<org.mozilla.javascript.Script> script = new Script<org.mozilla.javascript.Script>(
            "var i = 1; i++; hprint (i); i;".getBytes(), "test1");
    Double result = (Double) jsScriptExecutor.execute(script);
    Assert.assertEquals(2, result.longValue());
}

From source file:com.controller.schedule.ScheduleSocialPostServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w  . j  ava  2s .  c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    HttpSession session = request.getSession();
    if (session.getAttribute("UID") == null) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "User is not logged in");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().flush();
        response.setContentType("application/json");
        return;
    }
    Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
    List<Map<String, Object>> requestBodyList = AppConstants.GSON
            .fromJson(new BufferedReader(request.getReader()), List.class);
    if (requestBodyList == null || requestBodyList.isEmpty()) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Request body is missing");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }
    System.out.println(requestBodyList);
    List<String> errorMessages = validateRequestBodyList(requestBodyList);
    if (!errorMessages.isEmpty()) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", errorMessages);
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }

    /*
     If no error messages in the above validation, then next is to validate
     the JSON structure associated with the keys token_data and metadata
     */
    for (Map<String, Object> requestBodyMap : requestBodyList) {
        String tokenDataString = requestBodyMap.get("token_data").toString();
        String type = requestBodyMap.get("type").toString();
        errorMessages.addAll(validateTokenData(tokenDataString, type));
        String metadataString = requestBodyMap.get("metadata").toString();
        errorMessages.addAll(validateMetadata(metadataString, type));
    }

    if (!errorMessages.isEmpty()) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", errorMessages);
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }
    List<Map<String, Integer>> daoResponseList = new ArrayList<>();
    try (Connection conn = ConnectionManager.getInstance().getConnection()) {
        conn.setAutoCommit(false);
        try {
            for (Map<String, Object> requestBodyMap : requestBodyList) {
                Double schedule = (Double) requestBodyMap.get("schedule_time");

                Timestamp scheduleTimeStamp = new Timestamp(schedule.longValue());
                String tokenDataString = requestBodyMap.get("token_data").toString();
                String metadataString = requestBodyMap.get("metadata").toString();

                //As of now schedule description is not yet mandatory.
                String scheduleDesc = requestBodyMap.containsKey("schedule_desc")
                        ? String.valueOf(requestBodyMap.get("schedule_desc"))
                        : null;

                Map<String, Integer> daoResponse = ScheduleSocialPostDAO.addToScheduleSocialPost(userId,
                        requestBodyMap.get("image_name").toString(),
                        AppConstants.GSON.fromJson(tokenDataString, Map.class),
                        AppConstants.GSON.fromJson(metadataString, Map.class),
                        requestBodyMap.get("type").toString(), requestBodyMap.get("schedule_title").toString(),
                        scheduleDesc, scheduleTimeStamp, TemplateStatus.template_saved.toString(), conn);
                daoResponseList.add(daoResponse);
            }
            conn.commit();
        } catch (SQLException ex) {
            conn.rollback();
            throw ex;
        }
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(daoResponseList));
        response.getWriter().flush();

    } catch (SQLException ex) {
        Logger.getLogger(ScheduleSocialPostServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.tiempometa.muestradatos.TagReading.java

public TagReading(String data) {
    super();/*from   w  ww. j ava 2  s  . co m*/
    stringData = data;
    if (data.startsWith("#")) {
        readingType = TagReading.TYPE_COMMAND_RESPONSE;
        // command response
        String[] fields = data.replaceAll("\\r", "").split(",");
        switch (fields.length) {
        case 0:
            break;
        case 1:
            break;
        case 2:
            break;
        case 3:
            System.out.println("Time - " + fields[2]);
            System.out.println("Time + " + (new Date()).getTime());
            Double millis = Double.valueOf(fields[2]) * 1000;
            time = new Date(millis.longValue());
            Long diff = (new Date()).getTime() - time.getTime();
            epc = diff.toString();
            readingType = TagReading.TYPE_COMMAND_RESPONSE;
            timeMillis = time.getTime();

            break;
        }
    } else {
        readingType = TagReading.TYPE_TAG;
        String[] fields = data.replaceAll("\\r", "").split(",");
        switch (fields.length) {
        case 0:
            break;
        case 1:
            break;
        case 2:
            valid = true;
            // single field data packet is keep alive
            readingType = TagReading.TYPE_KEEP_ALIVE;
            antenna = fields[1];
            break;
        case 7:
            // six field data packet includes user data
            userData = fields[6];
        case 6:
            tid = fields[5];
        case 5:
            // five field data packet lacks user data
            valid = true;
            reader = fields[0];
            antenna = fields[1];
            epc = fields[2];
            try {
                timeMillis = Long.valueOf(fields[3]);
                time = new Date(timeMillis / 1000);
                peakRssi = Integer.parseInt(fields[4]);
            } catch (NumberFormatException e) {
                valid = false;
            }
            break;
        default:
        }
    }
}

From source file:org.globus.workspace.accounting.impls.dbdefault.DBAccountingAdapter.java

public void create(int id, String ownerDN, long minutesRequested, String network, String resource,
        String clientLaunchName, int CPUCount, int memory, double chargeRatio) {

    String moreToLog = "";

    if (resource != null) {
        moreToLog += ", vmm='" + resource.trim() + '\'';
    }//from   w w  w . j a  v a  2  s  .co m

    if (clientLaunchName != null) {
        moreToLog += ", clientLaunchName='" + clientLaunchName.trim() + '\'';
    }

    if (network != null) {
        moreToLog += ", network='" + network.trim() + '\'';
    }

    if (this.lager.accounting) {
        logger.trace("create(): id = " + id + ", ownerDN = '" + ownerDN + "', minutesRequested = "
                + minutesRequested + ", CPUCount = " + CPUCount + ", memory = " + memory + moreToLog);
    }

    if (!this.initialized) {
        logger.error("never initialized, can't do anything");
        return;
    }

    if (ownerDN == null) {
        logger.error("ownerDN is null, can't do anything");
        return;
    }

    // account for container recovery after a service state reset
    if (id == 1) {
        try {
            final int updated = this.db.forceAllInactive();

            if (updated < 0) {

                logger.error("compound, unresolvable DB problem");
                return;

            } else if (updated > 0) {

                logger.fatal("Fresh service install or service state "
                        + "was wiped: ALL previous deployments tracked "
                        + "by accounting module were moved to inactive.  "
                        + "Destruction time in this case is undefined and " + "not set!  Set " + updated
                        + " deployments to " + "inactive.");

            } else {

                logger.debug("fresh service install or service state "
                        + "was wiped, but all previous deployments were " + "already inactive: all is well");
            }

        } catch (WorkspaceDatabaseException e) {
            logger.error(e.getMessage());
            return;
        }
    }

    try {

        long charge = Util.positiveCeiling(minutesRequested, this.chargeGranularity);

        final Double chargeDouble = charge * chargeRatio;
        charge = chargeDouble.longValue();

        final String uuid = uuidGen.generateRandomBasedUUID().toString();

        final Calendar now = Calendar.getInstance();

        this.db.add(uuid, id, ownerDN, charge, now, CPUCount, memory);

        if (this.lager.eventLog) {
            logger.info(Lager.ev(id) + "accounting: ownerDN = '" + ownerDN + "', minutesRequested = "
                    + minutesRequested + ", minutes reserved = " + charge + ", charge ratio = " + chargeRatio
                    + ", CPUCount = " + CPUCount + ", memory = " + memory + ", uuid = '" + uuid + "'"
                    + moreToLog);
        }

        if (this.fileLog != null) {
            try {
                this.fileLog.logCreate(uuid, id, ownerDN, minutesRequested, charge, chargeRatio, now, CPUCount,
                        memory, moreToLog);
            } catch (WorkspaceException e) {
                if (logger.isDebugEnabled()) {
                    logger.error(e.getMessage(), e);
                } else {
                    logger.error(e.getMessage());
                }
            }
        }

    } catch (WorkspaceDatabaseException e) {
        logger.error(e.getMessage());
    }

}

From source file:fr.inria.soctrace.tools.importer.pajedump.core.PJDumpParser.java

private long getTimestamp(String ts) {
    if (doublePrecision) {
        Double timestamp = Double.parseDouble(ts);
        timestamp = Math.pow(10, precision) * timestamp;
        return timestamp.longValue();
    } else {//w  w w .  j  a v  a  2  s  .co m
        return Long.parseLong(ts);
    }
}

From source file:org.socraticgrid.displaycalendarlib.GoogleCalendar.java

/**
 * Get all events for all calendars for the given calendar account access.
 * @param userId//from  www .  j  a  v  a  2 s. c  om
 * @param pwd
 * @param accessType
 * @param feedAddress
 * @return
 * @throws MalformedURLException
 * @throws AuthenticationException
 * @throws IOException
 * @throws ServiceException 
 */
public List<CalResponse> getCalsForUser(String calUserId, String calPwd, String accessType, String feedAddress)
        throws MalformedURLException, AuthenticationException, IOException, ServiceException {

    CalendarService calService = getCalendarService(calUserId, calPwd);
    List<CalResponse> returnList = new ArrayList<CalResponse>();

    URL feedUrl = new URL(feedAddress);
    CalendarFeed resultFeed = calService.getFeed(feedUrl, CalendarFeed.class);

    //===== DBG =========
    System.out.println("===> getCalsForUser: PCAL userId/pwd=" + calUserId + "/" + calPwd);
    System.out.println("===> getCalsForUser:    getting Feed=" + feedUrl);
    System.out.println("===> getCalsForUser:      accessType=" + accessType);
    //===== DBG =========

    // Prep some return header info........
    //        StringBuilder sb = new StringBuilder();
    //        sb.append("BEGIN:VCALENDAR\n");
    //        sb.append("PRODID:-//Google Inc//Google Calendar 70.9054//EN\n");
    //        sb.append("VERSION:2.0\n");
    //        sb.append("CALSCALE:GREGORIAN\n");
    //        sb.append("METHOD:PUBLISH\n");

    //=========================================================
    // Loop through all claenders and get all events
    //=========================================================
    for (int i = 0; i < resultFeed.getEntries().size(); i++) {

        CalendarEntry entry = resultFeed.getEntries().get(i);

        System.out.println("\n===> getCalsForUser: Calendar=" + entry.getTitle().getPlainText());
        //            System.out.println("CAL Id=" + entry.getId());

        //-------------------------------------------------------
        // When being asked to retrieve only clinical calendars,
        // then skip to next one if Calendar found does NOT have
        // the word "Clinic" or "Medical" in it.
        //-------------------------------------------------------
        if (accessType.equalsIgnoreCase("Clinic") && (!entry.getTitle().getPlainText().contains("Clinic"))
                && (!entry.getTitle().getPlainText().contains("Medical"))) {
            System.out.println("===> getCalsForUser: SKIPPING Calendar: " + entry.getTitle().getPlainText());
            continue;
        }

        //---------------------------
        // Process located Calendar.
        //---------------------------
        //CalendarEntry entry = resultFeed.getEntries().get(i);
        //            sb.append("X-WR-CALNAME:").append(entry.getTitle().getPlainText()).append("\n");
        //            sb.append("X-WR-TIMEZONE:").append(entry.getTimeZone().getValue()).append("\n");

        CalResponse response = new CalResponse();

        //-------------------------------------------------------
        // DETERMINE which GUI category this calendar should be displayed under,
        // Personal or Medical, by naming convention in calendar's title.
        //-------------------------------------------------------
        if ((entry.getTitle().getPlainText().contains("Clinic"))
                || (entry.getTitle().getPlainText().contains("Medical"))) {
            response.setType("Provider");
        } else {
            response.setType("Private");
        }
        response.setEvents(new ArrayList<Events>());
        response.setTitle(entry.getTitle().getPlainText());

        String color = entry.getColor().getValue();
        response.setBackgroundColor(color);
        response.setBorderColor(color);
        response.setTextColor("#FFF");
        response.setCalendarId(entry.getId());

        //----------------------------------------------
        // Prepare the Event feed URL for this Calendar.
        //----------------------------------------------
        Link eventFeedLink = entry.getLink("http://schemas.google.com/gCal/2005#eventFeed", null);
        String eventURL = eventFeedLink.getHref();

        //            System.out.println("EventURL= "+ eventURL);

        URL eventFeedUrl = new URL(eventURL);

        CalendarQuery cq = new CalendarQuery(eventFeedUrl);
        cq.setMinimumStartTime(DateTime.parseDateTime("2011-01-01T00:00:00"));
        CalendarEventFeed eventFeed = calService.query(cq, CalendarEventFeed.class);

        Writer w = new StringWriter();
        XmlWriter writer = new XmlWriter(w);
        eventFeed.generate(writer, calService.getExtensionProfile());

        for (CalendarEventEntry event : eventFeed.getEntries()) {
            Events calEvent = new Events();
            DateTime startTime = event.getTimes().get(0).getStartTime();
            DateTime endTime = event.getTimes().get(0).getEndTime();
            Double d1 = startTime.getValue() * .001;
            Double d2 = endTime.getValue() * .001;
            calEvent.setStart(Long.toString(d1.longValue()));
            calEvent.setEnd(Long.toString(d2.longValue()));
            calEvent.setTitle(event.getTitle().getPlainText());
            calEvent.setEventId(event.getId());
            calEvent.setEditable(event.getCanEdit());
            if (endTime.getValue() - startTime.getValue() >= (1000 * 60 * 60 * 24)) {
                calEvent.setAllDay(true);
            } else {
                calEvent.setAllDay(false);
            }
            response.getEvents().add(calEvent);

            System.out.println("\tEvent: " + calEvent.getStart() + "  " + calEvent.getTitle());
        }
        returnList.add(response);

    }
    return returnList;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.excelimport.EntityDataImporter.java

private Object readPropertyValue(Cell nonEmptyCell, PropertyExpression<?> nonReleasenameProperty) {
    if (nonReleasenameProperty instanceof EnumerationPropertyExpression) {
        return getEnumPropertyValue(nonEmptyCell, nonReleasenameProperty);
    } else if (nonReleasenameProperty.getType().equals(BuiltinPrimitiveType.INTEGER)) {
        Double doubleValue = getCellValueOfType(nonEmptyCell, Double.class);
        return doubleValue == null ? null : BigInteger.valueOf(doubleValue.longValue());
    } else if (nonReleasenameProperty.getType().equals(BuiltinPrimitiveType.DECIMAL)) {
        Double doubleValue = getCellValueOfType(nonEmptyCell, Double.class);
        return doubleValue == null ? null : BigDecimal.valueOf(doubleValue.doubleValue());
    } else if (nonReleasenameProperty.getType().equals(BuiltinPrimitiveType.DATE)) {
        return getCellValueOfType(nonEmptyCell, Date.class);
    } else if (nonReleasenameProperty.getType().equals(BuiltinPrimitiveType.BOOLEAN)) {
        String stringValue = getCellValueOfType(nonEmptyCell, String.class);
        return Boolean.valueOf(Boolean.parseBoolean(stringValue));
    } else if (nonReleasenameProperty.getType().equals(BuiltinPrimitiveType.STRING)) {
        return getStringPropertyValue(nonEmptyCell, nonReleasenameProperty);
    } else {//  www .  j  a va  2  s  .  co  m
        LOGGER.info("Property type for Java enum: {0}", nonReleasenameProperty.getClass().getName());
        return resolveJavaEnum(nonReleasenameProperty.getType().getName(),
                ExcelUtils.getCellValue(nonEmptyCell, false));
    }
}

From source file:org.n52.ifgicopter.spf.input.LastDataPostgisInputPlugin.java

@Override
protected JPanel makeControlPanel() {
    if (this.controlPanel == null) {
        this.controlPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));

        JButton startButton = new JButton("Start");
        startButton.addActionListener(new ActionListener() {

            @Override//from  w  w  w.jav a  2 s .com
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        start();
                    }
                });
            }
        });
        this.controlPanel.add(startButton);
        JButton stopButton = new JButton("Stop");
        stopButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        stop();
                    }
                });
            }
        });
        this.controlPanel.add(stopButton);

        JLabel minTimeLabel = new JLabel("Mimium time database queries in milliseconds:");
        this.controlPanel.add(minTimeLabel);
        SpinnerModel model = new SpinnerNumberModel(this.minimumMillisBetweenRequests, 10d, 3600000d, 10d);
        JSpinner sleepTimeSpinner = new JSpinner(model);
        sleepTimeSpinner.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                Object source = e.getSource();
                if (source instanceof JSpinner) {
                    final JSpinner spinner = (JSpinner) source;

                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Double value = (Double) spinner.getValue();
                            value = Double.valueOf(value.doubleValue() * 1000d);
                            setMinimumMillisBetweenRequests(value.longValue());
                        }
                    });
                } else
                    log.warn("Unsupported ChangeEvent, need JSpinner as source: " + e);
            }
        });
        // catch text change events without loosing the focus
        // JSpinner.DefaultEditor editor = (DefaultEditor) sleepTimeSpinner.getEditor();
        // not implemented, can be done using KeyEvent, but then it hast to be checked where in the text
        // field the keystroke was etc. --> too complicated.

        this.controlPanel.add(sleepTimeSpinner);
    }

    return this.controlPanel;
}

From source file:org.cobbler.CobblerObject.java

/**
 * @return the created/*from ww w .  jav  a  2 s . com*/
 */
public Date getCreated() {
    Double time = (Double) dataMap.get(CTIME);
    // cobbler deals with seconds since epoch, Date expects milliseconds. Convert.
    return new Date(time.longValue() * 1000);
}

From source file:org.cobbler.CobblerObject.java

/**
 * @return the modified/*from   www.ja  va2s.  c  o  m*/
 */
public Date getModified() {
    Double time = (Double) dataMap.get(MTIME);
    // cobbler deals with seconds since epoch, Date expects milliseconds. Convert.
    return new Date(time.longValue() * 1000);
}