Utils.java 13.7 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.aemfd.docmanager.Document
 *  com.adobe.pdfg.exception.InvalidParameterException
 *  com.adobe.pdfg.exception.JobOptionsParseException
 *  com.adobe.pdfg.exception.NotAPDFException
 *  com.adobe.pdfg.exception.PageNotFoundException
 *  com.adobe.pdfg.logging.PDFGLogger
 */
package com.adobe.pdfg.common;

import com.adobe.aemfd.docmanager.Document;
import com.adobe.native2pdf.xml.SecuritySettings;
import com.adobe.pdfg.common.AESProperties;
import com.adobe.pdfg.common.Constants;
import com.adobe.pdfg.common.PDFGGlobalCache;
import com.adobe.pdfg.exception.InvalidParameterException;
import com.adobe.pdfg.exception.JobOptionsParseException;
import com.adobe.pdfg.exception.NotAPDFException;
import com.adobe.pdfg.exception.PageNotFoundException;
import com.adobe.pdfg.logging.PDFGLogger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * This class specifies class file version 49.0 but uses Java 6 signatures.  Assumed Java 6.
 */
public class Utils
implements Serializable {
    public static final String StandardInputFileName = "File";
    protected static Map<String, String> permissionsMap = new HashMap<String, String>();
    protected static Map<String, String> resourcesMap = new HashMap<String, String>();
    static final long serialVersionUID = 1101;
    private static PDFGLogger pdfgLogger = PDFGLogger.getPDFGLogger(Utils.class);
    private static int threadCount = 0;
    public static ThreadLocal<String> threadLocalValue = new ThreadLocal<String>(){

        @Override
        protected String initialValue() {
            return "" + threadCount++;
        }
    };

    public static String getPDFName(String urlStr) {
        int pathstart;
        int filestart = urlStr.lastIndexOf(47);
        String name = null;
        name = filestart >= 0 && filestart != urlStr.length() - 1 ? urlStr.substring(filestart + 1) : ((pathstart = urlStr.indexOf(47)) >= 0 && pathstart != urlStr.length() - 1 ? urlStr.substring(pathstart + 1) : urlStr);
        name = name.replaceAll("[\\\\]", "_");
        for (int i = 0; i < Constants.INVALID_CHARS.length; ++i) {
            name = name.replaceAll("[" + Constants.INVALID_CHARS[i] + "]", "_");
        }
        name = name.toLowerCase().endsWith(".pdf") ? name.substring(0, name.length() - 4).replaceAll("[.]", "_") : name.replaceAll("[.]", "_");
        return name + ".pdf";
    }

    public static boolean isCallerAuthorizedUser() throws Exception {
        return Utils.doesCallerHavePermission("PDFGUserPermission", "PDFGUserResource") || Utils.doesCallerHavePermission("PDFGAdminPermission", "PDFGAdminResource");
    }

    public static boolean isCallerAuthorizedAdmin() throws Exception {
        return Utils.doesCallerHavePermission("PDFGAdminPermission", "PDFGAdminResource");
    }

    private static boolean doesCallerHavePermission(String permissionName, String resourceTypeName) {
        return true;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static boolean hasPdfContent(String pdfUrlStr) throws Exception {
        String strRead;
        boolean retVal;
        retVal = false;
        URL pdfUrl = new URL(pdfUrlStr);
        URLConnection uconn = pdfUrl.openConnection();
        HttpURLConnection hconn = (HttpURLConnection)uconn;
        hconn.setInstanceFollowRedirects(true);
        byte[] buf = new byte[1024];
        hconn.connect();
        if (hconn.getResponseCode() == 404) {
            throw new PageNotFoundException();
        }
        InputStream is = null;
        strRead = "";
        try {
            int read;
            is = hconn.getInputStream();
            int totalread = 0;
            while ((read = is.read(buf)) != -1) {
                strRead = strRead + new String(buf, 0, read);
                if ((totalread += read) <= 1024) continue;
                break;
            }
        }
        finally {
            if (is != null) {
                try {
                    is.close();
                }
                catch (IOException e) {
                    pdfgLogger.trace(e.getMessage(), null, (Throwable)e);
                }
            }
        }
        if (strRead.indexOf("%PDF") < 0 && (strRead.indexOf("%!PS?Adobe?") < 0 || strRead.indexOf("PDF?") < 0)) {
            throw new NotAPDFException();
        }
        retVal = true;
        return retVal;
    }

    public static void flagInvalidFolders(Map wm) {
        for (String key : wm.keySet()) {
            File folder = new File(key);
            if (folder.exists() && folder.isDirectory()) {
                ((Map)wm.get(key)).put("invalidfolder", Boolean.FALSE);
                continue;
            }
            ((Map)wm.get(key)).put("invalidfolder", Boolean.TRUE);
        }
    }

    public static boolean shouldApplySecurity(SecuritySettings.Settings security) {
        boolean applySecurity = false;
        if (security != null && !"None".equals(security.getEncrypt())) {
            if (security.isSetDocumentOpenPasswd() && security.getDocumentOpenPasswd().length() > 0) {
                applySecurity = true;
            } else if (security.isSetDocumentChangePasswd() && security.getDocumentChangePasswd().length() > 0) {
                applySecurity = true;
            }
        }
        return applySecurity;
    }

    private static Object clone(Object obj) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream oout = new ObjectOutputStream(out);
            oout.writeObject(obj);
            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
            return in.readObject();
        }
        catch (Exception e) {
            pdfgLogger.debug(e.getMessage(), null, (Throwable)e);
            return null;
        }
    }

    public static String getLocale(Locale locale) {
        if (locale != null) {
            String language = AESProperties.getLocale().getLanguage();
            if (locale.getLanguage() != null && locale.getLanguage().length() > 0) {
                if (locale.getCountry() != null && locale.getCountry().length() > 0) {
                    return locale.getLanguage() + "_" + locale.getCountry();
                }
                language = locale.getLanguage();
            }
            if (language.startsWith("de")) {
                return "de_DE";
            }
            if (language.startsWith("fr")) {
                return "fr_FR";
            }
            if (language.startsWith("ja")) {
                return "ja_JP";
            }
        }
        return "en_US";
    }

    public static boolean checkSettingName(String name) {
        char[] splchars = new char[]{'<', '>', '\\', '/', ':', '?', '|', '*', '\"', '&', ';'};
        for (int i = 0; i < splchars.length; ++i) {
            if (name.indexOf(splchars[i]) == -1) continue;
            return false;
        }
        return true;
    }

    public static boolean checkFontName(List names) {
        if (names != null) {
            Iterator itr = names.iterator();
            Pattern p = Pattern.compile("(.)*((\\[)+|(\\<)+|(\\])+|(>)+|(\\s)+)+(.)*");
            while (itr.hasNext()) {
                String currString = (String)itr.next();
                Matcher m = p.matcher(currString);
                if (!m.matches()) continue;
                return false;
            }
        }
        return true;
    }

    public static Double parseNumber(String input, NumberFormat formatter, double defaultValue) {
        try {
            return new Double(formatter.parse(input).doubleValue());
        }
        catch (ParseException pe) {
            pdfgLogger.trace(pe.getMessage(), null, (Throwable)pe);
            return new Double(defaultValue);
        }
    }

    public static boolean isPDFAComplianceOn(String jobOptionsString) throws JobOptionsParseException {
        Map jobOptionsMap = PDFGGlobalCache.getJobOptionsMap(jobOptionsString);
        Map ditillerParametersMap = (Map)jobOptionsMap.get("setdistillerparams");
        return Utils.isPDFAComplianceOn(ditillerParametersMap);
    }

    public static boolean isPDFAComplianceOn(Map distillerParameters) {
        String cStd;
        boolean retVal = false;
        List compList = (List)distillerParameters.get("CheckCompliance");
        if (compList != null && compList.size() > 0 && ((cStd = (String)compList.get(0)).equals("PDFA:DRAFT") || cStd.equals("PDFA1B:2005"))) {
            retVal = true;
        }
        return retVal;
    }

    public static String checkJobOptionsPageNumbers(String jobOptionsString) throws JobOptionsParseException {
        StringBuilder retval = new StringBuilder(jobOptionsString);
        Map jobOptionsMap = PDFGGlobalCache.getJobOptionsMap(jobOptionsString);
        Map ditillerParametersMap = (Map)jobOptionsMap.get("setdistillerparams");
        int startPageNo = (Integer)ditillerParametersMap.get("StartPage");
        int endPageNo = (Integer)ditillerParametersMap.get("EndPage");
        if (endPageNo != -1 && startPageNo > endPageNo) {
            Map<String, Object> startPageIndex = Utils.getIndex("StartPage", jobOptionsString, startPageNo);
            int startPageBeginIndex = (Integer)startPageIndex.get("beginIndex");
            int startPageEndIndex = (Integer)startPageIndex.get("endIndex");
            retval = retval.replace(startPageBeginIndex, startPageEndIndex, "StartPage " + endPageNo);
            Map<String, Object> endPageIndex = Utils.getIndex("EndPage", retval.toString(), endPageNo);
            int endPageBeginIndex = (Integer)endPageIndex.get("beginIndex");
            int endPageEndIndex = (Integer)endPageIndex.get("endIndex");
            ditillerParametersMap.put("StartPage", new Integer(endPageNo));
            ditillerParametersMap.put("EndPage", new Integer(startPageNo));
            retval = retval.replace(endPageBeginIndex, endPageEndIndex, "EndPage " + startPageNo);
        }
        return retval.toString();
    }

    private static Map<String, Object> getIndex(String searchStr, String jobOptionsString, int pageNo) {
        HashMap<String, Object> indexMap = new HashMap<String, Object>();
        int beginIndexOfSearchStr = jobOptionsString.indexOf(searchStr);
        int beginIndexOfPageNo = jobOptionsString.indexOf(new Integer(pageNo).toString(), beginIndexOfSearchStr);
        int endIndexOfPageNo = jobOptionsString.indexOf("\n", beginIndexOfPageNo);
        indexMap.put("beginIndex", new Integer(beginIndexOfSearchStr));
        indexMap.put("endIndex", new Integer(endIndexOfPageNo));
        return indexMap;
    }

    private static String getFileFromDocumentAttribute(Document inputDoc) {
        String fileAttr = (String)inputDoc.getAttribute("adobe.docmanager.source.file");
        if (null == fileAttr || 0 == fileAttr.length()) {
            fileAttr = (String)inputDoc.getAttribute("adobe.docmanager.source.url");
        }
        return fileAttr;
    }

    private static String generateUniqueFilename(String inputFileExtension) {
        if (!inputFileExtension.startsWith(".")) {
            inputFileExtension = "." + inputFileExtension;
        }
        return "File" + inputFileExtension;
    }

    private static String validateFileExtension(Document inputDoc, String inputFileExtension) throws InvalidParameterException {
        String fileAttr = null;
        if (inputFileExtension != null && 0 != inputFileExtension.length()) {
            fileAttr = Utils.generateUniqueFilename(inputFileExtension);
        }
        return Utils.validateFilename(inputDoc, fileAttr);
    }

    public static String validateFilename(Document inputDoc, String inputFilename) throws InvalidParameterException {
        String fileAttr = inputFilename;
        if (null == fileAttr || 0 == fileAttr.length()) {
            fileAttr = Utils.getFileFromDocumentAttribute(inputDoc);
        }
        if (null == fileAttr || 0 == fileAttr.length()) {
            throw new InvalidParameterException(11020);
        }
        return Utils.getValidName(fileAttr);
    }

    private static String getValidName(String fileName) {
        int nameStartIndex = fileName.lastIndexOf(92);
        if (nameStartIndex == -1) {
            nameStartIndex = fileName.lastIndexOf(47);
        }
        return fileName.substring(nameStartIndex + 1, fileName.length());
    }

    public static String validate(Document inputDoc, String inputFilenameOrExtension, ValidateOption validateOption) throws InvalidParameterException {
        if (validateOption == ValidateOption.VALIDATE_FILENAME) {
            return Utils.validateFilename(inputDoc, inputFilenameOrExtension);
        }
        return Utils.validateFileExtension(inputDoc, inputFilenameOrExtension);
    }

    public static String unsplit(String[] strs) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < strs.length; ++i) {
            if (i != 0) {
                buf.append(' ');
            }
            buf.append(strs[i]);
        }
        return buf.toString();
    }

    /*
     * This class specifies class file version 49.0 but uses Java 6 signatures.  Assumed Java 6.
     */
    public static enum ValidateOption {
        VALIDATE_FILENAME,
        VALIDATE_FILE_EXTENSION;
        

        private ValidateOption() {
        }
    }

}