Html2PDFPhantomJS.java 30 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.aemds.bedrock.internal.OSGiUtils
 *  com.adobe.aemfd.docmanager.Document
 *  com.adobe.html2pdf.Html2PdfFontPaths
 *  com.adobe.html2pdf.Html2PdfSettings
 *  com.adobe.native2pdf.xml.FiletypeSettings
 *  com.adobe.native2pdf.xml.FiletypeSettings$Settings
 *  com.adobe.native2pdf.xml.FiletypeSettings$Settings$Html2Pdf
 *  com.adobe.native2pdf.xml.InitialView
 *  com.adobe.native2pdf.xml.SecuritySettings
 *  com.adobe.native2pdf.xml.SecuritySettings$Settings
 *  com.adobe.pdfg.common.AESProperties
 *  com.adobe.pdfg.common.JobConfiguration
 *  com.adobe.pdfg.common.PDFGGlobalCache
 *  com.adobe.pdfg.common.SettingValidator
 *  com.adobe.pdfg.common.Utils
 *  com.adobe.pdfg.exception.ConversionException
 *  com.adobe.pdfg.exception.FileFormatNotSupportedException
 *  com.adobe.pdfg.exception.InvalidParameterException
 *  com.adobe.pdfg.logging.PDFGLogger
 *  com.adobe.pdfg.service.api.PDFGConfigService
 *  com.adobe.service.ConnectionFactory
 *  com.day.cq.dam.handler.gibson.fontmanager.FontManagerService
 */
package com.adobe.pdfg.impl;

import com.adobe.aemds.bedrock.internal.OSGiUtils;
import com.adobe.aemfd.docmanager.Document;
import com.adobe.html2pdf.Html2PdfFontPaths;
import com.adobe.html2pdf.Html2PdfSettings;
import com.adobe.native2pdf.xml.FiletypeSettings;
import com.adobe.native2pdf.xml.InitialView;
import com.adobe.native2pdf.xml.SecuritySettings;
import com.adobe.pdfg.callbacks.HTMLToPDFTransactionCallback;
import com.adobe.pdfg.common.AESProperties;
import com.adobe.pdfg.common.JobConfiguration;
import com.adobe.pdfg.common.PDFGGlobalCache;
import com.adobe.pdfg.common.SettingValidator;
import com.adobe.pdfg.common.Utils;
import com.adobe.pdfg.exception.ConversionException;
import com.adobe.pdfg.exception.FileFormatNotSupportedException;
import com.adobe.pdfg.exception.InvalidParameterException;
import com.adobe.pdfg.impl.GeneratePDFServiceImpl;
import com.adobe.pdfg.impl.GeneratePDFUtil;
import com.adobe.pdfg.impl.Html2PDFConvertorHelper;
import com.adobe.pdfg.logging.PDFGLogger;
import com.adobe.pdfg.postprocess.PostProcessFileInfo;
import com.adobe.pdfg.service.api.PDFGConfigService;
import com.adobe.pdfg.transaction.TransactionCallback;
import com.adobe.pdfg.transaction.TransactionTemplate;
import com.adobe.service.ConnectionFactory;
import com.day.cq.dam.handler.gibson.fontmanager.FontManagerService;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.Semaphore;

public class Html2PDFPhantomJS
implements Html2PDFConvertorHelper.IHtml2PDFConvertor {
    protected static PDFGLogger pdfgLogger = PDFGLogger.getPDFGLogger(Html2PDFPhantomJS.class);
    private static Semaphore ourHtmlConversionLock = null;
    private static Pool phantomJSPool = null;
    private static final int SHUTDOWN_TIMEOUT = 10000;
    private static final int MAX_PHANTOMJS_POOL_SIZE = 100;

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     * Enabled aggressive block sorting
     * Enabled unnecessary exception pruning
     * Enabled aggressive exception aggregation
     * Converted monitor instructions to comments
     * Lifted jumps to return sites
     */
    public Map createPDF(GeneratePDFServiceImpl coreSvcImpl, String inputUrl, String fileTypeSettingsName, String securitySettingsName, Document settingsDoc, Document xmpDoc, String configString, File pdfgTmpDir, int spideringLevel, boolean isURL) throws ConversionException, FileFormatNotSupportedException, InvalidParameterException, Exception {
        Class<Html2PDFPhantomJS> class_;
        String jobIdentityId = (String)Utils.threadLocalValue.get();
        long waitTime = 0;
        StringBuilder debugMsgs = new StringBuilder();
        long startTime = System.currentTimeMillis();
        if (phantomJSPool == null) {
            debugMsgs.append("\nBefore (PhantomJS pool init) synchronized(Html2PDFPhantomJS.class) for job=" + jobIdentityId);
            class_ = Html2PDFPhantomJS.class;
            // MONITORENTER : com.adobe.pdfg.impl.Html2PDFPhantomJS.class
            if (phantomJSPool == null) {
                debugMsgs.append("\nBefore initializePhantomJSPool for job=" + jobIdentityId);
                StringBuilder PhantomJSPathBuilder = new StringBuilder(OSGiUtils.getCoreConfigService().getServerNativeDir());
                PhantomJSPathBuilder.append(File.separator).append("HtmlToPdfSvc").append(File.separator).append("bin").append(File.separator);
                String phantomJSExePath = PhantomJSPathBuilder.toString() + "phantomjs";
                String phantomJSListenerScriptPath = PhantomJSPathBuilder.toString() + "phantomjsListenerScript.js";
                Html2PDFPhantomJS.initializePhantomJSPool(coreSvcImpl, phantomJSExePath + " " + phantomJSListenerScriptPath);
                debugMsgs.append("\nAfter initializePhantomJSPool for job=" + jobIdentityId);
            }
            // MONITOREXIT : class_
        }
        if (ourHtmlConversionLock == null) {
            debugMsgs.append("\nBefore (conversion lock init) synchronized(Html2PDFPhantomJS.class) for job=" + jobIdentityId);
            class_ = Html2PDFPhantomJS.class;
            // MONITORENTER : com.adobe.pdfg.impl.Html2PDFPhantomJS.class
            if (ourHtmlConversionLock == null) {
                debugMsgs.append("\nBefore initializeHTMLConversionLock for job=" + jobIdentityId);
                Html2PDFPhantomJS.initializeHTMLConversionLock(coreSvcImpl);
                debugMsgs.append("\nAfter initializeHTMLConversionLock for job=" + jobIdentityId);
            }
            // MONITOREXIT : class_
        }
        pdfgLogger.info("001-024", new Object[]{inputUrl, new Date(startTime), jobIdentityId});
        pdfgLogger.info("001-016", new Object[]{inputUrl, "HTML to PDF"});
        boolean success = true;
        debugMsgs.append("\nBefore htmlConversionLock.acquire() for job=" + jobIdentityId);
        long waitStartTime = System.currentTimeMillis();
        ourHtmlConversionLock.acquire();
        long waitEndTime = System.currentTimeMillis();
        debugMsgs.append("\nAfter htmlConversionLock.acquire() for job=" + jobIdentityId);
        waitTime = waitEndTime - waitStartTime;
        try {
            Map xmpFile2;
            try {
                File tempPdf = new File(pdfgTmpDir, "TempHtmlToPdf");
                File pdfFile = new File(pdfgTmpDir, "HtmlToPdfResult");
                JobConfiguration config = null;
                try {
                    config = PDFGGlobalCache.getJobConfiguration((String)configString);
                }
                catch (Exception e) {
                    throw new InvalidParameterException(1001, (Throwable)e);
                }
                if (config == null) {
                    throw new InvalidParameterException(80001);
                }
                int timeoutSeconds = AESProperties.getMaximumTimeout();
                timeoutSeconds = Math.max(10, timeoutSeconds);
                timeoutSeconds = config.getConversionTimeoutSetting(10, timeoutSeconds, timeoutSeconds);
                HTMLToPDFTransactionCallback transactionCallback = new HTMLToPDFTransactionCallback(coreSvcImpl.getHtmlToPdfFactory());
                transactionCallback.setUsePhantomJS(true);
                transactionCallback.setSourcePath(inputUrl);
                transactionCallback.setDestinationPath(tempPdf.getAbsolutePath());
                transactionCallback.setTimeout(timeoutSeconds);
                transactionCallback.setHtml2PDFparams(config);
                transactionCallback.setIsURL(isURL);
                transactionCallback.setFontsPath(this.retrieveHtml2PdfFontPaths(coreSvcImpl));
                transactionCallback.setHTMLFont(coreSvcImpl.getFallbackFontForHTMLConversions());
                TransactionTemplate _txTemplate = coreSvcImpl.getTransactionTemplate();
                _txTemplate.setPropagationBehavior(0);
                _txTemplate.setTimeout(timeoutSeconds + 200);
                pdfgLogger.debug("before calling _txTemplate.execute for job=" + jobIdentityId);
                _txTemplate.execute(transactionCallback);
                FiletypeSettings.Settings.Html2Pdf html2pdf = config.getFiletypeSettings().getHtml2Pdf();
                InitialView initialView = html2pdf == null ? null : html2pdf.getInitialView();
                SecuritySettings.Settings securitySettings = config.getSecuritySettings();
                boolean shouldApplySecurity = Utils.shouldApplySecurity((SecuritySettings.Settings)securitySettings);
                String targetPdfVersion = null;
                if (shouldApplySecurity) {
                    SettingValidator validator = new SettingValidator(null, securitySettings);
                    if (validator.areEncryptionPasswordsIdentical()) {
                        throw new InvalidParameterException(80009);
                    }
                    int acrobatVersion = securitySettings.getAcrobatVersion();
                    if (acrobatVersion > 5) {
                        targetPdfVersion = "1." + (acrobatVersion - 1);
                    }
                    GeneratePDFUtil.updateSecuritySettings(coreSvcImpl.getConfigService(), securitySettings);
                } else {
                    securitySettings = null;
                }
                PostProcessFileInfo pp = new PostProcessFileInfo();
                pp.attachmentFilePath = "";
                pp.logFilePath = "";
                pp.tempPdfFilePath = tempPdf.getCanonicalPath();
                pp.pdfFilePath = pdfFile.getCanonicalPath();
                pp.xmpFilePath = "";
                if (xmpDoc != null) {
                    File xmpFile2 = new File(pdfgTmpDir, "HtmlToPdfXmp");
                    xmpDoc.copyToFile(xmpFile2);
                    pdfgLogger.info("001-020", new Object[]{inputUrl, xmpFile2.getName()});
                    pp.xmpFilePath = xmpFile2.getAbsolutePath();
                }
                coreSvcImpl.pdfPostProcess(pp, null, initialView, securitySettings, true, targetPdfVersion, "PDF generator", GeneratePDFUtil.applyWaterMark());
                xmpFile2 = this.getResponse(pp.pdfFilePath, null, null, pp.postProcessedDoc);
                Object var36_39 = null;
                debugMsgs.append("\nbefore htmlConversionLock.release() for job=" + jobIdentityId);
                ourHtmlConversionLock.release();
                debugMsgs.append("\nafter htmlConversionLock.release() for job=" + jobIdentityId);
            }
            catch (Exception e) {
                pdfgLogger.trace(e.getMessage(), null, (Throwable)e);
                success = false;
                throw e;
            }
            pdfgLogger.debug(debugMsgs.toString());
            long endTime = System.currentTimeMillis();
            if (success) {
                pdfgLogger.info("001-027", inputUrl);
            } else {
                pdfgLogger.info("001-028", inputUrl);
            }
            pdfgLogger.info("001-025", new Object[]{inputUrl, new Date(), jobIdentityId});
            pdfgLogger.info("001-030", new Object[]{inputUrl, waitTime, jobIdentityId});
            pdfgLogger.info("001-026", new Object[]{inputUrl, endTime - startTime - waitTime, jobIdentityId});
            return xmpFile2;
        }
        catch (Throwable var35_43) {
            Object var36_40 = null;
            debugMsgs.append("\nbefore htmlConversionLock.release() for job=" + jobIdentityId);
            ourHtmlConversionLock.release();
            debugMsgs.append("\nafter htmlConversionLock.release() for job=" + jobIdentityId);
            pdfgLogger.debug(debugMsgs.toString());
            long endTime = System.currentTimeMillis();
            if (success) {
                pdfgLogger.info("001-027", inputUrl);
            } else {
                pdfgLogger.info("001-028", inputUrl);
            }
            pdfgLogger.info("001-025", new Object[]{inputUrl, new Date(), jobIdentityId});
            pdfgLogger.info("001-030", new Object[]{inputUrl, waitTime, jobIdentityId});
            pdfgLogger.info("001-026", new Object[]{inputUrl, endTime - startTime - waitTime, jobIdentityId});
            throw var35_43;
        }
    }

    private static void initializeHTMLConversionLock(GeneratePDFServiceImpl coreSvcImpl) {
        ourHtmlConversionLock = new Semaphore(coreSvcImpl.getHtmlToPdfPoolSize(), true);
    }

    private static void initializePhantomJSPool(GeneratePDFServiceImpl coreSvcImpl, String cmdLine) {
        phantomJSPool = Pool.getInstance(100, 100, cmdLine);
    }

    private Html2PdfFontPaths retrieveHtml2PdfFontPaths(GeneratePDFServiceImpl coreSvcImpl) {
        Html2PdfFontPaths fontPaths = new Html2PdfFontPaths();
        fontPaths.customerFontPath = "";
        fontPaths.systemFontPath = "";
        fontPaths.adobeFontPath = "";
        try {
            fontPaths.customerFontPath = this.getNormalizedFontPath(coreSvcImpl.getFontManagerService().getCustomerFontDirectory());
        }
        catch (Exception ex2) {
            pdfgLogger.warning(ex2.getLocalizedMessage(), "");
            pdfgLogger.trace(ex2.getMessage(), null, (Throwable)ex2);
        }
        try {
            fontPaths.systemFontPath = this.getNormalizedFontPath(coreSvcImpl.getFontManagerService().getSystemFontDirectory());
        }
        catch (Exception ex2) {
            pdfgLogger.warning(ex2.getLocalizedMessage(), "");
            pdfgLogger.trace(ex2.getMessage(), null, (Throwable)ex2);
        }
        try {
            fontPaths.adobeFontPath = this.getNormalizedFontPath(coreSvcImpl.getFontManagerService().getAdobeServerFontDirectory());
        }
        catch (Exception ex2) {
            pdfgLogger.warning(ex2.getLocalizedMessage(), "");
            pdfgLogger.trace(ex2.getMessage(), null, (Throwable)ex2);
        }
        return fontPaths;
    }

    private String getNormalizedFontPath(String path) {
        String fileSeparator = System.getProperty("file.separator");
        String pathSeparator = ";";
        String modifiedPath = "";
        if (path == null) {
            return modifiedPath;
        }
        StringTokenizer tokens = new StringTokenizer(path, ";");
        while (tokens.hasMoreTokens()) {
            path = tokens.nextToken();
            if (path != null && !"".equals(path)) {
                modifiedPath = !path.endsWith(fileSeparator) ? modifiedPath + path + fileSeparator : modifiedPath + path;
            }
            if (!tokens.hasMoreTokens()) continue;
            modifiedPath = modifiedPath + ";";
        }
        return modifiedPath;
    }

    private Map getResponse(String pdfFilePath, String jdfFilePath, String logFilePath, Document postProcessedDoc) {
        File logFile;
        File pdfFile;
        HashMap<String, Document> response = new HashMap<String, Document>();
        Document convertedDoc = postProcessedDoc;
        if (convertedDoc == null && pdfFilePath != null && (pdfFile = new File(pdfFilePath)).exists() && pdfFile.length() > 0) {
            convertedDoc = new Document(pdfFile, true);
        }
        if (pdfFilePath != null && pdfFilePath.indexOf(".pdf") < 0) {
            convertedDoc.setAttribute("file", (Object)(pdfFilePath + ".pdf"));
            convertedDoc.setContentType("application/pdf");
        }
        Document logDoc = null;
        if (logFilePath != null && (logFile = new File(logFilePath)).exists() && logFile.length() > 0) {
            logDoc = new Document(logFile, true);
            if (logFilePath.indexOf(".log") < 0) {
                logDoc.setAttribute("file", (Object)(logFilePath + ".log"));
                logDoc.setContentType("text/plain");
            }
        }
        if (convertedDoc != null) {
            response.put("ConvertedDoc", convertedDoc);
        }
        if (logDoc != null) {
            response.put("LogDoc", logDoc);
        }
        return response;
    }

    public static Pool getPool() {
        return phantomJSPool;
    }

    public static class Pool {
        static Pool instance;
        int maxPoolSize;
        int maxUseCount;
        String commandLine;
        List<Process> processPool = new ArrayList<Process>();

        public static synchronized Pool getInstance(int size, int count, String cmdLine) {
            if (instance == null) {
                instance = new Pool(size, count, cmdLine);
            }
            return instance;
        }

        private Pool(int size, int count, String cmdLine) {
            this.maxPoolSize = size;
            this.maxUseCount = count;
            this.commandLine = cmdLine;
        }

        /*
         * Unable to fully structure code
         * Enabled aggressive block sorting
         * Enabled unnecessary exception pruning
         * Enabled aggressive exception aggregation
         * Lifted jumps to return sites
         */
        public synchronized Process acquire() {
            do {
                for (Process proc : this.processPool) {
                    if (proc.allocated) continue;
                    proc.allocated = true;
                    return proc;
                }
                if (this.processPool.size() < this.maxPoolSize) {
                    proc = this.createProcess();
                    if (proc == null) ** continue;
                    this.processPool.add(proc);
                    proc.allocated = true;
                    return proc;
                }
                try {
                    this.wait();
                }
                catch (InterruptedException ie) {
                }
            } while (true);
        }

        public synchronized void release(Process proc) {
            if (proc == null) {
                return;
            }
            if (proc.allocated) {
                proc.allocated = false;
            }
            if (proc.useCount >= this.maxUseCount || proc.rogueProcess) {
                proc.shutdown();
                proc.doProcessExitCleanup();
                this.processPool.remove(proc);
            }
            this.notifyAll();
        }

        private Process createProcess() {
            Process proc = new Process(this.commandLine);
            proc.create();
            return proc;
        }
    }

    public static class Process {
        java.lang.Process process;
        String commandLine;
        int useCount;
        boolean allocated;
        private ReaderThread stdoutReader;
        private ReaderThread stderrReader;
        private BufferedWriter stdinWriter;
        private static boolean plannedShutdown = false;
        public boolean rogueProcess = false;

        public Process(String cmdLine) {
            this.commandLine = cmdLine;
            this.useCount = 0;
            this.allocated = false;
        }

        private void writeToProcess(String param) throws IOException {
            this.stdinWriter.write(param);
            this.stdinWriter.newLine();
            this.stdinWriter.flush();
        }

        /*
         * WARNING - Removed try catching itself - possible behaviour change.
         * Enabled aggressive block sorting
         * Enabled unnecessary exception pruning
         * Enabled aggressive exception aggregation
         */
        public void convertToPdf(String url, String pdfFilePath, String controlFilePath, Html2PdfSettings htmlConversionSettings, Html2PdfFontPaths fontPaths, long timeout) {
            try {
                try {
                    this.writeToProcess(url);
                    this.writeToProcess(pdfFilePath);
                    this.writeToProcess(controlFilePath);
                    this.writeToProcess(String.valueOf(htmlConversionSettings.MarginBottom) + "in");
                    this.writeToProcess(String.valueOf(htmlConversionSettings.MarginLeft) + "in");
                    this.writeToProcess(String.valueOf(htmlConversionSettings.MarginRight) + "in");
                    this.writeToProcess(String.valueOf(htmlConversionSettings.MarginTop) + "in");
                    this.writeToProcess(String.valueOf(htmlConversionSettings.Orientation));
                    this.writeToProcess(String.valueOf(htmlConversionSettings.PageHeight) + "in");
                    this.writeToProcess(String.valueOf(htmlConversionSettings.PageWidth) + "in");
                    this.writeToProcess(String.valueOf(htmlConversionSettings.isPlaceHeader));
                    this.writeToProcess("");
                    this.writeToProcess(String.valueOf(htmlConversionSettings.isPlaceFooter));
                    this.writeToProcess("");
                }
                catch (Exception e) {
                    Html2PDFPhantomJS.pdfgLogger.warning("Exception while writing to PhantomJS process: " + e);
                    Object var10_8 = null;
                    ++this.useCount;
                    return;
                }
                Object var10_7 = null;
                ++this.useCount;
                return;
            }
            catch (Throwable var9_11) {
                Object var10_9 = null;
                ++this.useCount;
                throw var9_11;
            }
        }

        public void create() {
            try {
                this.process = Runtime.getRuntime().exec(this.commandLine);
            }
            catch (IOException ioe) {
                Html2PDFPhantomJS.pdfgLogger.warning("Exception while creating PhantomJS process: " + ioe);
            }
            if (this.process != null) {
                this.stdoutReader = new OutputReaderThread();
                this.stderrReader = new ErrorReaderThread();
                this.stdinWriter = new BufferedWriter(new OutputStreamWriter(this.process.getOutputStream()));
                this.stdoutReader.start();
                this.stderrReader.start();
            }
        }

        public void shutdown() {
            plannedShutdown = false;
            try {
                if (this.process != null) {
                    Html2PDFPhantomJS.pdfgLogger.info("PhantomJS process stopping");
                    plannedShutdown = true;
                    this.stdinWriter.write("--EOF--");
                    this.stdinWriter.newLine();
                    this.stdinWriter.flush();
                    do {
                        try {
                            this.stdoutReader.join(10000);
                            break;
                        }
                        catch (InterruptedException e) {
                            Html2PDFPhantomJS.pdfgLogger.debug("Interrupted waiting for thread to terminate. Trying again...", null, (Throwable)e);
                            continue;
                        }
                        break;
                    } while (true);
                    do {
                        try {
                            this.stderrReader.join(10000);
                            break;
                        }
                        catch (InterruptedException e) {
                            Html2PDFPhantomJS.pdfgLogger.debug("Interrupted waiting for thread to terminate. Trying again...", null, (Throwable)e);
                            continue;
                        }
                        break;
                    } while (true);
                    if (this.process != null) {
                        Html2PDFPhantomJS.pdfgLogger.info("PhantomJS process destroying");
                        this.process.destroy();
                    }
                }
            }
            catch (Exception e) {
                Html2PDFPhantomJS.pdfgLogger.warning("Error stopping process " + e.getLocalizedMessage());
            }
        }

        public void doProcessExitCleanup() {
            if (!plannedShutdown) {
                Html2PDFPhantomJS.pdfgLogger.warning("PhantomJS process terminated abnormally");
            }
            this.process = null;
        }

        private class OutputReaderThread
        extends ReaderThread {
            public OutputReaderThread() {
                super("PhantomJSProcess Output Reader", Process.this.process.getInputStream(), System.out);
            }
        }

        private class ErrorReaderThread
        extends ReaderThread {
            public ErrorReaderThread() {
                super("PhantomJS Process Error Reader", Process.this.process.getErrorStream(), System.err);
            }

            /*
             * WARNING - Removed try catching itself - possible behaviour change.
             * Unable to fully structure code
             * Enabled aggressive block sorting
             * Enabled unnecessary exception pruning
             * Enabled aggressive exception aggregation
             * Lifted jumps to return sites
             */
            public void run() {
                super.run();
                try {
                    block11 : {
                        try {
                            if (Process.this.process == null) break block11;
                            Process.this.process.getOutputStream().close();
                        }
                        catch (IOException e) {
                            Html2PDFPhantomJS.pdfgLogger.warning("Error closing process output stream " + e.getLocalizedMessage());
                            var3_2 = null;
                            do {
                                try {
                                    if (Process.this.process == null) return;
                                    Process.this.process.waitFor();
                                    return;
                                }
                                catch (InterruptedException e) {
                                    Html2PDFPhantomJS.pdfgLogger.warning("Interrupted waiting for process to terminate. Trying again..." + e.getLocalizedMessage());
                                    continue;
                                }
                                break;
                            } while (true);
                        }
                    }
                    var3_1 = null;
                    ** GOTO lbl24
                }
                catch (Throwable var2_8) {
                    ** GOTO lbl32
lbl24: // 1 sources:
                    do {
                        try {}
                        catch (InterruptedException e) {
                            Html2PDFPhantomJS.pdfgLogger.warning("Interrupted waiting for process to terminate. Trying again..." + e.getLocalizedMessage());
                            continue;
                        }
                        if (Process.this.process == null) return;
                        Process.this.process.waitFor();
                        return;
                        break;
                    } while (true);
lbl32: // 1 sources:
                    var3_3 = null;
                    do {
                        try {}
                        catch (InterruptedException e) {
                            Html2PDFPhantomJS.pdfgLogger.warning("Interrupted waiting for process to terminate. Trying again..." + e.getLocalizedMessage());
                            continue;
                        }
                        if (Process.this.process == null) throw var2_8;
                        Process.this.process.waitFor();
                        throw var2_8;
                        break;
                    } while (true);
                }
            }
        }

        private class ReaderThread
        extends Thread {
            private InputStream in;
            private PrintStream out;
            private final int BUFLEN = 512;
            private byte[] buffer;

            ReaderThread(String name, InputStream in, PrintStream out) {
                super(name);
                this.in = null;
                this.out = null;
                this.BUFLEN = 512;
                this.buffer = new byte[512];
                this.in = in;
                this.out = out;
            }

            /*
             * WARNING - Removed try catching itself - possible behaviour change.
             * Unable to fully structure code
             * Enabled aggressive block sorting
             * Enabled unnecessary exception pruning
             * Enabled aggressive exception aggregation
             * Lifted jumps to return sites
             */
            public void run() {
                try {
                    try {}
                    catch (IOException e) {
                        Html2PDFPhantomJS.pdfgLogger.warning("Error reading process error/input stream", e.getLocalizedMessage());
                        var3_4 = null;
                        try {
                            if (this.in == null) return;
                            this.in.close();
                            return;
                        }
                        catch (IOException e1) {
                            Html2PDFPhantomJS.pdfgLogger.warning("Error closing process error/input stream", e1.getLocalizedMessage());
                            return;
                        }
                    }
                }
                catch (Throwable throwable) {
                    var3_5 = null;
                    ** try [egrp 2[TRYBLOCK] [4 : 68->85)] { 
lbl19: // 1 sources:
                    if (this.in == null) throw throwable;
                    this.in.close();
                    throw throwable;
lbl22: // 1 sources:
                    catch (IOException e1) {
                        Html2PDFPhantomJS.pdfgLogger.warning("Error closing process error/input stream", e1.getLocalizedMessage());
                    }
                    throw throwable;
                }
                do {
                    if ((bytesRead = this.in.read(this.buffer)) == -1) break;
                    this.out.write(this.buffer, 0, bytesRead);
                } while (true);
                var3_3 = null;
                try {}
                catch (IOException e1) {
                    Html2PDFPhantomJS.pdfgLogger.warning("Error closing process error/input stream", e1.getLocalizedMessage());
                    return;
                }
                if (this.in == null) return;
                this.in.close();
            }
        }

    }

}