Create Export Content Catalog Cronjob.
items.xml
<enumtype code="TargetType" autocreate="true" generate="true">
<value code="LOCAL" />
<value code="BLOB" />
</enumtype>
<relation code="AdvancedTypeExportConfig2Types" autocreate="true"
generate="true" localized="false">
<deployment table="AdvExportConfig2Types"
typecode="31000" />
<sourceElement qualifier="exportConfigurations"
type="AdvancedTypeExportConfiguration" cardinality="many" ordered="false">
<description>type export configs</description>
</sourceElement>
<targetElement qualifier="typesToExport" type="ComposedType"
cardinality="many" ordered="true" collectiontype="list">
<description>composed types that we will export</description>
</targetElement>
</relation>
<relation code="AdvancedTypeExportConfig2CatVersion"
autocreate="true" generate="true" localized="false">
<deployment table="AdvExConfig2CatVersion"
typecode="31001" />
<sourceElement qualifier="exportConfigurations"
type="AdvancedTypeExportConfiguration" cardinality="many" ordered="false">
<description>type export configs</description>
</sourceElement>
<targetElement qualifier="catalogVersionsToExport" type="CatalogVersion"
cardinality="many" ordered="false" collectiontype="set">
<description>catalog versions to export</description>
</targetElement>
</relation>
<relation code="AdvancedTypeExportConfig2Lang"
autocreate="true" generate="true" localized="false">
<deployment table="AdvExConfig2Lang"
typecode="31002" />
<sourceElement qualifier="exportConfigurations" type="AdvancedTypeExportConfiguration" cardinality="many" ordered="false">
<description>type export configs</description>
</sourceElement>
<targetElement qualifier="languages" type="Language"
cardinality="many" ordered="false" collectiontype="set">
<description>languages to export</description>
</targetElement>
</relation>
<relation code="AdvancedTypeExportConfig2BlackListedAttrDesc"
autocreate="true" generate="true" localized="false">
<deployment table="AdvExConfig2BlkAttrDesc"
typecode="21003" />
<sourceElement qualifier="blackListedExportConfigurations" type="AdvancedTypeExportConfiguration" cardinality="many" ordered="false">
<description>type export configs</description>
</sourceElement>
<targetElement qualifier="blacklistedAttributes" type="AttributeDescriptor"
cardinality="many" ordered="true" collectiontype="set">
<description>languages to export</description>
</targetElement>
</relation>
<relation code="AdvancedTypeExportConfig2BlacklistedTypes"
autocreate="true" generate="true" localized="false">
<deployment table="AdvExConfig2BlkTypes"
typecode="31005" />
<sourceElement qualifier="blackListedExportConfigurations" type="AdvancedTypeExportConfiguration" cardinality="many" ordered="false">
<description>type export configs</description>
</sourceElement>
<targetElement qualifier="blacklistedTypes" type="ComposedType"
cardinality="many" ordered="true" collectiontype="set">
<description>languages to export</description>
</targetElement>
</relation>
<itemtype code="AdvancedTypeExportCronJob" extends="CronJob" jaloclass="com.msasafety.ac.jalo.advancedexport.AdvancedTypeExportCronJob" autocreate="true" generate="true">
<attributes>
<attribute qualifier="exportScript" type="ImpExMedia">
<persistence type="property"/>
</attribute>
<attribute qualifier="exportedMedia" type="ImpExMedia">
<persistence type="property"/>
</attribute>
<attribute qualifier="exportedData" type="ImpExMedia">
<persistence type="property"/>
</attribute>
<attribute qualifier="exportConfiguration" type="AdvancedTypeExportConfiguration">
<persistence type="property"/>
<modifiers optional="false"/>
</attribute>
<!-- Enhancement 6 Start here -->
<attribute qualifier="target" type="TargetType">
<persistence type="property"/>
<defaultvalue>em().getEnumerationValue("TargetType", "LOCAL")</defaultvalue>
</attribute>
<!-- Enhancement 6 Ends here -->
</attributes>
</itemtype>
<itemtype code="AdvancedTypeExportConfiguration" extends="GenericItem" jaloclass="com.msasafety.ac.jalo.advancedexport.AdvancedTypeExportConfiguration" autocreate="true" generate="true">
<deployment table="AdvExportConfig"
typecode="31004" />
<attributes>
<attribute type="java.lang.String" qualifier="code">
<persistence type="property"/>
<modifiers unique="true" optional="false"/>
</attribute>
<attribute type="java.util.Date" qualifier="lastExport">
<persistence type="property"/>
</attribute>
<attribute type="java.util.Date" qualifier="creationDate">
<persistence type="property"/>
</attribute>
<attribute type="java.util.Date" qualifier="modifiedDate">
<persistence type="property"/>
</attribute>
<attribute type="java.lang.Boolean" qualifier="relationsAsAttributes">
<persistence type="property"/>
<modifiers optional="false"/>
<defaultvalue>java.lang.Boolean.TRUE</defaultvalue>
</attribute>
</attributes>
</itemtype>
/**
*
*/
package com.msasafety.ac.advancedexport;
import com.msasafety.ac.model.advancedexport.AdvancedTypeExportCronJobModel;
import static java.io.File.separatorChar;
import de.hybris.platform.cronjob.enums.CronJobResult;
import de.hybris.platform.cronjob.enums.CronJobStatus;
import de.hybris.platform.impex.model.ImpExMediaModel;
import de.hybris.platform.servicelayer.config.ConfigurationService;
import de.hybris.platform.servicelayer.cronjob.AbstractJobPerformable;
import de.hybris.platform.servicelayer.cronjob.PerformResult;
import de.hybris.platform.servicelayer.impex.ExportConfig;
import de.hybris.platform.servicelayer.impex.ExportConfig.ValidationMode;
import de.hybris.platform.servicelayer.impex.ExportResult;
import de.hybris.platform.servicelayer.impex.ExportService;
import de.hybris.platform.servicelayer.impex.ImpExResource;
import de.hybris.platform.servicelayer.impex.impl.StreamBasedImpExResource;
import de.hybris.platform.servicelayer.media.MediaService;
import de.hybris.platform.util.CSVConstants;
import com.msasafety.ac.enums.TargetType;
import java.io.*;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.zip.transformer.SpringZipUtils;
import org.apache.commons.configuration.Configuration;
/**
* @author hydev
*
*/
public class AdvancedTypeExportJob extends AbstractJobPerformable<AdvancedTypeExportCronJobModel> {
private static final String TARGET_TYPE_LOCAL = "LOCAL";
private static final String TARGET_TYPE_BLOB = "BLOB";
private static final String CMS_JOB = "export-CMS-Catalog";
private static final String SOLR_JOB = "export-SOLR-Setup";
private static final String PCM_JOB = "export-Product-Staged";
private static final String CLASSIFICATION_JOB = "export-ClassificationSystem";
private static final String CONFIG_GET_CONNECTION_DIRECT = "bfs.blob.build.connection.direct";
private static final String CONFIG_AZURE_CONNECTION_STRING = "azure.hotfolder.storage.account.connection-string";
private static final Logger LOG = Logger.getLogger(AdvancedTypeExportJob.class);
// private ModelService modelService;
private ExportService exportService;
@Autowired
private ConfigurationService configurationService;
@Autowired
private MediaService mediaService;
@Override
public PerformResult perform(final AdvancedTypeExportCronJobModel cron) {
try {
LOG.info(".........perform started........");
final String exportString = generateExportScript(cron);
LOG.info(".........Writing the file to blob started........");
copyToBlob(cron, exportString, cron.getCode().concat("-" + "Script"), ".txt", true, false, false);
LOG.info("........Writing the file to blob end............");
LOG.info("***** Exporting types ********");
LOG.info("Using script.......");
LOG.info(exportString);
final ExportResult result = getExportResultByConfig(cron, exportString);
if (result.isSuccessful()) {
LOG.info("***** Result is successful********");
cron.setExportedData(result.getExportedData());
cron.setExportedMedia(result.getExportedMedia());
modelService.save(cron);
LOG.info("***** Result is successful end ********");
}
LOG.info("........Writing the Data to blob started............");
copyToBlob(cron, exportString, cron.getCode().concat("-" + "Data"), ".csv", false, true, false);
LOG.info("........Writing the Data to blob end............");
/*
* LOG.info("........Writing the Media to blob started............");
* copyToBlob(cron, exportString, cron.getCode().concat("-" + "Media"), ".zip",
* false, false, true);
* LOG.info("........Writing the Media to blob end............");
*/
LOG.info(".........perform ended........result successful ? : "+result.isSuccessful());
return result.isSuccessful() ? new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED) : new PerformResult(CronJobResult.FAILURE, CronJobStatus.FINISHED);
} catch(Exception e) {
LOG.info("......... perform ended........with exceptions : "+e.getMessage());
LOG.error(e.getMessage(), e);
return new PerformResult(CronJobResult.FAILURE, CronJobStatus.FINISHED);
}
}
private ExportResult getExportResultByConfig(final AdvancedTypeExportCronJobModel cron, final String exportString) throws UnsupportedEncodingException {
final ImpExResource exportResource = new StreamBasedImpExResource(
new ByteArrayInputStream(exportString.getBytes(StandardCharsets.UTF_8)), CSVConstants.HYBRIS_ENCODING);
final ExportConfig exportConfig = new ExportConfig();
exportConfig.setFailOnError(false);
exportConfig.setValidationMode(ValidationMode.RELAXED);
exportConfig.setScript(exportResource);
exportConfig.setSingleFile(true);
cron.setExportScript(exportResource.getMedia());
modelService.save(cron);
return exportService.exportData(exportConfig);
}
private void copyToBlob(AdvancedTypeExportCronJobModel cron, String exportString, String filename, String fileExtension,
boolean copyScript, boolean copyData, boolean copyMedia) throws IOException, URISyntaxException, InvalidKeyException {
//Creating a sample file
File sourceFile = File.createTempFile(filename, fileExtension);
LOG.info("Creating a sample file at: " + sourceFile.toString());
try(final BufferedWriter output = new BufferedWriter(new FileWriter(sourceFile))) {
if (copyScript) {
LOG.info("******* copyScript *******");
output.write(exportString);
} else if (copyData) {
LOG.info("******* copyData start *******");
final ExportResult result = getExportResultByConfig(cron, exportString);
sourceFile = writeFileFromMedia(result.getExportedData(), sourceFile);
LOG.info("******* copyData end *******");
} else if (copyMedia) {
LOG.info("******* copyMedia start *******");
final ExportResult result = getExportResultByConfig(cron, exportString);
sourceFile = writeZipFileFromMedia(result.getExportedMedia(), sourceFile);
LOG.info("******* copyMedia end *******");
}
}
}
//TODO please check, this is not in use. if not needed, please remove
/**
* @param result
*/
private void copyExportedMediaToExportDir(final ExportResult result, final String exportPrefix, final TargetType target) throws IOException {
if(target.getCode().endsWith(TARGET_TYPE_LOCAL)) {
LOG.info("***** In copyExportedMediaToExportDir********");
final String exportDir = configurationService.getConfiguration().getString("advancedexport.export.dir");
LOG.info("***** exportDir********" + exportDir);
if (StringUtils.isBlank(exportDir)) {
throw new IOException("No exportDir provided");
}
final File dir = new File(exportDir);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Directory " + exportDir + " does not exist. Unable to create it.");
}
if (dir.isDirectory() && dir.canWrite()) {
final Path dirPath = Paths.get(dir.getAbsolutePath());
LOG.info("Directory " + exportDir + " exist.Started Writing");
copyExportedMediaFile(dirPath, result.getExportedData(), exportPrefix);
copyExportedMediaFile(dirPath, result.getExportedMedia(), exportPrefix);
} else {
LOG.error("Unable to write to " + exportDir + " or it is not a directory");
}
} else {
LOG.warn("target type is not " + TARGET_TYPE_LOCAL + ", but is " + target.getCode() + ". Ignoring.");
}
}
private void copyExportedMediaFile(final Path targetDir, final ImpExMediaModel impexModel, final String exportPrefix) throws IOException {
if(impexModel != null) {
LOG.info("copying the files");
Files.copy(Paths.get(findRealMediaPath(impexModel)),
targetDir.resolve(StringUtils.isEmpty(exportPrefix) ? "" : exportPrefix + impexModel.getRealFileName() + new Date()));
LOG.info("copying the end");
} else {
LOG.warn("impexModel is null. Ignoring");
}
}
private String findRealMediaPath(final ImpExMediaModel impexModel) {
final StringBuilder stringBuilder = new StringBuilder()
.append(configurationService.getConfiguration().getProperty("HYBRIS_DATA_DIR")).append(separatorChar)
.append("media").append(separatorChar)
.append("sys_").append(impexModel.getFolder().getTenantId())
.append(separatorChar).append(impexModel.getLocation());
LOG.info("sb.toString()" + stringBuilder.toString());
return stringBuilder.toString();
}
private File writeFileFromMedia(final ImpExMediaModel impexModel,File sourceFile) throws IOException {
InputStream mediaStream = mediaService.getStreamFromMedia(impexModel);
FileUtils.copyInputStreamToFile(mediaStream, sourceFile);
return sourceFile;
}
private File writeZipFileFromMedia(final ImpExMediaModel impexModel, File sourceFile) throws IOException {
SpringZipUtils.copy(mediaService.getStreamFromMedia(impexModel), sourceFile);
return sourceFile;
}
/**
* Use a custom export script generator to dynamically create an export script
*
* @param cron
* @return script payload
*/
protected String generateExportScript(final AdvancedTypeExportCronJobModel cron) {
return new AdvancedTypeExportScriptGenerator(modelService.getSource(cron.getExportConfiguration())).generateScript();
}
/**
* @param exportService
* the exportService to set
*/
public void setExportService(final ExportService exportService) {
this.exportService = exportService;
}
}
#if target catalog already has data (i.e. this is a re-load and not the initial load) then ContentSlotName needs to move to blacklisttypes from exporttypes;
$exporttypes=BannerComponent,CMSImageComponent,CMSLinkComponent,CMSParagraphComponent,JspIncludeComponent,MiniFacetComponent,MSABadgedCardComponent,MSADetailedCardComponent,MSADoubleDetailedCardComponent,MSAExtendedDoubleDetailedCardComponent,MSAMarketCardComponent,MSAParagraphComponent,MSASearchComponent,MSASocialMediaDetailCardComponent,MSAStockComponent,MSAWhatsNewCardComponent,MSAWhatsNewCarouselComponent,PageTemplate,RotatingImagesComponent,SimpleBannerComponent,MSAExploreProductsSearchComponent,ProductCarouselComponent,SimpleMSABannerComponent,MSA2CategoryBannerComponent,MSAButtonBannerComponent,MSACMSLinkComponent,MSAGenericBannerComponent,MSAApplicationNavLinksListComponent,MSANewsReleasesComponent,MSASocialMediaCardComponent,MiniCartComponent,MSAApplicationIndividualTabComponent,MSA2TabsListComponent,MSAApplicationAccordionSectionComponent,MSAApplicationAccordionListComponent,MSAApplicationBannerComponent,CMSNavigationNode,CMSNavigationEntry,FooterComponent,MSACarouselInnerComponent,MSACarouselComponent,NavigationBarComponent,EmailPageTemplate,CategoryPage,EmailPage,ContentPage,MSAContentPage,ProductPage,ContentSlotName,AccordionParagraphContainer,AccordionParagraphComponent,RecentlyViewedProductCMSComponent,UserViewedHistoryProductCMSComponent,ContentSlot,ContentSlotForTemplate,ContentSlotForPage,MSAApplicationCardComponent,MSAHomePageBannerComponent,MSAFooterComponent,MSAMegaNavigationComponent
$blacklisttypes=CatalogVersionSyncScheduleMedia,HeaderLibrary,LogFile,ImpExMedia,ImpExExportMedia,CockpitUIConfigurationMedia
#===========
# NNA22
#===========
$jobname=NNA22-export-CMS-Catalog
$catalogname=nna22ContentCatalog:Staged
$cataloglanguages=en,es,fr
# AdvancedTypeExportConfiguration for NNA22 export
INSERT_UPDATE AdvancedTypeExportConfiguration ; code[unique=true] ; catalogVersionsToExport(catalog(id),version) ; languages(isocode) ; typesToExport(code) ; blacklistedTypes(code)
; $jobname ; $catalogname ; $cataloglanguages ; $exporttypes ; $blacklisttypes
# Blacklisted attributes
INSERT_UPDATE AdvancedTypeExportConfiguration ; code[unique=true] ; blacklistedAttributes(enclosingType(code),qualifier) ;
; $jobname ; Item:creationtime,Item:modifiedtime,Item:assignedCockpitItemTemplates,Item:comments,Item:owner,Item:allDocuments,Item:savedValues,Media:URL2,Media:folder,PageTemplate:availableContentSlots,FooterComponent:navigationNodes,AbstractPage:navigationNodeList
INSERT_UPDATE ServicelayerJob ; code[unique=true] ; springId[unique=true]
; $jobname ; advancedTypeExportJob
INSERT_UPDATE AdvancedTypeExportCronJob ; code[unique=true] ; job(code) ; exportConfiguration(code) ; sessionUser(uid) ; sessionLanguage(isocode)[default=en] ; active[default=true] ;
; $jobname ; $jobname ; $jobname ; admin ; en ; true ;
Comments
Post a Comment