code
stringlengths
73
34.1k
label
stringclasses
1 value
private void saveToPropertyVfsBundle() throws CmsException { for (Locale l : m_changedTranslations) { SortedProperties props = m_localizations.get(l); LockedFile f = m_lockedBundleFiles.get(l); if ((null != props) && (null != f)) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(outputStream, f.getEncoding()); props.store(writer, null); byte[] contentBytes = outputStream.toByteArray(); CmsFile file = f.getFile(); file.setContents(contentBytes); String contentEncodingProperty = m_cms.readPropertyObject( file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, false).getValue(); if ((null == contentEncodingProperty) || !contentEncodingProperty.equals(f.getEncoding())) { m_cms.writePropertyObject( m_cms.getSitePath(file), new CmsProperty( CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, f.getEncoding(), f.getEncoding())); } m_cms.writeFile(file); } catch (IOException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_READING_FILE_UNSUPPORTED_ENCODING_2, f.getFile().getRootPath(), f.getEncoding()), e); } } } }
java
private void saveToXmlVfsBundle() throws CmsException { if (m_lockedBundleFiles.get(null) != null) { // If the file was not locked, no changes were made, i.e., storing is not necessary. for (Locale l : m_locales) { SortedProperties props = m_localizations.get(l); if (null != props) { if (m_xmlBundle.hasLocale(l)) { m_xmlBundle.removeLocale(l); } m_xmlBundle.addLocale(m_cms, l); int i = 0; List<Object> keys = new ArrayList<Object>(props.keySet()); Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance()); for (Object key : keys) { if ((null != key) && !key.toString().isEmpty()) { String value = props.getProperty(key.toString()); if (!value.isEmpty()) { m_xmlBundle.addValue(m_cms, "Message", l, i); i++; m_xmlBundle.getValue("Message[" + i + "]/Key", l).setStringValue(m_cms, key.toString()); m_xmlBundle.getValue("Message[" + i + "]/Value", l).setStringValue(m_cms, value); } } } } CmsFile bundleFile = m_lockedBundleFiles.get(null).getFile(); bundleFile.setContents(m_xmlBundle.marshal()); m_cms.writeFile(bundleFile); } } }
java
private void setResourceInformation() { String sitePath = m_cms.getSitePath(m_resource); int pathEnd = sitePath.lastIndexOf('/') + 1; String baseName = sitePath.substring(pathEnd); m_sitepath = sitePath.substring(0, pathEnd); switch (CmsMessageBundleEditorTypes.BundleType.toBundleType( OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())) { case PROPERTY: String localeSuffix = CmsStringUtil.getLocaleSuffixForName(baseName); if ((null != localeSuffix) && !localeSuffix.isEmpty()) { baseName = baseName.substring( 0, baseName.lastIndexOf(localeSuffix) - (1 /* cut off trailing underscore, too*/)); m_locale = CmsLocaleManager.getLocale(localeSuffix); } if ((null == m_locale) || !m_locales.contains(m_locale)) { m_switchedLocaleOnOpening = true; m_locale = m_locales.iterator().next(); } break; case XML: m_locale = OpenCms.getLocaleManager().getBestAvailableLocaleForXmlContent( m_cms, m_resource, m_xmlBundle); break; case DESCRIPTOR: m_basename = baseName.substring( 0, baseName.length() - CmsMessageBundleEditorTypes.Descriptor.POSTFIX.length()); m_locale = new Locale("en"); break; default: throw new IllegalArgumentException( Messages.get().container( Messages.ERR_UNSUPPORTED_BUNDLE_TYPE_1, CmsMessageBundleEditorTypes.BundleType.toBundleType( OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())).toString()); } m_basename = baseName; }
java
private void unmarshalDescriptor() throws CmsXmlException, CmsException { if (null != m_desc) { // unmarshal descriptor m_descContent = CmsXmlContentFactory.unmarshal(m_cms, m_cms.readFile(m_desc)); // configure messages if wanted CmsProperty bundleProp = m_cms.readPropertyObject(m_desc, PROPERTY_BUNDLE_DESCRIPTOR_LOCALIZATION, true); if (!(bundleProp.isNullProperty() || bundleProp.getValue().trim().isEmpty())) { m_configuredBundle = bundleProp.getValue(); } } }
java
private void updateBundleDescriptorContent() throws CmsXmlException { if (m_descContent.hasLocale(Descriptor.LOCALE)) { m_descContent.removeLocale(Descriptor.LOCALE); } m_descContent.addLocale(m_cms, Descriptor.LOCALE); int i = 0; Property<Object> descProp; String desc; Property<Object> defaultValueProp; String defaultValue; Map<String, Item> keyItemMap = getKeyItemMap(); List<String> keys = new ArrayList<String>(keyItemMap.keySet()); Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance()); for (Object key : keys) { if ((null != key) && !key.toString().isEmpty()) { m_descContent.addValue(m_cms, Descriptor.N_MESSAGE, Descriptor.LOCALE, i); i++; String messagePrefix = Descriptor.N_MESSAGE + "[" + i + "]/"; m_descContent.getValue(messagePrefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue( m_cms, (String)key); descProp = keyItemMap.get(key).getItemProperty(TableProperty.DESCRIPTION); if ((null != descProp) && (null != descProp.getValue())) { desc = descProp.getValue().toString(); m_descContent.getValue(messagePrefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).setStringValue( m_cms, desc); } defaultValueProp = keyItemMap.get(key).getItemProperty(TableProperty.DEFAULT); if ((null != defaultValueProp) && (null != defaultValueProp.getValue())) { defaultValue = defaultValueProp.getValue().toString(); m_descContent.getValue(messagePrefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).setStringValue( m_cms, defaultValue); } } } }
java
protected void removeInvalidChildren() { if (getLoadState() == LoadState.LOADED) { List<CmsSitemapTreeItem> toDelete = new ArrayList<CmsSitemapTreeItem>(); for (int i = 0; i < getChildCount(); i++) { CmsSitemapTreeItem item = (CmsSitemapTreeItem)getChild(i); CmsUUID id = item.getEntryId(); if ((id != null) && (CmsSitemapView.getInstance().getController().getEntryById(id) == null)) { toDelete.add(item); } } for (CmsSitemapTreeItem deleteItem : toDelete) { m_children.removeItem(deleteItem); } } }
java
@UiHandler("m_everyDay") void onEveryDayChange(ValueChangeEvent<String> event) { if (handleChange()) { m_controller.setInterval(m_everyDay.getFormValueAsString()); } }
java
private String getApiKey(CmsObject cms, String sitePath) throws CmsException { String res = cms.readPropertyObject( sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY_WORKPLACE, true).getValue(); if (CmsStringUtil.isEmptyOrWhitespaceOnly(res)) { res = cms.readPropertyObject(sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY, true).getValue(); } return res; }
java
private void propagateFacetNames() { // collect all names and configurations Collection<String> facetNames = new ArrayList<String>(); Collection<I_CmsSearchConfigurationFacet> facetConfigs = new ArrayList<I_CmsSearchConfigurationFacet>(); facetNames.addAll(m_fieldFacets.keySet()); facetConfigs.addAll(m_fieldFacets.values()); facetNames.addAll(m_rangeFacets.keySet()); facetConfigs.addAll(m_rangeFacets.values()); if (null != m_queryFacet) { facetNames.add(m_queryFacet.getName()); facetConfigs.add(m_queryFacet); } // propagate all names for (I_CmsSearchConfigurationFacet facetConfig : facetConfigs) { facetConfig.propagateAllFacetNames(facetNames); } }
java
private int getDaysToNextMatch(WeekDay weekDay) { for (WeekDay wd : m_weekDays) { if (wd.compareTo(weekDay) > 0) { return wd.toInt() - weekDay.toInt(); } } return (m_weekDays.iterator().next().toInt() + (m_interval * I_CmsSerialDateValue.NUM_OF_WEEKDAYS)) - weekDay.toInt(); }
java
public static I_CmsMacroResolver newWorkplaceLocaleResolver(final CmsObject cms) { // Resolve macros in the property configuration CmsMacroResolver resolver = new CmsMacroResolver(); resolver.setCmsObject(cms); CmsUserSettings userSettings = new CmsUserSettings(cms.getRequestContext().getCurrentUser()); CmsMultiMessages multimessages = new CmsMultiMessages(userSettings.getLocale()); multimessages.addMessages(OpenCms.getWorkplaceManager().getMessages(userSettings.getLocale())); resolver.setMessages(multimessages); resolver.setKeepEmptyMacros(true); return resolver; }
java
protected static List<String> parseMandatoryStringValues(JSONObject json, String key) throws JSONException { List<String> list = null; JSONArray array = json.getJSONArray(key); list = new ArrayList<String>(array.length()); for (int i = 0; i < array.length(); i++) { try { String entry = array.getString(i); list.add(entry); } catch (JSONException e) { LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_STRING_ENTRY_UNPARSABLE_1, key), e); } } return list; }
java
protected Boolean getEscapeQueryChars() { Boolean isEscape = parseOptionalBooleanValue(m_configObject, JSON_KEY_ESCAPE_QUERY_CHARACTERS); return (null == isEscape) && (m_baseConfig != null) ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getEscapeQueryChars()) : isEscape; }
java
protected String getExtraSolrParams() { try { return m_configObject.getString(JSON_KEY_EXTRASOLRPARAMS); } catch (JSONException e) { if (null == m_baseConfig) { if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_EXTRA_PARAMETERS_0), e); } return ""; } else { return m_baseConfig.getGeneralConfig().getExtraSolrParams(); } } }
java
protected Boolean getIgnoreExpirationDate() { Boolean isIgnoreExpirationDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_EXPIRATION_DATE); return (null == isIgnoreExpirationDate) && (m_baseConfig != null) ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreExpirationDate()) : isIgnoreExpirationDate; }
java
protected Boolean getIgnoreQuery() { Boolean isIgnoreQuery = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_QUERY); return (null == isIgnoreQuery) && (m_baseConfig != null) ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreQueryParam()) : isIgnoreQuery; }
java
protected Boolean getIgnoreReleaseDate() { Boolean isIgnoreReleaseDate = parseOptionalBooleanValue(m_configObject, JSON_KEY_IGNORE_RELEASE_DATE); return (null == isIgnoreReleaseDate) && (m_baseConfig != null) ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getIgnoreReleaseDate()) : isIgnoreReleaseDate; }
java
protected List<Integer> getPageSizes() { try { return Collections.singletonList(Integer.valueOf(m_configObject.getInt(JSON_KEY_PAGESIZE))); } catch (JSONException e) { List<Integer> result = null; String pageSizesString = null; try { pageSizesString = m_configObject.getString(JSON_KEY_PAGESIZE); String[] pageSizesArray = pageSizesString.split("-"); if (pageSizesArray.length > 0) { result = new ArrayList<>(pageSizesArray.length); for (int i = 0; i < pageSizesArray.length; i++) { result.add(Integer.valueOf(pageSizesArray[i])); } } return result; } catch (NumberFormatException | JSONException e1) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_PARSING_PAGE_SIZES_FAILED_1, pageSizesString), e); } if (null == m_baseConfig) { if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_PAGESIZE_SPECIFIED_0), e); } return null; } else { return m_baseConfig.getPaginationConfig().getPageSizes(); } } }
java
protected String getQueryModifier() { String queryModifier = parseOptionalStringValue(m_configObject, JSON_KEY_QUERY_MODIFIER); return (null == queryModifier) && (null != m_baseConfig) ? m_baseConfig.getGeneralConfig().getQueryModifier() : queryModifier; }
java
protected String getQueryParam() { String param = parseOptionalStringValue(m_configObject, JSON_KEY_QUERYPARAM); if (param == null) { return null != m_baseConfig ? m_baseConfig.getGeneralConfig().getQueryParam() : DEFAULT_QUERY_PARAM; } else { return param; } }
java
protected Boolean getSearchForEmptyQuery() { Boolean isSearchForEmptyQuery = parseOptionalBooleanValue(m_configObject, JSON_KEY_SEARCH_FOR_EMPTY_QUERY); return (isSearchForEmptyQuery == null) && (null != m_baseConfig) ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getSearchForEmptyQueryParam()) : isSearchForEmptyQuery; }
java
protected List<I_CmsSearchConfigurationSortOption> getSortOptions() { List<I_CmsSearchConfigurationSortOption> options = new LinkedList<I_CmsSearchConfigurationSortOption>(); try { JSONArray sortOptions = m_configObject.getJSONArray(JSON_KEY_SORTOPTIONS); for (int i = 0; i < sortOptions.length(); i++) { I_CmsSearchConfigurationSortOption option = parseSortOption(sortOptions.getJSONObject(i)); if (option != null) { options.add(option); } } } catch (JSONException e) { if (null == m_baseConfig) { if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_SORT_CONFIG_0), e); } } else { options = m_baseConfig.getSortConfig().getSortOptions(); } } return options; }
java
protected void init(String configString, I_CmsSearchConfiguration baseConfig) throws JSONException { m_configObject = new JSONObject(configString); m_baseConfig = baseConfig; }
java
protected I_CmsFacetQueryItem parseFacetQueryItem(JSONObject item) { String query; try { query = item.getString(JSON_KEY_QUERY_FACET_QUERY_QUERY); } catch (JSONException e) { // TODO: Log return null; } String label = parseOptionalStringValue(item, JSON_KEY_QUERY_FACET_QUERY_LABEL); return new CmsFacetQueryItem(query, label); }
java
protected List<I_CmsFacetQueryItem> parseFacetQueryItems(JSONObject queryFacetObject) throws JSONException { JSONArray items = queryFacetObject.getJSONArray(JSON_KEY_QUERY_FACET_QUERY); List<I_CmsFacetQueryItem> result = new ArrayList<I_CmsFacetQueryItem>(items.length()); for (int i = 0; i < items.length(); i++) { I_CmsFacetQueryItem item = parseFacetQueryItem(items.getJSONObject(i)); if (item != null) { result.add(item); } } return result; }
java
protected I_CmsSearchConfigurationFacetField parseFieldFacet(JSONObject fieldFacetObject) { try { String field = fieldFacetObject.getString(JSON_KEY_FACET_FIELD); String name = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_NAME); String label = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_LABEL); Integer minCount = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_MINCOUNT); Integer limit = parseOptionalIntValue(fieldFacetObject, JSON_KEY_FACET_LIMIT); String prefix = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_PREFIX); String sorder = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_ORDER); I_CmsSearchConfigurationFacet.SortOrder order; try { order = I_CmsSearchConfigurationFacet.SortOrder.valueOf(sorder); } catch (Exception e) { order = null; } String filterQueryModifier = parseOptionalStringValue(fieldFacetObject, JSON_KEY_FACET_FILTERQUERYMODIFIER); Boolean isAndFacet = parseOptionalBooleanValue(fieldFacetObject, JSON_KEY_FACET_ISANDFACET); List<String> preselection = parseOptionalStringValues(fieldFacetObject, JSON_KEY_FACET_PRESELECTION); Boolean ignoreFilterAllFacetFilters = parseOptionalBooleanValue( fieldFacetObject, JSON_KEY_FACET_IGNOREALLFACETFILTERS); return new CmsSearchConfigurationFacetField( field, name, minCount, limit, prefix, label, order, filterQueryModifier, isAndFacet, preselection, ignoreFilterAllFacetFilters); } catch (JSONException e) { LOG.error( Messages.get().getBundle().key(Messages.ERR_FIELD_FACET_MANDATORY_KEY_MISSING_1, JSON_KEY_FACET_FIELD), e); return null; } }
java
protected I_CmsSearchConfigurationFacetRange parseRangeFacet(JSONObject rangeFacetObject) { try { String range = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_RANGE); String name = parseOptionalStringValue(rangeFacetObject, JSON_KEY_FACET_NAME); String label = parseOptionalStringValue(rangeFacetObject, JSON_KEY_FACET_LABEL); Integer minCount = parseOptionalIntValue(rangeFacetObject, JSON_KEY_FACET_MINCOUNT); String start = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_START); String end = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_END); String gap = rangeFacetObject.getString(JSON_KEY_RANGE_FACET_GAP); List<String> sother = parseOptionalStringValues(rangeFacetObject, JSON_KEY_RANGE_FACET_OTHER); Boolean hardEnd = parseOptionalBooleanValue(rangeFacetObject, JSON_KEY_RANGE_FACET_HARDEND); List<I_CmsSearchConfigurationFacetRange.Other> other = null; if (sother != null) { other = new ArrayList<I_CmsSearchConfigurationFacetRange.Other>(sother.size()); for (String so : sother) { try { I_CmsSearchConfigurationFacetRange.Other o = I_CmsSearchConfigurationFacetRange.Other.valueOf( so); other.add(o); } catch (Exception e) { LOG.error(Messages.get().getBundle().key(Messages.ERR_INVALID_OTHER_OPTION_1, so), e); } } } Boolean isAndFacet = parseOptionalBooleanValue(rangeFacetObject, JSON_KEY_FACET_ISANDFACET); List<String> preselection = parseOptionalStringValues(rangeFacetObject, JSON_KEY_FACET_PRESELECTION); Boolean ignoreAllFacetFilters = parseOptionalBooleanValue( rangeFacetObject, JSON_KEY_FACET_IGNOREALLFACETFILTERS); return new CmsSearchConfigurationFacetRange( range, start, end, gap, other, hardEnd, name, minCount, label, isAndFacet, preselection, ignoreAllFacetFilters); } catch (JSONException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_RANGE_FACET_MANDATORY_KEY_MISSING_1, JSON_KEY_RANGE_FACET_RANGE + ", " + JSON_KEY_RANGE_FACET_START + ", " + JSON_KEY_RANGE_FACET_END + ", " + JSON_KEY_RANGE_FACET_GAP), e); return null; } }
java
protected I_CmsSearchConfigurationSortOption parseSortOption(JSONObject json) { try { String solrValue = json.getString(JSON_KEY_SORTOPTION_SOLRVALUE); String paramValue = parseOptionalStringValue(json, JSON_KEY_SORTOPTION_PARAMVALUE); paramValue = (paramValue == null) ? solrValue : paramValue; String label = parseOptionalStringValue(json, JSON_KEY_SORTOPTION_LABEL); label = (label == null) ? paramValue : label; return new CmsSearchConfigurationSortOption(label, paramValue, solrValue); } catch (JSONException e) { LOG.error( Messages.get().getBundle().key(Messages.ERR_SORT_OPTION_NOT_PARSABLE_1, JSON_KEY_SORTOPTION_SOLRVALUE), e); return null; } }
java
private Map<String, String> mergeItem( String item, Map<String, String> localeValues, Map<String, String> resultLocaleValues) { if (resultLocaleValues.get(item) != null) { if (localeValues.get(item) != null) { localeValues.put(item, localeValues.get(item) + " " + resultLocaleValues.get(item)); } else { localeValues.put(item, resultLocaleValues.get(item)); } } return localeValues; }
java
public static CmsGalleryTabConfiguration resolve(String configStr) { CmsGalleryTabConfiguration tabConfig; if (CmsStringUtil.isEmptyOrWhitespaceOnly(configStr)) { configStr = "*sitemap,types,galleries,categories,vfstree,search,results"; } if (DEFAULT_CONFIGURATIONS != null) { tabConfig = DEFAULT_CONFIGURATIONS.get(configStr); if (tabConfig != null) { return tabConfig; } } return parse(configStr); }
java
private void forward() { Set<String> selected = new HashSet<>(); for (CheckBox checkbox : m_componentCheckboxes) { CmsSetupComponent component = (CmsSetupComponent)(checkbox.getData()); if (checkbox.getValue().booleanValue()) { selected.add(component.getId()); } } String error = null; for (String compId : selected) { CmsSetupComponent component = m_componentMap.get(compId); for (String dep : component.getDependencies()) { if (!selected.contains(dep)) { error = "Unfulfilled dependency: The component " + component.getName() + " can not be installed because its dependency " + m_componentMap.get(dep).getName() + " is not selected"; break; } } } if (error == null) { Set<String> modules = new HashSet<>(); for (CmsSetupComponent component : m_componentMap.values()) { if (selected.contains(component.getId())) { for (CmsModule module : m_context.getSetupBean().getAvailableModules().values()) { if (component.match(module.getName())) { modules.add(module.getName()); } } } } List<String> moduleList = new ArrayList<>(modules); m_context.getSetupBean().setInstallModules(CmsStringUtil.listAsString(moduleList, "|")); m_context.stepForward(); } else { CmsSetupErrorDialog.showErrorDialog(error, error); } }
java
private void initComponents(List<CmsSetupComponent> components) { for (CmsSetupComponent component : components) { CheckBox checkbox = new CheckBox(); checkbox.setValue(component.isChecked()); checkbox.setCaption(component.getName() + " - " + component.getDescription()); checkbox.setDescription(component.getDescription()); checkbox.setData(component); checkbox.setWidth("100%"); m_components.addComponent(checkbox); m_componentCheckboxes.add(checkbox); m_componentMap.put(component.getId(), component); } }
java
protected void addFacetPart(CmsSolrQuery query) { query.set("facet", "true"); String excludes = ""; if (m_config.getIgnoreAllFacetFilters() || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) { excludes = "{!ex=" + m_config.getIgnoreTags() + "}"; } for (I_CmsFacetQueryItem q : m_config.getQueryList()) { query.add("facet.query", excludes + q.getQuery()); } }
java
protected void convertSearchResults(final Collection<CmsSearchResource> searchResults) { m_foundResources = new ArrayList<I_CmsSearchResourceBean>(); for (final CmsSearchResource searchResult : searchResults) { m_foundResources.add(new CmsSearchResourceBean(searchResult, m_cmsObject)); } }
java
public void addAliasToConfigSite(String alias, String redirect, String offset) { long timeOffset = 0; try { timeOffset = Long.parseLong(offset); } catch (Throwable e) { // ignore } CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset); boolean redirectVal = new Boolean(redirect).booleanValue(); siteMatcher.setRedirect(redirectVal); m_aliases.add(siteMatcher); }
java
private void addServer(CmsSiteMatcher matcher, CmsSite site) { Map<CmsSiteMatcher, CmsSite> siteMatcherSites = new HashMap<CmsSiteMatcher, CmsSite>(m_siteMatcherSites); siteMatcherSites.put(matcher, site); setSiteMatcherSites(siteMatcherSites); }
java
private void updateLetsEncrypt() { getReport().println(Messages.get().container(Messages.RPT_STARTING_LETSENCRYPT_UPDATE_0)); CmsLetsEncryptConfiguration config = OpenCms.getLetsEncryptConfig(); if ((config == null) || !config.isValidAndEnabled()) { return; } CmsSiteConfigToLetsEncryptConfigConverter converter = new CmsSiteConfigToLetsEncryptConfigConverter(config); boolean ok = converter.run(getReport(), OpenCms.getSiteManager()); if (ok) { getReport().println( org.opencms.ui.apps.Messages.get().container(org.opencms.ui.apps.Messages.RPT_LETSENCRYPT_FINISHED_0), I_CmsReport.FORMAT_OK); } }
java
private String getDynamicAttributeValue( CmsFile file, I_CmsXmlContentValue value, String attributeName, CmsEntity editedLocalEntity) { if ((null != editedLocalEntity) && (editedLocalEntity.getAttribute(attributeName) != null)) { getSessionCache().setDynamicValue( attributeName, editedLocalEntity.getAttribute(attributeName).getSimpleValue()); } String currentValue = getSessionCache().getDynamicValue(attributeName); if (null != currentValue) { return currentValue; } if (null != file) { if (value.getTypeName().equals(CmsXmlDynamicCategoryValue.TYPE_NAME)) { List<CmsCategory> categories = new ArrayList<CmsCategory>(0); try { categories = CmsCategoryService.getInstance().readResourceCategories(getCmsObject(), file); } catch (CmsException e) { LOG.error(Messages.get().getBundle().key(Messages.ERROR_FAILED_READING_CATEGORIES_1), e); } I_CmsWidget widget = null; widget = CmsWidgetUtil.collectWidgetInfo(value).getWidget(); if ((null != widget) && (widget instanceof CmsCategoryWidget)) { String mainCategoryPath = ((CmsCategoryWidget)widget).getStartingCategory( getCmsObject(), getCmsObject().getSitePath(file)); StringBuffer pathes = new StringBuffer(); for (CmsCategory category : categories) { if (category.getPath().startsWith(mainCategoryPath)) { String path = category.getBasePath() + category.getPath(); path = getCmsObject().getRequestContext().removeSiteRoot(path); pathes.append(path).append(','); } } String dynamicConfigString = pathes.length() > 0 ? pathes.substring(0, pathes.length() - 1) : ""; getSessionCache().setDynamicValue(attributeName, dynamicConfigString); return dynamicConfigString; } } } return ""; }
java
public void setMonth(String monthStr) { final Month month = Month.valueOf(monthStr); if ((m_model.getMonth() == null) || !m_model.getMonth().equals(monthStr)) { removeExceptionsOnChange(new Command() { public void execute() { m_model.setMonth(month); onValueChange(); } }); } }
java
public void setPatternScheme(final boolean isWeekDayBased) { if (isWeekDayBased ^ (null != m_model.getWeekDay())) { removeExceptionsOnChange(new Command() { public void execute() { if (isWeekDayBased) { m_model.setWeekDay(getPatternDefaultValues().getWeekDay()); m_model.setWeekOfMonth(getPatternDefaultValues().getWeekOfMonth()); } else { m_model.setWeekDay(null); m_model.setWeekOfMonth(null); } m_model.setMonth(getPatternDefaultValues().getMonth()); m_model.setDayOfMonth(getPatternDefaultValues().getDayOfMonth()); m_model.setInterval(getPatternDefaultValues().getInterval()); onValueChange(); } }); } }
java
public void setWeekDay(String weekDayStr) { final WeekDay weekDay = WeekDay.valueOf(weekDayStr); if ((m_model.getWeekDay() != null) || !m_model.getWeekDay().equals(weekDay)) { removeExceptionsOnChange(new Command() { public void execute() { m_model.setWeekDay(weekDay); onValueChange(); } }); } }
java
public void setWeekOfMonth(String weekOfMonthStr) { final WeekOfMonth weekOfMonth = WeekOfMonth.valueOf(weekOfMonthStr); if ((null == m_model.getWeekOfMonth()) || !m_model.getWeekOfMonth().equals(weekOfMonth)) { removeExceptionsOnChange(new Command() { public void execute() { m_model.setWeekOfMonth(weekOfMonth); onValueChange(); } }); } }
java
public static String getLocalizedKey(Map<String, ?> propertiesMap, String key, Locale locale) { List<String> localizedKeys = CmsLocaleManager.getLocaleVariants(key, locale, true, false); for (String localizedKey : localizedKeys) { if (propertiesMap.containsKey(localizedKey)) { return localizedKey; } } return key; }
java
private List<CmsSearchField> getFields() { CmsSearchManager manager = OpenCms.getSearchManager(); I_CmsSearchFieldConfiguration fieldConfig = manager.getFieldConfiguration(getParamFieldconfiguration()); List<CmsSearchField> result; if (fieldConfig != null) { result = fieldConfig.getFields(); } else { result = Collections.emptyList(); if (LOG.isErrorEnabled()) { LOG.error( Messages.get().getBundle().key( Messages.ERR_SEARCHINDEX_EDIT_MISSING_PARAM_1, A_CmsFieldConfigurationDialog.PARAM_FIELDCONFIGURATION)); } } return result; }
java
public static Function<String, String> createStringTemplateSource( I_CmsFormatterBean formatter, Supplier<CmsXmlContent> contentSupplier) { return key -> { String result = null; if (formatter != null) { result = formatter.getAttributes().get(key); } if (result == null) { CmsXmlContent content = contentSupplier.get(); if (content != null) { result = content.getHandler().getParameter(key); } } return result; }; }
java
private Map<String, String> getContentsByContainerName( CmsContainerElementBean element, Collection<CmsContainer> containers) { CmsFormatterConfiguration configs = getFormatterConfiguration(element.getResource()); Map<String, String> result = new HashMap<String, String>(); for (CmsContainer container : containers) { String content = getContentByContainer(element, container, configs); if (content != null) { content = removeScriptTags(content); } result.put(container.getName(), content); } return result; }
java
public void setWorkConnection(CmsSetupDb db) { db.setConnection( m_setupBean.getDbDriver(), m_setupBean.getDbWorkConStr(), m_setupBean.getDbConStrParams(), m_setupBean.getDbWorkUser(), m_setupBean.getDbWorkPwd()); }
java
private void updateDb(String dbName, String webapp) { m_mainLayout.removeAllComponents(); m_setupBean.setDatabase(dbName); CmsDbSettingsPanel panel = new CmsDbSettingsPanel(m_setupBean); m_panel[0] = panel; panel.initFromSetupBean(webapp); m_mainLayout.addComponent(panel); }
java
public void removeExpiration() { if (getFilterQueries() != null) { for (String fq : getFilterQueries()) { if (fq.startsWith(CmsSearchField.FIELD_DATE_EXPIRED + ":") || fq.startsWith(CmsSearchField.FIELD_DATE_RELEASED + ":")) { removeFilterQuery(fq); } } } m_ignoreExpiration = true; }
java
public Map<String, CmsJspCategoryAccessBean> getReadAllSubCategories() { if (null == m_allSubCategories) { m_allSubCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { @Override public Object transform(Object categoryPath) { try { List<CmsCategory> categories = CmsCategoryService.getInstance().readCategories( m_cms, (String)categoryPath, true, m_cms.getRequestContext().getUri()); CmsJspCategoryAccessBean result = new CmsJspCategoryAccessBean( m_cms, categories, (String)categoryPath); return result; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_allSubCategories; }
java
public Map<String, CmsCategory> getReadCategory() { if (null == m_categories) { m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object categoryPath) { try { CmsCategoryService catService = CmsCategoryService.getInstance(); return catService.localizeCategory( m_cms, catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()), m_cms.getRequestContext().getLocale()); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_categories; }
java
public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() { if (null == m_resourceCategories) { m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object resourceName) { try { CmsResource resource = m_cms.readResource( getRequestContext().removeSiteRoot((String)resourceName)); return new CmsJspCategoryAccessBean(m_cms, resource); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_resourceCategories; }
java
public Map<String, String> getSitePath() { if (m_sitePaths == null) { m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object rootPath) { if (rootPath instanceof String) { return getRequestContext().removeSiteRoot((String)rootPath); } return null; } }); } return m_sitePaths; }
java
public Map<String, String> getTitleLocale() { if (m_localeTitles == null) { m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object inputLocale) { Locale locale = null; if (null != inputLocale) { if (inputLocale instanceof Locale) { locale = (Locale)inputLocale; } else if (inputLocale instanceof String) { try { locale = LocaleUtils.toLocale((String)inputLocale); } catch (IllegalArgumentException | NullPointerException e) { // do nothing, just go on without locale } } } return getLocaleSpecificTitle(locale); } }); } return m_localeTitles; }
java
protected String getLocaleSpecificTitle(Locale locale) { String result = null; try { if (isDetailRequest()) { // this is a request to a detail page CmsResource res = getDetailContent(); CmsFile file = m_cms.readFile(res); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file); result = content.getHandler().getTitleMapping(m_cms, content, m_cms.getRequestContext().getLocale()); if (result == null) { // title not found, maybe no mapping OR not available in the current locale // read the title of the detail resource as fall back (may contain mapping from another locale) result = m_cms.readPropertyObject( res, CmsPropertyDefinition.PROPERTY_TITLE, false, locale).getValue(); } } if (result == null) { // read the title of the requested resource as fall back result = m_cms.readPropertyObject( m_cms.getRequestContext().getUri(), CmsPropertyDefinition.PROPERTY_TITLE, true, locale).getValue(); } } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); } if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) { result = ""; } return result; }
java
public void setStringValue(String value) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) { try { m_editValue = CmsLocationValue.parse(value); m_currentValue = m_editValue.cloneValue(); displayValue(); if ((m_popup != null) && m_popup.isVisible()) { m_popupContent.displayValues(m_editValue); updateMarkerPosition(); } } catch (Exception e) { CmsLog.log(e.getLocalizedMessage() + "\n" + CmsClientStringUtil.getStackTrace(e, "\n")); } } else { m_currentValue = null; displayValue(); } }
java
public static byte[] hashPassword(String password) throws InvalidKeyException, NoSuchAlgorithmException { PasswordEncryptor encryptor = new PasswordEncryptor(); return encryptor.generateEncryptedPassword(password, null, PasswordEncryptor.MD4, null, null); }
java
public void setHeader(String header, String value) { StringValidator.throwIfEmptyOrNull("header", header); StringValidator.throwIfEmptyOrNull("value", value); if (headers == null) { headers = new HashMap<String, String>(); } headers.put(header, value); }
java
protected List<CmsResource> getTopFolders(List<CmsResource> folders) { List<String> folderPaths = new ArrayList<String>(); List<CmsResource> topFolders = new ArrayList<CmsResource>(); Map<String, CmsResource> foldersByPath = new HashMap<String, CmsResource>(); for (CmsResource folder : folders) { folderPaths.add(folder.getRootPath()); foldersByPath.put(folder.getRootPath(), folder); } Collections.sort(folderPaths); Set<String> topFolderPaths = new HashSet<String>(folderPaths); for (int i = 0; i < folderPaths.size(); i++) { for (int j = i + 1; j < folderPaths.size(); j++) { if (folderPaths.get(j).startsWith((folderPaths.get(i)))) { topFolderPaths.remove(folderPaths.get(j)); } else { break; } } } for (String path : topFolderPaths) { topFolders.add(foldersByPath.get(path)); } return topFolders; }
java
public void setDates(SortedSet<Date> dates) { if (!m_model.getIndividualDates().equals(dates)) { m_model.setIndividualDates(dates); onValueChange(); } }
java
public static CmsSolrSpellchecker getInstance(CoreContainer container) { if (null == instance) { synchronized (CmsSolrSpellchecker.class) { if (null == instance) { @SuppressWarnings("resource") SolrCore spellcheckCore = container.getCore(CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE); if (spellcheckCore == null) { LOG.error( Messages.get().getBundle().key( Messages.ERR_SPELLCHECK_CORE_NOT_AVAILABLE_1, CmsSolrSpellchecker.SPELLCHECKER_INDEX_CORE)); return null; } instance = new CmsSolrSpellchecker(container, spellcheckCore); } } } return instance; }
java
public void getSpellcheckingResult( final HttpServletResponse res, final ServletRequest servletRequest, final CmsObject cms) throws CmsPermissionViolationException, IOException { // Perform a permission check performPermissionCheck(cms); // Set the appropriate response headers setResponeHeaders(res); // Figure out whether a JSON or HTTP request has been sent CmsSpellcheckingRequest cmsSpellcheckingRequest = null; try { String requestBody = getRequestBody(servletRequest); final JSONObject jsonRequest = new JSONObject(requestBody); cmsSpellcheckingRequest = parseJsonRequest(jsonRequest); } catch (Exception e) { LOG.debug(e.getMessage(), e); cmsSpellcheckingRequest = parseHttpRequest(servletRequest, cms); } if ((null != cmsSpellcheckingRequest) && cmsSpellcheckingRequest.isInitialized()) { // Perform the actual spellchecking final SpellCheckResponse spellCheckResponse = performSpellcheckQuery(cmsSpellcheckingRequest); /* * The field spellCheckResponse is null when exactly one correctly spelled word is passed to the spellchecker. * In this case it's safe to return an empty JSON formatted map, as the passed word is correct. Otherwise, * convert the spellchecker response into a new JSON formatted map. */ if (null == spellCheckResponse) { cmsSpellcheckingRequest.m_wordSuggestions = new JSONObject(); } else { cmsSpellcheckingRequest.m_wordSuggestions = getConvertedResponseAsJson(spellCheckResponse); } } // Send response back to the client sendResponse(res, cmsSpellcheckingRequest); }
java
public void parseAndAddDictionaries(CmsObject cms) throws CmsRoleViolationException { OpenCms.getRoleManager().checkRole(cms, CmsRole.ROOT_ADMIN); CmsSpellcheckDictionaryIndexer.parseAndAddZippedDictionaries(m_solrClient, cms); CmsSpellcheckDictionaryIndexer.parseAndAddDictionaries(m_solrClient, cms); }
java
private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) { if (null == response) { return null; } final JSONObject suggestions = new JSONObject(); final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap(); // Add suggestions to the response for (final String key : solrSuggestions.keySet()) { // Indicator to ignore words that are erroneously marked as misspelled. boolean ignoreWord = false; // Suggestions that are in the form "Xxxx" -> "xxxx" should be ignored. if (Character.isUpperCase(key.codePointAt(0))) { final String lowercaseKey = key.toLowerCase(); // If the suggestion map doesn't contain the lowercased word, ignore this entry. if (!solrSuggestions.containsKey(lowercaseKey)) { ignoreWord = true; } } if (!ignoreWord) { try { // Get suggestions as List final List<String> l = solrSuggestions.get(key).getAlternatives(); suggestions.put(key, l); } catch (JSONException e) { LOG.debug("Exception while converting Solr spellcheckresponse to JSON. ", e); } } } return suggestions; }
java
private JSONObject getJsonFormattedSpellcheckResult(CmsSpellcheckingRequest request) { final JSONObject response = new JSONObject(); try { if (null != request.m_id) { response.put(JSON_ID, request.m_id); } response.put(JSON_RESULT, request.m_wordSuggestions); } catch (Exception e) { try { response.put(JSON_ERROR, true); LOG.debug("Error while assembling spellcheck response in JSON format.", e); } catch (JSONException ex) { LOG.debug("Error while assembling spellcheck response in JSON format.", ex); } } return response; }
java
private String getRequestBody(ServletRequest request) throws IOException { final StringBuilder sb = new StringBuilder(); String line = request.getReader().readLine(); while (null != line) { sb.append(line); line = request.getReader().readLine(); } return sb.toString(); }
java
private CmsSpellcheckingRequest parseHttpRequest(final ServletRequest req, final CmsObject cms) { if ((null != cms) && OpenCms.getRoleManager().hasRole(cms, CmsRole.ROOT_ADMIN)) { try { if (null != req.getParameter(HTTP_PARAMETER_CHECKREBUILD)) { if (CmsSpellcheckDictionaryIndexer.updatingIndexNecessesary(cms)) { parseAndAddDictionaries(cms); } } if (null != req.getParameter(HTTP_PARAMTER_REBUILD)) { parseAndAddDictionaries(cms); } } catch (CmsRoleViolationException e) { LOG.error(e.getLocalizedMessage(), e); } } final String q = req.getParameter(HTTP_PARAMETER_WORDS); if (null == q) { LOG.debug("Invalid HTTP request: No parameter \"" + HTTP_PARAMETER_WORDS + "\" defined. "); return null; } final StringTokenizer st = new StringTokenizer(q); final List<String> wordsToCheck = new ArrayList<String>(); while (st.hasMoreTokens()) { final String word = st.nextToken(); wordsToCheck.add(word); if (Character.isUpperCase(word.codePointAt(0))) { wordsToCheck.add(word.toLowerCase()); } } final String[] w = wordsToCheck.toArray(new String[wordsToCheck.size()]); final String dict = req.getParameter(HTTP_PARAMETER_LANG) == null ? LANG_DEFAULT : req.getParameter(HTTP_PARAMETER_LANG); return new CmsSpellcheckingRequest(w, dict); }
java
private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) { final String id = jsonRequest.optString(JSON_ID); final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS); if (null == params) { LOG.debug("Invalid JSON request: No field \"params\" defined. "); return null; } final JSONArray words = params.optJSONArray(JSON_WORDS); final String lang = params.optString(JSON_LANG, LANG_DEFAULT); if (null == words) { LOG.debug("Invalid JSON request: No field \"words\" defined. "); return null; } // Convert JSON array to array of type String final List<String> wordsToCheck = new LinkedList<String>(); for (int i = 0; i < words.length(); i++) { final String word = words.opt(i).toString(); wordsToCheck.add(word); if (Character.isUpperCase(word.codePointAt(0))) { wordsToCheck.add(word.toLowerCase()); } } return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id); }
java
private void performPermissionCheck(CmsObject cms) throws CmsPermissionViolationException { if (cms.getRequestContext().getCurrentUser().isGuestUser()) { throw new CmsPermissionViolationException(null); } }
java
private SpellCheckResponse performSpellcheckQuery(CmsSpellcheckingRequest request) { if ((null == request) || !request.isInitialized()) { return null; } final String[] wordsToCheck = request.m_wordsToCheck; final ModifiableSolrParams params = new ModifiableSolrParams(); params.set("spellcheck", "true"); params.set("spellcheck.dictionary", request.m_dictionaryToUse); params.set("spellcheck.extendedResults", "true"); // Build one string from array of words and use it as query. final StringBuilder builder = new StringBuilder(); for (int i = 0; i < wordsToCheck.length; i++) { builder.append(wordsToCheck[i] + " "); } params.set("spellcheck.q", builder.toString()); final SolrQuery query = new SolrQuery(); query.setRequestHandler("/spell"); query.add(params); try { QueryResponse qres = m_solrClient.query(query); return qres.getSpellCheckResponse(); } catch (Exception e) { LOG.debug("Exception while performing spellcheck query...", e); } return null; }
java
private void sendResponse(final HttpServletResponse res, final CmsSpellcheckingRequest request) throws IOException { final PrintWriter pw = res.getWriter(); final JSONObject response = getJsonFormattedSpellcheckResult(request); pw.println(response.toString()); pw.close(); }
java
private void setResponeHeaders(HttpServletResponse response) { response.setHeader("Cache-Control", "no-store, no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", System.currentTimeMillis()); response.setContentType("text/plain; charset=utf-8"); response.setCharacterEncoding("utf-8"); }
java
public static int toIntWithDefault(String value, int defaultValue) { int result = defaultValue; try { result = Integer.parseInt(value); } catch (@SuppressWarnings("unused") Exception e) { // Do nothing, return default. } return result; }
java
@Override public void init(NamedList args) { Object regex = args.remove(PARAM_REGEX); if (null == regex) { throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_REGEX); } try { m_regex = Pattern.compile(regex.toString()); } catch (PatternSyntaxException e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Invalid regex: " + regex, e); } Object replacement = args.remove(PARAM_REPLACEMENT); if (null == replacement) { throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_REPLACEMENT); } m_replacement = replacement.toString(); Object source = args.remove(PARAM_SOURCE); if (null == source) { throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_SOURCE); } m_source = source.toString(); Object target = args.remove(PARAM_TARGET); if (null == target) { throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_TARGET); } m_target = target.toString(); }
java
String getDefaultReturnFields() { StringBuffer fields = new StringBuffer(""); fields.append(CmsSearchField.FIELD_PATH); fields.append(','); fields.append(CmsSearchField.FIELD_INSTANCEDATE).append('_').append(getSearchLocale().toString()).append("_dt"); fields.append(','); fields.append(CmsSearchField.FIELD_INSTANCEDATE_END).append('_').append(getSearchLocale().toString()).append( "_dt"); fields.append(','); fields.append(CmsSearchField.FIELD_INSTANCEDATE_CURRENT_TILL).append('_').append( getSearchLocale().toString()).append("_dt"); fields.append(','); fields.append(CmsSearchField.FIELD_ID); fields.append(','); fields.append(CmsSearchField.FIELD_SOLR_ID); fields.append(','); fields.append(CmsSearchField.FIELD_DISPTITLE).append('_').append(getSearchLocale().toString()).append("_sort"); fields.append(','); fields.append(CmsSearchField.FIELD_LINK); return fields.toString(); }
java
private Map<String, I_CmsSearchConfigurationFacetField> getDefaultFieldFacets(boolean categoryConjunction) { Map<String, I_CmsSearchConfigurationFacetField> fieldFacets = new HashMap<String, I_CmsSearchConfigurationFacetField>(); fieldFacets.put( CmsListManager.FIELD_CATEGORIES, new CmsSearchConfigurationFacetField( CmsListManager.FIELD_CATEGORIES, null, Integer.valueOf(1), Integer.valueOf(200), null, "Category", SortOrder.index, null, Boolean.valueOf(categoryConjunction), null, Boolean.TRUE)); fieldFacets.put( CmsListManager.FIELD_PARENT_FOLDERS, new CmsSearchConfigurationFacetField( CmsListManager.FIELD_PARENT_FOLDERS, null, Integer.valueOf(1), Integer.valueOf(200), null, "Folders", SortOrder.index, null, Boolean.FALSE, null, Boolean.TRUE)); return Collections.unmodifiableMap(fieldFacets); }
java
public static String stripHtml(String html) { if (html == null) { return null; } Element el = DOM.createDiv(); el.setInnerHTML(html); return el.getInnerText(); }
java
public void setUserInfo(String username, String infoName, String value) throws CmsException { CmsUser user = m_cms.readUser(username); user.setAdditionalInfo(infoName, value); m_cms.writeUser(user); }
java
public void setTimewarpInt(String timewarp) { try { m_userSettings.setTimeWarp(Long.valueOf(timewarp).longValue()); } catch (Exception e) { m_userSettings.setTimeWarp(-1); } }
java
String buildSelect(String htmlAttributes, SelectOptions options) { return buildSelect(htmlAttributes, options.getOptions(), options.getValues(), options.getSelectedIndex()); }
java
private String getValueFromProp(final String propValue) { String value = propValue; // remove quotes value = value.trim(); if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'"))) { value = value.substring(1, value.length() - 1); } return value; }
java
public String getDynamicValue(String attribute) { return null == m_dynamicValues ? null : m_dynamicValues.get(attribute); }
java
public void setDynamicValue(String attribute, String value) { if (null == m_dynamicValues) { m_dynamicValues = new ConcurrentHashMap<String, String>(); } m_dynamicValues.put(attribute, value); }
java
public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) { final Map<String, String> galleryOptions = Maps.newHashMap(); String resultConfig = CmsStringUtil.substitute( PATTERN_EMBEDDED_GALLERY_CONFIG, configuration, new I_CmsRegexSubstitution() { public String substituteMatch(String string, Matcher matcher) { String galleryName = string.substring(matcher.start(1), matcher.end(1)); String embeddedConfig = string.substring(matcher.start(2), matcher.end(2)); galleryOptions.put(galleryName, embeddedConfig); return galleryName; } }); return CmsPair.create(resultConfig, galleryOptions); }
java
private void updateScaling() { List<I_CmsTransform> transforms = new ArrayList<>(); CmsCroppingParamBean crop = m_croppingProvider.get(); CmsImageInfoBean info = m_imageInfoProvider.get(); double wv = m_image.getElement().getParentElement().getOffsetWidth(); double hv = m_image.getElement().getParentElement().getOffsetHeight(); if (crop == null) { transforms.add( new CmsBoxFit(CmsBoxFit.Mode.scaleOnlyIfNecessary, wv, hv, info.getWidth(), info.getHeight())); } else { int wt, ht; wt = crop.getTargetWidth() >= 0 ? crop.getTargetWidth() : info.getWidth(); ht = crop.getTargetHeight() >= 0 ? crop.getTargetHeight() : info.getHeight(); transforms.add(new CmsBoxFit(CmsBoxFit.Mode.scaleOnlyIfNecessary, wv, hv, wt, ht)); if (crop.isCropped()) { transforms.add( new CmsBoxFit(CmsBoxFit.Mode.scaleAlways, wt, ht, crop.getCropWidth(), crop.getCropHeight())); transforms.add(new CmsTranslate(crop.getCropX(), crop.getCropY())); } else { transforms.add( new CmsBoxFit(CmsBoxFit.Mode.scaleAlways, wt, ht, crop.getOrgWidth(), crop.getOrgHeight())); } } CmsCompositeTransform chain = new CmsCompositeTransform(transforms); m_coordinateTransform = chain; if ((crop == null) || !crop.isCropped()) { m_region = transformRegionBack( m_coordinateTransform, CmsRectangle.fromLeftTopWidthHeight(0, 0, info.getWidth(), info.getHeight())); } else { m_region = transformRegionBack( m_coordinateTransform, CmsRectangle.fromLeftTopWidthHeight( crop.getCropX(), crop.getCropY(), crop.getCropWidth(), crop.getCropHeight())); } }
java
public static String getEncoding(CmsObject cms, CmsResource file) { CmsProperty encodingProperty = CmsProperty.getNullProperty(); try { encodingProperty = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true); } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); } return CmsEncoder.lookupEncoding(encodingProperty.getValue(""), OpenCms.getSystemInfo().getDefaultEncoding()); }
java
public String getEditorParameter(CmsObject cms, String editor, String param) { String path = OpenCms.getSystemInfo().getConfigFilePath(cms, "editors/" + editor + ".properties"); CmsVfsMemoryObjectCache cache = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache(); CmsParameterConfiguration config = (CmsParameterConfiguration)cache.getCachedObject(cms, path); if (config == null) { try { CmsFile file = cms.readFile(path); try (ByteArrayInputStream input = new ByteArrayInputStream(file.getContents())) { config = new CmsParameterConfiguration(input); // Uses ISO-8859-1, should be OK for config parameters cache.putCachedObject(cms, path, config); } } catch (CmsVfsResourceNotFoundException e) { return null; } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return null; } } return config.getString(param, null); }
java
public Date getEnd() { if (null != m_explicitEnd) { return isWholeDay() ? adjustForWholeDay(m_explicitEnd, true) : m_explicitEnd; } if ((null == m_end) && (m_series.getInstanceDuration() != null)) { m_end = new Date(m_start.getTime() + m_series.getInstanceDuration().longValue()); } return isWholeDay() && !m_series.isWholeDay() ? adjustForWholeDay(m_end, true) : m_end; }
java
public void setEnd(Date endDate) { if ((null == endDate) || getStart().after(endDate)) { m_explicitEnd = null; } else { m_explicitEnd = endDate; } }
java
private Date adjustForWholeDay(Date date, boolean isEnd) { Calendar result = new GregorianCalendar(); result.setTime(date); result.set(Calendar.HOUR_OF_DAY, 0); result.set(Calendar.MINUTE, 0); result.set(Calendar.SECOND, 0); result.set(Calendar.MILLISECOND, 0); if (isEnd) { result.add(Calendar.DATE, 1); } return result.getTime(); }
java
private boolean isSingleMultiDay() { long duration = getEnd().getTime() - getStart().getTime(); if (duration > I_CmsSerialDateValue.DAY_IN_MILLIS) { return true; } if (isWholeDay() && (duration <= I_CmsSerialDateValue.DAY_IN_MILLIS)) { return false; } Calendar start = new GregorianCalendar(); start.setTime(getStart()); Calendar end = new GregorianCalendar(); end.setTime(getEnd()); if (start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)) { return false; } return true; }
java
public static void checkCreateUpload(CmsObject cms, CmsUgcConfiguration config, String name, long size) throws CmsUgcException { if (!config.getUploadParentFolder().isPresent()) { String message = Messages.get().container(Messages.ERR_NO_UPLOADS_ALLOWED_0).key( cms.getRequestContext().getLocale()); throw new CmsUgcException(CmsUgcConstants.ErrorCode.errNoUploadAllowed, message); } if (config.getMaxUploadSize().isPresent()) { if (config.getMaxUploadSize().get().longValue() < size) { String message = Messages.get().container(Messages.ERR_UPLOAD_TOO_BIG_1, name).key( cms.getRequestContext().getLocale()); throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMaxUploadSizeExceeded, message); } } if (config.getValidExtensions().isPresent()) { List<String> validExtensions = config.getValidExtensions().get(); boolean foundExtension = false; for (String extension : validExtensions) { if (name.toLowerCase().endsWith(extension.toLowerCase())) { foundExtension = true; break; } } if (!foundExtension) { String message = Messages.get().container(Messages.ERR_UPLOAD_FILE_EXTENSION_NOT_ALLOWED_1, name).key( cms.getRequestContext().getLocale()); throw new CmsUgcException(CmsUgcConstants.ErrorCode.errInvalidExtension, message); } } }
java
protected void addFacetPart(CmsSolrQuery query) { StringBuffer value = new StringBuffer(); value.append("{!key=").append(m_config.getName()); addFacetOptions(value); if (m_config.getIgnoreAllFacetFilters() || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) { value.append(" ex=").append(m_config.getIgnoreTags()); } value.append("}"); value.append(m_config.getRange()); query.add("facet.range", value.toString()); }
java
private void setFittingWeekDay(Calendar date) { date.set(Calendar.DAY_OF_MONTH, 1); int weekDayFirst = date.get(Calendar.DAY_OF_WEEK); int firstFittingWeekDay = (((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS) - weekDayFirst) % I_CmsSerialDateValue.NUM_OF_WEEKDAYS) + 1; int fittingWeekDay = firstFittingWeekDay + (I_CmsSerialDateValue.NUM_OF_WEEKDAYS * m_weekOfMonth.ordinal()); if (fittingWeekDay > date.getActualMaximum(Calendar.DAY_OF_MONTH)) { fittingWeekDay -= I_CmsSerialDateValue.NUM_OF_WEEKDAYS; } date.set(Calendar.DAY_OF_MONTH, fittingWeekDay); }
java
public VerticalLayout getEmptyLayout() { m_emptyLayout = CmsVaadinUtils.getInfoLayout(CmsOuTreeType.USER.getEmptyMessageKey()); setVisible(size() > 0); m_emptyLayout.setVisible(size() == 0); return m_emptyLayout; }
java
public List<CmsUser> getVisibleUser() { if (!m_fullyLoaded) { return m_users; } if (size() == m_users.size()) { return m_users; } List<CmsUser> directs = new ArrayList<CmsUser>(); for (CmsUser user : m_users) { if (!m_indirects.contains(user)) { directs.add(user); } } return directs; }
java
String getStatus(CmsUser user, boolean disabled, boolean newUser) { if (disabled) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_0); } if (newUser) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_0); } if (OpenCms.getLoginManager().isUserTempDisabled(user.getName())) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_UNLOCK_USER_STATUS_0); } if (isUserPasswordReset(user)) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_0); } return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_ACTIVE_0); }
java
String getStatusHelp(CmsUser user, boolean disabled, boolean newUser) { if (disabled) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_DISABLED_HELP_0); } if (newUser) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_INACTIVE_HELP_0); } if (isUserPasswordReset(user)) { return CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_PASSWORT_RESET_HELP_0); } long lastLogin = user.getLastlogin(); return CmsVaadinUtils.getMessageText( Messages.GUI_USERMANAGEMENT_USER_ACTIVE_HELP_1, CmsDateUtil.getDateTime(new Date(lastLogin), DateFormat.SHORT, A_CmsUI.get().getLocale())); }
java
boolean isUserPasswordReset(CmsUser user) { if (USER_PASSWORD_STATUS.containsKey(user.getId())) { //Check if user was checked before if (!USER_PASSWORD_STATUS.get(user.getId()).booleanValue()) { // was false before, false->true is never done without changing map return false; } if (m_checkedUserPasswordReset.contains(user.getId())) { //was true before, true->false happens when user resets password. Only check one time per table load. return true; //Set gets flushed on reloading table } } CmsUser currentUser = user; if (user.getAdditionalInfo().size() < 3) { try { currentUser = m_cms.readUser(user.getId()); } catch (CmsException e) { LOG.error("Can not read user", e); } } if (currentUser.getAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET) != null) { USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(true)); m_checkedUserPasswordReset.add(currentUser.getId()); return true; } USER_PASSWORD_STATUS.put(currentUser.getId(), new Boolean(false)); return false; }
java
public CmsSolrQuery getQuery(CmsObject cms) { final CmsSolrQuery query = new CmsSolrQuery(); // set categories query.setCategories(m_categories); // set container types if (null != m_containerTypes) { query.addFilterQuery(CmsSearchField.FIELD_CONTAINER_TYPES, m_containerTypes, false, false); } // Set date created time filter query.addFilterQuery( CmsSearchUtil.getDateCreatedTimeRangeFilterQuery( CmsSearchField.FIELD_DATE_CREATED, getDateCreatedRange().m_startTime, getDateCreatedRange().m_endTime)); // Set date last modified time filter query.addFilterQuery( CmsSearchUtil.getDateCreatedTimeRangeFilterQuery( CmsSearchField.FIELD_DATE_LASTMODIFIED, getDateLastModifiedRange().m_startTime, getDateLastModifiedRange().m_endTime)); // set scope / folders to search in m_foldersToSearchIn = new ArrayList<String>(); addFoldersToSearchIn(m_folders); addFoldersToSearchIn(m_galleries); setSearchFolders(cms); query.addFilterQuery( CmsSearchField.FIELD_PARENT_FOLDERS, new ArrayList<String>(m_foldersToSearchIn), false, true); if (!m_ignoreSearchExclude) { // Reference for the values: CmsGallerySearchIndex.java, field EXCLUDE_PROPERTY_VALUES query.addFilterQuery( "-" + CmsSearchField.FIELD_SEARCH_EXCLUDE, Arrays.asList( new String[] { A_CmsSearchIndex.PROPERTY_SEARCH_EXCLUDE_VALUE_ALL, A_CmsSearchIndex.PROPERTY_SEARCH_EXCLUDE_VALUE_GALLERY}), false, true); } // set matches per page query.setRows(new Integer(m_matchesPerPage)); // set resource types if (null != m_resourceTypes) { List<String> resourceTypes = new ArrayList<>(m_resourceTypes); if (m_resourceTypes.contains(CmsResourceTypeFunctionConfig.TYPE_NAME) && !m_resourceTypes.contains(CmsXmlDynamicFunctionHandler.TYPE_FUNCTION)) { resourceTypes.add(CmsXmlDynamicFunctionHandler.TYPE_FUNCTION); } query.setResourceTypes(resourceTypes); } // set result page query.setStart(new Integer((m_resultPage - 1) * m_matchesPerPage)); // set search locale if (null != m_locale) { query.setLocales(CmsLocaleManager.getLocale(m_locale)); } // set search words if (null != m_words) { query.setQuery(m_words); } // set sort order query.setSort(getSort().getFirst(), getSort().getSecond()); // set result collapsing by id query.addFilterQuery("{!collapse field=id}"); query.setFields(CmsGallerySearchResult.getRequiredSolrFields()); if ((m_allowedFunctions != null) && !m_allowedFunctions.isEmpty()) { String functionFilter = "((-type:(" + CmsXmlDynamicFunctionHandler.TYPE_FUNCTION + " OR " + CmsResourceTypeFunctionConfig.TYPE_NAME + ")) OR (id:("; Iterator<CmsUUID> it = m_allowedFunctions.iterator(); while (it.hasNext()) { CmsUUID id = it.next(); functionFilter += id.toString(); if (it.hasNext()) { functionFilter += " OR "; } } functionFilter += ")))"; query.addFilterQuery(functionFilter); } return query; }
java