Example usage for java.lang Long equals

List of usage examples for java.lang Long equals

Introduction

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

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object to the specified object.

Usage

From source file:controllers.core.PortfolioEntryPlanningController.java

/**
 * Create or edit an allocated delivery unit (for a resource plan).
 * /*from w w  w . jav  a  2  s. c om*/
 * @param id
 *            the porfolio entry id
 * @param allocatedOrgUnitId
 *            the allocated delivery unit id, set to 0 for create case
 */
@With(CheckPortfolioEntryExists.class)
@Dynamic(IMafConstants.PORTFOLIO_ENTRY_EDIT_DYNAMIC_PERMISSION)
public Result manageAllocatedOrgUnit(Long id, Long allocatedOrgUnitId) {

    // get the portfolioEntry
    PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(id);

    // initiate the form with the template
    Form<PortfolioEntryResourcePlanAllocatedOrgUnitFormData> allocatedOrgUnitForm = allocatedOrgUnitFormTemplate;

    // edit case: inject values
    if (!allocatedOrgUnitId.equals(Long.valueOf(0))) {

        PortfolioEntryResourcePlanAllocatedOrgUnit allocatedOrgUnit = PortfolioEntryResourcePlanDAO
                .getPEResourcePlanAllocatedOrgUnitById(allocatedOrgUnitId);

        // security: the portfolioEntry must be related to the object
        if (!allocatedOrgUnit.portfolioEntryResourcePlan.lifeCycleInstancePlannings
                .get(0).lifeCycleInstance.portfolioEntry.id.equals(id)) {
            return forbidden(views.html.error.access_forbidden.render(""));
        }

        allocatedOrgUnitForm = allocatedOrgUnitFormTemplate
                .fill(new PortfolioEntryResourcePlanAllocatedOrgUnitFormData(allocatedOrgUnit));

        // add the custom attributes values
        this.getCustomAttributeManagerService().fillWithValues(allocatedOrgUnitForm,
                PortfolioEntryResourcePlanAllocatedOrgUnit.class, allocatedOrgUnitId);
    } else {
        // add the custom attributes default values
        this.getCustomAttributeManagerService().fillWithValues(allocatedOrgUnitForm,
                PortfolioEntryResourcePlanAllocatedOrgUnit.class, null);
    }

    return ok(views.html.core.portfolioentryplanning.allocated_org_unit_manage.render(portfolioEntry,
            allocatedOrgUnitForm));

}

From source file:controllers.core.PortfolioEntryPlanningController.java

/**
 * Create or edit an allocated competency (for a resource plan).
 * /*www .j  av a 2s. c o  m*/
 * @param id
 *            the porfolio entry id
 * @param allocatedCompetencyId
 *            the allocated competency id, set to 0 for create case
 */
@With(CheckPortfolioEntryExists.class)
@Dynamic(IMafConstants.PORTFOLIO_ENTRY_EDIT_DYNAMIC_PERMISSION)
public Result manageAllocatedCompetency(Long id, Long allocatedCompetencyId) {

    // get the portfolioEntry
    PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(id);

    // initiate the form with the template
    Form<PortfolioEntryResourcePlanAllocatedCompetencyFormData> allocatedCompetencyForm = allocatedCompetencyFormTemplate;

    // edit case: inject values
    if (!allocatedCompetencyId.equals(Long.valueOf(0))) {

        PortfolioEntryResourcePlanAllocatedCompetency allocatedCompetency = PortfolioEntryResourcePlanDAO
                .getPEResourcePlanAllocatedCompetencyById(allocatedCompetencyId);

        // security: the portfolioEntry must be related to the object
        if (!allocatedCompetency.portfolioEntryResourcePlan.lifeCycleInstancePlannings
                .get(0).lifeCycleInstance.portfolioEntry.id.equals(id)) {
            return forbidden(views.html.error.access_forbidden.render(""));
        }

        allocatedCompetencyForm = allocatedCompetencyFormTemplate
                .fill(new PortfolioEntryResourcePlanAllocatedCompetencyFormData(allocatedCompetency));

        // add the custom attributes values
        this.getCustomAttributeManagerService().fillWithValues(allocatedCompetencyForm,
                PortfolioEntryResourcePlanAllocatedCompetency.class, allocatedCompetencyId);
    } else {
        // add the custom attributes default values
        this.getCustomAttributeManagerService().fillWithValues(allocatedCompetencyForm,
                PortfolioEntryResourcePlanAllocatedCompetency.class, null);
    }

    return ok(views.html.core.portfolioentryplanning.allocated_competency_manage.render(portfolioEntry,
            allocatedCompetencyForm));
}

From source file:org.apache.bookkeeper.client.LedgerHandle.java

void ensembleChangeLoop(List<BookieSocketAddress> origEnsemble,
        Map<Integer, BookieSocketAddress> failedBookies) {
    int ensembleChangeId = numEnsembleChanges.incrementAndGet();
    String logContext = String.format("[EnsembleChange(ledger:%d, change-id:%010d)]", ledgerId,
            ensembleChangeId);/*from  w  w w .j  a va 2 s  . com*/

    // when the ensemble changes are too frequent, close handle
    if (ensembleChangeId > clientCtx.getConf().maxAllowedEnsembleChanges) {
        LOG.info("{} reaches max allowed ensemble change number {}", logContext,
                clientCtx.getConf().maxAllowedEnsembleChanges);
        handleUnrecoverableErrorDuringAdd(WriteException);
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("{} Replacing {} in {}", logContext, failedBookies, origEnsemble);
    }

    AtomicInteger attempts = new AtomicInteger(0);
    new MetadataUpdateLoop(clientCtx.getLedgerManager(), getId(), this::getVersionedLedgerMetadata,
            (metadata) -> metadata.getState() == LedgerMetadata.State.OPEN
                    && failedBookies.entrySet().stream().anyMatch(e -> LedgerMetadataUtils
                            .getLastEnsembleValue(metadata).get(e.getKey()).equals(e.getValue())),
            (metadata) -> {
                attempts.incrementAndGet();

                List<BookieSocketAddress> currentEnsemble = getCurrentEnsemble();
                List<BookieSocketAddress> newEnsemble = EnsembleUtils.replaceBookiesInEnsemble(
                        clientCtx.getBookieWatcher(), metadata, currentEnsemble, failedBookies, logContext);
                Long lastEnsembleKey = LedgerMetadataUtils.getLastEnsembleKey(metadata);
                LedgerMetadataBuilder builder = LedgerMetadataBuilder.from(metadata);
                long newEnsembleStartEntry = getLastAddConfirmed() + 1;
                checkState(lastEnsembleKey <= newEnsembleStartEntry,
                        "New ensemble must either replace the last ensemble, or add a new one");
                if (LOG.isDebugEnabled()) {
                    LOG.debug("{}[attempt:{}] changing ensemble from: {} to: {} starting at entry: {}",
                            logContext, attempts.get(), currentEnsemble, newEnsemble, newEnsembleStartEntry);
                }

                if (lastEnsembleKey.equals(newEnsembleStartEntry)) {
                    return builder.replaceEnsembleEntry(newEnsembleStartEntry, newEnsemble).build();
                } else {
                    return builder.newEnsembleEntry(newEnsembleStartEntry, newEnsemble).build();
                }
            }, this::setLedgerMetadata).run().whenCompleteAsync((metadata, ex) -> {
                if (ex != null) {
                    LOG.warn("{}[attempt:{}] Exception changing ensemble", logContext, attempts.get(), ex);
                    handleUnrecoverableErrorDuringAdd(BKException.getExceptionCode(ex, WriteException));
                } else if (metadata.getValue().isClosed()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                                "{}[attempt:{}] Metadata closed during attempt to replace bookie."
                                        + " Another client must have recovered the ledger.",
                                logContext, attempts.get());
                    }
                    handleUnrecoverableErrorDuringAdd(BKException.Code.LedgerClosedException);
                } else if (metadata.getValue().getState() == LedgerMetadata.State.IN_RECOVERY) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                                "{}[attempt:{}] Metadata marked as in-recovery during attempt to replace bookie."
                                        + " Another client must be recovering the ledger.",
                                logContext, attempts.get());
                    }

                    handleUnrecoverableErrorDuringAdd(BKException.Code.LedgerFencedException);
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("{}[attempt:{}] Success updating metadata.", logContext, attempts.get());
                    }

                    List<BookieSocketAddress> newEnsemble = null;
                    Set<Integer> replaced = null;
                    synchronized (metadataLock) {
                        if (!delayedWriteFailedBookies.isEmpty()) {
                            Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(
                                    delayedWriteFailedBookies);
                            delayedWriteFailedBookies.clear();

                            ensembleChangeLoop(origEnsemble, toReplace);
                        } else {
                            newEnsemble = getCurrentEnsemble();
                            replaced = EnsembleUtils.diffEnsemble(origEnsemble, newEnsemble);
                            LOG.info("New Ensemble: {} for ledger: {}", newEnsemble, ledgerId);

                            changingEnsemble = false;
                        }
                    }
                    if (newEnsemble != null) { // unsetSuccess outside of lock
                        unsetSuccessAndSendWriteRequest(newEnsemble, replaced);
                    }
                }
            }, clientCtx.getMainWorkerPool().chooseThread(ledgerId));
}

From source file:com.square.tarificateur.noyau.service.implementations.TarificateurServiceImpl.java

/**
 * {@inheritDoc}/*from w ww . j  a v a2s  .  co  m*/
 */
@Override
public List<IdentifiantLibelleDto> getListeModelesDevisByCriteres(CritereModeleDevisDto criteres) {
    // Rcupration des modles de devis prsents dans l'ditique
    final List<ModeleDevisDto> listeModelesDevis = editiqueMappingService.getListeModelesDevis();

    // Filtrage des modles de devis
    final List<IdentifiantLibelleDto> listeModeles = new ArrayList<IdentifiantLibelleDto>();
    if (criteres != null && criteres.getListeIdsModeles() != null && criteres.getListeIdsModeles().size() > 0) {
        for (Long idModele : criteres.getListeIdsModeles()) {
            for (ModeleDevisDto modeleEditique : listeModelesDevis) {
                if (idModele.equals(modeleEditique.getIdentifiant())) {
                    listeModeles.add((IdentifiantLibelleDto) mapperDozerBean.map(modeleEditique,
                            IdentifiantLibelleDto.class));
                    break;
                }
            }
        }
    } else {
        if (listeModelesDevis != null && listeModelesDevis.size() > 0) {
            for (ModeleDevisDto modeleEditique : listeModelesDevis) {
                listeModeles.add((IdentifiantLibelleDto) mapperDozerBean.map(modeleEditique,
                        IdentifiantLibelleDto.class));
            }
        }
    }
    return listeModeles;
}

From source file:org.apache.flink.streaming.connectors.kafka.KafkaConsumerTestBase.java

/**
 * Ensures that the committed offsets to Kafka are the offsets of "the next record to process"
 *//*w ww.java 2s.  c o m*/
public void runCommitOffsetsToKafka() throws Exception {
    // 3 partitions with 50 records each (0-49, so the expected commit offset of each partition should be 50)
    final int parallelism = 3;
    final int recordsInEachPartition = 50;

    final String topicName = writeSequence("testCommitOffsetsToKafkaTopic", recordsInEachPartition, parallelism,
            1);

    final StreamExecutionEnvironment env = StreamExecutionEnvironment.createRemoteEnvironment("localhost",
            flinkPort);
    env.getConfig().disableSysoutLogging();
    env.getConfig().setRestartStrategy(RestartStrategies.noRestart());
    env.setParallelism(parallelism);
    env.enableCheckpointing(200);

    DataStream<String> stream = env
            .addSource(kafkaServer.getConsumer(topicName, new SimpleStringSchema(), standardProps));
    stream.addSink(new DiscardingSink<String>());

    final AtomicReference<Throwable> errorRef = new AtomicReference<>();
    final Thread runner = new Thread("runner") {
        @Override
        public void run() {
            try {
                env.execute();
            } catch (Throwable t) {
                if (!(t.getCause() instanceof JobCancellationException)) {
                    errorRef.set(t);
                }
            }
        }
    };
    runner.start();

    final Long l50 = 50L; // the final committed offset in Kafka should be 50
    final long deadline = 30_000_000_000L + System.nanoTime();

    KafkaTestEnvironment.KafkaOffsetHandler kafkaOffsetHandler = kafkaServer.createOffsetHandler();

    do {
        Long o1 = kafkaOffsetHandler.getCommittedOffset(topicName, 0);
        Long o2 = kafkaOffsetHandler.getCommittedOffset(topicName, 1);
        Long o3 = kafkaOffsetHandler.getCommittedOffset(topicName, 2);

        if (l50.equals(o1) && l50.equals(o2) && l50.equals(o3)) {
            break;
        }

        Thread.sleep(100);
    } while (System.nanoTime() < deadline);

    // cancel the job
    JobManagerCommunicationUtils.cancelCurrentJob(flink.getLeaderGateway(timeout));

    final Throwable t = errorRef.get();
    if (t != null) {
        throw new RuntimeException("Job failed with an exception", t);
    }

    // final check to see if offsets are correctly in Kafka
    Long o1 = kafkaOffsetHandler.getCommittedOffset(topicName, 0);
    Long o2 = kafkaOffsetHandler.getCommittedOffset(topicName, 1);
    Long o3 = kafkaOffsetHandler.getCommittedOffset(topicName, 2);
    Assert.assertEquals(Long.valueOf(50L), o1);
    Assert.assertEquals(Long.valueOf(50L), o2);
    Assert.assertEquals(Long.valueOf(50L), o3);

    kafkaOffsetHandler.close();
    deleteTestTopic(topicName);
}

From source file:com.square.tarificateur.noyau.service.implementations.TarificateurEditiqueServiceImpl.java

/**
 * Rcupre le DTO permettant la gnration d'un bulletin d'adhsion  partir d'un devis.
 * @param devis le devis/*w  w w  . j a v  a2 s  .  com*/
 * @param editionDocumentDto les infos pour l'dition
 * @param reference la rfrence de l'opportunit ou du devis.
 * @param idModeleDevis l'identifiant du modle de devis
 * @param eidAgence l'identifiant extrieur de l'agence responsable
 * @param infosPersonneSquare le cache des infos de personnes Square
 * @return le DTO contenant les infos ncessaires  la gnration d'un bulletin d'adhsion
 */
public DocumentsBulletinsAdhesionDto getDocumentsBaDtoPourDevis(Devis devis,
        EditionDocumentDto editionDocumentDto, String reference, Long idModeleDevis, Long eidAgence,
        InfosPersonneSquareBean infosPersonneSquare) {
    logger.debug(messageSourceUtil.get(MessageKeyUtil.LOGGER_DEBUG_GENERATION_DOCUMENT_BA_DEVIS,
            new String[] { String.valueOf(devis.getId()) }));
    final DocumentsBulletinsAdhesionDto documentsBulletinsAdhesionDto = new DocumentsBulletinsAdhesionDto();
    // Rcupration du prospect
    final ProspectBADto prospectBADto = mapperProspect(devis.getPersonnePrincipale(),
            devis.getEidRelationParrain(), infosPersonneSquare);
    if (idModeleDevis != null
            && !idModeleDevis.equals(editiqueMappingService.getConstanteIdModeleDevisFicheTransfert())) {
        prospectBADto.setNumeroAdherent(null);
    }
    documentsBulletinsAdhesionDto.setProspect(prospectBADto);
    // Rcupration de l'agence
    if (eidAgence != null) {
        documentsBulletinsAdhesionDto.setAgence(getAgenceBa(eidAgence));
    }
    // Cration de la liste des bulletins d'adhsion
    documentsBulletinsAdhesionDto.setListeBulletinsAdhesion(creerListeBulletinsAdhesionPourDevis(devis,
            prospectBADto, editionDocumentDto, reference, idModeleDevis, infosPersonneSquare));
    // Motif du devis
    documentsBulletinsAdhesionDto.setMotifDevis(devis.getMotif() != null
            ? (IdentifiantLibelleDto) mapperDozerBean.map(devis.getMotif(), IdentifiantLibelleDto.class)
            : null);
    // Modle de devis
    documentsBulletinsAdhesionDto.setIdModeleDevis(idModeleDevis);
    // On detecte si il s'agit d'une signature numrique ou pas
    documentsBulletinsAdhesionDto.setFromSignatureNumerique(editionDocumentDto.getFromSignatureNumerique());
    // On complte le DTO (flag possedeProduitSante)
    completerDocumentsBulletinsAdhesion(documentsBulletinsAdhesionDto);
    // On complte les infos de rglement
    completerInfosReglement(documentsBulletinsAdhesionDto, devis, editionDocumentDto);
    return documentsBulletinsAdhesionDto;
}

From source file:com.cloud.storage.StorageManagerImpl.java

@Override
public PrimaryDataStoreInfo updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException {
    // Input validation
    Long id = cmd.getId();//  w  w  w . j a va2  s . c o  m

    StoragePoolVO pool = _storagePoolDao.findById(id);
    if (pool == null) {
        throw new IllegalArgumentException("Unable to find storage pool with ID: " + id);
    }

    final List<String> storagePoolTags = cmd.getTags();
    if (storagePoolTags != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Updating Storage Pool Tags to :" + storagePoolTags);
        }
        _storagePoolTagsDao.persist(pool.getId(), storagePoolTags);
    }

    Long updatedCapacityBytes = null;
    Long capacityBytes = cmd.getCapacityBytes();

    if (capacityBytes != null) {
        if (capacityBytes != pool.getCapacityBytes()) {
            updatedCapacityBytes = capacityBytes;
        }
    }

    Long updatedCapacityIops = null;
    Long capacityIops = cmd.getCapacityIops();

    if (capacityIops != null) {
        if (!capacityIops.equals(pool.getCapacityIops())) {
            updatedCapacityIops = capacityIops;
        }
    }

    if (updatedCapacityBytes != null || updatedCapacityIops != null) {
        StoragePoolVO storagePool = _storagePoolDao.findById(id);
        DataStoreProvider dataStoreProvider = _dataStoreProviderMgr
                .getDataStoreProvider(storagePool.getStorageProviderName());
        DataStoreLifeCycle dataStoreLifeCycle = dataStoreProvider.getDataStoreLifeCycle();

        if (dataStoreLifeCycle instanceof PrimaryDataStoreLifeCycle) {
            Map<String, String> details = new HashMap<String, String>();

            details.put(PrimaryDataStoreLifeCycle.CAPACITY_BYTES,
                    updatedCapacityBytes != null ? String.valueOf(updatedCapacityBytes) : null);
            details.put(PrimaryDataStoreLifeCycle.CAPACITY_IOPS,
                    updatedCapacityIops != null ? String.valueOf(updatedCapacityIops) : null);

            ((PrimaryDataStoreLifeCycle) dataStoreLifeCycle).updateStoragePool(storagePool, details);
        }
    }

    Boolean enabled = cmd.getEnabled();
    if (enabled != null) {
        if (enabled) {
            enablePrimaryStoragePool(pool);
        } else {
            disablePrimaryStoragePool(pool);
        }
    }

    if (updatedCapacityBytes != null) {
        _storagePoolDao.updateCapacityBytes(id, capacityBytes);
    }

    if (updatedCapacityIops != null) {
        _storagePoolDao.updateCapacityIops(id, capacityIops);
    }

    return (PrimaryDataStoreInfo) _dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary);
}

From source file:service.AdService.java

public void create(Boolean isAutherized, Long catId, String email, String phone, String price,
        MultipartFile previews[], String name, String desc, Long booleanIds[], String booleanVals[],
        Long stringIds[], String stringVals[], Long numIds[], String snumVals[], Long dateIds[],
        Date dateVals[], Long selIds[], Long selVals[], Long multyIds[], String multyVals[], Date dateFrom,
        Date dateTo, Long localIds[]) throws IOException {
    Boolean newUser = false;/*  ww  w  .  j a v a2s.c  o  m*/
    if (catId != null) {
        Category cat = catDao.find(catId);
        if (cat != null) {
            if (isAutherized || (!isAutherized && email != null && !email.equals(""))) {

                PhoneEditor phe = new PhoneEditor();
                phone = phe.getPhone(phone);
                addError(phe.error);

                if ((phone == null || phone.equals("")) && (email == null || email.equals(""))) {
                    addError(
                            "  email    ? ");
                }

                User user = userService.getUserByMail(email);
                if (!isAutherized && user == null) {
                    user = userService.registerStandardUser(email);
                    newUser = true;
                    List<String> userErrors = userService.getErrors();
                    if (!userErrors.isEmpty()) {
                        for (String er : userErrors) {
                            addError("user_service: " + er + "; ");
                        }
                    }
                }
                Ad ad = new Ad();
                ad.setInsertDate(new Date());
                ad.setShowCount((long) 0);
                ad.setStatus(Ad.NEW);
                ad.setDateFrom(dateFrom);
                ad.setDateTo(dateTo);
                ad.setEmail(email);
                ad.setPhone(phone);

                ad.setAuthor(user);

                ad.setCat(cat);

                Set<Locality> locals = new HashSet();
                /*if (region != null) {
                 if (region.isAllRussia()) {
                 locals.addAll(locDao.getAll());
                 } else {
                 locals.addAll(region.getLocalities());
                 }
                 }*/
                if (localIds != null && localIds.length > 0) {
                    locals.addAll(locDao.getLocs(localIds));
                } else {
                    addError("  ?   ");
                }
                ad.setLocalities(locals);
                ad.setName(name);
                ad.setDescription(desc);
                ad.setPrice(getNumFromString(price, true));
                ad.setValues(new HashSet());
                if (validate(ad) && getErrors().isEmpty()) {
                    adDao.save(ad);

                    List<Long> reqParamIds = catDao.getRequiredParamsIds(catId);
                    List<Parametr> catParams = paramDao.getParamsFromCat(catId);
                    int i = 0;
                    ArrayList<String> paramValsErrs = new ArrayList();
                    // ? ??  ? ?  ? ??,  ?, ? ?  
                    //? ad

                    ArrayList<ParametrValue> list4Save = new ArrayList();

                    //      
                    if (booleanIds != null) {
                        if (booleanVals == null) {
                            booleanVals = new String[booleanIds.length];
                        }
                        while (i < booleanIds.length) {
                            Parametr p = paramDao.find(booleanIds[i]);
                            if (catParams.contains(p) && Parametr.BOOL == p.getParamType()) {
                                Long val = ParametrValue.NO;
                                String sval = "";
                                if (booleanVals[i] != null) {
                                    val = ParametrValue.YES;
                                    sval = "";
                                }
                                ParametrValue pv = new ParametrValue();
                                pv.setAd(ad);
                                pv.setParametr(p);
                                pv.setSelectVal(val);
                                pv.setStringVal(sval);
                                if (validate(pv)) {
                                    list4Save.add(pv);
                                }

                            }
                            i++;
                        }
                    }

                    if (stringVals != null && stringVals.length > 0) {
                        i = 0;
                        while (i < stringIds.length) {
                            Long paramId = stringIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.TEXT == p.getParamType()) {
                                String val = stringVals[i];
                                if (val != null && !val.equals("")) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }

                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setStringVal(val);
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    if (snumVals != null && snumVals.length > 0) {
                        i = 0;
                        while (i < numIds.length) {
                            Long paramId = numIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.NUM == p.getParamType()) {
                                String sval = snumVals[i];
                                if (sval != null && !sval.equals("")) {
                                    Double val = getNumFromString(sval, true);
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setNumVal(val);
                                    pv.setStringVal(StringAdapter.getString(val));
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                        if (!getErrors().isEmpty()) {
                            for (String e : getErrors()) {
                                paramValsErrs.add(e);
                            }
                        }
                    }

                    if (dateVals != null && dateVals.length > 0) {
                        i = 0;
                        while (i < dateIds.length) {
                            Long paramId = dateIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.DATE == p.getParamType()) {
                                Date val = dateVals[i];
                                if (val != null) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setDateVal(val);
                                    pv.setStringVal(DateAdapter.formatByDate(val, DateAdapter.SMALL_FORMAT));
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    if (selVals != null && selVals.length > 0) {
                        i = 0;

                        while (i < selIds.length) {
                            Long paramId = selIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.SELECTING == p.getParamType()) {
                                Long val = selVals[i];
                                if (val != null && !val.equals(0L)) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setSelectVal(val);
                                    pv.setStringVal(paramSelDao.find(val).getName());
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    //?  ?
                    //TO DO       (??)
                    if (multyVals != null && multyVals.length > 0) {
                        for (String rawVal : multyVals) {
                            String idValArr[] = rawVal.split("_");
                            if (idValArr.length == 2) {
                                String strId = idValArr[0];
                                String strVal = idValArr[1];
                                Long paramId = Long.valueOf(strId);
                                Long val = Long.valueOf(strVal);
                                Parametr p = paramDao.find(paramId);
                                if (catParams.contains(p) && Parametr.MULTISELECTING == p.getParamType()) {
                                    if (reqParamIds.contains(paramId) && val != null) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setSelectVal(val);
                                    pv.setStringVal(paramSelDao.find(val).getName());
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }
                                }
                            }
                        }
                    }

                    //?  ?    ?    ?
                    if (!reqParamIds.isEmpty() || !paramValsErrs.isEmpty()) {
                        for (Long id : reqParamIds) {
                            addError("    "
                                    + paramDao.find(id).getName() + "; ");
                        }
                        //?
                        adDao.delete(ad);
                    } else {

                        for (ParametrValue pv : list4Save) {
                            paramValueDao.save(pv);
                        }

                        File file = new File("/usr/local/seller/preview/" + ad.getId() + "/");
                        if (file.exists()) {
                            for (File f : file.listFiles()) {
                                f.delete();
                            }
                            file.delete();
                        }
                        file.mkdirs();
                        if (previews != null && previews.length > 0) {
                            i = 0;
                            while (i < 10 && i < previews.length) {
                                MultipartFile prev = previews[i];
                                if (prev != null && 0L < prev.getSize()) {
                                    if (prev.getSize() <= (long) 3 * 1024 * 1024) {
                                        File f = new File(
                                                "/usr/local/seller/preview/" + ad.getId() + "/supPreview");
                                        if (f.exists()) {
                                            f.delete();
                                        }
                                        prev.transferTo(f);
                                        //to do  ? - ??
                                        try {
                                            BufferedImage bi = ImageIO.read(f);
                                            BigDecimal x = BigDecimal.valueOf(0);
                                            BigDecimal y = BigDecimal.valueOf(0);
                                            BigDecimal h = BigDecimal.valueOf(bi.getHeight());
                                            BigDecimal w = BigDecimal.valueOf(bi.getWidth());
                                            if (h.compareTo(w) > 0) {
                                                y = (h.subtract(w)).divide(BigDecimal.valueOf(2),
                                                        RoundingMode.HALF_UP);
                                                h = w;
                                            } else if (h.compareTo(w) < 0) {
                                                x = (w.subtract(h)).divide(BigDecimal.valueOf(2),
                                                        RoundingMode.HALF_UP);
                                                w = h;
                                            }
                                            bi = bi.getSubimage(x.intValue(), y.intValue(), w.intValue(),
                                                    h.intValue());
                                            f.delete();
                                            f = new File("/usr/local/seller/preview/" + ad.getId() + "/" + i);
                                            ImageIO.write(bi, "png", f);
                                        } catch (Exception e) {
                                            addError(
                                                    "? ?   "
                                                            + prev.getName()
                                                            + /*"; s="+prev.getSize()+"; t="+prev.getContentType()+"; l="+previews.length+*/ "; "
                                                            + StringAdapter.getStackTraceException(e));
                                        }
                                    } else {
                                        addError(" " + prev.getName()
                                                + "   ,      ?  3 .");
                                    }
                                }
                                i++;
                            }
                        }

                        if (newUser) {
                            userService.notifyAboutRegistration(email);
                        }
                    }

                } /* else {
                  addError("user:" + user.getId() + " " + user.getName());
                  }*/

            } else {
                addError(
                        "?  ??     email");
            }
        } else {
            addError("? ?  " + catId + "   .");
        }
    } else {
        addError("?  ");
    }
}

From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java

public List getMostDownloadedStudyIds(Long vdcId, Long vdcNetworkId, int numResults) {

    String dataverseClause = "";
    if (vdcId != null) {
        dataverseClause = " and s.owner_id = " + vdcId + " ";
    }//from  ww  w  .j av  a  2  s  .  c  om
    String linkedStudyClause = "";
    String networkClause = "";

    if (vdcNetworkId != null && !vdcNetworkId.equals(vdcNetworkService.findRootNetwork().getId())) {
        networkClause = " and v.vdcnetwork_id = " + vdcNetworkId + " ";
        VDCNetwork vdcNetwork = vdcNetworkService.findById(vdcNetworkId);

        List<Study> linkedStudys = (List) vdcNetwork.getLinkedStudies();
        List<Long> studyIdList = new ArrayList<Long>();
        for (Study study : linkedStudys) {
            studyIdList.add(study.getId());
        }
        if (studyIdList != null && studyIdList.size() > 0) {
            String studyIds = generateTempTableString(studyIdList);
            linkedStudyClause = " or s.id in (" + studyIds + ") ";
        }
    }
    String queryStr = "select s.id " + "from Study s "
            + "left outer JOIN StudyFileActivity sfa on  s.id = sfa.study_id "
            + "where  s.id in  ( select s.id from Study s,  VDC v,  StudyVersion sv "
            + " where s.id = sv.study_id " + " and s.owner_id = v.id " + " and v.restricted = false "
            + " and sv.versionstate = '" + StudyVersion.VersionState.RELEASED + "'" + dataverseClause
            + networkClause + ")" + linkedStudyClause + " group by s.id " + " order by "
            + "(CASE WHEN sum(downloadcount) is null THEN -1 ELSE sum(downloadcount) END) desc";

    //System.out.print("Download count query " + queryStr);

    Query query = em.createNativeQuery(queryStr);
    List<Long> returnList = new ArrayList<Long>();
    if (numResults == -1) {
        for (Object currentResult : query.getResultList()) {
            // convert results into Longs
            returnList.add(new Long(((Integer) currentResult).longValue()));
        }
    } else {
        int i = 0;
        for (Object currentResult : query.getResultList()) {
            i++;
            if (i > numResults) {
                break;
            } else {
                returnList.add(new Long(((Integer) currentResult).longValue()));
            }
        }
    }
    return returnList;
}

From source file:com.egt.core.aplicacion.web.GestorPaginaActualizacion.java

protected boolean isConsultaValida() {
    if (designing) {
        return true;
    }//from w ww  . j av  a 2 s .  co m
    this.track("isConsultaValida");
    boolean ok = !this.isRestauracion()
            && this.getPaginaActualizacion().getRecursoDataProvider().isFuncionSelectAutorizada();
    if (ok) {
        long f1 = this.getPaginaActualizacion().getRecursoDataProvider().getFuncionSelect();
        long f2 = this.getPaginaActualizacion().getFuncionConsultarRecurso();
        this.trace("funcion-actual=" + f1 + ", funcion-anterior=" + f2);
        ok = f1 == f2;
    }
    if (ok) {
        long v1 = this.getPaginaActualizacion().getRecursoDataProvider().getVersionComandoSelect();
        long v2 = this.getPaginaActualizacion().getContextoSesion()
                .getVersionComandoSelectPagina(this.getClavePagina());
        this.trace("version-actual=" + v1 + ", version-anterior=" + v2);
        ok = v1 == v2;
    }
    if (ok && this.isReinicio()) {
        String c1 = StringUtils
                .trimToNull(this.getPaginaActualizacion().getRecursoDataProvider().getCriteriosBusqueda());
        String c2 = StringUtils
                .trimToNull(this.getPaginaActualizacion().getContextoPeticion().getCriteriosBusqueda());
        this.trace("criterio-actual=" + c1 + ", criterio-anterior=" + c2);
        ok = c1 == null ? c2 == null : c1.equals(c2);
    }
    //      if (ok && this.isPaginaConsultaConMaestro()) {
    //          Long i1 = this.getIdentificacionRecursoMaestro();
    //          Long i2 = this.getPaginaActualizacion().getContextoSesion().getIdentificacionRecursoMaestroPagina(this.getClavePagina());
    //          this.trace("maestro-actual=" + i1 + ", maestro-anterior=" + i2);
    //          ok = i1 == null ? i2 == null : i1.equals(i2);
    //      }
    if (ok) {
        //          String c1 = this.getColumnaIdentificacionRecursoMaestro();
        String c1 = this.getPaginaActualizacion().getRecursoDataProvider().getColumnaMaestro();
        String c2 = this.getPaginaActualizacion().getContextoSesion()
                .getColumnaIdentificacionRecursoMaestroPagina(this.getClavePagina());
        this.trace("maestro-actual=" + c1 + ", maestro-anterior=" + c2);
        ok = c1 == null ? c2 == null : c1.equals(c2);
    }
    if (ok) {
        //          Long i1 = this.getIdentificacionRecursoMaestro();
        Long i1 = this.getPaginaActualizacion().getRecursoDataProvider().getIdentificacionMaestro();
        Long i2 = this.getPaginaActualizacion().getContextoSesion()
                .getIdentificacionRecursoMaestroPagina(this.getClavePagina());
        this.trace("maestro-actual=" + i1 + ", maestro-anterior=" + i2);
        ok = i1 == null ? i2 == null : i1.equals(i2);
    }
    return ok;
}