mitm.djigzo.web.pages.ca.CARequestsPreview.java Source code

Java tutorial

Introduction

Here is the source code for mitm.djigzo.web.pages.ca.CARequestsPreview.java

Source

/*
 * Copyright (c) 2010-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Common Development and 
 * Distribution License (CDDL), Common Public License (CPL) the 
 * licensors of this Program grant you additional permission to 
 * convey the resulting work.
 */
package mitm.djigzo.web.pages.ca;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import mitm.application.djigzo.admin.FactoryRoles;
import mitm.application.djigzo.ws.CAWS;
import mitm.application.djigzo.ws.CertificateRequestHandlerDTO;
import mitm.application.djigzo.ws.RequestParametersDTOUtils;
import mitm.common.security.ca.Match;
import mitm.common.security.ca.RequestParameters;
import mitm.common.security.ca.RequestUtils;
import mitm.common.security.certificate.X500PrincipalInspector;
import mitm.common.util.CollectionUtils;
import mitm.common.ws.WebServiceCheckedException;
import mitm.djigzo.web.pages.Certificates;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.tapestry5.Asset;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.IncludeStylesheet;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.Grid;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Value;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.BeanModelSource;
import org.apache.tapestry5.services.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.annotation.Secured;

@Secured({ FactoryRoles.ROLE_ADMIN, FactoryRoles.ROLE_PKI_MANAGER })
@IncludeStylesheet("context:styles/pages/ca/caRequestsPreview.css")
public class CARequestsPreview {
    private final static Logger logger = LoggerFactory.getLogger(CARequestsPreview.class);

    @Inject
    private Request request;

    @Inject
    private CAWS caWS;

    @Inject
    @Value("${certificateRequestsPreview.rowsPerPage}")
    private int rowsPerPage;

    /*
     * Maximum number of requests that are uploaded in one call.
     */
    @Inject
    @Value("${certificateRequestsPreview.maxBatchSize}")
    private int maxBatchSize;

    /*
     * The certificate requests to be previewed
     */
    @Persist
    private List<RequestParameters> certificateRequests;

    /*
     * The certificate request handler that was selected on the bulk request page
     */
    @Persist
    private CertificateRequestHandlerDTO certificateRequestHandler;

    /*
     * If true a user object will be added when a certificate is ussued
     */
    @Persist
    private boolean addUser;

    /*
     * The certificate request currently being drawn by the grid (is set by the grid component)
     */
    private RequestParameters certificateRequest;

    /*
     * Set of the selected email addresses
     */
    @Persist
    private Set<String> selected;

    /*
     * The email address to filter on.
     */
    @Persist
    private String email;

    @Component
    private Form form;

    @SuppressWarnings("unused")
    @Component(parameters = { "source = filteredRequests", "model = model", "row = certificateRequest",
            "volatile = true",
            "reorder = select,delete, email, subject, validity, keyLength, "
                    + "certificateRequestHandler, signatureAlgorithm, crlDistributionPoint",
            "rowsPerPage = prop:rowsPerPage" })
    private Grid grid;

    @Inject
    private BeanModelSource beanModelSource;

    @Inject
    private ComponentResources resources;

    @Inject
    @Path("context:icons/cross.png")
    private Asset deleteAsset;

    /*
     * True if and error has occurred
     */
    @Persist(PersistenceConstants.FLASH)
    private boolean error;

    /*
     * Error message if an error has occurred
     */
    @Persist(PersistenceConstants.FLASH)
    private String errorMessage;

    /*
     * True if the request button was clicked
     */
    private boolean requestClicked;

    @SetupRender
    @Secured({ FactoryRoles.ROLE_ADMIN, FactoryRoles.ROLE_PKI_MANAGER })
    protected void setupRender() {
        if (certificateRequests == null) {
            certificateRequests = new ArrayList<RequestParameters>();
        }

        if (selected == null) {
            selected = Collections.synchronizedSet(new HashSet<String>());
        } else {
            selected.clear();
        }
    }

    @Secured({ FactoryRoles.ROLE_ADMIN, FactoryRoles.ROLE_PKI_MANAGER })
    public void onActivate(String email) {
        this.email = email;
    }

    public boolean isFilterDisabled() {
        return StringUtils.isBlank(email);
    }

    /*
     * Returns the subject of the currently handled request
     */
    public String getSubject() {
        return request != null ? X500PrincipalInspector.getFriendly(certificateRequest.getSubject()) : "";
    }

    public Collection<RequestParameters> getFilteredRequests() {
        return StringUtils.isEmpty(email) ? certificateRequests
                : RequestUtils.findByEmail(certificateRequests, email, Match.LIKE);
    }

    public void setCertificateRequest(RequestParameters certificateRequest) {
        this.certificateRequest = certificateRequest;
    }

    public RequestParameters getCertificateRequest() {
        return certificateRequest;
    }

    public boolean getSelect() {
        return selected.contains(certificateRequest.getEmail());
    }

    public void setSelect(boolean value) {
        /*
         * Ignored. Checkbox values will be handled using EventCheckbox (see onCheckboxClick)
         */
    }

    public Asset getDeleteAsset() {
        return deleteAsset;
    }

    public BeanModel<RequestParameters> getModel() {
        BeanModel<RequestParameters> model = beanModelSource.createDisplayModel(RequestParameters.class,
                resources.getMessages());

        model.add("delete", null);
        model.add("select", null);
        model.add("subject", null);

        /*
         * Disable all sorting
         */
        for (String column : model.getPropertyNames()) {
            model.get(column).sortable(false);
        }

        return model;
    }

    public void onSelectedFromRequestButton() {
        requestClicked = true;
    }

    @OnEvent(component = "deleteEntry")
    protected void deleteEntry(String email) {
        certificateRequests.removeAll(RequestUtils.findByEmail(certificateRequests, email, Match.EXACT));
    }

    /*
     * Event handler called when the checkbox is clicked. 
     */
    public void onCheckboxEvent() {
        String data = request.getParameter("data");

        if (StringUtils.isEmpty(data)) {
            throw new IllegalArgumentException("data is missing.");
        }

        JSONObject json = new JSONObject(data);

        String element = json.getString("element");
        boolean checked = json.getBoolean("checked");

        if (checked) {
            selected.add(element);
        } else {
            selected.remove(element);
        }
    }

    @OnEvent(component = "deleteSelected")
    protected void deleteSelected() {
        /*
         * Note: we need to clone the set to make sure that concurrent modifications
         * are possible.
         */
        String[] emails = selected.toArray(new String[] {});

        for (String email : emails) {
            deleteEntry(email);
        }
    }

    protected void onValidateForm() {
        if (requestClicked && CollectionUtils.isEmpty(certificateRequests)) {
            form.recordError("There are no valid requests.");
        }
    }

    private void sendRequests(Collection<RequestParameters> requests)
            throws WebServiceCheckedException, IOException {
        caWS.requestCertificates(RequestParametersDTOUtils.toRequestParametersDTOs(requests), addUser,
                true /* skip if available */);
    }

    /*
     * Send the requests not all at once because that can result in a SOAP timeout when the number of requests
     * is very large
     */
    private void sendRequestsInBatches() throws WebServiceCheckedException, IOException {
        Collection<RequestParameters> batch = new ArrayList<RequestParameters>(maxBatchSize);

        for (RequestParameters request : certificateRequests) {
            batch.add(request);

            if (batch.size() >= maxBatchSize) {
                sendRequests(batch);

                batch.clear();
            }
        }

        /*
         * Check if there are still some requests left to send (happens when the number
         * of requests is not a multiple of maxBatchSize)
         */
        if (batch.size() > 0) {
            sendRequests(batch);
        }
    }

    protected Object onSuccess() {
        try {
            /* check if the request button was clicked */
            if (!requestClicked) {
                return null;
            }

            sendRequestsInBatches();

            certificateRequests = null;

            /*
             * If the certificates are instantly issued, the certificates pages will be openend. If 
             * they are not instantly issued the page with pending requests will be openened.
             */
            return certificateRequestHandler == null || certificateRequestHandler.isInstantlyIssued()
                    ? Certificates.class
                    : CARequests.class;
        } catch (Exception e) {
            logger.error("Error requesting certificates.", e);

            error = true;
            errorMessage = ExceptionUtils.getRootCauseMessage(e);

            return null;
        }
    }

    /*
     * Event handler called when the cancel button is pressed.
     */
    protected Object onCancel() {
        certificateRequests = null;

        return CABulkRequest.class;
    }

    public int getRowsPerPage() {
        return rowsPerPage;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }

    public boolean isError() {
        return error;
    }

    public String getErrorMessage() {
        return StringUtils.isNotBlank(errorMessage) ? errorMessage : "No details.";
    }

    public List<RequestParameters> getCertificateRequests() {
        return certificateRequests;
    }

    public void setCertificateRequests(List<RequestParameters> certificateRequests) {
        this.certificateRequests = certificateRequests;

        /* reset the email filter as we are getting new requests */
        email = null;
    }

    public CertificateRequestHandlerDTO getCertificateRequestHandler() {
        return certificateRequestHandler;
    }

    public void setCertificateRequestHandler(CertificateRequestHandlerDTO certificateRequestHandler) {
        this.certificateRequestHandler = certificateRequestHandler;
    }

    public boolean getAddUser() {
        return addUser;
    }

    public void setAddUser(boolean addUser) {
        this.addUser = addUser;
    }
}