Example usage for java.lang Long longValue

List of usage examples for java.lang Long longValue

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public long longValue() 

Source Link

Document

Returns the value of this Long as a long value.

Usage

From source file:com.dsf.dbxtract.cdc.AppJournalWindowTest.java

/**
 * Rigourous Test :-)//from   w ww  .  j a va  2 s  . c  o m
 * 
 * @throws Exception
 *             in case of any error
 */
@Test(dependsOnMethods = "setUp", timeOut = 120000)
public void testAppWithJournalWindow() throws Exception {

    final Config config = new Config(configFile);

    BasicDataSource ds = new BasicDataSource();
    Source source = config.getDataSources().getSources().get(0);
    ds.setDriverClassName(source.getDriver());
    ds.setUsername(source.getUser());
    ds.setPassword(source.getPassword());
    ds.setUrl(source.getConnection());

    // prepara os dados
    Connection conn = ds.getConnection();

    conn.createStatement().execute("truncate table test");
    conn.createStatement().execute("truncate table j$test");

    // Carrega os dados de origem
    PreparedStatement ps = conn.prepareStatement("insert into test (key1,key2,data) values (?,?,?)");
    for (int i = 0; i < TEST_SIZE; i++) {
        if ((i % 100) == 0) {
            ps.executeBatch();
        }
        ps.setInt(1, i);
        ps.setInt(2, i);
        ps.setInt(3, (int) Math.random() * 500);
        ps.addBatch();
    }
    ps.executeBatch();
    ps.close();

    // Popula as tabelas de journal
    ps = conn.prepareStatement("insert into j$test (key1,key2) values (?,?)");
    for (int i = 0; i < TEST_SIZE; i++) {
        if ((i % 500) == 0) {
            ps.executeBatch();
        }
        ps.setInt(1, i);
        ps.setInt(2, i);
        ps.addBatch();
    }
    ps.executeBatch();
    ps.close();

    Long maxWindowId = 0L;
    ResultSet rs = conn.createStatement().executeQuery("select max(window_id) from j$test");
    if (rs.next()) {
        maxWindowId = rs.getLong(1);
        System.out.println("maximum window_id loaded: " + maxWindowId);
    }
    rs.close();
    conn.close();
    ds.close();

    // Clear any previous test
    String zkKey = "/dbxtract/cdc/" + source.getName() + "/J$TEST/lastWindowId";
    if (client.checkExists().forPath(zkKey) != null)
        client.delete().forPath(zkKey);

    // starts monitor
    Monitor.getInstance(config);

    // start app
    app = new App(config);
    System.out.println(config.toString());
    app.start();

    Assert.assertEquals(config.getHandlers().iterator().next().getStrategy(), JournalStrategy.WINDOW);

    while (true) {
        TimeUnit.MILLISECONDS.sleep(500);

        try {
            Long lastWindowId = Long.parseLong(new String(client.getData().forPath(zkKey)));
            System.out.println("lastWindowId = " + lastWindowId);
            if (maxWindowId.longValue() == lastWindowId.longValue()) {
                System.out.println("expected window_id reached");
                break;
            }

        } catch (NoNodeException nne) {
            System.out.println("ZooKeeper - no node exception :: " + zkKey);
        }
    }
}

From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java

/**
* invoke creates a socket connection, sends the request SOAP message and
* then reads the response SOAP message back from the SOAP server
* 
* @param msgContext/*from   w  w  w. jav a2 s.c om*/
*            the messsage context
* 
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    log.debug(Messages.getMessage("enter00", "CommonsHttpSender::invoke"));
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(this.connectionManager);

        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());
            log.info("POST message created with target [" + targetURL.toString() + "]");
            TransactionContext transactionContext = TransactionContextFactory.get();
            transactionContext
                    .addDebugInformation("POST message created with target [" + targetURL.toString() + "]");

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            Credentials cred = httpClient.getState().getCredentials(AuthScope.ANY);
            if (cred instanceof UsernamePasswordCredentials) {
                log.trace("POST message created on client with credentials ["
                        + ((UsernamePasswordCredentials) cred).getUserName() + ", "
                        + ((UsernamePasswordCredentials) cred).getPassword() + "].");
            }

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - zipping request.");
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - not zipping request");
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            log.info("GET message created with target [" + targetURL.toString() + "]");
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP))
            log.info("HTTPCommonsSender - accepting GZIP");
        else
            log.info("HTTPCommonsSender - NOT accepting GZIP");

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10))
            method.getParams().setVersion(HttpVersion.HTTP_1_0);

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();

            boolean secure = hostConfiguration.getProtocol().isSecure();
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
            httpClient.setState(state);
        }

        // add HTTP header fields that the application thinks are "interesting"
        // the expectation is that these would be non-standard HTTP headers, 
        // by convention starting with "xxx-"
        VistaRealmPrincipal principal = VistaRealmSecurityContext.get();

        if (principal != null) {
            log.info("SecurityContext credentials for '" + principal.getAccessCode() + "' are available.");
            String duz = principal.getDuz();
            if (duz != null && duz.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderDuz, duz);

            String fullname = principal.getFullName();
            if (fullname != null && fullname.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderFullName, fullname);

            String sitename = principal.getSiteName();
            if (sitename != null && sitename.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteName, sitename);

            String sitenumber = principal.getSiteNumber();
            if (sitenumber != null && sitenumber.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteNumber, sitenumber);

            String ssn = principal.getSsn();
            if (ssn != null && ssn.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSSN, ssn);

            String securityToken = principal.getSecurityToken();
            if (securityToken != null && securityToken.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderBrokerSecurityTokenId,
                        securityToken);

            String cacheLocationId = principal.getCacheLocationId();
            if (cacheLocationId != null && cacheLocationId.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderCacheLocationId,
                        cacheLocationId);

            String userDivision = principal.getUserDivision();
            if (userDivision != null && userDivision.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderUserDivision, userDivision);
        } else
            log.debug("SecurityContext credentials are NOT available.");

        method.addRequestHeader(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache,no-store");
        method.addRequestHeader(HTTPConstants.HEADER_PRAGMA, "no-cache");

        try {
            log.info("Executing method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "]");
        } catch (IllegalStateException isX) {
        }

        // send the HTTP request and wait for a response 
        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        TransactionContext transactionContext = TransactionContextFactory.get();
        // don't set the response code here - this is not the response code we send out, but the resposne code we get back from the data source
        //transactionContext.setResponseCode (String.valueOf (returnCode));

        // How many bytes received?
        transactionContext.setDataSourceBytesReceived(method.getBytesReceived());

        // How long did it take to start getting a response coming back?
        Long timeSent = method.getTimeRequestSent();
        Long timeReceived = method.getTimeFirstByteReceived();
        if (timeSent != null && timeReceived != null) {
            long timeTook = timeReceived.longValue() - timeSent.longValue();
            transactionContext.setTimeToFirstByte(new Long(timeTook));
        }

        // Looks like it wasn't found in cache - is there a place to set this to true if it was?
        transactionContext.setItemCached(Boolean.FALSE);

        // extract the basic HTTP header fields for content type, location and length
        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html")
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            String statusMessage = method.getStatusText();
            try {
                log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                        + "] failed - '" + statusMessage + "'.");
            } catch (IllegalStateException isX) {
            }

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            try {
                fault.setFaultDetailString(
                        Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString()));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to
                // pool.
            }
        }

        // wrap the response body stream so that close() also releases
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        log.info("HTTPCommonsSender - " + HTTPConstants.HEADER_CONTENT_ENCODING + "="
                + (contentEncoding == null ? "null" : contentEncoding.getValue()));

        if (contentEncoding != null) {
            if (HTTPConstants.COMPRESSION_GZIP.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving gzipped stream.");
            } else if (ENCODING_DEFLATE.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new java.util.zip.InflaterInputStream(
                        releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving 'deflated' stream.");
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                log.warn(fault.getMessage());
                throw fault;
            }

        }
        try {
            log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "] succeeded, parsing response.");
        } catch (IllegalStateException isX) {
        }

        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP
        // message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        if (log.isTraceEnabled()) {
            if (null == contentLength)
                log.trace("\n" + Messages.getMessage("no00", "Content-Length"));
            log.trace("\n" + Messages.getMessage("xmlRecd00"));
            log.trace("-----------------------------------------------");
            log.trace(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
                } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) {
            method.releaseConnection();
        }

    } catch (Exception e) {
        log.debug(e);
        throw AxisFault.makeFault(e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    }
}

From source file:org.squale.squalecommon.enterpriselayer.facade.quality.MeasureFacade.java

/**
 * Retourne les mesures associes  la volumtrie d'un projet d'aprs sa configuration en base pour un audit donn
 * sous la forme de ResultsDTO : ResultsDTO.getResultMap.get(null) --> les noms des tres
 * ResultsDTO.getResultMap.get(pProject) --> les valeurs associes
 * /* w  w w  .  j  av  a 2  s  . c om*/
 * @param pAuditId l'id de l'audit
 * @param pProject le projet
 * @return l'ensemble des mesures de la volumtrie du projet
 * @throws JrafEnterpriseException si erreur
 */
public static ResultsDTO getProjectVolumetry(Long pAuditId, ComponentDTO pProject)
        throws JrafEnterpriseException {
    // Dclaration du ResultsDTO  retourner
    ResultsDTO results = new ResultsDTO();
    MetricDAOImpl metricDAO = MetricDAOImpl.getInstance();
    // Session Hibernate
    ISession session = null;

    try {
        // Rcupration d'une session
        session = PERSISTENTPROVIDER.getSession();

        // Rcupration de la configuration de la volumtrie pour ce projet et cet audit
        AuditDisplayConfBO auditConf = AuditDisplayConfDAOImpl.getInstance().findConfigurationWhere(session,
                new Long(pProject.getID()), pAuditId, DisplayConfConstants.VOLUMETRY_SUBCLASS,
                DisplayConfConstants.VOLUMETRY_PROJECT_TYPE);
        if (null != auditConf) {
            VolumetryConfBO volumConf = (VolumetryConfBO) auditConf.getDisplayConf();
            // Pour chaque nom de tre, on rcupre la valeur de la mtrique associe
            // et on construit ainsi les rsultats  retourner
            List tres = new ArrayList();
            List values = new ArrayList();
            for (Iterator it = volumConf.getTres().iterator(); it.hasNext();) {
                String treName = (String) it.next();
                IntegerMetricBO metric = metricDAO.findIntegerMetricWhere(session, pProject.getID(),
                        pAuditId.longValue(), treName);
                if (null != metric) {
                    // On ajoute  la liste des rsultats
                    tres.add(treName);
                    values.add(metric.getValue());
                }
            }
            results.getResultMap().put(null, tres);
            results.getResultMap().put(pProject, values);
        } // Sinon il y a un problme en base
    } catch (JrafDaoException e) {
        FacadeHelper.convertException(e, MeasureFacade.class.getName() + ".getMeasuresByTRE");
    } finally {
        FacadeHelper.closeSession(session, MeasureFacade.class.getName() + ".getMeasuresByTRE");
    }
    return results;
}

From source file:be.hogent.tarsos.util.histogram.Histogram.java

/**
 * Returns the cumulative frequency of values less than or equal to v.
 * <p>//from  ww  w. j  a v  a2s  . c  o  m
 * Returns 0 if v is not comparable to the values set.
 * </p>
 * <p>
 * Uses code from <a href="http://commons.apache.org/math">Apache Commons
 * Math"</a> licensed to the Apache Software Foundation (ASF) under one or
 * more contributor license agreements.
 * </p>
 * 
 * @param v
 *            the value to lookup.
 * @return the proportion of values equal to v
 */
public long getCumFreq(final Double v) {
    long cumulativeFreq = -1;
    if (getSumFreq() == 0) {
        cumulativeFreq = 0;
    } else if (v.compareTo(freqTable.firstKey()) < 0) {
        cumulativeFreq = 0;
    } else if (v.compareTo(freqTable.lastKey()) >= 0) {
        cumulativeFreq = getSumFreq();
    } else {

        // the frequency of this key
        long result = 0;
        final Long value = freqTable.get(v);
        if (value != null) {
            result = value.longValue();
        }

        // add the frequencies of values smaller than this key
        final Iterator<Double> values = freqTable.keySet().iterator();
        while (values.hasNext()) {
            final Double nextValue = values.next();
            if (v.compareTo(nextValue) > 0) {
                result += getCount(nextValue);
            } else {
                cumulativeFreq = result;
                break;
            }
        }
    }
    if (cumulativeFreq == -1) {
        throw new AssertionError("The key is greather than te last key but this is impossible."
                + " It should have been returned already.");
    }
    return cumulativeFreq;
}

From source file:dk.dma.epd.shore.gui.views.SendRouteDialog.java

/**
 * Loads data/*from  w w  w  .  j av  a2 s. c  o m*/
 */
public void loadData() {
    loading = true;

    // Initialize MMSI list
    Set<Long> mmsiList = new HashSet<>();
    for (int i = 0; i < routeSuggestionHandler.getRouteSuggestionServiceList().size(); i++) {
        mmsiList.add(MaritimeCloudUtils
                .toMmsi(routeSuggestionHandler.getRouteSuggestionServiceList().get(i).getRemoteId()));
    }

    mmsiListComboBox.removeAllItems();
    for (Long mmsi : mmsiList) {
        mmsiListComboBox.addItem(String.valueOf(mmsi));
    }
    mmsiListComboBox.setEnabled(mmsiList.size() > 0);

    // Initialize routes
    routeListComboBox.removeAllItems();
    for (int i = 0; i < routeManager.getRoutes().size(); i++) {
        routeListComboBox.addItem(routeManager.getRoutes().get(i).getName()
                + "                                                 " + i);
    }

    // Initialize names
    nameComboBox.removeAllItems();
    for (Long mmsi : mmsiList) {

        VesselTarget selectedShip = aisHandler.getVesselTarget(mmsi.longValue());
        if (selectedShip != null && selectedShip.getStaticData() != null) {
            nameComboBox.addItem(selectedShip.getStaticData().getTrimmedName());
        } else {
            nameComboBox.addItem("N/A");
        }
    }

    loading = false;
}

From source file:com.iflytek.spider.protocol.http.HttpBase.java

private String blockAddr(URL url, long crawlDelay) throws ProtocolException {

    String host;//from w  ww .j  a v a  2s  . co  m
    if (byIP) {
        try {
            InetAddress addr = InetAddress.getByName(url.getHost());
            host = addr.getHostAddress();
        } catch (UnknownHostException e) {
            // unable to resolve it, so don't fall back to host name
            throw new HttpException(e);
        }
    } else {
        host = url.getHost();
        if (host == null)
            throw new HttpException("Unknown host for url: " + url);
        host = host.toLowerCase();
    }

    int delays = 0;
    while (true) {
        cleanExpiredServerBlocks(); // free held addresses

        Long time;
        synchronized (BLOCKED_ADDR_TO_TIME) {
            time = (Long) BLOCKED_ADDR_TO_TIME.get(host);
            if (time == null) { // address is free

                // get # of threads already accessing this addr
                Integer counter = (Integer) THREADS_PER_HOST_COUNT.get(host);
                int count = (counter == null) ? 0 : counter.intValue();

                count++; // increment & store
                THREADS_PER_HOST_COUNT.put(host, new Integer(count));

                if (count >= maxThreadsPerHost) {
                    BLOCKED_ADDR_TO_TIME.put(host, new Long(0)); // block it
                }
                return host;
            }
        }

        if (delays == maxDelays)
            throw new BlockedException("Exceeded http.max.delays: retry later.");

        long done = time.longValue();
        long now = System.currentTimeMillis();
        long sleep = 0;
        if (done == 0) { // address is still in use
            sleep = crawlDelay; // wait at least delay

        } else if (now < done) { // address is on hold
            sleep = done - now; // wait until its free
        }

        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
        }
        delays++;
    }
}

From source file:gov.nih.nci.cananolab.restful.sample.SampleBO.java

public String getCurrentSampleNameInSession(HttpServletRequest request, String sampleId) throws Exception {

    if (sampleId == null)
        throw new Exception("Input sample id is null");

    SampleBean sampleBean = (SampleBean) request.getSession().getAttribute("theSample");
    if (sampleBean == null)
        throw new Exception("No sample in session matching sample id: " + sampleId);

    Long id = sampleBean.getDomain().getId();
    if (id == null)
        throw new Exception("Sample in session has null id");

    if (Long.parseLong(sampleId) != id.longValue())
        throw new Exception("Sample in session doesn't match input sample id");

    return sampleBean.getDomain().getName();

}

From source file:eu.supersede.gr.utility.PointsLogic.java

private void computePoints() {
    List<HAHPGamePlayerPoint> gamesPlayersPoints = gamesPlayersPointsRepository.findAll();

    // cycle on every gamesPlayersPoints
    for (int i = 0; i < gamesPlayersPoints.size(); i++) {
        HAHPGame g = gamesRepository.findOne(gamesPlayersPoints.get(i).getGame().getGameId());

        // set currentPlayer that is used for other methods
        g.setCurrentPlayer(gamesPlayersPoints.get(i).getUser());

        List<HAHPCriteriasMatrixData> criteriasMatrixDataList = criteriaMatricesRepository.findByGame(g);

        // calculate the agreementIndex for every gamesPlayersPoints of a game and a specific user

        Map<String, Double> resultTotal = AHPRest.CalculateAHP(g.getCriterias(), g.getRequirements(),
                criteriasMatrixDataList, g.getRequirementsMatrixData());
        Map<String, Double> resultPersonal = AHPRest.CalculatePersonalAHP(
                gamesPlayersPoints.get(i).getUser().getUserId(), g.getCriterias(), g.getRequirements(),
                criteriasMatrixDataList, g.getRequirementsMatrixData());
        List<Requirement> gameRequirements = g.getRequirements();
        Double sum = 0.0;/*from  w  w w.  java  2  s  . c  o m*/

        for (int j = 0; j < resultTotal.size(); j++) {
            Double requirementValueTotal = resultTotal
                    .get(gameRequirements.get(j).getRequirementId().toString());
            Double requirementValuePersonal = resultPersonal
                    .get(gameRequirements.get(j).getRequirementId().toString());
            sum = sum + (Math.abs(requirementValueTotal - requirementValuePersonal)
                    * (1.0 - requirementValueTotal));
        }

        Double agreementIndex = M - (M * sum);
        gamesPlayersPoints.get(i).setAgreementIndex(agreementIndex.longValue());

        // calculate the positionInVoting for every gamesPlayersPoints of a game and a specific user

        List<User> players = g.getPlayers();
        List<HAHPRequirementsMatrixData> lrmd = requirementsMatricesRepository.findByGame(g);
        Map<User, Float> gamePlayerVotes = new HashMap<>();

        for (User player : players) {
            Integer total = 0;
            Integer voted = 0;

            if (lrmd != null) {
                for (HAHPRequirementsMatrixData data : lrmd) {
                    for (HAHPPlayerMove pm : data.getPlayerMoves()) {
                        if (pm.getPlayer().getUserId().equals(player.getUserId())) {
                            total++;

                            if (pm.getPlayed() == true && pm.getValue() != null && !pm.getValue().equals(-1l)) {
                                voted++;
                            }
                        }
                    }
                }
            }

            gamePlayerVotes.put(player, total.equals(0) ? 0f : ((new Float(voted) / new Float(total)) * 100));
        }

        LinkedHashMap<User, Float> orderedList = sortHashMapByValues(gamePlayerVotes);
        List<User> indexes = new ArrayList<>(orderedList.keySet());
        Integer index = indexes.indexOf(gamesPlayersPoints.get(i).getUser());
        Double positionInVoting = (orderedList.size() - (new Double(index) + 1.0)) + 1.0;
        gamesPlayersPoints.get(i).setPositionInVoting(positionInVoting.longValue());

        // calculate the virtualPosition of a user base on his/her points in a particular game

        HAHPGamePlayerPoint gpp = gamesPlayersPointsRepository
                .findByUserAndGame(gamesPlayersPoints.get(i).getUser(), g);
        List<HAHPGamePlayerPoint> specificGamePlayersPoints = gamesPlayersPointsRepository.findByGame(g);

        Collections.sort(specificGamePlayersPoints, new CustomComparator());

        Long virtualPosition = specificGamePlayersPoints.indexOf(gpp) + 1l;
        gamesPlayersPoints.get(i).setVirtualPosition(virtualPosition);

        Long movesPoints = 0l;
        Long gameProgressPoints = 0l;
        Long positionInVotingPoints = 0l;
        Long gameStatusPoints = 0l;
        Long agreementIndexPoints = 0l;
        Long totalPoints = 0l;

        // set the movesPoints
        movesPoints = g.getMovesDone().longValue();

        // setGameProgressPoints
        gameProgressPoints = (long) Math.floor(g.getPlayerProgress() / 10);

        // setPositionInVotingPoints
        if (positionInVoting == 1) {
            positionInVotingPoints = 5l;
        } else if (positionInVoting == 2) {
            positionInVotingPoints = 3l;
        } else if (positionInVoting == 3) {
            positionInVotingPoints = 2l;
        }

        // setGameStatusPoints
        if (g.getPlayerProgress() != 100) {
            gameStatusPoints = -20l;
        } else {
            gameStatusPoints = 0l;
        }

        // set AgreementIndexPoints
        agreementIndexPoints = agreementIndex.longValue();
        totalPoints = movesPoints.longValue() + gameProgressPoints + positionInVotingPoints + gameStatusPoints
                + agreementIndexPoints;

        // set totalPoints 0 if the totalPoints are negative
        if (totalPoints < 0) {
            totalPoints = 0l;
        }

        gamesPlayersPoints.get(i).setPoints(totalPoints);
        gamesPlayersPointsRepository.save(gamesPlayersPoints.get(i));
    }

    System.out.println("Finished computing votes");
}

From source file:eu.optimis.ecoefficiencytool.core.EcoEffForecasterIP.java

/**
 * Forecasts the CPU utilization of the VM identified by vmId at the time
 * specified in timeSpan based on previous CPU utilization values and using
 * Linear Regression./*from www  . ja  v a  2 s  .  co m*/
 *
 * @param vmId Virtual Machine's Identifier.
 * @param timeSpan Future time specified in milliseconds since 1/1/1970.
 * @return Forecasted CPU utilization.
 */
private synchronized double forecastVMCpuUtilization(String vmId, Long timeSpan) {
    if (timeSpan == null) {
        timeSpan = new Long(Constants.DEFAULT_TIMESPAN);
    }

    VariableEstimator vmCPUPredictor = vmCPUPredictors.get(vmId);
    if (vmCPUPredictor != null) {
        Date currentDate = new Date();
        //TimeSpan is in minutes, converting it to milliseconds.
        long futurePredictionTimeStamp = currentDate.getTime() + timeSpan.longValue();
        double predictedUtilization = vmCPUPredictor.obtainBestForecast(futurePredictionTimeStamp);
        if (predictedUtilization < 0.0) {
            predictedUtilization = 0.0;
        } else if (predictedUtilization > 100.0) {
            predictedUtilization = 100.0;
        }
        cpuValidator.performForecasts(vmId, futurePredictionTimeStamp);
        return predictedUtilization;
    } else {
        log.error("No previous information was found of VM " + vmId + " to forecast its CPU usage.");
        return -1.0;
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.sync.TenantAwareChainingUserRegistrySynchronizer.java

/**
 * {@inheritDoc}/*w w  w.  j a v  a 2s .  c  o m*/
 */
@Override
public Date getSyncEndTime() {
    final Long end = (Long) this.doGetAttribute(true, END_TIME_ATTRIBUTE);

    final Date lastEnd = end.longValue() == -1 ? null : new Date(end.longValue());
    return lastEnd;
}