Possuo uma aplicação Spring/Ibatis que funciona sem problema. requisição é passada ao controller, que invoca um BO, que invoca um DAO que devolve os dados ao BO que trata os mesmos e devolve ao contoller para carregar na view, a grosso modo é isso que acontece.
Eu gostaria de criar um serviço WEB que se comunicasse com essa aplicação para apresentar os dados, o serviço seria um serviço REST.
mas não sei como fazer, imaginei ter uma instância do meu BO no serviço REST e ao receber uma solicitação encaminho para ele uma requisição que fará a comunicação com o DAO e me retornará os dados, é esse o raciocínio correto? Alguém sugere algo? Existe alguma configuração adicional a ser feita? Injeção de dependência ou algo do tipo?
Acho BO uma heresia. Fora isso, seria interessante você encarar seu serviço REST como um controller, ou seja, ele faria a mesma coisa que seu controller, mas com uma perspectiva mais orientada a recursos e REST. Se tiver dúvidas sobre como fazer, eu tenho um bootstrap de REST com Jersey e Spring já pronto no meu github: https://github.com/alesaudate/kickstart-springjerseyhibernate .
/* * To change this template, choose Tools | Templates * and open the template in the editor. */packagecom.kohlerapp.resources;importcom.gorilla.domain.Product;importjava.util.logging.Logger;importjavax.ejb.Stateless;importjavax.inject.Inject;importjavax.ws.rs.GET;importjavax.ws.rs.Path;importcom.app.bo.impl.webServiceBOImpl;importcom.app.bo.WebServiceBO;importjava.util.List;importjavax.ws.rs.Produces;@Path("/ws")publicclassProductFacadeRest{privatefinalLoggerLOGGER=Logger.getLogger(ProductFacadeRest.class.getName());@InjectprivatewebServiceBOImpl_webServiceBO;@GET@Produces({"application/xml","application/json"})publicList<Product>productsList(){returnthis._webServiceBO.listProductsByRecordType("Product");//return "Hello";}}
Minha classe BO
packagecom.app.bo.impl;importcom.gorilla.bo.BusinessServiceUtils;importcom.gorilla.bo.Option;importcom.gorilla.domain.*;importcom.app.bo.WebServiceBO;importcom.lelak.onlinecatalog.dao.ProductDao;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importorg.apache.commons.lang.StringUtils;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.beans.factory.annotation.Required;/** * Business object that provides AbstractProduct management functionalities. */publicclasswebServiceBOImplimplementsWebServiceBO,InitializingBean{protectedLog_log=LogFactory.getLog(webServiceBOImpl.class);privateProductDao_productDao;privateBusinessServiceUtils_businessServiceUtils;privateList<String>_orderedByPositionOptions;privateMap<String,List<String>>_ignoredProductFilters=newHashMap();/** * Finds Products by a general query. * This will look for products with the received query * as a product type, collection, construction type or parentItemNumber. * @param query the query * @param attributesToRetrieve the attributes names to retrieve * @return the resulting List of Products */publicList<Product>listProductsByRecordType(StringrecordType){if(StringUtils.isBlank(recordType)){Stringmessage="Error, the query can not be null or an empty string";_log.error(message);thrownewIllegalArgumentException(message);}returnthis.removeIgnoredProducts(getProductDao().getProductsByRecordType(recordType));}/** * Finds Products, attributes, copy and related by record_type * @param record_type * @return the resulting List of Products, copy, attributes, related products */publicList<Product>listProductsAndRelatedByRecordType(StringrecordType){if(StringUtils.isBlank(recordType)){Stringmessage="Error, the query can not be null or an empty string";_log.error(message);thrownewIllegalArgumentException(message);}returnthis.removeIgnoredProducts(getProductDao().getProductsAndRelatedByRecordType(recordType));}privateList<Option>convertMapToOptionsList(Map<String,String>optionsMap){List<Option>options=newArrayList();Optionoption;for(Map.Entry<String,String>entry:optionsMap.entrySet()){if(StringUtils.isNotBlank(entry.getKey())&&StringUtils.isNotBlank(entry.getValue())){option=newOption();option.setName(entry.getKey());option.setValue(entry.getValue());options.add(option);}}returnoptions;}privateList<ProductAttribute>convertMapToProductAttributeList(Map<String,String>optionsMap){List<ProductAttribute>attributesList=newArrayList();AttributeValuevalue;ProductAttributeattribute;for(Map.Entry<String,String>entry:optionsMap.entrySet()){if(StringUtils.isNotBlank(entry.getKey())&&StringUtils.isNotBlank(entry.getValue())){value=newAttributeValue();value.setValue(entry.getValue());attribute=newProductAttribute();attribute.setName(entry.getKey());attribute.getValues().add(value);attributesList.add(attribute);}}returnattributesList;}/** * Sets the ProductDao. * @param productDao the _productDao to set */@RequiredpublicvoidsetProductDao(ProductDaoproductDao){this._productDao=productDao;}/** * Sets the Gorilla BusinessServiceUtils required for the products details. * @param businessServiceUtils the _businessServiceUtils to set */@RequiredpublicvoidsetBusinessServiceUtils(BusinessServiceUtilsbusinessServiceUtils){this._businessServiceUtils=businessServiceUtils;}/** * Gets the ProductDao. * @return the _productDao */publicProductDaogetProductDao(){return_productDao;}/** * Gets the BusinessServiceUtils. * @return the _businessServiceUtils */publicBusinessServiceUtilsgetBusinessServiceUtils(){return_businessServiceUtils;}/** * Gets the ordered by position options. * @return the _orderedByPositionOptions */publicList<String>getOrderedByPositionOptions(){return_orderedByPositionOptions;}/** * Sets the ordered by position options. * This is used by getSectionFilters to determine which filters will be * retrieved and ordered by the position field. * @param orderedByPositionOptions the _orderedByPositionOptions to set */publicvoidsetOrderedByPositionOptions(List<String>orderedByPositionOptions){this._orderedByPositionOptions=orderedByPositionOptions;}/** * Gets the _ignoredProductFilters. * @return the _ignoredProductFilters */publicMap<String,List<String>>getIgnoredProductFilters(){returnthis._ignoredProductFilters;}/** * Sets the _ignoredProductFilters. * @param ignoredProductFilters the _ignoredProductFilters to set */publicvoidsetIgnoredProductFilters(Map<String,List<String>>ignoredProductFilters){this._ignoredProductFilters=ignoredProductFilters;}/** * Filters products that matches the configuration on _ignoredProductFilters. * @param products the products list * @return a products list without the filtered products */protectedList<Product>removeIgnoredProducts(List<Product>products){List<Product>clearedProducts=newArrayList();booleanmatches;for(Productproduct:products){matches=false;for(ProductAttributeproductAttribute:product.getAttributes()){if(this._ignoredProductFilters.containsKey(productAttribute.getName())){matches=this.checkValuesAgainstIgnoredOnes(productAttribute,this._ignoredProductFilters.get(productAttribute.getName()));break;}}if(!matches){clearedProducts.add(product);}}returnclearedProducts;}/** * Checks if a given productAttribute values matches against a list of regular expressions. * @param productAttribute the ProductAttribute to check * @param regexes the regex list * @return true if match, false otherwise */protectedbooleancheckValuesAgainstIgnoredOnes(ProductAttributeproductAttribute,List<String>regexes){for(AttributeValuevalue:productAttribute.getValues()){for(Stringregex:regexes){if(value.getValue()!=null&&value.getValue().matches(regex)){returntrue;}}}returnfalse;}/** * Replace characters and strings from product attributes * based on the replace Map. * @param product to be escaped * @return a escaped product; */publicProductreplaceString(Productproduct){returnproduct;}}
indica que uma RuntimeException foi lançada em algum ponto. Se você subir a aplicação pela IDE, em modo debug, deve ser possível habilitar o debugger para capturar essa exceção e, assim, você pode checar melhor o que aconteceu.
[]'s
J
jmountain
Certo, mas em tese está certo o caminho que estou tentando percorrer?
Alexandre_Saudate
Não tenho como saber. Não sei em que momento aconteceu o erro, nem como estão as configurações, nem o contêiner em que está rodando. Só o que sei é que o CDI está configurado.