diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..391dcca --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: Java client CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + java: ["17", "21", "25"] + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: ${{ matrix.java }} + cache: gradle + - name: Check formatting, lint, build and test + run: ./gradlew --no-daemon clean build -PjavaVersion=${{ matrix.java }} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..db442c3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,25 @@ +# Changelog + +## 0.1.0 — Sin publicar + +- Compatibilidad verificada con Java 17, 21 y 25; JDK 25 para compilar por defecto + y bytecode Java 17 para consumidores. +- Gradle 9.8.1 con wrapper regenerado y SHA-256 de distribución verificado. +- Spotless 8.10.4 con Palantir Java Format 2.102.0 para todas las fuentes y tests; + formato de los scripts Gradle con Groovy Eclipse. +- PMD 7.28.0 para analizar producción y tests, más advertencias de `javac` + tratadas como errores. `check`, `build` y CI incluyen las comprobaciones de calidad. +- Retrofit 3.0.0, OkHttp/logging-interceptor 5.5.0 mediante BOM y JUnit 6.1.3. + Se elimina `okhttp-urlconnection`, que no se utiliza. +- Fastjson2 2.0.65 y su conversor oficial de Retrofit reemplazan a Gson y + `converter-gson`. Se conservan los métodos públicos y los modelos. Los errores + de conversión JSON se propagan como `IOException` con la causa original. +- Cambio incompatible: `Contribuyente.getRuc()` devuelve `String` con el DV y + `setRuc()` recibe `String`. El documento numérico se obtiene con `getDoc()`. + El constructor completo recibe `doc`, `razonSocial`, `dv`, `ruc`, `estado`, + `esPersonaJuridica` y `esEntidadPublica`; el constructor vacío continúa disponible. +- `equals()` y `hashCode()` consideran los siete campos de la respuesta. +- Retrofit se expone como dependencia de API para que los consumidores puedan + compilar contra los tipos públicos del cliente. +- Pruebas HTTP locales de consulta, búsqueda, campos adicionales/nulos, errores + HTTP y JSON inválido; matriz CI Java 17/21/25. diff --git a/README.md b/README.md index 89afded..fd79108 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,140 @@ -# Tu Ruc Client -#### Cliente para el API Tu Ruc +# Tu RUC Java Client + +Cliente Java para consultar y buscar contribuyentes en la API de Tu RUC. + +## Requisitos y compilación + +La biblioteca funciona en Java 17, 21 y 25. La compilación usa JDK 25 por defecto +y genera bytecode Java 17; los consumidores no necesitan JDK 25. + +```bash +./gradlew clean build +``` + +Para compilar y ejecutar los tests con otro JDK instalado: + +```bash +./gradlew clean build -PjavaVersion=17 +./gradlew clean build -PjavaVersion=21 +``` + +El wrapper incluye Gradle 9.8.1 y verifica el SHA-256 de su distribución. Los +tests usan un servidor HTTP local con puerto efímero y no necesitan la API en +producción ni un servicio en `localhost:8080`. CI verifica Java 17, 21 y 25. + +## Formato y análisis estático + +[Spotless 8.10.4](https://plugins.gradle.org/plugin/com.diffplug.spotless/8.10.4) +aplica [Palantir Java Format 2.102.0](https://github.com/palantir/palantir-java-format) +a todas las fuentes Java, incluidos los tests, y formatea los archivos Gradle con +Groovy Eclipse. [PMD 7.28.0](https://pmd.github.io/2026/09/25/PMD-7.28.0/) +analiza producción y tests con las reglas de [config/pmd/ruleset.xml](config/pmd/ruleset.xml): +errores de igualdad, excepciones, recursos, código sin uso y operaciones redundantes. +El compilador también activa `-Xlint:all` y trata las advertencias como errores. + +```bash +./gradlew spotlessApply # Aplicar el formato +./gradlew spotlessCheck # Comprobar el formato +./gradlew pmdMain pmdTest # Analizar producción y tests +./gradlew check # Formato, análisis y tests +``` + +`build` incluye todas estas comprobaciones. Funcionan con los tres JDK admitidos; +se puede añadir `-PjavaVersion=17` o `-PjavaVersion=21` a los comandos anteriores. +CI ejecuta las mismas comprobaciones y falla si detecta un problema. Las herramientas +de calidad son dependencias del build y no se publican como dependencias del cliente. + +## Uso desde otro proyecto Gradle + +La versión de trabajo es `0.1.0`. Para consumir el checkout local, agrega a +`settings.gradle` del proyecto consumidor: + +```groovy +includeBuild("../tu-ruc-java-client") +``` + +Y a su `build.gradle`: + +```groovy +repositories { + mavenCentral() +} + +dependencies { + implementation("org.ith:tu-ruc-client:0.1.0") +} +``` + +Gradle resuelve la biblioteca local y sus dependencias. El JAR generado en +`build/libs/` no incluye las dependencias dentro del archivo. +Este ejemplo con `includeBuild` compila el checkout y requiere JDK 25 instalado +con la configuración por defecto. Consumir el JAR ya compilado requiere Java 17 +o superior. + +```java +import org.ith.client.TuRuc; +import org.ith.client.TuRucClient; + +TuRucClient client = new TuRuc("https://turuc.com.py/").getClient(); +var response = client.getContribuyente("80024191-6").execute(); + +if (response.isSuccessful()) { + var contribuyente = response.body().getData(); + System.out.println(contribuyente.getRuc()); // "80024191-6" + System.out.println(contribuyente.getDoc()); // 80024191 +} else { + System.err.println(response.code() + ": " + response.errorBody().string()); +} + +var page = client.searchContribuyentes("NUÑEZ", 0).execute(); +``` + +`execute()` puede lanzar `IOException` ante un fallo de transporte o un error +al convertir el JSON de la respuesta. Los errores HTTP se consultan mediante +`Response.isSuccessful()`, `code()` y `errorBody()`. +Las páginas comienzan en cero y la URL base debe terminar en `/`. + +## Migración desde 0.0.1-beta + +`0.1.0` cambia la API pública de `Contribuyente` para reflejar la respuesta actual +del servidor. Es necesario recompilar y adaptar a los consumidores: + +| Antes | Ahora | +| --- | --- | +| `Integer getRuc()` | `String getRuc()` devuelve el RUC completo con DV | +| `setRuc(Integer)` | `setRuc(String)` recibe el RUC completo | +| Número de documento en `ruc` | `Integer getDoc()` y `setDoc(Integer)` | +| Constructor de tres argumentos | Constructor con los siete campos de la respuesta | + +```java +var contribuyente = new org.ith.model.Contribuyente( + 80024191, "MINISTERIO DE PRUEBA", 6, "80024191-6", "ACTIVO", false, true); +``` + +También se exponen `estado`, `esPersonaJuridica` y `esEntidadPublica` mediante +getters y setters. `equals()` y `hashCode()` incluyen todos los campos del modelo. +`estado` puede ser `null`, tal como permite la API. El modelo usa `doc` y `ruc` +recibidos del servidor; no reconstruye uno a partir del otro. + +La conversión JSON utiliza Fastjson2 en lugar de Gson. Los métodos públicos +siguen devolviendo `retrofit2.Call` con los mismos modelos. El conversor oficial +de Fastjson2 propaga los errores de conversión como `IOException`, con la causa +original; si capturabas excepciones específicas de Gson, adapta esas capturas. + +## Dependencias + +Retrofit usa 3.0.0; OkHttp y su interceptor de logs se alinean con el BOM 5.5.0. +La conversión JSON usa el módulo oficial `fastjson2-extension` 2.0.65, que incluye +el conversor para Retrofit y depende de `fastjson2` de la misma versión. Gson y +`converter-gson` dejan de formar parte de las dependencias de ejecución. +Los tests usan JUnit 6.1.3. Retrofit se declara como dependencia de API porque +los métodos públicos devuelven `retrofit2.Call`. +El BOM de OkHttp también se expone para alinear sus tipos transitivos entre la +compilación del consumidor y la ejecución. + +El cliente procesa las respuestas JSON de texto de TuRuc mediante el conversor +[oficial de Fastjson2](https://github.com/alibaba/fastjson2/blob/2.0.65/extension/src/main/java/com/alibaba/fastjson2/support/retrofit/Retrofit2ConverterFactory.java). +La migración verifica compatibilidad funcional; no implica una mejora medida +del tiempo total de las consultas. + +Consulta [CHANGELOG.md](CHANGELOG.md) para los cambios de esta versión. diff --git a/build.gradle b/build.gradle index c8f627b..f0e682b 100644 --- a/build.gradle +++ b/build.gradle @@ -1,28 +1,62 @@ plugins { - id("java") + id("java-library") + id("pmd") + id("com.diffplug.spotless") version "8.10.4" } group = "org.ith" -version = "0.0.1-beta" +version = "0.1.0" + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(providers.gradleProperty("javaVersion").orElse("25").get()) + } +} + +tasks.withType(JavaCompile).configureEach { + options.release = 17 + options.encoding = "UTF-8" + options.compilerArgs.addAll(["-Xlint:all", "-Werror"]) +} repositories { mavenCentral() } dependencies { - //Retrofit - implementation("com.squareup.retrofit2:retrofit:2.9.0") - //Gson - implementation("com.squareup.retrofit2:converter-gson:2.9.0") - //OkHttp - implementation("com.squareup.okhttp3:okhttp:4.9.3") - implementation("com.squareup.okhttp3:okhttp-urlconnection:4.9.1") - implementation("com.squareup.okhttp3:logging-interceptor:4.9.0") - //Testing - testImplementation(platform("org.junit:junit-bom:5.9.1")) + api("com.squareup.retrofit2:retrofit:3.0.0") + implementation("com.alibaba.fastjson2:fastjson2-extension:2.0.65") + + api(platform("com.squareup.okhttp3:okhttp-bom:5.5.0")) + implementation("com.squareup.okhttp3:okhttp") + implementation("com.squareup.okhttp3:logging-interceptor") + + testImplementation(platform("org.junit:junit-bom:6.1.3")) testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") + + pmdAux(files(javaToolchains.launcherFor(java.toolchain).map { + it.metadata.installationPath.file("lib/jrt-fs.jar") + })) } tasks.test { useJUnitPlatform() } + +spotless { + java { + palantirJavaFormat("2.102.0") + } + groovyGradle { + target("*.gradle") + greclipse().configProperties("org.eclipse.jdt.core.formatter.tabulation.char=space") + } +} + +pmd { + toolVersion = "7.28.0" + ruleSets = [] + ruleSetFiles = files("config/pmd/ruleset.xml") + consoleOutput = true +} diff --git a/config/pmd/ruleset.xml b/config/pmd/ruleset.xml new file mode 100644 index 0000000..75499be --- /dev/null +++ b/config/pmd/ruleset.xml @@ -0,0 +1,52 @@ + + + Correctness, resource ownership and unused code in the SDK and its tests. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 249e583..9fa7f28 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 21e89aa..a78c88e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,10 @@ -#Tue Dec 12 18:58:05 PYST 2023 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip +distributionSha256Sum=dce76f55f8e251a3a1f130eb120f30b3d271de2b76c9b0729d316b5a1b6dc01f +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1b6c787..249efbb 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,10 +15,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # -# Gradle start up script for POSIX generated by Gradle. +# gradlew start up script for POSIX generated by Gradle. # # Important for running: # @@ -27,7 +29,7 @@ # bash, then to run this script, type that shell name before the whole # command line, like: # -# ksh Gradle +# ksh gradlew # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,13 +82,11 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -114,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -133,22 +132,29 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -165,7 +171,6 @@ fi # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) @@ -193,18 +198,27 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index ac1b06f..03754c4 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,19 +13,49 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,15 +70,16 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -56,34 +87,26 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 -:mainEnd -if "%OS%"=="Windows_NT" endlocal +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel -:omega +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/src/main/java/org/ith/client/TuRuc.java b/src/main/java/org/ith/client/TuRuc.java index f88dd56..7649846 100644 --- a/src/main/java/org/ith/client/TuRuc.java +++ b/src/main/java/org/ith/client/TuRuc.java @@ -1,13 +1,10 @@ package org.ith.client; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.alibaba.fastjson2.support.retrofit.Retrofit2ConverterFactory; +import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; -import retrofit2.converter.gson.GsonConverterFactory; - -import java.util.concurrent.TimeUnit; public class TuRuc { @@ -19,7 +16,6 @@ public class TuRuc { private final int readTimeout; private final int connectTimeout; - public TuRuc(String apiUrl) { this.apiUrl = apiUrl; this.callTimeout = DEFAULT_TIMEOUT; @@ -39,7 +35,7 @@ public TuRuc(String apiUrl, int callTimeout, int writeTimeout, int readTimeout, public TuRucClient getClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); - //Http Client + // Http Client OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor) .callTimeout(callTimeout, TimeUnit.SECONDS) @@ -47,17 +43,12 @@ public TuRucClient getClient() { .readTimeout(readTimeout, TimeUnit.SECONDS) .connectTimeout(connectTimeout, TimeUnit.SECONDS) .build(); - //Serializator - Gson gson = new GsonBuilder() - .setDateFormat("yyyy-MM-dd") - .create(); - //Retrofit + // Retrofit Retrofit retrofit = new Retrofit.Builder() .baseUrl(apiUrl) - .addConverterFactory(GsonConverterFactory.create(gson)) + .addConverterFactory(Retrofit2ConverterFactory.create()) .client(client) .build(); return retrofit.create(TuRucClient.class); } - } diff --git a/src/main/java/org/ith/client/TuRucClient.java b/src/main/java/org/ith/client/TuRucClient.java index 2fc610c..53101dd 100644 --- a/src/main/java/org/ith/client/TuRucClient.java +++ b/src/main/java/org/ith/client/TuRucClient.java @@ -10,14 +10,10 @@ public interface TuRucClient { @GET("api/contribuyente") - Call> getContribuyente( - @Query(value="ruc", encoded=false) String ruc - ); + Call> getContribuyente(@Query(value = "ruc", encoded = false) String ruc); @GET("api/contribuyente/search") Call> searchContribuyentes( - @Query(value="search", encoded=false) String search, - @Query(value="page", encoded=false) Integer page - ); - + @Query(value = "search", encoded = false) String search, + @Query(value = "page", encoded = false) Integer page); } diff --git a/src/main/java/org/ith/model/BaseResponse.java b/src/main/java/org/ith/model/BaseResponse.java index 6fa0dc0..242969a 100644 --- a/src/main/java/org/ith/model/BaseResponse.java +++ b/src/main/java/org/ith/model/BaseResponse.java @@ -7,8 +7,7 @@ public class BaseResponse { private T data; private String message; - public BaseResponse() { - } + public BaseResponse() {} public BaseResponse(T data, String message) { this.data = data; @@ -33,16 +32,13 @@ public void setMessage(String message) { @Override public String toString() { - return "BaseResponse{" + - "data=" + data + - ", message='" + message + '\'' + - '}'; + return "BaseResponse{" + "data=" + data + ", message='" + message + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof BaseResponse that)) return false; + if (!(o instanceof BaseResponse that)) return false; if (!Objects.equals(data, that.data)) return false; return Objects.equals(message, that.message); @@ -54,5 +50,4 @@ public int hashCode() { result = 31 * result + (message != null ? message.hashCode() : 0); return result; } - } diff --git a/src/main/java/org/ith/model/Contribuyente.java b/src/main/java/org/ith/model/Contribuyente.java index fc45bb5..7a63492 100644 --- a/src/main/java/org/ith/model/Contribuyente.java +++ b/src/main/java/org/ith/model/Contribuyente.java @@ -4,24 +4,46 @@ public class Contribuyente { - private Integer ruc; + private Integer doc; private String razonSocial; private Integer dv; + private String ruc; + private String estado; + private Boolean esPersonaJuridica; + private Boolean esEntidadPublica; + + public Contribuyente() {} + + public Contribuyente( + Integer doc, + String razonSocial, + Integer dv, + String ruc, + String estado, + Boolean esPersonaJuridica, + Boolean esEntidadPublica) { + this.doc = doc; + this.razonSocial = razonSocial; + this.dv = dv; + this.ruc = ruc; + this.estado = estado; + this.esPersonaJuridica = esPersonaJuridica; + this.esEntidadPublica = esEntidadPublica; + } - public Contribuyente() { + public Integer getDoc() { + return doc; } - public Contribuyente(Integer ruc, String razonSocial, Integer dv) { - this.ruc = ruc; - this.razonSocial = razonSocial; - this.dv = dv; + public void setDoc(Integer doc) { + this.doc = doc; } - public Integer getRuc() { + public String getRuc() { return ruc; } - public void setRuc(Integer ruc) { + public void setRuc(String ruc) { this.ruc = ruc; } @@ -41,13 +63,40 @@ public void setDv(Integer dv) { this.dv = dv; } + public String getEstado() { + return estado; + } + + public void setEstado(String estado) { + this.estado = estado; + } + + public Boolean getEsPersonaJuridica() { + return esPersonaJuridica; + } + + public void setEsPersonaJuridica(Boolean esPersonaJuridica) { + this.esPersonaJuridica = esPersonaJuridica; + } + + public Boolean getEsEntidadPublica() { + return esEntidadPublica; + } + + public void setEsEntidadPublica(Boolean esEntidadPublica) { + this.esEntidadPublica = esEntidadPublica; + } + @Override public String toString() { - return "Contribuyente{" + - "ruc=" + ruc + - ", razonSocial='" + razonSocial + '\'' + - ", dv=" + dv + - '}'; + return "Contribuyente{" + "doc=" + + doc + ", razonSocial='" + + razonSocial + '\'' + ", dv=" + + dv + ", ruc='" + + ruc + '\'' + ", estado='" + + estado + '\'' + ", esPersonaJuridica=" + + esPersonaJuridica + ", esEntidadPublica=" + + esEntidadPublica + '}'; } @Override @@ -55,17 +104,17 @@ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Contribuyente that)) return false; - if (!Objects.equals(ruc, that.ruc)) return false; - if (!Objects.equals(razonSocial, that.razonSocial)) return false; - return Objects.equals(dv, that.dv); + return Objects.equals(doc, that.doc) + && Objects.equals(razonSocial, that.razonSocial) + && Objects.equals(dv, that.dv) + && Objects.equals(ruc, that.ruc) + && Objects.equals(estado, that.estado) + && Objects.equals(esPersonaJuridica, that.esPersonaJuridica) + && Objects.equals(esEntidadPublica, that.esEntidadPublica); } @Override public int hashCode() { - int result = ruc != null ? ruc.hashCode() : 0; - result = 31 * result + (razonSocial != null ? razonSocial.hashCode() : 0); - result = 31 * result + (dv != null ? dv.hashCode() : 0); - return result; + return Objects.hash(doc, razonSocial, dv, ruc, estado, esPersonaJuridica, esEntidadPublica); } - } diff --git a/src/main/java/org/ith/model/SearchResponse.java b/src/main/java/org/ith/model/SearchResponse.java index f68e43c..fc1caf8 100644 --- a/src/main/java/org/ith/model/SearchResponse.java +++ b/src/main/java/org/ith/model/SearchResponse.java @@ -8,8 +8,7 @@ public class SearchResponse { private List contribuyentes; private Integer paginas; - public SearchResponse() { - } + public SearchResponse() {} public SearchResponse(List contribuyentes, Integer paginas) { this.contribuyentes = contribuyentes; @@ -34,10 +33,7 @@ public void setPaginas(Integer paginas) { @Override public String toString() { - return "SearchResponse{" + - "contribuyentes=" + contribuyentes + - ", paginas=" + paginas + - '}'; + return "SearchResponse{" + "contribuyentes=" + contribuyentes + ", paginas=" + paginas + '}'; } @Override @@ -45,8 +41,7 @@ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof SearchResponse that)) return false; - if (!Objects.equals(contribuyentes, that.contribuyentes)) - return false; + if (!Objects.equals(contribuyentes, that.contribuyentes)) return false; return Objects.equals(paginas, that.paginas); } @@ -56,5 +51,4 @@ public int hashCode() { result = 31 * result + (paginas != null ? paginas.hashCode() : 0); return result; } - } diff --git a/src/test/java/MainTest.java b/src/test/java/MainTest.java deleted file mode 100644 index c113c2e..0000000 --- a/src/test/java/MainTest.java +++ /dev/null @@ -1,50 +0,0 @@ -import com.google.gson.Gson; -import org.ith.client.TuRuc; -import org.ith.client.TuRucClient; -import org.ith.model.BaseResponse; -import org.ith.model.Contribuyente; -import org.ith.model.SearchResponse; -import org.junit.jupiter.api.Test; -import retrofit2.Response; - -import java.io.IOException; - -public class MainTest { - - private static final String API_URL = "http://localhost:8080/"; - - private TuRucClient getTuRucClient(){ - TuRuc tuRuc = new TuRuc(API_URL); - return tuRuc.getClient(); - } - - @Test - public void test() { - System.out.println("Hello World!"); - } - - @Test - public void getContribuyente() throws IOException { - TuRucClient tuRucClient = getTuRucClient(); - Response> response = tuRucClient.getContribuyente("31244-2").execute(); - if (response.isSuccessful()) { - System.out.println(response.body()); - }else { - assert response.errorBody() != null; - System.out.println(new Gson().fromJson(response.errorBody().string(), BaseResponse.class)); - } - } - - @Test - public void searchContribuyentes() throws IOException { - TuRucClient tuRucClient = getTuRucClient(); - Response> response = tuRucClient.searchContribuyentes("ESTEBAN", 0).execute(); - if (response.isSuccessful()) { - System.out.println(response.body()); - }else { - assert response.errorBody() != null; - System.out.println(new Gson().fromJson(response.errorBody().string(), BaseResponse.class)); - } - } - -} diff --git a/src/test/java/org/ith/client/TuRucClientTest.java b/src/test/java/org/ith/client/TuRucClientTest.java new file mode 100644 index 0000000..053152e --- /dev/null +++ b/src/test/java/org/ith/client/TuRucClientTest.java @@ -0,0 +1,171 @@ +package org.ith.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.alibaba.fastjson2.JSONException; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.stream.Collectors; +import org.ith.model.Contribuyente; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TuRucClientTest { + + private HttpServer server; + private TuRucClient client; + private final BlockingQueue requests = new LinkedBlockingQueue<>(); + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + client = new TuRuc("http://127.0.0.1:" + server.getAddress().getPort() + "/", 5, 5, 5, 5).getClient(); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + @Test + void looksUpContributorWithFullRuc() throws Exception { + respond(200, """ + {"data":{"doc":80024191,"razonSocial":"MINISTERIO DE PRUEBA","dv":6, + "ruc":"80024191-6","estado":"ACTIVO","esPersonaJuridica":false, + "esEntidadPublica":true},"message":"OK"} + """); + + var response = client.getContribuyente("80024191-6").execute(); + + assertTrue(response.isSuccessful()); + assertEquals("OK", response.body().getMessage()); + var contribuyente = response.body().getData(); + assertEquals("80024191-6", contribuyente.getRuc()); + assertEquals(80024191, contribuyente.getDoc()); + assertEquals(6, contribuyente.getDv()); + assertEquals("MINISTERIO DE PRUEBA", contribuyente.getRazonSocial()); + assertEquals("ACTIVO", contribuyente.getEstado()); + assertFalse(contribuyente.getEsPersonaJuridica()); + assertTrue(contribuyente.getEsEntidadPublica()); + assertEquals(URI.create("/api/contribuyente?ruc=80024191-6"), requests.remove()); + } + + @Test + void searchesWithUtf8AndPagination() throws Exception { + respond(200, """ + {"data":{"contribuyentes":[{"doc":1234567,"razonSocial":"NUÑEZ & ASOCIADOS", + "dv":8,"ruc":"1234567-8","estado":null,"esPersonaJuridica":true, + "esEntidadPublica":false}],"paginas":3},"message":"OK"} + """); + + var response = client.searchContribuyentes("NUÑEZ & ASOCIADOS", 2).execute(); + + assertTrue(response.isSuccessful()); + var page = response.body().getData(); + assertEquals(3, page.getPaginas()); + assertEquals(1, page.getContribuyentes().size()); + var contribuyente = page.getContribuyentes().get(0); + assertEquals("1234567-8", contribuyente.getRuc()); + assertEquals(1234567, contribuyente.getDoc()); + assertEquals(8, contribuyente.getDv()); + assertEquals("NUÑEZ & ASOCIADOS", contribuyente.getRazonSocial()); + assertNull(contribuyente.getEstado()); + assertTrue(contribuyente.getEsPersonaJuridica()); + assertFalse(contribuyente.getEsEntidadPublica()); + URI request = requests.remove(); + assertEquals("/api/contribuyente/search", request.getPath()); + assertEquals(Map.of("search", "NUÑEZ & ASOCIADOS", "page", "2"), queryParameters(request)); + } + + @Test + void returnsEmptySearchPage() throws Exception { + respond(200, """ + {"data":{"contribuyentes":[],"paginas":0},"message":"OK"} + """); + + var response = client.searchContribuyentes("SIN RESULTADOS", 0).execute(); + + assertTrue(response.isSuccessful()); + assertEquals(0, response.body().getData().getPaginas()); + assertTrue(response.body().getData().getContribuyentes().isEmpty()); + } + + @ParameterizedTest + @ValueSource(ints = {400, 500}) + void preservesHttpErrorStatusAndBody(int status) throws Exception { + String error = "{\"data\":null,\"message\":\"No se pudo completar la búsqueda\"}"; + respond(status, error); + + var response = client.getContribuyente("invalid").execute(); + + assertFalse(response.isSuccessful()); + assertEquals(status, response.code()); + assertNull(response.body()); + assertEquals(error, response.errorBody().string()); + } + + @Test + void ignoresAdditionalFieldsAndPreservesNullState() throws Exception { + respond(200, """ + {"data":{"doc":80024191,"razonSocial":"NUÑEZ & ASOCIADOS","dv":6, + "ruc":"80024191-6","estado":null,"esPersonaJuridica":false, + "esEntidadPublica":true,"nuevoCampo":{"valor":123}}, + "message":"OK","nuevaMetadata":[1,2,3]} + """); + + var response = client.getContribuyente("80024191-6").execute(); + + assertTrue(response.isSuccessful()); + assertEquals("OK", response.body().getMessage()); + assertEquals( + new Contribuyente(80024191, "NUÑEZ & ASOCIADOS", 6, "80024191-6", null, false, true), + response.body().getData()); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"data\": {\"doc\":not-a-number}}", "{\"data\":", "{\"data\":null} {\"data\":null}"}) + void rejectsMalformedJsonAsIoError(String json) throws Exception { + respond(200, json); + + var error = assertThrows( + IOException.class, () -> client.getContribuyente("80024191-6").execute()); + assertInstanceOf(JSONException.class, error.getCause()); + } + + private Map queryParameters(URI uri) { + return Arrays.stream(uri.getRawQuery().split("&")) + .map(parameter -> parameter.split("=", 2)) + .collect(Collectors.toMap( + pair -> URLDecoder.decode(pair[0], StandardCharsets.UTF_8), + pair -> URLDecoder.decode(pair[1], StandardCharsets.UTF_8))); + } + + private void respond(int status, String json) { + server.createContext("/", exchange -> { + requests.add(exchange.getRequestURI()); + byte[] body = json.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); + exchange.sendResponseHeaders(status, body.length); + try (var output = exchange.getResponseBody()) { + output.write(body); + } + }); + server.start(); + } +}