at.gv.egovernment.moa.id.advancedlogging.StatisticLogger.java Source code

Java tutorial

Introduction

Here is the source code for at.gv.egovernment.moa.id.advancedlogging.StatisticLogger.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.advancedlogging;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.lang3.StringEscapeUtils;

import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate;
import at.gv.e_government.reference.namespace.mandates._20040701_.Mandator;
import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType;
import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
import at.gv.egovernment.moa.id.auth.exception.BKUException;
import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException;
import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
import at.gv.egovernment.moa.id.auth.exception.ServiceException;
import at.gv.egovernment.moa.id.client.SZRGWClientException;
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.StatisticLogDBUtils;
import at.gv.egovernment.moa.id.commons.db.dao.config.AuthComponentOA;
import at.gv.egovernment.moa.id.commons.db.dao.config.BKUURLS;
import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication;
import at.gv.egovernment.moa.id.commons.db.dao.statistic.StatisticLog;
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.auth.AuthConfigurationProvider;
import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters;
import at.gv.egovernment.moa.id.data.IAuthData;
import at.gv.egovernment.moa.id.moduls.IRequest;
import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate;
import at.gv.egovernment.moa.logging.Logger;
import at.gv.egovernment.moa.util.MiscUtil;

public class StatisticLogger {

    private static final String GENERIC_LOCALBKU = ":3496/https-security-layer-request";
    private static final String GENERIC_HANDYBKU = "https://www.handy-signatur.at/";

    private static final String MANTATORTYPE_JUR = "jur";
    private static final String MANTATORTYPE_NAT = "nat";

    private static final int MAXERRORLENGTH = 250;

    private static final String ERRORTYPE_UNKNOWN = "unkown";
    private static final String ERRORTYPE_BKU = "bku";
    private static final String ERRORTYPE_MOASP = "moa-sp";
    private static final String ERRORTYPE_MANDATE = "mandate";
    private static final String ERRORTYPE_MOAID = "moa-id";
    private static final String ERRORTYPE_SZRGW = "szrgw";

    private static StatisticLogger instance;

    private boolean isAktive = false;

    public static StatisticLogger getInstance() {
        if (instance == null)
            instance = new StatisticLogger();

        return instance;
    }

    private StatisticLogger() {
        try {
            AuthConfigurationProvider config = AuthConfigurationProvider.getInstance();

            if (config != null)
                isAktive = config.isAdvancedLoggingActive();

        } catch (ConfigurationException e) {
            Logger.error("StatisticLogger can not be inizialized", e);
        }
    }

    public void logSuccessOperation(IRequest protocolRequest, IAuthData authData, boolean isSSOSession) {

        if (isAktive && protocolRequest != null && authData != null) {

            OnlineApplication dbOA = ConfigurationDBRead.getOnlineApplication(protocolRequest.getOAURL());

            if (dbOA == null) {
                Logger.warn("Advanced logging failed: OA can not be found in database.");
                return;
            }

            StatisticLog dblog = new StatisticLog();

            //set actual date and time
            dblog.setTimestamp(new Date());

            //set OA databaseID
            dblog.setOaID(dbOA.getHjid());

            //log basic AuthInformation
            dblog.setOaurlprefix(protocolRequest.getOAURL());
            dblog.setOafriendlyName(dbOA.getFriendlyName());

            boolean isbusinessservice = isBusinessService(dbOA);
            dblog.setBusinessservice(isbusinessservice);
            dblog.setOatarget(authData.getBPKType());

            dblog.setInterfederatedSSOSession(authData.isInterfederatedSSOSession());

            if (authData.isInterfederatedSSOSession()) {
                dblog.setBkutype(IOAAuthParameters.INDERFEDERATEDIDP);
                dblog.setBkuurl(authData.getInterfederatedIDP());

            } else {
                dblog.setBkuurl(authData.getBkuURL());
                dblog.setBkutype(findBKUType(authData.getBkuURL(), dbOA));

            }

            dblog.setProtocoltype(protocolRequest.requestedModule());
            dblog.setProtocolsubtype(protocolRequest.requestedAction());
            dblog.setSsosession(isSSOSession);

            //log MandateInforamtion
            if (authData.isUseMandate()) {
                dblog.setMandatelogin(authData.isUseMandate());

                MISMandate mandate = authData.getMISMandate();
                if (mandate != null) {

                    if (MiscUtil.isNotEmpty(mandate.getProfRep())) {
                        dblog.setMandatetype(mandate.getProfRep());
                        dblog.setPv(true);
                        dblog.setPvOID(mandate.getProfRep());

                    } else {
                        dblog.setPv(false);
                    }

                    InputStream is = null;
                    try {
                        is = new ByteArrayInputStream(mandate.getMandate());

                        JAXBContext jc = JAXBContext.newInstance(Mandate.class);
                        Unmarshaller u = jc.createUnmarshaller();
                        Object mismandateobj = u.unmarshal(is);

                        if (mismandateobj != null && mismandateobj instanceof Mandate) {
                            Mandate mismandate = (Mandate) mismandateobj;

                            if (MiscUtil.isEmpty(mandate.getProfRep()))
                                dblog.setMandatetype(mismandate.getAnnotation());

                            Mandator mandator = mismandate.getMandator();
                            CorporateBodyType corp = mandator.getCorporateBody();
                            if (corp != null) {
                                dblog.setMandatortype(MANTATORTYPE_JUR);

                            } else {
                                dblog.setMandatortype(MANTATORTYPE_NAT);
                            }

                        } else {
                            Logger.warn("Advancted logging can not unmarshall MISMandate");
                        }

                    } catch (JAXBException e) {
                        Logger.warn("Advancted logging can not parse mandate.", e);

                    } finally {
                        if (is != null) {
                            try {
                                is.close();

                            } catch (IOException e) {
                                Logger.warn("Close InputStream failed.", e);

                            }
                        }
                    }
                }
            }

            ConfigurationDBUtils.closeSession();

            try {
                StatisticLogDBUtils.saveOrUpdate(dblog);

            } catch (MOADatabaseException e) {
                Logger.warn("Statistic Log can not be stored into Database", e);
            }
        }
    }

    public void logErrorOperation(Throwable throwable) {
        if (isAktive) {
            StatisticLog dblog = new StatisticLog();

            //set actual date and time
            dblog.setTimestamp(new Date());

            if (throwable != null)
                generateErrorLogFormThrowable(throwable, dblog);

            else {
                dblog.setErrormessage("UNKOWN ERROR DETECTED!");
                dblog.setErrortype(ERRORTYPE_UNKNOWN);
            }

            try {
                StatisticLogDBUtils.saveOrUpdate(dblog);

            } catch (MOADatabaseException e) {
                Logger.warn("Statistic Log can not be stored into Database", e);
            }
        }

    }

    public void logErrorOperation(Throwable throwable, IRequest errorRequest) {

        if (isAktive && throwable != null && errorRequest != null) {
            StatisticLog dblog = new StatisticLog();

            //set actual date and time
            dblog.setTimestamp(new Date());

            dblog.setOaurlprefix(errorRequest.getOAURL());
            dblog.setProtocoltype(errorRequest.requestedModule());
            dblog.setProtocolsubtype(errorRequest.requestedAction());

            OnlineApplication dbOA = ConfigurationDBRead.getOnlineApplication(errorRequest.getOAURL());
            if (dbOA != null) {
                dblog.setOafriendlyName(dbOA.getFriendlyName());
                dblog.setOatarget(dbOA.getTarget());
                dblog.setOaID(dbOA.getHjid());
                dblog.setBusinessservice(isBusinessService(dbOA));
            }

            AuthenticationSession moasession = AuthenticationSessionStoreage
                    .getSessionWithPendingRequestID(errorRequest.getRequestID());
            if (moasession != null) {
                if (MiscUtil.isNotEmpty(moasession.getBkuURL())) {
                    dblog.setBkuurl(moasession.getBkuURL());
                    dblog.setBkutype(findBKUType(moasession.getBkuURL(), dbOA));
                }

                dblog.setMandatelogin(moasession.getUseMandate());
            }

            generateErrorLogFormThrowable(throwable, dblog);

            ConfigurationDBUtils.closeSession();

            try {
                StatisticLogDBUtils.saveOrUpdate(dblog);

            } catch (MOADatabaseException e) {
                Logger.warn("Statistic Log can not be stored into Database", e);
            }
        }
    }

    private boolean isBusinessService(OnlineApplication oa) {

        if (oa.getType().equals("businessService"))
            return true;
        else
            return false;
    }

    private String getErrorMessageWithMaxLength(String error, int maxlength) {
        if (error != null) {
            if (error.length() > maxlength)
                return StringEscapeUtils.escapeHtml4(error.substring(0, maxlength));

            else
                return StringEscapeUtils.escapeHtml4(error);

        } else
            return new String();

    }

    private void generateErrorLogFormThrowable(Throwable throwable, StatisticLog dblog) {
        if (throwable instanceof BKUException) {
            BKUException error = (BKUException) throwable;
            dblog.setErrortype(ERRORTYPE_BKU);
            dblog.setErrorcode(error.getBkuErrorCode());
            dblog.setErrormessage(getErrorMessageWithMaxLength(error.getBkuErrorMessage(), MAXERRORLENGTH));

        } else if (throwable instanceof SZRGWClientException) {
            SZRGWClientException error = (SZRGWClientException) throwable;
            dblog.setErrortype(ERRORTYPE_SZRGW);
            dblog.setErrorcode(error.getSzrErrorCode());
            dblog.setErrormessage(getErrorMessageWithMaxLength(error.getSzrErrorMessage(), MAXERRORLENGTH));

        } else if (throwable instanceof MISSimpleClientException) {
            MISSimpleClientException error = (MISSimpleClientException) throwable;
            dblog.setErrortype(ERRORTYPE_MANDATE);
            dblog.setErrorcode(error.getMISErrorCode());
            if (MiscUtil.isEmpty(error.getMISErrorMessage()))
                dblog.setErrormessage(getErrorMessageWithMaxLength(error.getMessage(), MAXERRORLENGTH));
            else
                dblog.setErrormessage(getErrorMessageWithMaxLength(error.getMISErrorMessage(), MAXERRORLENGTH));

        } else if (throwable instanceof ServiceException) {
            ServiceException error = (ServiceException) throwable;
            dblog.setErrortype(ERRORTYPE_MOASP);
            dblog.setErrorcode(error.getMessageId());
            dblog.setErrormessage(getErrorMessageWithMaxLength(error.getMessage(), MAXERRORLENGTH));

        } else if (throwable instanceof MOAIDException) {
            MOAIDException error = (MOAIDException) throwable;
            dblog.setErrortype(ERRORTYPE_MOAID);
            dblog.setErrorcode(error.getMessageId());
            dblog.setErrormessage(getErrorMessageWithMaxLength(error.getMessage(), MAXERRORLENGTH));

        } else {
            dblog.setErrortype(ERRORTYPE_UNKNOWN);
            dblog.setErrormessage(getErrorMessageWithMaxLength(throwable.getMessage(), MAXERRORLENGTH));
        }

    }

    private String findBKUType(String bkuURL, OnlineApplication dbOA) {

        if (dbOA != null) {
            AuthComponentOA oaAuth = dbOA.getAuthComponentOA();
            if (oaAuth != null) {
                BKUURLS bkuurls = oaAuth.getBKUURLS();
                if (bkuurls != null) {
                    if (bkuURL.equals(bkuurls.getHandyBKU()))
                        return IOAAuthParameters.HANDYBKU;

                    if (bkuURL.equals(bkuurls.getLocalBKU()))
                        return IOAAuthParameters.LOCALBKU;

                    if (bkuURL.equals(bkuurls.getOnlineBKU()))
                        return IOAAuthParameters.ONLINEBKU;
                }
            }
        }

        Logger.trace("Staticic Log search BKUType from DefaultBKUs");

        try {
            AuthConfigurationProvider authconfig = AuthConfigurationProvider.getInstance();
            if (bkuURL.equals(authconfig.getDefaultBKUURL(IOAAuthParameters.ONLINEBKU)))
                return IOAAuthParameters.ONLINEBKU;

            if (bkuURL.equals(authconfig.getDefaultBKUURL(IOAAuthParameters.LOCALBKU)))
                return IOAAuthParameters.LOCALBKU;

            if (bkuURL.equals(authconfig.getDefaultBKUURL(IOAAuthParameters.HANDYBKU)))
                return IOAAuthParameters.HANDYBKU;

        } catch (ConfigurationException e) {
            Logger.info("Advanced Logging: Default BKUs read failed");
        }

        Logger.debug("Staticic Log search BKUType from generneric Parameters");

        if (bkuURL.endsWith(GENERIC_LOCALBKU)) {
            Logger.debug("BKUURL " + bkuURL + " is mapped to " + IOAAuthParameters.LOCALBKU);
            return IOAAuthParameters.LOCALBKU;
        }

        if (bkuURL.startsWith(GENERIC_HANDYBKU)) {
            Logger.debug("BKUURL " + bkuURL + " is mapped to " + IOAAuthParameters.HANDYBKU);
            return IOAAuthParameters.HANDYBKU;
        }

        Logger.debug("BKUURL " + bkuURL + " is mapped to " + IOAAuthParameters.ONLINEBKU);
        return IOAAuthParameters.ONLINEBKU;
    }

}