Search in sources :

Example 6 with InitializationException

use of com.helger.commons.exception.InitializationException in project phase4 by phax.

the class ServletConfig method _initPeppolAS4.

private static void _initPeppolAS4() {
    // Check if crypto properties are okay
    final KeyStore aKS = AS4CryptoFactoryProperties.getDefaultInstance().getKeyStore();
    if (aKS == null)
        throw new InitializationException("Failed to load configured Keystore");
    LOGGER.info("Successfully loaded configured key store from the crypto factory");
    final KeyStore.PrivateKeyEntry aPKE = AS4CryptoFactoryProperties.getDefaultInstance().getPrivateKeyEntry();
    if (aPKE == null)
        throw new InitializationException("Failed to load configured private key");
    LOGGER.info("Successfully loaded configured private key from the crypto factory");
    // No OCSP check for performance
    final X509Certificate aAPCert = (X509Certificate) aPKE.getCertificate();
    // TODO This block SHOULD be uncommented once you have a Peppol certificate
    if (false) {
        final EPeppolCertificateCheckResult eCheckResult = PeppolCertificateChecker.checkPeppolAPCertificate(aAPCert, MetaAS4Manager.getTimestampMgr().getCurrentDateTime(), ETriState.FALSE, null);
        if (eCheckResult.isInvalid())
            throw new InitializationException("The provided certificate is not a Peppol certificate. Check result: " + eCheckResult);
        LOGGER.info("Sucessfully checked that the provided Peppol AP certificate is valid.");
    }
    final String sSMPURL = AS4Configuration.getConfig().getAsString("smp.url");
    final String sAPURL = AS4Configuration.getThisEndpointAddress();
    if (StringHelper.hasText(sSMPURL) && StringHelper.hasText(sAPURL)) {
        // To process the message even though the receiver is not registered in
        // our AP
        Phase4PeppolServletConfiguration.setReceiverCheckEnabled(false);
        Phase4PeppolServletConfiguration.setSMPClient(new SMPClientReadOnly(URLHelper.getAsURI(sSMPURL)));
        Phase4PeppolServletConfiguration.setAS4EndpointURL(sAPURL);
        Phase4PeppolServletConfiguration.setAPCertificate(aAPCert);
        LOGGER.info("phase4 Peppol receiver checks are enabled");
    } else {
        Phase4PeppolServletConfiguration.setReceiverCheckEnabled(false);
        LOGGER.warn("phase4 Peppol receiver checks are disabled");
    }
}
Also used : EPeppolCertificateCheckResult(com.helger.peppol.utils.EPeppolCertificateCheckResult) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) InitializationException(com.helger.commons.exception.InitializationException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate)

Example 7 with InitializationException

use of com.helger.commons.exception.InitializationException in project phase4 by phax.

the class ServletConfig method _initGlobalSettings.

private static void _initGlobalSettings(@Nonnull final ServletContext aSC) {
    // Logging: JUL to SLF4J
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    if (GlobalDebug.isDebugMode()) {
        RequestTrackerSettings.setLongRunningRequestsCheckEnabled(false);
        RequestTrackerSettings.setParallelRunningRequestsCheckEnabled(false);
    }
    HttpDebugger.setEnabled(false);
    // Sanity check
    if (CommandMap.getDefaultCommandMap().createDataContentHandler(CMimeType.MULTIPART_RELATED.getAsString()) == null)
        throw new IllegalStateException("No DataContentHandler for MIME Type '" + CMimeType.MULTIPART_RELATED.getAsString() + "' is available. There seems to be a problem with the dependencies/packaging");
    // Enforce Peppol profile usage
    AS4ProfileSelector.setCustomAS4ProfileID(AS4PeppolProfileRegistarSPI.AS4_PROFILE_ID);
    // Init the data path
    {
        // Get the ServletContext base path
        final String sServletContextPath = ServletHelper.getServletContextBasePath(aSC);
        // Get the data path
        final String sDataPath = AS4Configuration.getDataPath();
        if (StringHelper.hasNoText(sDataPath))
            throw new InitializationException("No data path was provided!");
        final boolean bFileAccessCheck = false;
        // Init the IO layer
        WebFileIO.initPaths(new File(sDataPath).getAbsoluteFile(), sServletContextPath, bFileAccessCheck);
    }
}
Also used : InitializationException(com.helger.commons.exception.InitializationException) File(java.io.File)

Example 8 with InitializationException

use of com.helger.commons.exception.InitializationException in project phase4 by phax.

the class MetaAS4Manager method onAfterInstantiation.

@Override
protected void onAfterInstantiation(@Nonnull final IScope aScope) {
    try {
        LOGGER.info("Creating AS4 managers using factory class " + s_aFactory.getClass().getName());
        // MPC manager before PMode manager
        m_aMPCMgr = s_aFactory.createMPCManager();
        m_aPModeMgr = s_aFactory.createPModeManager();
        m_aIncomingDuplicateMgr = s_aFactory.createDuplicateManager();
        m_aProfileMgr = s_aFactory.createProfileManager();
        // Validate content
        m_aPModeMgr.validateAllPModes();
        LOGGER.info(ClassHelper.getClassLocalName(this) + " was initialized");
    } catch (final Exception ex) {
        throw new InitializationException("Failed to init " + ClassHelper.getClassLocalName(this), ex);
    }
}
Also used : InitializationException(com.helger.commons.exception.InitializationException) InitializationException(com.helger.commons.exception.InitializationException)

Example 9 with InitializationException

use of com.helger.commons.exception.InitializationException in project ph-commons by phax.

the class MainReadSharedMimeInfo method main.

public static void main(final String[] args) throws MimeTypeParserException {
    LOGGER.info("Reading shared-mime-info/freedesktop.org.xml");
    final IMicroDocument aDoc = MicroReader.readMicroXML(new File("src/test/resources/shared-mime-info/freedesktop.org.xml.in"));
    if (aDoc == null)
        throw new IllegalStateException("Failed to read mime type info file!");
    final MimeTypeInfoManager aMgr = new MimeTypeInfoManager();
    for (final IMicroElement eSrcMimeType : aDoc.getDocumentElement().getAllChildElements(NS, "mime-type")) {
        final String sMIMEType = eSrcMimeType.getAttributeValue("type");
        final ICommonsOrderedSet<MimeTypeWithSource> aLocalNames = new CommonsLinkedHashSet<>();
        // Names
        aLocalNames.add(new MimeTypeWithSource(sMIMEType));
        for (final IMicroElement eSrcChild : eSrcMimeType.getAllChildElements(NS, "alias")) {
            final String sAlias = eSrcChild.getAttributeValue("type");
            aLocalNames.add(new MimeTypeWithSource(sAlias));
        }
        // Description
        String sComment = null;
        for (final IMicroElement eSrcChild : eSrcMimeType.getAllChildElements(NS, "comment")) if (!eSrcChild.hasAttribute("xml:lang")) {
            sComment = eSrcChild.getTextContentTrimmed();
            break;
        }
        // Sub class of
        final ICommonsOrderedSet<String> aSubClassOf = new CommonsLinkedHashSet<>();
        for (final IMicroElement eSrcChild : eSrcMimeType.getAllChildElements(NS, "sub-class-of")) {
            final String s = eSrcChild.getAttributeValue("type");
            aSubClassOf.add(s);
        }
        boolean bHasAnyGlob = false;
        final ICommonsOrderedSet<String> aGlobs = new CommonsLinkedHashSet<>();
        final ICommonsOrderedSet<ExtensionWithSource> aExts = new CommonsLinkedHashSet<>();
        for (final IMicroElement eSrcChild : eSrcMimeType.getAllChildElements(NS, "glob")) {
            final String sPattern = eSrcChild.getAttributeValue("pattern");
            if (RegExHelper.stringMatchesPattern("\\*\\.[0-9a-zA-Z]+", sPattern)) {
                final String sExt = sPattern.substring(2);
                aExts.add(new ExtensionWithSource(sExt));
            } else
                aGlobs.add(sPattern);
            bHasAnyGlob = true;
        }
        if (bHasAnyGlob) {
            // Append only if at least on filename pattern is present
            aMgr.registerMimeType(new MimeTypeInfo(aLocalNames, sComment, aSubClassOf, aGlobs, aExts, "shared-mime-info"));
        }
    }
    LOGGER.info("Read " + aMgr.getAllMimeTypeInfos().size() + " mime type infos");
    // Maps file extension to MIME type
    LOGGER.info("Reading shared-mime-info/fileext-mimetype-mapping-local.xml");
    final Map<String, String> FileExtMap = new HashMap<>();
    if (XMLMapHandler.readMap(new FileSystemResource("src/test/resources/shared-mime-info/fileext-mimetype-mapping-local.xml"), FileExtMap).isFailure())
        throw new InitializationException("Failed to init file extension to mimetype mapping file");
    LOGGER.info("Read " + FileExtMap.size() + " entries");
    // Check old data
    for (final Map.Entry<String, String> aEntry : CollectionHelper.getSortedByKey(FileExtMap).entrySet()) {
        final String sOldExt = aEntry.getKey();
        final String sOldMimeType = aEntry.getValue();
        final MimeType aOldMimeType = MimeTypeParser.parseMimeType(sOldMimeType);
        ICommonsList<MimeTypeInfo> aNew;
        // First check for Mime Type, as they are unique
        aNew = aMgr.getAllInfosOfMimeType(aOldMimeType);
        if (aNew != null) {
            // Mime type is present - check if extension is also present
            boolean bFound = false;
            for (final MimeTypeInfo aInfo : aNew) if (aInfo.containsExtension(sOldExt)) {
                bFound = true;
                break;
            }
            if (!bFound) {
                if (aNew.size() == 1) {
                    aMgr.addExtension(aNew.get(0), new ExtensionWithSource(sOldExt, "old"));
                    if (false)
                        LOGGER.info("Added extension '" + sOldExt + "' to " + sOldMimeType + "!");
                } else
                    LOGGER.error(sOldMimeType + ": '" + sOldExt + "' not found in " + aNew + "!");
            }
        } else {
            // no such mime type present - Check other direction: ext 2 mimetype
            aNew = aMgr.getAllInfosOfExtension(sOldExt);
            if (aNew != null) {
                // Found extension - check if MIME type matches that type
                boolean bFound = false;
                for (final MimeTypeInfo aInfo : aNew) if (aInfo.containsMimeType(sOldMimeType)) {
                    bFound = true;
                    break;
                }
                if (!bFound) {
                    if (aNew.size() == 1) {
                        aMgr.addMimeType(aNew.get(0), new MimeTypeWithSource(aOldMimeType, "old"));
                        if (false)
                            LOGGER.info("'" + sOldExt + "': " + sOldMimeType + " not found in " + aNew.get(0) + "!");
                    } else
                        LOGGER.error("'" + sOldExt + "': " + sOldMimeType + " not found in any of " + aNew + "!");
                }
            } else {
                // No such mapping from ext to mime type
                // Create a new entry
                aMgr.registerMimeType(new MimeTypeInfo(CollectionHelper.newOrderedSet(new MimeTypeWithSource(sOldMimeType)), null, new CommonsLinkedHashSet<>(), new CommonsLinkedHashSet<>(), CollectionHelper.newOrderedSet(new ExtensionWithSource(sOldExt)), "old"));
                if (false)
                    LOGGER.info("Creating new: " + sOldMimeType + " = '" + sOldExt + "'");
            }
        }
    }
    LOGGER.info("Finally having " + aMgr.getAllMimeTypeInfos().size() + " mime type infos");
    if (MicroWriter.writeToFile(aMgr.getAsDocument(), new File("src/main/resources/codelists/mime-type-info.xml")).isSuccess())
        LOGGER.info("done - run mvn license:format !!");
    else
        LOGGER.error("Error writing file");
}
Also used : MimeTypeWithSource(com.helger.xml.util.mime.MimeTypeInfo.MimeTypeWithSource) HashMap(java.util.HashMap) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) InitializationException(com.helger.commons.exception.InitializationException) MimeTypeInfoManager(com.helger.xml.util.mime.MimeTypeInfoManager) MimeType(com.helger.commons.mime.MimeType) ExtensionWithSource(com.helger.xml.util.mime.MimeTypeInfo.ExtensionWithSource) IMicroElement(com.helger.xml.microdom.IMicroElement) MimeTypeInfo(com.helger.xml.util.mime.MimeTypeInfo) IMicroDocument(com.helger.xml.microdom.IMicroDocument) CommonsLinkedHashSet(com.helger.commons.collection.impl.CommonsLinkedHashSet) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with InitializationException

use of com.helger.commons.exception.InitializationException in project ph-commons by phax.

the class SAXReaderFactory method createXMLReader.

@Nonnull
public static org.xml.sax.XMLReader createXMLReader() {
    try {
        org.xml.sax.XMLReader ret;
        if (true) {
            ret = XMLReaderFactory.createXMLReader();
            // Because of a performance flaw in this implementation, explicitly set
            // the system property to avoid scanning JAR files over and over again
            SystemProperties.setPropertyValue("org.xml.sax.driver", ret.getClass().getName());
        } else {
            // This fails with Xerces on the classpath
            ret = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        }
        return ret;
    } catch (final ParserConfigurationException | SAXException ex) {
        throw new InitializationException("Failed to instantiate XML reader!", ex);
    }
}
Also used : ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) InitializationException(com.helger.commons.exception.InitializationException) SAXException(org.xml.sax.SAXException) Nonnull(javax.annotation.Nonnull)

Aggregations

InitializationException (com.helger.commons.exception.InitializationException)22 KeyStore (java.security.KeyStore)4 Nonnull (javax.annotation.Nonnull)4 X509Certificate (java.security.cert.X509Certificate)3 EPeppolCertificateCheckResult (com.helger.peppol.utils.EPeppolCertificateCheckResult)2 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)2 InternalErrorBuilder (com.helger.photon.core.interror.InternalErrorBuilder)2 LoadedKeyStore (com.helger.security.keystore.LoadedKeyStore)2 SMPClientReadOnly (com.helger.smpclient.peppol.SMPClientReadOnly)2 IMicroDocument (com.helger.xml.microdom.IMicroDocument)2 IMicroElement (com.helger.xml.microdom.IMicroElement)2 File (java.io.File)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)2 Test (org.junit.Test)2 CommonsLinkedHashSet (com.helger.commons.collection.impl.CommonsLinkedHashSet)1 PDTFromString (com.helger.commons.datetime.PDTFromString)1 ClassPathResource (com.helger.commons.io.resource.ClassPathResource)1 FileSystemResource (com.helger.commons.io.resource.FileSystemResource)1 MimeType (com.helger.commons.mime.MimeType)1