Example usage for java.lang Long doubleValue

List of usage examples for java.lang Long doubleValue

Introduction

In this page you can find the example usage for java.lang Long doubleValue.

Prototype

public double doubleValue() 

Source Link

Document

Returns the value of this Long as a double after a widening primitive conversion.

Usage

From source file:org.activequant.util.charting.IntradayMarketTimeline.java

/**
 * Translates a value relative to this timeline into a domain value. The
 * domain value obtained by this method is not always the same domain value
 * that could have been supplied to// w w w.  jav a  2  s .co  m
 * translateDomainValueToTimelineValue(domainValue).
 * This is because the original tranformation may not be complete
 * reversable.
 *
 * @see org.jfree.chart.axis.SegmentedTimeline
 *
 * @param timelineValue  a timeline value.
 *
 * @return A domain value.
 */
public long toMillisecond(long timelineValue) {

    if (this.activeTimePerWeek == 0L)
        return 0;

    //starting from Jan 1, 1970 work backwards.
    //find out the number of whole weeks in the timelineValue
    Long l = new Long(timelineValue / this.activeTimePerWeek);
    int numWeeks = (int) Math.floor(l.doubleValue());

    //the amount of time left on the timeline from the last thursday
    long timeLeftSinceThursday = timelineValue - (numWeeks * this.activeTimePerWeek);

    int day = Calendar.THURSDAY;
    int numDays = 0;

    //from last friday until the current day
    //if the amount of time left is greater than
    //the active time for that day, increment the number of
    //days and subtract from the time left
    while (numDays < 7) {
        if (day == Calendar.SUNDAY) {
            if (timeLeftSinceThursday > this.sundayActive) {
                timeLeftSinceThursday -= this.sundayActive;
                numDays++;
            } else {
                break;
            }
        } else if (day == Calendar.MONDAY) {
            if (timeLeftSinceThursday > this.mondayActive) {
                timeLeftSinceThursday -= this.mondayActive;
                numDays++;
            } else {
                break;
            }
        } else if (day == Calendar.TUESDAY) {
            if (timeLeftSinceThursday > this.tuesdayActive) {
                timeLeftSinceThursday -= this.tuesdayActive;
                numDays++;
            } else {
                break;
            }
        } else if (day == Calendar.WEDNESDAY) {
            if (timeLeftSinceThursday > this.wednesdayActive) {
                timeLeftSinceThursday -= this.wednesdayActive;
                numDays++;
            } else {
                break;
            }
        } else if (day == Calendar.THURSDAY) {

            if (timeLeftSinceThursday > this.thursdayActive) {
                timeLeftSinceThursday -= this.thursdayActive;
                numDays++;

                //thursday numDays =  " + Integer.toString(numDays));
            } else {

                break;
            }
        } else if (day == Calendar.FRIDAY) {
            if (timeLeftSinceThursday > this.fridayActive) {
                timeLeftSinceThursday -= this.fridayActive;
                numDays++;
            } else {
                break;
            }
        } else if (day == Calendar.SATURDAY) {
            if (timeLeftSinceThursday > this.saturdayActive) {
                timeLeftSinceThursday -= this.saturdayActive;
                numDays++;
            } else {
                break;
            }
        }

        day = this.nextDay(day);
    }

    long millis = numWeeks * MILLIS_PER_WEEK + numDays * MILLIS_PER_DAY + this.getStartTime(day)
            + timeLeftSinceThursday;

    return millis;
}

From source file:edu.nwpu.gemfire.monitor.service.ClusterMembersRGraphService.java

/**
 * function used for getting all members details in format of JSON Object
 * array defined under a cluster. This function create json based on the
 * relation of physical host and members related to it.
 * //from ww  w .ja v  a  2  s. c om
 * @param cluster
 * @param host
 * @param port
 * @return Array list of JSON objects for required fields of members in
 *         cluster
 */
private ObjectNode getPhysicalServerJson(Cluster cluster, String host, String port) {
    Map<String, List<Cluster.Member>> physicalToMember = cluster.getPhysicalToMember();

    ObjectNode clusterTopologyJSON = mapper.createObjectNode();

    clusterTopologyJSON.put(this.ID, cluster.getClusterId());
    clusterTopologyJSON.put(this.NAME, cluster.getClusterId());
    ObjectNode data1 = mapper.createObjectNode();
    clusterTopologyJSON.put(this.DATA, data1);
    ArrayNode childHostArray = mapper.createArrayNode();
    DecimalFormat df2 = new DecimalFormat(PulseConstants.DECIMAL_FORMAT_PATTERN);

    updateAlertLists(cluster);

    for (Map.Entry<String, List<Cluster.Member>> physicalToMem : physicalToMember.entrySet()) {
        String hostName = physicalToMem.getKey();
        double hostCpuUsage = 0.0;
        long hostMemoryUsage = 0;
        double hostLoadAvg = 0.0;
        int hostNumThreads = 0;
        long hostSockets = 0;
        boolean hostSevere = false;
        boolean hostError = false;
        boolean hostWarning = false;
        String hostStatus;
        ObjectNode childHostObject = mapper.createObjectNode();
        childHostObject.put(this.ID, hostName);
        childHostObject.put(this.NAME, hostName);

        ArrayNode membersArray = mapper.createArrayNode();

        List<Cluster.Member> memberList = physicalToMem.getValue();
        for (Cluster.Member member : memberList) {
            ObjectNode memberJSONObj = mapper.createObjectNode();

            memberJSONObj.put(this.ID, member.getId());
            memberJSONObj.put(this.NAME, member.getName());

            ObjectNode memberData = mapper.createObjectNode();

            memberData.put("gemfireVersion", member.getGemfireVersion());

            Long currentHeap = member.getCurrentHeapSize();
            Long usedHeapSize = cluster.getUsedHeapSize();

            if (usedHeapSize > 0) {
                double heapUsage = (currentHeap.doubleValue() / usedHeapSize.doubleValue()) * 100;

                memberData.put(this.MEMORY_USAGE, Double.valueOf(df2.format(heapUsage)));
            } else
                memberData.put(this.MEMORY_USAGE, 0);

            double currentCPUUsage = member.getCpuUsage();

            memberData.put(this.CPU_USAGE, Double.valueOf(df2.format(currentCPUUsage)));
            memberData.put(this.REGIONS, member.getMemberRegions().size());
            memberData.put(this.HOST, member.getHost());
            if ((member.getMemberPort() == null) || (member.getMemberPort().equals(""))) {
                memberData.put(this.PORT, "-");
            } else {
                memberData.put(this.PORT, member.getMemberPort());
            }
            memberData.put(this.CLIENTS, member.getMemberClientsHMap().size());
            memberData.put(this.GC_PAUSES, member.getGarbageCollectionCount());
            memberData.put(this.NUM_THREADS, member.getNumThreads());

            // Host CPU Usage is aggregate of all members cpu usage
            // hostCpuUsage = hostCpuUsage + currentCPUUsage;
            hostCpuUsage = member.getHostCpuUsage();
            hostMemoryUsage = hostMemoryUsage + member.getCurrentHeapSize();
            hostLoadAvg = member.getLoadAverage();
            hostNumThreads = member.getNumThreads();
            hostSockets = member.getTotalFileDescriptorOpen();

            // defining the status of Member Icons for R Graph based on the alerts
            // created for that member
            String memberNodeType = "";
            // for severe alert
            if (severeAlertList.contains(member.getName())) {
                memberNodeType = getMemberNodeType(member, this.MEMBER_NODE_TYPE_SEVERE);
                if (!hostSevere) {
                    hostSevere = true;
                }
            } else if (errorAlertsList.contains(member.getName())) {
                // for error alerts
                memberNodeType = getMemberNodeType(member, this.MEMBER_NODE_TYPE_ERROR);
                if (!hostError) {
                    hostError = true;
                }
            }
            // for warning alerts
            else if (warningAlertsList.contains(member.getName())) {
                memberNodeType = getMemberNodeType(member, this.MEMBER_NODE_TYPE_WARNING);
                if (!hostWarning) {
                    hostWarning = true;
                }
            } else {
                memberNodeType = getMemberNodeType(member, this.MEMBER_NODE_TYPE_NORMAL);
            }

            memberData.put("nodeType", memberNodeType);
            memberData.put("$type", memberNodeType);
            memberData.put(this.GATEWAY_SENDER, member.getGatewaySenderList().size());
            if (member.getGatewayReceiver() != null) {
                memberData.put(this.GATEWAY_RECEIVER, 1);
            } else {
                memberData.put(this.GATEWAY_RECEIVER, 0);
            }
            memberJSONObj.put(this.DATA, memberData);
            memberJSONObj.put(this.CHILDREN, mapper.createArrayNode());
            membersArray.add(memberJSONObj);
        }
        ObjectNode data = mapper.createObjectNode();

        data.put(this.LOAD_AVG, hostLoadAvg);
        data.put(this.SOCKETS, hostSockets);
        data.put(this.THREADS, hostNumThreads);
        data.put(this.CPU_USAGE, Double.valueOf(df2.format(hostCpuUsage)));
        data.put(this.MEMORY_USAGE, hostMemoryUsage);

        String hostNodeType;
        // setting physical host status
        if (hostSevere) {
            hostStatus = this.MEMBER_NODE_TYPE_SEVERE;
            hostNodeType = "hostSevereNode";
        } else if (hostError) {
            hostStatus = this.MEMBER_NODE_TYPE_ERROR;
            hostNodeType = "hostErrorNode";
        } else if (hostWarning) {
            hostStatus = this.MEMBER_NODE_TYPE_WARNING;
            hostNodeType = "hostWarningNode";
        } else {
            hostStatus = this.MEMBER_NODE_TYPE_NORMAL;
            hostNodeType = "hostNormalNode";
        }
        data.put("hostStatus", hostStatus);
        data.put("$type", hostNodeType);

        childHostObject.put(this.DATA, data);

        childHostObject.put(this.CHILDREN, membersArray);
        childHostArray.add(childHostObject);
    }
    clusterTopologyJSON.put(this.CHILDREN, childHostArray);

    return clusterTopologyJSON;
}

From source file:eu.riscoss.rdc.RDCGithub.java

private void parseJsonParticipation(JSONAware jv, String entity, Map<String, RiskData> values) {
    if (jv instanceof JSONObject) {
        JSONObject jo = (JSONObject) jv;
        if (jo.containsKey("all")) {
            // JSONArray ja = (JSONArray)jo.get("all"));
            ArrayList<Long> ll = (ArrayList<Long>) jo.get("all");
            ArrayList<Double> doublelist = new ArrayList<Double>();
            Long sum = 0L;/*from   www  .  j av  a 2s. c om*/
            for (Long l : ll) {
                doublelist.add(l.doubleValue());
                sum += l;
            }

            Distribution d = new Distribution();
            d.setValues(doublelist);
            //weekly commit count for the repository owner and everyone else, 52 weeks
            RiskData rd = new RiskData(GITHUB_PREFIX + "participation", entity, new Date(),
                    RiskDataType.DISTRIBUTION, d);
            values.put(rd.getId(), rd);
            rd = new RiskData(GITHUB_PREFIX + "participation_sum", entity, new Date(), RiskDataType.NUMBER,
                    sum);
            values.put(rd.getId(), rd);
        }
    }
}

From source file:fr.gael.dhus.server.http.valve.processings.ProcessingValve.java

double sToMn(Long s) {
    return s.doubleValue() / 60.0;
}

From source file:com.example.ekanban.service.ProductService.java

private int getNoOfBins(Long value, Long binQty) {
    int result = (int) (value / binQty);
    int surplus = (int) (value % binQty);
    int roundValue = (int) (Constants.STK_ROUND_FRACTION * binQty.doubleValue());
    result = surplus > roundValue ? result + 1 : result;
    return result;
}

From source file:gov.nih.nci.rembrandt.web.taglib.ClinicalPlotTag.java

public int doStartTag() {
    chart = null;//from   w ww . j a  v  a  2 s  . com
    clinicalData.clear();

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    try {

        //
        //retrieve the Finding from cache and build the list of  Clinical Data points
        //ClinicalFinding clinicalFinding = (ClinicalFinding)businessTierCache.getSessionFinding(session.getId(),taskId);
        ReportBean clincalReportBean = presentationTierCache.getReportBean(session.getId(), taskId);
        Resultant clinicalResultant = clincalReportBean.getResultant();
        ResultsContainer resultsContainer = clinicalResultant.getResultsContainer();
        SampleViewResultsContainer sampleViewContainer = null;
        if (resultsContainer instanceof DimensionalViewContainer) {
            DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
            sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
        }
        if (sampleViewContainer != null) {
            Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
            clinicalFactors.add(ClinicalFactorType.AgeAtDx);
            //clinicalFactors.add(ClinicalFactorType.Survival);
            Collection<SampleResultset> samples = sampleViewContainer.getSampleResultsets();

            if (samples != null) {
                int numDxvsKa = 0;
                int numDxvsSl = 0;
                for (SampleResultset rs : samples) {
                    //String id = rs.getBiospecimen().getValueObject();
                    String id = rs.getSampleIDDE().getValueObject();
                    ClinicalDataPoint clinicalDataPoint = new ClinicalDataPoint(id);

                    String diseaseName = rs.getDisease().getValueObject();
                    if (diseaseName != null) {
                        clinicalDataPoint.setDiseaseName(diseaseName);
                    } else {
                        clinicalDataPoint.setDiseaseName(DiseaseType.NON_TUMOR.name());
                    }

                    Long sl = rs.getSurvivalLength();
                    double survivalDays = -1.0;
                    double survivalMonths = -1.0;
                    if (sl != null) {
                        survivalDays = sl.doubleValue();
                        survivalMonths = survivalDays / 30.0;
                        //if ((survivalMonths > 0.0)&&(survivalMonths < 1000.0)) {
                        clinicalDataPoint.setSurvival(survivalDays);
                        //}
                    }

                    Long dxAge = rs.getAge();
                    if (dxAge != null) {
                        clinicalDataPoint.setAgeAtDx(dxAge.doubleValue());
                    }

                    KarnofskyClinicalEvalDE ka = rs.getKarnofskyClinicalEvalDE();
                    if (ka != null) {
                        String kaStr = ka.getValueObject();
                        if (kaStr != null) {
                            if (kaStr.contains("|")) {
                                kaStr = kaStr.trim();
                                String[] kaStrArray = kaStr.split("\\|");
                                for (int i = 0; i < kaStrArray.length; i++) {
                                    if (i == 0) {
                                        //first score is baseline just use this for now
                                        //later we will need to use all score in a series for each patient
                                        double kaVal = Double.parseDouble(kaStrArray[i].trim());
                                        clinicalDataPoint.setKarnofskyScore(kaVal);
                                    }
                                }
                            } else {
                                double kaVal = Double.parseDouble(kaStr);
                                clinicalDataPoint.setKarnofskyScore(kaVal);
                            }

                        }
                    }

                    if ((dxAge != null) && (ka != null)) {
                        numDxvsKa++;
                    }

                    if ((dxAge != null) && (sl != null)) {
                        numDxvsSl++;
                    }

                    //                        Object dx = rs.getAgeGroup();
                    //                            if(sl !=null && dx !=null){
                    //                                clinicalDataPoint.setSurvival(new Double(sl.toString()));
                    //                                clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
                    //                            }
                    //                        Object ks = rs.getKarnofskyClinicalEvalDE();
                    //                        Object dx = rs.getAgeGroup();
                    //                            if(ks !=null && dx !=null){
                    //                                clinicalDataPoint.setNeurologicalAssessment(new Double(ks.toString()));
                    //                                clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
                    //                            }

                    clinicalData.add(clinicalDataPoint);
                }
            }
        }

        System.out.println("Done creating points!");

        //-------------------------------------------------------------
        //GET THE CLINICAL DATA AND POPULATE THE clinicalData list
        //Note the ClinicalFinding is currently an empty class
        //----------------------------------------------------------

        //check the components to see which graph to get
        if (components.equalsIgnoreCase("SurvivalvsAgeAtDx")) {
            chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,
                    ClinicalFactorType.SurvivalLength, "Survival Length (Months)", ClinicalFactorType.AgeAtDx,
                    "Age At Diagnosis (Years)");
        }
        if (components.equalsIgnoreCase("KarnofskyScorevsAgeAtDx")) {
            chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,
                    ClinicalFactorType.KarnofskyAssessment, "Karnofsky Score", ClinicalFactorType.AgeAtDx,
                    "Age At Diagnosis (Years)");
        }

        RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(), "png", 600,
                500);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();

        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 600, 500, info);

        /*   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         **/
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }

        out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, false, info));
        //finalURLpath = finalURLpath.replace("\\", "/");
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" alt=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?"
                + randomness + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //out.print("<img id=\"geneChart\" name=\"geneChart\" src=\""+finalURLpath+"\" usemap=\"#"+mapName + "\" border=\"0\" />");

    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:gov.nih.nci.rembrandt.web.taglib.PCAPlotTag.java

public int doStartTag() {
    chart = null;/* w  w w  .  j a v a2 s .  c o  m*/
    pcaResults = null;
    pcaData.clear();

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    try {
        //retrieve the Finding from cache and build the list of PCAData points
        PrincipalComponentAnalysisFinding principalComponentAnalysisFinding = (PrincipalComponentAnalysisFinding) businessTierCache
                .getSessionFinding(session.getId(), taskId);

        Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
        List<String> sampleIds = new ArrayList<String>();
        Map<String, PCAresultEntry> pcaResultMap = new HashMap<String, PCAresultEntry>();
        if (principalComponentAnalysisFinding != null) {
            pcaResults = principalComponentAnalysisFinding.getResultEntries();
            for (PCAresultEntry pcaEntry : pcaResults) {
                sampleIds.add(pcaEntry.getSampleId());
                pcaResultMap.put(pcaEntry.getSampleId(), pcaEntry);
            }

            Collection<SampleResultset> validatedSampleResultset = ClinicalDataValidator
                    .getValidatedSampleResultsetsFromSampleIDs(sampleIds, clinicalFactors);

            if (validatedSampleResultset != null) {
                String id;
                PCAresultEntry entry;

                for (SampleResultset rs : validatedSampleResultset) {
                    id = rs.getBiospecimen().getSpecimenName();
                    entry = pcaResultMap.get(id);
                    PrincipalComponentAnalysisDataPoint pcaPoint = new PrincipalComponentAnalysisDataPoint(id,
                            entry.getPc1(), entry.getPc2(), entry.getPc3());
                    String diseaseName = rs.getDisease().getValueObject();
                    if (diseaseName != null) {
                        pcaPoint.setDiseaseName(diseaseName);
                    } else {
                        pcaPoint.setDiseaseName(DiseaseType.NON_TUMOR.name());
                    }
                    GenderDE genderDE = rs.getGenderCode();
                    if (genderDE != null && genderDE.getValue() != null) {
                        String gt = genderDE.getValueObject().trim();
                        if (gt != null) {
                            GenderType genderType = GenderType.valueOf(gt);
                            if (genderType != null) {
                                pcaPoint.setGender(genderType);
                            }
                        }
                    }
                    Long survivalLength = rs.getSurvivalLength();
                    if (survivalLength != null) {
                        //survival length is stored in days in the DB so divide by 30 to get the 
                        //approx survival in months
                        double survivalInMonths = survivalLength.doubleValue() / 30.0;
                        pcaPoint.setSurvivalInMonths(survivalInMonths);
                    }
                    pcaData.add(pcaPoint);
                }
            }

            PCAcomponent pone = PCAcomponent.PC1;
            PCAcomponent ptwo = PCAcomponent.PC2;
            //check the components to see which graph to get
            if (components.equalsIgnoreCase("PC1vsPC2")) {
                pone = PCAcomponent.PC2;
                ptwo = PCAcomponent.PC1;
                //chart = (JFreeChart) CaIntegratorChartFactory.getPrincipalComponentAnalysisGraph(pcaData,PCAcomponent.PC2,PCAcomponent.PC1,PCAcolorByType.valueOf(PCAcolorByType.class,colorBy));
            }
            if (components.equalsIgnoreCase("PC1vsPC3")) {
                pone = PCAcomponent.PC3;
                ptwo = PCAcomponent.PC1;
                //chart = (JFreeChart) CaIntegratorChartFactory.getPrincipalComponentAnalysisGraph(pcaData,PCAcomponent.PC3,PCAcomponent.PC1,PCAcolorByType.valueOf(PCAcolorByType.class,colorBy));
            }
            if (components.equalsIgnoreCase("PC2vsPC3")) {
                pone = PCAcomponent.PC2;
                ptwo = PCAcomponent.PC3;
                //chart = (JFreeChart) CaIntegratorChartFactory.getPrincipalComponentAnalysisGraph(pcaData,PCAcomponent.PC3,PCAcomponent.PC2,PCAcolorByType.valueOf(PCAcolorByType.class,colorBy));
            }

            PrincipalComponentAnalysisPlot plot = new RBTPrincipalComponentAnalysisPlot(pcaData, pone, ptwo,
                    PCAcolorByType.valueOf(PCAcolorByType.class, colorBy));
            if (plot != null) {
                chart = (JFreeChart) plot.getChart();
            }

            RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(), "png", 650,
                    600);
            //The final complete path to be used by the webapplication
            String finalPath = imageHandler.getSessionTempFolder();
            String finalURLpath = imageHandler.getFinalURLPath();
            /*
             * Create the actual charts, writing it to the session temp folder
            */
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            String mapName = imageHandler.createUniqueMapName();
            //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
            ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
            //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
            //writer.close();

            /*   This is here to put the thread into a loop while it waits for the
             *   image to be available.  It has an unsophisticated timer but at 
             *   least it is something to avoid an endless loop.
             **/
            boolean imageReady = false;
            int timeout = 1000;
            FileInputStream inputStream = null;
            while (!imageReady) {
                timeout--;
                try {
                    inputStream = new FileInputStream(finalPath);
                    inputStream.available();
                    imageReady = true;
                    inputStream.close();
                } catch (IOException ioe) {
                    imageReady = false;
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
                if (timeout <= 1) {

                    break;
                }
            }

            out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, false, info));
            finalURLpath = finalURLpath.replace("\\", "/");
            long randomness = System.currentTimeMillis(); //prevent image caching
            out.print("<img id=\"geneChart\" name=\"geneChart\" alt=\"geneChart\" src=\"" + finalURLpath + "?"
                    + randomness + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

            //(imageHandler.getImageTag(mapFileName));
        }
    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:com.hmsinc.epicenter.webapp.remoting.EventService.java

/**
 * @param eventId/*from   w w  w. j  a v a 2s. co  m*/
 * @param analysisType
 * @return
 */
@SuppressWarnings("unchecked")
@RemoteMethod
@Transactional(readOnly = true)
public <G extends Geography, A extends QueryableAttribute> String getDescriptiveAnalysisChart(Long eventId,
        DescriptiveAnalysisType analysisType, SurveillanceResultType resultType) {

    Validate.notNull(analysisType, "Analysis type must be specified.");
    Validate.notNull(eventId, "Event id must be specified.");
    Validate.notNull(resultType, "Result type must be specified.");

    final Event event = workflowRepository.load(eventId, Event.class);
    Validate.notNull(event, "Invalid event id: " + eventId);
    checkPermission(getPrincipal(), event);
    Validate.isTrue(event instanceof Anomaly, "Event is not an anomaly.");

    final Anomaly anomaly = (Anomaly) event;
    final AnalysisParameters analysisParameters = anomaly.getAnalysisParameters();
    analysisParameters.setStartDate(analysisParameters.getEndDate().minusDays(3));

    logger.debug("Parameters: {}", analysisParameters);

    // FIXME: This casting mess is very annoying.  We need to fix this. -sk
    final Class<G> gtype;
    final Class<A> atype;

    if (Geography.class.isAssignableFrom(analysisType.getAggregateAttribute())) {
        gtype = (Class<G>) analysisType.getAggregateAttribute();
        atype = (Class<A>) Classification.class;
    } else {
        gtype = (Class<G>) ModelUtils.getRealClass(anomaly.getGeography());
        atype = (Class<A>) analysisType.getAggregateAttribute();
    }

    if (DescriptiveAnalysisType.BY_ZIPCODE.equals(analysisType)) {
        analysisParameters.setLocation(AnalysisLocation.HOME);
    }

    final TimeSeriesCollection<G, A> ts = dataQueryService.query(analysisParameters, gtype, atype);

    Validate.notNull(ts, "Unable to get timeseries!");

    final BarChart chart = new BarChart();

    final Set<SortableKeyValuePair> pairs = new TreeSet<SortableKeyValuePair>();

    if (Geography.class.isAssignableFrom(analysisType.getAggregateAttribute())) {

        for (TimeSeriesNode node : ts.getTimeSeriesNodes()) {
            double value = node.getTimeSeries().getValue(anomaly.getAnalysisTimestamp());
            if (SurveillanceResultType.NORMALIZED.equals(resultType)) {
                value = (value / anomaly.getObservedValue()) * 100;
            } else if (SurveillanceResultType.POPULATION.equals(resultType)) {

                final Geography g = (Geography) node.getPrimaryIndex();
                final Long population = g.getPopulation() == null ? geographyRepository.inferPopulation(g)
                        : g.getPopulation();
                value = AnalysisUtils.calculatePopulationRate(value, population.doubleValue());
            }
            pairs.add(new SortableKeyValuePair(((Geography) node.getPrimaryIndex()).getName(), value));
        }

    } else {

        if (ts.getPrimaryIndexes().contains(anomaly.getGeography())) {

            final Map<A, TimeSeries> map = ts.get((G) anomaly.getGeography());

            for (Map.Entry<A, TimeSeries> entry : map.entrySet()) {

                double value = entry.getValue().getValue(anomaly.getAnalysisTimestamp());

                if (SurveillanceResultType.NORMALIZED.equals(resultType)) {
                    value = (value / anomaly.getObservedValue()) * 100;
                } else if (SurveillanceResultType.POPULATION.equals(resultType)) {

                    final Long population = anomaly.getGeography().getPopulation() == null
                            ? geographyRepository.inferPopulation(anomaly.getGeography())
                            : anomaly.getGeography().getPopulation();

                    Validate.notNull(population,
                            "Could not determine population for: " + anomaly.getGeography().getDisplayName());

                    value = AnalysisUtils.calculatePopulationRate(value, population.doubleValue());
                }

                pairs.add(new SortableKeyValuePair(entry.getKey().getName(), value));

            }

        } else {
            logger.warn("Unable to generate descriptive analysis chart for: {}  [no data found]",
                    anomaly.getGeography());
        }

    }

    int i = 0;
    for (SortableKeyValuePair pair : pairs) {
        if (pair.getValue() > 0) {
            chart.add(pair.getValue(), analysisType.getDescription() + (pairs.size() > 5 ? " - Top 5" : ""),
                    pair.getKey());
            i++;
            if (i > 4) {
                break;
            }
        }
    }

    chart.setYLabel(resultType.getDescription());
    if (!SurveillanceResultType.NORMALIZED.equals(resultType)) {
        chart.setRangeTickUnits(NumberAxis.createIntegerTickUnits());
    }
    return chartService.getChartURL(chart);

}

From source file:org.pau.assetmanager.viewmodel.stocks.StocksUtils.java

public static StockConceptPerformance getStockConceptPerformance(
        Collection<StockIncomeDescription> stockIncomeDescriptionList) {
    Double profits = 0.0;//from   ww w.  ja  v  a  2 s. c om
    Date lastSoldDate = null;
    Book book = null;
    Long numberOfStocks = 0L;
    String concept = null;
    Validate.notEmpty(stockIncomeDescriptionList, "The StockIncomeDescriptionList cannot be empty");
    Set<StockExpensesAnnotation> stocksBoughtSet = new HashSet<StockExpensesAnnotation>();
    for (StockIncomeDescription stockIncomeDescription : stockIncomeDescriptionList) {
        StockIncomeAnnotation stockIncomeAnnotation = stockIncomeDescription.getStockIncomeAnnotation();
        numberOfStocks += stockIncomeAnnotation.getNumberOfStocks();
        profits += stockIncomeAnnotation.getAmount();
        for (StocksBuySubtransaction stocksBuySubtransaction : stockIncomeDescription
                .getStocksBuySubtransactionSet()) {
            profits -= (stocksBuySubtransaction.getNumberOfStocks()
                    * stocksBuySubtransaction.getPricePerStock());
            stocksBoughtSet.add(stocksBuySubtransaction.getStockExpensesAnnotation());
        }
        if (lastSoldDate == null) {
            lastSoldDate = stockIncomeAnnotation.getDate();
        } else if (lastSoldDate.before(stockIncomeAnnotation.getDate())) {
            lastSoldDate = stockIncomeAnnotation.getDate();
        }
        book = stockIncomeAnnotation.getBook();
        concept = stockIncomeAnnotation.getConcept();
    }
    Long numberOfStocksBought = 0L;
    for (StockExpensesAnnotation stockExpensesAnnotation : stocksBoughtSet) {
        numberOfStocksBought += stockExpensesAnnotation.getNumberOfStocks();
    }
    StockConceptPerformance stockConceptPerformance = new StockConceptPerformance(profits,
            (numberOfStocks.doubleValue() / numberOfStocksBought.doubleValue()) * 100.0, concept,
            numberOfStocks, lastSoldDate, book);
    return stockConceptPerformance;
}

From source file:org.finra.dm.dao.impl.S3DaoImpl.java

/**
 * Returns transfer rate in kBytes/s.  Please note that bytes->kBytes and ms->seconds conversions cancel each other (both use conversion factor of 1000).
 *
 * @param totalBytesTransferred Number of bytes transferred.
 * @param durationMillis Duration in milliseconds.
 *
 * @return the transfer rate in kBytes/s.
 *//*from   w  w  w . j  a v  a 2  s .  co  m*/
private Double getTransferRateInKilobytesPerSecond(Long totalBytesTransferred, Long durationMillis) {
    return totalBytesTransferred.doubleValue() / durationMillis;
}