Search in sources :

Example 1 with WillClose

use of javax.annotation.WillClose in project phase4 by phax.

the class AS4RequestHandler method handleRequest.

/**
 * This is the main handling routine when called from an abstract
 * (non-Servlet) API
 *
 * @param aServletRequestIS
 *        The input stream with the request data. May not be
 *        <code>null</code>.
 * @param aRequestHttpHeaders
 *        The HTTP headers of the request. May not be <code>null</code>.
 * @param aHttpResponse
 *        The HTTP response to be filled. May not be <code>null</code>.
 * @throws Phase4Exception
 *         in case the request is missing certain prerequisites. Since 0.9.11
 * @throws IOException
 *         In case of IO errors
 * @throws MessagingException
 *         MIME related errors
 * @throws WSSecurityException
 *         In case of WSS4J errors
 * @see #handleRequest(InputStream, HttpHeaderMap, IAS4ResponseAbstraction)
 *      for a more generic API
 */
public void handleRequest(@Nonnull @WillClose final InputStream aServletRequestIS, @Nonnull final HttpHeaderMap aRequestHttpHeaders, @Nonnull final IAS4ResponseAbstraction aHttpResponse) throws Phase4Exception, IOException, MessagingException, WSSecurityException {
    final IAS4ParsedMessageCallback aCallback = (aHttpHeaders, aSoapDocument, eSoapVersion, aIncomingAttachments) -> {
        // SOAP document and SOAP version are determined
        // Collect all runtime errors
        final ICommonsList<Ebms3Error> aErrorMessages = new CommonsArrayList<>();
        final IAS4ResponseFactory aResponder = _handleSoapMessage(aHttpHeaders, aSoapDocument, eSoapVersion, aIncomingAttachments, aErrorMessages);
        if (aResponder != null) {
            // Response present -> send back
            final IAS4OutgoingDumper aRealOutgoingDumper = m_aOutgoingDumper != null ? m_aOutgoingDumper : AS4DumpManager.getOutgoingDumper();
            aResponder.applyToResponse(aHttpResponse, aRealOutgoingDumper);
        } else {
            // Success, HTTP No Content
            aHttpResponse.setStatus(CHttp.HTTP_NO_CONTENT);
        }
        AS4HttpDebug.debug(() -> "RECEIVE-END with " + (aResponder != null ? "EBMS message" : "no content"));
    };
    AS4IncomingHandler.parseAS4Message(m_aIAF, m_aResHelper, m_aMessageMetadata, aServletRequestIS, aRequestHttpHeaders, aCallback, m_aIncomingDumper);
}
Also used : AS4DecompressException(com.helger.phase4.attachment.AS4DecompressException) StreamHelper(com.helger.commons.io.stream.StreamHelper) BasicHttpPoster(com.helger.phase4.http.BasicHttpPoster) EMimeContentType(com.helger.commons.mime.EMimeContentType) ESoapVersion(com.helger.phase4.soap.ESoapVersion) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) HttpXMLEntity(com.helger.phase4.http.HttpXMLEntity) LoggerFactory(org.slf4j.LoggerFactory) Ebms3PayloadInfo(com.helger.phase4.ebms3header.Ebms3PayloadInfo) MessagingException(javax.mail.MessagingException) EPModeSendReceiptReplyPattern(com.helger.phase4.model.pmode.leg.EPModeSendReceiptReplyPattern) AS4CryptParams(com.helger.phase4.crypto.AS4CryptParams) NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) EAS4MessageType(com.helger.phase4.messaging.domain.EAS4MessageType) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Nonempty(com.helger.commons.annotation.Nonempty) Locale(java.util.Locale) Document(org.w3c.dom.Document) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) IAS4RetryCallback(com.helger.phase4.client.IAS4RetryCallback) PModeLeg(com.helger.phase4.model.pmode.leg.PModeLeg) IAS4IncomingAttachmentFactory(com.helger.phase4.attachment.IAS4IncomingAttachmentFactory) IAS4OutgoingDumper(com.helger.phase4.dump.IAS4OutgoingDumper) CGlobal(com.helger.commons.CGlobal) AS4SigningParams(com.helger.phase4.crypto.AS4SigningParams) IAS4ServletMessageProcessorSPI(com.helger.phase4.servlet.spi.IAS4ServletMessageProcessorSPI) HttpEntity(org.apache.http.HttpEntity) Ebms3CollaborationInfo(com.helger.phase4.ebms3header.Ebms3CollaborationInfo) IThrowingRunnable(com.helger.commons.callback.IThrowingRunnable) IAS4ParsedMessageCallback(com.helger.phase4.servlet.AS4IncomingHandler.IAS4ParsedMessageCallback) SOAPHeaderElementProcessorRegistry(com.helger.phase4.servlet.soap.SOAPHeaderElementProcessorRegistry) ISuccessIndicator(com.helger.commons.state.ISuccessIndicator) AS4SignalMessageProcessorResult(com.helger.phase4.servlet.spi.AS4SignalMessageProcessorResult) AS4DumpManager(com.helger.phase4.dump.AS4DumpManager) HttpRetrySettings(com.helger.phase4.http.HttpRetrySettings) Ebms3Error(com.helger.phase4.ebms3header.Ebms3Error) AS4ErrorMessage(com.helger.phase4.messaging.domain.AS4ErrorMessage) ICommonsList(com.helger.commons.collection.impl.ICommonsList) Ebms3PartyInfo(com.helger.phase4.ebms3header.Ebms3PartyInfo) HttpMimeMessageEntity(com.helger.phase4.http.HttpMimeMessageEntity) CHttp(com.helger.commons.http.CHttp) PhotonWorkerPool(com.helger.photon.app.PhotonWorkerPool) Ebms3SignalMessage(com.helger.phase4.ebms3header.Ebms3SignalMessage) MessageHelperMethods(com.helger.phase4.messaging.domain.MessageHelperMethods) ResponseHandlerXml(com.helger.httpclient.response.ResponseHandlerXml) AS4Signer(com.helger.phase4.messaging.crypto.AS4Signer) AS4ServletMessageProcessorManager(com.helger.phase4.servlet.mgr.AS4ServletMessageProcessorManager) WillClose(javax.annotation.WillClose) ServletInputStream(javax.servlet.ServletInputStream) AS4MessageProcessorResult(com.helger.phase4.servlet.spi.AS4MessageProcessorResult) AS4HttpDebug(com.helger.phase4.http.AS4HttpDebug) MetaAS4Manager(com.helger.phase4.mgr.MetaAS4Manager) CompletableFuture(java.util.concurrent.CompletableFuture) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) Supplier(java.util.function.Supplier) Ebms3MessageProperties(com.helger.phase4.ebms3header.Ebms3MessageProperties) AS4Encryptor(com.helger.phase4.messaging.crypto.AS4Encryptor) Charset(java.nio.charset.Charset) EAS4MessageMode(com.helger.phase4.messaging.EAS4MessageMode) Node(org.w3c.dom.Node) IAS4IncomingDumper(com.helger.phase4.dump.IAS4IncomingDumper) AS4ResourceHelper(com.helger.phase4.util.AS4ResourceHelper) Ebms3MessageInfo(com.helger.phase4.ebms3header.Ebms3MessageInfo) AS4ReceiptMessage(com.helger.phase4.messaging.domain.AS4ReceiptMessage) Nonnull(javax.annotation.Nonnull) Phase4Exception(com.helger.phase4.util.Phase4Exception) Nullable(javax.annotation.Nullable) EEbmsError(com.helger.phase4.error.EEbmsError) Ebms3Property(com.helger.phase4.ebms3header.Ebms3Property) MimeMessageCreator(com.helger.phase4.messaging.mime.MimeMessageCreator) OutputStream(java.io.OutputStream) IRequestWebScopeWithoutResponse(com.helger.web.scope.IRequestWebScopeWithoutResponse) Ebms3UserMessage(com.helger.phase4.ebms3header.Ebms3UserMessage) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) HasInputStream(com.helger.commons.io.stream.HasInputStream) IPMode(com.helger.phase4.model.pmode.IPMode) StringHelper(com.helger.commons.string.StringHelper) IPModeResolver(com.helger.phase4.model.pmode.resolve.IPModeResolver) AS4MimeMessage(com.helger.phase4.messaging.mime.AS4MimeMessage) EMEPBinding(com.helger.phase4.model.EMEPBinding) IOException(java.io.IOException) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) XMLWriter(com.helger.xml.serialize.write.XMLWriter) ValueEnforcer(com.helger.commons.ValueEnforcer) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) IHasInputStream(com.helger.commons.io.IHasInputStream) MEPHelper(com.helger.phase4.model.MEPHelper) IMimeType(com.helger.commons.mime.IMimeType) CAS4(com.helger.phase4.CAS4) AS4XMLHelper(com.helger.phase4.util.AS4XMLHelper) InputStream(java.io.InputStream) IAS4ParsedMessageCallback(com.helger.phase4.servlet.AS4IncomingHandler.IAS4ParsedMessageCallback) IAS4OutgoingDumper(com.helger.phase4.dump.IAS4OutgoingDumper) ICommonsList(com.helger.commons.collection.impl.ICommonsList)

Example 2 with WillClose

use of javax.annotation.WillClose in project ph-commons by phax.

the class SettingsPersistenceJson method readSettings.

@Nonnull
public ISettings readSettings(@Nonnull @WillClose final InputStream aIS) {
    ValueEnforcer.notNull(aIS, "InputStream");
    // Create the settings object
    final ISettings aSettings = m_aSettingsFactory.apply(getReadSettingsName());
    // Read the properties file from the input stream
    final IJsonObject aProps = JsonReader.builder().source(aIS, m_aCharset).customizeCallback(aParser -> {
        aParser.setRequireStringQuotes(false);
        aParser.setAlwaysUseBigNumber(true);
    }).readAsObject();
    if (aProps != null)
        for (final Map.Entry<String, IJson> aEntry : aProps) _recursiveReadSettings(aEntry.getKey(), aEntry.getValue(), aSettings);
    return aSettings;
}
Also used : ESuccess(com.helger.commons.state.ESuccess) StreamHelper(com.helger.commons.io.stream.StreamHelper) WillClose(javax.annotation.WillClose) ISettingsPersistence(com.helger.settings.exchange.ISettingsPersistence) LoggerFactory(org.slf4j.LoggerFactory) IJsonObject(com.helger.json.IJsonObject) CollectionHelper(com.helger.commons.collection.CollectionHelper) ISettings(com.helger.settings.ISettings) JsonWriterSettings(com.helger.json.serialize.JsonWriterSettings) Charset(java.nio.charset.Charset) Nonempty(com.helger.commons.annotation.Nonempty) Map(java.util.Map) JsonReader(com.helger.json.serialize.JsonReader) Nonnull(javax.annotation.Nonnull) ISettingsFactory(com.helger.settings.factory.ISettingsFactory) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) IOException(java.io.IOException) JsonObject(com.helger.json.JsonObject) JsonWriter(com.helger.json.serialize.JsonWriter) ValueEnforcer(com.helger.commons.ValueEnforcer) TypeConverter(com.helger.commons.typeconvert.TypeConverter) IJson(com.helger.json.IJson) Comparator(java.util.Comparator) InputStream(java.io.InputStream) IJsonObject(com.helger.json.IJsonObject) ISettings(com.helger.settings.ISettings) Nonnull(javax.annotation.Nonnull)

Example 3 with WillClose

use of javax.annotation.WillClose in project ph-commons by phax.

the class DOMReader method readXMLDOM.

@Nullable
public static Document readXMLDOM(@WillClose @Nonnull final InputSource aInputSource, @Nonnull final IDOMReaderSettings aSettings) {
    ValueEnforcer.notNull(aInputSource, "InputSource");
    ValueEnforcer.notNull(aSettings, "Settings");
    Document aDoc = null;
    try {
        final StopWatch aSW = StopWatch.createdStarted();
        final DocumentBuilder aDocumentBuilder;
        boolean bFromPool = false;
        if (aSettings.requiresNewXMLParser()) {
            // We need to create a new DocumentBuilderFactory
            final DocumentBuilderFactory aDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
            // Apply the settings on the DocumentBuilderFactory
            aSettings.applyToDocumentBuilderFactory(aDocumentBuilderFactory);
            // Ready to create document builder
            aDocumentBuilder = aDocumentBuilderFactory.newDocumentBuilder();
        } else {
            // Use one from the pool
            aDocumentBuilder = POOL.borrowObject();
            bFromPool = true;
        }
        try {
            // Apply settings on DocumentBuilder
            aSettings.applyToDocumentBuilder(aDocumentBuilder);
            // Ensure a collecting error handler is present
            final CollectingSAXErrorHandler aCEH;
            final ErrorHandler aCustomErrorHandler = aSettings.getErrorHandler();
            if (aCustomErrorHandler instanceof CollectingSAXErrorHandler)
                aCEH = (CollectingSAXErrorHandler) aCustomErrorHandler;
            else {
                aCEH = new CollectingSAXErrorHandler();
                aDocumentBuilder.setErrorHandler(aCEH.andThen(aCustomErrorHandler));
            }
            // Main parsing
            aDoc = aDocumentBuilder.parse(aInputSource);
            // Statistics update
            if (aSettings.getSchema() == null)
                STARS_DOM_TIMER.addTime(aSW.stopAndGetMillis());
            else
                STATS_DOM_SCHEMA_TIMER.addTime(aSW.stopAndGetMillis());
            // collected errors
            if (aCEH.containsAtLeastOneError())
                return null;
        } finally {
            if (bFromPool) {
                // Return to the pool
                POOL.returnObject(aDocumentBuilder);
            }
        }
    } catch (final Exception ex) {
        aSettings.exceptionCallbacks().forEach(x -> x.onException(ex));
        STATS_DOM_ERROR_COUNTER.increment();
    } finally {
        // Close both byte stream and character stream, as we don't know which one
        // was used
        StreamHelper.close(aInputSource.getByteStream());
        StreamHelper.close(aInputSource.getCharacterStream());
    }
    return aDoc;
}
Also used : StreamHelper(com.helger.commons.io.stream.StreamHelper) Nonnegative(javax.annotation.Nonnegative) URL(java.net.URL) WillClose(javax.annotation.WillClose) ObjectPool(com.helger.commons.pool.ObjectPool) ByteBuffer(java.nio.ByteBuffer) ErrorHandler(org.xml.sax.ErrorHandler) XMLFactory(com.helger.xml.XMLFactory) Document(org.w3c.dom.Document) URI(java.net.URI) Path(java.nio.file.Path) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) IMutableStatisticsHandlerTimer(com.helger.commons.statistics.IMutableStatisticsHandlerTimer) CollectingSAXErrorHandler(com.helger.xml.sax.CollectingSAXErrorHandler) InputSource(org.xml.sax.InputSource) IReadableResource(com.helger.commons.io.resource.IReadableResource) InputSourceFactory(com.helger.xml.sax.InputSourceFactory) ThreadSafe(javax.annotation.concurrent.ThreadSafe) Reader(java.io.Reader) File(java.io.File) ValueEnforcer(com.helger.commons.ValueEnforcer) StatisticsManager(com.helger.commons.statistics.StatisticsManager) StopWatch(com.helger.commons.timing.StopWatch) DocumentBuilder(javax.xml.parsers.DocumentBuilder) IMutableStatisticsHandlerCounter(com.helger.commons.statistics.IMutableStatisticsHandlerCounter) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) InputStream(java.io.InputStream) PresentForCodeCoverage(com.helger.commons.annotation.PresentForCodeCoverage) ErrorHandler(org.xml.sax.ErrorHandler) CollectingSAXErrorHandler(com.helger.xml.sax.CollectingSAXErrorHandler) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) CollectingSAXErrorHandler(com.helger.xml.sax.CollectingSAXErrorHandler) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Document(org.w3c.dom.Document) StopWatch(com.helger.commons.timing.StopWatch) Nullable(javax.annotation.Nullable)

Example 4 with WillClose

use of javax.annotation.WillClose in project ph-commons by phax.

the class SAXReader method readXMLSAX.

/**
 * Read an XML document via a SAX handler. The streams are closed after
 * reading.
 *
 * @param aIS
 *        The input source to read from. Automatically closed upon success or
 *        error. May not be <code>null</code>.
 *        {@link com.helger.xml.sax.InputSourceFactory} may be used to create
 *        {@link InputSource} objects from different input types.
 * @param aSettings
 *        Reader settings. At least a content handler should be set. May be
 *        <code>null</code>.
 * @return {@link ESuccess#SUCCESS} if reading succeeded,
 *         {@link ESuccess#FAILURE} otherwise
 */
@Nonnull
public static ESuccess readXMLSAX(@WillClose @Nonnull final InputSource aIS, @Nonnull final ISAXReaderSettings aSettings) {
    ValueEnforcer.notNull(aIS, "InputStream");
    ValueEnforcer.notNull(aSettings, "Settings");
    try {
        boolean bFromPool = false;
        org.xml.sax.XMLReader aParser;
        if (aSettings.requiresNewXMLParser()) {
            aParser = SAXReaderFactory.createXMLReader();
        } else {
            // use parser from pool
            aParser = POOL.borrowObject();
            bFromPool = true;
        }
        try {
            final StopWatch aSW = StopWatch.createdStarted();
            // Apply settings
            aSettings.applyToSAXReader(aParser);
            // Start parsing
            aParser.parse(aIS);
            // Statistics
            STATS_SAX_SUCCESS_COUNTER.increment();
            STATS_SAX_TIMER.addTime(aSW.stopAndGetMillis());
            return ESuccess.SUCCESS;
        } finally {
            if (bFromPool) {
                // Return parser to pool
                POOL.returnObject(aParser);
            }
        }
    } catch (final SAXParseException ex) {
        boolean bHandled = false;
        if (aSettings.getErrorHandler() != null)
            try {
                aSettings.getErrorHandler().fatalError(ex);
                bHandled = true;
            } catch (final SAXException ex2) {
            // fall-through
            }
        if (!bHandled)
            aSettings.exceptionCallbacks().forEach(x -> x.onException(ex));
    } catch (final Exception ex) {
        aSettings.exceptionCallbacks().forEach(x -> x.onException(ex));
    } finally {
        // Close both byte stream and character stream, as we don't know which one
        // was used
        StreamHelper.close(aIS.getByteStream());
        StreamHelper.close(aIS.getCharacterStream());
    }
    STATS_SAX_ERROR_COUNTER.increment();
    return ESuccess.FAILURE;
}
Also used : ESuccess(com.helger.commons.state.ESuccess) StreamHelper(com.helger.commons.io.stream.StreamHelper) Nonnegative(javax.annotation.Nonnegative) IMutableObjectPool(com.helger.commons.pool.IMutableObjectPool) URL(java.net.URL) WillClose(javax.annotation.WillClose) ObjectPool(com.helger.commons.pool.ObjectPool) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI) Nonnull(javax.annotation.Nonnull) IMutableStatisticsHandlerTimer(com.helger.commons.statistics.IMutableStatisticsHandlerTimer) InputSource(org.xml.sax.InputSource) IReadableResource(com.helger.commons.io.resource.IReadableResource) InputSourceFactory(com.helger.xml.sax.InputSourceFactory) ThreadSafe(javax.annotation.concurrent.ThreadSafe) Reader(java.io.Reader) File(java.io.File) ValueEnforcer(com.helger.commons.ValueEnforcer) StatisticsManager(com.helger.commons.statistics.StatisticsManager) SAXParseException(org.xml.sax.SAXParseException) StopWatch(com.helger.commons.timing.StopWatch) SAXException(org.xml.sax.SAXException) IHasInputStream(com.helger.commons.io.IHasInputStream) IMutableStatisticsHandlerCounter(com.helger.commons.statistics.IMutableStatisticsHandlerCounter) InputStream(java.io.InputStream) PresentForCodeCoverage(com.helger.commons.annotation.PresentForCodeCoverage) SAXParseException(org.xml.sax.SAXParseException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) StopWatch(com.helger.commons.timing.StopWatch) SAXException(org.xml.sax.SAXException) Nonnull(javax.annotation.Nonnull)

Aggregations

ValueEnforcer (com.helger.commons.ValueEnforcer)4 StreamHelper (com.helger.commons.io.stream.StreamHelper)4 InputStream (java.io.InputStream)4 Nonnull (javax.annotation.Nonnull)4 WillClose (javax.annotation.WillClose)4 Nonempty (com.helger.commons.annotation.Nonempty)2 PresentForCodeCoverage (com.helger.commons.annotation.PresentForCodeCoverage)2 IHasInputStream (com.helger.commons.io.IHasInputStream)2 IReadableResource (com.helger.commons.io.resource.IReadableResource)2 ObjectPool (com.helger.commons.pool.ObjectPool)2 ESuccess (com.helger.commons.state.ESuccess)2 IMutableStatisticsHandlerCounter (com.helger.commons.statistics.IMutableStatisticsHandlerCounter)2 IMutableStatisticsHandlerTimer (com.helger.commons.statistics.IMutableStatisticsHandlerTimer)2 StatisticsManager (com.helger.commons.statistics.StatisticsManager)2 StopWatch (com.helger.commons.timing.StopWatch)2 InputSourceFactory (com.helger.xml.sax.InputSourceFactory)2 File (java.io.File)2 IOException (java.io.IOException)2 OutputStream (java.io.OutputStream)2 Reader (java.io.Reader)2