at.gv.egovernment.moa.id.configuration.struts.action.ImportExportAction.java Source code

Java tutorial

Introduction

Here is the source code for at.gv.egovernment.moa.id.configuration.struts.action.ImportExportAction.java

Source

/*******************************************************************************
 * Copyright 2014 Federal Chancellery Austria
 * MOA-ID has been developed in a cooperation between BRZ, the Federal
 * Chancellery Austria - ICT staff unit, and Graz University of Technology.
 *
 * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
 * the European Commission - subsequent versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 * http://www.osor.eu/eupl/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 *
 * This product combines work with different licenses. See the "NOTICE" text
 * file for details on the various modules and licenses.
 * The "NOTICE" text file is part of the distribution. Any derivative works
 * that you distribute must include a readable copy of the "NOTICE" text file.
 *******************************************************************************/
package at.gv.egovernment.moa.id.configuration.struts.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead;
import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils;
import at.gv.egovernment.moa.id.commons.db.dao.config.MOAIDConfiguration;
import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication;
import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
import at.gv.egovernment.moa.id.config.ConfigurationException;
import at.gv.egovernment.moa.id.config.legacy.BuildFromLegacyConfig;
import at.gv.egovernment.moa.id.configuration.Constants;
import at.gv.egovernment.moa.id.configuration.auth.AuthenticatedUser;
import at.gv.egovernment.moa.id.configuration.config.ConfigurationProvider;
import at.gv.egovernment.moa.id.configuration.exception.BasicActionException;
import at.gv.egovernment.moa.id.configuration.helper.LanguageHelper;
import at.gv.egovernment.moa.id.util.Random;

import com.opensymphony.xwork2.ActionSupport;

public class ImportExportAction extends BasicAction {

    private static final Logger log = Logger.getLogger(ImportExportAction.class);
    private static final long serialVersionUID = 1L;

    private String formID;
    private File fileUpload = null;
    private String fileUploadContentType = null;
    private String fileUploadFileName = null;

    private InputStream fileInputStream;

    public String init() {
        try {
            populateBasicInformations();

        } catch (BasicActionException e) {
            return Constants.STRUTS_ERROR;

        }

        if (authUser.isAdmin()) {

            formID = Random.nextRandom();
            session.setAttribute(Constants.SESSION_FORMID, formID);

            return Constants.STRUTS_SUCCESS;

        } else {
            log.info("No access to Import/Export for User with ID" + authUser.getUserID());
            addActionError(LanguageHelper.getErrorString("errors.notallowed", request));
            return Constants.STRUTS_NOTALLOWED;
        }
    }

    public String importLegacyConfig() {
        try {
            populateBasicInformations();

        } catch (BasicActionException e) {
            return Constants.STRUTS_ERROR;

        }

        Object formidobj = session.getAttribute(Constants.SESSION_FORMID);
        if (formidobj != null && formidobj instanceof String) {
            String formid = (String) formidobj;
            if (!formid.equals(formID)) {
                log.warn("FormIDs does not match. Some suspect Form is received from user "
                        + authUser.getFamilyName() + authUser.getGivenName() + authUser.getUserID());
                return Constants.STRUTS_ERROR;
            }
        } else {
            log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName()
                    + authUser.getGivenName() + authUser.getUserID());
            return Constants.STRUTS_ERROR;
        }
        session.setAttribute(Constants.SESSION_FORMID, null);

        if (authUser.isAdmin()) {

            //load legacy config if it is configured

            if (fileUpload == null) {
                addActionError(LanguageHelper.getErrorString("errors.importexport.nofile", request));

                formID = Random.nextRandom();
                session.setAttribute(Constants.SESSION_FORMID, formID);
                return Constants.STRUTS_ERROR_VALIDATION;
            }

            try {

                MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration();

                MOAIDConfiguration moaconfig;
                try {
                    log.warn("WARNING! The legacy import deletes the hole old config");

                    String rootConfigFileDir = ConfigurationProvider.getInstance().getConfigRootDir();

                    moaconfig = BuildFromLegacyConfig.build(fileUpload, rootConfigFileDir, moaidconfig);

                } catch (ConfigurationException e) {
                    log.info("Legacy configuration has an Import Error", e);
                    addActionError(LanguageHelper.getErrorString("errors.importexport.legacyimport",
                            new Object[] { e.getMessage() }, request));
                    ConfigurationDBUtils.closeSession();

                    formID = Random.nextRandom();
                    session.setAttribute(Constants.SESSION_FORMID, formID);
                    return Constants.STRUTS_ERROR_VALIDATION;

                } catch (at.gv.egovernment.moa.id.configuration.exception.ConfigurationException e) {
                    ConfigurationDBUtils.closeSession();

                    formID = Random.nextRandom();
                    session.setAttribute(Constants.SESSION_FORMID, formID);
                    return Constants.STRUTS_ERROR_VALIDATION;
                }

                //check if XML config should be use
                log.warn(
                        "WARNING! MOA-ID 2.0 is started with XML configuration. This setup overstrike the actual configuration in the Database!");

                if (moaidconfig != null)
                    ConfigurationDBUtils.delete(moaidconfig);

                List<OnlineApplication> oas = ConfigurationDBRead.getAllOnlineApplications();
                if (oas != null && oas.size() > 0) {
                    for (OnlineApplication oa : oas)
                        ConfigurationDBUtils.delete(oa);
                }

                oas = moaconfig.getOnlineApplication();
                for (OnlineApplication oa : oas)
                    ConfigurationDBUtils.save(oa);

                moaconfig.setOnlineApplication(null);
                ConfigurationDBUtils.save(moaconfig);

            } catch (MOADatabaseException e) {
                log.warn("General MOA-ID config can not be stored in Database");
                addActionError(e.getMessage());

                formID = Random.nextRandom();
                session.setAttribute(Constants.SESSION_FORMID, formID);
                return Constants.STRUTS_ERROR_VALIDATION;
            }

            finally {
                ConfigurationDBUtils.closeSession();
            }

            //set new formID
            formID = Random.nextRandom();
            session.setAttribute(Constants.SESSION_FORMID, formID);

            log.info("Legacy Configuration load is completed.");
            addActionMessage(LanguageHelper.getGUIString("webpages.inportexport.success", request));
            return Constants.STRUTS_SUCCESS;

        } else {
            log.info("No access to Import/Export for User with ID" + authUser.getUserID());
            addActionError(LanguageHelper.getErrorString("errors.notallowed", request));
            return Constants.STRUTS_NOTALLOWED;
        }
    }

    public String downloadXMLConfig() {
        try {
            populateBasicInformations();

        } catch (BasicActionException e) {
            return Constants.STRUTS_ERROR;

        }

        Object formidobj = session.getAttribute(Constants.SESSION_FORMID);
        if (formidobj != null && formidobj instanceof String) {
            String formid = (String) formidobj;
            if (!formid.equals(formID)) {
                log.warn("FormIDs does not match. Some suspect Form is received from user "
                        + authUser.getFamilyName() + authUser.getGivenName() + authUser.getUserID());
                return Constants.STRUTS_ERROR;
            }
        } else {
            log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName()
                    + authUser.getGivenName() + authUser.getUserID());
            return Constants.STRUTS_ERROR;
        }
        session.setAttribute(Constants.SESSION_FORMID, null);

        if (authUser.isAdmin()) {

            log.info("Write MOA-ID 2.x xml config");
            JAXBContext jc;
            try {
                jc = JAXBContext.newInstance("at.gv.egovernment.moa.id.commons.db.dao.config");

                Marshaller m = jc.createMarshaller();
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                //               File test = new File(xmlconfigout);
                //               m.marshal(moaidconfig, test);
                MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration();

                if (moaidconfig == null) {
                    log.info("No MOA-ID 2.x configruation available");
                    addActionError(LanguageHelper.getErrorString("errors.importexport.export.noconfig", request));

                    formID = Random.nextRandom();
                    session.setAttribute(Constants.SESSION_FORMID, formID);
                    return Constants.STRUTS_ERROR_VALIDATION;
                }

                List<OnlineApplication> oaconfigs = ConfigurationDBRead.getAllOnlineApplications();
                moaidconfig.setOnlineApplication(oaconfigs);

                StringWriter writer = new StringWriter();
                m.marshal(moaidconfig, writer);
                fileInputStream = IOUtils.toInputStream(writer.toString(), "UTF-8");

            } catch (JAXBException e) {
                log.info("MOA-ID 2.x configruation could not be exported into a XML file.", e);
                addActionError(LanguageHelper.getErrorString("errors.importexport.export",
                        new Object[] { e.getMessage() }, request));

                formID = Random.nextRandom();
                session.setAttribute(Constants.SESSION_FORMID, formID);
                return Constants.STRUTS_ERROR_VALIDATION;
            } catch (IOException e) {
                log.info("MOA-ID 2.x configruation could not be exported into a XML file.", e);
                addActionError(LanguageHelper.getErrorString("errors.importexport.export",
                        new Object[] { e.getMessage() }, request));

                formID = Random.nextRandom();
                session.setAttribute(Constants.SESSION_FORMID, formID);
                return Constants.STRUTS_ERROR_VALIDATION;
            }

            finally {
                ConfigurationDBUtils.closeSession();
            }

            //set new formID
            formID = Random.nextRandom();
            session.setAttribute(Constants.SESSION_FORMID, formID);

            return Constants.STRUTS_SUCCESS;
        } else {
            log.info("No access to Import/Export for User with ID" + authUser.getUserID());
            addActionError(LanguageHelper.getErrorString("errors.notallowed", request));
            return Constants.STRUTS_NOTALLOWED;
        }
    }

    public String importXMLConfig() {
        try {
            populateBasicInformations();

        } catch (BasicActionException e) {
            return Constants.STRUTS_ERROR;

        }

        Object formidobj = session.getAttribute(Constants.SESSION_FORMID);
        if (formidobj != null && formidobj instanceof String) {
            String formid = (String) formidobj;
            if (!formid.equals(formID)) {
                log.warn("FormIDs does not match. Some suspect Form is received from user "
                        + authUser.getFamilyName() + authUser.getGivenName() + authUser.getUserID());
                return Constants.STRUTS_ERROR;
            }
        } else {
            log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName()
                    + authUser.getGivenName() + authUser.getUserID());
            return Constants.STRUTS_ERROR;
        }

        session.setAttribute(Constants.SESSION_FORMID, null);

        if (authUser.isAdmin()) {

            if (fileUpload == null) {
                addActionError(LanguageHelper.getErrorString("errors.importexport.nofile", request));

                formID = Random.nextRandom();
                session.setAttribute(Constants.SESSION_FORMID, formID);

                return Constants.STRUTS_ERROR_VALIDATION;
            }

            log.info("Load configuration from MOA-ID 2.x XML configuration");

            try {
                JAXBContext jc = JAXBContext.newInstance("at.gv.egovernment.moa.id.commons.db.dao.config");
                Unmarshaller m = jc.createUnmarshaller();
                MOAIDConfiguration moaconfig = (MOAIDConfiguration) m.unmarshal(fileUpload);

                log.warn("WARNING! The XML import deletes the hole old config");
                List<OnlineApplication> oas = ConfigurationDBRead.getAllOnlineApplications();
                if (oas != null && oas.size() > 0) {
                    for (OnlineApplication oa : oas)
                        ConfigurationDBUtils.delete(oa);
                }
                MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration();
                if (moaidconfig != null)
                    ConfigurationDBUtils.delete(moaidconfig);

                List<OnlineApplication> importoas = moaconfig.getOnlineApplication();
                for (OnlineApplication importoa : importoas) {
                    ConfigurationDBUtils.saveOrUpdate(importoa);
                }

                moaconfig.setOnlineApplication(null);
                ConfigurationDBUtils.saveOrUpdate(moaconfig);

            } catch (Exception e) {
                log.warn("MOA-ID XML configuration can not be loaded from File.", e);
                addActionError(LanguageHelper.getErrorString("errors.importexport.import",
                        new Object[] { e.getMessage() }, request));

                formID = Random.nextRandom();
                session.setAttribute(Constants.SESSION_FORMID, formID);
                return Constants.STRUTS_ERROR_VALIDATION;

            }

            finally {
                ConfigurationDBUtils.closeSession();
            }

            //set new formID
            formID = Random.nextRandom();
            session.setAttribute(Constants.SESSION_FORMID, formID);

            log.info("XML Configuration load is completed.");
            addActionMessage(LanguageHelper.getGUIString("webpages.inportexport.success", request));
            return Constants.STRUTS_SUCCESS;

        } else {
            log.info("No access to Import/Export for User with ID" + authUser.getUserID());
            addActionError(LanguageHelper.getErrorString("errors.notallowed", request));
            return Constants.STRUTS_NOTALLOWED;
        }

    }

    /**
     * @return the fileUpload
     */
    public File getFileUpload() {
        return fileUpload;
    }

    /**
     * @param fileUpload the fileUpload to set
     */
    public void setFileUpload(File fileUpload) {
        this.fileUpload = fileUpload;
    }

    /**
     * @return the fileUploadContentType
     */
    public String getFileUploadContentType() {
        return fileUploadContentType;
    }

    /**
     * @param fileUploadContentType the fileUploadContentType to set
     */
    public void setFileUploadContentType(String fileUploadContentType) {
        this.fileUploadContentType = fileUploadContentType;
    }

    /**
     * @return the fileUploadFileName
     */
    public String getFileUploadFileName() {
        return fileUploadFileName;
    }

    /**
     * @param fileUploadFileName the fileUploadFileName to set
     */
    public void setFileUploadFileName(String fileUploadFileName) {
        this.fileUploadFileName = fileUploadFileName;
    }

    public InputStream getFileInputStream() {
        return fileInputStream;
    }

    /**
     * @return the formID
     */
    public String getFormID() {
        return formID;
    }

    /**
     * @param formID the formID to set
     */
    public void setFormID(String formID) {
        this.formID = formID;
    }

}