DesignPackageImporter.java 19.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.commons.jcr.JcrUtil
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.api.AssetManager
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.api.PageManager
 *  com.day.cq.wcm.api.PageManagerFactory
 *  com.day.cq.wcm.api.designer.Design
 *  com.day.cq.wcm.api.designer.Designer
 *  javax.jcr.Binary
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.commons.JcrUtils
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.request.RequestParameter
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.commons.mime.MimeTypeService
 *  org.apache.sling.commons.osgi.OsgiUtil
 *  org.osgi.framework.BundleContext
 *  org.osgi.framework.InvalidSyntaxException
 *  org.osgi.framework.ServiceReference
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.designimporter;

import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.AssetManager;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.api.PageManagerFactory;
import com.day.cq.wcm.api.designer.Design;
import com.day.cq.wcm.api.designer.Designer;
import com.day.cq.wcm.designimporter.CanvasBuildOptions;
import com.day.cq.wcm.designimporter.DesignImportException;
import com.day.cq.wcm.designimporter.DesignImportResult;
import com.day.cq.wcm.designimporter.DesignImporterContext;
import com.day.cq.wcm.designimporter.MalformedArchiveException;
import com.day.cq.wcm.designimporter.MissingHTMLException;
import com.day.cq.wcm.designimporter.api.CanvasBuilder;
import com.day.cq.wcm.designimporter.api.EntryPreprocessor;
import com.day.cq.wcm.designimporter.util.ImporterUtil;
import com.day.cq.wcm.designimporter.util.StreamUtil;
import java.io.BufferedInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.mime.MimeTypeService;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(label="%design.importer.name", description="%design.importer.description", metatype=1)
@Service(value={DesignPackageImporter.class})
public class DesignPackageImporter {
    private static final String DEFAULT_EXTRACT_FILTER_GITIGNORE = "[^.]*\\.gitignore";
    private static final String DEFAULT_EXTRACT_FILTER_DS_STORE = "[^.]*\\.DS_Store";
    private static final String DEFAULT_EXTRACT_FILTER_MACOSX = "__MACOSX.*";
    @org.apache.felix.scr.annotations.Property(value={"__MACOSX.*", "[^.]*\\.DS_Store", "[^.]*\\.gitignore"})
    private static final String PN_EXTRACT_FILTER = "extract.filter";
    private Logger logger = LoggerFactory.getLogger(DesignPackageImporter.class);
    @Reference
    protected MimeTypeService mimeTypeService;
    @Reference
    protected EntryPreprocessor entryPreprocessor;
    @Reference
    protected PageManagerFactory pageManagerFactory;
    private ArrayList<Node> extractedHtmlNodes = new ArrayList();
    private ArrayList<String> extractedResources = new ArrayList();
    private BundleContext bundleContext;
    private String[] extractFilters;
    private AssetManager assetManager;

    public DesignImportResult importDesignPackage(SlingHttpServletRequest slingHttpServletRequest) throws DesignImportException {
        return this.importDesignPackage(slingHttpServletRequest, null);
    }

    public DesignImportResult importDesignPackage(SlingHttpServletRequest slingHttpServletRequest, CanvasBuildOptions buildOptions) throws DesignImportException {
        try {
            if (buildOptions == null) {
                buildOptions = new CanvasBuildOptions();
                buildOptions.setBuildPageNodes(true);
                buildOptions.setBuildClientLibs(true);
                buildOptions.setBuildCanvasComponent(true);
            }
            Resource importer = slingHttpServletRequest.getResource();
            InputStream designPackage = this.getArchiveStreamFromRequest(slingHttpServletRequest);
            return this.importDesignPackageInternal(importer, designPackage, buildOptions);
        }
        catch (ZipException e) {
            throw new MalformedArchiveException();
        }
        catch (IOException e) {
            throw new DesignImportException(e);
        }
        catch (RepositoryException e) {
            throw new DesignImportException((Throwable)e);
        }
    }

    public DesignImportResult importDesignPackage(Page importerPage, String designPackagePath, CanvasBuildOptions buildOptions) throws DesignImportException {
        try {
            if (buildOptions == null) {
                buildOptions = new CanvasBuildOptions();
                buildOptions.setBuildPageNodes(true);
                buildOptions.setBuildClientLibs(true);
                buildOptions.setBuildCanvasComponent(true);
            }
            String importerPath = "jcr:content/importer";
            Resource importer = ((Resource)importerPage.adaptTo(Resource.class)).getChild(importerPath);
            Node importerPageNode = (Node)importerPage.adaptTo(Node.class);
            Node dst = importerPageNode.getNode(importerPath).addNode("designpackage", "nt:unstructured");
            Node src = importerPageNode.getSession().getNode(designPackagePath);
            JcrUtil.copy((Node)src, (Node)dst, (String)"file");
            Resource jcrContent = importer.getChild("designpackage/file/jcr:content");
            InputStream designPackage = (InputStream)((ValueMap)jcrContent.adaptTo(ValueMap.class)).get((Object)"jcr:data");
            return this.importDesignPackageInternal(importer, designPackage, buildOptions);
        }
        catch (ZipException e) {
            throw new MalformedArchiveException();
        }
        catch (IOException e) {
            throw new DesignImportException(e);
        }
        catch (RepositoryException e) {
            throw new DesignImportException((Throwable)e);
        }
    }

    protected Node extractEntry(ZipEntry entry, Node parent, ZipInputStream zipInputStream, DesignImporterContext designImporterContext) throws RepositoryException, IOException {
        if (!entry.isDirectory()) {
            String destPath = this.mapPath(entry.getName());
            int lastIndexOfSlash = destPath.lastIndexOf(47);
            String fileName = destPath.substring(lastIndexOfSlash + 1);
            Node fileParent = parent;
            if (lastIndexOfSlash > 0) {
                String folder = destPath.substring(0, lastIndexOfSlash);
                fileParent = JcrUtil.createPath((Node)parent, (String)folder, (boolean)false, (String)"{http://www.jcp.org/jcr/nt/1.0}folder", (String)"{http://www.jcp.org/jcr/nt/1.0}folder", (Session)parent.getSession(), (boolean)true);
            }
            String encoding = "utf-8";
            FilterInputStream stream = zipInputStream;
            if (entry.getName().matches("(?i)[^.]*\\.html")) {
                if (!stream.markSupported()) {
                    stream = new BufferedInputStream(zipInputStream);
                }
                encoding = StreamUtil.getEncoding(stream);
            }
            String mimeType = this.getMimeType(fileName) + ";charset=" + encoding;
            InputStream entryStream = stream;
            if (this.entryPreprocessor != null) {
                entryStream = this.entryPreprocessor.getProcessedStream(entry.getName(), stream, designImporterContext);
            }
            if (this.assetManager != null && mimeType.startsWith("image/")) {
                this.assetManager.createAsset(fileParent.getPath() + "/" + fileName, entryStream, mimeType, true);
            } else {
                return JcrUtils.putFile((Node)fileParent, (String)fileName, (String)mimeType, (InputStream)entryStream);
            }
        }
        return null;
    }

    protected Node getOrCreateDesignPath(Resource importer) throws RepositoryException {
        ResourceResolver resourceResolver = importer.getResourceResolver();
        PageManager pageManager = this.pageManagerFactory.getPageManager(resourceResolver);
        Page page = pageManager.getContainingPage(importer);
        Session session = ((Node)page.adaptTo(Node.class)).getSession();
        String pagePath = page.getPath();
        String path = null;
        if (ImporterUtil.isImporter(importer)) {
            Designer designer = (Designer)resourceResolver.adaptTo(Designer.class);
            String pageDesignPath = designer.getDesign(page).getPath();
            path = pageDesignPath + "/canvas" + importer.getPath();
        } else {
            path = "/etc/designs/canvaspage" + pagePath;
        }
        Node designNode = JcrUtil.createPath((String)path, (String)"{http://www.jcp.org/jcr/nt/1.0}folder", (String)"cq:Page", (Session)session, (boolean)true);
        Node jcrContent = JcrUtils.getOrAddNode((Node)designNode, (String)"jcr:content", (String)"{http://www.jcp.org/jcr/nt/1.0}unstructured");
        JcrUtil.setProperty((Node)jcrContent, (String)"cq:doctype", (Object)"html_5");
        JcrUtil.setProperty((Node)jcrContent, (String)"sling:resourceType", (Object)"wcm/core/components/designer");
        session.save();
        return designNode;
    }

    protected Node getOrCreateDesignPath(Page page) throws RepositoryException {
        Session session = ((Node)page.adaptTo(Node.class)).getSession();
        String pagePath = page.getPath();
        String path = "/etc/designs/canvaspage" + pagePath;
        Node designNode = JcrUtil.createPath((String)path, (String)"{http://www.jcp.org/jcr/nt/1.0}folder", (String)"cq:Page", (Session)session, (boolean)true);
        Node jcrContent = JcrUtils.getOrAddNode((Node)designNode, (String)"jcr:content", (String)"{http://www.jcp.org/jcr/nt/1.0}unstructured");
        JcrUtil.setProperty((Node)jcrContent, (String)"cq:doctype", (Object)"html_5");
        JcrUtil.setProperty((Node)jcrContent, (String)"sling:resourceType", (Object)"wcm/core/components/designer");
        session.save();
        return designNode;
    }

    protected String mapPath(String zipEntry) {
        return zipEntry;
    }

    protected String mapPath(ZipEntry entry) {
        return this.mapPath(entry.getName());
    }

    protected boolean shouldExtractEntry(ZipEntry entry) {
        for (String extractFilter : this.extractFilters) {
            if (!entry.getName().matches(extractFilter)) continue;
            return false;
        }
        return true;
    }

    private void cleanup() {
        try {
            for (Node node : this.extractedHtmlNodes) {
                node.remove();
            }
        }
        catch (RepositoryException e) {
            this.logger.error("A repository exception occured while cleaning up the temporary HTML file nodes from the design path", (Throwable)e);
        }
    }

    private void extractArchive(Node designNode, InputStream archiveStream, DesignImporterContext designImporterContext) throws IOException, RepositoryException {
        try {
            ZipInputStream zipInputStream = new ZipInputStream(archiveStream);
            ZipEntry entry = zipInputStream.getNextEntry();
            if (entry == null) {
                throw new ZipException();
            }
            while (entry != null) {
                if (this.shouldExtractEntry(entry)) {
                    Node node = this.extractEntry(entry, designNode, zipInputStream, designImporterContext);
                    if (this.isHtmlEntry(entry)) {
                        this.extractedHtmlNodes.add(node);
                    } else if (!entry.isDirectory()) {
                        this.extractedResources.add(entry.getName());
                    }
                }
                entry = zipInputStream.getNextEntry();
            }
        }
        catch (IllegalArgumentException ex) {
            throw new IOException("Archived file is not in a valid format");
        }
    }

    private String getMimeType(String name) {
        String mimeType = this.mimeTypeService.getMimeType(name);
        return mimeType != null ? mimeType : "";
    }

    private DesignImportResult importDesignPackageInternal(Resource importer, InputStream designPackage, CanvasBuildOptions buildOptions) throws DesignImportException, RepositoryException, IOException {
        this.initialize();
        this.assetManager = (AssetManager)importer.getResourceResolver().adaptTo(AssetManager.class);
        PageManager pageManager = this.pageManagerFactory.getPageManager(importer.getResourceResolver());
        Page page = pageManager.getContainingPage(importer);
        Node designNode = this.getOrCreateDesignPath(importer);
        DesignImporterContext importerContext = new DesignImporterContext(page, designNode, null);
        importerContext.setImporter(importer);
        this.extractArchive(designNode, designPackage, importerContext);
        if (this.extractedHtmlNodes.size() == 0) {
            throw new MissingHTMLException();
        }
        Comparator<Node> comparator = new Comparator<Node>(){

            @Override
            public int compare(Node n1, Node n2) {
                String n1Name = "";
                String n2Name = "";
                try {
                    n1Name = n1.getName();
                    n2Name = n2.getName();
                }
                catch (RepositoryException var5_5) {
                    // empty catch block
                }
                return n2Name.compareTo(n1Name);
            }
        };
        Collections.sort(this.extractedHtmlNodes, comparator);
        ArrayList<String> warnings = new ArrayList<String>();
        boolean built = false;
        for (int i = this.extractedHtmlNodes.size() - 1; i >= 0; --i) {
            Node htmlNode = this.extractedHtmlNodes.get(i);
            String htmlName = htmlNode.getName();
            InputStream htmlStream = htmlNode.getNode("jcr:content").getProperty("jcr:data").getBinary().getStream();
            CanvasBuilder canvasBuilder = this.getCanvasBuilder(htmlNode, importer);
            if (canvasBuilder != null) {
                DesignImporterContext designImporterContext = new DesignImporterContext(page, designNode, htmlName, canvasBuilder, this.bundleContext, this.extractedResources);
                designImporterContext.setImporter(importer);
                canvasBuilder.build(htmlStream, designImporterContext, buildOptions);
                warnings.addAll(designImporterContext.importWarnings);
                built = true;
                continue;
            }
            this.extractedHtmlNodes.remove(i);
        }
        if (!built) {
            throw new MissingHTMLException();
        }
        this.cleanup();
        designNode.getSession().save();
        return new DesignImportResult(warnings);
    }

    private InputStream getArchiveStreamFromRequest(SlingHttpServletRequest request) throws IOException, DesignImportException {
        RequestParameter designfile = request.getRequestParameter("designfile");
        InputStream archiveStream = null;
        if (designfile != null) {
            archiveStream = designfile.getInputStream();
        } else {
            Resource importer = request.getResource();
            if (ImporterUtil.isImporter(importer)) {
                Resource jcrContent = importer.getChild("designpackage/file/jcr:content");
                if (jcrContent == null) {
                    throw new DesignImportException("Design Package not found");
                }
                archiveStream = (InputStream)((ValueMap)jcrContent.adaptTo(ValueMap.class)).get((Object)"jcr:data");
            }
        }
        return archiveStream;
    }

    private void initialize() {
        this.extractedHtmlNodes = new ArrayList();
        this.extractedResources = new ArrayList();
    }

    private boolean isHtmlEntry(ZipEntry entry) {
        return entry.getName().matches("(?i)[^/\\\\]*\\.html?");
    }

    protected CanvasBuilder getCanvasBuilder(Node htmlNode, Resource importer) throws RepositoryException {
        try {
            ServiceReference[] references = this.bundleContext.getServiceReferences(CanvasBuilder.class.getName(), null);
            Arrays.sort(references, new Comparator<ServiceReference>(){

                @Override
                public int compare(ServiceReference o1, ServiceReference o2) {
                    int o1Priority = OsgiUtil.toInteger((Object)o1.getProperty("service.ranking"), (int)0);
                    int o2Priority = OsgiUtil.toInteger((Object)o2.getProperty("service.ranking"), (int)0);
                    return o2Priority - o1Priority;
                }
            });
            for (ServiceReference reference : references) {
                String filepattern = (String)reference.getProperty("filepattern");
                if (!htmlNode.getName().matches(filepattern)) continue;
                return (CanvasBuilder)this.bundleContext.getService(reference);
            }
        }
        catch (InvalidSyntaxException e) {
            this.logger.error("An error occurred while obtaining CanvasPageBuilder ServiceReference", (Throwable)e);
        }
        return null;
    }

    @Activate
    protected void activate(ComponentContext context) {
        this.extractFilters = OsgiUtil.toStringArray(context.getProperties().get("extract.filter"));
        this.bundleContext = context.getBundleContext();
    }

    protected void bindMimeTypeService(MimeTypeService mimeTypeService) {
        this.mimeTypeService = mimeTypeService;
    }

    protected void unbindMimeTypeService(MimeTypeService mimeTypeService) {
        if (this.mimeTypeService == mimeTypeService) {
            this.mimeTypeService = null;
        }
    }

    protected void bindEntryPreprocessor(EntryPreprocessor entryPreprocessor) {
        this.entryPreprocessor = entryPreprocessor;
    }

    protected void unbindEntryPreprocessor(EntryPreprocessor entryPreprocessor) {
        if (this.entryPreprocessor == entryPreprocessor) {
            this.entryPreprocessor = null;
        }
    }

    protected void bindPageManagerFactory(PageManagerFactory pageManagerFactory) {
        this.pageManagerFactory = pageManagerFactory;
    }

    protected void unbindPageManagerFactory(PageManagerFactory pageManagerFactory) {
        if (this.pageManagerFactory == pageManagerFactory) {
            this.pageManagerFactory = null;
        }
    }

}