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:com.controller.schedule.ScheduleEmailServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w  . j  a  v a 2  s  . 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");
    try {
        if (!AuthenticationUtil.isUserLoggedIn(request)) {
            AuthenticationUtil.printAuthErrorToResponse(response);
            return;
        }
        Integer userId = AuthenticationUtil.getUUID(request);

        Map<String, Object> requestBodyMap = AppConstants.GSON.fromJson(new BufferedReader(request.getReader()),
                Map.class);
        if (requestBodyMap == null) {
            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;
        }

        List<String> errorMsgs = validateRequestBody(requestBodyMap);
        if (!errorMsgs.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        Double schedule = (Double) requestBodyMap.get("schedule_time");
        //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> idMap = ScheduleDAO.addToScheduledEmailList(userId,
                requestBodyMap.get("email_subject").toString(), requestBodyMap.get("email_body").toString(),
                requestBodyMap.get("from_email_address").toString(),
                requestBodyMap.get("email_list").toString(), requestBodyMap.get("from_name").toString(),
                requestBodyMap.get("reply_to_email_address").toString(),
                requestBodyMap.get("to_email_addresses").toString().split(","),
                requestBodyMap.get("schedule_title").toString(), scheduleDesc,
                new Timestamp(schedule.longValue()), TemplateStatus.template_saved.toString());
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(idMap));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Invalid format for schedule time.");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (Exception ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.sonar.server.component.ws.ComponentAppAction.java

@CheckForNull
private String formatMeasure(@Nullable MeasureDto measure) {
    if (measure != null) {
        Metric metric = CoreMetrics.getMetric(measure.getKey().metricKey());
        Metric.ValueType metricType = metric.getType();
        Double value = measure.getValue();
        String data = measure.getData();

        if (metricType.equals(Metric.ValueType.FLOAT) && value != null) {
            return i18n.formatDouble(UserSession.get().locale(), value);
        }//w  w w. j  a v  a 2  s .  c  o m
        if (metricType.equals(Metric.ValueType.INT) && value != null) {
            return i18n.formatInteger(UserSession.get().locale(), value.intValue());
        }
        if (metricType.equals(Metric.ValueType.PERCENT) && value != null) {
            return i18n.formatDouble(UserSession.get().locale(), value) + "%";
        }
        if (metricType.equals(Metric.ValueType.WORK_DUR) && value != null) {
            return durations.format(UserSession.get().locale(), durations.create(value.longValue()),
                    Durations.DurationFormat.SHORT);
        }
        if ((metricType.equals(Metric.ValueType.STRING) || metricType.equals(Metric.ValueType.RATING))
                && data != null) {
            return data;
        }
    }
    return null;
}

From source file:org.sonar.server.component.ws.ComponentAppAction.java

@CheckForNull
private String formatVariation(@Nullable MeasureDto measure, Integer periodIndex) {
    if (measure != null) {
        Double variation = measure.getVariation(periodIndex);
        if (variation != null) {
            Metric metric = CoreMetrics.getMetric(measure.getKey().metricKey());
            Metric.ValueType metricType = metric.getType();
            if (metricType.equals(Metric.ValueType.FLOAT) || metricType.equals(Metric.ValueType.PERCENT)) {
                return i18n.formatDouble(UserSession.get().locale(), variation);
            }/*from w ww .  ja  v a2 s.  c om*/
            if (metricType.equals(Metric.ValueType.INT)) {
                return i18n.formatInteger(UserSession.get().locale(), variation.intValue());
            }
            if (metricType.equals(Metric.ValueType.WORK_DUR)) {
                return durations.format(UserSession.get().locale(), durations.create(variation.longValue()),
                        Durations.DurationFormat.SHORT);
            }
        }
    }
    return null;
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Extract a tracking ID from an XML string.
 * //w  w w. j  ava 2  s.  co m
 * @param xml
 *        the XML to extract from
 * @param xp
 *        the XPath to use that returns a number
 * @param xpath
 *        the XPath as a string (for debugging)
 * @return the tracking ID, or <em>null</em> if not found
 */
protected Long extractTrackingId(InputSource xml, XPathExpression xp, String xpath) {
    Double tid;
    try {
        tid = (Double) xp.evaluate(xml, XPathConstants.NUMBER);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
    if (tid.isNaN()) {
        log.warn("Unable to extract tracking ID via XPath [{}]", xpath);
        return null;
    }
    return tid.longValue();
}

From source file:org.exoplatform.social.addons.search.SpaceElasticUnifiedSearchServiceConnector.java

protected Collection<SearchResult> buildResult(String jsonResponse, SearchContext context) {

    LOG.debug("Search Query response from ES : {} ", jsonResponse);

    Collection<SearchResult> results = new ArrayList<>();
    JSONParser parser = new JSONParser();

    Map json;/*from  ww  w. j  a va  2s  .  c om*/
    try {
        json = (Map) parser.parse(jsonResponse);
    } catch (ParseException e) {
        throw new ElasticSearchException("Unable to parse JSON response", e);
    }

    //TODO check if response is successful
    JSONObject jsonResult = (JSONObject) json.get("hits");
    JSONArray jsonHits = (JSONArray) jsonResult.get("hits");

    for (Object jsonHit : jsonHits) {
        JSONObject hitSource = (JSONObject) ((JSONObject) jsonHit).get("_source");
        Space space = spaceService.getSpaceById(((JSONObject) jsonHit).get("_id").toString());
        if (Space.HIDDEN.equals(space.getVisibility())) {
            continue;
        }

        String title = getTitleFromJsonResult(hitSource);
        String url = getUrlFromJsonResult(space, context);
        Long lastUpdatedDate = (Long) hitSource.get("lastUpdatedDate");
        if (lastUpdatedDate == null)
            lastUpdatedDate = new Date().getTime();
        Double score = (Double) ((JSONObject) jsonHit).get("_score");

        //
        StringBuilder sb = new StringBuilder(String.valueOf(space.getDisplayName()));
        sb.append(String.format(" - %s Member(s)", space.getMembers().length));
        if (Space.OPEN.equals(space.getRegistration())) {
            sb.append(" - Free to Join");
        } else if (Space.VALIDATION.equals(space.getRegistration())) {
            sb.append(" - Register");
        } else if (Space.CLOSE.equals(space.getRegistration())) {
            sb.append(" - Invitation Only");
        } else {
            LOG.debug(space.getRegistration() + " registration unknown");
        }

        results.add(
                new SearchResult(url, title, space.getDescription(), sb.toString(),
                        space.getAvatarUrl() != null ? space.getAvatarUrl()
                                : LinkProvider.SPACE_DEFAULT_AVATAR_URL,
                        lastUpdatedDate,
                        //score must not be null as "track_scores" is part of the query
                        score.longValue()));
    }

    return results;

}

From source file:org.sakaiproject.lessonbuildertool.service.Assignment2Entity.java

public LessonSubmission getSubmission(String userId) {
    if (assignment == null)
        assignment = getAssignment(id);/*from   w  w w.j  av  a  2  s  .com*/
    if (assignment == null) {
        log.warn("can't find assignment " + id);
        return null;
    }
    Connection connection = null;
    try {
        connection = SqlService.borrowConnection();
        String sql = "select completed from A2_SUBMISSION_T where assignment_id = ? and user_id = ?";
        Object fields[] = new Object[2];
        fields[0] = id;
        fields[1] = userId;
        List<String> submissions = SqlService.dbRead(connection, sql, fields, null);
        if (submissions != null && submissions.size() > 0) {
            String completed = submissions.get(0);
            if (!("1".equals(completed) || "true".equals(completed)))
                return null;
            if (assignment.gradebookitem == null)
                return new LessonSubmission(null);
            // following will give a security error if assignment not released. I think that's better than
            // checking myself, as that would require fetchign the assignment definition from the gradebook
            // A2 doesn't seem to save that.  Score is scaled, so need * 10
            Double score = toDouble(
                    gradebookService.getAssignmentScore(assignment.context, assignment.gradebookitem, userId));
            if (score != null) {
                LessonSubmission ret = new LessonSubmission(score);
                // shouldn't actually need the string value
                score = score * 10.0;
                ret.setGradeString(Long.toString(score.longValue()));
                return ret;
            } else
                return null;
        } else
            return null;
    } catch (Exception e) {
        return null;
    } finally {
        try {
            if (connection != null)
                SqlService.returnConnection(connection);
        } catch (Exception ignore) {
        }
        ;
    }

}

From source file:org.exoplatform.social.addons.search.PeopleElasticUnifiedSearchServiceConnector.java

protected Collection<SearchResult> buildResult(String jsonResponse, SearchContext context) {

    LOG.debug("Search Query response from ES : {} ", jsonResponse);

    Collection<SearchResult> results = new ArrayList<>();
    JSONParser parser = new JSONParser();

    Map json;/*from   ww w .  j a va  2 s  .c  o  m*/
    try {
        json = (Map) parser.parse(jsonResponse);
    } catch (ParseException e) {
        throw new ElasticSearchException("Unable to parse JSON response", e);
    }

    // TODO check if response is successful
    JSONObject jsonResult = (JSONObject) json.get("hits");
    JSONArray jsonHits = (JSONArray) jsonResult.get("hits");

    for (Object jsonHit : jsonHits) {
        Identity identity = identityManager.getIdentity(((JSONObject) jsonHit).get("_id").toString(), true);
        Profile profile = identity.getProfile();
        if (identity.isDeleted()) {
            continue;
        }

        Double score = (Double) ((JSONObject) jsonHit).get("_score");

        //
        StringBuilder sb = new StringBuilder();

        //
        if (profile.getEmail() != null) {
            sb.append(profile.getEmail());
        }

        //
        List<Map> phones = (List<Map>) profile.getProperty(Profile.CONTACT_PHONES);
        if (phones != null && phones.size() > 0) {
            sb.append(" - " + phones.get(0).get("value"));
        }

        //
        if (profile.getProperty(Profile.GENDER) != null) {
            sb.append(" - " + profile.getProperty(Profile.GENDER));
        }

        results.add(
                new SearchResult(profile.getUrl(), profile.getFullName(), profile.getPosition(), sb.toString(),
                        profile.getAvatarUrl() != null ? profile.getAvatarUrl()
                                : LinkProvider.PROFILE_DEFAULT_AVATAR_URL,
                        profile.getCreatedTime(),
                        // score must not be null as "track_scores"
                        // is part of the query
                        score.longValue()));
    }

    return results;

}

From source file:org.exoplatform.addons.es.search.ElasticSearchServiceConnector.java

protected Collection<SearchResult> buildResult(String jsonResponse, SearchContext context) {

    LOG.debug("Search Query response from ES : {} ", jsonResponse);

    Collection<SearchResult> results = new ArrayList<>();
    JSONParser parser = new JSONParser();

    Map json;// w  w  w  . j a  v a 2 s  . c  o  m
    try {
        json = (Map) parser.parse(jsonResponse);
    } catch (ParseException e) {
        throw new ElasticSearchException("Unable to parse JSON response", e);
    }

    //TODO check if response is successful
    JSONObject jsonResult = (JSONObject) json.get("hits");
    JSONArray jsonHits = (JSONArray) jsonResult.get("hits");

    for (Object jsonHit : jsonHits) {
        JSONObject hitSource = (JSONObject) ((JSONObject) jsonHit).get("_source");
        String title = getTitleFromJsonResult(hitSource);
        String url = getUrlFromJsonResult(hitSource, context);
        Long lastUpdatedDate = (Long) hitSource.get("lastUpdatedDate");
        if (lastUpdatedDate == null)
            lastUpdatedDate = new Date().getTime();
        Double score = (Double) ((JSONObject) jsonHit).get("_score");
        //Get the excerpt
        JSONObject hitHighlight = (JSONObject) ((JSONObject) jsonHit).get("highlight");
        Iterator<?> keys = hitHighlight.keySet().iterator();
        StringBuilder excerpt = new StringBuilder();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            JSONArray highlights = (JSONArray) hitHighlight.get(key);
            for (Object highlight : highlights) {
                excerpt.append("... ").append(highlight);
            }
        }

        LOG.debug("Excerpt extract from ES response : " + excerpt.toString());

        results.add(new SearchResult(url, title, excerpt.toString(), null, img, lastUpdatedDate,
                //score must not be null as "track_scores" is part of the query
                score.longValue()));
    }

    return results;

}

From source file:org.opencastproject.inspection.ffmpeg.FFmpegAnalyzer.java

@Override
public MediaContainerMetadata analyze(File media) throws MediaAnalyzerException {

    if (binary == null)
        throw new IllegalStateException("Binary is not set");

    String[] command = new String[] { binary, "-show_format", "-show_streams", "-of", "json",
            media.getAbsolutePath().replaceAll(" ", "\\ ") };
    String commandline = StringUtils.join(command, " ");

    /* Execute ffprobe and obtain the result */
    logger.debug("Running {}", commandline);

    MediaContainerMetadata metadata = new MediaContainerMetadata();

    ProcessBuilder pbuilder = new ProcessBuilder(command);

    JSONParser parser = new JSONParser();

    try {//from   ww  w  .  j av a 2  s .  c  om
        Process process = pbuilder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        JSONObject jsonObject = (JSONObject) parser.parse(reader);
        Object obj;
        Double duration;

        /* Get format specific stuff */
        JSONObject jsonFormat = (JSONObject) jsonObject.get("format");

        /* File Name */
        obj = jsonFormat.get("filename");
        if (obj != null) {
            metadata.setFileName((String) obj);
        }

        /* Format */
        obj = jsonFormat.get("format_long_name");
        if (obj != null) {
            metadata.setFormat((String) obj);
        }

        /* Mediainfo does not return a duration if there is no stream but FFprobe
         * will return 0. For compatibility reasons, check if there are any
         * streams before reading the duration: */
        obj = jsonFormat.get("nb_streams");
        if (obj != null && (Long) obj > 0) {
            obj = jsonFormat.get("duration");
            if (obj != null) {
                duration = new Double((String) obj) * 1000;
                metadata.setDuration(duration.longValue());
            }
        }

        /* File Size */
        obj = jsonFormat.get("size");
        if (obj != null) {
            metadata.setSize(new Long((String) obj));
        }

        /* Bitrate */
        obj = jsonFormat.get("bit_rate");
        if (obj != null) {
            metadata.setBitRate(new Float((String) obj));
        }

        /* Loop through streams */
        /* FFprobe will return an empty stream array if there are no streams.
         * Thus we do not need to check. */
        JSONArray streams = (JSONArray) jsonObject.get("streams");
        Iterator<JSONObject> iterator = streams.iterator();
        while (iterator.hasNext()) {
            JSONObject stream = iterator.next();
            /* Check type of string */
            String codecType = (String) stream.get("codec_type");

            /* Handle audio streams ----------------------------- */

            if ("audio".equals(codecType)) {
                /* Extract audio stream metadata */
                AudioStreamMetadata aMetadata = new AudioStreamMetadata();

                /* Codec */
                obj = stream.get("codec_long_name");
                if (obj != null) {
                    aMetadata.setFormat((String) obj);
                }

                /* Duration */
                obj = stream.get("duration");
                if (obj != null) {
                    duration = new Double((String) obj) * 1000;
                    aMetadata.setDuration(duration.longValue());
                } else {
                    /* If no duration for this stream is specified assume the duration
                     * of the file for this as well. */
                    aMetadata.setDuration(metadata.getDuration());
                }

                /* Bitrate */
                obj = stream.get("bit_rate");
                if (obj != null) {
                    aMetadata.setBitRate(new Float((String) obj));
                }

                /* Channels */
                obj = stream.get("channels");
                if (obj != null) {
                    aMetadata.setChannels(((Long) obj).intValue());
                }

                /* Sample Rate */
                obj = stream.get("sample_rate");
                if (obj != null) {
                    aMetadata.setSamplingRate(Integer.parseInt((String) obj));
                }

                /* Add video stream metadata to overall metadata */
                metadata.getAudioStreamMetadata().add(aMetadata);

                /* Handle video streams ----------------------------- */

            } else if ("video".equals(codecType)) {
                /* Extract video stream metadata */
                VideoStreamMetadata vMetadata = new VideoStreamMetadata();

                /* Codec */
                obj = stream.get("codec_long_name");
                if (obj != null) {
                    vMetadata.setFormat((String) obj);
                }

                /* Duration */
                obj = stream.get("duration");
                if (obj != null) {
                    duration = new Double((String) obj) * 1000;
                    vMetadata.setDuration(duration.longValue());
                } else {
                    /* If no duration for this stream is specified assume the duration
                     * of the file for this as well. */
                    vMetadata.setDuration(metadata.getDuration());
                }

                /* Bitrate */
                obj = stream.get("bit_rate");
                if (obj != null) {
                    vMetadata.setBitRate(new Float((String) obj));
                }

                /* Width */
                obj = stream.get("width");
                if (obj != null) {
                    vMetadata.setFrameWidth(((Long) obj).intValue());
                }

                /* Height */
                obj = stream.get("height");
                if (obj != null) {
                    vMetadata.setFrameHeight(((Long) obj).intValue());
                }

                /* Profile */
                obj = stream.get("profile");
                if (obj != null) {
                    vMetadata.setFormatProfile((String) obj);
                }

                /* Aspect Ratio */
                obj = stream.get("sample_aspect_ratio");
                if (obj != null) {
                    vMetadata.setPixelAspectRatio(parseFloat((String) obj));
                }

                /* Frame Rate */
                obj = stream.get("avg_frame_rate");
                if (obj != null) {
                    vMetadata.setFrameRate(parseFloat((String) obj));
                }

                /* Add video stream metadata to overall metadata */
                metadata.getVideoStreamMetadata().add(vMetadata);
            }
        }

    } catch (IOException e) {
        logger.error("Error executing ffprobe: {}", e.getMessage());
    } catch (ParseException e) {
        logger.error("Error parsing ffprobe output: {}", e.getMessage());
    }

    return metadata;
}

From source file:net.grinder.SingleConsole.java

@Override
public long getCurrentExecutionCount() {
    Map<?, ?> totalStatistics = (Map<?, ?>) getStatisticsData().get("totalStatistics");
    Double testCount = MapUtils.getDoubleValue(totalStatistics, "Tests", 0D);
    Double errorCount = MapUtils.getDoubleValue(totalStatistics, "Errors", 0D);
    return testCount.longValue() + errorCount.longValue();
}