1

При отправке сообщения с xml контетном в наследуемом от AbstractPhaseInterceptor классе возникает ошибка SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.

-В день отправляется большое количество файлов и лишь для одного, двух файлов возникает подобная ошибка, притом не каждый день.

Класс интерсептора для изменения сообщения представлен ниже( притом до интерсептора сообщение с xml контетном было сформировано без ошибок ):

/**
 * Абстрактный перехватчик SOAP-сообщения для изменения содержимого перед самой отправкой. (Фаза - PRE_STREAM)
 */
public abstract class MessageModifierInterceptor extends AbstractPhaseInterceptor<Message> {

    public MessageModifierInterceptor() {
        super(Phase.PRE_STREAM);
    }

    protected abstract String changeOutboundMessage(String currentEnvelope);

    protected abstract String changeInboundMessage(String currentEnvelope);

    public void handleMessage(Message message) {
        boolean isOutbound;
        isOutbound = message == message.getExchange().getOutMessage()
                || message == message.getExchange().getOutFaultMessage();

        if (isOutbound) {
            OutputStream os = message.getContent(OutputStream.class);

            CachedStream cs = new CachedStream();
            message.setContent(OutputStream.class, cs);

            message.getInterceptorChain().doIntercept(message);

            try {
                cs.flush();
                IOUtils.closeQuietly(cs);
                CachedOutputStream csnew = (CachedOutputStream) message.getContent(OutputStream.class);

                String currentEnvelopeMessage = IOUtils.toString(csnew.getInputStream(), (String) message.get(Message.ENCODING));
                csnew.flush();
                IOUtils.closeQuietly(csnew);

                String res = changeOutboundMessage(currentEnvelopeMessage);
                res = res != null ? res : currentEnvelopeMessage;

                InputStream replaceInStream = IOUtils.toInputStream(res, (String) message.get(Message.ENCODING));

                IOUtils.copy(replaceInStream, os);
                //replaceInStream.close();
                IOUtils.closeQuietly(replaceInStream);

                os.flush();
                message.setContent(OutputStream.class, os);
                IOUtils.closeQuietly(os);

            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        } else {
            try {
                InputStream is = message.getContent(InputStream.class);
                String currentEnvelopeMessage = IOUtils.toString(is, (String) message.get(Message.ENCODING));
                IOUtils.closeQuietly(is);

                String res = changeInboundMessage(currentEnvelopeMessage);
                res = res != null ? res : currentEnvelopeMessage;

                is = IOUtils.toInputStream(res, (String) message.get(Message.ENCODING));
                message.setContent(InputStream.class, is);
                IOUtils.closeQuietly(is);
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }
    }

    public void handleFault(Message message) {
    }

    private class CachedStream extends CachedOutputStream {
        public CachedStream() {
            super();
        }

        protected void doFlush() throws IOException {
            currentStream.flush();
        }

        protected void doClose() throws IOException {
        }

        protected void onWrite() throws IOException {
        }
    }
}

Есть класс, который наследуется от MessageModifierInterceptor и определяет метод changeOutboundMessage, в котором и возникает ошибка. Код метода представлен ниже:

@Override
    protected String changeOutboundMessage(String currentEnvelope) {
        String result;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(currentEnvelope));
            Document doc = db.parse(is);
            Smev3SignatureProvider signatureProvider = new Smev3SignatureProvider();
            signatureProvider.sign(doc);

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            result = writer.getBuffer().toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
        return result;
    }

Собственно ошибка выходит в методе changeOutboundMessage на строке:

Document doc = db.parse(is);

Почему может возникать данная ошибка, если для большинства сообщений всё отрабатывает отлично и лишь иногда возникает ошибка SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file. Ошибка возникает всё же редко, но с периодичностью около 5 раз в месяц.

PS: После добавления логирования в MessageModifierInterceptor метод стал выглядеть так:

@Override
protected String changeOutboundMessage(String currentEnvelope) {
    String result;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(currentEnvelope));
        Document doc = db.parse(is);
        Smev3SignatureProvider signatureProvider = new Smev3SignatureProvider();
        signatureProvider.sign(doc);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        result = writer.getBuffer().toString();
    } catch (SAXParseException spe) {
        logger.debug("Ошибка SAXParseException: строка " + spe.getLineNumber() +
                ", колонка " + spe.getColumnNumber() + " файл = " + currentEnvelope);
        throw new RuntimeException(spe.getMessage(), spe);
    } catch (Exception ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
    return result;
}

Логирование вернуло строку: DEBUG r.f.g.i.s.s.Smev3SigningInterceptor - Ошибка SAXParseException: строка 1, колонка 1 файл =

Таким образом почему-то отправляется пустая строка

4
  • Текст ошибки указывает на то что на вход парсеру прилетает пустая строка. Добавляйте логирование и смотрите, какие конкретно сообщения вызывают такую ошибку. По вашему коду невозможно определить, как получается, что туда приходит пустая строка.
    – fori1ton
    27 фев 2018 в 7:21
  • поставьте catch на SAXParseException и сохраняйте там документы вызывающие ошибки и в каких строках они возникают... без документов тут вряд ли кто что сказать может 27 фев 2018 в 8:38
  • Спасибо за подсказки, буду добавлять логирование. 27 фев 2018 в 9:41
  • Добавил логирование, непонятно почему пустая строка приходит) 23 мар 2018 в 10:24

1 ответ 1

2

В коде MessageModifierInterceptor были строчки

        OutputStream os = message.getContent(OutputStream.class);
        CachedStream cs = new CachedStream();
        message.setContent(OutputStream.class, cs);
        message.getInterceptorChain().doIntercept(message);

,где CachedStream, если сообщение больше 64кб записывал данные сообщения в файл. При этом последний интерсептор в строке message.getInterceptorChain().doIntercept(message) закрывал CachedStream, что вызывало удаление temp файла с данными, при этом данных в стриме уже не будет. Поэтому возникала ошибка SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file. (стрим удалял все данные)

Решение: подставим новый стрим, который не будет удалять данные по закрытию стрима в строке message.getInterceptorChain().doIntercept(message) -

            /* Здесь сохранятся данные xml, даже если temp файл будет удалён в процессе работы (>64 кб данных) */
            LoadingByteArrayOutputStream cs = new LoadingByteArrayOutputStream();
            /* Создадим новый стрим, через который пройдёт сообщение */
            final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(cs);

Таким образом весь код обновлённого перехватчика сообщения будет такой:

/**
* Абстрактный перехватчик SOAP-сообщения для изменения содержимого перед самой отправкой. (Фаза - PRE_STREAM)
*/
public abstract class MessageModifierInterceptor extends AbstractPhaseInterceptor<Message> {

public MessageModifierInterceptor() {
    super(Phase.PRE_STREAM);
}

protected abstract String changeOutboundMessageText(String currentEnvelope);

public void handleMessage(Message message) {
    boolean isOutbound;
    isOutbound = message == message.getExchange().getOutMessage()
            || message == message.getExchange().getOutFaultMessage();

    if (isOutbound) {
        try {
            /* В оригинальный стрим запишем изменённые данные */
            OutputStream origStream = message.getContent(OutputStream.class);
            /* Здесь сохранятся данные xml, даже если temp файл будет удалён в процессе работы (>64 кб данных) */
            LoadingByteArrayOutputStream cs = new LoadingByteArrayOutputStream();
            /* Создадим новый стрим, через который пройдёт сообщение */
            final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(cs);
            message.setContent(OutputStream.class, newOut);
            /* Запишем сообщение в newOut.cs */
            message.getInterceptorChain().doIntercept(message);

            newOut.flush();
            IOUtils.closeQuietly(newOut);

            /* Получим текущее сообщение */
            CacheAndWriteOutputStream csOutNew = (CacheAndWriteOutputStream) message.getContent(OutputStream.class);
            LoadingByteArrayOutputStream csNew = (LoadingByteArrayOutputStream) csOutNew.getFlowThroughStream();
            InputStream in = csNew.createInputStream();
            String currentEnvelopeMessage = IOUtils.toString(in, (String) message.get(Message.ENCODING));

            csOutNew.flush();
            IOUtils.closeQuietly(csOutNew);

            /* Изменяем исходное сообщение */
            String res = changeOutboundMessageText(currentEnvelopeMessage);
            res = res != null ? res : currentEnvelopeMessage;

            /* Положим изменённое сообщение обратно */
            InputStream replaceInStream = IOUtils.toInputStream(res, (String) message.get(Message.ENCODING));
            IOUtils.copy(replaceInStream, origStream);
            IOUtils.closeQuietly(replaceInStream);
            origStream.flush();
            message.setContent(OutputStream.class, origStream);
            IOUtils.closeQuietly(origStream);
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage());
        }
    }
}
}

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.