List of usage examples for java.lang Integer compareTo
public int compareTo(Integer anotherInteger)
From source file:com.square.adherent.noyau.service.implementations.ContratServiceImpl.java
@Override public ContratPersonneMoraleDto getContratPersonneMorale(Long uidContrat) { final Contrat contrat = contratDao.getContratById(uidContrat); if (contrat == null) { throw new BusinessException(messageSourceUtil.get(MessageKeyUtil.ERROR_CONTRAT_INEXISTANT)); }/*from ww w.j av a 2 s . c om*/ final ContratPersonneMoraleDto contratDto = mapperDozerBean.map(contrat, ContratPersonneMoraleDto.class); final IdentifiantLibelleDto typeGestionDto = mapperDozerBean.map(contrat.getTypePayeur(), IdentifiantLibelleDto.class); contratDto.setTypeGestion(typeGestionDto); final List<String> listeProduitsGestion = contratDao .getListeProduitsGestionFromContrat(contrat.getIdentifiantExterieur()); if (listeProduitsGestion != null && listeProduitsGestion.size() > 0) { String produitGestion = listeProduitsGestion.get(0); if (listeProduitsGestion.size() > 1) { for (int i = 1; i < listeProduitsGestion.size(); i++) { produitGestion = produitGestion + ", " + listeProduitsGestion.get(i); } } contratDto.setProduitGestion(produitGestion); } contratDto.setNbAdherents(contratDao.getNombreAdherentsContrat(contrat.getIdentifiantExterieur())); contratDto.setNbBeneficiaires(contratDao.getNombreBeneficiairesContrat(contrat.getIdentifiantExterieur())); InfosPaiementPersonneMoraleDto infosPaiement = new InfosPaiementPersonneMoraleDto(); if (contrat.getBanqueCotisation() != null) { infosPaiement = mapperDozerBean.map(contrat.getBanqueCotisation(), InfosPaiementPersonneMoraleDto.class); } if (contrat.getTermePaiement() != null) { infosPaiement.setTypeEcheance(contrat.getTermePaiement().getLibelle()); } if (contrat.getFrequencePaiementCotisation() != null) { final IdentifiantLibelleDto frequencePaiementDto = mapperDozerBean .map(contrat.getFrequencePaiementCotisation(), IdentifiantLibelleDto.class); infosPaiement.setFrequencePaiement(frequencePaiementDto); } if (contrat.getMoyenPaiementCotisation() != null) { final IdentifiantLibelleDto moyenPaiementDto = mapperDozerBean.map(contrat.getMoyenPaiementCotisation(), IdentifiantLibelleDto.class); infosPaiement.setMoyenPaiement(moyenPaiementDto); } infosPaiement.setJourPaiement(contrat.getJourPaiementCotisation()); contratDto.setInfosPaiement(infosPaiement); // Construction du rcapitulatif des populations final RecapitulatifPopulationDto recapitulatifPopulation = contratDao .getRecapitulatifPopulationContrat(contrat.getIdentifiantExterieur()); // Tri en fonction des populations if (recapitulatifPopulation.getListeValeursPopulation() != null && recapitulatifPopulation.getListeValeursPopulation().size() > 1) { // Rcupration de l'ordre de la population for (ValeursStatutsPopulationDto valeurStatutPopulation : recapitulatifPopulation .getListeValeursPopulation()) { final Integer ordre = adherentMappingService .getOrdrePopulation(valeurStatutPopulation.getLibellePopulation()); valeurStatutPopulation.setOrdrePopulation(ordre); } // Tri final Comparator<ValeursStatutsPopulationDto> comparatorPopulation = new Comparator<ValeursStatutsPopulationDto>() { @Override public int compare(ValeursStatutsPopulationDto o1, ValeursStatutsPopulationDto o2) { if (o1 == null || o1.getOrdrePopulation() == null) { return 1; } else if (o2 == null || o2.getOrdrePopulation() == null) { return -1; } else { return o1.getOrdrePopulation().compareTo(o2.getOrdrePopulation()); } } }; Collections.sort(recapitulatifPopulation.getListeValeursPopulation(), comparatorPopulation); } contratDto.setRecapitulatifPopulation(recapitulatifPopulation); // Rcupration de la liste des garanties final List<Garantie> listeGaranties = garantieDao .getListeGarantiesContratPersonneMorale(contrat.getIdentifiantExterieur()); final List<GarantiePersonneMoraleDto> listeGarantiesDto = new ArrayList<GarantiePersonneMoraleDto>(); final List<String> listeProduitsDejaPresents = new ArrayList<String>(); if (listeGaranties != null && listeGaranties.size() > 0) { for (Garantie garantie : listeGaranties) { final ProduitCriteresDto critereProduit = new ProduitCriteresDto(); critereProduit.setProduitAia(garantie.getLibelleProduitGestion()); critereProduit.setGarantieAia(garantie.getLibelleGarantieGestion()); final List<ProduitDto> listeProduits = produitService.getListeProduits(critereProduit); if (listeProduits == null || listeProduits.size() != 1) { logger.error(messageSourceUtil.get(MessageKeyUtil.LOGGER_ERROR_RECUP_PRODUIT, new String[] { garantie.getLibelleProduitGestion(), garantie.getLibelleGarantieGestion() })); // On ne traite pas cette garantie car le produit n'a pas t trouv contratDto.getListeProduitsNonTrouves().add( messageSourceUtil.get(MessageKeyUtil.MESSAGE_LIBELLE_PRODUIT_NON_TROUVE, new String[] { garantie.getLibelleProduitGestion(), garantie.getLibelleGarantieGestion() })); continue; } final ProduitDto produit = listeProduits.get(0); if (!listeProduitsDejaPresents.contains(produit.getLibelleCommercial())) { listeProduitsDejaPresents.add(produit.getLibelleCommercial()); final GarantiePersonneMoraleDto garantieDto = new GarantiePersonneMoraleDto(); garantieDto.setId(garantie.getId()); garantieDto.setIdProduit(produit.getIdentifiant()); garantieDto.setLibelle(produit.getLibelleCommercial()); if (produit.getFormulePresta() != null) { garantieDto.setIdFormulePresta(produit.getFormulePresta().getIdentifiant()); garantieDto.setLibelleFormulePresta(produit.getFormulePresta().getLibelle()); } final IdentifiantLibelleDto statut = (IdentifiantLibelleDto) mapperDozerBean .map(garantie.getStatut(), IdentifiantLibelleDto.class); garantieDto.setStatut(statut); garantieDto.setIdNatureProduit(produit.getGamme().getIdCategorie()); garantieDto.setDateSignature(garantie.getDateSignature()); final List<InfosGarantiePersonneMoraleDto> listeInfosGarantie = new ArrayList<InfosGarantiePersonneMoraleDto>(); final InfosGarantiePersonneMoraleDto infosGarantie = mapperDozerBean.map(garantie, InfosGarantiePersonneMoraleDto.class); // On initialise le statut de la garantie au statut de la premire garantie trouve infosGarantie.setStatut(statut); listeInfosGarantie.add(infosGarantie); garantieDto.setListeInfosGarantie(listeInfosGarantie); listeGarantiesDto.add(garantieDto); } else { if (listeGarantiesDto != null && listeGarantiesDto.size() > 0) { for (GarantiePersonneMoraleDto garantieDto : listeGarantiesDto) { if (produit.getLibelleCommercial().equals(garantieDto.getLibelle())) { // Mis jour des champs pour le tri si ncessaire final Long idStatutGarantieExistant = garantieDto.getStatut().getIdentifiant(); final Long idNouveauStatutGarantie = garantie.getStatut().getId(); if (adherentMappingService.getNiveauImportanceStatutGarantie( idStatutGarantieExistant) < adherentMappingService .getNiveauImportanceStatutGarantie(idNouveauStatutGarantie)) { final IdentifiantLibelleDto statut = mapperDozerBean.map(garantie.getStatut(), IdentifiantLibelleDto.class); garantieDto.setStatut(statut); } if (produit.getGamme().getIdCategorie() < garantieDto.getIdNatureProduit()) { garantieDto.setIdNatureProduit(produit.getGamme().getIdCategorie()); } if (garantie.getDateSignature().before(garantieDto.getDateSignature())) { garantieDto.setDateSignature(garantie.getDateSignature()); } // Gestion des infos de garantie if (garantieDto.getListeInfosGarantie() != null && garantieDto.getListeInfosGarantie().size() > 0) { final InfosGarantiePersonneMoraleDto infosGarantie = mapperDozerBean .map(garantie, InfosGarantiePersonneMoraleDto.class); infosGarantie.setStatut((IdentifiantLibelleDto) mapperDozerBean .map(garantie.getStatut(), IdentifiantLibelleDto.class)); boolean isExiste = false; for (InfosGarantiePersonneMoraleDto infos : garantieDto .getListeInfosGarantie()) { // On ajoute si a n'est pas un "doublon" if (infosGarantie.getCodeTarif().equals(infos.getCodeTarif()) && infosGarantie.getLibelleGarantieGestion() .equals(infos.getLibelleGarantieGestion()) && infosGarantie.getLibellePopulation() .equals(infos.getLibellePopulation()) && (infosGarantie.getMontantSouscrit() == null && infos.getMontantSouscrit() == null || (infosGarantie.getMontantSouscrit() != null && infos.getMontantSouscrit() != null && infosGarantie.getMontantSouscrit() .equals(infos.getMontantSouscrit())))) { isExiste = true; // On met jour le statut d'une garantie si le nouveau statut est plus important que l'ancien final Long idStatutExistant = infos.getStatut().getIdentifiant(); final Long idNouveauStatut = infosGarantie.getStatut().getIdentifiant(); if (adherentMappingService.getNiveauImportanceStatutGarantie( idStatutExistant) < adherentMappingService .getNiveauImportanceStatutGarantie(idNouveauStatut)) { infos.setStatut(infosGarantie.getStatut()); } break; } } if (!isExiste) { garantieDto.getListeInfosGarantie().add(infosGarantie); } break; } } } } } } } if (listeGarantiesDto != null && listeGarantiesDto.size() > 1) { // Tri des infos de garantie dans chaque garantie final Comparator<InfosGarantiePersonneMoraleDto> comparatorListeInfosGarantie = new Comparator<InfosGarantiePersonneMoraleDto>() { @Override public int compare(InfosGarantiePersonneMoraleDto o1, InfosGarantiePersonneMoraleDto o2) { if (o1 == null) { return -1; } else if (o2 == null) { return 1; } else { final IdentifiantLibelleDto statut1 = o1.getStatut(); final IdentifiantLibelleDto statut2 = o2.getStatut(); if (statut1 == null || statut1.getIdentifiant() == null) { return -1; } else if (statut2 == null || statut2.getIdentifiant() == null) { return 1; } else { // On rcupre le niveau d'importance des statuts de chaque garantie final Integer niveauImportanceStatut1 = adherentMappingService .getNiveauImportanceStatutGarantie(statut1.getIdentifiant()); final Integer niveauImportanceStatut2 = adherentMappingService .getNiveauImportanceStatutGarantie(statut2.getIdentifiant()); int compareStatut = niveauImportanceStatut1.compareTo(niveauImportanceStatut2); // On inverse le rsultat de comparaison // Niveau d'importance du statut 1 > au niveau d'importance du statut 2 if (compareStatut == 1) { // La garantie 1 doit donc apparaitre avant la garantie 2 compareStatut = -1; } else if (compareStatut == -1) { // Niveau d'importance du statut 1 < au niveau d'importance du statut 2 // La garantie 2 doit donc apparaitre avant la garantie 1 compareStatut = 1; } if (compareStatut == 0) { final String libellePopulation1 = o1.getLibellePopulation(); final String libellePopulation2 = o2.getLibellePopulation(); if (StringUtils.isBlank(libellePopulation1)) { return -1; } else if (StringUtils.isBlank(libellePopulation2)) { return 1; } else { // On compare par rapport au libell population de la garantie final Integer ordreO1 = adherentMappingService .getOrdrePopulation(libellePopulation1); final Integer ordreO2 = adherentMappingService .getOrdrePopulation(o2.getLibellePopulation()); if (ordreO1 == null) { return -1; } else if (ordreO2 == null) { return 1; } else { return ordreO1.compareTo(ordreO2); } } } else { return compareStatut; } } } } }; for (GarantiePersonneMoraleDto garantie : listeGarantiesDto) { Collections.sort(garantie.getListeInfosGarantie(), comparatorListeInfosGarantie); } // Tri des garanties final Comparator<GarantiePersonneMoraleDto> comparator = new Comparator<GarantiePersonneMoraleDto>() { @Override public int compare(GarantiePersonneMoraleDto o1, GarantiePersonneMoraleDto o2) { if (o1 == null) { return 1; } else if (o2 == null) { return -1; } else { if (o1.getStatut() == null && o2.getStatut() != null) { return 1; } else if (o1.getStatut() != null && o2.getStatut() == null) { return -1; } else { if ((o1.getStatut() == null && o2.getStatut() == null) || (o1.getStatut().getIdentifiant() == null && o2.getStatut().getIdentifiant() == null) || (o1.getStatut().getIdentifiant().equals(o2.getStatut().getIdentifiant()))) { if (o1.getIdNatureProduit() == null && o2.getIdNatureProduit() != null) { return 1; } else if (o1.getIdNatureProduit() != null && o2.getIdNatureProduit() == null) { return -1; } else if ((o1.getIdNatureProduit() == null && o2.getIdNatureProduit() == null) || (o1.getIdNatureProduit().equals(o2.getIdNatureProduit()))) { if (o1.getDateSignature() == null) { return 1; } else if (o2.getDateSignature() == null) { return -1; } else { return o2.getDateSignature().compareTo(o1.getDateSignature()); } } else { return o1.getIdNatureProduit().compareTo(o2.getIdNatureProduit()); } } else if (o1.getStatut().getIdentifiant() == null) { return 1; } else if (o2.getStatut().getIdentifiant() == null) { return -1; } else { final Integer niveauImportanceStatut1 = adherentMappingService .getNiveauImportanceStatutGarantie(o1.getStatut().getIdentifiant()); final Integer niveauImportanceStatut2 = adherentMappingService .getNiveauImportanceStatutGarantie(o2.getStatut().getIdentifiant()); return niveauImportanceStatut2.compareTo(niveauImportanceStatut1); } } } } }; Collections.sort(listeGarantiesDto, comparator); } contratDto.setListeGaranties(listeGarantiesDto); return contratDto; }
From source file:org.intermine.bio.dataconversion.XenmineConverter.java
/** * /*ww w.java 2 s . c o m*/ * @param start * @param end * @return * @throws NumberFormatException */ private String getLength(String start, String end) throws NumberFormatException { Integer a = new Integer(start); Integer b = new Integer(end); if (a.compareTo(b) > 0) { a = new Integer(end); b = new Integer(start); } Integer length = new Integer(b.intValue() - a.intValue()); return length.toString(); }
From source file:com.doculibre.constellio.wicket.panels.search.SearchFormPanel.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public SearchFormPanel(String id, final IModel simpleSearchModel) { super(id);// w ww . j a va 2 s . co m searchForm = new WebMarkupContainer("searchForm", new CompoundPropertyModel(simpleSearchModel)); simpleSearchFormDiv = new WebMarkupContainer("simpleSearchFormDiv") { @Override public boolean isVisible() { SimpleSearch search = (SimpleSearch) simpleSearchModel.getObject(); return search.getAdvancedSearchRule() == null; } }; advancedSearchFormDiv = new WebMarkupContainer("advancedSearchFormDiv") { @Override public boolean isVisible() { SimpleSearch search = (SimpleSearch) simpleSearchModel.getObject(); return search.getAdvancedSearchRule() != null; } }; advancedSearchPanel = new AdvancedSearchPanel("advanceForm", simpleSearchModel); searchForm.add(new AttributeModifier("action", new LoadableDetachableModel() { @Override protected Object load() { PageFactoryPlugin pageFactoryPlugin = PluginFactory.getPlugin(PageFactoryPlugin.class); return urlFor(pageFactoryPlugin.getSearchResultsPage(), new PageParameters()); } })); hiddenFields = new ListView("hiddenFields", new LoadableDetachableModel() { @Override protected Object load() { List<SimpleParam> hiddenParams = new ArrayList<SimpleParam>(); HiddenSearchFormParamsPlugin hiddenSearchFormParamsPlugin = PluginFactory .getPlugin(HiddenSearchFormParamsPlugin.class); if (hiddenSearchFormParamsPlugin != null) { WebRequestCycle webRequestCycle = (WebRequestCycle) RequestCycle.get(); HttpServletRequest request = webRequestCycle.getWebRequest().getHttpServletRequest(); SimpleParams hiddenSimpleParams = hiddenSearchFormParamsPlugin.getHiddenParams(request); for (String paramName : hiddenSimpleParams.keySet()) { for (String paramValue : hiddenSimpleParams.getList(paramName)) { hiddenParams.add(new SimpleParam(paramName, paramValue)); } } } SimpleSearch simpleSearch = (SimpleSearch) simpleSearchModel.getObject(); SimpleSearch clone = simpleSearch.clone(); SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils .getSearchInterfaceConfigServices(); SearchInterfaceConfig config = searchInterfaceConfigServices.get(); if (!config.isKeepFacetsNewSearch()) { // Will be true if we just clicked on a delete link // on the CurrentSearchPanel if (!clone.isRefinedSearch()) { clone.getSearchedFacets().clear(); clone.setCloudKeyword(null); } // We must click on a delete link on // CurrentSearchPanel so that it is considered // again as refined clone.setRefinedSearch(false); } clone.initFacetPages(); List<String> ignoredParamNames = Arrays.asList("query", "searchType", "page", "singleSearchLocale"); SimpleParams searchParams = clone.toSimpleParams(); for (String paramName : searchParams.keySet()) { if (!ignoredParamNames.contains(paramName) && !paramName.contains(SearchRule.ROOT_PREFIX)) { List<String> paramValues = searchParams.getList(paramName); for (String paramValue : paramValues) { SimpleParam hiddenParam = new SimpleParam(paramName, paramValue); hiddenParams.add(hiddenParam); } } } return hiddenParams; } }) { @Override protected void populateItem(ListItem item) { SimpleParam hiddenParam = (SimpleParam) item.getModelObject(); if (hiddenParam.value != null) { item.add(new SimpleAttributeModifier("name", hiddenParam.name)); item.add(new SimpleAttributeModifier("value", hiddenParam.value)); } else { item.setVisible(false); } } }; SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils .getSearchInterfaceConfigServices(); SearchInterfaceConfig config = searchInterfaceConfigServices.get(); if (config.isSimpleSearchAutocompletion() && ((SimpleSearch) simpleSearchModel.getObject()).getAdvancedSearchRule() == null) { AutoCompleteSettings settings = new AutoCompleteSettings(); settings.setCssClassName("simpleSearchAutoCompleteChoices"); IModel model = new Model(((SimpleSearch) simpleSearchModel.getObject()).getQuery()); WordsAndValueAutoCompleteRenderer render = new WordsAndValueAutoCompleteRenderer() { @Override protected String getTextValue(String word, Object value) { return word; } }; queryField = new TextAndValueAutoCompleteTextField("query", model, String.class, settings, render) { @Override public String getInputName() { return super.getId(); } @Override protected Iterator getChoicesForWord(String word) { SimpleSearch simpleSearch = (SimpleSearch) simpleSearchModel.getObject(); String collectionName = simpleSearch.getCollectionName(); AutocompleteServices autocompleteServices = ConstellioSpringUtils.getAutocompleteServices(); RecordCollectionServices collectionServices = ConstellioSpringUtils .getRecordCollectionServices(); RecordCollection collection = collectionServices.get(collectionName); List<String> suggestions = autocompleteServices.suggestSimpleSearch(word, collection, getLocale()); return suggestions.iterator(); } @Override protected boolean supportMultipleWords() { return false; } }; } else { queryField = new TextField("query") { @Override public String getInputName() { return super.getId(); } }; } searchTypeField = new RadioGroup("searchType") { @Override public String getInputName() { return super.getId(); } }; IModel languages = new LoadableDetachableModel() { protected Object load() { Set<String> localeCodes = new HashSet<String>(); SimpleSearch simpleSearch = (SimpleSearch) simpleSearchModel.getObject(); RecordCollectionServices recordCollectionServices = ConstellioSpringUtils .getRecordCollectionServices(); RecordCollection collection = recordCollectionServices.get(simpleSearch.getCollectionName()); List<Locale> searchableLocales = ConstellioSpringUtils.getSearchableLocales(); if (!collection.isOpenSearch()) { localeCodes.add(""); if (!searchableLocales.isEmpty()) { for (Locale searchableLocale : searchableLocales) { localeCodes.add(searchableLocale.getLanguage()); } } else { IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices(); IndexField languageField = indexFieldServices.get(IndexField.LANGUAGE_FIELD, collection); for (String localeCode : indexFieldServices.suggestValues(languageField)) { localeCodes.add(localeCode); } } } else { localeCodes.add(""); if (!searchableLocales.isEmpty()) { for (Locale searchableLocale : searchableLocales) { localeCodes.add(searchableLocale.getLanguage()); } } else { for (Locale availableLocale : Locale.getAvailableLocales()) { localeCodes.add(availableLocale.getLanguage()); } } } List<Locale> locales = new ArrayList<Locale>(); for (String localeCode : localeCodes) { locales.add(new Locale(localeCode)); } Collections.sort(locales, new Comparator<Locale>() { @Override public int compare(Locale locale1, Locale locale2) { Locale locale1Display; Locale locale2Display; SearchInterfaceConfig config = ConstellioSpringUtils.getSearchInterfaceConfigServices() .get(); if (config.isTranslateLanguageNames()) { locale1Display = locale2Display = getLocale(); } else { locale1Display = locale1; locale2Display = locale2; } List<Locale> searchableLocales = ConstellioSpringUtils.getSearchableLocales(); if (searchableLocales.isEmpty()) { searchableLocales = ConstellioSpringUtils.getSupportedLocales(); } Integer indexOfLocale1; Integer indexOfLocale2; if (locale1.getLanguage().equals(getLocale().getLanguage())) { indexOfLocale1 = Integer.MIN_VALUE; } else { indexOfLocale1 = searchableLocales.indexOf(locale1); } if (locale2.getLanguage().equals(getLocale().getLanguage())) { indexOfLocale2 = Integer.MIN_VALUE; } else { indexOfLocale2 = searchableLocales.indexOf(locale2); } if (indexOfLocale1 == -1) { indexOfLocale1 = Integer.MAX_VALUE; } if (indexOfLocale2 == -1) { indexOfLocale2 = Integer.MAX_VALUE; } if (!indexOfLocale1.equals(Integer.MAX_VALUE) || !indexOfLocale2.equals(Integer.MAX_VALUE)) { return indexOfLocale1.compareTo(indexOfLocale2); } else if (StringUtils.isBlank(locale1.getLanguage())) { return Integer.MIN_VALUE; } else { return locale1.getDisplayLanguage(locale1Display) .compareTo(locale2.getDisplayLanguage(locale2Display)); } } }); return locales; } }; IChoiceRenderer languageRenderer = new ChoiceRenderer() { @Override public Object getDisplayValue(Object object) { Locale locale = (Locale) object; String text; if (locale.getLanguage().isEmpty()) { text = (String) new StringResourceModel("all", SearchFormPanel.this, null).getObject(); } else { Locale localeDisplay; SearchInterfaceConfig config = ConstellioSpringUtils.getSearchInterfaceConfigServices().get(); if (config.isTranslateLanguageNames()) { localeDisplay = getLocale(); } else { localeDisplay = locale; } text = StringUtils.capitalize(locale.getDisplayLanguage(localeDisplay)); } return text; } @Override public String getIdValue(Object object, int index) { return ((Locale) object).getLanguage(); } }; IModel languageModel = new Model() { @Override public Object getObject() { SimpleSearch simpleSearch = (SimpleSearch) simpleSearchModel.getObject(); Locale singleSearchLocale = simpleSearch.getSingleSearchLocale(); if (singleSearchLocale == null) { SearchedFacet facet = simpleSearch.getSearchedFacet(IndexField.LANGUAGE_FIELD); List<String> values = facet == null ? new ArrayList<String>() : facet.getIncludedValues(); singleSearchLocale = values.isEmpty() ? null : new Locale(values.get(0)); } if (singleSearchLocale == null) { singleSearchLocale = getLocale(); } return singleSearchLocale; } @Override public void setObject(Object object) { Locale singleSearchLocale = (Locale) object; SimpleSearch simpleSearch = (SimpleSearch) simpleSearchModel.getObject(); simpleSearch.setSingleSearchLocale(singleSearchLocale); } }; languageDropDown = new DropDownChoice("singleSearchLocale", languageModel, languages, languageRenderer) { @Override public String getInputName() { return "singleSearchLocale"; } @Override public boolean isVisible() { SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils .getSearchInterfaceConfigServices(); SearchInterfaceConfig config = searchInterfaceConfigServices.get(); return config.isLanguageInSearchForm(); } @Override protected CharSequence getDefaultChoice(Object selected) { return ""; }; }; searchButton = new Button("searchButton") { @Override public String getMarkupId() { return super.getId(); } @Override public String getInputName() { return super.getId(); } }; String submitImgUrl = "" + urlFor(new ResourceReference(BaseConstellioPage.class, "images/ico_loupe.png")); add(searchForm); searchForm.add(simpleSearchFormDiv); searchForm.add(advancedSearchFormDiv); searchForm.add(hiddenFields); queryField.add(new SetFocusBehavior(queryField)); addChoice(SimpleSearch.ALL_WORDS); addChoice(SimpleSearch.AT_LEAST_ONE_WORD); addChoice(SimpleSearch.EXACT_EXPRESSION); simpleSearchFormDiv.add(queryField); simpleSearchFormDiv.add(searchTypeField); simpleSearchFormDiv.add(languageDropDown); simpleSearchFormDiv.add(searchButton); advancedSearchFormDiv.add(advancedSearchPanel); searchButton.add(new SimpleAttributeModifier("src", submitImgUrl)); }
From source file:org.mifosplatform.portfolio.loanproduct.serialization.LoanProductDataValidator.java
public void validateForCreate(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }//from ww w . j a v a 2 s .c om final Type typeOfMap = new TypeToken<Map<String, Object>>() { }.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("loanproduct"); final JsonElement element = this.fromApiJsonHelper.parse(json); final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); final String description = this.fromApiJsonHelper.extractStringNamed("description", element); baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500); if (this.fromApiJsonHelper.parameterExists("fundId", element)) { final Long fundId = this.fromApiJsonHelper.extractLongNamed("fundId", element); baseDataValidator.reset().parameter("fundId").value(fundId).ignoreIfNull().integerGreaterThanZero(); } final Boolean includeInBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed("includeInBorrowerCycle", element); baseDataValidator.reset().parameter("includeInBorrowerCycle").value(includeInBorrowerCycle).ignoreIfNull() .validateForBooleanValue(); // terms final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element); baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3); final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, Locale.getDefault()); baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull() .inMinMaxRange(0, 6); final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element, Locale.getDefault()); baseDataValidator.reset().parameter("inMultiplesOf").value(inMultiplesOf).ignoreIfNull() .integerZeroOrGreater(); final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); baseDataValidator.reset().parameter("principal").value(principal).notNull().positiveAmount(); final String minPrincipalParameterName = "minPrincipal"; BigDecimal minPrincipalAmount = null; if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) { minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element); baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount).ignoreIfNull() .positiveAmount(); } final String maxPrincipalParameterName = "maxPrincipal"; BigDecimal maxPrincipalAmount = null; if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) { maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element); baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).ignoreIfNull() .positiveAmount(); } if (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) != -1) { if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) != -1) { baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount) .notLessThanMin(minPrincipalAmount); if (minPrincipalAmount.compareTo(maxPrincipalAmount) <= 0) { baseDataValidator.reset().parameter("principal").value(principal) .inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount); } } else { baseDataValidator.reset().parameter("principal").value(principal) .notGreaterThanMax(maxPrincipalAmount); } } else if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) != -1) { baseDataValidator.reset().parameter("principal").value(principal).notLessThanMin(minPrincipalAmount); } final Integer numberOfRepayments = this.fromApiJsonHelper .extractIntegerWithLocaleNamed("numberOfRepayments", element); baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notNull() .integerGreaterThanZero(); final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments"; Integer minNumberOfRepayments = null; if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) { minNumberOfRepayments = this.fromApiJsonHelper .extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element); baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments) .ignoreIfNull().integerGreaterThanZero(); } final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments"; Integer maxNumberOfRepayments = null; if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) { maxNumberOfRepayments = this.fromApiJsonHelper .extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element); baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments) .ignoreIfNull().integerGreaterThanZero(); } if (maxNumberOfRepayments != null && maxNumberOfRepayments.compareTo(0) == 1) { if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) { baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments) .notLessThanMin(minNumberOfRepayments); if (minNumberOfRepayments.compareTo(maxNumberOfRepayments) <= 0) { baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments) .inMinMaxRange(minNumberOfRepayments, maxNumberOfRepayments); } } else { baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments) .notGreaterThanMax(maxNumberOfRepayments); } } else if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) { baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments) .notLessThanMin(minNumberOfRepayments); } final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element); baseDataValidator.reset().parameter("repaymentEvery").value(repaymentEvery).notNull() .integerGreaterThanZero(); final Integer repaymentFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("repaymentFrequencyType", element, Locale.getDefault()); baseDataValidator.reset().parameter("repaymentFrequencyType").value(repaymentFrequencyType).notNull() .inMinMaxRange(0, 3); final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper .extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element); baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod).notNull() .zeroOrPositiveAmount(); final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod"; BigDecimal minInterestRatePerPeriod = null; if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) { minInterestRatePerPeriod = this.fromApiJsonHelper .extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, element); baseDataValidator.reset().parameter(minInterestRatePerPeriodParameterName) .value(minInterestRatePerPeriod).ignoreIfNull().zeroOrPositiveAmount(); } final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod"; BigDecimal maxInterestRatePerPeriod = null; if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) { maxInterestRatePerPeriod = this.fromApiJsonHelper .extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, element); baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName) .value(maxInterestRatePerPeriod).ignoreIfNull().zeroOrPositiveAmount(); } if (maxInterestRatePerPeriod != null && maxInterestRatePerPeriod.compareTo(BigDecimal.ZERO) != -1) { if (minInterestRatePerPeriod != null && minInterestRatePerPeriod.compareTo(BigDecimal.ZERO) != -1) { baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName) .value(maxInterestRatePerPeriod).notLessThanMin(minInterestRatePerPeriod); if (minInterestRatePerPeriod.compareTo(maxInterestRatePerPeriod) <= 0) { baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod) .inMinAndMaxAmountRange(minInterestRatePerPeriod, maxInterestRatePerPeriod); } } else { baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod) .notGreaterThanMax(maxInterestRatePerPeriod); } } else if (minInterestRatePerPeriod != null && minInterestRatePerPeriod.compareTo(BigDecimal.ZERO) != -1) { baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod) .notLessThanMin(minInterestRatePerPeriod); } final Integer interestRateFrequencyType = this.fromApiJsonHelper .extractIntegerNamed("interestRateFrequencyType", element, Locale.getDefault()); baseDataValidator.reset().parameter("interestRateFrequencyType").value(interestRateFrequencyType).notNull() .inMinMaxRange(0, 3); // settings final Integer amortizationType = this.fromApiJsonHelper.extractIntegerNamed("amortizationType", element, Locale.getDefault()); baseDataValidator.reset().parameter("amortizationType").value(amortizationType).notNull().inMinMaxRange(0, 1); final Integer interestType = this.fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); baseDataValidator.reset().parameter("interestType").value(interestType).notNull().inMinMaxRange(0, 1); final Integer interestCalculationPeriodType = this.fromApiJsonHelper .extractIntegerNamed("interestCalculationPeriodType", element, Locale.getDefault()); baseDataValidator.reset().parameter("interestCalculationPeriodType").value(interestCalculationPeriodType) .notNull().inMinMaxRange(0, 1); final BigDecimal inArrearsTolerance = this.fromApiJsonHelper .extractBigDecimalWithLocaleNamed("inArrearsTolerance", element); baseDataValidator.reset().parameter("inArrearsTolerance").value(inArrearsTolerance).ignoreIfNull() .zeroOrPositiveAmount(); final Long transactionProcessingStrategyId = this.fromApiJsonHelper .extractLongNamed("transactionProcessingStrategyId", element); baseDataValidator.reset().parameter("transactionProcessingStrategyId") .value(transactionProcessingStrategyId).notNull().integerGreaterThanZero(); // grace validation final Integer graceOnPrincipalPayment = this.fromApiJsonHelper .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment) .zeroOrPositiveAmount(); final Integer graceOnInterestPayment = this.fromApiJsonHelper .extractIntegerWithLocaleNamed("graceOnInterestPayment", element); baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment) .zeroOrPositiveAmount(); final Integer graceOnInterestCharged = this.fromApiJsonHelper .extractIntegerWithLocaleNamed("graceOnInterestCharged", element); baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged) .zeroOrPositiveAmount(); // accounting related data validation final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault()); baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).notNull().inMinMaxRange(1, 3); if (isCashBasedAccounting(accountingRuleType) || isAccrualBasedAccounting(accountingRuleType)) { final Long fundAccountId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()) .value(fundAccountId).notNull().integerGreaterThanZero(); final Long loanPortfolioAccountId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue()) .value(loanPortfolioAccountId).notNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero(); final Long incomeFromInterestId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue()) .value(incomeFromInterestId).notNull().integerGreaterThanZero(); final Long incomeFromFeeId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()) .value(incomeFromFeeId).notNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()) .value(incomeFromPenaltyId).notNull().integerGreaterThanZero(); final Long writeOffAccountId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue()) .value(writeOffAccountId).notNull().integerGreaterThanZero(); final Long overpaymentAccountId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue()) .value(overpaymentAccountId).notNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(baseDataValidator, element); validateChargeToIncomeAccountMappings(baseDataValidator, element); } if (isAccrualBasedAccounting(accountingRuleType)) { final Long receivableInterestAccountId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue()) .value(receivableInterestAccountId).notNull().integerGreaterThanZero(); final Long receivableFeeAccountId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue()) .value(receivableFeeAccountId).notNull().integerGreaterThanZero(); final Long receivablePenaltyAccountId = this.fromApiJsonHelper .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue()) .value(receivablePenaltyAccountId).notNull().integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.useBorrowerCycleParameterName, element)) { final Boolean useBorrowerCycle = this.fromApiJsonHelper .extractBooleanNamed(LoanProductConstants.useBorrowerCycleParameterName, element); baseDataValidator.reset().parameter(LoanProductConstants.useBorrowerCycleParameterName) .value(useBorrowerCycle).ignoreIfNull().validateForBooleanValue(); } validateBorrowerCycleVariations(element, baseDataValidator); throwExceptionIfValidationWarningsExist(dataValidationErrors); }
From source file:eu.itesla_project.online.db.OnlineDbMVStore.java
@Override public List<Integer> listStoredStates(String workflowId) { LOGGER.info("Getting list of stored states for workflow {}", workflowId); List<Integer> storedStates = new ArrayList<Integer>(); if (workflowStatesFolderExists(workflowId)) { Path workflowStatesFolder = getWorkflowStatesFolder(workflowId); File[] files = workflowStatesFolder.toFile().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().startsWith(STORED_STATE_PREFIX); }/*from ww w.j a v a 2s . c om*/ }); for (File file : files) { if (file.isDirectory()) { String stateId = file.getName().substring(STORED_STATE_PREFIX.length()); storedStates.add(Integer.parseInt(stateId)); } } Collections.sort(storedStates, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); LOGGER.info("Found {} state(s) for workflow {}", storedStates.size(), workflowId); } else { LOGGER.info("Found no state(s) for workflow {}", workflowId); } return storedStates; }
From source file:org.fhaes.neofhchart.svg.FireChartSVG.java
/** * Sort the series by end year./* ww w . j a v a2 s . c om*/ */ public void sortByPositionInFile() { Comparator<FHSeriesSVG> comparator = new Comparator<FHSeriesSVG>() { @Override public int compare(FHSeriesSVG c1, FHSeriesSVG c2) { Integer c1pos = c1.getSequenceInFile(); Integer c2pos = c2.getSequenceInFile(); return c1pos.compareTo(c2pos); } }; Collections.sort(seriesSVGList, comparator); lastTypeSortedBy = SeriesSortType.AS_IN_FILE; rebuildChronologyPlot(); log.debug("Finished sorting chart series by position in file"); }
From source file:edu.ku.brc.specify.tasks.QueryTask.java
/** * @param parent/* w w w .j ava2s .c o m*/ * @param parentTT * * Recursively constructs tableTree defined by "querybuilder.xml" schema. */ protected void processForTables(final Element parent, final TableTree parentTT) { String tableName = XMLHelper.getAttr(parent, "name", null); DBTableInfo tableInfo = DBTableIdMgr.getInstance().getByShortClassName(tableName); if (!tableInfo.isHidden() && (!AppContextMgr.isSecurityOn() || tableInfo.getPermissions().canView())) { String fieldName = XMLHelper.getAttr(parent, "field", null); if (StringUtils.isEmpty(fieldName)) { fieldName = tableName.substring(0, 1).toLowerCase() + tableName.substring(1); } String abbrev = XMLHelper.getAttr(parent, "abbrev", null); TableTree newTreeNode = parentTT.addKid(new TableTree(tableName, fieldName, abbrev, tableInfo)); if (Treeable.class.isAssignableFrom(tableInfo.getClassObj())) { try { TreeDefIface<?, ?, ?> treeDef = getTreeDefForTreeLevelQRI(fieldName, parentTT, tableInfo); SortedSet<TreeDefItemIface<?, ?, ?>> defItems = new TreeSet<TreeDefItemIface<?, ?, ?>>( new Comparator<TreeDefItemIface<?, ?, ?>>() { public int compare(TreeDefItemIface<?, ?, ?> o1, TreeDefItemIface<?, ?, ?> o2) { Integer r1 = o1.getRankId(); Integer r2 = o2.getRankId(); return r1.compareTo(r2); } }); defItems.addAll(treeDef.getTreeDefItems()); for (TreeDefItemIface<?, ?, ?> defItem : defItems) { if (defItem.getRankId() > 0) { //skip root, just because. try { //newTreeNode.getTableQRI().addField( // new TreeLevelQRI(newTreeNode.getTableQRI(), null, defItem // .getRankId())); newTreeNode.getTableQRI().addField(new TreeLevelQRI(newTreeNode.getTableQRI(), null, defItem.getRankId(), "name", treeDef)); if (defItem instanceof TaxonTreeDefItem) { DBFieldInfo fi = DBTableIdMgr.getInstance().getInfoById(Taxon.getClassTableId()) .getFieldByName("author"); if (fi != null && !fi.isHidden()) { newTreeNode.getTableQRI() .addField(new TreeLevelQRI(newTreeNode.getTableQRI(), null, defItem.getRankId(), "author", treeDef)); } fi = DBTableIdMgr.getInstance().getInfoById(Taxon.getClassTableId()) .getFieldByName("groupNumber"); if (fi != null && !fi.isHidden()) { newTreeNode.getTableQRI() .addField(new TreeLevelQRI(newTreeNode.getTableQRI(), null, defItem.getRankId(), "groupNumber", treeDef)); } } } catch (Exception ex) { // if there is no TreeDefItem for the rank then just skip it. if (ex instanceof TreeLevelQRI.NoTreeDefItemException) { log.error(ex); } // else something is really messed up else { UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryTask.class, ex); ex.printStackTrace(); } } } } } catch (Exception ex) { UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryTask.class, ex); ex.printStackTrace(); } } for (Object kidObj : parent.selectNodes("table")) { Element kidElement = (Element) kidObj; processForTables(kidElement, newTreeNode); } for (Object obj : parent.selectNodes("alias")) { Element kidElement = (Element) obj; String kidClassName = XMLHelper.getAttr(kidElement, "name", null); tableInfo = DBTableIdMgr.getInstance().getByShortClassName(kidClassName); if (!tableInfo.isHidden() && (!AppContextMgr.isSecurityOn() || tableInfo.getPermissions().canView())) { tableName = XMLHelper.getAttr(kidElement, "name", null); fieldName = XMLHelper.getAttr(kidElement, "field", null); if (StringUtils.isEmpty(fieldName)) { fieldName = tableName.substring(0, 1).toLowerCase() + tableName.substring(1); } newTreeNode.addKid(new TableTree(kidClassName, fieldName, true)); } } } }
From source file:com.haulmont.cuba.core.app.scheduling.Scheduling.java
protected void processTask(ScheduledTask task) { if (isRunning(task)) { log.trace("{} is running", task); return;/* ww w . j a v a 2 s. c o m*/ } try { long now = timeSource.currentTimeMillis(); String me = serverInfo.getServerId(); Integer serverPriority = getServerPriority(task, me); if (!checkFirst(task, serverPriority, now)) return; long period = task.getPeriod() != null ? task.getPeriod() * 1000 : 0; long frame = task.getTimeFrame() != null ? task.getTimeFrame() * 1000 : period / 2; if (frame == 0) {//for cron tasks, where period is null we set default frame as scheduling interval frame = getSchedulingInterval(); } if (BooleanUtils.isTrue(task.getSingleton())) { if (task.getStartDate() != null || SchedulingType.CRON == task.getSchedulingType()) { long currentStart; if (SchedulingType.FIXED_DELAY == task.getSchedulingType()) { currentStart = calculateNextDelayDate(task, task.getLastStart(), coordinator.getLastFinished(task), now, frame, period); } else if (SchedulingType.CRON == task.getSchedulingType()) { currentStart = calculateNextCronDate(task, task.getLastStart(), now, frame); } else { currentStart = calculateNextPeriodDate(task, task.getLastStart(), now, frame, period); } if (needToStartInTimeFrame(now, frame, task.getLastStart(), currentStart)) { runSingletonTask(task, now, me); } else { log.trace("{}\n not in time frame to start", task); } } else { Integer lastServerPriority = task.getLastStartServer() == null ? null : getServerPriority(task, task.getLastStartServer()); // We should switch to me if the last server wasn't me and I have higher priority boolean shouldSwitch = lastServerWasNotMe(task, me) && (lastServerPriority == null || serverPriority.compareTo(lastServerPriority) < 0); // The last server wasn't me and it has higher priority boolean giveChanceToPreviousHost = lastServerWasNotMe(task, me) && (lastServerPriority != null && serverPriority.compareTo(lastServerPriority) > 0); log.trace("{}\n now={} lastStart={} lastServer={} shouldSwitch={} giveChanceToPreviousHost={}", task, now, task.getLastStart(), task.getLastStartServer(), shouldSwitch, giveChanceToPreviousHost); if (task.getLastStart() == 0 || shouldSwitch) { runSingletonTask(task, now, me); } else { long delay = giveChanceToPreviousHost ? period + period / 2 : period; if (SchedulingType.FIXED_DELAY == task.getSchedulingType()) { long lastFinish = coordinator.getLastFinished(task); if ((task.getLastStart() < lastFinish || !lastFinishCache.containsKey(task)) && lastFinish + delay < now) { runSingletonTask(task, now, me); } else { log.trace("{}\n time has not come and we shouldn't switch", task); } } else if (task.getLastStart() + delay <= now) { runSingletonTask(task, now, me); } else { log.trace("{}\n time has not come and we shouldn't switch", task); } } } } else { Long lastStart = lastStartCache.getOrDefault(task, 0L); Long lastFinish = lastFinishCache.getOrDefault(task, 0L); if (task.getStartDate() != null || SchedulingType.CRON == task.getSchedulingType()) { long currentStart; if (SchedulingType.FIXED_DELAY == task.getSchedulingType()) { currentStart = calculateNextDelayDate(task, lastStart, lastFinish, now, frame, period); } else if (SchedulingType.CRON == task.getSchedulingType()) { currentStart = calculateNextCronDate(task, lastStart, now, frame); } else { currentStart = calculateNextPeriodDate(task, lastStart, now, frame, period); } if (needToStartInTimeFrame(now, frame, lastStart, currentStart)) { runTask(task, now); } else { log.trace("{}\n not in time frame to start", task); } } else { log.trace("{}\n now={} lastStart={} lastFinish={}", task, now, lastStart, lastFinish); if (SchedulingType.FIXED_DELAY == task.getSchedulingType()) { if ((lastStart == 0 || lastStart < lastFinish) && now >= lastFinish + period) { runTask(task, now); } else { log.trace("{}\n time has not come", task); } } else if (now >= lastStart + period) { runTask(task, now); } else { log.trace("{}\n time has not come", task); } } } } catch (Throwable throwable) { log.error("Unable to process " + task, throwable); } }
From source file:raptor.connector.ics.IcsConnector.java
/** * Stores off the tab states that matter to this connector so they can be * restored when reconnected./* w ww . jav a2 s . com*/ */ public void storeTabStates() { if (!Raptor.getInstance().getWindow().getShell().isDisposed()) { String preference = ""; RaptorConnectorWindowItem[] items = Raptor.getInstance().getWindow().getWindowItems(this); // Sort to order channels. Arrays.sort(items, new Comparator<RaptorConnectorWindowItem>() { public int compare(RaptorConnectorWindowItem arg0, RaptorConnectorWindowItem arg1) { if (arg0 instanceof ChatConsoleWindowItem && arg1 instanceof ChatConsoleWindowItem) { ChatConsoleWindowItem chatConsole1 = (ChatConsoleWindowItem) arg0; ChatConsoleWindowItem chatConsole2 = (ChatConsoleWindowItem) arg1; if (chatConsole1.getController() instanceof ChannelController && chatConsole2.getController() instanceof ChannelController) { Integer integer1 = new Integer( ((ChannelController) chatConsole1.getController()).getChannel()); Integer integer2 = new Integer( ((ChannelController) chatConsole2.getController()).getChannel()); return integer1.compareTo(integer2); } else if (!(chatConsole1.getController() instanceof ChannelController) && chatConsole2.getController() instanceof ChannelController) { return 1; } else if (chatConsole1.getController() instanceof ChannelController && !(chatConsole2.getController() instanceof ChannelController)) { return -1; } else { return 0; } } else if (arg0 instanceof ChatConsoleWindowItem && !(arg1 instanceof ChatConsoleWindowItem)) { return -1; } else if (arg1 instanceof ChatConsoleWindowItem && !(arg0 instanceof ChatConsoleWindowItem)) { return 1; } else { return 0; } } }); for (RaptorConnectorWindowItem item : items) { if (item instanceof ChatConsoleWindowItem) { ChatConsoleWindowItem chatConsoleItem = (ChatConsoleWindowItem) item; if (chatConsoleItem.getController() instanceof ChannelController) { ChannelController controller = (ChannelController) chatConsoleItem.getController(); preference += (StringUtils.isBlank(preference) ? "" : "`") + "Channel`" + controller.getChannel() + "`" + Raptor.getInstance().getWindow().getQuadrant(item).toString(); } else if (chatConsoleItem.getController() instanceof RegExController) { RegExController controller = (RegExController) chatConsoleItem.getController(); preference += (StringUtils.isBlank(preference) ? "" : "`") + "RegEx`" + controller.getPattern() + "`" + Raptor.getInstance().getWindow().getQuadrant(item).toString(); } } else if (item instanceof SeekTableWindowItem) { preference += (StringUtils.isBlank(preference) ? "" : "`") + "SeekTableWindowItem` " + "` "; } else if (item instanceof BugWhoWindowItem) { preference += (StringUtils.isBlank(preference) ? "" : "`") + "BugWhoWindowItem` " + "` "; } else if (item instanceof BugButtonsWindowItem) { preference += (StringUtils.isBlank(preference) ? "" : "`") + "BugButtonsWindowItem` " + "` "; } else if (item instanceof GamesWindowItem) { preference += (StringUtils.isBlank(preference) ? "" : "`") + "GamesWindowItem` ` "; } } Raptor.getInstance().getPreferences().setValue( context.getShortName() + "-" + currentProfileName + "-" + PreferenceKeys.CHANNEL_REGEX_TAB_INFO, preference); Raptor.getInstance().getPreferences().save(); } }