MobileAssetUploadOperation.java 37.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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.ui.components.HtmlResponse
 *  com.day.cq.commons.jcr.JcrUtil
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.api.AssetManager
 *  com.day.cq.dam.api.Rendition
 *  com.day.cq.i18n.I18n
 *  com.day.cq.wcm.api.Page
 *  javax.jcr.Binary
 *  javax.jcr.Item
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.ValueFactory
 *  javax.servlet.http.HttpServletRequest
 *  org.apache.commons.io.IOUtils
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.PropertyUnbounded
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.util.Text
 *  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.PropertiesUtil
 *  org.apache.sling.servlets.post.Modification
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 */
package com.adobe.cq.mobile.platform.impl.operations;

import com.adobe.cq.mobile.platform.MobileResource;
import com.adobe.cq.mobile.platform.MobileResourceLocator;
import com.adobe.cq.mobile.platform.MobileResourceType;
import com.adobe.cq.mobile.platform.impl.WidgetConfigDocument;
import com.adobe.cq.mobile.platform.impl.operations.CreateMobileAppOperation;
import com.adobe.cq.mobile.platform.impl.operations.MobileOperationException;
import com.adobe.cq.mobile.platform.impl.utils.MobileAppJCRUtil;
import com.adobe.granite.ui.components.HtmlResponse;
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.dam.api.Rendition;
import com.day.cq.i18n.I18n;
import com.day.cq.wcm.api.Page;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Dictionary;
import java.util.List;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.jcr.Binary;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFactory;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.util.Text;
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.PropertiesUtil;
import org.apache.sling.servlets.post.Modification;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

@Component(metatype=1, label="Upload Mobile App Assets Operation")
@Service
@Properties(value={@org.apache.felix.scr.annotations.Property(name="sling.post.operation", value={"mobileapps:uploadAssets"})})
public class MobileAssetUploadOperation
extends CreateMobileAppOperation {
    public static final String OPERATION_NAME = "uploadAssets";
    private static final String PARAM_PATH = "path";
    private static final String PARAM_ARCHIVE = "archive";
    private static final String MIME_TYPE_ZIP = "application/zip";
    private static final String FILE_EXT_ZIP = ".zip";
    private static final int BUFFER = 2048;
    private static final String FN_CONFIG_XML = "config.xml";
    @Reference(policy=ReferencePolicy.STATIC)
    protected MimeTypeService mimeTypeService;
    private static final String DEFAULT_EXCLUSION_PATTERN = "^(__MACOSX.*)|(.*\\.DS_Store)$";
    @org.apache.felix.scr.annotations.Property(label="Exclusion Pattern", description="A regular expression which filters out non-interesting filenames", value={"^(__MACOSX.*)|(.*\\.DS_Store)$"})
    private static final String EXCLUSION_PATTERN_PROP_NAME = "cq.mobileapps.assetuploadoperation.exclusionpattern";
    private String exclusionPattern;
    @org.apache.felix.scr.annotations.Property(label="Asset Mime Types", description="List of mime types to be extracted as Assets", value={"image/jpg", "image/jpeg", "image/png"}, unbounded=PropertyUnbounded.ARRAY)
    private static final String DEFAULT_DAM_MIME_TYPES = "cq.mobileapps.assetuploadoperation.defaultMimeTypes";
    private List<String> defaultMimeTypes = new ArrayList<String>();

    @Activate
    protected void activate(ComponentContext ctx) throws Exception {
        Dictionary props = ctx.getProperties();
        this.exclusionPattern = PropertiesUtil.toString(props.get("cq.mobileapps.assetuploadoperation.exclusionpattern"), (String)"^(__MACOSX.*)|(.*\\.DS_Store)$");
        this.defaultMimeTypes.clear();
        if (props.get("cq.mobileapps.assetuploadoperation.defaultMimeTypes") != null) {
            this.defaultMimeTypes.addAll(Arrays.asList(PropertiesUtil.toStringArray(props.get("cq.mobileapps.assetuploadoperation.defaultMimeTypes"))));
        }
    }

    /*
     * Enabled aggressive block sorting
     * Enabled unnecessary exception pruning
     * Enabled aggressive exception aggregation
     */
    @Override
    protected void perform(SlingHttpServletRequest request, HtmlResponse response, List<Modification> changes) {
        String resourcePath;
        UnarchiverContext zipcontext;
        I18n i18n = new I18n((HttpServletRequest)request);
        String assetPath = request.getParameter("path");
        if (StringUtils.isBlank((CharSequence)assetPath)) {
            String message = i18n.get("Missing mandatory parameter {0}", null, new Object[]{"path"});
            String title = i18n.get("Error");
            this.generateError(response, message, title);
            return;
        }
        try {
            resourcePath = URLDecoder.decode(assetPath, "UTF-8");
            if (resourcePath.endsWith("/")) {
                resourcePath = resourcePath.substring(0, resourcePath.length() - 1);
            }
        }
        catch (UnsupportedEncodingException e) {
            String message = i18n.get("The server has problem processing your request. Unable to decode file path");
            String title = i18n.get("Error");
            this.generateError(response, message, title);
            return;
        }
        String archivePath = request.getParameter("archivePath");
        RequestParameter archiveParameter = request.getRequestParameter("archive");
        if (StringUtils.isBlank((CharSequence)archivePath) && (archiveParameter == null || archiveParameter.getSize() == 0)) {
            String message = i18n.get("Missing mandatory parameter {0}", null, new Object[]{"archive"});
            String title = i18n.get("Error");
            this.generateError(response, message, title);
            return;
        }
        if (StringUtils.isNotBlank((CharSequence)archivePath)) {
            Resource archiveResource = request.getResourceResolver().getResource(archivePath);
            if (archiveResource == null) {
                String message = i18n.get("Unable to locate asset archive");
                String title = i18n.get("Error");
                this.generateError(response, message, title);
                return;
            }
            zipcontext = new UnarchiverContext(request.getResourceResolver(), archiveResource, resourcePath);
        } else {
            zipcontext = new UnarchiverContext(request.getResourceResolver(), archiveParameter, resourcePath);
        }
        try {
            if (!this.isZipFile(zipcontext)) {
                String message = i18n.get("The uploaded file is not a valid archive");
                String title = i18n.get("Error");
                this.generateError(response, message, title);
                return;
            }
            this.log.info("scan: scanning archive [{}] and verifying configured limits", (Object)assetPath);
            this.scan(zipcontext, i18n);
            this.log.debug("execute: calling findAppInstance for [{}]", (Object)assetPath);
            MobileResource appInstance = this.findAppInstance(request, response, changes, zipcontext, i18n);
            zipcontext.setAppInstance(appInstance);
            this.log.debug("execute: calling beforeExtract for [{}]", (Object)assetPath);
            this.beforeExtract(zipcontext);
            boolean isExtractionSuccessful = this.extract(zipcontext);
            this.log.debug("execute: calling afterExtract for [{}] (extraction {})", (Object)assetPath, (Object)(isExtractionSuccessful ? "successful" : "failed"));
            this.afterExtract(zipcontext, isExtractionSuccessful, i18n);
        }
        catch (Throwable e) {
            String title = i18n.get("Error");
            this.generateError(response, e.getMessage(), title, e);
            return;
        }
        String message = i18n.get("Successfully uploaded app assets.");
        String title = i18n.get("Upload");
        this.generateResponse(response, 200, message, title);
    }

    private MobileResource findAppInstance(SlingHttpServletRequest request, HtmlResponse response, List<Modification> changes, UnarchiverContext context, I18n i18n) throws MobileOperationException {
        MobileResource appInstance = (MobileResource)request.getResource().adaptTo(MobileResource.class);
        if (appInstance == null || !appInstance.isA(MobileResourceType.INSTANCE.getType())) {
            try {
                String appPath = request.getParameter("parentPath") + "/" + context.getAppName();
                Resource appRes = null;
                if (!context.getSession().itemExists(appPath)) {
                    request.setAttribute("pageName", (Object)context.getAppName());
                    String appTemplatePath = context.getAppTemplate();
                    if (StringUtils.isNotBlank((CharSequence)appTemplatePath)) {
                        request.setAttribute("template", (Object)appTemplatePath);
                    }
                    Page newAppPage = this.createPage(request, response, changes, i18n);
                    appRes = (Resource)newAppPage.adaptTo(Resource.class);
                } else {
                    appRes = context.getResourceResolver().getResource(appPath);
                }
                MobileResourceLocator locator = (MobileResourceLocator)request.getResourceResolver().adaptTo(MobileResourceLocator.class);
                appInstance = locator.getResourceByType(appRes, MobileResourceType.INSTANCE.getType(), true);
            }
            catch (Exception ex) {
                String message = i18n.get("The server was unable to locate or create an app instance for this request.");
                if (ex.getCause() instanceof PathNotFoundException) {
                    message = i18n.get("The provided path does not exist") + ":<br/>" + ex.getCause().getMessage();
                }
                throw new MobileOperationException(message);
            }
        }
        if (appInstance == null || !appInstance.isA(MobileResourceType.INSTANCE.getType())) {
            String message = i18n.get("Unable to resolve mobile application for {0}", null, new Object[]{request.getResource().getPath()});
            throw new MobileOperationException(message);
        }
        return appInstance;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private boolean extract(UnarchiverContext context) throws IOException, MobileOperationException {
        Session session = context.getSession();
        ZipInputStream zis = context.createZipInputStream();
        try {
            context.setAssetRoot(this.getOrCreateRoot(context));
            try {
                ZipEntry entry;
                while (null != (entry = zis.getNextEntry())) {
                    long numFiles = context.updateNumFiles();
                    this.extractEntry(context, zis, entry);
                    if (numFiles % context.getSaveThreshold() != 0) continue;
                    this.log.debug("extract: threshold of [{}] reached, saving....", (Object)context.getSaveThreshold());
                    session.save();
                }
            }
            catch (Exception e) {
                this.log.error("extract: error while extracting archive [{}]: ", (Object)context.getArchiveName(), (Object)e);
            }
            finally {
                zis.closeEntry();
            }
            session.save();
            this.log.info("extract: extraction of archive [{}] successfully completed.", (Object)context.getArchiveName());
            boolean e = true;
            return e;
        }
        catch (IOException e) {
            this.log.error("extract: IO error while extracting archive [{}]: ", (Object)context.getArchiveName(), (Object)e);
        }
        catch (RepositoryException e) {
            this.log.error("extract: repository error while extracting archive [{}]: ", (Object)context.getArchiveName(), (Object)e);
        }
        finally {
            IOUtils.closeQuietly((InputStream)zis);
        }
        return false;
    }

    protected void scan(UnarchiverContext context, I18n i18n) throws IOException, MobileOperationException {
        String configPath;
        String wwwPath;
        ZipInputStream zis = context.createZipInputStream();
        configPath = null;
        wwwPath = null;
        try {
            ZipEntry entry;
            while (null != (entry = zis.getNextEntry())) {
                if (entry.isDirectory() || Pattern.matches(this.exclusionPattern, entry.getName())) continue;
                EntryInfo info = context.getEntryInfo(entry);
                String parentPath = info.getParentPath();
                String entryName = info.getFileName();
                if ("config.xml".equals(entryName) && configPath == null) {
                    configPath = parentPath;
                }
                if (parentPath.contains("www") && wwwPath == null) {
                    wwwPath = parentPath.substring(0, parentPath.indexOf("www") + 3);
                }
                if (configPath == null || wwwPath == null) {
                    this.log.debug("scan: scanned entry [{}] - [{}] bytes - folder:[" + parentPath + "]", (Object)entry.getName(), (Object)entry.getSize());
                    continue;
                }
                break;
            }
        }
        catch (IOException e) {
            this.log.error("scan: IO error while scanning archive [{}]: ", (Object)context.getArchiveName(), (Object)e);
            throw new MobileOperationException(i18n.get("Unable to scan archive"));
        }
        finally {
            IOUtils.closeQuietly((InputStream)zis);
        }
        if (configPath == null) {
            this.log.error("scan: archive [{}] does not contain a config", (Object)context.getArchiveName());
            throw new MobileOperationException(i18n.get("Archive does not contain an app configuration file."));
        }
        if (wwwPath == null) {
            this.log.error("scan: archive [{}] does not contain a 'www' dir", (Object)context.getArchiveName());
            throw new MobileOperationException(i18n.get("Archive does not contain a 'www' directory."));
        }
        String wwwParent = Text.getRelativeParent((String)wwwPath, (int)1);
        if (!configPath.equals(wwwPath) && !configPath.equals(wwwParent)) {
            this.log.error("scan: archive [{}] does not contain config in a valid location", (Object)context.getArchiveName());
            throw new MobileOperationException(i18n.get("App configuration file is in an invalid location."));
        }
        WidgetConfigDocument configDocument = this.extractConfigDocument(context);
        if (configDocument == null) {
            this.log.error("scan: archive [{}] does not contain a valid config", (Object)context.getArchiveName());
            throw new MobileOperationException(i18n.get("Unable to load app configuration file."));
        }
        this.log.info("scan: scan of archive [{}] completed. archive is within configured limits.", (Object)context.getArchiveName());
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private WidgetConfigDocument extractConfigDocument(UnarchiverContext context) throws IOException {
        ZipInputStream zis = context.createZipInputStream();
        try {
            try {
                ZipEntry entry;
                while (null != (entry = zis.getNextEntry())) {
                    EntryInfo info;
                    if (Pattern.matches(this.exclusionPattern, entry.getName()) || !(info = context.getEntryInfo(entry)).getFileName().equals("config.xml")) continue;
                    WidgetConfigDocument configDocument = WidgetConfigDocument.loadConfigDocument(zis);
                    context.setConfigDocument(configDocument);
                    break;
                }
            }
            catch (Exception e) {
                this.log.error("scan: error while extracting config document [{}]: ", (Object)context.getArchiveName(), (Object)e);
            }
            finally {
                if (context.getConfigDocument() == null) {
                    zis.closeEntry();
                }
            }
        }
        catch (IOException e) {
            this.log.error("scan: IO error while extracting config document [{}]: ", (Object)context.getArchiveName(), (Object)e);
        }
        finally {
            IOUtils.closeQuietly((InputStream)zis);
        }
        return context.getConfigDocument();
    }

    protected void beforeExtract(UnarchiverContext context) {
        Session session = context.getSession();
        MobileResource appInstance = context.getAppInstance();
        String configPath = (String)appInstance.getProperties().get("widgetConfigPath", String.class);
        if (StringUtils.isNotBlank((CharSequence)configPath)) {
            try {
                this.log.debug("beforeExtract: removing existing config doc [{}]", (Object)configPath);
                session.removeItem(configPath);
                session.save();
                this.log.info("beforeExtract: original config doc [{}] removed", (Object)configPath);
            }
            catch (RepositoryException e) {
                this.log.error("beforeExtract: could not remove config doc [{}]: ", (Object)configPath, (Object)e);
            }
        }
    }

    protected void afterExtract(UnarchiverContext context, boolean isExtractionSuccessful, I18n i18n) throws MobileOperationException {
        Session session = context.getSession();
        String archivePath = context.getArchivePath();
        if (StringUtils.isNotBlank((CharSequence)archivePath)) {
            try {
                this.log.debug("afterExtract: removing original archive [{}]", (Object)archivePath);
                session.removeItem(archivePath);
                session.save();
                this.log.info("afterExtract: original archive [{}] removed", (Object)archivePath);
            }
            catch (RepositoryException e) {
                this.log.error("afterExtract: could not remove archive [{}]: ", (Object)archivePath, (Object)e);
            }
        }
        if (!isExtractionSuccessful) {
            return;
        }
        try {
            Resource appResource = (Resource)context.getAppInstance().adaptTo(Resource.class);
            Resource appContent = appResource.getChild("jcr:content");
            Node assetAppRoot = this.findAssetAppRoot(context.getAssetRoot());
            if (assetAppRoot != null) {
                MobileAppJCRUtil.setMobileAppProperty(appContent, "appAssetPath", new String[]{assetAppRoot.getPath()});
            } else {
                this.log.debug("afterExtract: unable to find app root under [{}]", (Object)context.getAssetRoot().getPath());
            }
        }
        catch (RepositoryException e) {
            this.log.error("afterExtract: could not update asset path on [{}]: ", (Object)context.getAppInstance().getPath(), (Object)e);
            throw new MobileOperationException(i18n.get("Unable to update the asset path property"));
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void extractEntry(UnarchiverContext context, ZipInputStream zis, ZipEntry entry) throws Exception, MobileOperationException {
        block16 : {
            String fullPath;
            Session session = context.getSession();
            Node assetRoot = context.getAssetRoot();
            Node instanceRoot = (Node)context.getAppInstance().adaptTo(Node.class);
            EntryInfo info = context.getEntryInfo(entry);
            String name = entry.getName();
            String fileName = info.getFileName();
            String mimeType = this.mimeTypeService.getMimeType(fileName);
            this.log.debug("extractEntry: extracting entry [{}] in archive [{}]", (Object)entry.getName(), (Object)context.getArchiveName());
            if (Pattern.matches(this.exclusionPattern, entry.getName())) {
                this.log.info("extractEntry: entry [{}] matches excluded file pattern, skipping..", (Object)entry.getName());
                return;
            }
            boolean isAssetPath = false;
            if (this.defaultMimeTypes.contains(mimeType)) {
                fullPath = info.getTargetPath(assetRoot.getPath());
                isAssetPath = true;
            } else {
                String phonegapContentPath = "jcr:content/pge-app/app-content/phonegap";
                fullPath = info.getTargetPath(instanceRoot.getPath() + "/" + phonegapContentPath);
            }
            if (!entry.isDirectory()) {
                File tempFile = File.createTempFile("unarchiver-file-" + System.currentTimeMillis(), null);
                this.log.debug("extractEntry: created temporary file at [{}]", (Object)tempFile.getPath());
                FileOutputStream fos = null;
                FileInputStream fis = null;
                try {
                    Resource newResource;
                    String assetSha1;
                    int size;
                    byte[] buffer = new byte[2048];
                    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
                    fos = new FileOutputStream(tempFile);
                    while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                        fos.write(buffer, 0, size);
                        sha1.update(buffer, 0, size);
                    }
                    IOUtils.closeQuietly((OutputStream)fos);
                    String zipSha1 = this.getSHA1(sha1);
                    this.log.debug("extractEntry: got SHA-1 [{}] for entry [{}]", (Object)zipSha1, (Object)name);
                    Resource resource = context.getResourceResolver().getResource(fullPath);
                    if (null != resource && StringUtils.equals((CharSequence)(assetSha1 = this.getResourceSha(resource)), (CharSequence)zipSha1)) {
                        this.log.info("extractEntry: entry [{}] exists as asset [{}] with identical SHA-1, skipping.", (Object)name, (Object)resource.getPath());
                        return;
                    }
                    fis = new FileInputStream(tempFile);
                    if (null != resource) {
                        Asset asset = (Asset)resource.adaptTo(Asset.class);
                        if (null != asset) {
                            asset.addRendition("orginal", (InputStream)fis, mimeType).adaptTo(Resource.class);
                        } else {
                            this.addResourceData(resource, fis, mimeType);
                        }
                        this.log.info("extractEntry: updated existing asset [{}] from entry [{}]", (Object)resource.getPath(), (Object)name);
                        break block16;
                    }
                    JcrUtil.createPath((String)Text.getRelativeParent((String)fullPath, (int)1), (String)"sling:OrderedFolder", (String)"sling:OrderedFolder", (Session)session, (boolean)false);
                    if (isAssetPath) {
                        Asset newAsset = context.getAssetManager().createAsset(fullPath, (InputStream)fis, mimeType, false);
                        newResource = context.getResourceResolver().getResource(newAsset.getPath());
                    } else {
                        Node newNode = JcrUtil.createPath((String)fullPath, (String)"sling:OrderedFolder", (String)"nt:file", (Session)session, (boolean)false);
                        JcrUtil.createPath((Node)newNode, (String)"jcr:content", (boolean)false, (String)"sling:OrderedFolder", (String)"nt:resource", (Session)session, (boolean)false);
                        newResource = context.getResourceResolver().getResource(newNode.getPath());
                        this.addResourceData(newResource, fis, mimeType);
                    }
                    if (null != newResource) {
                        this.log.info("extractEntry: created new asset [{}] from entry [{}]", (Object)newResource.getPath(), (Object)name);
                        break block16;
                    }
                    this.log.error("extractEntry: asset manager couldn't create asset for entry [{}]", (Object)name);
                    throw new MobileOperationException("Asset manager couldn't create asset for entry " + name);
                }
                finally {
                    IOUtils.closeQuietly((OutputStream)fos);
                    IOUtils.closeQuietly((InputStream)fis);
                    tempFile.delete();
                    this.log.debug("extractEntry: deleted temporary file at [{}]", (Object)tempFile.getPath());
                }
            }
        }
    }

    private String getResourceSha(Resource resource) throws RepositoryException, NoSuchAlgorithmException, IOException {
        Asset targetAsset;
        Node targetNode;
        if (null != resource && null != (targetAsset = (Asset)resource.adaptTo(Asset.class))) {
            return targetAsset.getMetadataValue("dam:sha1");
        }
        if (null != resource && null != (targetNode = (Node)resource.adaptTo(Node.class))) {
            Binary assetBinary = targetNode.getProperty("jcr:content/jcr:data").getBinary();
            MessageDigest assetSha = MessageDigest.getInstance("SHA1");
            byte[] assetBytes = IOUtils.toByteArray((InputStream)assetBinary.getStream());
            assetSha.update(assetBytes);
            return this.getSHA1(assetSha);
        }
        return null;
    }

    private void addResourceData(Resource resource, InputStream inputStream, String mimeType) throws RepositoryException, IOException {
        if (null != resource) {
            ByteArrayInputStream bais = new ByteArrayInputStream(IOUtils.toByteArray((InputStream)inputStream));
            Node content = ((Node)resource.adaptTo(Node.class)).getNode("jcr:content");
            Session session = (Session)resource.getResourceResolver().adaptTo(Session.class);
            content.setProperty("jcr:data", session.getValueFactory().createBinary((InputStream)bais));
            content.setProperty("jcr:lastModified", Calendar.getInstance());
            content.setProperty("jcr:mimeType", mimeType);
        }
    }

    protected Node getOrCreateRoot(UnarchiverContext context) throws RepositoryException {
        String assetPath;
        Node root;
        String rootHint;
        Session session = context.getSession();
        if (session.itemExists(rootHint = (assetPath = context.getExtractPath()) + "/" + context.getAppName())) {
            root = (Node)session.getItem(rootHint);
            this.log.debug("extract: update mode is [{}], using existing folder [{}]...", (Object)context.getUpdateMode().name(), (Object)rootHint);
        } else {
            root = JcrUtil.createPath((String)rootHint, (String)"sling:OrderedFolder", (Session)session);
            session.save();
            this.log.debug("extract: update mode is [{}], but destination doesn't exit, created [{}]", (Object)context.getUpdateMode().name(), (Object)rootHint);
        }
        return root;
    }

    /*
     * Enabled force condition propagation
     * Lifted jumps to return sites
     */
    protected Node findAssetAppRoot(Node node) throws RepositoryException {
        Node child;
        if (node == null) {
            return null;
        }
        if (node.hasNode("www")) {
            return node;
        }
        Node appNode = null;
        if (!node.hasNodes()) return appNode;
        NodeIterator childNodes = node.getNodes();
        while (childNodes.hasNext() && ("jcr:content".equals((child = childNodes.nextNode()).getName()) || (appNode = this.findAssetAppRoot(child)) == null)) {
        }
        return appNode;
    }

    private boolean isZipFile(UnarchiverContext context) {
        return "application/zip".equals(context.getArchiveContentType()) || context.getArchiveName().endsWith(".zip");
    }

    private String getSHA1(MessageDigest sha1) {
        return new BigInteger(1, sha1.digest()).toString(16);
    }

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

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

    protected static class EntryInfo {
        private static final String ROOT_FOLDER = "";
        private final ZipEntry entry;
        private final String path;
        private final String fileName;
        private final String parentPath;

        private EntryInfo(ZipEntry entry) {
            this.entry = entry;
            String name = entry.getName();
            this.path = name.endsWith("/") ? StringUtils.substring((String)name, (int)0, (int)(name.length() - 1)) : name;
            this.fileName = Text.getName((String)entry.getName());
            this.parentPath = Text.getRelativeParent((String)this.path, (int)1);
        }

        protected ZipEntry getEntry() {
            return this.entry;
        }

        protected String getFileName() {
            return this.fileName;
        }

        protected String getParentPath() {
            return StringUtils.isBlank((CharSequence)this.parentPath) ? "" : this.parentPath;
        }

        protected String getPath() {
            return this.path;
        }

        protected String getTargetPath(String rootPath) {
            return rootPath + "/" + ("".equals(this.getParentPath()) ? "" : new StringBuilder().append(this.getParentPath()).append("/").toString()) + Text.escapeIllegalJcrChars((String)this.getFileName());
        }
    }

    protected static class UnarchiverContext {
        protected static final long DEFAULT_SAVE_THRESHOLD = 1024;
        private final long saveThreshold;
        private final ResourceResolver resolver;
        private final Session session;
        private final AssetManager assetManager;
        private final RequestParameter archive;
        private final Resource archiveResource;
        private final String extractRootPath;
        private Node assetRoot;
        private UPDATE_MODE updateMode;
        private WidgetConfigDocument widgetDoc;
        private MobileResource appInstance;
        private long numFiles = 0;

        private UnarchiverContext(ResourceResolver resourceResolver, RequestParameter archive, String extractRootPath) {
            this.resolver = resourceResolver;
            this.session = (Session)resourceResolver.adaptTo(Session.class);
            this.assetManager = (AssetManager)resourceResolver.adaptTo(AssetManager.class);
            this.archive = archive;
            this.archiveResource = null;
            this.extractRootPath = extractRootPath;
            this.saveThreshold = 1024;
            this.updateMode = UPDATE_MODE.UPDATE;
        }

        private UnarchiverContext(ResourceResolver resourceResolver, Resource archive, String extractRootPath) {
            this.resolver = resourceResolver;
            this.session = (Session)resourceResolver.adaptTo(Session.class);
            this.assetManager = (AssetManager)resourceResolver.adaptTo(AssetManager.class);
            this.archive = null;
            this.archiveResource = archive;
            this.extractRootPath = extractRootPath;
            this.saveThreshold = 1024;
            this.updateMode = UPDATE_MODE.UPDATE;
        }

        public AssetManager getAssetManager() {
            return this.assetManager;
        }

        public ResourceResolver getResourceResolver() {
            return this.resolver;
        }

        public Session getSession() {
            return this.session;
        }

        public EntryInfo getEntryInfo(ZipEntry entry) {
            return new EntryInfo(entry);
        }

        public long getSaveThreshold() {
            return this.saveThreshold;
        }

        public Node getAssetRoot() {
            return this.assetRoot;
        }

        public WidgetConfigDocument getConfigDocument() {
            return this.widgetDoc;
        }

        public MobileResource getAppInstance() {
            return this.appInstance;
        }

        public UPDATE_MODE getUpdateMode() {
            return this.updateMode;
        }

        public String getExtractPath() {
            Document configDoc = this.getConfigDocument().adaptTo(Document.class);
            Element widget = configDoc.getDocumentElement();
            String assetPath = widget.getAttributeNS("http://www.day.com/jcr/cq/1.0", "assetPath");
            if (StringUtils.isNotBlank((CharSequence)assetPath)) {
                return assetPath;
            }
            return this.extractRootPath;
        }

        public String getArchivePath() {
            if (this.archiveResource != null) {
                return this.archiveResource.getPath();
            }
            return null;
        }

        public String getArchiveName() {
            if (this.archive != null) {
                return this.archive.getFileName();
            }
            if (this.archiveResource != null) {
                return this.archiveResource.getName();
            }
            return null;
        }

        public String getArchiveContentType() {
            if (this.archive != null) {
                return this.archive.getContentType();
            }
            if (this.archiveResource != null) {
                Resource jcrContent = this.archiveResource.getChild("jcr:content");
                return (String)((ValueMap)jcrContent.adaptTo(ValueMap.class)).get((Object)"jcr:mimeType");
            }
            return null;
        }

        public String getAppName() {
            Document configDoc = this.getConfigDocument().adaptTo(Document.class);
            Element widget = configDoc.getDocumentElement();
            String appName = widget.getAttributeNS("http://www.day.com/jcr/cq/1.0", "appName");
            if (StringUtils.isBlank((CharSequence)appName)) {
                appName = this.getConfigDocument().getName();
            }
            if (StringUtils.isBlank((CharSequence)appName)) {
                appName = StringUtils.substringBeforeLast((String)this.getArchiveName(), (String)".");
            }
            appName = JcrUtil.createValidName((String)appName);
            return appName;
        }

        public String getAppTemplate() {
            Document configDoc = this.getConfigDocument().adaptTo(Document.class);
            Element widget = configDoc.getDocumentElement();
            return widget.getAttributeNS("http://www.day.com/jcr/cq/1.0", "templatePath");
        }

        protected ZipInputStream createZipInputStream() throws IOException {
            if (this.archive != null) {
                return new ZipInputStream(new BufferedInputStream(this.archive.getInputStream()));
            }
            if (this.archiveResource != null) {
                Resource jcrContent = this.archiveResource.getChild("jcr:content");
                return new ZipInputStream(new BufferedInputStream((InputStream)((ValueMap)jcrContent.adaptTo(ValueMap.class)).get((Object)"jcr:data")));
            }
            return null;
        }

        private void setAssetRoot(Node root) {
            this.assetRoot = root;
        }

        private void setConfigDocument(WidgetConfigDocument doc) {
            this.widgetDoc = doc;
        }

        private void setAppInstance(MobileResource resource) {
            this.appInstance = resource;
        }

        private long updateNumFiles() {
            ++this.numFiles;
            return this.numFiles;
        }

        protected static enum UPDATE_MODE {
            UPDATE;
            

            private UPDATE_MODE() {
            }
        }

    }

}