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:de.bps.onyx.util.ExamPool.java

Long registerStudentTest(Identity student, QTIResultSet resultSet, TestState state) {
    Long result = null;/*  ww  w .ja  va  2  s.  co  m*/

    addStudent(student, (state != null ? state : TestState.WAITING));

    //map this assessment to it's id
    assessmentIdentityMapping.put(resultSet.getAssessmentID(), student);
    //map this student to his / her assessment
    identityAssessmentMapping.put(student.getKey(), resultSet.getAssessmentID());

    HashMap<String, String> parameterMap = new HashMap<String, String>();
    parameterMap.put(PARAM_LANGUAGE, student.getUser().getPreferences().getLanguage());
    parameterMap.put(PARAM_FIRSTNAME, student.getUser().getProperty(UserConstants.FIRSTNAME, null));
    parameterMap.put(PARAM_LASTNAME, student.getUser().getProperty(UserConstants.LASTNAME, null));

    byte[] recommitedFiles = new byte[0];
    if (resultSet.getSuspended()) {
        log.info("Try to recreate for student " + student.getName() + " and suspended assessment : "
                + resultSet.getAssessmentID());
        //addStudent(student, TestState.SUSPENDED);
        parameterMap.put(PARAM_STATUS, String.valueOf(TestState.RESUME_SUSPENDED.getValue()));
        String assessmentType = referencedCourseNode.getModuleConfiguration()
                .get(IQEditController.CONFIG_KEY_TYPE).toString();
        String path = null;

        Boolean isSurvey = false;
        File xml = null;
        if (referencedCourseNode instanceof IQSURVCourseNode) {
            isSurvey = true;
        }
        if (isSurvey) {
            OlatRootFolderImpl courseRootContainer = referencedCourse.getCourseEnvironment()
                    .getCourseBaseContainer();
            path = courseRootContainer.getBasefile() + File.separator + referencedCourseNode.getIdent()
                    + File.separator;
            xml = new File(path);
        } else {
            path = OnyxResultManager.getResReporting() + File.separator + student.getName() + File.separator
                    + assessmentType + File.separator;
            xml = new File(directory, path);
        }

        if (xml != null && xml.exists()) {
            File commitMe = null;
            File[] allXmls = xml.listFiles(new OnyxReporterConnectorFileNameFilter(
                    referencedCourseNode.getIdent(), String.valueOf(resultSet.getAssessmentID())));
            if (allXmls != null && allXmls.length > 0) {
                for (File file : allXmls) {
                    if (file.isFile()) {
                        if (commitMe == null || file.getName().toLowerCase().endsWith(".zip")) {
                            commitMe = file;
                        }
                    }
                }
            }
            if (commitMe != null) {
                Long fileLength = commitMe.length();
                recommitedFiles = new byte[fileLength.intValue()];
                java.io.FileInputStream inp = null;
                try {
                    inp = new java.io.FileInputStream(commitMe);
                    inp.read(recommitedFiles);
                    log.info("Found file for suspended assessment for student " + student.getName()
                            + " and suspended assessment : " + resultSet.getAssessmentID() + " # "
                            + commitMe.getAbsolutePath() + "; lenght " + recommitedFiles.length);
                } catch (FileNotFoundException e) {
                    log.error("Missing file: " + commitMe.getAbsolutePath(), e);
                } catch (IOException e) {
                    log.error("Error copying file: " + commitMe.getAbsolutePath(), e);
                } finally {
                    IOUtils.closeQuietly(inp);
                }
            } else {
                log.info("Did not find files for suspended assessment for student " + student.getName()
                        + " and suspended assessment : " + resultSet.getAssessmentID() + " at "
                        + xml.getAbsolutePath() + " an filter-options " + referencedCourseNode.getIdent()
                        + " and " + resultSet.getAssessmentID());
            }
        } else {
            log.info("Did not find resreporting folder for student " + student.getName()
                    + " and suspended assessment : " + resultSet.getAssessmentID() + " at "
                    + xml.getAbsolutePath());
        }
    } else {
        log.info("Assessment not suspended, nothing to restore.");
    }

    MapWrapper parameterWrapper = new MapWrapper();
    parameterWrapper.setMap(parameterMap);

    result = service.registerStudent(testSessionId, resultSet.getAssessmentID(), recommitedFiles,
            parameterWrapper);
    log.info("Tried to register student with assessmentId" + resultSet.getAssessmentID() + " to test: "
            + testSessionId + " resulting in : " + TestState.getState(result));
    return result;
}

From source file:mx.edu.um.mateo.inventario.dao.impl.ProductoDaoHibernate.java

@Override
@Transactional(readOnly = true)//from w  w  w. ja v  a  2 s.  co  m
public Map<String, Object> lista(Map<String, Object> params) {
    log.debug("Buscando lista de productos 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(Producto.class);
    Criteria countCriteria = currentSession().createCriteria(Producto.class);

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

    if (params.containsKey("inactivo")) {
        criteria.add(Restrictions.eq("inactivo", true));
        countCriteria.add(Restrictions.eq("inactivo", true));
    } else {
        Disjunction propiedades = Restrictions.disjunction();
        propiedades.add(Restrictions.eq("inactivo", Boolean.FALSE));
        propiedades.add(Restrictions.isNull("inactivo"));
        criteria.add(propiedades);
        countCriteria.add(propiedades);
    }

    if (params.containsKey("filtro")) {
        String filtro = (String) params.get("filtro");
        Disjunction propiedades = Restrictions.disjunction();
        propiedades.add(Restrictions.ilike("sku", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("nombre", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("descripcion", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("marca", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("modelo", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("ubicacion", 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("productos", criteria.list());

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

    return params;
}

From source file:hermes.ext.imq.ImqAdmin.java

@Override
public int getDepth(DestinationConfig destinationConfig) throws JMSException {
    LOG.debug("Getting depth");

    try {/*from w w w .j  a  v a  2s  .  c  om*/
        subscribeToDestMetricTopic(destinationConfig.getShortName(), destinationConfig.getDomain());

        synchronized (destMetricGuard) {
            destMetricGuard.wait(5000);
        }
    } catch (InterruptedException e) {
    }

    Long result = messageCounts.get(destinationConfig.getShortName());

    LOG.debug("Got depth for " + destinationConfig.getShortName() + ": " + result);

    if (result == null) {
        throw new RuntimeException("Timeout: Got no data from metric topic.");
    }

    clearDestMetricTopicSubscribers();

    return result.intValue();
}

From source file:com.clican.pluto.fsm.engine.impl.EventQueue.java

public Object invoke(final MethodInvocation invocation) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Using the IntroductionInterceptor to interrupt the event ["
                + invocation.getMethod().getName() + "]");
    }/*from   w  ww .  ja va 2 s .  c om*/

    Object result = null;
    Object[] args = invocation.getArguments();
    Long sessionId = (Long) args[0];
    Long stateId = (Long) args[1];
    Session session = engineContext.querySession(sessionId);
    State state = engineContext.findStateById(stateId);
    if (session == null) {
        throw new RuntimeException("The session doesn't exist sessionId[" + sessionId + "]");
    }
    if (state == null) {
        throw new RuntimeException("The state doesn't exist stateId[" + stateId + "]");
    } else {
        Object lock = locks[sessionId.intValue() % 10];
        if (log.isDebugEnabled()) {
            log.debug("Using lock for session[" + sessionId + "]");
        }
        synchronized (lock) {
            try {
                boolean executed = false;
                List<State> activeStates = engineContext.getActiveAndPendingState(sessionId);
                for (State activeState : activeStates) {
                    if (activeState.getId().equals(stateId)) {
                        result = invocation.proceed();
                        executed = true;
                        break;
                    }
                }
                if (!executed && log.isDebugEnabled()) {
                    log.debug("The event shall be ignore for current active states[" + activeStates + "]");
                }
                return result;
            } catch (Throwable e) {
                throw e;
            } finally {
                if (log.isDebugEnabled()) {
                    log.debug("Release lock for session[" + sessionId + "]");
                }
            }
        }
    }

}

From source file:GenricDAOImpl.java

/**
 * statementName  ?statementNameCount SQL
 * @param statementName//from w ww  . j  a  v a 2  s.  c  om
 * @param QueryCondition condition  pageNo,pageSize
 * @return
 */
@Override
public Pagination<T> queryForPage(final String statementName, final PageParam param) {
    Long count = (Long) getSqlMapClientTemplate()
            .queryForObject(getQualifiedStatementName(statementName + COUNT), param);
    List<T> data = getSqlMapClientTemplate().queryForList(getQualifiedStatementName(statementName), param);
    Pagination<T> page = new Pagination<T>(param.getPageNumber(), param.getLength());//condition.get("pageNo", Integer.class),condition.get("pageSize", Integer.class));
    page.setTotal(count.intValue());
    page.setData(data);
    return page;
}

From source file:com.linkedin.pinot.query.aggregation.StarTreeQueriesTest.java

@Test(dataProvider = "instancePlanMakerDataProvider")
public void testRawQuery(PlanMaker instancePlanMaker) throws Exception {
    // Build request
    final BrokerRequest brokerRequest = new BrokerRequest();
    final List<AggregationInfo> aggregationsInfo = new ArrayList<AggregationInfo>();
    aggregationsInfo.add(getCountAggregationInfo());
    brokerRequest.setAggregationsInfo(aggregationsInfo);

    // Compute plan
    final PlanNode rootPlanNode = instancePlanMaker.makeInnerSegmentPlan(indexSegment, brokerRequest);
    rootPlanNode.showTree("");
    Assert.assertTrue(rootPlanNode.getClass().equals(RawAggregationPlanNode.class)
            || rootPlanNode.getClass().equals(AggregationPlanNode.class));

    // Perform aggregation
    final MAggregationOperator operator = (MAggregationOperator) rootPlanNode.run();
    final IntermediateResultsBlock resultBlock = (IntermediateResultsBlock) operator.nextBlock();

    // Get response
    final ReduceService reduceService = new DefaultReduceService();
    final Map<ServerInstance, DataTable> instanceResponseMap = new HashMap<ServerInstance, DataTable>();
    instanceResponseMap.put(new ServerInstance("localhost:0000"), resultBlock.getAggregationResultDataTable());
    instanceResponseMap.put(new ServerInstance("localhost:1111"), resultBlock.getAggregationResultDataTable());
    instanceResponseMap.put(new ServerInstance("localhost:2222"), resultBlock.getAggregationResultDataTable());
    instanceResponseMap.put(new ServerInstance("localhost:3333"), resultBlock.getAggregationResultDataTable());
    instanceResponseMap.put(new ServerInstance("localhost:4444"), resultBlock.getAggregationResultDataTable());
    instanceResponseMap.put(new ServerInstance("localhost:5555"), resultBlock.getAggregationResultDataTable());
    instanceResponseMap.put(new ServerInstance("localhost:6666"), resultBlock.getAggregationResultDataTable());
    instanceResponseMap.put(new ServerInstance("localhost:7777"), resultBlock.getAggregationResultDataTable());
    instanceResponseMap.put(new ServerInstance("localhost:8888"), resultBlock.getAggregationResultDataTable());
    instanceResponseMap.put(new ServerInstance("localhost:9999"), resultBlock.getAggregationResultDataTable());
    final BrokerResponse reducedResults = reduceService.reduceOnDataTable(brokerRequest, instanceResponseMap);

    // Check (we sent 10 broker requests, so assume 10x)
    Long fromPinot = reducedResults.getAggregationResults().get(0).getLong("value");
    Assert.assertEquals(fromPinot.intValue(), numRecords * 10 /* because 10 broker requests */);
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.LexiconBuilderController.java

/**
 * Gets the document at the given rank.// ww w  . j av  a2s. co  m
 * @param em the {@link EntityManager} to use.
 * @param builder the {@link LexiconBuilderDocumentStore} to use.
 * @param rank the rank of the document. If {@code null}, this returns the same result as {@code getNextDocument}.
 * @return the {@link LexiconBuilderDocument} at the given rank.
 */
public LexiconBuilderDocument getDocument(EntityManager em, LexiconBuilderDocumentStore builder, Long rank) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(builder, CannedMessages.NULL_ARGUMENT, "builder");

    if (rank == null) {
        return this.getNextDocument(em, builder);
    }

    TypedQuery<LexiconBuilderDocument> query = this.getDocumentsQuery(em, builder, null);
    query.setFirstResult(rank.intValue());
    query.setMaxResults(1);
    LexiconBuilderDocument doc = this.getSingleResult(query);
    doc.setRank(rank);
    return doc;
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private Cookie makeAuthTokenCookie(AuthToken attrlist, CookieUse use) {

    String cookieValue = attrlist.getTokenString();

    if (use == CookieUse.EXTERNAL) {
        // Generate digital signature and add to token string
        byte[] signature = generateSignature(cookieValue);
        cookieValue = cookieValue + "-" + Base64.encodeBase64String(signature);
    }/*  ww w.  j  a  va 2s. c  om*/

    logger.debug("Cookie value: " + cookieValue);

    Cookie c = new Cookie(ConfigurationListener.getTokenName(), cookieValue);
    Long expiry = attrlist.getExpirationDate() / 1000L;
    c.setMaxAge(expiry.intValue());
    return c;

}

From source file:ar.com.zauber.commons.test.SpringHibernateRepositoryTest.java

/** Prueba el caso en que se desea hacer un count de un campo y se 
 * hace tambin order by sin group by//from  www . jav a2  s  .  c  om
 */
@SuppressWarnings("unchecked")
public final void testCountOrderBy() {
    createSomeData();

    final Query<DireccionDummy> query = new SimpleQuery<DireccionDummy>(DireccionDummy.class, new NullFilter(),
            null, new Ordering(Arrays.asList(new Order[] { new Order("numero", false, true) })));

    AggregateFunction function = new CompositeAggregateFunction(
            Arrays.asList(new AggregateFunction[] { new CountPropertyAggregateFunction("numero"), }));
    Object rows = repository.aggregate(query, function, Object.class);
    List<Object> result = new LinkedList<Object>();
    if (rows instanceof List) {
        result = (List<Object>) rows;
    } else {
        result.add(rows);
    }
    assertEquals(1, result.size());

    Long row = (Long) result.get(0);
    assertEquals(12, row.intValue());

}

From source file:GenricDAOImpl.java

/**
 * statementName  ?statementNameCount SQL
 * @param statementName// w w w . j a va2  s  .c  o m
 * @param QueryCondition condition  pageNo,pageSize
 * @return
 */
@Override
public <E> Pagination<E> queryForPage(Class<E> classz, final String statementName,
        final QueryCondition condition) {
    Long count = (Long) getSqlMapClientTemplate()
            .queryForObject(getQualifiedStatementName(statementName + COUNT), condition.asMap());
    List<E> data = getSqlMapClientTemplate().queryForList(getQualifiedStatementName(statementName),
            condition.asMap());
    Pagination<E> page = new Pagination<E>(condition.get("pageNo", Integer.class),
            condition.get("pageSize", Integer.class));
    page.setTotal(count.intValue());
    page.setData(data);
    return page;
}