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:com.infinira.aerospike.dataaccess.model.Entity.java

/**
 * Get Integer object for a given field value
 * @param name  field name/*from   www .  j  av  a 2  s.  co  m*/
 * @return  Integer value
 */
protected Integer getInteger(String name) {
    Long value = this.getLong(name);
    return value != null ? value.intValue() : null;
}

From source file:mx.edu.um.mateo.general.dao.impl.UsuarioDaoHibernate.java

@Override
@Transactional(readOnly = true)/*from w  ww .  j a va  2 s. c o m*/
public Map<String, Object> lista(Map<String, Object> params) {
    log.debug("Buscando lista de usuarios con params {}", params);
    if (params == null) {
        params = new HashMap<>();
    }

    if (!params.containsKey("max")) {
        params.put("max", 10);
    } else {
        params.put("max", Math.min((Integer) params.get("max"), 100));
    }

    if (params.containsKey("pagina")) {
        Long pagina = (Long) params.get("pagina");
        Long offset = (pagina - 1) * (Integer) params.get("max");
        params.put("offset", offset.intValue());
    }

    if (!params.containsKey("offset")) {
        params.put("offset", 0);
    }

    Criteria criteria = currentSession().createCriteria(Usuario.class);
    Criteria countCriteria = currentSession().createCriteria(Usuario.class);

    if (params.containsKey("empresa")) {
        criteria.createCriteria("empresa").add(Restrictions.idEq(params.get("empresa")));
        countCriteria.createCriteria("empresa").add(Restrictions.idEq(params.get("empresa")));
    }

    if (params.containsKey("filtro")) {
        String filtro = (String) params.get("filtro");
        Disjunction propiedades = Restrictions.disjunction();
        propiedades.add(Restrictions.ilike("username", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("nombre", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("apellido", filtro, MatchMode.ANYWHERE));
        criteria.add(propiedades);
        countCriteria.add(propiedades);
    }

    if (params.containsKey("order")) {
        String campo = (String) params.get("order");
        if (params.get("sort").equals("desc")) {
            criteria.addOrder(Order.desc(campo));
        } else {
            criteria.addOrder(Order.asc(campo));
        }
    }

    if (!params.containsKey("reporte")) {
        criteria.setFirstResult((Integer) params.get("offset"));
        criteria.setMaxResults((Integer) params.get("max"));
    }
    params.put("usuarios", criteria.list());

    countCriteria.setProjection(Projections.rowCount());
    params.put("cantidad", (Long) countCriteria.list().get(0));

    return params;
}

From source file:fm.pattern.tokamak.server.service.ClientServiceImpl.java

@Transactional(readOnly = true)
public Result<List<Client>> list(Criteria criteria) {
    Long count = super.count(super.query("select count(client.id) from Clients client"));
    List<Client> clients = super.query("from Clients order by created desc")
            .setFirstResult(criteria.getFirstResult()).setMaxResults(criteria.getLimit()).getResultList();
    return Result.accept((List<Client>) new PaginatedList<Client>(clients, count.intValue(), criteria));
}

From source file:com.edgenius.wiki.ext.todo.service.TodoServiceImpl.java

@Transactional(readOnly = true)
public void fillTodosAndStatuses(Map<String, Object> map, Todo todo) {

    if (todo.getUid() == null) {
        //This todo is not persist yet, it shouldn't have todo items. So only fill in status list
        map.put("statuslist", todo.getStatuses());
        return;/*from w w  w. ja v  a 2  s . co m*/
    }

    //here doesn't use todo.getItems() for 2 reasons:
    //1. if todo is new one and just persisted, it won't refresh items - although this can be fix by adding items to todo.setItems() list
    //2. For a new item, it won't sort correctly as it won't get real createDate from database. 
    List<TodoItem> todos = getTodoItems(todo.getPageUuid(), todo.getName());

    //status from current macro - some status tag maybe not tag any TodoItem yet. so we need merge them - database and macro.
    List<TodoStatus> statuses = todo.getStatuses();

    Map<String, Long> taggedStatuses = todoItemDAO.getStatusCount(todo.getPageUuid(), todo.getName());

    //fill in TodoItem.statusObject
    for (TodoItem item : todos) {
        int idx = -1;
        for (int findIdx = 0; findIdx < statuses.size(); findIdx++) {
            if (StringUtils.equalsIgnoreCase(statuses.get(findIdx).getText(), item.getStatus())) {
                idx = findIdx;
                break;
            }
        }

        TodoStatus status;
        if (idx == -1) {
            //this TodoItem status not available in current macro status list(user have updated macro and remove some statuses)
            //then create a temporarily one.
            status = new TodoStatus();
            status.setText(item.getStatus());
            status.setSequence(statuses.size());
            status.setPersisted(false);
            //fill it to current status list
            statuses.add(status);
        } else {
            status = statuses.get(idx);
        }

        //lower case - see todoItemDAO.getStatusCount()
        Long count = taggedStatuses.get(status.getText().toLowerCase());
        if (count == null)
            status.setItemsCount(0);
        else
            status.setItemsCount(count.intValue());

        //update status object
        item.setStatusObj(status);
    }

    map.put("todos", todos);
    map.put("statuslist", statuses);

}

From source file:gate.corpora.DocumentContentImpl.java

@Override
public DocumentContent getContent(Long start, Long end) throws InvalidOffsetException {
    if (!isValidOffsetRange(start, end))
        throw new InvalidOffsetException("Invalid offset range " + start + " to " + end
                + " for document content of length " + this.size());

    return new DocumentContentImpl(content.substring(start.intValue(), end.intValue()));
}

From source file:whitelabel.cloud.webapp.impl.controller.NewCloudServersController.java

private final int validateEthParams(NewCloudServer newCloudServer) {

    Long selSwitchEth2 = newCloudServer.getVlan_eth02();
    Long selSwitchEth3 = newCloudServer.getVlan_eth03();
    if (selSwitchEth2 != null && selSwitchEth2.intValue() > 0 && selSwitchEth2.equals(selSwitchEth3)) {
        return 23; // can not connect same switch to two different ethernets
    }//from w  w w  . j a v  a  2  s.  c  om
    if (selSwitchEth2.intValue() > 0) {
        if (newCloudServer.getEth02_IP() == null || newCloudServer.getEth02_IP().isEmpty()) {
            return 2; // can not bind same IP to different ethernets
        }
        if (newCloudServer.getEth02_IP().equals(newCloudServer.getEth03_IP())) {
            return 23;
        }
        if (newCloudServer.getEth02_IP() != null && !newCloudServer.getEth02_IP().isEmpty()) {
            if (newCloudServer.getEth02_NM() == null || newCloudServer.getEth02_NM().isEmpty()) {
                return 2;
            }
        }
    }
    if (selSwitchEth3.intValue() > 0) {
        if (newCloudServer.getEth03_IP() == null || newCloudServer.getEth03_IP().isEmpty()) {
            return 3;
        }
        if (newCloudServer.getEth03_IP() != null && !newCloudServer.getEth03_IP().isEmpty()) {
            if (newCloudServer.getEth03_NM() == null || newCloudServer.getEth03_NM().isEmpty()) {
                return 3;
            }
        }
    }
    return 0;
}

From source file:com.capitalone.dashboard.collector.DefaultNexusIQClient.java

/**
 * Get the report details given a url for the report data.
 * @param url url of the report/*from  w  ww  .j  a  v a2 s  .  co m*/
 * @return LibraryPolicyResult
 */
@SuppressWarnings({ "PMD.AvoidDeeplyNestedIfStmts", "PMD.NPathComplexity" }) // agreed PMD, fixme

@Override
public LibraryPolicyResult getDetailedReport(String url) {
    LibraryPolicyResult policyResult = null;
    try {
        JSONObject obj = parseAsObject(url);
        JSONArray componentArray = (JSONArray) obj.get("components");
        if ((componentArray == null) || (componentArray.isEmpty()))
            return null;
        for (Object element : componentArray) {
            JSONObject component = (JSONObject) element;
            int licenseLevel = 0;
            JSONArray pathArray = (JSONArray) component.get("pathnames");

            String componentName = !CollectionUtils.isEmpty(pathArray) ? (String) pathArray.get(0)
                    : getComponentNameFromIdentifier((JSONObject) component.get("componentIdentifier"));

            JSONObject licenseData = (JSONObject) component.get("licenseData");

            if (licenseData != null) {
                //process license data
                JSONArray effectiveLicenseThreats = (JSONArray) licenseData.get("effectiveLicenseThreats");
                if (!CollectionUtils.isEmpty(effectiveLicenseThreats)) {
                    for (Object et : effectiveLicenseThreats) {
                        JSONObject etJO = (JSONObject) et;
                        Long longvalue = toLong(etJO, "licenseThreatGroupLevel");
                        if (longvalue != null) {
                            int newlevel = longvalue.intValue();
                            if (licenseLevel == 0) {
                                licenseLevel = newlevel;
                            } else {
                                licenseLevel = nexusIQSettings.isSelectStricterLicense()
                                        ? Math.max(licenseLevel, newlevel)
                                        : Math.min(licenseLevel, newlevel);
                            }
                        }
                    }

                }
            }

            if (policyResult == null) {
                policyResult = new LibraryPolicyResult();
            }

            if (licenseLevel > 0) {
                policyResult.addThreat(LibraryPolicyType.License,
                        LibraryPolicyThreatLevel.fromInt(licenseLevel), componentName);
            }

            JSONObject securityData = (JSONObject) component.get("securityData");
            if (securityData != null) {
                //process security data
                JSONArray securityIssues = (JSONArray) securityData.get("securityIssues");
                if (!CollectionUtils.isEmpty(securityIssues)) {
                    for (Object si : securityIssues) {
                        JSONObject siJO = (JSONObject) si;
                        BigDecimal bigDecimalValue = decimal(siJO, "severity");
                        double securityLevel = (bigDecimalValue == null)
                                ? getSeverityLevel(str(siJO, "threatCategory"))
                                : bigDecimalValue.doubleValue();
                        policyResult.addThreat(LibraryPolicyType.Security,
                                LibraryPolicyThreatLevel.fromDouble(securityLevel), componentName);
                    }
                }
            }
        }
    } catch (ParseException e) {
        LOG.error("Could not parse response from: " + url, e);
    } catch (RestClientException rce) {
        LOG.error("RestClientException from: " + url + ". Error code=" + rce.getMessage());
    }
    return policyResult;
}

From source file:cn.chenlichao.web.ssm.service.impl.BaseServiceImpl.java

@Override
public PageResults<E> queryPage(PageParams<E> pageParams) {
    if (pageParams == null) {
        throw new IllegalArgumentException("?null");
    }//from  www . ja v  a 2  s.co m
    LOGGER.trace("...");

    // ??
    int pageNum = pageParams.getPageIndex();
    int pageSize = pageParams.getPageSize();
    if (pageSize > 100) {
        LOGGER.warn(", ?[{}] ?, ? 100 ?", pageSize);
        pageSize = 100;
    }

    // ?
    PageHelper.startPage(pageNum, pageSize);

    Example example = new Example(entityClass);
    // ??
    E params = pageParams.getParamEntity();
    if (params != null) {
        Example.Criteria criteria = example.createCriteria();
        PropertyDescriptor[] propArray = BeanUtils.getPropertyDescriptors(entityClass);
        for (PropertyDescriptor pd : propArray) {
            if (pd.getPropertyType().equals(Class.class)) {
                continue;
            }
            try {
                Object value = pd.getReadMethod().invoke(params);
                if (value != null) {
                    if (pd.getPropertyType() == String.class) {
                        String strValue = (String) value;
                        if (strValue.startsWith("%") || strValue.endsWith("%")) {
                            criteria.andLike(pd.getName(), strValue);
                            continue;
                        }
                    }
                    criteria.andEqualTo(pd.getName(), value);
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                LOGGER.error("example: {}", e.getMessage(), e);
            }
        }
    }
    // ??
    String orderBy = pageParams.getOrderBy();
    if (StringUtils.hasText(orderBy)) {
        processOrder(example, orderBy, pageParams.isAsc());
    }
    List<E> results = baseMapper.selectByExample(example);

    // 
    if (results == null || !(results instanceof Page)) {
        return new PageResults<>(0, new ArrayList<E>(0), pageParams);
    }
    Page page = (Page) results;
    Long totalCount = page.getTotal();
    return new PageResults<>(totalCount.intValue(), Collections.unmodifiableList(results), pageParams);
}

From source file:io.omatic.event.service.EventMaintainanceService.java

/**
 * Maintenance method used to keep the number of {@link Event} records in the database
 * at a manageable level. /*from   w w  w .j  a va2s  .com*/
 * 
 * Note that this method can be scheduled. To do so specify a value for the externalised 
 * property eventomatic.maintenance.cronSchedule. The value must be in crontab format. For more information see 
 * <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html">here</a>
 */
@Transactional
@Scheduled(cron = "${eventomatic.maintenance.cronSchedule}")
public void maintainPoll() {

    // Firstly delete any events that are older than they should be, this will stop historic data clogging up the system. 0 disable
    if (applicationConfiguration.getMaintenance().getMaxAge() < 0) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, applicationConfiguration.getMaintenance().getMaxAge().intValue());
        Date maxAge = cal.getTime();

        long countOldEvents = eventRepository.countByRecievedDateBefore(maxAge);
        log.info("Checking for mesages older than {} and found {}", maxAge, countOldEvents);

        if (countOldEvents > 0) {
            log.info("Deleting {} events from before {}", countOldEvents, maxAge);
            eventRepository.deleteByRecievedDateBefore(maxAge);
            log.info("Deletion complete");
        }
    } else {
        log.info("Age based housekeeping disabled");
    }
    // Secondly, if the max events has exceeded the specified limit then trim the database. 0 or -1 will disable. 
    if (applicationConfiguration.getMaintenance().getEventLimit() > 0) {
        long countTotalEvents = eventRepository.count();
        Long overrun = countTotalEvents - applicationConfiguration.getMaintenance().getEventLimit();
        log.info("Checking for event count of greather than {} and found {}",
                applicationConfiguration.getMaintenance().getEventLimit(), countTotalEvents);
        if (overrun > 0) {
            Page<Event> events = eventRepository
                    .findAll(new PageRequest(0, overrun.intValue(), new Sort(Direction.ASC, "recievedDate")));
            eventRepository.deleteInBatch(events);
            log.info("Deleted {} of {} events.", overrun, countTotalEvents);
        }
    } else {
        log.info("Event limit based housekeeping disabled");
    }
}

From source file:com.alibaba.otter.node.etl.load.loader.db.FileLoadAction.java

/**
 * ??//from  w  w  w .j a va2s. co m
 */
public FileLoadContext load(FileBatch fileBatch, File rootDir, WeightController controller) {
    if (false == rootDir.exists()) {
        throw new LoadException(rootDir.getPath() + " is not exist");
    }
    FileLoadContext context = buildContext(fileBatch.getIdentity());
    context.setPrepareDatas(fileBatch.getFiles());
    boolean isDryRun = context.getPipeline().getParameters().isDryRun();
    try {
        // ???
        WeightBuckets<FileData> buckets = buildWeightBuckets(fileBatch.getIdentity(), fileBatch.getFiles());
        List<Long> weights = buckets.weights();
        controller.start(weights);
        // ??
        for (int i = 0; i < weights.size(); i++) {
            Long weight = weights.get(i);
            controller.await(weight.intValue());
            if (logger.isInfoEnabled()) {
                logger.debug("##start load for weight:{}\n", weight);
            }

            // ??weight?
            List<FileData> items = buckets.getItems(weight);
            if (context.getPipeline().getParameters().isDryRun()) {
                dryRun(context, items, rootDir);
            } else {
                moveFiles(context, items, rootDir);
            }

            controller.single(weight.intValue());
            if (logger.isInfoEnabled()) {
                logger.debug("##end load for weight:{}\n", weight);
            }
        }

        if (dump || isDryRun) {
            MDC.put(OtterConstants.splitPipelineLoadLogFileKey,
                    String.valueOf(fileBatch.getIdentity().getPipelineId()));
            logger.info(FileloadDumper.dumpContext("successed", context));
            MDC.remove(OtterConstants.splitPipelineLoadLogFileKey);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        if (dump || isDryRun) {
            MDC.put(OtterConstants.splitPipelineLoadLogFileKey,
                    String.valueOf(fileBatch.getIdentity().getPipelineId()));
            logger.info(FileloadDumper.dumpContext("error", context));
            MDC.remove(OtterConstants.splitPipelineLoadLogFileKey);
        }
    } catch (Exception e) {
        if (dump || isDryRun) {
            MDC.put(OtterConstants.splitPipelineLoadLogFileKey,
                    String.valueOf(fileBatch.getIdentity().getPipelineId()));
            logger.info(FileloadDumper.dumpContext("error", context));
            MDC.remove(OtterConstants.splitPipelineLoadLogFileKey);
        }
        throw new LoadException(e);
    } finally {

        // ???
        NioUtils.delete(rootDir, 3);
    }

    return context;
}