Example usage for java.lang Integer equals

List of usage examples for java.lang Integer equals

Introduction

In this page you can find the example usage for java.lang Integer equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object to the specified object.

Usage

From source file:eu.supersede.gr.utility.PointsLogic.java

private void computePoints() {
    List<HAHPGamePlayerPoint> gamesPlayersPoints = gamesPlayersPointsRepository.findAll();

    // cycle on every gamesPlayersPoints
    for (int i = 0; i < gamesPlayersPoints.size(); i++) {
        HAHPGame g = gamesRepository.findOne(gamesPlayersPoints.get(i).getGame().getGameId());

        // set currentPlayer that is used for other methods
        g.setCurrentPlayer(gamesPlayersPoints.get(i).getUser());

        List<HAHPCriteriasMatrixData> criteriasMatrixDataList = criteriaMatricesRepository.findByGame(g);

        // calculate the agreementIndex for every gamesPlayersPoints of a game and a specific user

        Map<String, Double> resultTotal = AHPRest.CalculateAHP(g.getCriterias(), g.getRequirements(),
                criteriasMatrixDataList, g.getRequirementsMatrixData());
        Map<String, Double> resultPersonal = AHPRest.CalculatePersonalAHP(
                gamesPlayersPoints.get(i).getUser().getUserId(), g.getCriterias(), g.getRequirements(),
                criteriasMatrixDataList, g.getRequirementsMatrixData());
        List<Requirement> gameRequirements = g.getRequirements();
        Double sum = 0.0;//from  w  w  w .  j a va 2s .  c om

        for (int j = 0; j < resultTotal.size(); j++) {
            Double requirementValueTotal = resultTotal
                    .get(gameRequirements.get(j).getRequirementId().toString());
            Double requirementValuePersonal = resultPersonal
                    .get(gameRequirements.get(j).getRequirementId().toString());
            sum = sum + (Math.abs(requirementValueTotal - requirementValuePersonal)
                    * (1.0 - requirementValueTotal));
        }

        Double agreementIndex = M - (M * sum);
        gamesPlayersPoints.get(i).setAgreementIndex(agreementIndex.longValue());

        // calculate the positionInVoting for every gamesPlayersPoints of a game and a specific user

        List<User> players = g.getPlayers();
        List<HAHPRequirementsMatrixData> lrmd = requirementsMatricesRepository.findByGame(g);
        Map<User, Float> gamePlayerVotes = new HashMap<>();

        for (User player : players) {
            Integer total = 0;
            Integer voted = 0;

            if (lrmd != null) {
                for (HAHPRequirementsMatrixData data : lrmd) {
                    for (HAHPPlayerMove pm : data.getPlayerMoves()) {
                        if (pm.getPlayer().getUserId().equals(player.getUserId())) {
                            total++;

                            if (pm.getPlayed() == true && pm.getValue() != null && !pm.getValue().equals(-1l)) {
                                voted++;
                            }
                        }
                    }
                }
            }

            gamePlayerVotes.put(player, total.equals(0) ? 0f : ((new Float(voted) / new Float(total)) * 100));
        }

        LinkedHashMap<User, Float> orderedList = sortHashMapByValues(gamePlayerVotes);
        List<User> indexes = new ArrayList<>(orderedList.keySet());
        Integer index = indexes.indexOf(gamesPlayersPoints.get(i).getUser());
        Double positionInVoting = (orderedList.size() - (new Double(index) + 1.0)) + 1.0;
        gamesPlayersPoints.get(i).setPositionInVoting(positionInVoting.longValue());

        // calculate the virtualPosition of a user base on his/her points in a particular game

        HAHPGamePlayerPoint gpp = gamesPlayersPointsRepository
                .findByUserAndGame(gamesPlayersPoints.get(i).getUser(), g);
        List<HAHPGamePlayerPoint> specificGamePlayersPoints = gamesPlayersPointsRepository.findByGame(g);

        Collections.sort(specificGamePlayersPoints, new CustomComparator());

        Long virtualPosition = specificGamePlayersPoints.indexOf(gpp) + 1l;
        gamesPlayersPoints.get(i).setVirtualPosition(virtualPosition);

        Long movesPoints = 0l;
        Long gameProgressPoints = 0l;
        Long positionInVotingPoints = 0l;
        Long gameStatusPoints = 0l;
        Long agreementIndexPoints = 0l;
        Long totalPoints = 0l;

        // set the movesPoints
        movesPoints = g.getMovesDone().longValue();

        // setGameProgressPoints
        gameProgressPoints = (long) Math.floor(g.getPlayerProgress() / 10);

        // setPositionInVotingPoints
        if (positionInVoting == 1) {
            positionInVotingPoints = 5l;
        } else if (positionInVoting == 2) {
            positionInVotingPoints = 3l;
        } else if (positionInVoting == 3) {
            positionInVotingPoints = 2l;
        }

        // setGameStatusPoints
        if (g.getPlayerProgress() != 100) {
            gameStatusPoints = -20l;
        } else {
            gameStatusPoints = 0l;
        }

        // set AgreementIndexPoints
        agreementIndexPoints = agreementIndex.longValue();
        totalPoints = movesPoints.longValue() + gameProgressPoints + positionInVotingPoints + gameStatusPoints
                + agreementIndexPoints;

        // set totalPoints 0 if the totalPoints are negative
        if (totalPoints < 0) {
            totalPoints = 0l;
        }

        gamesPlayersPoints.get(i).setPoints(totalPoints);
        gamesPlayersPointsRepository.save(gamesPlayersPoints.get(i));
    }

    System.out.println("Finished computing votes");
}

From source file:org.kuali.coeus.s2sgen.impl.generate.S2SBaseFormGenerator.java

/**
 *
 * This method is used to get the answerId for a particular Questionnaire question
 * question based on the question id.//from  w  w w .ja v a 2s .  c  om
 *
 * @param questionSeqId
 *            the question seq id to be passed.
 * @return returns the answer for a particular
 *         question based on the question id passed.
 */
protected Long getAnswerId(Integer questionSeqId, List<? extends AnswerHeaderContract> answerHeaders) {
    if (answerHeaders != null && !answerHeaders.isEmpty()) {
        for (AnswerHeaderContract answerHeader : answerHeaders) {
            List<? extends AnswerContract> answerDetails = answerHeader.getAnswers();
            for (AnswerContract answers : answerDetails) {
                if (answers.getAnswer() != null && questionSeqId.equals(getQuestionAnswerService()
                        .findQuestionById(answers.getQuestionId()).getQuestionSeqId())) {
                    return answers.getId();
                }
            }
        }
    }
    return null;
}

From source file:com.sawyer.advadapters.widget.JSONAdapter.java

/**
 * Determines whether the provided constraint filters out the given item. Subclass to provide
 * you're own logic. It's incorrect to modify the adapter or the contents of the item itself.
 * Any alterations will lead to undefined behavior or crashes. Internally, this method is only
 * ever invoked from a background thread.
 *
 * @param item       The Integer item to compare against the constraint
 * @param constraint The constraint used to filter the item
 *
 * @return True if the item is filtered out by the given constraint. False if the item will
 * continue to display in the adapter.//from   w  w w . j  av  a2 s .  c o m
 */
protected boolean isFilteredOut(Integer item, CharSequence constraint) {
    try {
        return !item.equals(Integer.valueOf(constraint.toString()));
    } catch (NumberFormatException e) {
        return true;
    }
}

From source file:com.gst.infrastructure.campaigns.sms.serialization.SmsCampaignValidator.java

public void validateCreate(String json) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }//from   w ww.j a  v a2  s .c  o m

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SmsCampaignValidator.supportedParams);

    final JsonElement element = this.fromApiJsonHelper.parse(json);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();

    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource(SmsCampaignValidator.RESOURCE_NAME);

    final String campaignName = this.fromApiJsonHelper.extractStringNamed(SmsCampaignValidator.campaignName,
            element);
    baseDataValidator.reset().parameter(SmsCampaignValidator.campaignName).value(campaignName).notBlank()
            .notExceedingLengthOf(100);

    final Long campaignType = this.fromApiJsonHelper.extractLongNamed(SmsCampaignValidator.campaignType,
            element);
    baseDataValidator.reset().parameter(SmsCampaignValidator.campaignType).value(campaignType).notNull()
            .integerGreaterThanZero();

    final Long triggerType = this.fromApiJsonHelper.extractLongNamed(SmsCampaignValidator.triggerType, element);
    baseDataValidator.reset().parameter(SmsCampaignValidator.triggerType).value(triggerType).notNull()
            .integerGreaterThanZero();

    if (triggerType.intValue() == SmsCampaignTriggerType.SCHEDULE.getValue()) {

        final Integer frequencyParam = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(SmsCampaignValidator.frequencyParamName, element);
        baseDataValidator.reset().parameter(SmsCampaignValidator.frequencyParamName).value(frequencyParam)
                .notNull().integerGreaterThanZero();

        final String intervalParam = this.fromApiJsonHelper
                .extractStringNamed(SmsCampaignValidator.intervalParamName, element);
        baseDataValidator.reset().parameter(SmsCampaignValidator.intervalParamName).value(intervalParam)
                .notBlank();

        if (frequencyParam != null && frequencyParam.equals(CalendarFrequencyType.WEEKLY.getValue())) {
            final String repeatsOnDayParam = this.fromApiJsonHelper
                    .extractStringNamed(SmsCampaignValidator.repeatsOnDayParamName, element);
            baseDataValidator.reset().parameter(SmsCampaignValidator.repeatsOnDayParamName)
                    .value(repeatsOnDayParam).notBlank();
        }
        final String recurrenceStartDate = this.fromApiJsonHelper
                .extractStringNamed(SmsCampaignValidator.recurrenceStartDate, element);
        baseDataValidator.reset().parameter(SmsCampaignValidator.recurrenceStartDate).value(recurrenceStartDate)
                .notBlank();
    }

    final Long runReportId = this.fromApiJsonHelper.extractLongNamed(SmsCampaignValidator.runReportId, element);
    baseDataValidator.reset().parameter(SmsCampaignValidator.runReportId).value(runReportId).notNull()
            .integerGreaterThanZero();

    final String message = this.fromApiJsonHelper.extractStringNamed(SmsCampaignValidator.message, element);
    baseDataValidator.reset().parameter(SmsCampaignValidator.message).value(message).notBlank()
            .notExceedingLengthOf(480);

    final JsonElement paramValueJsonObject = this.fromApiJsonHelper
            .extractJsonObjectNamed(SmsCampaignValidator.paramValue, element);
    if (triggerType.intValue() != SmsCampaignTriggerType.TRIGGERED.getValue()) {
        baseDataValidator.reset().parameter(SmsCampaignValidator.paramValue).value(paramValueJsonObject)
                .notBlank();
        if (paramValueJsonObject != null && paramValueJsonObject.isJsonObject()) {
            for (Map.Entry<String, JsonElement> entry : paramValueJsonObject.getAsJsonObject().entrySet()) {
                final JsonElement inner = entry.getValue();
                baseDataValidator.reset().parameter(entry.getKey()).value(inner).notBlank();
            }
        }
    }

    if (this.fromApiJsonHelper.parameterExists(SmsCampaignValidator.submittedOnDateParamName, element)) {
        final LocalDate submittedOnDate = this.fromApiJsonHelper
                .extractLocalDateNamed(SmsCampaignValidator.submittedOnDateParamName, element);
        baseDataValidator.reset().parameter(SmsCampaignValidator.submittedOnDateParamName)
                .value(submittedOnDate).notNull();
    }
    throwExceptionIfValidationWarningsExist(dataValidationErrors);

}

From source file:br.gov.jfrj.siga.vraptor.GrupoController.java

/**
 * Grava o grupo e as configuraes/* w w w  .  j a v  a 2 s .  com*/
 * @param idConfiguracao TODO
 * 
 * @throws AplicacaoException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws InvocationTargetException
 */
public Long aGravar(Long idCpGrupo, String siglaGrupo, String dscGrupo, CpGrupoDeEmailSelecao grupoPaiSel,
        Integer codigoTipoConfiguracaoNova, String conteudoConfiguracaoNova, List<String> idConfiguracao,
        List<String> codigoTipoConfiguracao, List<String> conteudoConfiguracao) throws Exception {

    if (siglaGrupo == null) {
        throw new AplicacaoException("A sigla do grupo deve ser definida!");
    }

    idConfiguracao = Optional.fromNullable(idConfiguracao).or(new ArrayList<String>());

    codigoTipoConfiguracao = Optional.fromNullable(codigoTipoConfiguracao).or(new ArrayList<String>());

    conteudoConfiguracao = Optional.fromNullable(conteudoConfiguracao).or(new ArrayList<String>());

    try {
        CpGrupo grp = null;
        CpGrupo grpNovo = null;
        Date dt = dao().consultarDataEHoraDoServidor();
        CpTipoGrupo tpGrp = obterCpTipoGrupoPorId(getIdTipoGrupo());
        if (tpGrp == null) {
            throw new AplicacaoException("Tipo de grupo nulo para Id do grupo: " + idCpGrupo);
        }

        // Substituir isso por uma fbrica
        //
        if (tpGrp.getIdTpGrupo() == CpTipoGrupo.TIPO_GRUPO_GRUPO_DE_DISTRIBUICAO)
            grpNovo = new CpGrupoDeEmail();
        if (tpGrp.getIdTpGrupo() == CpTipoGrupo.TIPO_GRUPO_PERFIL_DE_ACESSO)
            grpNovo = new CpPerfil();
        if (tpGrp.getIdTpGrupo() == CpTipoGrupo.TIPO_GRUPO_PERFIL_JEE)
            grpNovo = new CpPerfilJEE();

        if (idCpGrupo == null) {
            grpNovo.setCpTipoGrupo(tpGrp);
            grpNovo.setOrgaoUsuario(getLotaTitular().getOrgaoUsuario());
        } else {
            grp = (CpGrupo) Objeto.getImplementation(daoGrupo(idCpGrupo));
            PropertyUtils.copyProperties(grpNovo, grp);
            grpNovo.setIdGrupo(null);
        }
        grpNovo.setCpGrupoPai(grupoPaiSel != null ? grupoPaiSel.getObjeto() : null);
        grpNovo.setDscGrupo(dscGrupo);
        grpNovo.setSiglaGrupo(siglaGrupo);

        dao().iniciarTransacao();
        grp = (CpGrupo) dao().gravarComHistorico(grpNovo, grp, dt, getIdentidadeCadastrante());
        idCpGrupo = grp.getIdGrupo();

        // Fabrica
        ConfiguracaoGrupoFabrica fabrica = new ConfiguracaoGrupoFabrica();
        // grava uma nova configurao

        TipoConfiguracaoGrupoEnum tpCfgGrpEnum = TipoConfiguracaoGrupoEnum.obterPara(tpGrp,
                codigoTipoConfiguracaoNova);
        if (tpCfgGrpEnum != null) {
            ConfiguracaoGrupo cfgGrp = fabrica.getInstance(tpCfgGrpEnum);
            if (isConfiguracaoAvancada(cfgGrp) && !podeEditarConfiguracoesAvancadas()) {
                throw new AplicacaoException("Voc no tem permisso para configurar "
                        + tpCfgGrpEnum.getDescricao()
                        + ". Por favor, entre em contato com o suporte tcnico para realizar tal configurao.");
            }

            if (conteudoConfiguracaoNova != null) {
                cfgGrp.setConteudoConfiguracao(conteudoConfiguracaoNova);
            }

            if (conteudoConfiguracaoNova == null || cfgGrp.getConteudoConfiguracao() == null
                    || cfgGrp.getConteudoConfiguracao().equals("")) {
                throw new AplicacaoException("Erro ao gravar nova configurao para o grupo: contedo do(a) "
                        + tpCfgGrpEnum.getDescricao() + " inexistente! ");
            }
            CpConfiguracao cfg = new CpConfiguracao();
            cfg.setCpTipoConfiguracao(tipoConfiguracao);
            cfg.setHisDtIni(dt);
            cfgGrp.setCpConfiguracao(cfg);
            cfgGrp.setCpGrupo(grp);
            cfgGrp.atualizarCpConfiguracao();
            dao().gravarComHistorico(cfg, getIdentidadeCadastrante());
        }

        // processa as configuraes existentes
        configuracoesGrupo = Cp.getInstance().getConf().obterCfgGrupo(grp);
        for (int i = 0; i < idConfiguracao.size(); i++) {
            Long idCfg = Long.parseLong(idConfiguracao.get(i));
            for (ConfiguracaoGrupo cfgGrpGravada : configuracoesGrupo) {
                Long idCfgGravada = cfgGrpGravada.getCpConfiguracao().getIdConfiguracao();
                if (idCfgGravada.equals(idCfg)) {
                    Integer tpCfg = Integer.parseInt(codigoTipoConfiguracao.get(i));
                    // Remoo de uma configurao gravada antes
                    if (tpCfg.equals(-1)) {
                        // excluso remove apenas logicamente, deixa o
                        // registro antigo como log
                        if (isConfiguracaoAvancada(cfgGrpGravada) && !podeEditarConfiguracoesAvancadas()) {
                            throw new AplicacaoException("Voc no tem permisso para remover "
                                    + cfgGrpGravada.getTipo().getDescricao()
                                    + ". Por favor, entre em contato com o suporte tcnico para realizar tal configurao.");
                        }

                        cfgGrpGravada.getCpConfiguracao().setHisDtFim(dt);
                        dao().gravarComHistorico(cfgGrpGravada.getCpConfiguracao(), getIdentidadeCadastrante());
                    } else {
                        String cfgConteudo = conteudoConfiguracao.get(i);
                        // Nato: o ideal seria se pudssemos utilizar o
                        // mtodo "semelhante" para comparar configuraes.
                        // No entanto, como as configuraes anteriores so
                        // lidas do "cache-da-aplicao", e no do
                        // Hibernate, fica impossvel fazer a comparao
                        // automaticamente. Por isso,  necessrio esse "if"
                        // que s grava alteraes se no for do mesmo tipo
                        // ou no tiver mesmo contedo que a gravada
                        if (!tpCfg.equals(cfgGrpGravada.getTipo().getCodigo())
                                || !cfgConteudo.equals(cfgGrpGravada.getConteudoConfiguracao())) {
                            TipoConfiguracaoGrupoEnum tpCfgGrpNova = TipoConfiguracaoGrupoEnum.obterPara(tpGrp,
                                    tpCfg);
                            ConfiguracaoGrupo cfgGrpNova = fabrica.getInstance(tpCfgGrpNova);
                            if (isConfiguracaoAvancada(cfgGrpNova) && !podeEditarConfiguracoesAvancadas()) {
                                throw new AplicacaoException("Voc no tem permisso para configurar "
                                        + tpCfgGrpNova.getDescricao()
                                        + ". Por favor, entre em contato com o suporte tcnico para realizar tal configurao.");
                            }
                            if (cfgConteudo == null || cfgConteudo.equals("")) {
                                throw new AplicacaoException(
                                        "Erro ao gravar alterao da configurao para o grupo: contedo do(a)"
                                                + tpCfgGrpEnum.getDescricao() + " inexistente!");
                            }
                            cfgGrpNova.setConteudoConfiguracao(cfgConteudo);
                            CpConfiguracao cfgNova = new CpConfiguracao();
                            cfgNova.setCpTipoConfiguracao(tipoConfiguracao);
                            cfgGrpNova.setCpConfiguracao(cfgNova);
                            cfgGrpNova.setCpGrupo(grp);
                            cfgGrpNova.atualizarCpConfiguracao();
                            dao().gravarComHistorico(cfgNova, cfgGrpGravada.getCpConfiguracao(), dt,
                                    getIdentidadeCadastrante());
                        }
                    }
                }
            }
        }

        dao().commitTransacao();
        Cp.getInstance().getConf().limparCache(
                dao().consultar(CpTipoConfiguracao.TIPO_CONFIG_PERTENCER, CpTipoConfiguracao.class, false));
        return idCpGrupo;
    } catch (Exception e) {
        throw new AplicacaoException("Id do grupo: " + idCpGrupo + " erro ao gravar grupo e configuraes.", 0,
                e);
    }
}

From source file:de.ingrid.importer.udk.strategy.v32.IDCStrategy3_2_0_migrateUsers.java

/** Called recursively to extract full institution path ! */
private AddrHelper readAddress(String addrUuid, boolean alsoReadCommunication, AddrHelper myAddressToExtend)
        throws Exception {
    Integer addrType = null;//from w  ww.  j  a  v  a2 s .co m
    String addrParentUuid = null;

    Statement stNode = jdbc.createStatement();
    ResultSet rsNode = jdbc.executeQuery("select * from address_node where addr_uuid = '" + addrUuid + "'",
            stNode);
    while (rsNode.next()) {
        long addrNodeId = rsNode.getLong("id");
        long addrIdWork = rsNode.getLong("addr_id");
        long addrIdPubl = rsNode.getLong("addr_id_published");
        addrParentUuid = rsNode.getString("fk_addr_uuid");

        // we migrate published version !
        long addrId = addrIdPubl;
        if (addrId == 0) {
            log.error("User Address (or Parent) NOT PUBLISHED, we migrate working version !!! " + addrUuid);
            addrId = addrIdWork;
        } else {
            if (addrIdWork != addrIdPubl) {
                log.warn("User Address (or Parent) HAS WORKING VERSION, we migrate published version !!! "
                        + addrUuid);
            }
        }

        // Read Address
        Statement stAddress = jdbc.createStatement();
        ResultSet rsAddress = jdbc.executeQuery("select * from t02_address where id = " + addrId, stAddress);
        while (rsAddress.next()) {
            addrType = rsAddress.getInt("adr_type");
            String addrInstitution = rsAddress.getString("institution");

            // read / extend data
            if (myAddressToExtend == null) {
                // initial call, this is the user address
                myAddressToExtend = new AddrHelper(addrUuid, addrId, addrNodeId);
                myAddressToExtend.addrType = addrType;
                myAddressToExtend.firstname = rsAddress.getString("firstname");
                myAddressToExtend.lastname = rsAddress.getString("lastname");
                myAddressToExtend.street = rsAddress.getString("street");
                myAddressToExtend.postcode = rsAddress.getString("postcode");
                myAddressToExtend.city = rsAddress.getString("city");
                myAddressToExtend.institution = addrInstitution;
            } else {
                // just extend institution
                if (addrInstitution != null && addrInstitution.trim().length() > 0) {
                    if (myAddressToExtend.institution == null) {
                        myAddressToExtend.institution = addrInstitution.trim();
                    } else {
                        myAddressToExtend.institution = addrInstitution.trim() + " / "
                                + myAddressToExtend.institution;
                    }
                }
            }

            // Read Email
            if (alsoReadCommunication) {
                Statement stComm = jdbc.createStatement();
                ResultSet rsComm = jdbc
                        .executeQuery("select * from t021_communication where adr_id = " + addrId, stComm);
                String freeEmail = null;
                while (rsComm.next()) {
                    Integer commtypeKey = rsComm.getInt("commtype_key");
                    String commtypeValue = rsComm.getString("commtype_value");
                    String commValue = rsComm.getString("comm_value");
                    if (commValue == null) {
                        continue;
                    }

                    if (commtypeKey.equals(COMM_TYPE_EMAIL)) {
                        myAddressToExtend.email = commValue;
                    } else if (commtypeKey.equals(COMM_TYPE_PHONE)) {
                        myAddressToExtend.phone = commValue;
                    } else if (commtypeKey.equals(-1)) {
                        // just for sure, remember email entered as free entry !
                        if (commtypeValue != null && commtypeValue.toLowerCase().contains("mail")
                                && commValue.contains("@")) {
                            freeEmail = commValue;
                        }
                    }
                }
                rsComm.close();
                stComm.close();

                // add free email entry if no regular email !
                if (myAddressToExtend.email == null) {
                    myAddressToExtend.email = freeEmail;
                }
            }
        }
        rsAddress.close();
        stAddress.close();
    }
    rsNode.close();
    stNode.close();

    // read parent if not institution yet to extract full institution !
    if (addrParentUuid != null && !ADDRESS_TYPE_INSTITUTION.equals(addrType)) {
        readAddress(addrParentUuid, false, myAddressToExtend);
    }

    return myAddressToExtend;
}

From source file:ch.ralscha.extdirectspring.provider.RemoteProviderStoreRead.java

@ExtDirectMethod(value = ExtDirectMethodType.STORE_READ)
public ExtDirectStoreResult<Row> method10(ExtDirectStoreReadRequest request, Locale locale,
        @RequestParam(value = "id", required = false, defaultValue = "20") Integer id) {

    if (!id.equals(20)) {
        assertThat(id).isEqualTo(10);/*from   w  w  w.  ja va 2s . c o m*/
        assertThat(request.getParams().size()).isEqualTo(1);
        assertThat(request.getParams()).contains(entry("id", 10));
    } else {
        assertThat(id).isEqualTo(20);
        assertThat(request.getParams().isEmpty()).isTrue();
    }
    assertThat(locale).isEqualTo(Locale.ENGLISH);

    return RemoteProviderStoreRead.createExtDirectStoreResult(request, ":" + id + ";" + locale);
}

From source file:edu.ku.brc.specify.conversion.SynonymCleanup.java

/**
 * @param doCleanup true does clean and report, false does report only
 * @param frame progress frame/*from   www  . ja  va2s .  c om*/
 */
private void fixMisparentedSynonyms(List<Object[]> synConfigs) {
    Connection newDBConn = DBConnection.getInstance().getConnection();
    final String TOKEN = "<!-- STATISTICS -->";
    try {
        TableWriter tblWriter = new TableWriter(tmpReportName, "Orphan Synonyms for " + collectionName, true);
        tblWriter.println(TOKEN);
        //tblWriter.startTable();
        //String parentRankText = "Parent";//getRankText(parentRank);
        //tblWriter.logHdr(NBSP, "Orphan Synonym", "Current " + parentRankText, "Current Family", "Proposed " + parentRankText, "Proposed Family", "Catalog Numbers<BR>Determined to Synonym");

        Discipline discipline = AppContextMgr.getInstance().getClassObject(Discipline.class);
        PlaceholderHelper phHelper = new PlaceholderHelper(doCleanup, discipline.getTaxonTreeDef());
        phHelper.setSynonymBranch(true);
        phHelper.buildPlaceHolderInfo();

        DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(Taxon.getClassTableId());
        String whereStr = QueryAdjusterForDomain.getInstance().getSpecialColumns(ti, false);
        Taxon phTop = phHelper.getHighestPlaceHolder();
        if (phTop.getId() != null && phTop.getNodeNumber() != null
                && phTop.getHighestChildNodeNumber() != null) {
            whereStr = "((" + whereStr + ") AND  NOT NodeNumber BETWEEN " + phTop.getNodeNumber() + " AND "
                    + phTop.getHighestChildNodeNumber() + ")";
        }
        String cntStr = String.format("SELECT COUNT(*) FROM taxon WHERE IsAccepted = 0 AND %s", whereStr);

        // Now eliminate duplicates with no Determination
        String sql = String.format(
                "SELECT K,CNT FROM (SELECT K,COUNT(K) CNT FROM (SELECT CONCAT(AcceptedID, '_', ParentID, '_', TimestampCreated, '_', FullName) AS K FROM taxon WHERE %s AND IsAccepted = 0) T1 GROUP BY K) T1 WHERE CNT > 1",
                whereStr);
        Statement stmt = null;
        try {
            int dupCnt = 0;
            stmt = newDBConn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                Object[] tokens = StringUtils.split(rs.getString(1), '_');
                sql = String.format(
                        "SELECT t.TaxonID FROM taxon t LEFT JOIN determination d ON d.TaxonID = t.TaxonID WHERE AcceptedID = %s AND ParentID = %s AND t.TimestampCreated = '%s' AND t.FullName = '%s'",
                        tokens[0], tokens[1], tokens[2], tokens[3]);
                Integer taxonId = BasicSQLUtils.getCount(sql);
                if (taxonId != null) {
                    log.debug(tokens[3]);
                    dupCnt++;
                }
            }
            rs.close();
            log.debug("dupCnt: " + dupCnt);

        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            if (stmt != null)
                stmt.close();
        }

        //String [] statsStr = new String[synConfigs.size()];
        //int s = 0;

        //String statsStr = "";
        tblWriter.startTable(UIRegistry.getResourceString("SynonymCleanup.Table_2_Title"));
        String parentRankText = "Parent";//getRankText((Integer)config[0]);
        tblWriter.logHdr(NBSP, getResourceString("SynonymCleanup.OrphanSynonym"),
                String.format(getResourceString("SynonymCleanup.CurrentParent"), parentRankText),
                getResourceString("SynonymCleanup.CurrentFamily"),
                String.format(getResourceString("SynonymCleanup.ProposedParent"), parentRankText),
                getResourceString("SynonymCleanup.ProposedFamily"),
                getResourceString("SynonymCleanup.CatalogNumsDetermined"));
        int[] stats = { 0, 0, 0, 0, 0, 0, 0, 0 };

        boolean needKeys = false;
        int currRank = synConfigs.size() > 0 ? (Integer) synConfigs.get(0)[1] : 0;
        int totalSynCount = BasicSQLUtils.getCount(cntStr);
        boolean doPercent = totalSynCount < 5000;
        int progressInterval = totalSynCount / (!doPercent ? 500 : (totalSynCount > 1200 ? 100 : 50));
        if (!doPercent) {
            progressFrame.getProcessProgress().setIndeterminate(true);
            setProgress(0, totalSynCount);
        } else {
            setProgress(0, 100);
        }

        progressInterval = Math.max(progressInterval, 1);
        progressFrame.setDesc(doCleanup ? "Cleaning up Synonyms..." : "Creating Synonym Report...");

        for (int c = 1; c < synConfigs.size(); c++) {
            if (currRank == (Integer) synConfigs.get(c)[1]) {
                needKeys = true;
                break;
            }
            currRank = (Integer) synConfigs.get(c)[1];
        }

        Set<Integer> processedKeys = needKeys ? new HashSet<Integer>() : null;
        for (int c = 0; c < synConfigs.size(); c++) {
            //tblWriter.startTable();
            //String parentRankText = getRankText((Integer)config[0]);
            //tblWriter.logHdr(NBSP, "Orphan Synonym", "Current " + parentRankText, "Current Family", "Proposed " + parentRankText, "Proposed Family", "Catalog Numbers<BR>Determined to Synonym");
            //statsStr[s++] = fixMisparentedSynonymsLevel(newDBConn, tblWriter, phHelper, (Integer)config[0], (Integer)config[1]);
            Object[] config = synConfigs.get(c);
            Integer parentRank = (Integer) config[0];
            Integer childRank = (Integer) config[1];
            boolean skipBads = needKeys && c < synConfigs.size() - 1
                    && childRank.equals(synConfigs.get(c + 1)[1]); //wha???               
            fixMisparentedSynonymsLevel(newDBConn, tblWriter, phHelper, parentRank, childRank, skipBads, stats,
                    processedKeys, progressInterval, doPercent);
            //tblWriter.endTable();
        }
        tblWriter.endTable();
        tblWriter.flush();
        tblWriter.close();
        progressFrame.processDone();

        if (doCleanup) {
            try {
                phHelper.getTaxonTreeDef().updateAllNodes(null, true, true);
            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TreeTableViewer.class, ex);
            }
        }
        StringBuilder statsSB = new StringBuilder();
        statsSB.append("<BR><TABLE class=\"o\" cellspacing=\"0\" cellpadding=\"1\"><caption>"
                + UIRegistry.getResourceString("SynonymCleanup.Table_1_Title") + "</caption>\n");
        String[] descs = { getResourceString("SynonymCleanup.TotalRecsProcessed"), //1 
                getResourceString("SynonymCleanup.NumberSynsDetermined"), //2 
                getResourceString("SynonymCleanup.NumberSynsCorrectlyParented"), //3  
                getResourceString("SynonymCleanup.NumberRecsInReport"), //4 
                getResourceString("SynonymCleanup.NumberRecsWithNewGenus"), //5 
                getResourceString("SynonymCleanup.NumberRecsParentedToPlaceHolder"), //6 
                getResourceString("SynonymCleanup.NumberRecordsInError"), //7 
                getResourceString("SynonymCleanup.NumberOfUpdateErrors") };//8
        //int[]    values = {processCnt, cnt, fndCnt, phCnt, withCatNumCnt, correct, err, updateErr};
        for (int i = 0; i < descs.length; i++) {
            statsSB.append(createRow(descs[i], stats[i], stats[0]));
        }
        statsSB.append("</TABLE><BR/><BR/><BR/>");

        PrintWriter pw = new PrintWriter(reportName);
        File tf = new File(tmpReportName);
        BufferedReader br = new BufferedReader(new FileReader(tf));
        try {
            String line = br.readLine();
            //s = 0;
            doPercent = stats[0] < 5000;
            progressInterval = stats[0] / (!doPercent ? 500 : (stats[0] > 1200 ? 100 : 50));
            if (!doPercent) {
                progressFrame.getProcessProgress().setIndeterminate(true);
                setProgress(0, stats[0]);
            } else {
                setProgress(0, 100);
            }

            progressInterval = Math.max(progressInterval, 1);
            int processCnt = 0;
            boolean statsPrinted = false;
            boolean inDetailTbl = false;
            while (line != null) {
                boolean isTableStart = line.trim().toLowerCase().startsWith("<table ");
                boolean isTableEnd = line.trim().toLowerCase().startsWith("</table");
                if (line.startsWith(TOKEN)) {
                    //pw.println(statsStr[s++]);
                    //pw.println(statsStr);
                    pw.println(statsSB.toString());
                    statsPrinted = true;
                } else {
                    boolean printIt = tblWriter.hasLines() || !statsPrinted;
                    if (!printIt && !tblWriter.hasLines()) {
                        if (statsPrinted) {
                            if (!inDetailTbl) {
                                inDetailTbl = isTableStart;
                            } else {
                                inDetailTbl = !isTableEnd;
                            }
                        }
                        printIt = !inDetailTbl && !isTableEnd;
                    }
                    if (printIt) {
                        pw.println(line);
                    }
                }
                line = br.readLine();
                processCnt++;
                if (processCnt % progressInterval == 0) {
                    int p = (int) (((processCnt * 100) / (double) stats[0]) + 0.5);
                    setProgress(doPercent ? p : processCnt, null);
                }
            }
            isSuccessful = true;

        } finally {
            br.close();
            pw.flush();
            pw.close();
        }
        tf.delete();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:nc.noumea.mairie.organigramme.viewmodel.OrganigrammeViewModel.java

private List<EntiteDto> getListeFromEntiteAndNiveau(List<EntiteDto> listeEnfant, Integer niveau,
        List<EntiteDto> result) {
    if (niveau.equals(0)) {
        result.addAll(listeEnfant);//from   w  w  w.j  a  v a 2s  .c o m
        return result;
    }

    for (EntiteDto entiteDtoEnfant : listeEnfant) {
        getListeFromEntiteAndNiveau(entiteDtoEnfant.getEnfants(), niveau - 1, result);
    }

    return result;
}

From source file:net.neurowork.cenatic.centraldir.workers.xml.AsociacionXmlImporter.java

private Asociacion importAsociacion(String xmlString, Integer associationCode)
        throws ParserConfigurationException, SAXException, IOException {
    Document doc = XmlParserUtil.createDocumentFromString(xmlString);
    Asociacion ret = null;// w  ww  . j  a v  a  2s. co m
    NodeList nodeLst = doc.getElementsByTagName("association");

    for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
            Element elPDU = (Element) fstNode;
            String code = XmlParserUtil.getAttribute(elPDU, "code");
            String url = XmlParserUtil.getAttribute(elPDU, "url");
            String icon = XmlParserUtil.getAttribute(elPDU, "icon");
            NodeList fstNm = elPDU.getChildNodes();
            String associationName = null;

            if (fstNm.getLength() > 0) {
                associationName = ((Node) fstNm.item(0)).getNodeValue();

                Integer capId = AbstractXmlImporter.getId(code);
                Asociacion association = null;
                try {
                    Collection<Asociacion> associations = asociacionService.findByName(associationName);

                    if (associations != null && associations.size() > 0) {
                        association = associations.iterator().next();
                    } else {
                        association = new Asociacion();
                        association.setName(associationName);
                        association.setUrl(url);
                        association.setIcon(icon);
                        logger.info("Saving Asociacion: " + associationName + " url: " + url + " icon " + icon);
                        asociacionService.save(association);
                    }

                    if (capId != null && capId.equals(associationCode)) {
                        ret = association;
                    }
                } catch (ServiceException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }
    return ret;
}