Example usage for java.lang Long intValue

List of usage examples for java.lang Long intValue

Introduction

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

Prototype

public int intValue() 

Source Link

Document

Returns the value of this Long as an int after a narrowing primitive conversion.

Usage

From source file:cc.kune.core.server.content.ContentManagerDefault.java

@Override
public SearchResult<?> searchMime(final String search, final Integer firstResult, final Integer maxResults,
        final String groupShortName, final String mimetype, final String mimetype2) {
    final List<Content> list = contentFinder.find2Mime(groupShortName, "%" + search + "%", mimetype, mimetype2,
            firstResult, maxResults);/*  w  w  w  .  j a va  2s. c om*/
    final Long count = contentFinder.find2MimeCount(groupShortName, "%" + search + "%", mimetype, mimetype2);
    return new SearchResult<Content>(count.intValue(), list);
}

From source file:eumetsat.pn.elasticsearch.webapp.ElasticsearchApp.java

@Override
protected Map<String, Object> search(String searchTerms, String filterString, int from, int size) {
    Map<String, Object> data = new HashMap<>();
    // put "session" parameters here rightaway so it can be used in template even when empty result
    data.put("search_terms", searchTerms);
    data.put("filter_terms", filterString);

    URL url;/*from  ww w.j  a  v  a  2s .  co m*/
    try {
        url = new URL(searchEndpointUrlString);
    } catch (MalformedURLException e) {
        log.error("Search enpoint URL malformed: {}", e.getMessage());
        addMessage(data, MessageLevel.danger, "Search endpoint URL is malformed: " + e.getMessage());
        return data;
    }

    List<Map<String, String>> resHits = new ArrayList<>();
    Map<String, String> resHit = null;

    Multimap<String, String> filterTermsMap = parseFiltersTerms(filterString);
    Set<String> hiddenFacets = new HashSet<>(); // to create the list of filters to hide

    String filterConstruct = "";
    if (filterTermsMap.size() > 0) {
        int i = 0;
        String filterTerms = "";
        for (String key : filterTermsMap.keySet()) {
            for (String term : filterTermsMap.get(key)) {
                if (i == 0) {
                    filterTerms += "{ \"term\" : { \"" + FACETS2HIERACHYNAMES.get(key) + "\":\"" + term
                            + "\"}}";
                } else {
                    filterTerms += ",{ \"term\" : { \"" + FACETS2HIERACHYNAMES.get(key) + "\":\"" + term
                            + "\"}}";
                }

                // hide the facets that are used for filtering
                hiddenFacets.add(key + ":" + term);

                i++;
            }
        }

        filterConstruct = " \"bool\" : { \"must\" : [" + filterTerms + "] }";
    }

    int lengthOfTitle = 300;
    int lengthOfAbstract = 5000;
    int boostFactorTitle = 10;

    String body = "{ " + // pagination information
            "\"from\" : " + from + ", \"size\" : " + size + "," + // request highlighted info
            "\"highlight\" : { \"pre_tags\" : [\"<em><strong>\"], \"post_tags\" : [\"</strong></em>\"], "
            + "                  \"fields\" : { \"identificationInfo.title\": {\"fragment_size\" : "
            + lengthOfTitle + ", \"number_of_fragments\" : 1}, "
            + "                                 \"identificationInfo.abstract\": {\"fragment_size\" : "
            + lengthOfAbstract + ", \"number_of_fragments\" : 1} } } , " + // request facets to refine search (here the maximum number of facets can be configured)
            " \"facets\" :   { \"satellites\": { \"terms\" : { \"field\" : \"hierarchyNames.satellite\", \"size\":5 } }, "
            + "                  \"instruments\": { \"terms\" : { \"field\" : \"hierarchyNames.instrument\", \"size\":5  } }, "
            + "                  \"categories\": { \"terms\" : { \"field\" : \"hierarchyNames.category\", \"size\": 5 } }, "
            + "                  \"societal Benefit Area\": { \"terms\" : { \"field\" : \"hierarchyNames.societalBenefitArea\", \"size\":5 } }, "
            + "                  \"distribution\": { \"terms\" : { \"field\" : \"hierarchyNames.distribution\", \"size\":5 } } "
            + "                }," + // add query info
            "\"query\" : { \"filtered\": { \"query\": "
            + "              { \"simple_query_string\" : { \"fields\" : [\"identificationInfo.title^"
            + boostFactorTitle + "\", \"identificationInfo.abstract\"], " + "\"query\" : \"" + searchTerms
            + "\" } " + "}" + ",\"filter\": {" + filterConstruct + "}" + " }}}";

    log.trace("elastic-search request: {}", body);

    //measure elapsed time
    Stopwatch stopwatch = Stopwatch.createStarted();

    WebResponse response = rClient.doGetRequest(url, new HashMap<String, String>(),
            new HashMap<String, String>(), body, log.isDebugEnabled());

    if (response == null) {
        log.error("Response from {} is null!", this.name);
        data.put("total_hits", 0);
        data = addMessage(data, MessageLevel.danger, "Response is null from " + this.name);
    } else {
        log.trace("Got response: {}", response);

        if (response.status == 200) {
            JSONParser parser = new JSONParser();
            JSONObject jsObj;
            try {
                jsObj = (JSONObject) parser.parse(response.body);
            } catch (ParseException e) {
                log.error("Could not parse search server response: {}", e);
                addMessage(data, MessageLevel.danger, "Could not parse server response: " + e.getMessage());
                return data;
            }

            Long hitcount = (Long) ((Map<?, ?>) jsObj.get("hits")).get("total");
            data.put("total_hits", hitcount);
            if (hitcount < 1)
                addMessage(data, MessageLevel.info, "No results found!");

            // compute the pagination information to create the pagination bar
            Map<String, Object> pagination = computePaginationParams(hitcount.intValue(), from);
            data.put("pagination", pagination);

            @SuppressWarnings("unchecked")
            List<Map<String, Object>> hits = (List<Map<String, Object>>) ((Map<?, ?>) jsObj.get("hits"))
                    .get("hits");

            //to get the highlight
            Map<?, ?> highlight = null;
            for (Map<String, Object> hit : hits) {
                resHit = new HashMap<>();

                resHit.put("id", (String) hit.get("_id"));
                resHit.put("score", String.format("%.4g%n", ((Double) hit.get("_score"))));

                // can have or not title or abstract
                // strategy. If it doesn't have an abstract or a title match then take it from the _source
                highlight = (Map<?, ?>) hit.get("highlight");

                if (highlight.containsKey("identificationInfo.title")) {
                    resHit.put("title",
                            (String) ((JSONArray) highlight.get("identificationInfo.title")).get(0));
                } else {
                    resHit.put("title", ((String) (((Map<?, ?>) (((Map<?, ?>) hit.get("_source"))
                            .get("identificationInfo"))).get("title"))));
                }

                if (highlight.containsKey("identificationInfo.abstract")) {
                    resHit.put("abstract",
                            (String) ((JSONArray) highlight.get("identificationInfo.abstract")).get(0));
                } else {
                    resHit.put("abstract", ((String) (((Map<?, ?>) (((Map<?, ?>) hit.get("_source"))
                            .get("identificationInfo"))).get("abstract"))));
                }

                JSONObject info = (JSONObject) ((JSONObject) hit.get("_source")).get("identificationInfo");
                JSONArray keywords = (JSONArray) info.get("keywords");
                resHit.put("keywords", Joiner.on(", ").join(keywords.iterator()));

                resHit.put("thumbnail", info.get("thumbnail").toString());
                resHit.put("status", info.get("status").toString());

                resHits.add(resHit);
            }

            data.put("hits", resHits);

            data.put("facets", jsObj.get("facets"));

            data.put("tohide", hiddenFacets);

        } else { // non-200 resonse
            log.error("Received non-200 response: {}", response);
            data = addMessage(data, MessageLevel.danger, "Non 200 response: " + response.toString());
        }
    }

    stopwatch.stop();

    data.put("elapsed", (double) (stopwatch.elapsed(TimeUnit.MILLISECONDS)) / (double) 1000);

    return data;
}

From source file:info.jtrac.hibernate.HibernateJtracDao.java

public int loadCountOfHistoryInvolvingUser(User user) {
    Long count = (Long) getHibernateTemplate().find("select count(history) from History history where "
            + " history.loggedBy = ? or history.assignedTo = ?", new Object[] { user, user }).get(0);
    return count.intValue();
}

From source file:org.obiba.onyx.jade.instrument.jtech.Tracker5InstrumentRunner.java

private void extractTrials() {
    log.info("Extracting data");
    Map<String, Data> exam = extractExam();

    ParadoxDb dataDb = getGripTestDataDB();

    for (ParadoxRecord record : dataDb) {

        Long examMax = record.getValue("Maximum");
        Long avg = record.getValue("Average");
        Long cv = record.getValue("CV");

        for (int i = 1; i <= 4; i++) {
            String side = record.getValue("Side");
            String rungPosition = record.getValue("Position");
            Long rep = record.getValue("Rep" + i);
            Integer exclude = record.getValue("Rep" + i + "Exclude");
            if (rep != null && (exclude == null || exclude == 0)) {
                LinkedHashMap<String, Data> map = new LinkedHashMap<String, Data>(exam);
                map.put("Side", DataBuilder.buildText(side));
                // Convert it to an int
                map.put("Position", DataBuilder.build(DataType.INTEGER, rungPosition));
                map.put("Rep", DataBuilder.buildDecimal(Tracker5Util.asKg(rep.intValue())));

                // These don't change for each rep... but onyx doesn't support repeated and non-repeated values
                map.put("Max", DataBuilder.buildDecimal(Tracker5Util.asKg(examMax.intValue())));
                map.put("Avg", DataBuilder.buildDecimal(Tracker5Util.asKg(avg.intValue())));
                map.put("CV", DataBuilder.buildInteger(cv));
                sendToOnyx(map);//from ww  w .  java2  s . c om
            }
        }
    }
}

From source file:com.jskaleel.xml.JSONObject.java

/**
 * Try to convert a string into a number, boolean, or null. If the string
 * can't be converted, return the string.
 *
 * @param string// www .jav  a  2  s  .c  o  m
 *            A String.
 * @return A simple JSON value.
 */
public static Object stringToValue(String string) {
    Double d;
    if (string.equals("")) {
        return string;
    }
    if (string.equalsIgnoreCase("true")) {
        return Boolean.TRUE;
    }
    if (string.equalsIgnoreCase("false")) {
        return Boolean.FALSE;
    }
    if (string.equalsIgnoreCase("null")) {
        return JSONObject.NULL;
    }

    /*
     * If it might be a number, try converting it. If a number cannot be
     * produced, then the value will just be a string.
     */

    char b = string.charAt(0);
    if ((b >= '0' && b <= '9') || b == '-') {
        try {
            if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) {
                d = Double.valueOf(string);
                if (!d.isInfinite() && !d.isNaN()) {
                    return d;
                }
            } else {
                Long myLong = new Long(string);
                if (string.equals(myLong.toString())) {
                    if (myLong == myLong.intValue()) {
                        return myLong.intValue();
                    } else {
                        return myLong;
                    }
                }
            }
        } catch (Exception ignore) {
        }
    }
    return string;
}

From source file:com.redhat.rhn.frontend.action.systems.sdc.SnapshotTagCreateAction.java

/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
        HttpServletResponse response) {/*from  w ww  .j a  v  a 2s  .  c  o m*/
    DynaActionForm form = (DynaActionForm) formIn;
    RequestContext context = new RequestContext(request);
    Long sid = context.getRequiredParam("sid");
    Server server = context.lookupAndBindServer();
    Long snapshotID = getSnapshotID(context);

    Map params = makeParamMap(request);
    params.put("sid", sid);
    if (snapshotID != null) {
        params.put("ss_id", snapshotID);
        request.setAttribute("parentUrl",
                request.getRequestURI() + "?sid=" + sid.toString() + "&ss_id=" + snapshotID.toString());
    } else {
        request.setAttribute("parentUrl", request.getRequestURI() + "?sid=" + sid.toString());
    }

    if (context.isSubmitted()) {
        String tagName = form.get("tagName").toString();
        ServerSnapshot snap = null;
        if (snapshotID != null) {
            snap = ServerFactory.lookupSnapshotById(snapshotID.intValue());
        } else {
            snap = ServerFactory.lookupLatestForServer(server);
        }
        if (StringUtils.isBlank(tagName)) {
            createErrorMessage(request, "system.history.snapshot.tagNameEmpty", null);
        } else if (!snap.addTag(tagName)) {
            createErrorMessage(request, "system.history.snapshot.tagCreateFailure", null);
        } else {
            createSuccessMessage(request, "system.history.snapshot.tagCreateSuccess", null);
            return getStrutsDelegate().forwardParams(mapping.findForward(RhnHelper.CONFIRM_FORWARD), params);
        }
    }

    return getStrutsDelegate().forwardParams(mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);
}

From source file:net.duckling.ddl.web.sync.FileContentController.java

@RequirePermission(target = "team", operation = "view")
@ResponseBody//  w w  w . j a va 2  s .co  m
@RequestMapping(params = "func=download")
public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam("fid") Long rid,
        @RequestParam(value = "fver", required = false) Long fver) {
    Context ctx = ContextUtil.retrieveContext(request);
    int tid = ctx.getTid();

    Resource resource = resourceService.getResource(rid.intValue(), tid);
    if (resource == null || LynxConstants.STATUS_DELETE.equals(resource.getStatus())) {
        Result<Object> result = new Result<Object>(Result.CODE_FILE_NOT_FOUND, Result.MESSAGE_FILE_NOT_FOUND);
        response.setHeader(DDL_API_RESULT_HEADER, result.toString());
        return;
    }

    if (resource.getItemType().equals(LynxConstants.TYPE_PAGE)) {
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(DDOC_FILE_CONTENT);
            if (rid == 254974) {
                throw new IOException("a test");
            }
            return;
        } catch (IOException e) {
            LOG.error(String.format("Fail to download rid: %d", rid), e);
            return;
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    FileVersion file = null;
    file = fver == null ? fileVersionService.getLatestFileVersion(rid.intValue(), tid)
            : fileVersionService.getFileVersion(rid.intValue(), tid, fver.intValue());
    if (file == null || LynxConstants.STATUS_DELETE.equals(file.getStatus())) {
        Result<Object> result = new Result<Object>(Result.CODE_FILE_NOT_FOUND, Result.MESSAGE_FILE_NOT_FOUND);
        response.setHeader(DDL_API_RESULT_HEADER, result.toString());
        LOG.error(String.format("Resource of rid:%d exists, but there is no valid file version.", rid));
        return;
    }

    if (NginxAgent.isNginxMode()) {
        String url = resourceOperateService.getDirectURL(file.getClbId(), String.valueOf(file.getClbVersion()),
                false);
        NginxAgent.setRedirectUrl(request, response, file.getTitle(), file.getSize(), url);
    } else {
        try {
            AttSaver fs = new AttSaver(response, request, file.getTitle());
            resourceOperateService.getContent(file.getClbId(), String.valueOf(file.getClbVersion()), fs);
        } catch (ResourceNotFound resourceNotFound) {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            } catch (IOException ignored) {
            }
            LOG.error(String.format("Fail to get file %d from CLB.", file.getRid()), resourceNotFound);
        } catch (Exception e) {
            JsonResponse.error(response);
            LOG.error(String.format("Fail to get file %d from CLB.", file.getRid()), e);
        }
    }
}

From source file:com.fer.hr.web.rest.resources.Query2Resource.java

/**
 *
 * Execute a Saiku Query/*from www  . ja  v a  2  s . c o  m*/
 * @summary Execute Query
 * @param tq Thin Query model
 * @return A query result set.
 */
@POST
@Consumes({ "application/json" })
@Produces({ "application/json" })
@Path("/execute")
public QueryResult execute(ThinQuery tq) {
    try {
        if (thinQueryService.isMdxDrillthrough(tq)) {
            Long start = (new Date()).getTime();
            ResultSet rs = thinQueryService.drillthrough(tq);
            QueryResult rsc = RestUtil.convert(rs);
            rsc.setQuery(tq);
            Long runtime = (new Date()).getTime() - start;
            rsc.setRuntime(runtime.intValue());
            return rsc;
        }

        QueryResult qr = RestUtil.convert(thinQueryService.execute(tq));
        ThinQuery tqAfter = thinQueryService.getContext(tq.getName()).getOlapQuery();
        qr.setQuery(tqAfter);
        return qr;
    } catch (Exception e) {
        log.error("Cannot execute query (" + tq + ")", e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        return new QueryResult(error);
    }
}

From source file:au.org.theark.lims.model.dao.BiospecimenDao.java

public long getBiospecimenCount(LimsVO limsVo) {
    Criteria criteria = buildBiospecimenCriteria(limsVo);
    criteria.setProjection(Projections.rowCount());
    Long totalCount = (Long) criteria.uniqueResult();
    return totalCount.intValue();
}

From source file:com.wakacommerce.common.util.StreamingTransactionCapableUtil.java

@Override
public <G extends Throwable> void runStreamingTransactionalOperation(
        final StreamCapableTransactionalOperation streamOperation, Class<G> exceptionType,
        int transactionBehavior, int isolationLevel) throws G {
    //this should be a read operation, so doesn't need to be in a transaction
    final Long totalCount = streamOperation.retrieveTotalCount();
    final Holder holder = new Holder();
    holder.setVal(0);//from w  w  w  .j  a  v a  2  s .co m
    StreamCapableTransactionalOperation operation = new StreamCapableTransactionalOperationAdapter() {
        @Override
        public void execute() throws Throwable {
            pagedItems = streamOperation.retrievePage(holder.getVal(), pageSize);
            streamOperation.pagedExecute(pagedItems);
            if (((Collection) pagedItems[0]).size() == 0) {
                holder.setVal(totalCount.intValue());
            } else {
                holder.setVal(holder.getVal() + ((Collection) pagedItems[0]).size());
            }
        }
    };
    while (holder.getVal() < totalCount) {
        runTransactionalOperation(operation, exceptionType, transactionBehavior, isolationLevel);
        if (em != null) {
            //The idea behind using this class is that it will likely process a lot of records. As such, it is necessary
            //to clear the level 1 cache after each iteration so that we don't run out of heap
            em.clear();
        }
        streamOperation
                .executeAfterCommit(((StreamCapableTransactionalOperationAdapter) operation).getPagedItems());
    }
}