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.npower.dm.hibernate.management.ProfileAssignmentManagementBeanImpl.java

public void update(ProfileAssignment assignment) throws DMException {
    if (assignment == null) {
        throw new NullPointerException("Could not add a null ProfileAssignmentEntity into database.");
    }/*w  ww  .  j ava  2  s . c  om*/
    Session session = this.getHibernateSession();
    try {
        ProfileConfig profile = assignment.getProfileConfig();

        ProfileTemplate template = profile.getProfileTemplate();
        Device device = assignment.getDevice();
        Model model = device.getModel();

        ProfileMapping mapping = model.getProfileMap(template);
        if (mapping == null) {
            // TODO uncomments the following line, make sure the device had a ProfileMapping for this template.
            //throw new DMException("Could not assign the profile to this device, no ProfileMapping defined for this device.");
        }

        long id = assignment.getID();
        if (id == 0) {
            // is new!
            // Automaticly caculate assignIndex

            Query query = session.createQuery("select max(assignmentIndex) from ProfileAssignmentEntity "
                    + " where DEVICE_ID=? and PROFILE_ID=?");
            query.setLong(0, device.getID());
            query.setLong(1, profile.getID());

            Long assignmentIndex = (Long) query.uniqueResult();
            if (assignmentIndex == null) {
                assignment.setAssignmentIndex(1L);
            } else {
                assignment.setAssignmentIndex(assignmentIndex.longValue() + 1);
            }
        }

        // TODO checking this assignment before update(), make sure every attributes has been filled value and match the policy defined by ProfileTemplate
        session.saveOrUpdate(assignment);
    } catch (HibernateException e) {
        throw new DMException(e);
    } finally {
    }
}

From source file:org.apache.streams.twitter.provider.TwitterFollowingProviderTask.java

protected void getFollowing(Long id) {

    Preconditions.checkArgument(endpoint.equals("friends") || endpoint.equals("followers"));

    int keepTrying = 0;

    long curser = -1;

    do {/*  ww w .  jav  a2  s. c  o m*/
        try {
            twitter4j.User followee4j;
            String followeeJson;
            try {
                followee4j = client.users().showUser(id);
                followeeJson = TwitterObjectFactory.getRawJSON(followee4j);
            } catch (TwitterException e) {
                LOGGER.error("Failure looking up " + id);
                break;
            }

            PagableResponseList<twitter4j.User> list = null;
            if (endpoint.equals("followers"))
                list = client.friendsFollowers().getFollowersList(id.longValue(), curser, max_per_page);
            else if (endpoint.equals("friends"))
                list = client.friendsFollowers().getFriendsList(id.longValue(), curser, max_per_page);

            Preconditions.checkNotNull(list);
            Preconditions.checkArgument(list.size() > 0);

            for (twitter4j.User follower4j : list) {

                String followerJson = TwitterObjectFactory.getRawJSON(follower4j);

                try {
                    Follow follow = new Follow().withFollowee(mapper.readValue(followeeJson, User.class))
                            .withFollower(mapper.readValue(followerJson, User.class));

                    ComponentUtils.offerUntilSuccess(new StreamsDatum(follow), provider.providerQueue);
                } catch (JsonParseException e) {
                    LOGGER.warn(e.getMessage());
                } catch (JsonMappingException e) {
                    LOGGER.warn(e.getMessage());
                } catch (IOException e) {
                    LOGGER.warn(e.getMessage());
                }
            }
            if (list.size() == max_per_page)
                curser = list.getNextCursor();
            else
                break;
        } catch (TwitterException twitterException) {
            keepTrying += TwitterErrorHandler.handleTwitterError(client, twitterException);
        } catch (Exception e) {
            keepTrying += TwitterErrorHandler.handleTwitterError(client, e);
        }
    } while (curser != 0 && keepTrying < 10);
}

From source file:business.controllers.RequestController.java

private void incrementCount(Map<String, Long> counts, String key) {
    Long count = counts.get(key);
    counts.put(key, ((count == null) ? 0 : count.longValue()) + 1);
}

From source file:hu.netmind.beankeeper.modification.impl.ModificationTrackerImpl.java

/**
 * Return whether the given object changed since the given serial.
 *///from www .j a va 2  s .  c o  m
private boolean hasChanged(Long id, Class objectClass, Long serial) {
    // Try to get a modification entry if there is one for that object
    ModificationEntry entry = (ModificationEntry) entriesById.get(id);
    // If there was no entry, then there was no modification
    // since the last removed serial. If the query serial is newer than
    // the last removed serial, then the object must be current.
    if ((entry == null) && ((lastCacheRemovedSerial == null)
            || (serial.longValue() > lastCacheRemovedSerial.longValue()))) {
        logger.debug("there was no modification yet for this class in cache, "
                + "but the serial is newer the cache's start serial, so object is current.");
        return false;
    }
    // If there was no entry, and the query serial is old, we must check the
    // database whether that object is current. Note, that at this point the
    // object should be locked, or else this query can not tell for sure.
    if ((entry == null) && (lastCacheRemovedSerial != null)
            && (serial.longValue() <= lastCacheRemovedSerial.longValue())) {
        // Query the object now
        Object current = queryService.findSingle("find obj(" + objectClass.getName() + ") where obj = ?",
                new Object[] { new Identifier(id) });
        if (current == null) {
            logger.debug("object does not exists, so it's unchanged: " + id);
            return false; // Object does not yet exist globally
        }
        PersistenceMetaData persistenceMeta = objectTracker.getMetaData(current);
        if (persistenceMeta.getPersistenceStart().longValue() <= serial.longValue()) {
            logger.debug("object is old, but database said it is current.");
            return false;
        } else {
            logger.debug("object is old, and database said it is also not current.");
            return true;
        }
    }
    // If there is an enty, but it has potentialTxSerial, that means
    // it was in a transaction, which started commiting, but never finished.
    // The client disconnected, and the locks were relinquished. In this
    // case, we must query the database to make sure the transaction commited.
    if (entry.potentialTxSerial != null) {
        // Query the object now
        Object current = queryService.findSingle("find obj(" + objectClass.getName() + ") where obj = ?",
                new Object[] { new Identifier(id) });
        if (current == null) {
            logger.debug("unfinished transaction found, but object not found in database: " + id);
            return false; // Object does not yet exist globally
        }
        PersistenceMetaData persistenceMeta = objectTracker.getMetaData(current);
        // If the metadata's serial equals the potentialChangeSerial, then commit
        // the transaction manually.
        if (persistenceMeta.getPersistenceStart().longValue() >= entry.potentialChangeSerial.longValue()) {
            logger.info("transaction commit not received for serial: " + entry.potentialTxSerial
                    + ", but transaction commited according to database.");
            // Transaction was committed successfully
            endTransaction(entry.potentialTxSerial);
        } else {
            logger.info("transaction commit not received for serial: " + entry.potentialTxSerial
                    + ", and transaction failed according to database.");
            // Originating transaction failed. Remove those entries which do
            // not have a lastChangeSerial, because those were not modified yet.
            List entries = (List) entriesByTxSerial.remove(entry.potentialTxSerial);
            for (int i = 0; (entries != null) && (i < entries.size()); i++) {
                ModificationEntry removeEntry = (ModificationEntry) entries.get(i);
                entriesById.remove(removeEntry.id);
                entriesByDate.remove(removeEntry);
                modifyClassEntries(removeEntry, false);
            }
        }
        // Now compare the query serial with the object start serial
        if (persistenceMeta.getPersistenceStart().longValue() <= serial.longValue()) {
            logger.debug("unfinished transaction is resolved, current object did not change.");
            return false;
        }
    }
    // Default is to compare entry's last change serial with the query date.
    // If the lastChangeSerial is not yet present in the entry, that means
    // the modification already started, but not yet commited. This means it is
    // not modified.
    if ((entry.lastChangeSerial == null) || (entry.lastChangeSerial.longValue() <= serial.longValue())) {
        logger.debug("there was a change for that object in cache, but the object is newer. "
                + "Last change was on: " + entry.lastChangeSerial + ", current object selected: " + serial);
        return false;
    }
    // Last default is changed
    logger.debug("object was not current, fallthrough return");
    return true;
}

From source file:com.eviware.soapui.tools.SoapUITestCaseRunner.java

@Override
public void afterStep(TestCaseRunner testRunner, TestCaseRunContext runContext, TestStepResult result) {
    super.afterStep(testRunner, runContext, result);
    TestStep currentStep = runContext.getCurrentStep();

    if (currentStep instanceof Assertable) {
        Assertable requestStep = (Assertable) currentStep;
        for (int c = 0; c < requestStep.getAssertionCount(); c++) {
            TestAssertion assertion = requestStep.getAssertionAt(c);
            log.info("Assertion [" + assertion.getName() + "] has status " + assertion.getStatus());
            if (assertion.getStatus() == AssertionStatus.FAILED) {
                for (AssertionError error : assertion.getErrors())
                    log.error("ASSERTION FAILED -> " + error.getMessage());

                assertions.add(assertion);
                assertionResults.put(assertion, (WsdlTestStepResult) result);
            }//from ww w. j av  a 2 s. c  o m

            testAssertionCount++;
        }
    }

    String countPropertyName = currentStep.getName() + " run count";
    Long count = (Long) runContext.getProperty(countPropertyName);
    if (count == null) {
        count = new Long(0);
    }

    runContext.setProperty(countPropertyName, new Long(count.longValue() + 1));

    if (result.getStatus() == TestStepStatus.FAILED || exportAll) {
        try {
            String exportSeparator = System.getProperty(SOAPUI_EXPORT_SEPARATOR, "-");

            TestCase tc = currentStep.getTestCase();
            String nameBase = StringUtils.createFileName(tc.getTestSuite().getName(), '_') + exportSeparator
                    + StringUtils.createFileName(tc.getName(), '_') + exportSeparator
                    + StringUtils.createFileName(currentStep.getName(), '_') + "-" + count.longValue() + "-"
                    + result.getStatus();

            WsdlTestCaseRunner callingTestCaseRunner = (WsdlTestCaseRunner) runContext
                    .getProperty("#CallingTestCaseRunner#");

            if (callingTestCaseRunner != null) {
                WsdlTestCase ctc = callingTestCaseRunner.getTestCase();
                WsdlRunTestCaseTestStep runTestCaseTestStep = (WsdlRunTestCaseTestStep) runContext
                        .getProperty("#CallingRunTestCaseStep#");

                nameBase = StringUtils.createFileName(ctc.getTestSuite().getName(), '_') + exportSeparator
                        + StringUtils.createFileName(ctc.getName(), '_') + exportSeparator
                        + StringUtils.createFileName(runTestCaseTestStep.getName(), '_') + exportSeparator
                        + StringUtils.createFileName(tc.getTestSuite().getName(), '_') + exportSeparator
                        + StringUtils.createFileName(tc.getName(), '_') + exportSeparator
                        + StringUtils.createFileName(currentStep.getName(), '_') + "-" + count.longValue() + "-"
                        + result.getStatus();
            }

            String absoluteOutputFolder = getAbsoluteOutputFolder(ModelSupport.getModelItemProject(tc));
            String fileName = absoluteOutputFolder + File.separator + nameBase + ".txt";

            if (result.getStatus() == TestStepStatus.FAILED)
                log.error(currentStep.getName() + " failed, exporting to [" + fileName + "]");

            new File(fileName).getParentFile().mkdirs();

            PrintWriter writer = new PrintWriter(fileName);
            result.writeTo(writer);
            writer.close();

            // write attachments
            if (result instanceof MessageExchange) {
                Attachment[] attachments = ((MessageExchange) result).getResponseAttachments();
                if (attachments != null && attachments.length > 0) {
                    for (int c = 0; c < attachments.length; c++) {
                        fileName = nameBase + "-attachment-" + (c + 1) + ".";

                        Attachment attachment = attachments[c];
                        String contentType = attachment.getContentType();
                        if (!"application/octet-stream".equals(contentType) && contentType != null
                                && contentType.indexOf('/') != -1) {
                            fileName += contentType.substring(contentType.lastIndexOf('/') + 1);
                        } else {
                            fileName += "dat";
                        }

                        fileName = absoluteOutputFolder + File.separator + fileName;

                        FileOutputStream outFile = new FileOutputStream(fileName);
                        Tools.writeAll(outFile, attachment.getInputStream());
                        outFile.close();
                    }
                }
            }

            exportCount++;
        } catch (Exception e) {
            log.error("Error saving failed result: " + e, e);
        }
    }

    testStepCount++;

}

From source file:com.gemstone.gemfire.distributed.internal.membership.gms.messenger.JGroupsMessengerJUnitTest.java

@Test
public void testGetMessageState() throws Exception {
    initMocks(true/*multicast*/);
    messenger.testMulticast(50); // do some multicast messaging
    NAKACK2 nakack = (NAKACK2) messenger.myChannel.getProtocolStack().findProtocol("NAKACK2");
    assertNotNull(nakack);/*www . j  a v  a 2  s  .  com*/
    long seqno = nakack.getCurrentSeqno();
    Map state = new HashMap();
    messenger.getMessageState(null, state, true);
    assertEquals(1, state.size());
    Long stateLong = (Long) state.values().iterator().next();
    assertTrue("expected multicast state to be at least " + seqno + " but it was " + stateLong.longValue(),
            stateLong.longValue() >= seqno);
}

From source file:de.jwic.base.SessionContext.java

/**
 * Validates if the ticket number of the specified layerId equals the expected ticket number.
 * If the numbers are equal, true is returned and the request ticket 
 * number is increased by one./*from  ww w .  j a  v  a2s  .  c  o  m*/
 * @param ticket
 * @return
 */
public boolean validateTicket(long ticket, String layerId) {
    if (layerId == null || layerId.length() == 0) {
        return validateTicket(ticket);
    }
    Long lngTicket = layerTickets.get(layerId);
    long lTicket = lngTicket == null ? 0 : lngTicket.longValue();

    if (ticket == lTicket) {
        if (lTicket == Long.MAX_VALUE) {
            lTicket = 0;
        } else {
            lTicket++;
        }
        layerTickets.put(layerId, new Long(lTicket));
        return true;
    }
    return false;
}

From source file:org.duniter.core.client.service.bma.BlockchainRemoteServiceImpl.java

@Override
public long getLastUD(String currencyId) {
    // get block number with UD
    String blocksWithUdResponse = executeRequest(currencyId, URL_BLOCK_WITH_UD, String.class);
    Integer blockNumber = getLastBlockNumberFromJson(blocksWithUdResponse);

    // If no result (this could happen when no UD has been send
    if (blockNumber == null) {
        // get the first UD from currency parameter
        BlockchainParameters parameter = getParameters(currencyId);
        return parameter.getUd0();
    }//from   w  ww. j av a 2  s .  c  o  m

    // Get the UD from the last block with UD
    Long lastUD = getBlockDividend(currencyId, blockNumber);

    // Check not null (should never append)
    if (lastUD == null) {
        throw new TechnicalException("Unable to get last UD from server");
    }
    return lastUD.longValue();
}

From source file:de.jwic.base.SessionContext.java

/**
 * Returns the ticket number for the specified layer.
 * @param layerId//w  w w . jav  a  2s . co m
 * @return
 */
public long getRequestTicket(String layerId) {
    if (layerId == null || layerId.length() == 0) {
        return requestTicket;
    }
    Long l = layerTickets.get(layerId);
    if (l == null) {
        return 0;
    }
    return l.longValue();
}

From source file:net.sf.sze.frontend.zeugnis.ZeugnisController.java

/**
 * Zeigt die Zeugnisdetails an./*w ww. j a  va  2 s.  c o  m*/
 * @param halbjahrId die Id des Schulhalbjahres
 * @param klassenId die Id der Klasse
 * @param schuelerId die Id des Schuelers
 * @param model das Model
 * @return die logische View
 */
@RequestMapping(value = URL.ZeugnisPath.ZEUGNIS_EDIT_DETAIL, method = RequestMethod.GET)
public String editZeugnisDetail(@PathVariable(URL.Session.P_HALBJAHR_ID) Long halbjahrId,
        @PathVariable(URL.Session.P_KLASSEN_ID) Long klassenId,
        @PathVariable(URL.Session.P_SCHUELER_ID) Long schuelerId, Model model) {
    final Zeugnis zeugnis = zeugnisErfassungsService.getZeugnis(halbjahrId, schuelerId);
    final SchuelerList schuelerList = schuelerService.getSchuelerWithZeugnis(halbjahrId.longValue(),
            klassenId.longValue(), schuelerId);
    fillZeugnisDetailModel(model, halbjahrId, klassenId, schuelerId, zeugnis, schuelerList.getPrevSchuelerId(),
            schuelerList.getNextSchuelerId());
    return EDIT_ZEUGNIS_DETAIL_VIEW;
}