Ошибка теста Camel Route: IllegalArgumentException: формат данных «jaxb» не может быть создан

Я тестирую верблюжий маршрут, который демаршалирует полезную нагрузку xml (в строке) в сгенерированный jaxb bean-компонент, а затем дополнительно устанавливает bean-компонент в свойстве, которое используется в процессоре. Все это отлично работает в реальном потоке, но когда я пытаюсь запустить junit для проверки моего маршрута, я получаю сообщение об ошибке:

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 6.536 sec <<< FAILURE! - in com.equifax.icc.esb.tradinghistory.routes.report.PreDataRetrievalServiceTest
preDataRetrievalOrchestrationSuccessTest(com.equifax.icc.esb.tradinghistory.routes.report.PreDataRetrievalServiceTest)  Time elapsed: 4.575 sec  <<< ERROR!
org.apache.camel.FailedToCreateRouteException: Failed to create route report-info-preparation-service-route at: >>> Unmarshal[ref:bthRequestModel] <<< in route: Route(report-info-preparation-service-route)[[From[direct:re... because of Data format 'jaxb' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
Caused by: java.lang.IllegalArgumentException: Data format 'jaxb' could not be created. Ensure that the data format is valid and the associated Camel component is present on the class path: 

Я переопределил getBlueprintDescriptor() и включил все файлы контекста чертежа (включая тот, в котором есть объявление bean-компонента для JAXB DataFormat). Ниже приведен метод getBlueprintDescriptor() и объявление bean-компонента:

@Override
    protected String getBlueprintDescriptor() {
        return "/OSGI-INF/blueprint/test-beans-context.xml,"
                 +"/OSGI-INF/blueprint/test-env-context.xml," 
                + "/OSGI-INF/blueprint/test-camel-context.xml";
}

<bean class="org.apache.camel.model.dataformat.JaxbDataFormat" id="bthRequestModel">
            <property name="prettyPrint" value="false" />
            <property name="fragment" value="true" />
            <property name="ignoreJAXBElement" value="true" />
            <property name="contextPath" value="com.vedaxml.vxml2.veda_bth_request_v1" />
        </bean>

Я также попытался переопределить createRegistry():

@Override 
    protected JndiRegistry createRegistry() throws Exception { 
        JndiRegistry registry = super.createRegistry(); 
        JaxbDataFormat jdf = new org.apache.camel.model.dataformat.JaxbDataFormat(false);
        jdf.setFragment(true);
        jdf.setIgnoreJAXBElement(true);
        jdf.setContextPath("com.vedaxml.vxml2.veda_bth_request_v1");

        DataFormat jaxb = (DataFormat) jdf;

        registry.bind( "bthRequestModel", jdf); 
        //registry.bind( "jaxb", new org.apache.camel.model.dataformat.JaxbDataFormat() ); 

        return registry; 
    } 

Это дает мне ошибку ниже:

2017-10-27 22:38:56,613 INFO  org.apache.camel.test.junit4.CamelTestSupport  ********************************************************************************
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 5.792 sec <<< FAILURE! - in com.equifax.icc.esb.tradinghistory.routes.report.PreDataRetrievalServiceTest
preDataRetrievalOrchestrationSuccessTest(com.equifax.icc.esb.tradinghistory.routes.report.PreDataRetrievalServiceTest)  Time elapsed: 4.316 sec  <<< ERROR!
org.apache.camel.FailedToCreateRouteException: Failed to create route report-info-preparation-service-route at: >>> Unmarshal[ref:bthRequestModel] <<< in route: Route(report-info-preparation-service-route)[[From[direct:re... because of Cannot find data format in registry with ref: bthRequestModel
Caused by: java.lang.IllegalArgumentException: Cannot find data format in registry with ref: bthRequestModel

Кажется, что dataFormat имеет значение null согласно https://issues.apache.org/jira/browse/CAMEL-3508

Я просматривал код DataFormatDefinition.java (приведенный ниже). Во время отладки я заметил, что jaxbcontext в Routecontext.getcamelContext() имеет значение null.

   public static DataFormat getDataFormat(RouteContext routeContext, DataFormatDefinition type, String ref) {
        if (type == null) {
            ObjectHelper.notNull(ref, "ref or type");

            // try to let resolver see if it can resolve it, its not always possible
            type = routeContext.getCamelContext().resolveDataFormatDefinition(ref);

            if (type != null) {
                return type.getDataFormat(routeContext);
            }

            DataFormat dataFormat = routeContext.getCamelContext().resolveDataFormat(ref);
            if (dataFormat == null) {
                throw new IllegalArgumentException("Cannot find data format in registry with ref: " + ref);
            }

            return dataFormat;
        } else {
            return type.getDataFormat(routeContext);
        }
    }

public DataFormat getDataFormat(RouteContext routeContext) {
        if (dataFormat == null) {
            Runnable propertyPlaceholdersChangeReverter = ProcessorDefinitionHelper.createPropertyPlaceholdersChangeReverter();

            // resolve properties before we create the data format
            try {
                ProcessorDefinitionHelper.resolvePropertyPlaceholders(routeContext.getCamelContext(), this);
            } catch (Exception e) {
                throw new IllegalArgumentException("Error resolving property placeholders on data format: " + this, e);
            }
            try {
                dataFormat = createDataFormat(routeContext);
                if (dataFormat != null) {
                    // is enabled by default so assume true if null
                    final boolean contentTypeHeader = this.contentTypeHeader == null || this.contentTypeHeader;
                    try {
                        setProperty(routeContext.getCamelContext(), dataFormat, "contentTypeHeader", contentTypeHeader);
                    } catch (Exception e) {
                        // ignore as this option is optional and not all data formats support this
                    }
                    // configure the rest of the options
                    configureDataFormat(dataFormat, routeContext.getCamelContext());
                } else {
                    throw new IllegalArgumentException(
                            "Data format '" + (dataFormatName != null ? dataFormatName : "<null>") + "' could not be created. "
                                    + "Ensure that the data format is valid and the associated Camel component is present on the classpath");
                }
            } finally {
                propertyPlaceholdersChangeReverter.run();
            }
        }
        return dataFormat;
    }

Я попробовал конструктор, внедряющий объект JaxbDataFormat для создания экземпляра класса DataFormatDefinition (чтобы DataFormat не был нулевым), но все равно получаю ту же ошибку, что DataFormat не найден в реестре.

Может ли кто-нибудь помочь мне исправить это? Заранее спасибо.


person suvojit    schedule 27.10.2017    source источник


Ответы (1)


Это не класс модели, который вы должны создать и связать в JNDI, а настоящий класс DataFormat из camel-jaxb. У них одинаковое имя класса, но другое имя пакета.

person Claus Ibsen    schedule 27.10.2017
comment
Спасибо за ваш ответ. Простите меня, но я не слежу за вами. Я создаю и привязываю класс JaxbDataFormat. Просто эталонное имя звучит как модель (соглашение об именах - это проект). Не могли бы вы уточнить, что вы предлагаете? Спасибо. - person suvojit; 28.10.2017