PDFGAdminServlet.java 19.2 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.crypto.CryptoSupport
 *  com.adobe.pdfg.config.PDFGConfigUtility
 *  com.adobe.pdfg.exception.ConfigException
 *  com.adobe.pdfg.service.api.GeneratePDFService
 *  com.adobe.pdfg.service.api.PDFGConfigService
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.servlet.Servlet
 *  javax.servlet.ServletOutputStream
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.api.request.RequestParameter
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.servlets.SlingAllMethodsServlet
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.pdfg.admin;

import com.adobe.granite.crypto.CryptoSupport;
import com.adobe.pdfg.config.PDFGConfigUtility;
import com.adobe.pdfg.exception.ConfigException;
import com.adobe.pdfg.service.api.GeneratePDFService;
import com.adobe.pdfg.service.api.PDFGConfigService;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.Servlet;
import javax.servlet.ServletOutputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

/*
 * This class specifies class file version 49.0 but uses Java 6 signatures.  Assumed Java 6.
 */
@Component(metatype=1, immediate=1, label="PDFGAdminServlet", description="PDFG Administration Helper Servlet")
@Service(value={Servlet.class})
@Properties(value={@Property(name="sling.servlet.extensions", value={"html"}), @Property(name="sling.servlet.paths", value={"/libs/fd/pdfg/config/handler"}), @Property(name="sling.servlet.methods", value={"GET", "POST"}), @Property(name="sling.auth.requirements", value={"-/libs/fd/pdfg/config"})})
public class PDFGAdminServlet
extends SlingAllMethodsServlet {
    public static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
    public static final String XML_CONTENT_TYPE = "text/xml;charset=UTF-8";
    public static final String ATTACHMENT_HEADER = "attachment;filename=exported_settings.xml";
    public static final String fileName = "result";
    public static final String lineSeparator = System.getProperty("line.separator");
    public static final String XML_NODE_FILE2PDF_SETTINGS = "file2pdf-settings";
    public static final String XML_NODE_SETTINGS_VERSION = "11.0.0";
    public static final String XML_NODE_FILETYPE_SETTINGS = "filetype-settings";
    public static final String XML_NODE_JOB_OPTIONS = "job-options";
    public static final String XML_NODE_SECURITY_SETTINGS = "security-settings";
    private static final String PDFG_SETTINGS_NODE_PATH = "etc/fd/pdfg/admin/settings";
    private static final String PDFG_PROPERTY_PREFIX = "pdfg_";
    private static final String REQUEST_PARAM_IMPORT_SETTINGS = "__importSettings";
    private static final String REQUEST_PARAM_IMPORT_SETTINGS_RESET = "reset";
    private static final String REQUEST_PARAM_IMPORT_SETTINGS_EXISTING = "existing";
    private static final String REQUEST_PARAM_EXPORT_SETTINGS = "__exportSettings";
    private static final String REQUEST_PARAM_EXPORT_SETTINGS_ENTIRE = "entire";
    private static final String REQUEST_PARAM_EXPORT_SETTINGS_MINIMAL = "minimal";
    private static final String REQUEST_PARAM_MODIFY_USER = "__modifyUser";
    private static final String REQUEST_PARAM_MODIFY_USER_PASSWORD = "__modifyUserPwd";
    private static final String REQUEST_PARAM_DELETE_USER = "__deleteUser";
    private static final String REQUEST_PARAM_MODIFY_SETTING = "__modifySetting";
    private static final String REQUEST_PARAM_MODIFY_OPEN_PASSWORD = "__modifyOpenPasswd";
    private static final String REQUEST_PARAM_MODIFY_PERM_PASSWORD = "__modifyPermPasswd";
    private static final String REQUEST_PARAM_DELETE_SETTING = "__deleteSetting";
    private static final String REQUEST_PARAM_FETCH_SECURITY_SETTINGS = "__fetchSecuritySettings";
    private static final String REQUEST_PARAM_MODIFY_GENERAL_CONFIG = "__modifyGeneralConfig";
    private static final String REQUEST_PARAM_HTML2PDF_PRIMARY_ROUTE = "pdfg_html2pdf_primary_route";
    private static final String REQUEST_PARAM_HTML2PDF_SECONDARY_ROUTE = "pdfg_html2pdf_secondary_route";
    private static final String REQUEST_PARAM_ACROBAT_IMAGE_CONVERSION = "pdfg_acrobat_image_conv";
    private static final String REQUEST_PARAM_ACROBAT_AUTOCAD = "pdfg_acrobat_autocad";
    private static final String REQUEST_PARAM_RETRY_LOGIC = "pdfg_retry_logic";
    private static final String REQUEST_PARAM_CONVERSION_TIMEOUT = "pdfg_conv_timeout";
    private static final String REQUEST_PARAM_GLOBAL_TIMEOUT = "pdfg_global_timeout";
    private static final String REQUEST_PARAM_CLEANUP_SCAN_SECONDS = "pdfg_cleanup_scan";
    private static final String REQUEST_PARAM_JOB_EXPIRATION_SECONDS = "pdfg_job_expiration";
    private static final String REQUEST_PARAM_DEFAULT_LOCALE = "pdfg_def_locale";
    private static PDFGConfigUtility ch = null;
    private static final long serialVersionUID = 1;
    private final Logger log = LoggerFactory.getLogger(PDFGAdminServlet.class);
    @Reference
    private CryptoSupport cryptoSupport;
    @Reference
    private SlingRepository slingRepository;
    @Reference
    private PDFGConfigService configService;
    @Reference
    private GeneratePDFService generatePDFService;

    protected void activate(ComponentContext componentContext) throws ConfigException {
        ch = PDFGConfigUtility.getInstance((SlingRepository)this.slingRepository, (CryptoSupport)this.cryptoSupport);
        this.log.info("Activated: PDFGAdminServlet started");
    }

    protected void deactivate(ComponentContext context) {
        this.log.info("Deactivated: PDFGAdminServlet stopped");
    }

    public void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp) {
        this.requestHandler(req, resp);
    }

    public void doPost(SlingHttpServletRequest req, SlingHttpServletResponse resp) {
        this.requestHandler(req, resp);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void requestHandler(SlingHttpServletRequest req, SlingHttpServletResponse resp) {
        try {
            PDFGConfigUtility.currentUserSession.set(req.getResourceResolver().adaptTo(Session.class));
            if (req.getParameter("__modifyGeneralConfig") != null) {
                this.modifyGeneralConfig(req, resp);
            } else if (req.getParameter("__importSettings") != null) {
                this.importSettings(req, resp);
            } else if (req.getParameter("__exportSettings") != null) {
                this.exportSettings(req, resp);
            } else if (req.getParameter("__modifyUser") != null) {
                this.modifyUser(req, resp);
            } else if (req.getParameter("__deleteUser") != null) {
                this.deleteUser(req, resp);
            } else if (req.getParameter("__modifySetting") != null) {
                this.modifySecuritySetting(req, resp);
            } else if (req.getParameter("__deleteSetting") != null) {
                this.deleteSecuritySetting(req, resp);
            } else if (req.getParameter("__fetchSecuritySettings") != null) {
                this.getSettings(req, resp);
            }
        }
        catch (Exception e) {
            resp.setStatus(500);
            PrintStream ps = null;
            try {
                ps = new PrintStream((OutputStream)resp.getOutputStream(), true);
                ps.println(e.getMessage());
            }
            catch (IOException ioe) {
                this.log.trace(ioe.getMessage(), (Throwable)ioe);
            }
            finally {
                if (ps != null) {
                    ps.close();
                }
            }
            this.log.debug(e.getMessage(), (Throwable)e);
        }
        finally {
            if (PDFGConfigUtility.currentUserSession.get() != null) {
                PDFGConfigUtility.currentUserSession.remove();
            }
        }
    }

    private void modifyGeneralConfig(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws ConfigException, IOException {
        HashMap<String, String[]> generalConfigMap = new HashMap<String, String[]>();
        generalConfigMap.put("pdfg_html2pdf_primary_route", req.getParameterValues("pdfg_html2pdf_primary_route"));
        generalConfigMap.put("pdfg_html2pdf_secondary_route", req.getParameterValues("pdfg_html2pdf_secondary_route"));
        generalConfigMap.put("pdfg_acrobat_image_conv", req.getParameterValues("pdfg_acrobat_image_conv"));
        generalConfigMap.put("pdfg_acrobat_autocad", req.getParameterValues("pdfg_acrobat_autocad"));
        generalConfigMap.put("pdfg_retry_logic", req.getParameterValues("pdfg_retry_logic"));
        generalConfigMap.put("pdfg_conv_timeout", req.getParameterValues("pdfg_conv_timeout"));
        generalConfigMap.put("pdfg_global_timeout", req.getParameterValues("pdfg_global_timeout"));
        generalConfigMap.put("pdfg_cleanup_scan", req.getParameterValues("pdfg_cleanup_scan"));
        generalConfigMap.put("pdfg_job_expiration", req.getParameterValues("pdfg_job_expiration"));
        generalConfigMap.put("pdfg_def_locale", req.getParameterValues("pdfg_def_locale"));
        this.configService.updateGeneralConfig(generalConfigMap);
        this.generatePDFService.updateGeneralConfig(this.configService.getGeneralConfigMap());
    }

    private void importSettings(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws PathNotFoundException, RepositoryException, ParserConfigurationException, SAXException, IOException, TransformerException, ConfigException {
        String importAction = req.getParameter("__importSettings");
        if (importAction.equalsIgnoreCase("existing")) {
            RequestParameter settingsFile = req.getRequestParameter("file2pdf-settings");
            if (settingsFile != null) {
                ch.setConfigurationXML(settingsFile.getInputStream());
            }
        } else if (importAction.equalsIgnoreCase("reset")) {
            this.configService.resetConfigurationToDefault();
        }
    }

    private void exportSettings(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws ConfigException, IOException {
        String filetypeSettingsName = req.getParameter("filetype-settings");
        String jobOptionsName = req.getParameter("job-options");
        String securitySettingsName = req.getParameter("security-settings");
        String configXML = "";
        String exportAction = req.getParameter("__exportSettings");
        if (exportAction.equalsIgnoreCase("minimal")) {
            if (filetypeSettingsName == null || filetypeSettingsName.length() == 0) {
                this.log.info("PDFGAdminServlet.exportSettings(): No filetype setting specified, exporting default");
                filetypeSettingsName = "default#";
            }
            if (jobOptionsName == null || jobOptionsName.length() == 0) {
                this.log.info("PDFGAdminServlet.exportSettings(): No job option specified, exporting default");
                jobOptionsName = "default#";
            }
            if (securitySettingsName == null || securitySettingsName.length() == 0) {
                this.log.info("PDFGAdminServlet.exportSettings(): No security setting specified, exporting default");
                securitySettingsName = "default#";
            }
            configXML = ch.getNamedConfigurationXML(securitySettingsName, jobOptionsName, filetypeSettingsName);
        } else if (exportAction.equalsIgnoreCase("entire")) {
            configXML = ch.getEntireConfigurationXML();
        }
        resp.setContentType("text/xml;charset=UTF-8");
        resp.setHeader("Content-Disposition", "attachment;filename=exported_settings.xml");
        resp.getOutputStream().write(configXML.getBytes());
    }

    private void modifyUser(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws ConfigException, IOException {
        String username = req.getParameter("__modifyUser");
        String password = req.getParameter("__modifyUserPwd");
        if (username == null || username.length() <= 0) {
            throw new ConfigException("User name cannot be empty");
        }
        this.log.info("Received request to modify/add user: " + username);
        HashMap<String, String> userInfo = new HashMap<String, String>(2);
        userInfo.put("username", username);
        userInfo.put("password", password);
        this.configService.updateUserAccountsSettings(userInfo, true);
        Map userAccountsMap = this.configService.getUserAccountsMap();
        String jsonArr = this.buildJsonArr(userAccountsMap.keySet());
        resp.setContentType("application/json");
        resp.getOutputStream().print(jsonArr);
    }

    private void deleteUser(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws ConfigException, IOException {
        String user = req.getParameter("__deleteUser");
        if (user == null || user.length() <= 0) {
            throw new ConfigException("User name cannot be empty");
        }
        this.log.info("Received request to delete user: " + user);
        ArrayList<String> users = new ArrayList<String>();
        users.add(user);
        this.configService.removeUserAccounts(users);
        this.log.info("User: " + user + " deleted successfully");
        Map userAccountsMap = this.configService.getUserAccountsMap();
        String jsonArr = this.buildJsonArr(userAccountsMap.keySet());
        resp.setContentType("application/json");
        resp.getOutputStream().print(jsonArr);
    }

    private void modifySecuritySetting(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws ConfigException, IOException {
        String settingName = req.getParameter("__modifySetting");
        if (settingName != null && settingName.length() > 0) {
            String openPassword = req.getParameter("__modifyOpenPasswd");
            String permPassword = req.getParameter("__modifyPermPasswd");
            if (openPassword != null || permPassword != null) {
                this.configService.updateSecuritySetting(settingName, openPassword, permPassword);
            }
        } else {
            throw new ConfigException("Setting name cannot be empty");
        }
    }

    private void deleteSecuritySetting(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws ConfigException, IOException {
        String settingName = req.getParameter("__deleteSetting");
        if (settingName == null || settingName.length() <= 0) {
            throw new ConfigException("Setting name cannot be empty");
        }
        this.log.info("Received request to delete security setting: " + settingName);
        ArrayList<String> securitySettings = new ArrayList<String>();
        securitySettings.add(settingName);
        this.configService.removeSecuritySettings(securitySettings);
    }

    private void getSettings(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws ConfigException, IOException {
        Map securitySettingsMap = this.configService.getSecuritySettingsMap();
        StringBuilder jsonRepBuilder = new StringBuilder();
        jsonRepBuilder.append("[");
        Iterator iter = securitySettingsMap.keySet().iterator();
        if (iter.hasNext()) {
            jsonRepBuilder.append("\"").append((String)iter.next()).append("\"");
        }
        while (iter.hasNext()) {
            String settingName = (String)iter.next();
            jsonRepBuilder.append(",").append("\"").append(settingName).append("\"");
        }
        jsonRepBuilder.append("]");
        String jsonArr = jsonRepBuilder.toString();
        resp.setContentType("application/json");
        resp.getOutputStream().print(jsonArr);
    }

    private String buildJsonArr(Set<String> itemSet) {
        int indx;
        String str;
        String itemName;
        StringBuilder jsonArrBuilder = new StringBuilder();
        jsonArrBuilder.append("[");
        Iterator<String> iter = itemSet.iterator();
        if (iter.hasNext()) {
            itemName = iter.next();
            indx = itemName.indexOf("\\");
            if (indx != -1) {
                itemName = str = "".concat(itemName.substring(0, indx)).concat("\\\\").concat(itemName.substring(indx + 1));
            }
            jsonArrBuilder.append("\"").append(itemName).append("\"");
        }
        while (iter.hasNext()) {
            itemName = iter.next();
            indx = itemName.indexOf("\\");
            if (indx != -1) {
                itemName = str = "".concat(itemName.substring(0, indx)).concat("\\\\").concat(itemName.substring(indx + 1));
            }
            jsonArrBuilder.append(",").append("\"").append(itemName).append("\"");
        }
        jsonArrBuilder.append("]");
        String jsonArr = jsonArrBuilder.toString();
        return jsonArr;
    }

    protected void bindCryptoSupport(CryptoSupport cryptoSupport) {
        this.cryptoSupport = cryptoSupport;
    }

    protected void unbindCryptoSupport(CryptoSupport cryptoSupport) {
        if (this.cryptoSupport == cryptoSupport) {
            this.cryptoSupport = null;
        }
    }

    protected void bindSlingRepository(SlingRepository slingRepository) {
        this.slingRepository = slingRepository;
    }

    protected void unbindSlingRepository(SlingRepository slingRepository) {
        if (this.slingRepository == slingRepository) {
            this.slingRepository = null;
        }
    }

    protected void bindConfigService(PDFGConfigService pDFGConfigService) {
        this.configService = pDFGConfigService;
    }

    protected void unbindConfigService(PDFGConfigService pDFGConfigService) {
        if (this.configService == pDFGConfigService) {
            this.configService = null;
        }
    }

    protected void bindGeneratePDFService(GeneratePDFService generatePDFService) {
        this.generatePDFService = generatePDFService;
    }

    protected void unbindGeneratePDFService(GeneratePDFService generatePDFService) {
        if (this.generatePDFService == generatePDFService) {
            this.generatePDFService = null;
        }
    }
}