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:de.acosix.alfresco.mtsupport.repo.sync.TenantAwareChainingUserRegistrySynchronizer.java

protected Date getMostRecentUpdateTime(final String label, final String zoneId, final boolean splitTxns) {
    final Long result = this.inReadOnlyTransaction(() -> {
        final Long updateTime = (Long) this.doGetAttribute(1, label, zoneId);
        return updateTime;
    }, splitTxns);//from  w ww . j a va 2s  . c o  m

    final Date time = result != null ? new Date(result.longValue()) : null;
    return time;
}

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

protected SampleBean findMatchSampleInSession(HttpServletRequest request, long sampleId) {

    SampleBean sampleBean = (SampleBean) request.getSession().getAttribute("theSample");
    if (sampleBean == null) {
        logger.error("No sample in session"); //should not happen
        return null;
    }// w  ww.  jav a2  s.co  m

    Long domainSampleId = sampleBean.getDomain().getId();
    if (domainSampleId == null) {
        if (sampleId == 0)
            return sampleBean; // from a failed save, incomplete sampleBean
        else {
            logger.error("Sample in session doesn't seem to be valid");
            return null;
        }
    }

    if (sampleId != domainSampleId.longValue()) {
        logger.error("The given sample id doesn't match the sample id in session");
        return null;
    }

    return sampleBean;

}

From source file:com.ibm.bi.dml.yarn.ropt.ResourceOptimizer.java

/**
 * //from  w w  w  . j  ava2 s . co m
 * @param prog
 * @param cc
 * @param cptype
 * @param mrtype
 * @return
 * @throws DMLRuntimeException
 */
public synchronized static ResourceConfig optimizeResourceConfig(ArrayList<ProgramBlock> prog,
        YarnClusterConfig cc, GridEnumType cptype, GridEnumType mrtype) throws DMLRuntimeException {
    ResourceConfig ROpt = null;

    try {
        //init statistics and counters
        Timing time = new Timing(true);
        initStatistics();

        //get constraints (yarn-specific: force higher min to limit degree of parallelism)
        long max = (long) (YarnOptimizerUtils.toB(cc.getMaxAllocationMB()) / DMLYarnClient.MEM_FACTOR);
        long minCP = (long) Math.max(YarnOptimizerUtils.toB(cc.getMinAllocationMB()) / DMLYarnClient.MEM_FACTOR,
                MIN_CP_BUDGET);
        long minMR = YarnOptimizerUtils.computeMinContraint(minCP, max, cc.getAvgNumCores());

        //enumerate grid points for given types (refers to jvm max heap)
        ArrayList<Long> SRc = enumerateGridPoints(prog, minCP, max, cptype);
        ArrayList<Long> SRm = enumerateGridPoints(prog, minMR, max, mrtype);

        //init resource config and global costs
        ROpt = new ResourceConfig(prog, minMR);
        double costOpt = Double.MAX_VALUE;

        for (Long rc : SRc) //enumerate CP memory rc
        {
            //baseline compile and pruning
            ArrayList<ProgramBlock> B = compileProgram(prog, null, rc, minMR); //unrolled Bp
            ArrayList<ProgramBlock> Bp = pruneProgramBlocks(B);
            LOG.debug("Enum (rc=" + rc + "): |B|=" + B.size() + ", |Bp|=" + Bp.size());

            //init local memo table [resource, cost]
            double[][] memo = initLocalMemoTable(Bp, minMR);

            for (int i = 0; i < Bp.size(); i++) //for all relevant blocks
            {
                ProgramBlock pb = Bp.get(i);

                for (Long rm : SRm) //for each MR memory 
                {
                    //recompile program block 
                    recompileProgramBlock(pb, rc, rm);

                    //local costing and memo table maintenance (cost entire program to account for 
                    //in-memory status of variables and loops)
                    double lcost = getProgramCosts(pb);
                    if (lcost < memo[i][1]) { //accept new local opt
                        memo[i][0] = rm;
                        memo[i][1] = lcost;
                        //LOG.debug("Enum (rc="+rc+"): found new local opt w/ cost="+lcost);         
                    }
                    //LOG.debug("Enum (rc="+rc+", rm="+rm+"): lcost="+lcost+", mincost="+memo[i][1]);                  
                }
            }

            //global costing 
            double[][] gmemo = initGlobalMemoTable(B, Bp, memo, minMR);
            recompileProgramBlocks(B, rc, gmemo);
            double gcost = getProgramCosts(B.get(0).getProgram());
            if (gcost < costOpt) { //accept new global opt
                ROpt.setCPResource(rc.longValue());
                ROpt.setMRResources(B, gmemo);
                costOpt = gcost;
                LOG.debug("Enum (rc=" + rc + "): found new opt w/ cost=" + gcost);
            }
        }

        //print optimization summary
        LOG.info("Optimization summary:");
        LOG.info("-- optimal plan (rc, rm): " + YarnOptimizerUtils.toMB(ROpt.getCPResource()) + "MB, "
                + YarnOptimizerUtils.toMB(ROpt.getMaxMRResource()) + "MB");
        LOG.info("-- costs of optimal plan: " + costOpt);
        LOG.info("-- # of block compiles:   " + _cntCompilePB);
        LOG.info("-- # of block costings:   " + _cntCostPB);
        LOG.info("-- optimization time:     " + String.format("%.3f", (double) time.stop() / 1000) + " sec.");
        LOG.info("-- optimal plan details:  " + ROpt.serialize());
    } catch (Exception ex) {
        throw new DMLRuntimeException(ex);
    }

    return ROpt;
}

From source file:com.cyberway.issue.crawler.fetcher.FetchHTTP.java

private long getMaxLength(CrawlURI curi) {
    Long res;
    try {//from   w w w . j  ava2s . c  o m
        res = (Long) getAttribute(ATTR_MAX_LENGTH_BYTES, curi);
        if (res.longValue() == OLD_DEFAULT_MAX_LENGTH_BYTES) {
            res = DEFAULT_MAX_LENGTH_BYTES;
        }
    } catch (Exception e) {
        res = DEFAULT_MAX_LENGTH_BYTES;
    }
    return res.longValue();
}

From source file:com.redhat.rhn.frontend.xmlrpc.errata.ErrataHandler.java

/**
 * Set erratum details.// w ww.j  av a  2 s.  com
 *
 * @param loggedInUser The current user
 * @param advisoryName The advisory name of the errata
 * @param details Map of (optional) erratum details to be set.
 * @return 1 on success, exception thrown otherwise.
 *
 * @xmlrpc.doc Set erratum details. All arguments are optional and will only be modified
 * if included in the struct. This method will only allow for modification of custom
 * errata created either through the UI or API.
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #param("string", "advisoryName")
 * @xmlrpc.param
 *      #struct("errata details")
 *          #prop("string", "synopsis")
 *          #prop("string", "advisory_name")
 *          #prop("int", "advisory_release")
 *          #prop_desc("string", "advisory_type", "Type of advisory (one of the
 *                  following: 'Security Advisory', 'Product Enhancement Advisory',
 *                  or 'Bug Fix Advisory'")
 *          #prop("string", "product")
 *          #prop("dateTime.iso8601", "issue_date")
 *          #prop("dateTime.iso8601", "update_date")
 *          #prop("string", "errataFrom")
 *          #prop("string", "topic")
 *          #prop("string", "description")
 *          #prop("string", "references")
 *          #prop("string", "notes")
 *          #prop("string", "solution")
 *          #prop_desc("array", "bugs", "'bugs' is the key into the struct")
 *              #array()
 *                 #struct("bug")
 *                    #prop_desc("int", "id", "Bug Id")
 *                    #prop("string", "summary")
 *                    #prop("string", "url")
 *                 #struct_end()
 *              #array_end()
 *          #prop_desc("array", "keywords", "'keywords' is the key into the struct")
 *              #array_single("string", "keyword - List of keywords to associate
 *                  with the errata.")
 *          #prop_desc("array", "CVEs", "'cves' is the key into the struct")
 *              #array_single("string", "cves - List of CVEs to associate
 *                  with the errata. (valid only for published errata)")
 *     #struct_end()
 *
 *  @xmlrpc.returntype #return_int_success()
 */
public Integer setDetails(User loggedInUser, String advisoryName, Map<String, Object> details) {

    Errata errata = lookupErrata(advisoryName, loggedInUser.getOrg());

    if (errata.getOrg() == null) {
        // Errata in the null org should not be modified; therefore, this is
        // considered an invalid errata for this request
        throw new InvalidErrataException(errata.getAdvisoryName());
    }

    // confirm that the user only provided valid keys in the map
    Set<String> validKeys = new HashSet<String>();
    validKeys.add("synopsis");
    validKeys.add("advisory_name");
    validKeys.add("advisory_release");
    validKeys.add("advisory_type");
    validKeys.add("product");
    validKeys.add("issue_date");
    validKeys.add("update_date");
    validKeys.add("errataFrom");
    validKeys.add("topic");
    validKeys.add("description");
    validKeys.add("references");
    validKeys.add("notes");
    validKeys.add("solution");
    validKeys.add("bugs");
    validKeys.add("keywords");
    if (errata.isPublished()) {
        validKeys.add("cves");
    }
    validateMap(validKeys, details);

    validKeys.clear();
    validKeys.add("id");
    validKeys.add("summary");
    validKeys.add("url");
    if (details.containsKey("bugs")) {
        for (Map<String, Object> bugMap : (ArrayList<Map<String, Object>>) details.get("bugs")) {

            validateMap(validKeys, bugMap);
        }
    }

    if (details.containsKey("issue_date")) {
        try {
            errata.setIssueDate((Date) details.get("issue_date"));
        } catch (ClassCastException e) {
            throw new InvalidParameterException("Wrong 'issue_date' format.");
        }
    }

    if (details.containsKey("update_date")) {
        try {
            errata.setUpdateDate((Date) details.get("update_date"));
        } catch (ClassCastException e) {
            throw new InvalidParameterException("Wrong 'update_date' format.");
        }
    }

    if (details.containsKey("synopsis")) {
        if (StringUtils.isBlank((String) details.get("synopsis"))) {
            throw new InvalidParameterException("Synopsis is required.");
        }
        errata.setSynopsis((String) details.get("synopsis"));
    }
    if (details.containsKey("advisory_name")) {
        if (StringUtils.isBlank((String) details.get("advisory_name"))) {
            throw new InvalidParameterException("Advisory name is required.");
        }
        errata.setAdvisoryName((String) details.get("advisory_name"));
    }
    if (details.containsKey("advisory_release")) {
        Long rel = new Long((Integer) details.get("advisory_release"));
        if (rel.longValue() > ErrataManager.MAX_ADVISORY_RELEASE) {
            throw new InvalidAdvisoryReleaseException(rel.longValue());
        }
        errata.setAdvisoryRel(rel);
    }
    if (details.containsKey("advisory_type")) {
        String pea = "Product Enhancement Advisory"; // hack for checkstyle
        if (!((String) details.get("advisory_type")).equals("Security Advisory")
                && !((String) details.get("advisory_type")).equals(pea)
                && !((String) details.get("advisory_type")).equals("Bug Fix Advisory")) {
            throw new InvalidParameterException("Invalid advisory type");
        }
        errata.setAdvisoryType((String) details.get("advisory_type"));
    }
    if (details.containsKey("product")) {
        if (StringUtils.isBlank((String) details.get("product"))) {
            throw new InvalidParameterException("Product name is required.");
        }
        errata.setProduct((String) details.get("product"));
    }
    if (details.containsKey("errataFrom")) {
        errata.setErrataFrom((String) details.get("errataFrom"));
    }
    if (details.containsKey("topic")) {
        if (StringUtils.isBlank((String) details.get("topic"))) {
            throw new InvalidParameterException("Topic is required.");
        }
        errata.setTopic((String) details.get("topic"));
    }
    if (details.containsKey("description")) {
        if (StringUtils.isBlank((String) details.get("description"))) {
            throw new InvalidParameterException("Description is required.");
        }
        errata.setDescription((String) details.get("description"));
    }
    if (details.containsKey("solution")) {
        if (StringUtils.isBlank((String) details.get("solution"))) {
            throw new InvalidParameterException("Solution is required.");
        }
        errata.setSolution((String) details.get("solution"));
    }
    if (details.containsKey("references")) {
        errata.setRefersTo((String) details.get("references"));
    }
    if (details.containsKey("notes")) {
        errata.setNotes((String) details.get("notes"));
    }
    if (details.containsKey("bugs")) {

        if (errata.getBugs() != null) {
            errata.getBugs().clear();
            HibernateFactory.getSession().flush();
        }

        for (Map<String, Object> bugMap : (ArrayList<Map<String, Object>>) details.get("bugs")) {

            if (bugMap.containsKey("id") && bugMap.containsKey("summary")) {
                String url = null;
                if (bugMap.containsKey("url")) {
                    url = (String) bugMap.get("url");
                }

                Bug bug = ErrataFactory.createPublishedBug(new Long((Integer) bugMap.get("id")),
                        (String) bugMap.get("summary"), url);

                errata.addBug(bug);
            }
        }
    }
    if (details.containsKey("keywords")) {
        if (errata.getKeywords() != null) {
            errata.getKeywords().clear();
            HibernateFactory.getSession().flush();
        }
        for (String keyword : (ArrayList<String>) details.get("keywords")) {
            errata.addKeyword(keyword);
        }
    }
    if (details.containsKey("cves")) {
        if (errata.getCves() != null) {
            errata.getCves().clear();
            HibernateFactory.getSession().flush();
        }
        for (String cveName : (ArrayList<String>) details.get("cves")) {
            Cve c = CveFactory.lookupByName(cveName);
            if (c == null) {
                c = new Cve();
                c.setName(cveName);
                CveFactory.save(c);
            }
            errata.getCves().add(c);
        }
    }

    // ALWAYS change the advisory to match, as we do in the UI.
    errata.setAdvisory(errata.getAdvisoryName() + "-" + errata.getAdvisoryRel().toString());

    //Save the errata
    ErrataManager.storeErrata(errata);

    return 1;
}

From source file:net.cellcloud.talk.TalkService.java

/** ???
 *//*from ww w.j a  va2 s.co m*/
protected void noticeResume(Cellet cellet, String targetTag, Queue<Long> timestampQueue,
        Queue<Primitive> primitiveQueue, long startTime) {
    TalkSessionContext context = this.tagContexts.get(targetTag);
    if (null == context) {
        if (Logger.isDebugLevel()) {
            Logger.d(TalkService.class, "Not find session by remote tag");
        }
        return;
    }

    Message message = null;

    synchronized (context) {
        // ?
        TalkTracker tracker = context.getTracker();
        // ?? Cellet
        if (tracker.getCellet(cellet.getFeature().getIdentifier()) == cellet) {
            Session session = context.getLastSession();

            // ??
            for (int i = 0, size = timestampQueue.size(); i < size; ++i) {
                Long timestamp = timestampQueue.poll();
                Primitive primitive = primitiveQueue.poll();
                if (timestamp.longValue() >= startTime) {
                    message = this.packetResume(targetTag, timestamp, primitive);
                    if (null != message) {
                        session.write(message);
                    }
                }
            }
        }
    }
}

From source file:xx.tream.chengxin.ms.action.TrainBackAction.java

@RequestMapping({ "/toUpdateTrain" })
public String toUpdateTrain(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response,
        FormMap formMap, Integer currentPage, Integer pageSize, Long id) {
    Map<String, Object> oldTrainInfoMap = this.paramService.findByCode("canAddOldTrain");
    modelMap.put("oldTrainInfoMap", oldTrainInfoMap);
    Map<String, Object> queryMap = new HashMap<String, Object>();
    queryMap.put("trainId", id);
    Map<String, Object> user = ParamUtil.getSessionUser(request);
    queryMap.put("updateUser", user.get("id"));
    queryMap.put("updateStatus", "0");
    List<Map<String, Object>> list = this.trainBackService.queryByParam(queryMap);
    if ((list != null) && (list.size() > 0)) {
        modelMap.put("msg", "??");
    } else {//from w  w w  .j a  v a  2s.  co m
        Map<String, Object> trainMap = this.trainService.find(id.longValue());
        modelMap.put("trainMap", trainMap);
    }
    return "train/updateTrain";
}

From source file:com.evolveum.midpoint.gui.api.util.WebComponentUtil.java

public static Integer safeLongToInteger(Long l) {
    if (l == null) {
        return null;
    }/* w  w  w  .j  ava 2s  .c om*/

    if (l > Integer.MAX_VALUE || l < Integer.MIN_VALUE) {
        throw new IllegalArgumentException("Couldn't transform long '" + l + "' to int, too big or too small.");
    }

    return (int) l.longValue();
}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * ?????.//from  www  .  ja  v a  2s  . co m
 * 
 * @param response ?
 * @param deviceId ?ID
 * @param path 
 * @param data 
 * @param position ????
 */
public void writeDataToFile(final Intent response, final String deviceId, final String path, final byte[] data,
        final Long position) {
    int pos = 0;
    if (position != null) {
        pos = (int) position.longValue();
    }
    if (pos < 0 || data.length < pos) {
        MessageUtils.setInvalidRequestParameterError(response, "invalid position");
        sendBroadcast(response);
        return;
    }
    if (mFileOpenFlag && mFileName.equals(path)) {
        try {
            if (mFlag.equals(Flag.RW)) {
                // ???
                mFileDescriptorCurrentSystemTime = System.currentTimeMillis();
                Date date = new Date();
                SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy'-'MM'-'dd' 'kk':'mm':'ss'+0900'");
                mFileDescriptorCurrentTime = mDateFormat.format(date);
                mFos.write(data, pos, data.length - pos);
                response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_OK);
                response.putExtra(DConnectMessage.EXTRA_VALUE, "Write data:" + path);
                sendBroadcast(response);
                sendFileDescriptorOnWatchfileEvent();
            } else {
                MessageUtils.setIllegalDeviceStateError(response, "Read mode only");
                sendBroadcast(response);
            }

        } catch (Exception e) {
            MessageUtils.setUnknownError(response, "Can not write data:" + path + e);
            sendBroadcast(response);
        }
    } else {
        response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_ERROR);
        response.putExtra(DConnectMessage.EXTRA_VALUE, "Can not write data:" + path);
        sendBroadcast(response);
    }
}

From source file:de.otto.mongodb.profiler.web.OpProfileController.java

@RequestMapping(value = "/{id:.+}/stats", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<String> getStatsData(@PathVariable("connectionId") final String connectionId,
        @PathVariable("databaseName") final String databaseName, @PathVariable("id") final String id,
        @RequestParam(value = "datum", required = false) final List<String> datum,
        @RequestParam(value = "from", required = false) final Long from,
        @RequestParam(value = "to", required = false) final Long to,
        @RequestParam(value = "min", required = false) final Double min,
        @RequestParam(value = "max", required = false) final Double max,
        @RequestParam(value = "limit", required = false) final Integer limit) throws Exception {

    final ProfiledDatabase database = requireDatabase(connectionId, databaseName);

    final OpProfile profile = requireProfile(database, id);

    final JsonObject json = new JsonObject();
    final JsonObject outliersJson = new JsonObject();

    final JsonObject params = new JsonObject();
    outliersJson.add("params", params);

    final JsonArray datumParamValues = new JsonArray();
    params.add("datum", datumParamValues);
    if (datum != null) {
        for (String datumValue : datum) {
            datumParamValues.add(new JsonPrimitive(datumValue));
        }//from  w ww.  j  a va  2s  . com
    }

    final DateTime lowerTimeBound = from != null ? new DateTime(from.longValue()) : null;
    final DateTime upperTimeBound = to != null ? new DateTime(to.longValue()) : null;

    if (lowerTimeBound != null && upperTimeBound != null && !upperTimeBound.isAfter(lowerTimeBound)) {
        throw new IllegalArgumentException("'to' must not be lower than or equal to 'from'");
    }

    params.add("from", from != null ? new JsonPrimitive(from.longValue()) : null);
    params.add("to", to != null ? new JsonPrimitive(to.longValue()) : null);

    if (min != null && max != null && !(max.longValue() > min.longValue())) {
        throw new IllegalArgumentException("'max' must not be lower than or equal to 'min'");
    }

    params.add("min", min != null ? new JsonPrimitive(min.intValue()) : null);
    params.add("max", max != null ? new JsonPrimitive(max.intValue()) : null);

    if (limit != null && limit.intValue() < 1) {
        throw new IllegalArgumentException("'limit' must not be lower than 1");
    }

    final int maximumValues = limit != null && limit.intValue() > 0 ? limit.intValue() : maximumGraphValues;

    params.add("limit", new JsonPrimitive(maximumValues));

    if (profile.getOutlierConfiguration() != null && profile.getOutlierConfiguration().captureOutliers()) {

        final OutlierGraphDataBuilder builder = new OutlierGraphDataBuilder(datum, maximumValues,
                lowerTimeBound, upperTimeBound, min, max);

        builder.add("executionTimeOutliers", "Execution time outliers", profile.getAverageMillisOutliers());
        builder.add("readLockAcquisitionTimeOutliers", "Read lock acquisition time outliers",
                profile.getAverageAcquireReadLockMicrosOutliers());
        builder.add("writeLockAcquisitionTimeOutliers", "Write lock acquisition time outliers",
                profile.getAverageAcquireWriteLockMicrosOutliers());
        builder.add("readLockTimeOutliers", "Read lock time outliers",
                profile.getAverageLockedReadMicrosOutliers());
        builder.add("writeLockTimeOutliers", "Write lock time outliers",
                profile.getAverageLockedWriteMicrosOutliers());

        outliersJson.add("data", builder.getGroups());
        outliersJson.add("lowestTime", new JsonPrimitive(builder.getLowestTime()));
        outliersJson.add("highestTime", new JsonPrimitive(builder.getHighestTime()));

        final JsonArray warningJson = new JsonArray();

        if (!builder.getKeysWithTooMuchData().isEmpty()) {
            final StringBuilder warning = new StringBuilder();
            final JsonArray tooMuchDataFor = new JsonArray();
            for (String key : builder.getKeysWithTooMuchData()) {
                tooMuchDataFor.add(new JsonPrimitive(key));
                if (warning.length() > 0) {
                    warning.append(", ");
                }
                warning.append(key);
            }
            warningJson.add(new JsonPrimitive(String.format(
                    "The maximum amount of %d values has been exceeded. "
                            + "The following data could not be (completely) returned: %s. "
                            + "Please narrow your filter to get applicable results.",
                    maximumValues, warning.toString())));
        }

        if (warningJson.size() > 0) {
            outliersJson.add("warnings", warningJson);
        }
    }

    json.add("outliers", outliersJson);

    return new HttpEntity<>(json.toString());
}