001/* 002 * Copyright 2020 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.plugins.contentio.csv; 017 018import java.io.IOException; 019import java.util.ArrayList; 020import java.util.Arrays; 021import java.util.Collection; 022import java.util.HashMap; 023import java.util.List; 024import java.util.Map; 025import java.util.Map.Entry; 026import java.util.Objects; 027import java.util.Optional; 028import java.util.Set; 029import java.util.function.Function; 030import java.util.stream.Collectors; 031import java.util.stream.Stream; 032 033import org.apache.avalon.framework.component.Component; 034import org.apache.avalon.framework.service.ServiceException; 035import org.apache.avalon.framework.service.ServiceManager; 036import org.apache.avalon.framework.service.Serviceable; 037import org.apache.commons.lang3.LocaleUtils; 038import org.apache.commons.lang3.StringUtils; 039import org.supercsv.io.ICsvListReader; 040import org.supercsv.util.Util; 041 042import org.ametys.cms.ObservationConstants; 043import org.ametys.cms.contenttype.ContentAttributeDefinition; 044import org.ametys.cms.contenttype.ContentType; 045import org.ametys.cms.contenttype.ContentTypeExtensionPoint; 046import org.ametys.cms.data.ContentValue; 047import org.ametys.cms.data.type.BaseMultilingualStringElementType; 048import org.ametys.cms.data.type.impl.MultilingualStringRepositoryElementType; 049import org.ametys.cms.indexing.solr.SolrIndexHelper; 050import org.ametys.cms.repository.Content; 051import org.ametys.cms.repository.ContentQueryHelper; 052import org.ametys.cms.repository.ModifiableDefaultContent; 053import org.ametys.cms.repository.ModifiableWorkflowAwareContent; 054import org.ametys.cms.workflow.AbstractContentWorkflowComponent; 055import org.ametys.cms.workflow.ContentWorkflowHelper; 056import org.ametys.cms.workflow.CreateContentFunction; 057import org.ametys.core.util.I18nUtils; 058import org.ametys.plugins.contentio.csv.SynchronizeModeEnumerator.ImportMode; 059import org.ametys.plugins.contentio.in.ContentImportException; 060import org.ametys.plugins.repository.AmetysObjectIterable; 061import org.ametys.plugins.repository.AmetysObjectResolver; 062import org.ametys.plugins.repository.data.holder.group.ModelAwareRepeater; 063import org.ametys.plugins.repository.data.holder.group.ModelAwareRepeaterEntry; 064import org.ametys.plugins.repository.data.holder.group.Repeater; 065import org.ametys.plugins.repository.data.holder.values.SynchronizableRepeater; 066import org.ametys.plugins.repository.data.holder.values.SynchronizableValue; 067import org.ametys.plugins.repository.data.holder.values.SynchronizableValue.Mode; 068import org.ametys.plugins.repository.data.type.ModelItemTypeConstants; 069import org.ametys.plugins.repository.metadata.MultilingualString; 070import org.ametys.plugins.repository.metadata.MultilingualStringHelper; 071import org.ametys.plugins.repository.query.expression.AndExpression; 072import org.ametys.plugins.repository.query.expression.Expression.Operator; 073import org.ametys.plugins.repository.query.expression.ExpressionContext; 074import org.ametys.plugins.repository.query.expression.MultilingualStringExpression; 075import org.ametys.plugins.repository.query.expression.StringExpression; 076import org.ametys.runtime.model.ElementDefinition; 077import org.ametys.runtime.model.ModelItem; 078import org.ametys.runtime.model.ModelViewItemGroup; 079import org.ametys.runtime.model.View; 080import org.ametys.runtime.model.ViewElement; 081import org.ametys.runtime.model.ViewElementAccessor; 082import org.ametys.runtime.model.ViewItem; 083import org.ametys.runtime.model.type.ElementType; 084import org.ametys.runtime.plugin.component.AbstractLogEnabled; 085 086import com.opensymphony.workflow.WorkflowException; 087 088/** 089 * Import contents from an uploaded CSV file. 090 */ 091public class CSVImporter extends AbstractLogEnabled implements Component, Serviceable 092{ 093 094 /** Avalon Role */ 095 public static final String ROLE = CSVImporter.class.getName(); 096 097 /** Result key containing updated content's ids */ 098 public static final String RESULT_CONTENT_IDS = "contentIds"; 099 /** Result key containing number of errors */ 100 public static final String RESULT_NB_ERRORS = "nbErrors"; 101 /** Result key containing number of warnings */ 102 public static final String RESULT_NB_WARNINGS = "nbWarnings"; 103 104 private ContentWorkflowHelper _contentWorkflowHelper; 105 106 private ContentTypeExtensionPoint _contentTypeEP; 107 108 private AmetysObjectResolver _resolver; 109 110 private I18nUtils _i18nUtils; 111 112 private SolrIndexHelper _solrIndexHelper; 113 114 public void service(ServiceManager smanager) throws ServiceException 115 { 116 _resolver = (AmetysObjectResolver) smanager.lookup(AmetysObjectResolver.ROLE); 117 _contentTypeEP = (ContentTypeExtensionPoint) smanager.lookup(ContentTypeExtensionPoint.ROLE); 118 _contentWorkflowHelper = (ContentWorkflowHelper) smanager.lookup(ContentWorkflowHelper.ROLE); 119 _i18nUtils = (I18nUtils) smanager.lookup(I18nUtils.ROLE); 120 _solrIndexHelper = (SolrIndexHelper) smanager.lookup(SolrIndexHelper.ROLE); 121 } 122 123 /** 124 * Extract contents from CSV file 125 * @param mapping mapping of content attributes and CSV file header 126 * @param view View of importing content 127 * @param contentType content type to import 128 * @param listReader mapReader to parse CSV file 129 * @param createAction creation action id 130 * @param editAction edition action id 131 * @param workflowName workflow name 132 * @param language language of created content. 133 * @param importMode The import mode 134 * @param parentContent Optional parent content 135 * @return list of created contents 136 * @throws IOException IOException while reading CSV 137 */ 138 public Map<String, Object> importContentsFromCSV(Map<String, Object> mapping, View view, ContentType contentType, ICsvListReader listReader, int createAction, int editAction, String workflowName, String language, ImportMode importMode, Optional< ? extends Content> parentContent) throws IOException 139 { 140 try 141 { 142 _solrIndexHelper.pauseSolrCommitForEvents(_getIndexationEvents()); 143 144 List<String> contentIds = new ArrayList<>(); 145 String[] columns = listReader.getHeader(true); 146 int nbErrors = 0; 147 int nbWarnings = 0; 148 List<String> row = null; 149 150 while ((row = listReader.read()) != null) 151 { 152 try 153 { 154 if (listReader.length() != columns.length) 155 { 156 getLogger().error("[{}] Import from CSV file: content skipped because of invalid row: {}", contentType.getId(), row); 157 nbErrors++; 158 continue; 159 } 160 161 Map<String, String> rowMap = new HashMap<>(); 162 Util.filterListToMap(rowMap, columns, row); 163 List<ViewItem> errors = new ArrayList<>(); 164 SynchronizeResult synchronizeResult = _processContent(view, rowMap, contentType, mapping, createAction, editAction, workflowName, language, errors, importMode, parentContent); 165 Optional<ModifiableWorkflowAwareContent> content = synchronizeResult.content(); 166 167 // If we are in CREATE_ONLY mode but content was not created, do not add it to the contents list 168 if (content.isPresent() && (importMode != ImportMode.CREATE_ONLY || synchronizeResult.isCreated())) 169 { 170 contentIds.add(content.get().getId()); 171 } 172 173 if (!errors.isEmpty()) 174 { 175 nbWarnings++; 176 } 177 } 178 catch (Exception e) 179 { 180 nbErrors++; 181 getLogger().error("[{}] Import from CSV file: error importing the content on line {}", contentType.getId(), listReader.getLineNumber(), e); 182 } 183 } 184 185 Map<String, Object> results = new HashMap<>(); 186 results.put(RESULT_CONTENT_IDS, contentIds); 187 results.put(RESULT_NB_ERRORS, nbErrors); 188 results.put(RESULT_NB_WARNINGS, nbWarnings); 189 return results; 190 } 191 finally 192 { 193 _solrIndexHelper.restartSolrCommitForEvents(_getIndexationEvents()); 194 } 195 } 196 197 private String[] _getIndexationEvents() 198 { 199 return new String[] { 200 ObservationConstants.EVENT_CONTENT_ADDED, 201 ObservationConstants.EVENT_CONTENT_MODIFIED, 202 ObservationConstants.EVENT_CONTENT_WORKFLOW_CHANGED, 203 ObservationConstants.EVENT_CONTENT_VALIDATED 204 }; 205 } 206 207 private SynchronizeResult _processContent(View view, Map<String, String> row, ContentType contentType, Map<String, Object> mapping, int createAction, int editAction, String workflowName, String language, List<ViewItem> errors, ImportMode importMode, Optional< ? extends Content> parentContent) throws Exception 208 { 209 @SuppressWarnings("unchecked") 210 List<String> attributeIdNames = (List<String>) mapping.get(ImportCSVFileHelper.NESTED_MAPPING_ID); 211 @SuppressWarnings("unchecked") 212 Map<String, Object> mappingValues = (Map<String, Object>) mapping.get(ImportCSVFileHelper.NESTED_MAPPING_VALUES); 213 214 SynchronizeResult synchronizeResult = _synchronizeContent(row, contentType, view, attributeIdNames, mappingValues, createAction, editAction, workflowName, language, errors, importMode, parentContent); 215 return synchronizeResult; 216 } 217 218 private void _editContent(int editAction, View view, Map<String, Object> values, ModifiableWorkflowAwareContent content) throws WorkflowException 219 { 220 Collection<ModelItem> viewItemsDiff = content.getDifferences(view, values); 221 if (!viewItemsDiff.isEmpty()) 222 { 223 _contentWorkflowHelper.editContent(content, values, editAction, View.of(viewItemsDiff.toArray(ModelItem[]::new))); 224 } 225 } 226 227 private Object _getValue(Optional<? extends Content> parentContent, ViewItem viewItem, Map<String, Object> mapping, Map<String, String> row, int createAction, int editAction, String language, List<ViewItem> errors, String prefix, ImportMode importMode) throws Exception 228 { 229 if (viewItem instanceof ViewElement viewElement) 230 { 231 ElementDefinition elementDefinition = viewElement.getDefinition(); 232 if (elementDefinition instanceof ContentAttributeDefinition contentAttributeDefinition && viewElement instanceof ViewElementAccessor viewElementAccessor) 233 { 234 return _getContentAttributeDefinitionValues(parentContent, mapping, row, createAction, editAction, language, viewElementAccessor, contentAttributeDefinition, errors, importMode); 235 } 236 else 237 { 238 return _getAttributeDefinitionValues(parentContent, mapping, row, elementDefinition, language, prefix); 239 } 240 } 241 else if (viewItem instanceof ModelViewItemGroup modelViewItemGroup) 242 { 243 List<ViewItem> children = modelViewItemGroup.getViewItems(); 244 @SuppressWarnings("unchecked") 245 Map<String, Object> nestedMap = (Map<String, Object>) mapping.get(viewItem.getName()); 246 @SuppressWarnings("unchecked") 247 Map<String, Object> nestedMapValues = (Map<String, Object>) (nestedMap.get(ImportCSVFileHelper.NESTED_MAPPING_VALUES)); 248 if (ModelItemTypeConstants.REPEATER_TYPE_ID.equals(modelViewItemGroup.getDefinition().getType().getId())) 249 { 250 return _getRepeaterValues(parentContent, modelViewItemGroup, row, createAction, editAction, language, children, nestedMap, errors, prefix, importMode); 251 } 252 else 253 { 254 return _getCompositeValues(parentContent, viewItem, row, createAction, editAction, language, children, nestedMapValues, errors, prefix, importMode); 255 } 256 } 257 else 258 { 259 errors.add(viewItem); 260 throw new RuntimeException("Import from CSV file: unsupported type of ViewItem for view: " + viewItem.getName()); 261 } 262 } 263 264 private Map<String, Object> _getCompositeValues(Optional<? extends Content> parentContent, ViewItem viewItem, Map<String, String> row, int createAction, int editAction, 265 String language, List<ViewItem> children, Map<String, Object> nestedMapValues, List<ViewItem> errors, String prefix, ImportMode importMode) 266 { 267 Map<String, Object> compositeValues = new HashMap<>(); 268 for (ViewItem child : children) 269 { 270 try 271 { 272 compositeValues.put(child.getName(), _getValue(parentContent, child, nestedMapValues, row, createAction, editAction, language, errors, prefix + viewItem.getName() + ModelItem.ITEM_PATH_SEPARATOR, importMode)); 273 } 274 catch (Exception e) 275 { 276 errors.add(viewItem); 277 getLogger().error("Import from CSV file: error while trying to get values for view: {}", viewItem.getName(), e); 278 } 279 } 280 return compositeValues; 281 } 282 283 private SynchronizableRepeater _getRepeaterValues(Optional<? extends Content> parentContent, ModelViewItemGroup viewItem, Map<String, String> row, int createAction, int editAction, String language, 284 List<ViewItem> children, Map<String, Object> nestedMap, List<ViewItem> errors, String prefix, ImportMode importMode) 285 { 286 @SuppressWarnings("unchecked") 287 Map<String, Object> mappingValues = (Map<String, Object>) nestedMap.get(ImportCSVFileHelper.NESTED_MAPPING_VALUES); 288 @SuppressWarnings("unchecked") 289 List<String> attributeIdNames = (List<String>) nestedMap.getOrDefault(ImportCSVFileHelper.NESTED_MAPPING_ID, List.of()); 290 Map<String, Object> repeaterValues = new HashMap<>(); 291 List<Map<String, Object>> repeaterValuesList = new ArrayList<>(); 292 List<Integer> indexList = new ArrayList<>(); 293 294 Optional<ModelAwareRepeater> repeater = parentContent.map(p -> p.getRepeater(prefix + viewItem.getName())); 295 296 if (repeater.isPresent() && !attributeIdNames.isEmpty() && _allAttributesFilled(mappingValues, attributeIdNames)) 297 { 298 indexList = repeater.get() 299 .getEntries() 300 .stream() 301 .filter(entry -> 302 { 303 return attributeIdNames.stream() 304 .allMatch(attributeName -> 305 { 306 // Get the entry value 307 Object entryValue = entry.getValue(attributeName); 308 309 // Get the row value for the attribute (from CSV file) 310 Object rowValue = Optional.of(attributeName) 311 .map(mappingValues::get) 312 .map(String.class::cast) 313 .map(row::get) 314 .orElse(null); 315 316 // Transform the row value to the right type then compare entry value and row value 317 return Optional.of(attributeName) 318 .map(viewItem::getModelViewItem) 319 .map(ViewElement.class::cast) 320 .map(ViewElement::getDefinition) 321 .map(ElementDefinition::getType) 322 .map(def -> def.castValue(rowValue)) 323 .map(value -> value.equals(entryValue)) 324 .orElse(false); 325 }); 326 }) 327 .map(ModelAwareRepeaterEntry::getPosition) 328 .collect(Collectors.toList()); 329 } 330 331 // If entries match with attribute ids, we replace the first entries 332 // Else if the repeater exists, we assume we are on the next model item after the last one 333 // Else (the repeater doesn't exist, we set the rowIndex to first index 334 Integer rowIndex = indexList.isEmpty() ? repeater.map(Repeater::getSize).orElse(1) : indexList.get(0); 335 336 for (ViewItem child : children) 337 { 338 try 339 { 340 Object entryValues = _getValue(parentContent, child, mappingValues, row, createAction, editAction, language, errors, prefix + viewItem.getName() + "[" + rowIndex + "]" + ModelItem.ITEM_PATH_SEPARATOR, importMode); 341 if (entryValues != null) 342 { 343 repeaterValues.put(child.getName(), entryValues); 344 } 345 } 346 catch (Exception e) 347 { 348 errors.add(viewItem); 349 getLogger().error("Import from CSV file: error while trying to get values for view: {}", viewItem.getName(), e); 350 } 351 } 352 repeaterValuesList.add(repeaterValues); 353 354 if (indexList.isEmpty()) 355 { 356 return SynchronizableRepeater.appendOrRemove(repeaterValuesList, Set.of()); 357 } 358 else 359 { 360 // If several rows match the id, only replace the first but add a warning 361 if (indexList.size() > 1) 362 { 363 errors.add(viewItem); 364 } 365 return SynchronizableRepeater.replace(repeaterValuesList, List.of(rowIndex)); 366 } 367 } 368 369 private Object _getContentAttributeDefinitionValues(Optional<? extends Content> parentContent, Map<String, Object> mapping, Map<String, String> row, 370 int createAction, int editAction, String language, ViewElementAccessor viewElementAccessor, ContentAttributeDefinition contentAttributeDefinition, List<ViewItem> errors, ImportMode importMode) throws Exception 371 { 372 String contentTypeId = contentAttributeDefinition.getContentTypeId(); 373 ContentType contentType = _contentTypeEP.getExtension(contentTypeId); 374 @SuppressWarnings("unchecked") 375 Map<String, Object> nestedMap = (Map<String, Object>) mapping.get(viewElementAccessor.getName()); 376 @SuppressWarnings("unchecked") 377 Map<String, Object> mappingValues = (Map<String, Object>) nestedMap.get(ImportCSVFileHelper.NESTED_MAPPING_VALUES); 378 @SuppressWarnings("unchecked") 379 List<String> attributeIdNames = (List<String>) nestedMap.get(ImportCSVFileHelper.NESTED_MAPPING_ID); 380 if (_allAttributesFilled(mappingValues, attributeIdNames)) 381 { 382 View view = new View(); 383 view.addViewItems(viewElementAccessor.getViewItems()); 384 SynchronizeResult synchronizeResult = _synchronizeContent(row, contentType, view, attributeIdNames, mappingValues, createAction, editAction, null, language, errors, importMode, parentContent); 385 386 Optional<ModifiableWorkflowAwareContent> attachedContent = synchronizeResult.content(); 387 388 if (synchronizeResult.hasKey && attachedContent.isEmpty() && importMode == ImportMode.UPDATE_ONLY) 389 { 390 errors.add(viewElementAccessor); 391 } 392 393 // If content is multiple, we keep the old value list and we check if content was already inside, and add it otherwise 394 if (attachedContent.isPresent() && contentAttributeDefinition.isMultiple()) 395 { 396 Optional<ContentValue[]> multipleContents = parentContent.map(c -> c.getValue(contentAttributeDefinition.getPath())); 397 if (!_containsContent(attachedContent.get(), multipleContents)) 398 { 399 // If there is no list or if it is empty, add it. Otherwise, we have to check if it is inside. 400 SynchronizableValue syncValue = new SynchronizableValue(List.of(attachedContent.get())); 401 syncValue.setMode(Mode.APPEND); 402 return syncValue; 403 } 404 else if (multipleContents.isPresent()) 405 { 406 // return existing values as otherwise the values would be erased 407 SynchronizableValue syncValue = new SynchronizableValue(Arrays.asList(multipleContents.get())); 408 syncValue.setMode(Mode.REPLACE); 409 return syncValue; 410 } 411 } 412 else 413 { 414 return attachedContent.orElse(null); 415 } 416 } 417 return null; 418 } 419 420 private boolean _containsContent(ModifiableWorkflowAwareContent attachedContent, Optional<ContentValue[]> multipleContents) 421 { 422 return multipleContents 423 .map(Arrays::stream) 424 .orElseGet(Stream::empty) 425 .map(ContentValue::getContentId) 426 .anyMatch(valueFromContent -> valueFromContent.equals(attachedContent.getId())); 427 } 428 429 private Object _getAttributeDefinitionValues(Optional<? extends Content> parentContent, Map<String, Object> mapping, Map<String, String> row, ElementDefinition elementDefinition, String language, String prefix) 430 { 431 ElementType elementType = elementDefinition.getType(); 432 String elementName = elementDefinition.getName(); 433 String elementColumn = (String) mapping.get(elementName); 434 String valueAsString = row.get(elementColumn); 435 436 Object value; 437 if (elementType instanceof BaseMultilingualStringElementType && !MultilingualStringHelper.matchesMultilingualStringPattern(valueAsString)) 438 { 439 MultilingualString multilingualString = new MultilingualString(); 440 multilingualString.add(LocaleUtils.toLocale(language), valueAsString); 441 value = multilingualString; 442 } 443 else 444 { 445 value = elementType.castValue(valueAsString); 446 } 447 448 if (elementDefinition.isMultiple()) 449 { 450 // Build path with index for repeaters. 451 String pathWithIndex = prefix + elementDefinition.getName(); 452 453 Optional<Object[]> values = parentContent.map(c -> c.getValue(pathWithIndex)); 454 if (!_containsValue(value, parentContent.map(c -> c.getValue(pathWithIndex)))) 455 { 456 // If there is no list or if it is empty, add it. Otherwise, we have to check if it is inside. 457 // If there is no parentContent, still append as we want to fill the values map anyway. 458 SynchronizableValue syncValue = new SynchronizableValue(value != null ? List.of(value) : List.of()); 459 syncValue.setMode(Mode.APPEND); 460 return syncValue; 461 } 462 else if (values.isPresent()) 463 { 464 // return existing values as otherwise the values would be erased 465 SynchronizableValue syncValue = new SynchronizableValue(Arrays.asList(values.get())); 466 syncValue.setMode(Mode.REPLACE); 467 return syncValue; 468 } 469 } 470 else 471 { 472 return value; 473 } 474 475 return null; 476 } 477 478 private boolean _containsValue(Object value, Optional<Object[]> multipleValues) 479 { 480 return multipleValues 481 .map(Arrays::stream) 482 .orElseGet(Stream::empty) 483 .anyMatch(valueFromContent -> valueFromContent.equals(value)); 484 } 485 486 private SynchronizeResult _synchronizeContent(Map<String, String> row, ContentType contentType, View view, List<String> attributeIdNames, Map<String, Object> mappingValues, int createAction, int editAction, String workflowName, String language, List<ViewItem> errors, ImportMode importMode, Optional< ? extends Content> parentContent) throws Exception 487 { 488 SynchronizeResult synchronizeResult = _getOrCreateContent(mappingValues, row, contentType, Optional.ofNullable(workflowName), createAction, language, attributeIdNames, parentContent, importMode); 489 Optional<ModifiableWorkflowAwareContent> content = synchronizeResult.content(); 490 491 // If we are on CREATE_ONLY mode and content already exists, or if we are on UPDATE_ONLY mode and content does not exists, stop recursivity 492 if (importMode == ImportMode.CREATE_ONLY && !synchronizeResult.isCreated() || importMode == ImportMode.UPDATE_ONLY && content.isEmpty()) 493 { 494 return synchronizeResult; 495 } 496 497 Map<String, Object> values = _getValues(content, row, view, mappingValues, createAction, editAction, language, errors, importMode); 498 if (!values.isEmpty()) 499 { 500 if (content.isEmpty()) 501 { 502 // Throw this exception only when values are filled, as an empty content should not trigger any warning 503 throw new ContentImportException("Can't create and fill content of content type '" + contentType.getId() + "' and following values '" + values + "' : at least one of those identifiers is null : " + attributeIdNames); 504 } 505 else 506 { 507 try 508 { 509 _editContent(editAction, view, values, content.get()); 510 } 511 catch (WorkflowException e) 512 { 513 errors.addAll(view.getViewItems()); 514 getLogger().error("[{}] Import from CSV file: error editing the content [{}] after import, some values have not been set", contentType.getId(), content.get().getId(), e); 515 } 516 } 517 } 518 519 return synchronizeResult; 520 } 521 522 private SynchronizeResult _getOrCreateContent(Map<String, Object> mapping, Map<String, String> row, ContentType contentType, Optional<String> workflowName, int createAction, String language, List<String> attributeIdNames, Optional<? extends Content> parentContent, ImportMode importMode) throws ContentImportException, WorkflowException 523 { 524 AndExpression expression = new AndExpression(); 525 List<String> values = new ArrayList<>(); 526 527 for (String attributeName : attributeIdNames) 528 { 529 ModelItem modelItem = contentType.getModelItem(attributeName); 530 String attributePath = (String) mapping.get(attributeName); 531 String value = row.get(attributePath); 532 values.add(value); 533 534 if (value == null) 535 { 536 return new SynchronizeResult(false, Optional.empty(), false); 537 } 538 539 // Get content 540 if (modelItem.getType() instanceof MultilingualStringRepositoryElementType) 541 { 542 expression.add(new MultilingualStringExpression(attributeName, Operator.EQ, value, language)); 543 } 544 else 545 { 546 expression.add(new StringExpression(attributeName, Operator.EQ, value)); 547 } 548 } 549 550 expression.add(_contentTypeEP.createHierarchicalCTExpression(contentType.getId())); 551 552 if (!contentType.isMultilingual()) 553 { 554 expression.add(new StringExpression("language", Operator.EQ, language, ExpressionContext.newInstance().withInternal(true))); 555 } 556 557 String xPathQuery = ContentQueryHelper.getContentXPathQuery(expression); 558 AmetysObjectIterable<ModifiableDefaultContent> matchingContents = _resolver.query(xPathQuery); 559 if (matchingContents.getSize() > 1) 560 { 561 throw new ContentImportException("More than one content found for type " + contentType.getId() + " with " 562 + attributeIdNames + " as identifier and " + values + " as value"); 563 } 564 else if (matchingContents.getSize() == 1) 565 { 566 return new SynchronizeResult(false, Optional.of(matchingContents.iterator().next()), true); 567 } 568 else if (importMode == ImportMode.UPDATE_ONLY) 569 { 570 return new SynchronizeResult(false, Optional.empty(), true); 571 } 572 573 // Create content 574 575 if (contentType.isAbstract()) 576 { 577 throw new ContentImportException("Can not create content for type " + contentType.getId() + " with " 578 + attributeIdNames + " as identifier and " + values + " as value, the content type is abstract"); 579 } 580 581 Map<String, Object> result; 582 String title; 583 if (mapping.containsKey("title")) 584 { 585 title = row.get(mapping.get("title")); 586 } 587 else 588 { 589 title = _i18nUtils.translate(contentType.getDefaultTitle(), language); 590 } 591 592 593 String finalWorkflowName = workflowName.or(contentType::getDefaultWorkflowName) 594 .orElseThrow(() -> new ContentImportException("No workflow specified for content type " + contentType.getId() + " with " 595 + attributeIdNames + " as identifier and " + values + " as value")); 596 597 Map<String, Object> inputs = new HashMap<>(); 598 inputs.put(CreateContentFunction.INITIAL_VALUE_SUPPLIER, new Function<List<String>, Object>() 599 { 600 public Object apply(List<String> keys) 601 { 602 // Browse the mapping to find the column related to the attribute 603 Object nestedValue = mapping; 604 for (String key : keys) 605 { 606 nestedValue = ((Map) nestedValue).get(key); 607 // If nestedValue is null, the attribute is absent from the map, no value can be found 608 if (nestedValue == null) 609 { 610 return null; 611 } 612 // If nestedValue is a map, the key is a complex element such a content or a composite, 613 // we need to keep browsing the map to find the column 614 if (nestedValue instanceof Map) 615 { 616 nestedValue = ((Map) nestedValue).get(ImportCSVFileHelper.NESTED_MAPPING_VALUES); 617 } 618 } 619 620 // Get the value of the attribute for the current row 621 return row.get(nestedValue.toString()); 622 } 623 }); 624 625 parentContent.ifPresent(content -> inputs.put(CreateContentFunction.PARENT_CONTEXT_VALUE, content.getId())); 626 627 // CONTENTIO-253 To avoid issue with title starting with a non letter character, we prefix the name with the contentTypeId 628 String prefix = StringUtils.substringAfterLast(contentType.getId(), ".").toLowerCase(); 629 String contentName = prefix + "-" + title; 630 631 if (contentType.isMultilingual()) 632 { 633 inputs.put(CreateContentFunction.CONTENT_LANGUAGE_KEY, language); 634 result = _contentWorkflowHelper.createContent(finalWorkflowName, createAction, contentName, Map.of(language, title), new String[] {contentType.getId()}, null, inputs); 635 } 636 else 637 { 638 result = _contentWorkflowHelper.createContent(finalWorkflowName, createAction, contentName, title, new String[] {contentType.getId()}, null, language, inputs); 639 } 640 641 ModifiableWorkflowAwareContent content = (ModifiableWorkflowAwareContent) result.get(AbstractContentWorkflowComponent.CONTENT_KEY); 642 return new SynchronizeResult(true, Optional.of(content), true); 643 } 644 645 private Map<String, Object> _getValues(Optional<ModifiableWorkflowAwareContent> content, Map<String, String> row, View view, Map<String, Object> mappingValues, int createAction, int editAction, String language, List<ViewItem> errors, ImportMode importMode) 646 { 647 Map<String, Object> values = new HashMap<>(); 648 649 for (ViewItem viewItem : view.getViewItems()) 650 { 651 try 652 { 653 Object value = _getValue(content, viewItem, mappingValues, row, createAction, editAction, language, errors, StringUtils.EMPTY, importMode); 654 if (value != null) 655 { 656 values.put(viewItem.getName(), value); 657 } 658 } 659 catch (Exception e) 660 { 661 errors.add(viewItem); 662 getLogger().error("Import from CSV file: error while trying to get values for item '{}'", viewItem.getName(), e); 663 } 664 } 665 666 return values; 667 } 668 669 private boolean _allAttributesFilled(Map<String, Object> mappingValues, List<String> attributeNames) 670 { 671 return mappingValues.entrySet() 672 .stream() 673 .filter(entry -> attributeNames.contains(entry.getKey())) 674 .map(Entry::getValue) 675 .allMatch(Objects::nonNull); 676 } 677 678 private record SynchronizeResult(boolean isCreated, Optional<ModifiableWorkflowAwareContent> content, boolean hasKey) { /* empty */ } 679 680}