Skip to content

Commit

Permalink
Merge pull request #10 from lunasoft/release/SW.SDK_(java)_0.0.1.2
Browse files Browse the repository at this point in the history
Release/sw.sdk (java) 0.0.1.2
  • Loading branch information
rbarusta authored May 2, 2017
2 parents c36a0fa + 04f04ec commit 4e55ba0
Show file tree
Hide file tree
Showing 22 changed files with 720 additions and 634 deletions.
7 changes: 7 additions & 0 deletions .idea/artifacts/SW_JAVA.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

625 changes: 358 additions & 267 deletions .idea/workspace.xml

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions META-INF/MANIFEST.MF
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Manifest-Version: 1.0

125 changes: 118 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,14 @@ Java 1.6 o superior

##Dependencias
* [Unirest](http://unirest.io/java.html)
* [org.json](http://www.json.org/java)
* [httpclient 4.3.6](http://hc.apache.org/downloads.cgi)
* [httpmime 4.3.6](http://hc.apache.org/downloads.cgi)
* [httpasyncclient 4.0.2](http://hc.apache.org/downloads.cgi)


##Instalación

Descargas el modulo mediante Maven:

```html
Expand All @@ -22,18 +28,25 @@ Descargas el modulo mediante Maven:
<dependency>
<groupId>mx.com.sw.services</groupId>
<artifactId>SW-JAVA</artifactId>
<version>1.0.0</version>
<version>1.0.1</version>
</dependency>
</dependencies>
```
##Instalación manual
```
git clone https://github.com/lunasoft/sw-sdk-java.git
cd sw-sdk-java/
mvn clean package
##Instalación manual (sin Maven)
Descargar el modulo directamente de los siguientes links:

* [Relase Github](https://github.com/lunasoft/sw-sdk-java/releases)
* [Maven](https://oss.sonatype.org/service/local/repositories/releases/content/mx/com/sw/services/SW-JAVA/1.0.0/SW-JAVA-1.0.0.jar)
Asi como instalar manualmente cada una de las dependencias:
* [Unirest](http://unirest.io/java.html)
* [org.json](http://www.json.org/java)
* [httpclient 4.3.6](http://hc.apache.org/downloads.cgi)
* [httpmime 4.3.6](http://hc.apache.org/downloads.cgi)
* [httpasyncclient 4.0.2](http://hc.apache.org/downloads.cgi)

Alternativamente tambien se cuenta con un archivo JAR en el que se incluyen todas las dependencias, este se encuentra en la carpeta [Relase Github](https://github.com/lunasoft/sw-sdk-java/releases), con el sufijo _"jar-with-dependencies.jar"_


```

##Uso rapido...

Expand Down Expand Up @@ -159,4 +172,102 @@ TimbrarV1 Recibe el contenido de un XML ya emitido (sellado) en formato String
}


```



##Timbrar CFDI V2
TimbrarV2 Recibe el contenido de un XML ya emitido (sellado) en formato String , posteriormente si la factura y el token son correctos devuelve el CFDI ya tibrado, en caso contrario lanza una excepción.

##Timbrar XML en formato string utilizando usuario y contraseña
```java
try{
//Es preferible inicializar el objeto con el usuario y password de nuestra cuenta, en caso contrario se puede incluir solamente el token de acceso
//Se especifica el base path, esto para consumir el api de pruebas o productivo
SWStampService sdk = new SWStampService("demo","123456789","http://services.test.sw.com.mx");
//Se inicializa un objeto response, que obtendra la respuesta del api
IResponse response = null;
//Se asigna el resultado de la respuesta a dicho objeto
//Se ejecuta el metodo "Stamp", que timbrara nuestro comprobante posteriormente sellado, asi como la versión del servicio de timbrado,
//puede ver mas de estas versiones en el apartado "Versiones de timbrado"
response = sdk.Stamp(stringXML,"v2");
//El objeto response tendra así los atributos:
// Status: estado de la petición procesada, puede ser : "success", "fail", "error"
// HttpStatusCode: Codigo de respuesta HTTP del servidor: eg. 200, 400, 500
// Data: Cuerpo de la respuesta que arroja el servidor
//En este caso arrojara el complemento timbre: {"tfd":"<Complemento>"}
System.out.println(response.Status);
System.out.println(response.HttpStatusCode);
System.out.println(response.Data);
}
catch(Exception e){
//En caso de obtener estatus "fail", "error"
//Se generara una excepción
System.out.println(e.getMessage());
}


```

##Timbrar XML en formato string utilizando token

```java
try{
//Es preferible inicializar el objeto con el usuario y password de nuestra cuenta, en caso contrario se puede incluir solamente el token de acceso
//Se especifica el base path, esto para consumir el api de pruebas o productivo
SWStampService sdk = new SWStampService("T2lYQ0t4L0R....","http://services.test.sw.com.mx");
//Se inicializa un objeto response, que obtendra la respuesta del api
IResponse response = null;
//Se asigna el resultado de la respuesta a dicho objeto
//Se ejecuta el metodo "Stamp", que timbrara nuestro comprobante posteriormente sellado, asi como la versión del servicio de timbrado,
//puede ver mas de estas versiones en el apartado "Versiones de timbrado"
response = sdk.Stamp(stringXML,"v2");
//El objeto response tendra así los atributos:
// Status: estado de la petición procesada, puede ser : "success", "fail", "error"
// HttpStatusCode: Codigo de respuesta HTTP del servidor: eg. 200, 400, 500
// Data: Cuerpo de la respuesta que arroja el servidor
//En este caso arrojara el complemento timbre: {"tfd":"<Complemento>"}
System.out.println(response.Status);
System.out.println(response.HttpStatusCode);
System.out.println(response.Data);
}
catch(Exception e){
//En caso de obtener estatus "fail", "error"
//Se generara una excepción
System.out.println(e.getMessage());
}


```

##Timbrar XML en File type utilizando token

```java
try{
//Es preferible inicializar el objeto con el usuario y password de nuestra cuenta, en caso contrario se puede incluir solamente el token de acceso
//Se especifica el base path, esto para consumir el api de pruebas o productivo
SWStampService sdk = new SWStampService("T2lYQ0t4L0R....","http://services.test.sw.com.mx");
//Se inicializa un objeto response, que obtendra la respuesta del api
IResponse response = null;
//Se asigna el resultado de la respuesta a dicho objeto
//Se ejecuta el metodo "Stamp", que timbrara nuestro comprobante posteriormente sellado, asi como la versión del servicio de timbrado,
//puede ver mas de estas versiones en el apartado "Versiones de timbrado"
File fileXML = new File('xfdi.xml');
response = sdk.Stamp(fileXML,"v2");
//El objeto response tendra así los atributos:
// Status: estado de la petición procesada, puede ser : "success", "fail", "error"
// HttpStatusCode: Codigo de respuesta HTTP del servidor: eg. 200, 400, 500
// Data: Cuerpo de la respuesta que arroja el servidor
//En este caso arrojara el complemento timbre: {"tfd":"<Complemento>"}
System.out.println(response.Status);
System.out.println(response.HttpStatusCode);
System.out.println(response.Data);
}
catch(Exception e){
//En caso de obtener estatus "fail", "error"
//Se generara una excepción
System.out.println(e.getMessage());
}


```
5 changes: 3 additions & 2 deletions SW-JAVA.iml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="com.github.bingoohuang:unirest-java:0.0.1" level="project" />
<orderEntry type="library" exported="" name="com.github.bingoohuang:unirest-java:0.0.1" level="project" />
<orderEntry type="module-library" scope="TEST">
<library>
<CLASSES>
Expand Down Expand Up @@ -40,7 +41,7 @@
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<orderEntry type="module-library" exported="">
<library>
<CLASSES>
<root url="jar://$USER_HOME$/Desktop/CDI/juniversalchardet-1.0.3.jar!/" />
Expand Down
21 changes: 20 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

<groupId>mx.com.sw.services</groupId>
<artifactId>SW-JAVA</artifactId>
<version>1.0.0</version>
<version>0.0.1.2</version>

<packaging>jar</packaging>

<scm>
Expand Down Expand Up @@ -50,6 +51,24 @@
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>create-my-bundle</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package Exceptions;

public class GenaralException extends Exception {
public class GeneralException extends Exception {
public int HttpStatusCode;
public String ErrorMSG;

Expand All @@ -20,7 +20,7 @@ public void setErrorMSG(String errorMSG) {
ErrorMSG = errorMSG;
}

public GenaralException(int httpStatusCode, String errorMSG) {
public GeneralException(int httpStatusCode, String errorMSG) {
super(httpStatusCode+" ----> "+errorMSG);
HttpStatusCode = httpStatusCode;
ErrorMSG = errorMSG;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package Services.Authentication;

import Exceptions.AuthException;
import Exceptions.GenaralException;
import Exceptions.GeneralException;
import Services.SWService;
import Utils.Constants;
import Utils.Requests.Authentication.AuthOptionsRequest;
Expand All @@ -16,7 +16,7 @@ public SWAuthenticationService(String user, String password, String URI) {
}


public IResponse Token() throws GenaralException, AuthException {
public IResponse Token() throws GeneralException, AuthException {
AuthOptionsRequest settings = new AuthOptionsRequest(getURI(),getUser(),getPassword());

String dum = settings.URI.split("-")[0];
Expand Down
63 changes: 23 additions & 40 deletions src/main/java/Services/Stamp/SWStampService.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
package Services.Stamp;

import Exceptions.AuthException;
import Exceptions.GenaralException;
import Exceptions.GeneralException;
import Services.SWService;
import Utils.Constants;
import Utils.EncoderHelper;
import Utils.Requests.Authentication.AuthOptionsRequest;
import Utils.Requests.Authentication.AuthRequest;
import Utils.Requests.Authentication.AuthSoapRequest;
import Utils.Requests.Stamp.StampOptionsRequest;
import Utils.Requests.Stamp.StampRequest;
import Utils.Requests.Stamp.StampRequestDummy;
import Utils.Responses.AuthResponse;

import Utils.Responses.IResponse;
import org.json.JSONObject;


import java.nio.charset.Charset;


import java.io.*;
import java.net.MalformedURLException;

public class SWStampService extends SWService {

Expand All @@ -28,7 +28,7 @@ public SWStampService(String token, String URI) {
super(token, URI);
}

public IResponse Stamp(String xml, String version) throws AuthException, GenaralException {
public IResponse Stamp(String xml, String version) throws AuthException, GeneralException {



Expand All @@ -41,12 +41,12 @@ public IResponse Stamp(String xml, String version) throws AuthException, Genaral
}

//CUSTOMER HASN'T TOKEN, BUT HAS USER AND PASSWORD --> AUTH,GENERATE TOKEN AND SET TOKEN IN GLOBAL SETTINGS
// Temporaly changes to soap
AuthOptionsRequest settings = new AuthOptionsRequest(Constants.BASE_PATH+Constants.AUTH_PATH,getUser(),getPassword());
AuthSoapRequest req = new AuthSoapRequest();
IResponse res = req.sendRequest(settings);
AuthOptionsRequest settings = new AuthOptionsRequest(Constants.BASE_PATH,getUser(),getPassword());
AuthRequest req = new AuthRequest();
IResponse res = req.sendRequest(settings);
if (res.HttpStatusCode==200){
setToken(res.Data);
JSONObject obj = new JSONObject(res.Data);
setToken(obj.getString("token"));
}
else{
//CUSTOMER HASN'T TOKEN, AND USER AND PASSWORD ARE BAD--> WE CANT' DO ANYTHING --> THROW EXCEPTION
Expand All @@ -68,22 +68,11 @@ public IResponse Stamp(String xml, String version) throws AuthException, Genaral

}

public IResponse Stamp(File xmlFile, String version) throws AuthException, GenaralException {
public IResponse Stamp(byte[] xmlFile, String version) throws AuthException, GeneralException {
//BINARY XML

try{
String xmlProcess = "";
String strLine;
BufferedReader reader = new BufferedReader(new FileReader(xmlFile));
while ((strLine = reader.readLine()) != null) {
// Print the content on the console
xmlProcess+=strLine;
}

reader.close();



String xmlProcess = new String(xmlFile,Charset.forName("UTF-8"));

if (getToken()==null){

Expand All @@ -94,11 +83,12 @@ public IResponse Stamp(File xmlFile, String version) throws AuthException, Genar
}

//CUSTOMER HASN'T TOKEN, BUT HAS USER AND PASSWORD --> TRY AUTH,GENERATE TOKEN AND SET TOKEN IN GLOBAL SETTINGS
AuthOptionsRequest settings = new AuthOptionsRequest(Constants.BASE_PATH+Constants.AUTH_PATH,getUser(),getPassword());
AuthOptionsRequest settings = new AuthOptionsRequest(Constants.BASE_PATH,getUser(),getPassword());
AuthRequest req = new AuthRequest();
AuthResponse res = (AuthResponse) req.sendRequest(settings);
IResponse res = req.sendRequest(settings);
if (res.HttpStatusCode==200){
setToken(res.Data);
JSONObject obj = new JSONObject(res.Data);
setToken(obj.getString("token"));
}
else{
//CUSTOMER HASN'T TOKEN, AND USER AND PASSWORD ARE BAD--> WE CANT' DO ANYTHING --> THROW EXCEPTION
Expand All @@ -112,20 +102,13 @@ public IResponse Stamp(File xmlFile, String version) throws AuthException, Genar

StampOptionsRequest settings = new StampOptionsRequest(getToken(),getURI(),xmlProcess,version);

String dum = settings.URI.split("-")[0];
System.out.println(dum);
if (dum.equalsIgnoreCase("d")){
StampRequestDummy req = new StampRequestDummy();
return req.sendRequest(settings);
}
String dum = settings.URI.split("-")[0];
if (dum.equalsIgnoreCase("d")){
StampRequestDummy req = new StampRequestDummy();
return req.sendRequest(settings);
}
StampRequest req = new StampRequest();
return req.sendRequest(settings);

}catch (FileNotFoundException e) {
throw new GenaralException(500,"ERROR AL LEER ARCHIVO");
} catch (IOException e) {
throw new GenaralException(500,"ERROR AL LEER ARCHIVO");
}

}
}
Loading

0 comments on commit 4e55ba0

Please sign in to comment.