at.gv.egovernment.moa.id.protocols.stork2.MandateRetrievalRequest.java Source code

Java tutorial

Introduction

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

import at.gv.egovernment.moa.id.auth.builder.BPKBuilder;
import at.gv.egovernment.moa.id.auth.data.IdentityLink;
import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
import at.gv.egovernment.moa.id.auth.exception.BuildException;
import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider;
import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
import at.gv.egovernment.moa.id.data.IAuthData;
import at.gv.egovernment.moa.id.data.SLOInformationInterface;
import at.gv.egovernment.moa.id.moduls.IAction;
import at.gv.egovernment.moa.id.moduls.IRequest;
import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
import at.gv.egovernment.moa.logging.Logger;
import at.gv.egovernment.moa.util.Constants;
import eu.stork.peps.auth.commons.IPersonalAttributeList;
import eu.stork.peps.auth.commons.PersonalAttribute;
import eu.stork.peps.auth.commons.PersonalAttributeList;
import eu.stork.peps.auth.commons.STORKAttrQueryResponse;
import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import java.io.StringWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.regex.Pattern;

/**
 *
 */
public class MandateRetrievalRequest implements IAction {

    private IAuthData authData;
    private MOASTORKRequest moaStorkRequest;
    private IdentityLink representingIdentityLink;
    private Integer QAALevel;
    private byte[] originalContent;

    public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq,
            HttpServletResponse httpResp, IAuthData authData) throws MOAIDException {
        Logger.debug("Entering AttributeRequest for MandateProvider");
        httpResp.reset();
        this.representingIdentityLink = authData.getIdentityLink();
        this.QAALevel = translateQAALevel(authData.getQAALevel());

        // preparing original content and removing sensitive data from it
        this.originalContent = authData.getMISMandate().getMandate(); // TODO ERROR
        //Logger.debug("Original content " + StringUtils.newStringUtf8(authData.getMISMandate().getMandate()));
        String originalMandate = StringUtils.newStringUtf8(authData.getMISMandate().getMandate()).replaceAll(
                "<pd:Value>.*?==</pd:Value><pd:Type>urn:publicid:gv.at:baseid</pd:Type>",
                "<pd:Value></pd:Value><pd:Type></pd:Type>");
        ;
        Logger.debug("Removing personal identification value and type from original mandate ");
        originalContent = StringUtils.getBytesUtf8(originalMandate);

        OAAuthParameter oaParam = AuthConfigurationProvider.getInstance()
                .getOnlineApplicationParameter(req.getOAURL());
        if (oaParam == null)
            throw new AuthenticationException("stork.12", new Object[] { req.getOAURL() });

        MOASTORKResponse moaStorkResponse = new MOASTORKResponse();
        STORKAttrQueryResponse attrResponse = new STORKAttrQueryResponse();

        this.authData = authData;

        if ((req instanceof MOASTORKRequest)) {
            this.moaStorkRequest = (MOASTORKRequest) req;
        } else {
            Logger.error("Internal error - did not receive MOASTORKRequest as expected");
            throw new MOAIDException("stork.16", new Object[] {}); // TODO
        }

        if (!(moaStorkRequest.isAttrRequest() || moaStorkRequest.getStorkAttrQueryRequest() == null)) {
            Logger.error("Did not receive attribute request as expected");
            throw new MOAIDException("stork.16", new Object[] {}); // TODO
        }

        MandateContainer mandateContainer = null;

        try {
            mandateContainer = new CorporateBodyMandateContainer(
                    new String(authData.getMISMandate().getMandate(), "UTF-8"));
        } catch (Exception ex) {
            try {
                mandateContainer = new PhyPersonMandateContainer(
                        new String(authData.getMISMandate().getMandate(), "UTF-8"));
            } catch (Exception ex2) {
                Logger.error("Could not extract data and create mandate container.");
                throw new MOAIDException("stork.16", new Object[] {}); // TODO
            }
        }

        IPersonalAttributeList sourceAttributeList = moaStorkRequest.getStorkAttrQueryRequest()
                .getPersonalAttributeList();

        IPersonalAttributeList attributeList = new PersonalAttributeList();

        for (PersonalAttribute currentAttribute : sourceAttributeList) {
            Logger.debug("Evaluating currentattribute " + currentAttribute.getName());
            if (currentAttribute.getName().equals("mandateContent")) {
                MandateContentType mandateContent = getMandateContent(mandateContainer, currentAttribute);
                attributeList.add(marshallComplexAttribute(currentAttribute, mandateContent));
            } else if (currentAttribute.getName().equals("representative")) { //  TODO CHECK IN DETAIL
                RepresentationPersonType representative = getRepresentative(mandateContainer, currentAttribute);
                attributeList.add(marshallComplexAttribute(currentAttribute, representative));

                //attributeList.add(getRepresentative(mandateContainer, currentAttribute));
            } else if (currentAttribute.getName().equals("represented")) {
                //attributeList.add(getRepresented(mandateContainer, currentAttribute));
                RepresentationPersonType represented = getRepresented(mandateContainer, currentAttribute);
                attributeList.add(marshallComplexAttribute(currentAttribute, represented));

            } else if (currentAttribute.getName().equals("mandate")) {
                //attributeList.add(getMandateType(mandateContainer, currentAttribute));
                MandateType mandateType = getMandateType(mandateContainer, currentAttribute);
                attributeList.add(marshallComplexAttribute(currentAttribute, mandateType));

            } else if (currentAttribute.getName().equals("legalName")) {
                String legalName = getLegalName(mandateContainer, currentAttribute);
                if (legalName.length() > 0) {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(legalName), AttributeStatusType.AVAILABLE.value()));
                } else {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(legalName), AttributeStatusType.NOT_AVAILABLE.value()));
                }
            } else if (currentAttribute.getName().equals("eLPIdentifier")) {
                String eLPIdentifier = geteLPIdentifier(mandateContainer, currentAttribute);
                if (eLPIdentifier.length() > 0) {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(eLPIdentifier), AttributeStatusType.AVAILABLE.value()));
                } else {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(eLPIdentifier), AttributeStatusType.NOT_AVAILABLE.value()));
                }
            } else if (currentAttribute.getName().equals("type")) {
                String type = getCompanyType(mandateContainer, currentAttribute);
                if (type.length() > 0) {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(type), AttributeStatusType.AVAILABLE.value()));
                } else {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(type), AttributeStatusType.NOT_AVAILABLE.value()));
                }
            } else if (currentAttribute.getName().equals("status")) {
                String status = getCompanyStatus(mandateContainer, currentAttribute);
                if (status.length() > 0) {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(status), AttributeStatusType.AVAILABLE.value()));
                } else {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(status), AttributeStatusType.NOT_AVAILABLE.value()));
                }
            } else if (currentAttribute.getName().equals("translatableType")) {
                String translatableType = getCompanyTranslatableType(mandateContainer, currentAttribute);
                if (translatableType.length() > 0) {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(translatableType), AttributeStatusType.AVAILABLE.value()));
                } else {
                    attributeList
                            .add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                                    Arrays.asList(translatableType), AttributeStatusType.NOT_AVAILABLE.value()));
                }
            }

        }

        //            if (attrResponse.getPersonalAttributeList().size() == 0) {
        //                Logger.error("AttributeList empty - could not retrieve attributes");
        //                throw new MOAIDException("stork.16", new Object[]{}); // TODO MESSAGE
        //            }

        attrResponse.setPersonalAttributeList(attributeList);
        moaStorkResponse.setSTORKAttrResponse(attrResponse);

        Logger.debug("Attributes retrieved: "
                + moaStorkResponse.getStorkAttrQueryResponse().getPersonalAttributeList().size()
                + " for SP country " + attrResponse.getCountry());

        // Prepare extended attributes
        Logger.debug("Preparing data container");

        // create fresh container
        DataContainer container = new DataContainer();

        // - fill in the request we extracted above
        container.setRequest(moaStorkRequest);

        // - fill in the partial response created above
        container.setResponse(moaStorkResponse);

        container.setRemoteAddress(httpReq.getRemoteAddr());

        Logger.debug("Data container prepared");

        // ask for consent if necessary
        if (oaParam.isRequireConsentForStorkAttributes())
            new ConsentEvaluator().requestConsent(container, httpResp, oaParam);
        else
            new ConsentEvaluator().generateSTORKResponse(httpResp, container);

        return null;
    }

    private Integer translateQAALevel(String qaaLevel) throws MOAIDException {
        if (qaaLevel.equals(PVPConstants.STORK_QAA_1_1))
            return 1;
        if (qaaLevel.equals(PVPConstants.STORK_QAA_1_2))
            return 2;
        if (qaaLevel.equals(PVPConstants.STORK_QAA_1_3))
            return 3;
        if (qaaLevel.equals(PVPConstants.STORK_QAA_1_4))
            return 4;
        Logger.error("Wrong QAA Number format");
        throw new MOAIDException("stork.16", new Object[] {});
    }

    private String geteLPIdentifier(MandateContainer mandateContainer, PersonalAttribute currentAttribute)
            throws MOAIDException {
        RepresentationPersonType represented = getRepresented(mandateContainer, currentAttribute);
        if (mandateContainer instanceof CorporateBodyMandateContainer) {
            return represented.getELPIdentifier();
        } else if (currentAttribute.isRequired()) {
            Logger.error("Cannot provide eLPIdentifier for natural person.");
            throw new MOAIDException("stork.19", new Object[] { currentAttribute.getName() }); // TODO
        }
        return "";
    }

    private PersonalAttribute marshallComplexAttribute(PersonalAttribute currentAttribute, Object obj) { // TODO refactor
        StringWriter stringWriter = new StringWriter();
        try {
            if (obj instanceof MandateContentType) {
                final Marshaller marshaller = JAXBContext.newInstance(MandateContentType.class).createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                marshaller.marshal(new JAXBElement<MandateContentType>(
                        new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()),
                        MandateContentType.class, null, (MandateContentType) obj), stringWriter);
            } else if (obj instanceof MandateType) {
                final Marshaller marshaller = JAXBContext.newInstance(MandateType.class).createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                marshaller.marshal(new JAXBElement<MandateType>(
                        new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()),
                        MandateType.class, null, (MandateType) obj), stringWriter);
            } else if (obj instanceof RepresentationPersonType) {
                final Marshaller marshaller = JAXBContext.newInstance(RepresentationPersonType.class)
                        .createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                marshaller.marshal(
                        new JAXBElement<RepresentationPersonType>(
                                new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()),
                                RepresentationPersonType.class, null, (RepresentationPersonType) obj),
                        stringWriter);
            }

        } catch (Exception ex) {
            Logger.error("Could not marshall atrribute: " + currentAttribute.getName() + ", " + ex.getMessage());
            return new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                    new ArrayList<String>(), AttributeStatusType.NOT_AVAILABLE.value());
        }
        ArrayList<String> value = new ArrayList<String>();
        value.add(stringWriter.toString());

        PersonalAttribute personalAttribute = new PersonalAttribute(currentAttribute.getName(),
                currentAttribute.isRequired(), value, AttributeStatusType.AVAILABLE.value());
        return personalAttribute;
    }

    private String mapPowersType(MandateContainer mandateContainer) {
        // using if for java 6 compatibility if necessary
        if (mandateContainer.getAnnotation().equals("ELGABilateral")) {
            return "6"; // Health Powers
        } else if (mandateContainer.getAnnotation().equals("ERsB")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("GeneralvollmachtBilateral")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("ERsBMitPostvollmacht")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("ZVR")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("ZVRMitPostvollmacht")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("EVB")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("Einzelvertretungsbefugnis")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("Prokura")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("Notar")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("Organwalter")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("Rechtsanwalt")) {
            return "0"; // General Powers
        } else if (mandateContainer.getAnnotation().equals("Ziviltechniker")) {
            return "0"; // General Powers
        }
        return "9";
    }

    private MandateType getMandateType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute)
            throws MOAIDException {
        MandateType mandateType = new MandateType();
        RepresentationPersonType representative = getRepresentative(mandateContainer, sourceAttribute);
        RepresentationPersonType represented = getRepresented(mandateContainer, sourceAttribute);
        MandateContentType mandateContent = getMandateContent(mandateContainer, sourceAttribute);
        mandateType.setRepresentative(representative);
        mandateType.setRepresented(represented);
        mandateType.getMandateContent().add(mandateContent);
        Logger.debug("Complex attribute extracted: " + sourceAttribute.getName());
        return mandateType;
    }

    private String getLegalName(MandateContainer mandateContainer, PersonalAttribute sourceAttribute)
            throws MOAIDException {
        RepresentationPersonType represented = getRepresented(mandateContainer, sourceAttribute);
        if (mandateContainer instanceof CorporateBodyMandateContainer) {
            represented.getLegalName();
            //return represented.getName();
        } else if (sourceAttribute.isRequired()) {
            Logger.error("Cannot provide legalName for natural person.");
            throw new MOAIDException("stork.19", new Object[] { sourceAttribute.getName() });
        }
        return "";
    }

    private String getLegalIdentificationType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute)
            throws MOAIDException {
        if (mandateContainer instanceof CorporateBodyMandateContainer) {
            return ((CorporateBodyMandateContainer) mandateContainer).getCorpMandatorIdentificationType();
        } else if (sourceAttribute.isRequired()) {
            Logger.error("Cannot provide type for natural person.");
            throw new MOAIDException("stork.19", new Object[] { sourceAttribute.getName() }); // TODO
        }
        return "";
    }

    private String getCompanyStatus(MandateContainer mandateContainer, PersonalAttribute sourceAttribute)
            throws MOAIDException {
        String legalName = getLegalName(mandateContainer, sourceAttribute);
        if (legalName.contains("in Liquidation") || legalName.contains("in Liqu.")) {
            return "L"; // liqudation
        }
        return "R";
    }

    private String getCompanyType(String legalName, String legalIdentificationType,
            PersonalAttribute sourceAttrivbute) throws MOAIDException {
        // compile patterns for different organisation types
        // sources: USP, WKO, LexAndTax

        // gmbh patterns
        ArrayList<Pattern> gmbhPatterns = new ArrayList<Pattern>();
        gmbhPatterns.add(Pattern.compile(".+ GmbH(( in Liquidation)|( in Liqu.)){0,1}$"));
        gmbhPatterns.add(Pattern.compile(".+ GesmbH$"));
        gmbhPatterns.add(Pattern.compile(".+ Gesellschaft mit beschrnkter Haftung$"));
        gmbhPatterns.add(Pattern.compile(".+ Ges\\.m\\.b\\.H\\.$"));
        gmbhPatterns.add(Pattern.compile(".+ G\\.m\\.b\\.H\\.$"));
        gmbhPatterns.add(Pattern.compile(".+ Handelsges\\.m\\.b\\.H\\.$"));
        gmbhPatterns.add(Pattern.compile(".+ Gesellschaft m\\.b\\.H\\.$"));

        // ag patterns
        ArrayList<Pattern> agPatterns = new ArrayList<Pattern>();
        agPatterns.add(Pattern.compile(".+ AG$"));
        agPatterns.add(Pattern.compile(".+ Aktiengesellschaft$"));

        // og patterns
        ArrayList<Pattern> ogPatterns = new ArrayList<Pattern>();
        ogPatterns.add(Pattern.compile(".+ OG$"));
        ogPatterns.add(Pattern.compile(".+ OHG$"));
        ogPatterns.add(Pattern.compile(".+ offene Gesellschaft$"));

        // kg patterns
        ArrayList<Pattern> kgPatterns = new ArrayList<Pattern>();
        kgPatterns.add(Pattern.compile(".+ KG$"));
        kgPatterns.add(Pattern.compile(".+ Kommanditgesellschaft$"));

        // eu patterns
        ArrayList<Pattern> euPatterns = new ArrayList<Pattern>();
        euPatterns.add(Pattern.compile(".+ eingetragene Unternehmerin$"));
        euPatterns.add(Pattern.compile(".+ eingetragener Unternehmer$"));
        euPatterns.add(Pattern.compile(".+ e\\.U\\.$"));

        // company patterns
        HashMap<String, ArrayList<Pattern>> companyPatterns = new HashMap<String, ArrayList<Pattern>>();
        companyPatterns.put("GmbH", gmbhPatterns);
        companyPatterns.put("AG", agPatterns);
        companyPatterns.put("OG", ogPatterns);
        companyPatterns.put("KG", kgPatterns);
        companyPatterns.put("e.U.", euPatterns);

        // iterate over different types of companies and check if the name ending matches
        if (S2Constants.IDENTIFICATION_TYPE_COMPANY.equals(legalIdentificationType)) {
            for (String companyType : companyPatterns.keySet()) {
                for (Pattern pattern : companyPatterns.get(companyType)) {
                    if (pattern.matcher(legalName).matches()) {
                        return companyType;
                    }
                }
            }
        }

        // check if the subject is association
        if (S2Constants.IDENTIFICATION_TYPE_ASSOCIATION.equals(legalIdentificationType)) {
            return "Verein";
        }

        // check if the subject falls under category of others
        if (S2Constants.IDENTIFICATION_TYPE_OTHERS.equals(legalIdentificationType)) {
            return "ERsB";
        }

        return "";
    }

    private String getCompanyType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute)
            throws MOAIDException {
        // retrieve the registered subject name and identification type
        String legalName = getLegalName(mandateContainer, sourceAttribute);
        String legalIdentificationType = getLegalIdentificationType(mandateContainer, sourceAttribute);
        return getCompanyType(legalName, legalIdentificationType, sourceAttribute);
    }

    private String getCompanyTranslatableType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute)
            throws MOAIDException {
        // retrieve first the company type
        String companyType = getCompanyType(mandateContainer, sourceAttribute);

        // translate company type based on the section 5.6 in STORK 2 D4.11
        if (companyType.length() == 0) {
            return "";
        } else if (companyType.equals("GmbH")) {
            return "G";
        } else if (companyType.equals("AG")) {
            return "A";
        } else if (companyType.equals("OG")) {
            return "O";
        } else if (companyType.equals("KG")) {
            return "K";
        } else {
            return "";
        }
    }

    private String getRepresentedStorkeIdentifier(MandateContainer mandateContainer) throws MOAIDException {

        //String identificationType, String identificationValue
        if (!(mandateContainer instanceof PhyPersonMandateContainer)) {
            Logger.error("Physical person mandate container missing");
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }

        PhyPersonMandateContainer phyPersonMandateContainer = (PhyPersonMandateContainer) mandateContainer;

        if (!phyPersonMandateContainer.getPhyPersMandatorIdentificationType().equals(Constants.URN_PREFIX_BASEID)) {
            Logger.error("Identification type of represented person from MIS is not correct");
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }

        if (phyPersonMandateContainer.getPhyPersMandatorIdentificationValue().length() != 24) {
            Logger.error("Identification value of represented person from MIS is not correct");
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }

        if ((this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry() == null)
                || (this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry().length() == 0)) {
            Logger.error("Error accessing SP country code");
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }

        BPKBuilder bpkBuilder = new BPKBuilder();
        try {
            return bpkBuilder.buildStorkeIdentifier(
                    phyPersonMandateContainer.getPhyPersMandatorIdentificationType(),
                    phyPersonMandateContainer.getPhyPersMandatorIdentificationValue(),
                    this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry());
        } catch (BuildException be) {
            Logger.error("Could not build STORK eIdentifier while generating mandate assertion.");
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }
    }

    private String getRepresentingStorkeIdentifier(MandateContainer mandateContainer) throws MOAIDException {
        if ((this.representingIdentityLink == null)) {
            Logger.error("Error accessing identityLink while fetching mandate attribute");
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }

        if ((this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry() == null)
                || (this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry().length() == 0)) {
            Logger.error("Error accessing SP country code");
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }

        if (!this.representingIdentityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) {
            Logger.error("Incorrect identity link (local): identification type is not correct! Got: "
                    + this.representingIdentityLink.getIdentificationType());
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }

        if (!mandateContainer.getPhysicalRepresentativeIdentificationType().equals(Constants.URN_PREFIX_BASEID)) {
            Logger.error("Incorrect identity link (MIS): identification type is not correct! Got: "
                    + this.representingIdentityLink.getIdentificationType() + " (representingIdentityLink) and "
                    + mandateContainer.getPhysicalRepresentativeIdentificationType()
                    + " (mandateContainer.phyRepresentative)");
            Logger.debug("mandatecontainervalue: " + mandateContainer.getPhysicalRepresentativeIdentificationValue()
                    + ", representingidentitylinkvalue: " + this.representingIdentityLink.getIdentificationValue());
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }

        if (!mandateContainer.getPhysicalRepresentativeIdentificationValue()
                .equals(this.representingIdentityLink.getIdentificationValue())) {
            Logger.error("Identification values from MIS and local service are not equal!");
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }

        BPKBuilder bpkBuilder = new BPKBuilder();
        try {
            return bpkBuilder.buildStorkeIdentifier(this.representingIdentityLink,
                    this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry());
        } catch (BuildException be) {
            Logger.error("Could not build STORK eIdentifier while generating mandate assertion.");
            throw new MOAIDException("stork.20", new Object[] {}); // TODO
        }
    }

    private RepresentationPersonType getRepresentative(MandateContainer mandateContainer,
            PersonalAttribute sourceAttribute) throws MOAIDException {
        RepresentationPersonType representative = new RepresentationPersonType();

        representative.setEIdentifier(getRepresentingStorkeIdentifier(mandateContainer));
        representative.setGivenName(mandateContainer.getPhysicalRepresentativeGivenName());
        representative.setSurname(mandateContainer.getPhysicalRepresentativeFamilyName());
        representative.setDateOfBirth(mandateContainer.getPhysicalRepresentativeBirthDate());

        Logger.debug("Complex attribute extracted: " + sourceAttribute.getName());
        return representative;
    }

    private RepresentationPersonType getRepresented(MandateContainer mandateContainer,
            PersonalAttribute sourceAttribute) throws MOAIDException {
        RepresentationPersonType represented = new RepresentationPersonType();

        if (mandateContainer instanceof CorporateBodyMandateContainer) {
            CorporateBodyMandateContainer corporateBodyMandateContainer = (CorporateBodyMandateContainer) mandateContainer;
            represented.setELPIdentifier(corporateBodyMandateContainer.getCorpMandatorIdentificationValue());
            represented.setLegalName(corporateBodyMandateContainer.getCorpMandatorFullName());
            represented.setTextRegisteredAddress(null);
            represented.setCanonicalRegisteredAddress(new CanonicalAddressType());
            represented.setLegalForm(getCompanyType(corporateBodyMandateContainer.corpMandatorFullName,
                    corporateBodyMandateContainer.corpMandatorIdentificationType, sourceAttribute));
        } else if (mandateContainer instanceof PhyPersonMandateContainer) {
            PhyPersonMandateContainer phyPersonMandateContainer = (PhyPersonMandateContainer) mandateContainer;
            represented.setEIdentifier(getRepresentedStorkeIdentifier(mandateContainer));
            represented.setGivenName(phyPersonMandateContainer.getPhyPersMandatorGivenName());
            represented.setSurname(phyPersonMandateContainer.getPhyPersMandatorFamilyName());
            represented.setDateOfBirth(phyPersonMandateContainer.getPhyPersMandatorBirthDate());
        }

        Logger.debug("Complex attribute extracted: " + sourceAttribute.getName());

        return represented;
    }

    private MandateContentType getMandateContent(MandateContainer mandateContainer,
            PersonalAttribute sourceAttribute) throws MOAIDException {
        MandateContentType mandateContent = new MandateContentType();
        try {
            XMLGregorianCalendar validFrom = DatatypeFactory.newInstance()
                    .newXMLGregorianCalendar(mandateContainer.getMandateValidFrom());
            XMLGregorianCalendar validTo = DatatypeFactory.newInstance()
                    .newXMLGregorianCalendar(mandateContainer.getMandateValidTo());
            TimeRestrictionType timeRestriction = new TimeRestrictionType();
            timeRestriction.setValidFrom(validFrom);
            timeRestriction.setValidTo(validTo);
            mandateContent.setTimeRestriction(timeRestriction);
        } catch (DatatypeConfigurationException dte) {
            Logger.error("Error converting date from mandate: " + mandateContainer.getMandateValidFrom() + ", "
                    + mandateContainer.getMandateValidTo());
            throw new MOAIDException("stork.20", new Object[] {});
        }
        mandateContent.setAQAA(this.QAALevel);
        mandateContent.setOriginalMandate(originalContent);
        mandateContent.setOriginalMandateType("application/xml");
        TransactionLimitRestrictionType transactionLimit = new TransactionLimitRestrictionType();
        mandateContent.setTransactionLimit(transactionLimit);
        mandateContent.setIsJoint("");
        mandateContent.setIsChained(false);
        mandateContent.setTypeOfPower(mapPowersType(mandateContainer)); // TODO check
        Logger.debug("Complex attribute extracted: " + sourceAttribute.getName());
        return mandateContent;
    }

    public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) {
        return true;
    }

    public String getDefaultActionName() {
        return STORKProtocol.MANDATERETRIEVALREQUEST;
    }
}