Sei sulla pagina 1di 8

Projeto Cliente de serviço SOAP com Spring Boot e JPA/Hibernate

Objetivos:

 Criar projeto Spring Boot Java;


 Implementar modelo de domínio;
 Estruturar camadas lógicas: resource, service e repository;
 Configurar banco de dados de teste (H2);
 Configurar banco de dados PostgreSQL;
 Tratamento de exceções.

Github: https://github.com/grizzlyPi/UnidasSoapWsClient

Conceitos importantes:

XML Web services

Um endpoint de um web service é a URL onde seu serviço pode ser acessado por uma
aplicação cliente.

Assim ao desenvolver web services devemos considerar o uso de tecnologias que:

 Comunica-se via protocolos internet (normalmente HTTP);


 Envia e recebe dados formatados como documentos XML;
 Forneça uma descrição de serviço que, no mínimo, consista de um documento WSDL;
 Seja capaz de transportar documentos XML utilizando SOAP sobre HTTP.
Estudo de caso PORTAL UNIDAS:

WSDL Portal Unidas Saúde:

[1] schemaLocation: url para o xsd.

[2] Operations: representam uma função web service e podem referenciar múltiplas messages.

[3] Dentro de um documento WSDL, o elemento service representa um ou mais endpoints nos
quais o web service pode ser acessado.

[4] O protocolo de transporte é o HTTP e o serviço espera como entrada documentos XML e
retornará como resposta documentos XML.
Created Project
Versão e Release do framework:

Spring Tool Suite 4


Version: 4.6.0. RELEASE
Build Id: 202003181317

Checklist:

 File > New > Spring Starter Project


o Maven
o Java 11
o Packing JAR
o Dependencies: Spring Web Starter

$ git init
$ git remote add origin https://github.com/grizzlyPi/UnidasSoapWsClient.git
$ git pull origin master
$ git add .
$ git commit -m “Created project”
$ git push -u origin master

Configuring JAXB dependency for Java SE 11


Checklist:

 Criar as pastas “wsdl” e “xsd” no caminho src/main/resources;


 Criar os arquivos em branco “proposta.wsdl” e “proposta.xsd”;
 Copiar e colar o conteúdo do endereço abaixo no arquivo wsdl:
http://treinamento.portalunidassaude.com.br/ws/Proposta?wsdl
 Copiar e colocar o conteúdo do endereço abaixo no arquivo xsd:
http://treinamento.portalunidassaude.com.br:80/ws/Proposta?xsd=1
 Alterar o endereço de importação definido na tag <xsd:import “schemaLocation”> com o local do arquivo
“proposta.xsd”.
 Copiar e colar as dependências abaixo no arquivo pom.xml.

<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->


<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/com.sun.activation/javax.activation -->


<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime -->


<!-- unmarshal XML to Java objects or marshal Java objects as XML: -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/saaj/saaj -->


<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
</dependency>
Generating JAXB classes with Maven plugin
Checklist:

 Copiar e colar o plugin abaixo no arquivo pom.xml.

<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.14.0</version>
<configuration>
<schemaLanguage>WSDL</schemaLanguage>
<generatePackage>com.lucasdelima.client.xsdtojava</generatePackage>
<schemas>
<schema>
<url> file:///C:/Users/Sr.%20e%20Sra.%20Lima/JAVA/ws-sts-
norti/UnidasSoapWsClient/src/main/resources/wsdl/proposta.wsdl
</url>
</schema>
</schemas>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>

 Run as > Maven Clean > Maven Install


Configuring a WSTemplate to Use Basic Authentication
WebServiceTemplate

The WebServiceTemplate is the core class for client-side Web service access in Spring-WS. It contains methods for
sending Source objects, and receiving response messages as either Source or Result. Additionally, it can marshal objects to XML
before sending them across a transport, and unmarshal any response XML into an object again.

URIs and Transports

The WebServiceTemplate class uses an URI as the message destination. You can either set a defaultUri property on the template
itself, or supply an URI explicitly when calling a method on the template. The URI will be resolved into
a WebServiceMessageSender, which is responsible for sending the XML message across a transport layer. You can set one or more
message senders using the messageSender or messageSenders properties of the WebServiceTemplate class.

There are two implementations of the WebServiceMessageSender interface for sending messages via HTTP. The default
implementation is the HttpUrlConnectionMessageSender, which uses the facilities provided by Java itself. The alternative is
the HttpComponentsMessageSender, which uses the Apache HttpComponents HttpClient. Use the latter if you need more
advanced and easy-to-use functionality (such as authentication, HTTP connection pooling, and so forth).

Checklist:

 Criar o pacote “com.lucasdelima.client.config”;


 Criar a classe “ClientConfig.java”;
 Copiar e colar as dependências abaixo no arquivo pom.xml;

<!-- https://mvnrepository.com/artifact/org.springframework.ws/spring-ws-core -->


<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->


<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>

 Criar o @Bean marshaller ;


 Criar o @Bean webServiceTemplate;
 Criar o @Bean httpComponentsMessageSender;
 Criar o @Bean usernamePasswordCredentials.

@Value annotation to inject values into configuration variables


 Copiar e colar os valores abaixo para o arquivo application.properties;

defaul-uri: http://treinamento.portalunidassaude.com.br:80/ws/Proposta
client-user-name: bcb
client-user-password: iuRie9ji

 Declarar as variáveis de configuração de acesso com a anotação @Value na classe “ClientConfig.java”.


Create a Unidas Service Client
The client contains one method getLoteResponse that does the actual SOAP exchange. In this method, both the EnviarLote
and the EnviarLoteResponse classes are derived from the WSDL and were generated in the JAXB generation process
(described in Generating JAXB classes with Maven plugin). It creates the EnviarLote request object and sets it up with
the loteProposta parameter. It uses the WebServiceTemplate supplied by the WebServiceGatewaySupport base class to
do the actual SOAP exchange. It passes the EnviarLote request object (as well as a SoapActionCallback to pass on
a SOAPAction header with the request) as the WSDL described that it needed this header in the  <soap:operation/> elements.
It casts the response into a EnviarLoteResponse object, which is then returned.

Checklist:

 Criar o pacote “com.lucasdelima.client.message”;


 Criar a classe “SoapMessage.java”.

Test with CommandLineRunner


Checklist:

 Criar o @Bean CommandLineRunner na classe principal;


 Anotar a classe “EnviarLote” com @XmlRootElement(name = "enviarLote");
 Adicionar o método JAXBIntrospector.getValue();
Cotacao entity and repository (* o nome da classe foi alterado)
Checklist:

1. Copiar e colar as dependências abaixo no arquivo pom.xml.

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->


<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

2. Basic entity checklist:


 Basic attributes;
 Associations (instantiate collections);
 Constructors;
 Getters & Setters (collections: only get);
 hashCode & equals;
 Serializable.

3. CotacaoRepository extends JPARepository<Cotacao, Long>;

H2 database and test profile


Checklist:

 application.properties
 application-test.properties

JPA repository, dependency injection, database seeding and Service layer


Checklist:

 Configuration class for "test" profile;


 @Autowired OpmeCotacaoRepository;
 Instantiate objects in memory;
 Persist objects.
Dev profile
Checklist:

 PgAdmin: create local database: create database springboot_course


 Add PostgreSQL Maven dependency

<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->


<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>

 Create file: application-dev.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/postgress
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

 Update application.properties: spring.profiles.active=dev

Build an executable JAR

Potrebbero piacerti anche