Example usage for java.lang SecurityException getClass

List of usage examples for java.lang SecurityException getClass

Introduction

In this page you can find the example usage for java.lang SecurityException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.evolveum.midpoint.util.ReflectionUtil.java

/**
 * Try to get java property from the object by reflection
 *///from  w w  w  .ja  v  a 2  s  . com
public static <T> T getJavaProperty(Object object, String propertyName, Class<T> propetyClass) {
    String getterName = getterName(propertyName);
    Method method;
    try {
        method = object.getClass().getMethod(getterName);
    } catch (SecurityException e) {
        throw new IllegalArgumentException(
                "Security error getting getter for property " + propertyName + ": " + e.getMessage(), e);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(
                "No getter for property " + propertyName + " in " + object + " (" + object.getClass() + ")");
    }
    if (method == null) {
        throw new IllegalArgumentException(
                "No getter for property " + propertyName + " in " + object + " (" + object.getClass() + ")");
    }
    if (!propetyClass.isAssignableFrom(method.getReturnType())) {
        throw new IllegalArgumentException(
                "The getter for property " + propertyName + " returns " + method.getReturnType() + ", expected "
                        + propetyClass + " in " + object + " (" + object.getClass() + ")");
    }
    try {
        return (T) method.invoke(object);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                "Error invoking getter for property " + propertyName + " in " + object + " ("
                        + object.getClass() + "): " + e.getClass().getSimpleName() + ": " + e.getMessage(),
                e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException(
                "Error invoking getter for property " + propertyName + " in " + object + " ("
                        + object.getClass() + "): " + e.getClass().getSimpleName() + ": " + e.getMessage(),
                e);
    } catch (InvocationTargetException e) {
        throw new IllegalArgumentException(
                "Error invoking getter for property " + propertyName + " in " + object + " ("
                        + object.getClass() + "): " + e.getClass().getSimpleName() + ": " + e.getMessage(),
                e);
    }
}

From source file:org.coinspark.wallet.CSMessageDatabase.java

public CSMessageDatabase(String FilePrefix, CSLogger CSLog, Wallet ParentWallet) {
    dirName = FilePrefix + MESSAGE_DIR_SUFFIX + File.separator;
    fileName = dirName + MESSAGE_DATABASE_FILENAME
            + ((CSMessageDatabase.testnet3) ? TESTNET3_FILENAME_SUFFIX : ""); // H2 will add .mv.db extension itself
    csLog = CSLog;/*from  w ww .  jav  a  2  s .co  m*/
    wallet = ParentWallet;

    String folder = FilenameUtils.getFullPath(FilePrefix);
    String name = MESSAGE_BLOB_KEYSTORE_FILENAME
            + ((CSMessageDatabase.testnet3) ? TESTNET3_FILENAME_SUFFIX : "") + MESSAGE_MVSTORE_FILE_EXTENSION;
    String blobPath = FilenameUtils.concat(folder, name);
    boolean b = CSMessageDatabase.initBlobMap(blobPath);
    if (!b) {
        log.error("Message DB: Could not create BLOB storage map at: " + blobPath);
        return;
    }

    File dir = new File(dirName);
    if (!dir.exists()) {
        // Files.createDirectory(Paths.get(dirName));
        try {
            dir.mkdir();
        } catch (SecurityException ex) {
            log.error("Message DB: Cannot create files directory" + ex.getClass().getName() + " "
                    + ex.getMessage());
            return;
        }
    }

    String kvStoreFileName = dirName + MESSAGE_META_KEYSTORE_FILENAME
            + ((CSMessageDatabase.testnet3) ? TESTNET3_FILENAME_SUFFIX : "") + MESSAGE_MVSTORE_FILE_EXTENSION;
    kvStore = MVStore.open(kvStoreFileName);
    if (kvStore != null) {
        defMap = kvStore.openMap(MESSAGE_TXID_TO_META_MAP_NAME);
        errorMap = kvStore.openMap(MESSAGE_TXID_TO_ERROR_MAP_NAME);
    }

    // TODO?: This database URL could be passed in via constructor
    String databaseUrl = "jdbc:h2:file:" + fileName + ";USER=sa;PASSWORD=sa;AUTO_SERVER=TRUE";

    try {
        connectionSource = new JdbcConnectionSource(databaseUrl);
        messageDao = DaoManager.createDao(connectionSource, CSMessage.class);
        TableUtils.createTableIfNotExists(connectionSource, CSMessage.class);

        messagePartDao = DaoManager.createDao(connectionSource, CSMessagePart.class);
        TableUtils.createTableIfNotExists(connectionSource, CSMessagePart.class);

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

From source file:org.csploit.android.services.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    mCurrentTask = (Update) intent.getSerializableExtra(UPDATE);
    boolean exitForError = true;

    if (mCurrentTask == null) {
        Logger.error("received null update");
        return;//from  www.j  av a2  s . c  o  m
    }

    mRunning = true;

    try {
        setupNotification();

        mCurrentTask.errorOccurred = true;
        if (!haveLocalFile())
            downloadFile();

        if (mCurrentTask instanceof CoreUpdate)
            System.shutdownCoreDaemon();

        extract();

        if (mCurrentTask instanceof MsfUpdate)
            installGems();

        deleteTemporaryFiles();
        createVersionFile();

        mCurrentTask.errorOccurred = exitForError = false;

        sendDone();
    } catch (SecurityException e) {
        sendError(R.string.bad_permissions);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (KeyException e) {
        sendError(R.string.checksum_failed);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (CancellationException e) {
        sendError(R.string.update_cancelled);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (NoSuchAlgorithmException | RuntimeException | ChildManager.ChildDiedException
            | ChildManager.ChildNotStartedException | InterruptedException | IOException e) {
        sendError(R.string.error_occured);
        System.errorLogging(e);
    } finally {
        if (exitForError) {
            if (mCurrentTask instanceof MsfUpdate)
                clearGemsCache();
            if (!(mCurrentTask instanceof CoreUpdate))
                wipe();
        }
        stopSelf();
        mRunning = false;
    }
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    action what_to_do = (action) intent.getSerializableExtra(ACTION);
    boolean exitForError = true;

    if (what_to_do == null) {
        Logger.error("received null action");
        return;/*from w w w . j  a  v  a2  s.c  o m*/
    }

    mRunning = true;

    switch (what_to_do) {
    case apk_update:
        mCurrentTask = mApkInfo;
        break;
    case ruby_update:
        mCurrentTask = mRubyInfo;
        break;
    case msf_update:
        mCurrentTask = mMsfInfo;
        break;
    case gems_update:
        mCurrentTask = new ArchiveMetadata();
        break;
    }

    try {
        setupNotification();

        synchronized (mCurrentTask) {
            if (!haveLocalFile())
                downloadFile();
            extract();
            correctModes();
            patchShebang();

            if (what_to_do == action.ruby_update)
                updateRubyGems();
            else if (what_to_do == action.msf_update)
                installGems();
            else if (what_to_do == action.gems_update)
                updateGems();

            if (what_to_do != action.apk_update)
                deleteTemporaryFiles();
        }
        exitForError = false;
        if (what_to_do == action.msf_update)
            System.updateLocalMsfVersion();
        if (what_to_do == action.ruby_update)
            System.updateLocalRubyVersion();
        sendDone(what_to_do);
    } catch (SecurityException e) {
        sendError(R.string.bad_permissions);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (KeyException e) {
        sendError(R.string.checksum_failed);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        sendError(R.string.error_occured);
        System.errorLogging(e);
    } catch (CancellationException e) {
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (IOException e) {
        sendError(R.string.error_occured);
        System.errorLogging(e);
    } catch (RuntimeException e) {
        sendError(R.string.error_occured);
        if (e.getClass() == NullPointerException.class)
            System.errorLogging(e);
        else
            Logger.error(e.getClass().getName() + ": " + e.getMessage());
    } catch (InterruptedException e) {
        sendError(R.string.error_occured);
        System.errorLogging(e);
    } finally {
        if (exitForError) {
            clearGemsCache();
            wipe();
        }
        stopSelf();
        mRunning = false;
    }
}

From source file:org.csploit.android.core.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    action what_to_do = (action) intent.getSerializableExtra(ACTION);
    boolean exitForError = true;

    if (what_to_do == null) {
        Logger.error("received null action");
        return;/*from w  w  w  .  j av  a  2 s.  c o  m*/
    }

    mRunning = true;

    switch (what_to_do) {
    case apk_update:
        mCurrentTask = mApkInfo;
        break;
    case core_update:
        mCurrentTask = mCoreInfo;
        break;
    case ruby_update:
        mCurrentTask = mRubyInfo;
        break;
    case msf_update:
        mCurrentTask = mMsfInfo;
        break;
    case gems_update:
        mCurrentTask = new ArchiveMetadata();
        break;
    }

    try {
        setupNotification();

        synchronized (mCurrentTask) {
            mCurrentTask.errorOccurred = true;
            if (!haveLocalFile())
                downloadFile();

            if (what_to_do == action.core_update)
                System.shutdownCoreDaemon();

            extract();

            if (what_to_do == action.msf_update)
                installGems();
            else if (what_to_do == action.gems_update)
                updateGems();
            else if (what_to_do == action.core_update)
                System.initCore();

            deleteTemporaryFiles();
            createVersionFile();

            mCurrentTask.errorOccurred = exitForError = false;
        }

        sendDone(what_to_do);
    } catch (SecurityException e) {
        sendError(what_to_do, R.string.bad_permissions);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (KeyException e) {
        sendError(what_to_do, R.string.checksum_failed);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (CancellationException e) {
        sendError(what_to_do, R.string.update_cancelled);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (IOException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (RuntimeException e) {
        sendError(what_to_do, R.string.error_occured);

        StackTraceElement[] stack = e.getStackTrace();
        StackTraceElement frame = e.getStackTrace()[0];

        for (StackTraceElement f : stack) {
            if (f.getClassName().startsWith("org.csploit.android")) {
                frame = f;
                break;
            }
        }

        Logger.error(String.format("%s: %s [%s:%d]", e.getClass().getName(), e.getMessage(),
                frame.getFileName(), frame.getLineNumber()));
    } catch (InterruptedException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (ChildManager.ChildNotStartedException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (ChildManager.ChildDiedException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (System.SuException e) {
        sendError(what_to_do, R.string.only_4_root);
    } catch (System.DaemonException e) {
        sendError(what_to_do, R.string.heart_attack);
        Logger.error(e.getMessage());
    } finally {
        if (exitForError) {
            if (what_to_do == action.msf_update || what_to_do == action.gems_update)
                clearGemsCache();
            if (what_to_do != action.core_update)
                wipe();
        }
        stopSelf();
        mRunning = false;
    }
}

From source file:wjhk.jupload2.policies.DefaultUploadPolicy.java

/** {@inheritDoc} */
public void setCurrentBrowsingDirectory(File currentBrowsingDirectoryParam) {
    try {/*from   ww  w  .j a va2 s  . c  om*/
        if (currentBrowsingDirectoryParam.isDirectory()) {
            this.currentBrowsingDirectory = currentBrowsingDirectoryParam;
        } else {
            displayWarn("DefaultUploadPolicy.setCurrentBrowsingDirectory(): " + currentBrowsingDirectoryParam
                    + " doesn't exist.");
        }
    } catch (SecurityException se) {
        displayWarn(se.getClass().getName() + " in DefaultUploadPolicy.setCurrentBrowsingDirectory(): "
                + currentBrowsingDirectoryParam + " is ignored.");
    }
}

From source file:wjhk.jupload2.policies.DefaultUploadPolicy.java

/**
 * @param currentBrowsingDirectoryParam/*from  w w  w . ja v  a  2 s. co  m*/
 *            The name of the directory that should be the current one.
 * @see UploadPolicy#setCurrentBrowsingDirectory(String)
 */
public void setCurrentBrowsingDirectory(String currentBrowsingDirectoryParam) {
    try {
        if (currentBrowsingDirectoryParam == null) {
            this.currentBrowsingDirectory = null;
        } else {
            // Apparently, Java deosn't manage path beginning by ~. folder
            // is actually ... ~!
            // Let's manager this.
            if (currentBrowsingDirectoryParam.startsWith("~")) {
                // Let's keep the part of this path that is after the ~
                currentBrowsingDirectoryParam = System.getProperty("user.home")
                        + currentBrowsingDirectoryParam.substring(1);
            }

            this.currentBrowsingDirectory = new File(currentBrowsingDirectoryParam);

            // Let's check that we have a folder.
            if (this.currentBrowsingDirectory != null && !this.currentBrowsingDirectory.isDirectory()) {
                displayWarn("DefaultUploadPolicy.setCurrentBrowsingDirectory(): <"
                        + currentBrowsingDirectoryParam + "> doesn't exist or is not a directory.");
                this.currentBrowsingDirectory = null;
            }
        }
    } catch (SecurityException se) {
        displayWarn(se.getClass().getName() + " in DefaultUploadPolicy.setCurrentBrowsingDirectory(): "
                + currentBrowsingDirectoryParam + " is ignored.");
    }
}

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

public Object handleMessage(AuthenticationDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    LOG.debug("authentication data message received");

    if (null == message.authnCert) {
        /*/*  www  .j  a v  a2 s  . c o m*/
         * Can be the case for future (Kids) eID cards that have some
         * certificates missing.
         */
        String msg = "authentication certificate not present";
        LOG.warn(msg);
        throw new ServletException(msg);
    }
    byte[] signatureValue = message.signatureValue;
    LOG.debug("authn signing certificate subject: " + message.authnCert.getSubjectX500Principal());
    PublicKey signingKey = message.authnCert.getPublicKey();

    if (this.sessionIdChannelBinding) {
        checkSessionIdChannelBinding(message, request);
        if (null == this.serverCertificate) {
            LOG.warn("adviced to use in combination with server certificate channel binding");
        }
    }

    ChannelBindingService channelBindingService = this.channelBindingServiceLocator.locateService();
    if (null != this.serverCertificate || null != channelBindingService) {
        LOG.debug("using server certificate channel binding");
    }

    if (false == this.sessionIdChannelBinding && null == this.serverCertificate
            && null == channelBindingService) {
        LOG.warn("not using any secure channel binding");
    }

    byte[] challenge;
    try {
        challenge = AuthenticationChallenge.getAuthnChallenge(session, this.maxMaturity);
    } catch (SecurityException e) {
        AuditService auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            String remoteAddress = request.getRemoteAddr();
            auditService.authenticationError(remoteAddress, message.authnCert);
        }
        throw new ServletException("security error: " + e.getMessage(), e);
    }

    byte[] serverCertificateClientPOV = null;
    try {
        if (null != message.serverCertificate) {
            serverCertificateClientPOV = message.serverCertificate.getEncoded();
        }
    } catch (CertificateEncodingException e) {
        throw new ServletException("server cert decoding error: " + e.getMessage(), e);
    }
    /*
     * We validate the authentication contract using the client-side
     * communicated server SSL certificate in case of secure channel
     * binding.
     */
    AuthenticationContract authenticationContract = new AuthenticationContract(message.saltValue, this.hostname,
            this.inetAddress, message.sessionId, serverCertificateClientPOV, challenge);
    byte[] toBeSigned;
    try {
        toBeSigned = authenticationContract.calculateToBeSigned();
    } catch (IOException e) {
        throw new ServletException("IO error: " + e.getMessage(), e);
    }

    try {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(signingKey);
        signature.update(toBeSigned);
        boolean result = signature.verify(signatureValue);
        if (false == result) {
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.authenticationError(remoteAddress, message.authnCert);
            }
            throw new SecurityException("authn signature incorrect");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException("algo error");
    } catch (InvalidKeyException e) {
        throw new SecurityException("authn key error");
    } catch (SignatureException e) {
        throw new SecurityException("signature error");
    }

    RequestContext requestContext = new RequestContext(session);
    String transactionMessage = requestContext.getTransactionMessage();
    if (null != transactionMessage) {
        LOG.debug("verifying TransactionMessage signature");
        byte[] transactionMessageSignature = message.transactionMessageSignature;
        if (null == transactionMessageSignature) {
            throw new SecurityException("missing TransactionMessage signature");
        }
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, signingKey);
            byte[] signatureDigestInfoValue = cipher.doFinal(transactionMessageSignature);
            ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue);
            DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject());
            if (false == PLAIN_TEXT_DIGEST_ALGO_OID
                    .equals(signatureDigestInfo.getAlgorithmId().getObjectId().getId())) {
                throw new SecurityException("TransactionMessage signature algo OID incorrect");
            }
            if (false == Arrays.equals(transactionMessage.getBytes(), signatureDigestInfo.getDigest())) {
                throw new SecurityException("signed TransactionMessage incorrect");
            }
            LOG.debug("TransactionMessage signature validated");
        } catch (Exception e) {
            LOG.error("error verifying TransactionMessage signature", e);
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.authenticationError(remoteAddress, message.authnCert);
            }
            throw new SecurityException("error verifying TransactionMessage signature: " + e.getMessage());
        }
    }

    /*
     * Secure channel binding verification.
     */
    if (null != channelBindingService) {
        X509Certificate serverCertificate = channelBindingService.getServerCertificate();
        if (null == serverCertificate) {
            LOG.warn("could not verify secure channel binding as the server does not know its identity yet");
        } else {
            if (false == serverCertificate.equals(message.serverCertificate)) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.authenticationError(remoteAddress, message.authnCert);
                }
                throw new SecurityException("secure channel binding identity mismatch");
            }
            LOG.debug("secure channel binding verified");
        }
    } else {
        if (null != this.serverCertificate) {
            if (false == this.serverCertificate.equals(message.serverCertificate)) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.authenticationError(remoteAddress, message.authnCert);
                }
                throw new SecurityException("secure channel binding identity mismatch");
            }
            LOG.debug("secure channel binding verified");
        }
    }

    AuthenticationService authenticationService = this.authenticationServiceLocator.locateService();
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    certificateChain.add(message.authnCert);
    certificateChain.add(message.citizenCaCert);
    certificateChain.add(message.rootCaCert);
    certificateChain.add(message.rrnCertificate);
    try {
        authenticationService.setHttpSessionObject(request.getSession());
        authenticationService.validateCertificateChain(certificateChain);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    } catch (Exception e) {
        /*
         * We don't want to depend on the full JavaEE profile in this
         * artifact.
         */
        if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
            Exception exception;
            try {
                Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                        new Class[] {});
                exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
            } catch (Exception e2) {
                LOG.debug("error: " + e.getMessage(), e);
                throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
            }
            if (exception instanceof ExpiredCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
            }
            if (exception instanceof RevokedCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
            }
            if (exception instanceof TrustCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
            }
            if (exception instanceof CertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE);
            }
        }
        throw new SecurityException("authn service error: " + e.getMessage());
    }

    String userId = UserIdentifierUtil.getUserId(message.authnCert);
    LOG.info("authenticated: " + userId + " @ " + request.getRemoteAddr());
    if (null != this.nrcidSecret) {
        userId = UserIdentifierUtil.getNonReversibleCitizenIdentifier(userId, this.nrcidOrgId, this.nrcidAppId,
                this.nrcidSecret);
    }
    /*
     * Some people state that you cannot use the national register number
     * without hashing. Problem is that hashing introduces hash collision
     * problems. The probability is very low, but what if it's your leg
     * they're cutting of because of a patient mismatch based on the SHA1 of
     * your national register number?
     */

    /*
     * Push authenticated used Id into the HTTP session.
     */
    session.setAttribute(AUTHENTICATED_USER_IDENTIFIER_SESSION_ATTRIBUTE, userId);

    EIdData eidData = (EIdData) session.getAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE);
    if (null == eidData) {
        eidData = new EIdData();
        session.setAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE, eidData);
    }
    eidData.identifier = userId;

    AuditService auditService = this.auditServiceLocator.locateService();
    if (null != auditService) {
        auditService.authenticated(userId);
    }

    boolean includeIdentity = requestContext.includeIdentity();
    boolean includeAddress = requestContext.includeAddress();
    boolean includeCertificates = requestContext.includeCertificates();
    boolean includePhoto = requestContext.includePhoto();

    /*
     * Also process the identity data in case it was requested.
     */
    if (includeIdentity) {
        if (null == message.identityData) {
            throw new ServletException("identity data not included while requested");
        }
    }
    if (includeAddress) {
        if (null == message.addressData) {
            throw new ServletException("address data not included while requested");
        }
    }
    if (includePhoto) {
        if (null == message.photoData) {
            throw new ServletException("photo data not included while requested");
        }
    }
    IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator.locateService();
    if (null != identityIntegrityService) {
        if (null == message.rrnCertificate) {
            throw new ServletException("national registry certificate not included while requested");
        }
        List<X509Certificate> rrnCertificateChain = new LinkedList<X509Certificate>();
        rrnCertificateChain.add(message.rrnCertificate);
        rrnCertificateChain.add(message.rootCaCert);

        try {
            identityIntegrityService.checkNationalRegistrationCertificate(rrnCertificateChain);
        } catch (ExpiredCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
        } catch (RevokedCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
        } catch (TrustCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
        } catch (CertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE);
        } catch (Exception e) {
            if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
                Exception exception;
                try {
                    Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                            new Class[] {});
                    exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
                } catch (Exception e2) {
                    LOG.debug("error: " + e.getMessage(), e);
                    throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
                }
                if (exception instanceof ExpiredCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
                }
                if (exception instanceof RevokedCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
                }
                if (exception instanceof TrustCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
                }
                if (exception instanceof CertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE);
                }
            }
            throw new SecurityException("error checking the NRN certificate: " + e.getMessage(), e);
        }

        PublicKey rrnPublicKey = message.rrnCertificate.getPublicKey();
        if (includeIdentity) {
            if (null == message.identitySignatureData) {
                throw new ServletException("identity signature data not included while requested");
            }
            verifySignature(message.rrnCertificate.getSigAlgName(), message.identitySignatureData, rrnPublicKey,
                    request, message.identityData);
        }
        if (includeAddress) {
            if (null == message.addressSignatureData) {
                throw new ServletException("address signature data not included while requested");
            }
            byte[] addressFile = trimRight(message.addressData);
            verifySignature(message.rrnCertificate.getSigAlgName(), message.addressSignatureData, rrnPublicKey,
                    request, addressFile, message.identitySignatureData);
        }
    }
    if (includeIdentity) {
        Identity identity = TlvParser.parse(message.identityData, Identity.class);
        if (false == UserIdentifierUtil.getUserId(message.authnCert).equals(identity.nationalNumber)) {
            throw new ServletException("national number mismatch");
        }
        session.setAttribute(IdentityDataMessageHandler.IDENTITY_SESSION_ATTRIBUTE, identity);
        eidData.identity = identity;
        auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            auditService.identified(identity.nationalNumber);
        }
    }
    if (includeAddress) {
        Address address = TlvParser.parse(message.addressData, Address.class);
        session.setAttribute(IdentityDataMessageHandler.ADDRESS_SESSION_ATTRIBUTE, address);
        eidData.address = address;
    }
    if (includePhoto) {
        if (includeIdentity) {
            byte[] expectedPhotoDigest = eidData.identity.photoDigest;
            byte[] actualPhotoDigest = digestPhoto(getDigestAlgo(expectedPhotoDigest.length),
                    message.photoData);
            if (false == Arrays.equals(expectedPhotoDigest, actualPhotoDigest)) {
                throw new ServletException("photo digest incorrect");
            }
        }
        session.setAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE, message.photoData);
        eidData.photo = message.photoData;
    }
    if (includeCertificates) {
        if (includeIdentity) {
            eidData.certs = new EIdCertsData();
            eidData.certs.authn = message.authnCert;
            eidData.certs.ca = message.citizenCaCert;
            eidData.certs.root = message.rootCaCert;
            eidData.certs.sign = message.signCert;
        }
        session.setAttribute(IdentityDataMessageHandler.AUTHN_CERT_SESSION_ATTRIBUTE, message.authnCert);
        session.setAttribute(IdentityDataMessageHandler.CA_CERT_SESSION_ATTRIBUTE, message.citizenCaCert);
        session.setAttribute(IdentityDataMessageHandler.ROOT_CERT_SESSION_ATTRIBTUE, message.rootCaCert);
        session.setAttribute(IdentityDataMessageHandler.SIGN_CERT_SESSION_ATTRIBUTE, message.signCert);
    }

    if (this.includeDataFiles) {
        session.setAttribute(IdentityDataMessageHandler.EID_DATA_IDENTITY_SESSION_ATTRIBUTE,
                message.identityData);
        session.setAttribute(IdentityDataMessageHandler.EID_DATA_ADDRESS_SESSION_ATTRIBUTE,
                message.addressData);
    }

    AuthenticationSignatureService authenticationSignatureService = this.authenticationSignatureServiceLocator
            .locateService();
    if (null != authenticationSignatureService) {
        List<X509Certificate> authnCertificateChain;
        if (null != message.authnCert) {
            authnCertificateChain = new LinkedList<X509Certificate>();
            authnCertificateChain.add(message.authnCert);
            authnCertificateChain.add(message.citizenCaCert);
            authnCertificateChain.add(message.rootCaCert);
            authnCertificateChain.add(message.rrnCertificate);
        } else {
            authnCertificateChain = null;
        }
        AuthenticationSignatureContext authenticationSignatureContext = new AuthenticationSignatureContextImpl(
                session);
        PreSignResult preSignResult = authenticationSignatureService.preSign(authnCertificateChain,
                authenticationSignatureContext);
        if (null == preSignResult) {
            return new FinishedMessage();
        }
        boolean logoff = preSignResult.getLogoff();
        byte[] computedDigestValue = preSignResult.getDigestInfo().digestValue;
        String digestAlgo = preSignResult.getDigestInfo().digestAlgo;
        String authnMessage = preSignResult.getDigestInfo().description;
        AuthSignRequestMessage authSignRequestMessage = new AuthSignRequestMessage(computedDigestValue,
                digestAlgo, authnMessage, logoff);
        return authSignRequestMessage;
    }
    return new FinishedMessage();
}