# Desenvolvimento mtls swaggerhub arrecadacao ## Referência ``` https://app.swaggerhub.com/ ``` --- ## Edit Codegen Options ``` client / java apiPackage: br.com.autbank.arrecadacao.api invokerPackage: br.com.autbank.arrecadacao.invoker dateLibrary: Legacy java.util.Date jakarta: Use Java EE fullJavaUtil: true library: HTTP client jersey 1.19.4 java8: Various third party libraries as needed modelPackage: br.com.autbank.arrecadacao.model ``` ![](https://i.imgur.com/uhi5LCk.png) --- ### c:\autbank\portal\tomcat98080\webapps\autbank\ab-arrecadacao-client.properties ``` mtls=S truststoretype=JKS truststore=c:\autbank\portal\tomcat98080\conf\ABTRUSTSTORE.jks keystoretype=pkcs12 keystore=c:\autbank\portal\tomcat98080\conf\key.pfx keystorepassword=changeit ``` --- ## adicionar br.com.autbank.gen.util.SSLContextUtils ``` package br.com.autbank.gen.util; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; public final class SSLContextUtils { /** * * @param keystoreFile arquivo contendo chave privada * @param keystoreFilePassword arquivo cuja chave está protegida com senha * @param keystoreType jks * @param truststoreFile arquivo contendo chave publica * @param truststoreFilePassword pode ser null ou branco * @param truststoreType jks * @return * @throws GeneralSecurityException * @throws IOException */ public static SSLContext sslContext(String keystoreFile, String keystoreFilePassword, String keystoreType, String truststoreFile, String truststoreType) throws GeneralSecurityException, IOException { if (keystoreType==null) { keystoreType = KeyStore.getDefaultType(); } if (truststoreType==null) { truststoreType = KeyStore.getDefaultType(); } if (keystoreFilePassword==null) { keystoreFilePassword = ""; } KeyStore keystore = KeyStore.getInstance(keystoreType); InputStream in=null; try { in = new FileInputStream(keystoreFile); keystore.load(in, keystoreFilePassword.toCharArray()); } finally { if (in!=null) {in.close();} } KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keystore, keystoreFilePassword.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore truststore = KeyStore.getInstance(truststoreType); InputStream in2=null; try { in2 = new FileInputStream(truststoreFile); truststore.load(in2, null); } finally { if (in2!=null) {in2.close();} } trustManagerFactory.init(truststore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new java.security.SecureRandom()); return sslContext; } } ``` --- ## adicionar br.com.autbank.utils.ObjectUtils ``` package br.com.autbank.utils; /* * copiado commons-lang3-3.6.jar */ public class ObjectUtils { /** * <p>Compares two objects for equality, where either one or both * objects may be {@code null}.</p> * * <pre> * ObjectUtils.equals(null, null) = true * ObjectUtils.equals(null, "") = false * ObjectUtils.equals("", null) = false * ObjectUtils.equals("", "") = true * ObjectUtils.equals(Boolean.TRUE, null) = false * ObjectUtils.equals(Boolean.TRUE, "true") = false * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false * </pre> * * @param object1 the first object, may be {@code null} * @param object2 the second object, may be {@code null} * @return {@code true} if the values of both objects are the same * be removed from future releases. */ public static boolean equals(final Object object1, final Object object2) { if (object1 == object2) { return true; } if (object1 == null || object2 == null) { return false; } return object1.equals(object2); } /** * <p>Gets the hash code for multiple objects.</p> * * <p>This allows a hash code to be rapidly calculated for a number of objects. * The hash code for a single object is the <em>not</em> same as {@link #hashCode(Object)}. * The hash code for multiple objects is the same as that calculated by an * {@code ArrayList} containing the specified objects.</p> * * <pre> * ObjectUtils.hashCodeMulti() = 1 * ObjectUtils.hashCodeMulti((Object[]) null) = 1 * ObjectUtils.hashCodeMulti(a) = 31 + a.hashCode() * ObjectUtils.hashCodeMulti(a,b) = (31 + a.hashCode()) * 31 + b.hashCode() * ObjectUtils.hashCodeMulti(a,b,c) = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode() * </pre> * * @param objects the objects to obtain the hash code of, may be {@code null} * @return the hash code of the objects, or zero if null * @since 3.0 * removed in future releases. */ public static int hashCodeMulti(final Object... objects) { int hash = 1; if (objects != null) { for (final Object object : objects) { final int tmpHash = ObjectUtils.hashCode(object); hash = hash * 31 + tmpHash; } } return hash; } /** * <p>Gets the hash code of an object returning zero when the * object is {@code null}.</p> * * <pre> * ObjectUtils.hashCode(null) = 0 * ObjectUtils.hashCode(obj) = obj.hashCode() * </pre> * * @param obj the object to obtain the hash code of, may be {@code null} * @return the hash code of the object, or zero if null * @since 2.1 * removed in future releases */ public static int hashCode(final Object obj) { // hashCode(Object) retained for performance, as hash code is often critical return obj == null ? 0 : obj.hashCode(); } } ``` --- ## substituir br.com.autbank.arrecadacao.invoker.ApiClient ``` /** * Build the Client used to make HTTP requests with the latest settings, * i.e. objectMapper and debugging. * TODO: better to use the Builder Pattern? * @return API client */ public ApiClient rebuildHttpClient() { // Add the JSON serialization support to Jersey JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper); DefaultClientConfig conf = new DefaultClientConfig(); conf.getSingletons().add(jsonProvider); //TODO aqui inicia codigo mtls javax.net.ssl.HostnameVerifier abAllHostsValid = new javax.net.ssl.HostnameVerifier() { public boolean verify(String hostname, javax.net.ssl.SSLSession session) { return true; } }; java.util.Properties params = br.com.autbank.gen.util.ManipulaArquivos.getPropertyCaminhoPadrao("ab-arrecadacao-client.properties");// trocar pelo adequado String mtls = "N"; if ((params.getProperty("mtls")!=null) && (!"".equals(params.getProperty("mtls")))) { mtls = params.getProperty("mtls").trim(); } if ("S".equalsIgnoreCase(mtls) || "SIM".equalsIgnoreCase(mtls) || "Y".equalsIgnoreCase(mtls) || "YES".equalsIgnoreCase(mtls) || "TRUE".equalsIgnoreCase(mtls)) { ClientFactory1 factory = new ClientFactory1(); try { conf.getProperties().put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new com.sun.jersey.client.urlconnection.HTTPSProperties(abAllHostsValid, factory.createSSLContext(params))); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } String host = System.getProperty("https.proxyHost"); if (host!=null || !"".equals(host)) { String _usr = System.getProperty("https.proxyUser"); String _pws = System.getProperty("https.proxyPassword"); java.net.Authenticator.setDefault(new DefaultAuthenticator(_usr, _pws)); } //TODO aqui termina codigo mtls Client client = Client.create(conf); client.addFilter(new GZIPContentEncodingFilter(false)); if (debugging) { client.addFilter(new LoggingFilter()); } this.httpClient = client; return this; } ``` --- ## br.com.autbank.sng.arrecadacao.DefaultAuthenticator ``` package br.com.autbank.sng.arrecadacao; class DefaultAuthenticator extends java.net.Authenticator { private String user; private String password; public DefaultAuthenticator(String user, String pass) { this.user = user; this.password = pass; } protected java.net.PasswordAuthentication getPasswordAuthentication() { return new java.net.PasswordAuthentication(user, password.toCharArray()); } } ``` --- ## br.com.autbank.sng.arrecadacao.ClientFactory1 ``` package br.com.autbank.arrecadacao.invoker; import java.io.IOException; import java.security.GeneralSecurityException; public class ClientFactory1 { private static String getTomcatConfigurationDir() { String autbankHome = getAutbankHome(); if (autbankHome == null) { String fileSeparator = System.getProperty("file.separator"); if (System.getProperty("catalina.home") != null) { return System.getProperty("catalina.home") + fileSeparator + "conf"; } } else { return autbankHome; } return null; } private static String getAutbankHome() { if (System.getProperty("autbank.home") != null) { return System.getProperty("autbank.home"); } else { return null; } } private static String getWeblogicConfigurationDir() { return getAutbankHome(); } private static String getWebsphereConfigurationDir() { return getAutbankHome(); } public static String getConfigurationHome(){ String autbankHome = getAutbankHome(); if (autbankHome==null){ autbankHome = getTomcatConfigurationDir(); } if (autbankHome==null){ autbankHome = getWebsphereConfigurationDir(); } if (autbankHome==null){ autbankHome = getWeblogicConfigurationDir(); } return autbankHome; } public javax.net.ssl.SSLContext createSSLContext(java.util.Properties sslproperties) throws GeneralSecurityException, IOException { String fileSeparator = System.getProperty("file.separator"); String truststoreType = "jks"; if ((sslproperties.getProperty("truststoretype")!=null) && (!"".equals(sslproperties.getProperty("truststoretype")))) { truststoreType = sslproperties.getProperty("truststoretype"); } String keystoreType = "jks"; if ((sslproperties.getProperty("keystoretype")!=null) && (!"".equals(sslproperties.getProperty("keystoretype")))) { keystoreType = sslproperties.getProperty("keystoretype"); } String truststore = getConfigurationHome() + fileSeparator + "ABTRUSTSTORE.jks"; if ((sslproperties.getProperty("truststore")!=null) && (!"".equals(sslproperties.getProperty("truststore")))) { truststore = sslproperties.getProperty("truststore"); } //System.out.println("truststore="+truststore); String keystore = getConfigurationHome() + fileSeparator + "ABKEYSTORE.jks"; if ((sslproperties.getProperty("keystore")!=null) && (!"".equals(sslproperties.getProperty("keystore")))) { keystore = sslproperties.getProperty("keystore"); } //System.out.println("keystore="+keystore); String keystoreFilePassword=""; if (sslproperties.getProperty("keystorepassword")!=null) { keystoreFilePassword = sslproperties.getProperty("keystorepassword"); } javax.net.ssl.SSLContext sc = null; //try { sc = br.com.autbank.gen.util.SSLContextUtils.sslContext(keystore, keystoreFilePassword, keystoreType, truststore, truststoreType); //} catch (GeneralSecurityException e) { // e.printStackTrace(); // throw new RuntimeException(e); //} catch (IOException e) { // e.printStackTrace(); // throw new RuntimeException(e); //} return sc; } } ``` --- ## substituir `@Schema(` por `//@Schema(` --- ## substituir `import io.swagger.v3.oas.annotations.media.Schema` por `//import io.swagger.v3.oas.annotations.media.Schema` --- ## substituir `import java.util.Objects por import br.com.autbank.utils.ObjectUtils` --- ## substituir `Objects.equals(` por `ObjectUtils.equals(` --- ## substituir `Objects.hash(` por `ObjectUtils.hashCodeMulti(` --- ## pom.xml ``` <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>ab-arrecadacao-client</artifactId> <packaging>jar</packaging> <name>ab-arrecadacao-client</name> <version>V01_01_1_02H-SNAPSHOT</version> <parent> <groupId>br.com.autbank</groupId> <artifactId>autbank-settings</artifactId> <version>V1_01_01H</version> </parent> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-enforcer-plugin</artifactId> <version>3.0.0-M1</version> <executions> <execution> <id>enforce-maven</id> <goals> <goal>enforce</goal> </goals> <configuration> <rules> <requireMavenVersion> <version>2.2.0</version> </requireMavenVersion> </rules> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12</version> <configuration> <systemProperties> <property> <name>loggerPath</name> <value>conf/log4j.properties</value> </property> </systemProperties> <argLine>-Xms512m -Xmx1500m</argLine> <parallel>methods</parallel> <forkMode>pertest</forkMode> </configuration> </plugin> <plugin> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin> <!-- attach test jar --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.2</version> <executions> <execution> <goals> <goal>jar</goal> <goal>test-jar</goal> </goals> </execution> </executions> <configuration> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.10.4</version> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>sign-artifacts</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <version>1.5</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> <dependencies> <!-- <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>${swagger-annotations-version}</version> </dependency> --> <!-- HTTP client: jersey-client --> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>${jersey-version}</version> </dependency> <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-multipart</artifactId> <version>${jersey-version}</version> </dependency> <!-- JSON processing: jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson-version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson-version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson-version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>${jackson-version}</version> </dependency> <!-- Base64 encoding that works in both JVM and Android --> <dependency> <groupId>com.brsanthu</groupId> <artifactId>migbase64</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>br.com.autbank</groupId> <artifactId>ab-generico</artifactId> <version>V7_01_07H</version> </dependency> <!-- <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency> --> </dependencies> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <swagger-annotations-version>1.5.15</swagger-annotations-version> <jersey-version>1.19.4</jersey-version> <jackson-version>2.6.4</jackson-version> <maven-plugin-version>1.0.0</maven-plugin-version> </properties> </project> ``` --- ## Main ``` package br; import java.math.BigDecimal; import br.com.autbank.arrecadacao.api.*; import br.com.autbank.arrecadacao.model.InlineResponse200; public class Main { public static void main(String[] args) throws Exception { String urlOauthBasePath = "https://oauth.sandbox.bb.com.br";//"https://oauth.bb.com.br" String username=""; String password=""; String grantType="client_credentials"; String escopo = "cobrancas.boletos-info cobrancas.boletos-requisicao"; // criar objeto apiClient br.com.autbank.arrecadacao.invoker.ApiClient apiClient = br.com.autbank.arrecadacao.invoker.Configuration.getDefaultApiClient(); // configurar BasePath Oauth apiClient.setBasePath(urlOauthBasePath); // criando Api Servico Oauth br.com.autbank.arrecadacao.api.TokenApiAutbank tokenApi = new br.com.autbank.arrecadacao.api.TokenApiAutbank(apiClient); // parametros de seguranca String accessToken = tokenApi.v5TokenPost(username, password, grantType, escopo); String urlBasePath = "https://api.hm.bb.com.br/servicos-arrecadacao/v1"; String authorization = "Bearer " + accessToken; String gwDevAppKey = ""; String dataPagamento = ""; BigDecimal valorPagamento = new BigDecimal("1.00"); Integer codigoClienteSolicitacao = new Integer(0); String codigoBarrasDigitado = ""; String codigoBarrasCapturado = ""; // configurar BasePath Servico apiClient.setBasePath(urlBasePath); // passar AccessToken apiClient.setAccessToken(accessToken); // criando Api Servico ConsultasApi api = new ConsultasApi(apiClient); // parametros do servico InlineResponse200 resp = api.getArrecadacoesCodigoBarras(authorization, gwDevAppKey, dataPagamento, valorPagamento, codigoClienteSolicitacao, codigoBarrasDigitado, codigoBarrasCapturado); System.out.println(resp.toString()); } } ``` ---