diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f3e7aa..0cc6dc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +4.3.0 +- Solicitar autorização com envio opcional dos dados do cliente para sugestão de cadastro + 4.2.0 - Criar requisições de assinaturas transparente e gerenciá-las (aderir, cancelar, consultar, efetuar cobrança, etc) diff --git a/public/example-api/src/main/java/br/com/uol/pagseguro/example/api/application/authorization/register/CreateAuthorizationWithCompanyAccountSuggestion.java b/public/example-api/src/main/java/br/com/uol/pagseguro/example/api/application/authorization/register/CreateAuthorizationWithCompanyAccountSuggestion.java new file mode 100644 index 0000000..54ad11b --- /dev/null +++ b/public/example-api/src/main/java/br/com/uol/pagseguro/example/api/application/authorization/register/CreateAuthorizationWithCompanyAccountSuggestion.java @@ -0,0 +1,83 @@ +package br.com.uol.pagseguro.example.api.application.authorization.register; + +import br.com.uol.pagseguro.api.PagSeguro; +import br.com.uol.pagseguro.api.PagSeguroEnv; +import br.com.uol.pagseguro.api.application.authorization.AuthorizationRegistration; +import br.com.uol.pagseguro.api.application.authorization.AuthorizationRegistrationBuilder; +import br.com.uol.pagseguro.api.application.authorization.RegisteredAuthorization; +import br.com.uol.pagseguro.api.common.domain.PermissionCode; +import br.com.uol.pagseguro.api.common.domain.builder.*; +import br.com.uol.pagseguro.api.common.domain.enums.AccountType; +import br.com.uol.pagseguro.api.common.domain.enums.DocumentType; +import br.com.uol.pagseguro.api.common.domain.enums.PhoneType; +import br.com.uol.pagseguro.api.credential.Credential; + +public class CreateAuthorizationWithCompanyAccountSuggestion { + + public static void main(String[] args) { + + String appId = "your_app_id"; + String appKey = "your_app_key"; + + try{ + final PagSeguro pagSeguro = PagSeguro.instance(Credential.applicationCredential(appId, + appKey), PagSeguroEnv.SANDBOX); + + // Registra as autorizações com sugestão de cadastro de empresa + AuthorizationRegistration authorizationRegistration = + new AuthorizationRegistrationBuilder() + .withReference("123") + .addPermission(PermissionCode.Code.CREATE_CHECKOUTS) + .withRedirectURL("http://seusite.com.br/redirect") + .withNotificationUrl("http://seusite.com.br/notification") + .withAccount(new AccountRegisterSuggestionBuilder() + .withEmail("usuario@seusite.com.br") + .withType(AccountType.COMPANY) + .withCompany(new CompanyBuilder() + .withName("Seu Site") + .addDocument(new DocumentBuilder() + .withType(DocumentType.CNPJ) + .withValue("17302417000101") + ) + .withDisplayName("Seu Site") + .withWebsiteUrl("http://www.seusite.com.br") + .withPartner(new PartnerBuilder() + .withName("Antonio Carlos") + .addDocument(new DocumentBuilder() + .withType(DocumentType.CPF) + .withValue("34163749160") + ) + .withBirthDate("1982-02-05") + ) + .addPhone(new PhoneAccountBuilder() + .withType(PhoneType.BUSINESS) + .withAreaCode("11") + .withNumber("30302323") + ) + .addPhone(new PhoneAccountBuilder() + .withType(PhoneType.BUSINESS) + .withAreaCode("11") + .withNumber("976302323") + ) + .withAddress(new AddressBuilder() + .withPostalCode("01452002") + .withStreet("Av. Brig. Faria Lima") + .withNumber("1384") + .withComplement("5o andar") + .withDistrict("Jardim Paulistano") + .withCity("Sao Paulo") + .withState("SP") + .withCountry("BRA") + ) + ) + ) + .build(); + + RegisteredAuthorization ra = pagSeguro.authorizations().registerWithSuggestion(authorizationRegistration); + System.out.print(ra); + + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/public/example-api/src/main/java/br/com/uol/pagseguro/example/api/application/authorization/register/CreateAuthorizationWithPersonAccountSuggestion.java b/public/example-api/src/main/java/br/com/uol/pagseguro/example/api/application/authorization/register/CreateAuthorizationWithPersonAccountSuggestion.java new file mode 100644 index 0000000..0793a56 --- /dev/null +++ b/public/example-api/src/main/java/br/com/uol/pagseguro/example/api/application/authorization/register/CreateAuthorizationWithPersonAccountSuggestion.java @@ -0,0 +1,76 @@ +package br.com.uol.pagseguro.example.api.application.authorization.register; + +import br.com.uol.pagseguro.api.PagSeguro; +import br.com.uol.pagseguro.api.PagSeguroEnv; +import br.com.uol.pagseguro.api.application.authorization.AuthorizationRegistration; +import br.com.uol.pagseguro.api.application.authorization.AuthorizationRegistrationBuilder; +import br.com.uol.pagseguro.api.application.authorization.RegisteredAuthorization; +import br.com.uol.pagseguro.api.common.domain.PermissionCode; +import br.com.uol.pagseguro.api.common.domain.builder.*; +import br.com.uol.pagseguro.api.common.domain.enums.AccountType; +import br.com.uol.pagseguro.api.common.domain.enums.DocumentType; +import br.com.uol.pagseguro.api.common.domain.enums.PhoneType; +import br.com.uol.pagseguro.api.credential.Credential; + +public class CreateAuthorizationWithPersonAccountSuggestion { + + public static void main(String[] args) { + + String appId = "your_app_id"; + String appKey = "your_app_key"; + + try{ + final PagSeguro pagSeguro = PagSeguro.instance(Credential.applicationCredential(appId, + appKey), PagSeguroEnv.SANDBOX); + + // Registra as autorizações com sugestão de cadastro de pessoa + AuthorizationRegistration authorizationRegistration = + new AuthorizationRegistrationBuilder() + .withReference("123") + .addPermission(PermissionCode.Code.CREATE_CHECKOUTS) + .addPermission(PermissionCode.Code.SEARCH_TRANSACTIONS) + .addPermission(PermissionCode.Code.RECEIVE_TRANSACTION_NOTIFICATIONS) + .withRedirectURL("http://seusite.com.br/redirect") + .withNotificationUrl("http://seusite.com.br/notification") + .withAccount(new AccountRegisterSuggestionBuilder() + .withEmail("usuario@seusite.com.br") + .withType(AccountType.SELLER) + .withPerson(new PersonBuilder() + .withName("Antonio Carlos") + .addDocument(new DocumentBuilder() + .withType(DocumentType.CPF) + .withValue("23606838450") + ) + .withBirthDate("1982-02-05") + .addPhone(new PhoneAccountBuilder() + .withType(PhoneType.HOME) + .withAreaCode("11") + .withNumber("30302323") + ) + .addPhone(new PhoneAccountBuilder() + .withType(PhoneType.MOBILE) + .withAreaCode("11") + .withNumber("976302323") + ) + .withAddress(new AddressBuilder() + .withPostalCode("01452002") + .withStreet("Av. Brig. Faria Lima") + .withNumber("1384") + .withComplement("5o andar") + .withDistrict("Jardim Paulistano") + .withCity("Sao Paulo") + .withState("SP") + .withCountry("BRA") + ) + ) + ) + .build(); + + RegisteredAuthorization ra = pagSeguro.authorizations().registerWithSuggestion(authorizationRegistration); + System.out.print(ra); + + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AccountV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AccountV2XMLConverter.java new file mode 100644 index 0000000..31b3a72 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AccountV2XMLConverter.java @@ -0,0 +1,79 @@ +package br.com.uol.pagseguro.api.application.authorization; + +import br.com.uol.pagseguro.api.common.domain.AccountRegisterSuggestion; + +import javax.xml.bind.annotation.XmlType; + +@XmlType(propOrder = { "email", "type", "person", "company" }) +public class AccountV2XMLConverter { + + private final static PersonV2XMLConverter PERSON_V_2_XML_CONVERTER = new PersonV2XMLConverter(); + private final static CompanyV2XMLConverter COMPANY_V_2_XML_CONVERTER = new CompanyV2XMLConverter(); + + private String email; + private String type; + private PersonV2XMLConverter person; + private CompanyV2XMLConverter company; + + public AccountV2XMLConverter() { + } + + public AccountV2XMLConverter(String email, String type, PersonV2XMLConverter person, CompanyV2XMLConverter company) { + this.email = email; + this.type = type; + this.person = person; + this.company = company; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public PersonV2XMLConverter getPerson() { + return person; + } + + public void setPerson(PersonV2XMLConverter person) { + this.person = person; + } + + public CompanyV2XMLConverter getCompany() { + return company; + } + + public void setCompany(CompanyV2XMLConverter company) { + this.company = company; + } + + /** + * Convert attributes in request XML + * + * @param account Account register suggestion data + * @see AccountRegisterSuggestion + * @return AccountV2XMLConverter + */ + public AccountV2XMLConverter convert(AccountRegisterSuggestion account) { + if (account == null) { + return null; + } + + AccountV2XMLConverter convertedAccount = new AccountV2XMLConverter(); + convertedAccount.setEmail(account.getEmail()); + convertedAccount.setType(account.getType()); + convertedAccount.setPerson(PERSON_V_2_XML_CONVERTER.convert(account.getPerson())); + convertedAccount.setCompany(COMPANY_V_2_XML_CONVERTER.convert(account.getCompany())); + return convertedAccount; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistration.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistration.java index 7386801..fa536d1 100755 --- a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistration.java +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistration.java @@ -22,6 +22,8 @@ import java.util.List; +import br.com.uol.pagseguro.api.common.domain.Account; +import br.com.uol.pagseguro.api.common.domain.AccountRegisterSuggestion; import br.com.uol.pagseguro.api.common.domain.PermissionCode; /** @@ -72,5 +74,12 @@ public interface AuthorizationRegistration { */ String getNotificationURL(); - + /** + * Account data suggested for registration. + * + * Optional + * + * @return Account Data suggested for registration + */ + AccountRegisterSuggestion getAccount(); } diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistrationBuilder.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistrationBuilder.java index 5970d21..da9a3d5 100755 --- a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistrationBuilder.java +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistrationBuilder.java @@ -23,6 +23,7 @@ import java.util.ArrayList; import java.util.List; +import br.com.uol.pagseguro.api.common.domain.AccountRegisterSuggestion; import br.com.uol.pagseguro.api.common.domain.PermissionCode; import br.com.uol.pagseguro.api.utils.Builder; @@ -34,117 +35,144 @@ */ public final class AuthorizationRegistrationBuilder implements Builder { - private String reference; - private List permissions = new ArrayList(); - private String notificationURL; - private String redirectURL; - - /** - * Set reference of authorization - * - * @param reference Optional. Identifier used to refer to the permission of your request. - * @return Builder for authorization registration - * @see AuthorizationRegistration#getReference() - */ - public AuthorizationRegistrationBuilder withReference(String reference) { - this.reference = reference; - return this; - } - - /** - * Add permission of authorization - * - * @param permission Required. List of permissions in this authorization. - * @return Builder for Authorization Registration - * @see PermissionCode.Code - * @see AuthorizationRegistration#getPermissions() - */ - public AuthorizationRegistrationBuilder addPermission(PermissionCode.Code permission) { - permissions.add(permission); - return this; - } - - /** - * Add Permissions of Authorization - * - * @param permissions Required. List of permissions in this authorization. - * @return Builder for Authorization Registration - * @see PermissionCode.Code - * @see AuthorizationRegistration#getPermissions() - */ - public AuthorizationRegistrationBuilder addPermissions( - Iterable permissions) { - for (PermissionCode.Code permission : permissions) { - addPermission(permission); + private String reference; + private List permissions = new ArrayList(); + private String notificationURL; + private String redirectURL; + private AccountRegisterSuggestion account; + + /** + * Set reference of authorization + * + * @param reference Optional. Identifier used to refer to the permission of your request. + * @return Builder for authorization registration + * @see AuthorizationRegistration#getReference() + */ + public AuthorizationRegistrationBuilder withReference(String reference) { + this.reference = reference; + return this; } - return this; - } - - /** - * Set notification URL of Authorization - * - * @param notificationURL Notification URL of Authorization - * @return Builder for Authorization Registration - * @see AuthorizationRegistration#getNotificationURL() - */ - public AuthorizationRegistrationBuilder withNotificationUrl(String notificationURL) { - this.notificationURL = notificationURL; - return this; - } - - /** - * Set redirect URL of Authorization - * - * @param redirectURL Redirect URL of Authorization - * @return Builder for Authorization Registration - * @see AuthorizationRegistration#getRedirectURL() - */ - public AuthorizationRegistrationBuilder withRedirectURL(String redirectURL) { - this.redirectURL = redirectURL; - return this; - } - - - /** - * Build the Authorization Registration - * - * @return Interface for Authorization Registration - * @see AuthorizationRegistration - */ - @Override - public AuthorizationRegistration build() { - return new SimpleAuthorizationRegistration(this); - } - - /** - * Implementation of {@code AuthorizationRegistration} - */ - private static class SimpleAuthorizationRegistration implements AuthorizationRegistration { - - private final AuthorizationRegistrationBuilder authorizationRegistrationBuilder; - - private SimpleAuthorizationRegistration(AuthorizationRegistrationBuilder authorizationRegistrationBuilder) { - this.authorizationRegistrationBuilder = authorizationRegistrationBuilder; + + /** + * Add permission of authorization + * + * @param permission Required. List of permissions in this authorization. + * @return Builder for Authorization Registration + * @see PermissionCode.Code + * @see AuthorizationRegistration#getPermissions() + */ + public AuthorizationRegistrationBuilder addPermission(PermissionCode.Code permission) { + permissions.add(permission); + return this; } - @Override - public String getReference() { - return authorizationRegistrationBuilder.reference; + /** + * Add Permissions of Authorization + * + * @param permissions Required. List of permissions in this authorization. + * @return Builder for Authorization Registration + * @see PermissionCode.Code + * @see AuthorizationRegistration#getPermissions() + */ + public AuthorizationRegistrationBuilder addPermissions( + Iterable permissions) { + for (PermissionCode.Code permission : permissions) { + addPermission(permission); + } + return this; } - @Override - public List getPermissions() { - return authorizationRegistrationBuilder.permissions; + /** + * Set notification URL of Authorization + * + * @param notificationURL Notification URL of Authorization + * @return Builder for Authorization Registration + * @see AuthorizationRegistration#getNotificationURL() + */ + public AuthorizationRegistrationBuilder withNotificationUrl(String notificationURL) { + this.notificationURL = notificationURL; + return this; } - @Override - public String getRedirectURL() { - return authorizationRegistrationBuilder.redirectURL; + /** + * Set redirect URL of Authorization + * + * @param redirectURL Redirect URL of Authorization + * @return Builder for Authorization Registration + * @see AuthorizationRegistration#getRedirectURL() + */ + public AuthorizationRegistrationBuilder withRedirectURL(String redirectURL) { + this.redirectURL = redirectURL; + return this; } + /** + * Set Account of Authorization + * + * @param account Account of Authorization + * @return Builder for Authorization Registration + * @see AuthorizationRegistration#getAccount() + */ + public AuthorizationRegistrationBuilder withAccount(AccountRegisterSuggestion account) { + this.account = account; + return this; + } + + /** + * Set Account of Authorization + * + * @param accountBuilder Builder for Account of Authorization + * @return Builder for person + * @see AuthorizationRegistration#getAccount() + */ + public AuthorizationRegistrationBuilder withAccount(Builder accountBuilder) { + return withAccount(accountBuilder.build()); + } + + + /** + * Build the Authorization Registration + * + * @return Interface for Authorization Registration + * @see AuthorizationRegistration + */ @Override - public String getNotificationURL() { - return authorizationRegistrationBuilder.notificationURL; + public AuthorizationRegistration build() { + return new SimpleAuthorizationRegistration(this); + } + + /** + * Implementation of {@code AuthorizationRegistration} + */ + private static class SimpleAuthorizationRegistration implements AuthorizationRegistration { + + private final AuthorizationRegistrationBuilder authorizationRegistrationBuilder; + + private SimpleAuthorizationRegistration(AuthorizationRegistrationBuilder authorizationRegistrationBuilder) { + this.authorizationRegistrationBuilder = authorizationRegistrationBuilder; + } + + @Override + public String getReference() { + return authorizationRegistrationBuilder.reference; + } + + @Override + public List getPermissions() { + return authorizationRegistrationBuilder.permissions; + } + + @Override + public String getRedirectURL() { + return authorizationRegistrationBuilder.redirectURL; + } + + @Override + public String getNotificationURL() { + return authorizationRegistrationBuilder.notificationURL; + } + + @Override + public AccountRegisterSuggestion getAccount() { return authorizationRegistrationBuilder.account; } } - } } diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistrationV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistrationV2XMLConverter.java new file mode 100644 index 0000000..7bd8ee8 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRegistrationV2XMLConverter.java @@ -0,0 +1,47 @@ +package br.com.uol.pagseguro.api.application.authorization; + +import br.com.uol.pagseguro.api.utils.RequestXML; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import java.io.StringWriter; + +/** + * Converter for V2 XML Authorization Register + * + * @author PagSeguro Internet Ltda. + */ +public class AuthorizationRegistrationV2XMLConverter { + + private final static PermissionsV2XMLConverter PERMISSION_V_2_XML_CONVERTER = new PermissionsV2XMLConverter(); + private final static AccountV2XMLConverter ACCOUNT_V_2_XML_CONVERTER = new AccountV2XMLConverter(); + + AuthorizationRegistrationV2XMLConverter() { + } + + /** + * Convert Interface for Authorization Registration in XML + * + * @param authorizationRegistration Interface for Authorization Registration + * @see AuthorizationRegistration + * @return RequestXML + * @see RequestXML + * @throws JAXBException Exception if a problem occurs during the XML parsing process + */ + public RequestXML convert(AuthorizationRegistration authorizationRegistration) throws JAXBException { + AuthorizationRequestV2XMLConverter authorizationRequest = new AuthorizationRequestV2XMLConverter(); + authorizationRequest.setReference(authorizationRegistration.getReference()); + authorizationRequest.setRedirectURL(authorizationRegistration.getRedirectURL()); + authorizationRequest.setPermissions(PERMISSION_V_2_XML_CONVERTER.convert(authorizationRegistration.getPermissions())); + authorizationRequest.setNotificationURL(authorizationRegistration.getNotificationURL()); + authorizationRequest.setAccount(ACCOUNT_V_2_XML_CONVERTER.convert(authorizationRegistration.getAccount())); + + JAXBContext jaxbContext = JAXBContext.newInstance(AuthorizationRequestV2XMLConverter.class); + Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); + StringWriter stringWriter = new StringWriter(); + jaxbMarshaller.marshal(authorizationRequest, stringWriter); + + return new RequestXML(stringWriter.toString()); + } +} \ No newline at end of file diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRequestV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRequestV2XMLConverter.java new file mode 100644 index 0000000..38a2c4a --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationRequestV2XMLConverter.java @@ -0,0 +1,55 @@ +package br.com.uol.pagseguro.api.application.authorization; + +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +@XmlRootElement(name = "authorizationRequest") +@XmlType(propOrder = {"reference", "permissions", "redirectURL", "notificationURL", "account"}) +public class AuthorizationRequestV2XMLConverter { + + private String reference; + private String redirectURL; + private String notificationURL; + private PermissionsV2XMLConverter permissions; + private AccountV2XMLConverter account; + + public String getReference() { + return reference; + } + + public void setReference(String reference) { + this.reference = reference; + } + + public String getRedirectURL() { + return redirectURL; + } + + public void setRedirectURL(String redirectURL) { + this.redirectURL = redirectURL; + } + + public PermissionsV2XMLConverter getPermissions() { + return permissions; + } + + public void setPermissions(PermissionsV2XMLConverter permissions) { + this.permissions = permissions; + } + + public String getNotificationURL() { + return notificationURL; + } + + public void setNotificationURL(String notificationURL) { + this.notificationURL = notificationURL; + } + + public AccountV2XMLConverter getAccount() { + return account; + } + + public void setAccount(AccountV2XMLConverter account) { + this.account = account; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationsResource.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationsResource.java index afccac4..dbcb3ae 100755 --- a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationsResource.java +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/AuthorizationsResource.java @@ -20,11 +20,10 @@ */ package br.com.uol.pagseguro.api.application.authorization; -import java.io.IOException; - import br.com.uol.pagseguro.api.Endpoints; import br.com.uol.pagseguro.api.PagSeguro; import br.com.uol.pagseguro.api.application.authorization.search.AuthorizationSearchResource; +import br.com.uol.pagseguro.api.direct.preapproval.DirectPreApprovalsResource; import br.com.uol.pagseguro.api.exception.PagSeguroLibException; import br.com.uol.pagseguro.api.http.HttpClient; import br.com.uol.pagseguro.api.http.HttpMethod; @@ -32,6 +31,14 @@ import br.com.uol.pagseguro.api.utils.Builder; import br.com.uol.pagseguro.api.utils.CharSet; import br.com.uol.pagseguro.api.utils.RequestMap; +import br.com.uol.pagseguro.api.utils.RequestXML; +import br.com.uol.pagseguro.api.utils.logging.Log; +import br.com.uol.pagseguro.api.utils.logging.LoggerFactory; + +import javax.xml.bind.JAXBException; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; /** * Factory to authorization registration and authorizations search @@ -39,67 +46,129 @@ * @author PagSeguro Internet Ltda. */ public class AuthorizationsResource { + private static final Log LOGGER = LoggerFactory.getLogger(AuthorizationsResource.class.getName()); + + private static final AuthorizationRegistrationV2MapConverter AUTHORIZATION_REGISTRATION_MC = + new AuthorizationRegistrationV2MapConverter(); + + private static final AuthorizationRegistrationV2XMLConverter AUTHORIZATION_REGISTRATION_XMLC = + new AuthorizationRegistrationV2XMLConverter(); + + private final PagSeguro pagSeguro; + private final HttpClient httpClient; + + public AuthorizationsResource(PagSeguro pagSeguro, HttpClient httpClient) { + this.pagSeguro = pagSeguro; + this.httpClient = httpClient; + } + + /** + * Authorization registration + * + * @param authorizationRegistrationBuilder Builder of interface with attributes for authorization + * registration + * @return Response of authorization registration + * @see AuthorizationRegistration + * @see RegisteredAuthorization + */ + public RegisteredAuthorization register( + Builder authorizationRegistrationBuilder) { + return register(authorizationRegistrationBuilder.build()); + } + + /** + * Authorization registration + * + * @param authorizationRegistration Interface with attributes for authorization registration + * @return Response of authorization registration + * @see AuthorizationRegistration + * @see RegisteredAuthorization + */ + public RegisteredAuthorization register(AuthorizationRegistration authorizationRegistration) { + try { + LOGGER.info("Iniciando registro de autorizacao"); + + LOGGER.info("Convertendo valores"); + final RequestMap map = AUTHORIZATION_REGISTRATION_MC.convert(authorizationRegistration); + LOGGER.info("Valores convertidos"); + LOGGER.debug(String.format("Parametros: %s", map)); - private static final AuthorizationRegistrationV2MapConverter AUTHORIZATION_REGISTRATION_MC = - new AuthorizationRegistrationV2MapConverter(); - - private final PagSeguro pagSeguro; - private final HttpClient httpClient; - - public AuthorizationsResource(PagSeguro pagSeguro, HttpClient httpClient) { - this.pagSeguro = pagSeguro; - this.httpClient = httpClient; - } - - /** - * Authorization registration - * - * @param authorizationRegistrationBuilder Builder of interface with attributes for authorization - * registration - * @return Response of authorization registration - * @see AuthorizationRegistration - * @see RegisteredAuthorization - */ - public RegisteredAuthorization register( - Builder authorizationRegistrationBuilder) { - return register(authorizationRegistrationBuilder.build()); - } - - /** - * Authorization registration - * - * @param authorizationRegistration Interface with attributes for authorization registration - * @return Response of authorization registration - * @see AuthorizationRegistration - * @see RegisteredAuthorization - */ - public RegisteredAuthorization register(AuthorizationRegistration authorizationRegistration) { - final RequestMap map = AUTHORIZATION_REGISTRATION_MC.convert(authorizationRegistration); - final HttpResponse response; - try { - response = - httpClient.execute(HttpMethod.POST, - String.format(Endpoints.AUTHORIZATION_REQUEST, pagSeguro.getHost()), - null, map.toHttpRequestBody(CharSet.ENCODING_ISO)); - - RegisteredAuthorizationResponseXML responseXML = response.parseXMLContent(pagSeguro, - RegisteredAuthorizationResponseXML.class); - - return responseXML; - } catch (IOException e) { - throw new PagSeguroLibException(e); + final HttpResponse response; + + response = + httpClient.execute(HttpMethod.POST, + String.format(Endpoints.AUTHORIZATION_REQUEST, pagSeguro.getHost()), + null, map.toHttpRequestBody(CharSet.ENCODING_ISO)); + LOGGER.debug(String.format("Resposta: %s", response.toString())); + + LOGGER.info("Parseando XML de resposta"); + RegisteredAuthorizationResponseXML responseXML = response.parseXMLContent(pagSeguro, + RegisteredAuthorizationResponseXML.class); + LOGGER.info("Parseamento finalizado"); + + LOGGER.info("Registro de autorizacao finalizado"); + return responseXML; + + } catch (IOException e) { + LOGGER.error("Erro no registro de autorizacao"); + throw new PagSeguroLibException(e); + } } - } + /** + * Authorization registration + * + * @param authorizationRegistration Interface with attributes for authorization registration + * @return Response of authorization registration + * @see AuthorizationRegistration + * @see RegisteredAuthorization + */ + public RegisteredAuthorization registerWithSuggestion(AuthorizationRegistration authorizationRegistration) { + try { + LOGGER.info("Iniciando registro de autorizacao com sugestao de cadastro de pessoa/empresa"); + + LOGGER.info("Convertendo valores"); + final RequestXML xmlBody = AUTHORIZATION_REGISTRATION_XMLC.convert(authorizationRegistration); + LOGGER.info("Valores convertidos"); + LOGGER.debug(String.format("Parametros: %s", xmlBody)); + + final HttpResponse response; + + Map headers = new HashMap(); + headers.put("Content-Type", "application/xml"); - /** - * Factory to Search Authorizations - * - * @return Factory to Search Authorizations - * @see AuthorizationSearchResource - */ - public AuthorizationSearchResource search() { - return new AuthorizationSearchResource(pagSeguro, httpClient); - } + response = httpClient.executeXML(HttpMethod.POST, + String.format(Endpoints.AUTHORIZATION_REQUEST, pagSeguro.getHost()), + headers, + xmlBody.toHttpXMLRequestBody(CharSet.ENCODING_ISO) + ); + LOGGER.debug(String.format("Resposta: %s", response.toString())); + LOGGER.info("Parseando XML de resposta"); + RegisteredAuthorizationResponseXML responseXML = response.parseXMLContent(pagSeguro, + RegisteredAuthorizationResponseXML.class); + LOGGER.info("Parseamento finalizado"); + + LOGGER.info("Registro de autorizacao com sugestao de cadastro de pessoa/empresa finalizado"); + return responseXML; + + } catch (IOException e) { + LOGGER.error("Erro no registro de autorizacao com sugestao de cadastro de pessoa/empresa"); + throw new PagSeguroLibException(e); + + } catch (JAXBException e) { + LOGGER.error("Erro no registro de autorizacao com sugestao de cadastro de pessoa/empresa"); + throw new PagSeguroLibException(e); + } + } + + /** + * Factory to Search Authorizations + * + * @return Factory to Search Authorizations + * @see AuthorizationSearchResource + */ + public AuthorizationSearchResource search() { + return new AuthorizationSearchResource(pagSeguro, httpClient); + } } diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/CodeV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/CodeV2XMLConverter.java new file mode 100644 index 0000000..2e7aaf0 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/CodeV2XMLConverter.java @@ -0,0 +1,14 @@ +package br.com.uol.pagseguro.api.application.authorization; + +public class CodeV2XMLConverter { + + private String code; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/CompanyV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/CompanyV2XMLConverter.java new file mode 100644 index 0000000..55bb082 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/CompanyV2XMLConverter.java @@ -0,0 +1,121 @@ +package br.com.uol.pagseguro.api.application.authorization; + +import br.com.uol.pagseguro.api.common.domain.Company; +import br.com.uol.pagseguro.api.common.domain.converterXML.AddressV2XMLConverter; +import br.com.uol.pagseguro.api.common.domain.converterXML.DocumentsV2XMLConverter; +import br.com.uol.pagseguro.api.common.domain.converterXML.PhonesV2XMLConverter; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +@XmlType(propOrder = {"name", "documents", "displayName", "websiteURL", "partner", "phones", "address"}) +public class CompanyV2XMLConverter { + + private final static DocumentsV2XMLConverter DOCUMENTS_V_2_XML_CONVERTER = new DocumentsV2XMLConverter(); + private final static PartnerV2XMLConverter PARTNER_V_2_XML_CONVERTER = new PartnerV2XMLConverter(); + private final static PhonesV2XMLConverter PHONES_V_2_XML_CONVERTER = new PhonesV2XMLConverter(); + private final static AddressV2XMLConverter ADDRESS_V_2_XML_CONVERTER = new AddressV2XMLConverter(); + + private String name; + private DocumentsV2XMLConverter documents; + private String displayName; + private String websiteURL; + private String birthDate; + private PartnerV2XMLConverter partner; + private PhonesV2XMLConverter phones; + @XmlElement(name = "address") + private AddressV2XMLConverter address; + + public CompanyV2XMLConverter() { + } + + public CompanyV2XMLConverter(String name, DocumentsV2XMLConverter documents, String displayName, String websiteURL, + PhonesV2XMLConverter phones, PartnerV2XMLConverter partner, AddressV2XMLConverter address) { + this.name = name; + this.documents = documents; + this.displayName = displayName; + this.websiteURL = websiteURL; + this.phones = phones; + this.partner = partner; + this.address = address; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public DocumentsV2XMLConverter getDocuments() { + return documents; + } + + public void setDocuments(DocumentsV2XMLConverter documents) { + this.documents = documents; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getWebsiteURL() { + return websiteURL; + } + + public void setWebsiteURL(String websiteURL) { + this.websiteURL = websiteURL; + } + + public PhonesV2XMLConverter getPhones() { + return phones; + } + + public void setPhones(PhonesV2XMLConverter phones) { + this.phones = phones; + } + + public PartnerV2XMLConverter getPartner() { + return partner; + } + + public void setPartner(PartnerV2XMLConverter partner) { + this.partner = partner; + } + + public AddressV2XMLConverter getAddressn() { + return address; + } + + public void setAddress(AddressV2XMLConverter address) { + this.address = address; + } + + /** + * Convert attributes in request XML + * + * @param company Company data + * @see Company + * @return CompanyV2XMLConverter + */ + public CompanyV2XMLConverter convert(Company company) { + if (company == null) { + return null; + } + + CompanyV2XMLConverter convertedCompany = new CompanyV2XMLConverter(); + convertedCompany.setName(company.getName()); + convertedCompany.setDocuments(DOCUMENTS_V_2_XML_CONVERTER.convert(company.getDocuments())); + convertedCompany.setDisplayName(company.getDisplayName()); + convertedCompany.setWebsiteURL(company.getWebsiteUrl()); + convertedCompany.setPartner(PARTNER_V_2_XML_CONVERTER.convert(company.getPartner())); + convertedCompany.setPhones(PHONES_V_2_XML_CONVERTER.convert(company.getPhones())); + convertedCompany.setAddress(ADDRESS_V_2_XML_CONVERTER.convert(company.getAddress())); + return convertedCompany; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/PartnerV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/PartnerV2XMLConverter.java new file mode 100644 index 0000000..b7d9b99 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/PartnerV2XMLConverter.java @@ -0,0 +1,71 @@ +package br.com.uol.pagseguro.api.application.authorization; + +import br.com.uol.pagseguro.api.common.domain.Partner; +import br.com.uol.pagseguro.api.common.domain.converterXML.DocumentsV2XMLConverter; + +import javax.xml.bind.annotation.XmlType; + +@XmlType(propOrder = { "name", "documents", "birthDate" }) +public class PartnerV2XMLConverter { + + private final static DocumentsV2XMLConverter DOCUMENTS_V_2_XML_CONVERTER = new DocumentsV2XMLConverter(); + + private String name; + private DocumentsV2XMLConverter documents; + private String birthDate; + + public PartnerV2XMLConverter(){ + } + + public PartnerV2XMLConverter(String name, DocumentsV2XMLConverter documents, String birthDate) { + this.name = name; + this.documents = documents; + this.birthDate = birthDate; + } + + public String getName() { + return name; + } + + public PartnerV2XMLConverter setName(String name) { + this.name = name; + return this; + } + + public DocumentsV2XMLConverter getDocuments() { + return documents; + } + + public PartnerV2XMLConverter setDocuments(DocumentsV2XMLConverter documents) { + this.documents = documents; + return this; + } + + public String getBirthDate() { + return birthDate; + } + + public PartnerV2XMLConverter setBirthDate(String birthDate) { + this.birthDate = birthDate; + return this; + } + + /** + * Convert attributes in request XML + * + * @param partner Partner data + * @see Partner + * @return PartnerV2XMLConverter + */ + public PartnerV2XMLConverter convert(Partner partner) { + if (partner == null) { + return null; + } + + PartnerV2XMLConverter convertedPartner = new PartnerV2XMLConverter(); + convertedPartner.setName(partner.getName()); + convertedPartner.setBirthDate(partner.getBirthDate()); + convertedPartner.setDocuments(DOCUMENTS_V_2_XML_CONVERTER.convert(partner.getDocuments())); + return convertedPartner; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/PermissionsV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/PermissionsV2XMLConverter.java new file mode 100644 index 0000000..4b790ee --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/PermissionsV2XMLConverter.java @@ -0,0 +1,48 @@ +package br.com.uol.pagseguro.api.application.authorization; + +import br.com.uol.pagseguro.api.common.domain.PermissionCode; + +import java.util.ArrayList; +import java.util.List; + +public class PermissionsV2XMLConverter { + + private ArrayList code; + + public ArrayList getCode() { + if (code == null) { + code = new ArrayList(); + } + return code; + } + + public void setCode(ArrayList code) { + this.code = code; + } + + /** + * Convert attributes in request XML + * + * @param codeList List of permission codes + * @return PermissionsV2XMLConverter + */ + public PermissionsV2XMLConverter convert(List codeList) { + PermissionsV2XMLConverter convertedPermissions = new PermissionsV2XMLConverter(); + convertedPermissions.setCode(parseToCodeStringList(codeList)); + return convertedPermissions; + } + + /** + * Parse a permission codes list to a string list of codes + * + * @param codeList List of permission codes + * @return ArrayList List of permission codes + */ + private ArrayList parseToCodeStringList(List codeList) { + ArrayList codeStringList = new ArrayList(); + for (PermissionCode.Code code : codeList) { + codeStringList.add(code.getStringCode()); + } + return codeStringList; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/PersonV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/PersonV2XMLConverter.java new file mode 100644 index 0000000..50e045a --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/application/authorization/PersonV2XMLConverter.java @@ -0,0 +1,97 @@ +package br.com.uol.pagseguro.api.application.authorization; + +import br.com.uol.pagseguro.api.common.domain.Person; +import br.com.uol.pagseguro.api.common.domain.converterXML.AddressV2XMLConverter; +import br.com.uol.pagseguro.api.common.domain.converterXML.DocumentsV2XMLConverter; +import br.com.uol.pagseguro.api.common.domain.converterXML.PhonesV2XMLConverter; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +@XmlType(propOrder = { "name", "documents", "birthDate", "phones", "address" }) +public class PersonV2XMLConverter { + + private final static DocumentsV2XMLConverter DOCUMENTS_V_2_XML_CONVERTER = new DocumentsV2XMLConverter(); + private final static PhonesV2XMLConverter PHONES_V_2_XML_CONVERTER = new PhonesV2XMLConverter(); + private final static AddressV2XMLConverter ADDRESS_V_2_XML_CONVERTER = new AddressV2XMLConverter(); + + private String name; + private DocumentsV2XMLConverter documents; + private String birthDate; + private PhonesV2XMLConverter phones; + @XmlElement(name = "address") + private AddressV2XMLConverter address; + + public PersonV2XMLConverter() { + } + + public PersonV2XMLConverter(String name, DocumentsV2XMLConverter documents, String birthDate, PhonesV2XMLConverter phones, + AddressV2XMLConverter address) { + this.name = name; + this.documents = documents; + this.birthDate = birthDate; + this.phones = phones; + this.address = address; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public DocumentsV2XMLConverter getDocuments() { + return documents; + } + + public void setDocuments(DocumentsV2XMLConverter documents) { + this.documents = documents; + } + + public String getBirthDate() { + return birthDate; + } + + public void setBirthDate(String birthDate) { + this.birthDate = birthDate; + } + + public PhonesV2XMLConverter getPhones() { + return phones; + } + + public void setPhones(PhonesV2XMLConverter phones) { + this.phones = phones; + } + + public AddressV2XMLConverter getAddressn() { + return address; + } + + public void setAddress(AddressV2XMLConverter address) { + this.address = address; + } + + /** + * Convert attributes in request XML + * + * @param person Person data + * @see Person + * @return PersonV2XMLConverter + */ + public PersonV2XMLConverter convert(Person person) { + if (person == null) { + return null; + } + + PersonV2XMLConverter convertedPerson = new PersonV2XMLConverter(); + convertedPerson.setName(person.getName()); + convertedPerson.setDocuments(DOCUMENTS_V_2_XML_CONVERTER.convert(person.getDocuments())); + convertedPerson.setBirthDate(person.getBirthDate()); + convertedPerson.setPhones(PHONES_V_2_XML_CONVERTER.convert(person.getPhones())); + convertedPerson.setAddress(ADDRESS_V_2_XML_CONVERTER.convert(person.getAddress())); + return convertedPerson; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/AccountRegisterSuggestion.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/AccountRegisterSuggestion.java new file mode 100644 index 0000000..a38d89c --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/AccountRegisterSuggestion.java @@ -0,0 +1,37 @@ +package br.com.uol.pagseguro.api.common.domain; + +/** + * Interface for Account Register Suggestion + * + * @author PagSeguro Internet Ltda. + */ +public interface AccountRegisterSuggestion { + + /** + * Get email account + * + * @return Email + */ + String getEmail(); + + /** + * Get account type + * + * @return Type + */ + String getType(); + + /** + * Get person account data + * + * @return Person + */ + Person getPerson(); + + /** + * Get company account data + * + * @return Company + */ + Company getCompany(); +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/Company.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/Company.java new file mode 100644 index 0000000..981016d --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/Company.java @@ -0,0 +1,64 @@ +package br.com.uol.pagseguro.api.common.domain; + +import java.util.List; + +/** + * Interface for Company + * + * @author PagSeguro Internet Ltda. + */ +public interface Company { + + /** + * Get company's name + * + * @return Name + */ + String getName(); + + /** + * Get company's display name + * + * @return Display Name + */ + String getDisplayName(); + + /** + * Get company's website URL + * + * @return Website URL + */ + String getWebsiteUrl(); + + /** + * Get company's partner + * + * @return Partner + * @see Partner + */ + Partner getPartner(); + + /** + * Get company's address + * + * @return Address + * @see Address + */ + Address getAddress(); + + /** + * Get company's documents + * + * @return Documents + * @see Document + */ + List getDocuments(); + + /** + * Get company's phones + * + * @return Phones + * @see PhoneAccount + */ + List getPhones(); +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/Partner.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/Partner.java new file mode 100644 index 0000000..15baa7d --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/Partner.java @@ -0,0 +1,34 @@ +package br.com.uol.pagseguro.api.common.domain; + +import java.util.Date; +import java.util.List; + +/** + * Interface for Partner + * + * @author PagSeguro Internet Ltda. + */ +public interface Partner { + + /** + * Get partner's name + * + * @return Name + */ + String getName(); + + /** + * Get partner's birth date + * + * @return Birth Date + */ + String getBirthDate(); + + /** + * Get partner's documents + * + * @return Documents + * @see Document + */ + List getDocuments(); +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/Person.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/Person.java new file mode 100644 index 0000000..44bea64 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/Person.java @@ -0,0 +1,50 @@ +package br.com.uol.pagseguro.api.common.domain; + +import java.util.Date; +import java.util.List; + +/** + * Interface for Person + * + * @author PagSeguro Internet Ltda. + */ +public interface Person { + + /** + * Get person's name + * + * @return Name + */ + String getName(); + + /** + * Get person's birth date + * + * @return Birth Date + */ + String getBirthDate(); + + /** + * Get person's address + * + * @return Address + * @see Address + */ + Address getAddress(); + + /** + * Get person's documents + * + * @return Documents + * @see Document + */ + List getDocuments(); + + /** + * Get person's phones + * + * @return Phones + * @see PhoneAccount + */ + List getPhones(); +} \ No newline at end of file diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/PhoneAccount.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/PhoneAccount.java new file mode 100644 index 0000000..7072015 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/PhoneAccount.java @@ -0,0 +1,16 @@ +package br.com.uol.pagseguro.api.common.domain; + +/** + * Interface for phone account + * + * @author PagSeguro Internet Ltda. + */ +public interface PhoneAccount extends Phone { + + /** + * Get type of phone account + * + * @return Type + */ + String getType(); +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/AccountRegisterSuggestionBuilder.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/AccountRegisterSuggestionBuilder.java new file mode 100644 index 0000000..7b3277d --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/AccountRegisterSuggestionBuilder.java @@ -0,0 +1,141 @@ +package br.com.uol.pagseguro.api.common.domain.builder; + +import br.com.uol.pagseguro.api.common.domain.AccountRegisterSuggestion; +import br.com.uol.pagseguro.api.common.domain.Company; +import br.com.uol.pagseguro.api.common.domain.Person; +import br.com.uol.pagseguro.api.common.domain.enums.AccountType; +import br.com.uol.pagseguro.api.utils.Builder; + +public final class AccountRegisterSuggestionBuilder implements Builder { + + private String email; + private String type; + private Person person; + private Company company; + + /** + * Set email of account register suggestion + * + * @param email Account Register Suggestion Email + * @return Builder for Account Register Suggestion + * @see AccountRegisterSuggestion#getEmail() + */ + public AccountRegisterSuggestionBuilder withEmail(String email) { + this.email = email; + return this; + } + + /** + * Set type of account register suggestion + * + * @param type Account Register Suggestion Type + * @return Builder for Account Register Suggestion + * @see AccountRegisterSuggestion#getType() + */ + public AccountRegisterSuggestionBuilder withType(String type) { + this.type = type; + return this; + } + + /** + * Set type of account register suggestion + * + * @param type Account Register Suggestion Type + * @return Builder for Account Register Suggestion + * @see AccountRegisterSuggestion#getType() + */ + public AccountRegisterSuggestionBuilder withType(AccountType type) { + this.type = type.getValue(); + return this; + } + + /** + * Set person of account register suggestion + * + * @param person Person + * @return Builder for Account Register Suggestion + * @see AccountRegisterSuggestion#getPerson() + */ + public AccountRegisterSuggestionBuilder withPerson(Person person) { + this.person = person; + return this; + } + + /** + * Set person account of account register suggestion + * + * @param personBuilder Builder for Person + * @return Builder for Account Register Suggestion + * @see AccountRegisterSuggestion#getPerson() + */ + public AccountRegisterSuggestionBuilder withPerson(Builder personBuilder) { + return withPerson(personBuilder.build()); + } + + /** + * Set company of account register suggestion + * + * @param company Company + * @return Builder for Account Register Suggestion + * @see AccountRegisterSuggestion#getCompany() + */ + public AccountRegisterSuggestionBuilder withCompany(Company company) { + this.company = company; + return this; + } + + /** + * Set company of account register suggestion + * + * @param companyBuilder Builder for Company + * @return Builder for Account Register Suggestion + * @see AccountRegisterSuggestion#getCompany() + */ + public AccountRegisterSuggestionBuilder withCompany(Builder companyBuilder) { + return withCompany(companyBuilder.build()); + } + + /** + * Build the Account Register Suggestion + * + * @return Interface for Account Register Suggestion + * @see AccountRegisterSuggestion + */ + @Override + public AccountRegisterSuggestion build() { + return new SimpleAccountRegisterSuggestion(this); + } + + /** + * Implementation of {@code AccountRegisterSuggestion} + */ + private static class SimpleAccountRegisterSuggestion implements AccountRegisterSuggestion { + + private final AccountRegisterSuggestionBuilder accountRegisterSuggestionBuilder; + + SimpleAccountRegisterSuggestion(AccountRegisterSuggestionBuilder accountRegisterSuggestionBuilder) { + this.accountRegisterSuggestionBuilder = accountRegisterSuggestionBuilder; + } + + @Override + public String getEmail() { + return accountRegisterSuggestionBuilder.email; + } + + @Override + public String getType() { + return accountRegisterSuggestionBuilder.type; + } + + @Override + public Person getPerson() { + return accountRegisterSuggestionBuilder.person; + } + + @Override + public Company getCompany() { + return accountRegisterSuggestionBuilder.company; + } + + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/CompanyBuilder.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/CompanyBuilder.java new file mode 100644 index 0000000..b9bded2 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/CompanyBuilder.java @@ -0,0 +1,233 @@ +package br.com.uol.pagseguro.api.common.domain.builder; + +import br.com.uol.pagseguro.api.common.domain.*; +import br.com.uol.pagseguro.api.utils.Builder; + +import java.util.ArrayList; +import java.util.List; + +public final class CompanyBuilder implements Builder { + + private String name; + private String displayName; + private String websiteUrl; + private Partner partner; + private Address address; + private List documents = new ArrayList(); + private List phones = new ArrayList(); + + /** + * Set company's name + * + * @param name Name + * @return Builder for company + * @see Company#getName() + */ + public CompanyBuilder withName(String name) { + this.name = name; + return this; + } + + /** + * Set company's display name + * + * @param displayName Display Name + * @return Builder for company + * @see Company#getDisplayName() + */ + public CompanyBuilder withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Set company's website URL + * + * @param websiteUrl Website URL + * @return Builder for company + * @see Company#getWebsiteUrl() + */ + public CompanyBuilder withWebsiteUrl(String websiteUrl) { + this.websiteUrl = websiteUrl; + return this; + } + + /** + * Set company's address + * + * @param partner Partner + * @return Builder for company + * @see Company#getPartner() + */ + public CompanyBuilder withPartner(Partner partner) { + this.partner = partner; + return this; + } + + /** + * Set company's partner + * + * @param partnerBuilder Builder for Address + * @return Builder for company + * @see Company#getPartner() + */ + public CompanyBuilder withPartner(Builder partnerBuilder) { + return withPartner(partnerBuilder.build()); + } + + /** + * Set company's address + * + * @param address Address + * @return Builder for company + * @see Company#getAddress() + */ + public CompanyBuilder withAddress(Address address) { + this.address = address; + return this; + } + + /** + * Set company's address + * + * @param addressBuilder Builder for Address + * @return Builder for company + * @see Company#getAddress() + */ + public CompanyBuilder withAddress(Builder
addressBuilder) { + return withAddress(addressBuilder.build()); + } + + /** + * Add document to company + * + * @param document Document + * @return Builder for company + * @see Company#getDocuments() + */ + public CompanyBuilder addDocument(Document document) { + documents.add(document); + return this; + } + + /** + * Add document to company + * + * @param documentBuilder Builder for Document + * @return Builder for company + * @see Company#getDocuments() + */ + public CompanyBuilder addDocument(Builder documentBuilder) { + return addDocument(documentBuilder.build()); + } + + /** + * Add document to company + * + * @param documents Documents + * @return Builder for company + * @see Company#getDocuments() + */ + public CompanyBuilder addDocuments(Iterable documents) { + for (Document document : documents) { + addDocument(document); + } + return this; + } + + /** + * Add phone to company + * + * @param phone Phone + * @return Builder for company + * @see Company#getPhones() + */ + public CompanyBuilder addPhone(PhoneAccount phone) { + phones.add(phone); + return this; + } + + /** + * Add phone to company + * + * @param phoneAccountBuilder Builder for Phone Account + * @return Builder for company + * @see Company#getPhones() + */ + public CompanyBuilder addPhone(Builder phoneAccountBuilder) { + return addPhone(phoneAccountBuilder.build()); + } + + /** + * Add phone to company + * + * @param phones Phone + * @return Builder for company + * @see Company#getPhones() + */ + public CompanyBuilder addPhones(Iterable phones) { + for (PhoneAccount phone : phones) { + addPhone(phone); + } + return this; + } + + /** + * Build the company + * + * @return Interface for company + * @see Company + */ + @Override + public Company build() { + return new SimpleCompany(this); + } + + /** + * Implementation of {@code Company} + */ + private static class SimpleCompany implements Company { + + private final CompanyBuilder companyBuilder; + + SimpleCompany(CompanyBuilder companyBuilder) { + this.companyBuilder = companyBuilder; + } + + @Override + public String getName() { + return companyBuilder.name; + } + + @Override + public String getDisplayName() { + return companyBuilder.displayName; + } + + @Override + public String getWebsiteUrl() { + return companyBuilder.websiteUrl; + } + + @Override + public Partner getPartner() { + return companyBuilder.partner; + } + + @Override + public Address getAddress() { + return companyBuilder.address; + } + + @Override + public List getDocuments() { + return companyBuilder.documents; + } + + @Override + public List getPhones() { + return companyBuilder.phones; + } + + } +} \ No newline at end of file diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/DocumentBuilder.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/DocumentBuilder.java index 2e2c8a5..7ae22d7 100755 --- a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/DocumentBuilder.java +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/DocumentBuilder.java @@ -1,20 +1,20 @@ /* * 2007-2016 [PagSeguro Internet Ltda.] - * + * * NOTICE OF LICENSE - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * Copyright: 2007-2016 PagSeguro Internet Ltda. * Licence: http://www.apache.org/licenses/LICENSE-2.0 */ @@ -32,64 +32,64 @@ */ public final class DocumentBuilder implements Builder { - private DocumentType type = DocumentType.CPF; + private DocumentType type = DocumentType.CPF; - private String value = null; + private String value = null; - /** - * Set document type - * - * @param type Document type - * @return Builder for document - * @see Document#getType() - */ - public DocumentBuilder withType(DocumentType type) { - this.type = type; - return this; - } + /** + * Set document type + * + * @param type Document type + * @return Builder for document + * @see Document#getType() + */ + public DocumentBuilder withType(DocumentType type) { + this.type = type; + return this; + } - /** - * Set document value - * - * @param value Document Value - * @return Builder for Document - * @see Document#getValue() - */ - public DocumentBuilder withValue(String value) { - this.value = value; - return this; - } + /** + * Set document value + * + * @param value Document Value + * @return Builder for Document + * @see Document#getValue() + */ + public DocumentBuilder withValue(String value) { + this.value = value; + return this; + } - /** - * Build the Document - * - * @return Interface for document - * @see Document - */ - @Override - public Document build() { - return new SimpleDocument(this); - } + /** + * Build the Document + * + * @return Interface for document + * @see Document + */ + @Override + public Document build() { + return new SimpleDocument(this); + } - /** - * Implementation of {@code Document} - */ - private static class SimpleDocument implements Document { + /** + * Implementation of {@code Document} + */ + private static class SimpleDocument implements Document { - private final DocumentBuilder documentBuilder; + private final DocumentBuilder documentBuilder; - public SimpleDocument(DocumentBuilder documentBuilder) { - this.documentBuilder = documentBuilder; - } + public SimpleDocument(DocumentBuilder documentBuilder) { + this.documentBuilder = documentBuilder; + } - @Override - public DocumentType getType() { - return documentBuilder.type; - } + @Override + public DocumentType getType() { + return documentBuilder.type; + } - @Override - public String getValue() { - return documentBuilder.value; + @Override + public String getValue() { + return documentBuilder.value; + } } - } } diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/PartnerBuilder.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/PartnerBuilder.java new file mode 100644 index 0000000..9061230 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/PartnerBuilder.java @@ -0,0 +1,122 @@ +package br.com.uol.pagseguro.api.common.domain.builder; + +import br.com.uol.pagseguro.api.common.domain.Document; +import br.com.uol.pagseguro.api.common.domain.Partner; +import br.com.uol.pagseguro.api.utils.Builder; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Builder for Partner + * + * @author PagSeguro Internet Ltda. + */ +public final class PartnerBuilder implements Builder { + + private String name; + private String birthDate; + private List documents = new ArrayList(); + + /** + * Set partner's name + * + * @param name Name + * @return Builder for partner + * @see Partner#getName() + */ + public PartnerBuilder withName(String name) { + this.name = name; + return this; + } + + /** + * Set partner's birth date + * + * @param birthDate Brith Date + * @return Builder for partner + * @see Partner#getBirthDate() + */ + public PartnerBuilder withBirthDate(String birthDate) { + this.birthDate = birthDate; + return this; + } + + /** + * Add document to partner + * + * @param document Document + * @return Builder for partner + * @see Partner#getDocuments() + */ + public PartnerBuilder addDocument(Document document) { + documents.add(document); + return this; + } + + /** + * Add document to partner + * + * @param documentBuilder Builder for Document + * @return Builder for partner + * @see Partner#getDocuments() + */ + public PartnerBuilder addDocument(Builder documentBuilder) { + return addDocument(documentBuilder.build()); + } + + /** + * Add document to partner + * + * @param documents Documents + * @return Builder for partner + * @see Partner#getDocuments() + */ + public PartnerBuilder addDocuments(Iterable documents) { + for (Document document : documents) { + addDocument(document); + } + return this; + } + + /** + * Build the partner + * + * @return Interface for partner + * @see Partner + */ + @Override + public Partner build() { + return new SimplePartner(this); + } + + /** + * Implementation of {@code Partner} + */ + private static class SimplePartner implements Partner { + + private final PartnerBuilder partnerBuilder; + + SimplePartner(PartnerBuilder partnerBuilder) { + this.partnerBuilder = partnerBuilder; + } + + @Override + public String getName() { + return partnerBuilder.name; + } + + @Override + public String getBirthDate() { + return partnerBuilder.birthDate; + } + + @Override + public List getDocuments() { + return partnerBuilder.documents; + } + + } + +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/PersonBuilder.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/PersonBuilder.java new file mode 100644 index 0000000..937b7ad --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/PersonBuilder.java @@ -0,0 +1,195 @@ +package br.com.uol.pagseguro.api.common.domain.builder; + +import br.com.uol.pagseguro.api.common.domain.Address; +import br.com.uol.pagseguro.api.common.domain.Document; +import br.com.uol.pagseguro.api.common.domain.Person; +import br.com.uol.pagseguro.api.common.domain.PhoneAccount; +import br.com.uol.pagseguro.api.utils.Builder; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Builder for Person + * + * @author PagSeguro Internet Ltda. + */ +public final class PersonBuilder implements Builder { + + private String name; + private String birthDate; + private Address address; + private List documents = new ArrayList(); + private List phones = new ArrayList(); + + /** + * Set person's name + * + * @param name Name + * @return Builder for person + * @see Person#getName() + */ + public PersonBuilder withName(String name) { + this.name = name; + return this; + } + + /** + * Set person's birth date + * + * @param birthDate Brith Date + * @return Builder for person + * @see Person#getBirthDate() + */ + public PersonBuilder withBirthDate(String birthDate) { + this.birthDate = birthDate; + return this; + } + + /** + * Set person's address + * + * @param address Address + * @return Builder for person + * @see Person#getAddress() + */ + public PersonBuilder withAddress(Address address) { + this.address = address; + return this; + } + + /** + * Set person's address + * + * @param addressBuilder Builder for Address + * @return Builder for person + * @see Person#getAddress() + */ + public PersonBuilder withAddress(Builder
addressBuilder) { + return withAddress(addressBuilder.build()); + } + + /** + * Add document to person + * + * @param document Document + * @return Builder for person + * @see Person#getDocuments() + */ + public PersonBuilder addDocument(Document document) { + documents.add(document); + return this; + } + + /** + * Add document to person + * + * @param documentBuilder Builder for Document + * @return Builder for person + * @see Person#getDocuments() + */ + public PersonBuilder addDocument(Builder documentBuilder) { + return addDocument(documentBuilder.build()); + } + + /** + * Add document to person + * + * @param documents Documents + * @return Builder for person + * @see Person#getDocuments() + */ + public PersonBuilder addDocuments(Iterable documents) { + for (Document document : documents) { + addDocument(document); + } + return this; + } + + /** + * Add phone to person + * + * @param phone Phone + * @return Builder for person + * @see Person#getPhones() + */ + public PersonBuilder addPhone(PhoneAccount phone) { + phones.add(phone); + return this; + } + + /** + * Add phone to person + * + * @param phoneAccountBuilder Builder for Phone Account + * @return Builder for person + * @see Person#getPhones() + */ + public PersonBuilder addPhone(Builder phoneAccountBuilder) { + return addPhone(phoneAccountBuilder.build()); + } + + /** + * Add phone to person + * + * @param phones Phone + * @return Builder for person + * @see Person#getPhones() + */ + public PersonBuilder addPhones(Iterable phones) { + for (PhoneAccount phone : phones) { + addPhone(phone); + } + return this; + } + + /** + * Build the person + * + * @return Interface for person + * @see Person + */ + @Override + public Person build() { + return new SimplePerson(this); + } + + /** + * Implementation of {@code Person} + */ + private static class SimplePerson implements Person { + + private final PersonBuilder personBuilder; + + SimplePerson(PersonBuilder personBuilder) { + this.personBuilder = personBuilder; + } + + @Override + public String getName() { + return personBuilder.name; + } + + @Override + public String getBirthDate() { + return personBuilder.birthDate; + } + + @Override + public Address getAddress() { + return personBuilder.address; + } + + @Override + public List getDocuments() { + return personBuilder.documents; + } + + @Override + public List getPhones() { + return personBuilder.phones; + } + + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/PhoneAccountBuilder.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/PhoneAccountBuilder.java new file mode 100644 index 0000000..bad72d7 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/builder/PhoneAccountBuilder.java @@ -0,0 +1,104 @@ +package br.com.uol.pagseguro.api.common.domain.builder; + +import br.com.uol.pagseguro.api.common.domain.PhoneAccount; +import br.com.uol.pagseguro.api.common.domain.enums.PhoneType; +import br.com.uol.pagseguro.api.utils.Builder; + +/** + * Builder for phone account + * + * @author PagSeguro Internet Ltda. + */ +public final class PhoneAccountBuilder implements Builder { + + private String type; + private String areaCode; + private String number; + + /** + * Set type of phone account + * + * @param type Phone Account Type + * @return Builder for Phone Account + * @see PhoneAccount#getType() + */ + public PhoneAccountBuilder withType(String type) { + this.type = type; + return this; + } + + /** + * Set type of phone account + * + * @param type Phone Account Type + * @return Builder for Phone Account + * @see PhoneAccount#getType() + */ + public PhoneAccountBuilder withType(PhoneType type) { + this.type = type.getValue(); + return this; + } + + /** + * Set area code of phone account + * + * @param areaCode Phone Account Area Code + * @return Builder for Phone Account + * @see PhoneAccount#getAreaCode() + */ + public PhoneAccountBuilder withAreaCode(String areaCode) { + this.areaCode = areaCode; + return this; + } + + /** + * Set Number of phone account + * + * @param phoneNumber Phone Account Number + * @return Builder for Phone Account + * @see PhoneAccount#getNumber() + */ + public PhoneAccountBuilder withNumber(String phoneNumber) { + this.number = phoneNumber; + return this; + } + + /** + * Build the phone account + * + * @return Interface for Phone Account + * @see PhoneAccount + */ + @Override + public PhoneAccount build() { + return new SimplePhoneAccount(this); + } + + /** + * Implementation of {@code PhoneAccount} + */ + private static class SimplePhoneAccount implements PhoneAccount { + + private PhoneAccountBuilder phoneAccountBuilder; + + private SimplePhoneAccount(PhoneAccountBuilder phoneAccountBuilder) { + this.phoneAccountBuilder = phoneAccountBuilder; + } + + @Override + public String getType() { + return phoneAccountBuilder.type; + } + + @Override + public String getAreaCode() { + return phoneAccountBuilder.areaCode; + } + + @Override + public String getNumber() { + return phoneAccountBuilder.number; + } + + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/AddressV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/AddressV2XMLConverter.java new file mode 100644 index 0000000..d999659 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/AddressV2XMLConverter.java @@ -0,0 +1,129 @@ +package br.com.uol.pagseguro.api.common.domain.converterXML; + +import br.com.uol.pagseguro.api.common.domain.Address; + +import javax.xml.bind.annotation.XmlType; + +@XmlType(propOrder = {"postalCode", "street", "number", "complement", "district", "city", "state", "country"}) +public class AddressV2XMLConverter { + + private String postalCode; + private String street; + private String number; + private String complement; + private String district; + private String city; + private String state; + private String country; + + public AddressV2XMLConverter() { + } + + public AddressV2XMLConverter(String postalCode, String street, String number, String complement, + String district, String city, String state, String country) { + this.postalCode = postalCode; + this.street = street; + this.number = number; + this.complement = complement; + this.district = district; + this.city = city; + this.state = state; + this.country = country; + } + + public String getPostalCode() { + return postalCode; + } + + public AddressV2XMLConverter setPostalCode(String postalCode) { + this.postalCode = postalCode; + return this; + } + + public String getStreet() { + return street; + } + + public AddressV2XMLConverter setStreet(String street) { + this.street = street; + return this; + } + + public String getNumber() { + return number; + } + + public AddressV2XMLConverter setNumber(String number) { + this.number = number; + return this; + } + + public String getComplement() { + return complement; + } + + public AddressV2XMLConverter setComplement(String complement) { + this.complement = complement; + return this; + } + + public String getDistrict() { + return district; + } + + public AddressV2XMLConverter setDistrict(String district) { + this.district = district; + return this; + } + + public String getCity() { + return city; + } + + public AddressV2XMLConverter setCity(String city) { + this.city = city; + return this; + } + + public String getState() { + return state; + } + + public AddressV2XMLConverter setState(String state) { + this.state = state; + return this; + } + + public String getCountry() { + return country; + } + + public AddressV2XMLConverter setCountry(String country) { + this.country = country; + return this; + } + + /** + * Convert attributes in request XML + * + * @param address Address data + * @see Address + * @return AddressV2XMLConverter + */ + public AddressV2XMLConverter convert(Address address) { + if (address == null) { + return null; + } + + AddressV2XMLConverter convertedAddress = new AddressV2XMLConverter(); + convertedAddress.setPostalCode(address.getPostalCode()); + convertedAddress.setStreet(address.getStreet()); + convertedAddress.setNumber(address.getNumber()); + convertedAddress.setComplement(address.getComplement()); + convertedAddress.setDistrict(address.getDistrict()); + convertedAddress.setCity(address.getCity()); + convertedAddress.setState(address.getState()); + convertedAddress.setCountry(address.getCountry()); + return convertedAddress; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/DocumentV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/DocumentV2XMLConverter.java new file mode 100644 index 0000000..da254f4 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/DocumentV2XMLConverter.java @@ -0,0 +1,31 @@ +package br.com.uol.pagseguro.api.common.domain.converterXML; + +public class DocumentV2XMLConverter { + + private String type; + private String value; + + public DocumentV2XMLConverter() { + } + + public DocumentV2XMLConverter(String type, String value) { + this.type = type; + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/DocumentsV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/DocumentsV2XMLConverter.java new file mode 100644 index 0000000..ff5af89 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/DocumentsV2XMLConverter.java @@ -0,0 +1,55 @@ +package br.com.uol.pagseguro.api.common.domain.converterXML; + +import br.com.uol.pagseguro.api.common.domain.Document; + +import java.util.ArrayList; +import java.util.List; + +public class DocumentsV2XMLConverter { + + private ArrayList document; + + public ArrayList getDocument() { + if (document == null) { + document = new ArrayList(); + } + return document; + } + + public void setDocument(ArrayList document) { + this.document = document; + } + + /** + * Convert attributes in request XML + * + * @param documentAccountList Document data + * @see Document + * @return DocumentsV2XMLConverter + */ + public DocumentsV2XMLConverter convert(List documentAccountList) { + DocumentsV2XMLConverter convertedDocument = new DocumentsV2XMLConverter(); + convertedDocument.setDocument(parseToDocumentList(documentAccountList)); + return convertedDocument; + } + + /** + * Parse a Document list to a list of converted documents + * + * @param documentsList List of Document + * @see Document + * @return ArrayList List of converted documents + */ + private ArrayList parseToDocumentList(List documentsList) { + ArrayList documentList = new ArrayList(); + + for (Document document : documentsList) { + DocumentV2XMLConverter documentConverter = new DocumentV2XMLConverter( + document.getType().toString(), document.getValue() + ); + documentList.add(documentConverter); + } + + return documentList; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/PhoneV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/PhoneV2XMLConverter.java new file mode 100644 index 0000000..12df642 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/PhoneV2XMLConverter.java @@ -0,0 +1,47 @@ +package br.com.uol.pagseguro.api.common.domain.converterXML; + +import javax.xml.bind.annotation.XmlType; + +@XmlType(propOrder = {"type", "areaCode", "number"}) +public class PhoneV2XMLConverter { + + private String type; + private String areaCode; + private String number; + + public PhoneV2XMLConverter() { + } + + public PhoneV2XMLConverter(String type, String areaCode, String number) { + this.type = type; + this.areaCode = areaCode; + this.number = number; + } + + public String getType() { + return type; + } + + public PhoneV2XMLConverter setType(String type) { + this.type = type; + return this; + } + + public String getAreaCode() { + return areaCode; + } + + public PhoneV2XMLConverter setAreaCode(String areaCode) { + this.areaCode = areaCode; + return this; + } + + public String getNumber() { + return number; + } + + public PhoneV2XMLConverter setNumber(String number) { + this.number = number; + return this; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/PhonesV2XMLConverter.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/PhonesV2XMLConverter.java new file mode 100644 index 0000000..c175395 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/converterXML/PhonesV2XMLConverter.java @@ -0,0 +1,55 @@ +package br.com.uol.pagseguro.api.common.domain.converterXML; + +import br.com.uol.pagseguro.api.common.domain.PhoneAccount; + +import java.util.ArrayList; +import java.util.List; + +public class PhonesV2XMLConverter { + + private ArrayList phone; + + public ArrayList getPhone() { + if (phone == null){ + phone = new ArrayList(); + } + return phone; + } + + public void setPhone(ArrayList phone) { + this.phone = phone; + } + + /** + * Convert attributes in request XML + * + * @param phoneAccountList Phone Account data + * @see PhoneAccount + * @return PhonesV2XMLConverter + */ + public PhonesV2XMLConverter convert(List phoneAccountList) { + PhonesV2XMLConverter convertedPhone = new PhonesV2XMLConverter(); + convertedPhone.setPhone(parseToPhoneList(phoneAccountList)); + return convertedPhone; + } + + /** + * Parse a PhoneAccount list to a list of converted phone accounts + * + * @param phoneAccountList List of PhoneAccount + * @see PhoneAccount + * @return ArrayList List of converted phones + */ + private ArrayList parseToPhoneList(List phoneAccountList) { + ArrayList phoneList = new ArrayList(); + + for (PhoneAccount phoneAccount : phoneAccountList) { + PhoneV2XMLConverter phone = new PhoneV2XMLConverter( + phoneAccount.getType(), phoneAccount.getAreaCode(), phoneAccount.getNumber() + ); + phoneList.add(phone); + } + + return phoneList; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/AccountType.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/AccountType.java new file mode 100644 index 0000000..c8157b7 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/AccountType.java @@ -0,0 +1,59 @@ +package br.com.uol.pagseguro.api.common.domain.enums; + +/** + * AccountType. Used to define the type of the account. + * + * @author PagSeguro Internet Ltda. + */ +public enum AccountType { + + /** + * SELLER type + */ + SELLER("SELLER"), + + /** + * COMPANY type + */ + COMPANY("COMPANY"), + + /** + * Unrecognized + */ + UNRECOGNIZED(null); + + private final String value; + + /** + * Constructor + * + * @param value Enum value + */ + AccountType(String value) { + this.value = value; + } + + /** + * Get value + * + * @return Enum value + */ + public String getValue() { + return value; + } + + /** + * Get enum by value + * + * @param value Enum value + * @return Enum + */ + public static AccountType fromValue(String value) { + for (AccountType type : AccountType.values()) { + if (type.value != null && type.value.equalsIgnoreCase(value)) { + return type; + } + } + return UNRECOGNIZED; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/DocumentType.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/DocumentType.java index 7d25bfb..8d48981 100755 --- a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/DocumentType.java +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/DocumentType.java @@ -28,5 +28,5 @@ */ public enum DocumentType { - CPF, CPNJ; + CPF, CNPJ; } diff --git a/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/PhoneType.java b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/PhoneType.java new file mode 100644 index 0000000..195425e --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/common/domain/enums/PhoneType.java @@ -0,0 +1,64 @@ +package br.com.uol.pagseguro.api.common.domain.enums; + +/** + * PhoneType. Used to define the type of phone. + * + * @author PagSeguro Internet Ltda. + */ +public enum PhoneType { + + /** + * HOME status + */ + HOME("HOME"), + + /** + * MOBILE status + */ + MOBILE("MOBILE"), + + /** + * BUSINESS status + */ + BUSINESS("BUSINESS"), + + /** + * Unrecognized + */ + UNRECOGNIZED(null); + + private final String value; + + /** + * Constructor + * + * @param value Enum value + */ + PhoneType(String value) { + this.value = value; + } + + /** + * Get value + * + * @return Enum value + */ + public String getValue() { + return value; + } + + /** + * Get enum by value + * + * @param value Enum value + * @return Enum + */ + public static PhoneType fromValue(String value) { + for (PhoneType type : PhoneType.values()) { + if (type.value != null && type.value.equalsIgnoreCase(value)) { + return type; + } + } + return UNRECOGNIZED; + } +} diff --git a/source/src/main/java/br/com/uol/pagseguro/api/direct/preapproval/DirectPreApprovalsResource.java b/source/src/main/java/br/com/uol/pagseguro/api/direct/preapproval/DirectPreApprovalsResource.java index 175a1b7..2f43c86 100644 --- a/source/src/main/java/br/com/uol/pagseguro/api/direct/preapproval/DirectPreApprovalsResource.java +++ b/source/src/main/java/br/com/uol/pagseguro/api/direct/preapproval/DirectPreApprovalsResource.java @@ -131,7 +131,7 @@ public AccededDirectPreApproval accede( * @see AccededDirectPreApproval */ public AccededDirectPreApproval accede(DirectPreApprovalAccession directPreApprovalAccession) { - LOGGER.info("Iniciando adesão direct pre approval"); + LOGGER.info("Iniciando adesao direct pre approval"); LOGGER.info("Convertendo valores"); final RequestJson jsonBody = DIRECT_PRE_APPROVAL_REGISTRATION_JC.convert(directPreApprovalAccession); @@ -147,14 +147,14 @@ public AccededDirectPreApproval accede(DirectPreApprovalAccession directPreAppro pagSeguro.getHost()), headers, jsonBody.toHttpJsonRequestBody(CharSet.ENCODING_ISO)); LOGGER.debug(String.format("Resposta: %s", response.toString())); } catch (IOException e) { - LOGGER.error("Erro ao executar adesão direct pre approval"); + LOGGER.error("Erro ao executar adesao direct pre approval"); throw new PagSeguroLibException(e); } LOGGER.info("Parseando XML de resposta"); AccedeDirectPreApprovalResponseXML registeredPreApproval = response.parseXMLContent(pagSeguro, AccedeDirectPreApprovalResponseXML.class); LOGGER.info("Parseamento finalizado"); - LOGGER.info("Adesão direct pre approval finalizada"); + LOGGER.info("Adesao direct pre approval finalizada"); return registeredPreApproval; } @@ -565,7 +565,7 @@ public RetriedPayment paymentRetry(DirectPreApprovalPaymentRetry directPreApprov pagSeguro.getHost(),directPreApprovalPaymentRetry.getPreApprovalCode(), directPreApprovalPaymentRetry.getPaymentOrderCode()), headers, null); LOGGER.debug(String.format("Resposta: %s", response.toString())); } catch (IOException e) { - LOGGER.error("Erro ao executar adesão direct pre approval"); + LOGGER.error("Erro ao executar adesao direct pre approval"); throw new PagSeguroLibException(e); } LOGGER.info("Parseando XML de resposta"); @@ -645,7 +645,7 @@ public DataList listDirectPreApprovalByDateInte * @see DirectPreApprovalData */ public DataList listDirectPreApprovalByDateInterval(DirectPreApprovalByDateIntervalList directPreApprovalByDateIntervalList) { - LOGGER.info("Iniciando lista de recorrências dentro do intervalo de datas"); + LOGGER.info("Iniciando lista de recorrencias dentro do intervalo de datas"); LOGGER.info("Convertendo valores"); final RequestMap map = DIRECT_PRE_APPROVAL_BY_DATE_INTERVAL_LIST_MC.convert(directPreApprovalByDateIntervalList); @@ -660,7 +660,7 @@ public DataList listDirectPreApprovalByDateInte pagSeguro.getHost(), map.toUrlEncode(CharSet.ENCODING_UTF)), headers, null); LOGGER.debug(String.format("Resposta: %s", response.toString())); } catch (IOException e) { - LOGGER.error("Erro ao pesquisar pelas reconrrências dentro de um intervalo de datas"); + LOGGER.error("Erro ao pesquisar pelas reconrrencias dentro de um intervalo de datas"); throw new PagSeguroLibException(e); } LOGGER.info("Parseando XML de resposta"); @@ -668,7 +668,7 @@ public DataList listDirectPreApprovalByDateInte DataList directPreApprovalData = response.parseXMLContent(pagSeguro, DirectPreApprovalByDateIntervalListResponseXML.class); LOGGER.info("Parseamento finalizado"); - LOGGER.info("Listagem de recorrências por intervalo de datas finalizada"); + LOGGER.info("Listagem de recorrencias por intervalo de datas finalizada"); return directPreApprovalData; } @@ -695,7 +695,7 @@ public DataList listDirectPreApprovalByDayInter * @see DirectPreApprovalData */ public DataList listDirectPreApprovalByDayInterval(DirectPreApprovalByDayIntervalList directPreApprovalByDayIntervalList) { - LOGGER.info("Iniciando lista de recorrências dentro do intervalo de dias"); + LOGGER.info("Iniciando lista de recorrencias dentro do intervalo de dias"); LOGGER.info("Convertendo valores"); final RequestMap map = DIRECT_PRE_APPROVAL_BY_DAY_INTERVAL_LIST_MC.convert(directPreApprovalByDayIntervalList); @@ -710,7 +710,7 @@ public DataList listDirectPreApprovalByDayInter pagSeguro.getHost(), map.toUrlEncode(CharSet.ENCODING_UTF)), headers, null); LOGGER.debug(String.format("Resposta: %s", response.toString())); } catch (IOException e) { - LOGGER.error("Erro ao pesquisar pelas reconrrências dentro de um intervalo de dias"); + LOGGER.error("Erro ao pesquisar pelas reconrrencias dentro de um intervalo de dias"); throw new PagSeguroLibException(e); } LOGGER.info("Parseando XML de resposta"); @@ -718,7 +718,7 @@ public DataList listDirectPreApprovalByDayInter DataList directPreApprovalData = response.parseXMLContent(pagSeguro, DirectPreApprovalByDayIntervalListResponseXML.class); LOGGER.info("Parseamento finalizado"); - LOGGER.info("Listagem de recorrências por intervalo de dias finalizada"); + LOGGER.info("Listagem de recorrencias por intervalo de dias finalizada"); return directPreApprovalData; } diff --git a/source/src/main/java/br/com/uol/pagseguro/api/http/AuthenticatedHttpClient.java b/source/src/main/java/br/com/uol/pagseguro/api/http/AuthenticatedHttpClient.java index 4c8095a..b18dc8c 100755 --- a/source/src/main/java/br/com/uol/pagseguro/api/http/AuthenticatedHttpClient.java +++ b/source/src/main/java/br/com/uol/pagseguro/api/http/AuthenticatedHttpClient.java @@ -43,112 +43,132 @@ */ public class AuthenticatedHttpClient implements HttpClient { - private static Log LOGGER = LoggerFactory.getLogger(AuthenticatedHttpClient.class.getName()); + private static Log LOGGER = LoggerFactory.getLogger(AuthenticatedHttpClient.class.getName()); - private final HttpClient httpClient; + private final HttpClient httpClient; - private final String credentialQuery; + private final String credentialQuery; - /** - * Constructor - * - * @param httpClient Http client - * @param credential Credential - */ - public AuthenticatedHttpClient(HttpClient httpClient, Credential credential) { - this.httpClient = httpClient; - try { - this.credentialQuery = URLDecoder.decode(credential.asMap().toUrlEncode(CharSet.ENCODING_UTF), - CharSet.ENCODING_UTF); - } catch (UnsupportedEncodingException e) { - throw new PagSeguroLibException(e); + /** + * Constructor + * + * @param httpClient Http client + * @param credential Credential + */ + public AuthenticatedHttpClient(HttpClient httpClient, Credential credential) { + this.httpClient = httpClient; + try { + this.credentialQuery = URLDecoder.decode(credential.asMap().toUrlEncode(CharSet.ENCODING_UTF), + CharSet.ENCODING_UTF); + } catch (UnsupportedEncodingException e) { + throw new PagSeguroLibException(e); + } } - } - /** - * Execute the request - * - * @param method Http Method - * @param targetURL Target url - * @param headers Headers - * @param body Http Request Body - * @return Http Response - */ - @Override - public HttpResponse execute(HttpMethod method, String targetURL, Map headers, - HttpRequestBody body) throws IOException { - try { - return httpClient.execute(method, appendParameters(targetURL), headers, body); - } catch (URISyntaxException e) { - throw new PagSeguroLibException(e); + /** + * Execute the request + * + * @param method Http Method + * @param targetURL Target url + * @param headers Headers + * @param body Http Request Body + * @return Http Response + */ + @Override + public HttpResponse execute(HttpMethod method, String targetURL, Map headers, + HttpRequestBody body) throws IOException { + try { + return httpClient.execute(method, appendParameters(targetURL), headers, body); + } catch (URISyntaxException e) { + throw new PagSeguroLibException(e); + } } - } - //@TODO validar json - public HttpResponse executeJson(HttpMethod method, String targetURL, Map headers, - HttpJsonRequestBody body) throws IOException { - try { - return httpClient.executeJson(method, appendParameters(targetURL), headers, body); - } catch (URISyntaxException e) { - throw new PagSeguroLibException(e); + + /** + * Execute the request + * + * @param method Http Method + * @param targetURL Target url + * @param headers Headers + * @param body Http XML Request Body + * @return Http Response + */ + @Override + public HttpResponse executeXML(HttpMethod method, String targetURL, Map headers, + HttpXMLRequestBody body) throws IOException { + try { + return httpClient.executeXML(method, appendParameters(targetURL), headers, body); + } catch (URISyntaxException e) { + throw new PagSeguroLibException(e); + } + } + + //@TODO validar json + public HttpResponse executeJson(HttpMethod method, String targetURL, Map headers, + HttpJsonRequestBody body) throws IOException { + try { + return httpClient.executeJson(method, appendParameters(targetURL), headers, body); + } catch (URISyntaxException e) { + throw new PagSeguroLibException(e); + } } - } - /** - * Append parameters to uri - * - * @param uri Uri - * @return Url with parameters - */ - private String appendParameters(String uri) throws UnsupportedEncodingException, - URISyntaxException { - return appendCorrelationId(appendCredential(uri)); - } + /** + * Append parameters to uri + * + * @param uri Uri + * @return Url with parameters + */ + private String appendParameters(String uri) throws UnsupportedEncodingException, + URISyntaxException { + return appendCorrelationId(appendCredential(uri)); + } - /** - * Add correlation id to url - * - * @param uri Url - * @return Url with correlation id - * @throws URISyntaxException if invalid url is used - * @throws UnsupportedEncodingException if not accepted encode is used - */ - public String appendCorrelationId(String uri) throws URISyntaxException, - UnsupportedEncodingException { - URI oldUri = new URI(uri); - String newQuery = oldUri.getQuery(); - String correlationId = UUID.randomUUID().toString(); - RequestMap correlationMap = new RequestMap(); - correlationMap.putString("correlationId", correlationId); - LOGGER.info(String.format("Correlation Id: %s", correlationId)); - String correlationIdQuery = URLDecoder.decode(correlationMap.toUrlEncode(CharSet.ENCODING_UTF), - CharSet.ENCODING_UTF); - if (newQuery == null) { - newQuery = correlationIdQuery; - } else { - newQuery += "&" + correlationIdQuery; + /** + * Add correlation id to url + * + * @param uri Url + * @return Url with correlation id + * @throws URISyntaxException if invalid url is used + * @throws UnsupportedEncodingException if not accepted encode is used + */ + public String appendCorrelationId(String uri) throws URISyntaxException, + UnsupportedEncodingException { + URI oldUri = new URI(uri); + String newQuery = oldUri.getQuery(); + String correlationId = UUID.randomUUID().toString(); + RequestMap correlationMap = new RequestMap(); + correlationMap.putString("correlationId", correlationId); + LOGGER.info(String.format("Correlation Id: %s", correlationId)); + String correlationIdQuery = URLDecoder.decode(correlationMap.toUrlEncode(CharSet.ENCODING_UTF), + CharSet.ENCODING_UTF); + if (newQuery == null) { + newQuery = correlationIdQuery; + } else { + newQuery += "&" + correlationIdQuery; + } + return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), newQuery, + oldUri.getFragment()).toString(); } - return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), newQuery, - oldUri.getFragment()).toString(); - } - /** - * Add credential to url - * - * @param uri Url - * @return Url with credential - * @throws URISyntaxException if invalid url is used - * @throws UnsupportedEncodingException if not accepted encode is used - */ - public String appendCredential(String uri) throws URISyntaxException, - UnsupportedEncodingException { - URI oldUri = new URI(uri); - String newQuery = oldUri.getQuery(); - if (newQuery == null) { - newQuery = credentialQuery; - } else { - newQuery += "&" + credentialQuery; + /** + * Add credential to url + * + * @param uri Url + * @return Url with credential + * @throws URISyntaxException if invalid url is used + * @throws UnsupportedEncodingException if not accepted encode is used + */ + public String appendCredential(String uri) throws URISyntaxException, + UnsupportedEncodingException { + URI oldUri = new URI(uri); + String newQuery = oldUri.getQuery(); + if (newQuery == null) { + newQuery = credentialQuery; + } else { + newQuery += "&" + credentialQuery; + } + return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), newQuery, + oldUri.getFragment()).toString(); } - return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), newQuery, - oldUri.getFragment()).toString(); - } } diff --git a/source/src/main/java/br/com/uol/pagseguro/api/http/HttpClient.java b/source/src/main/java/br/com/uol/pagseguro/api/http/HttpClient.java index 16364be..648a4cf 100755 --- a/source/src/main/java/br/com/uol/pagseguro/api/http/HttpClient.java +++ b/source/src/main/java/br/com/uol/pagseguro/api/http/HttpClient.java @@ -30,20 +30,33 @@ */ public interface HttpClient { - /** - * Execute the requests - * - * @param method Http method - * @param targetURL target url - * @param headers Headers - * @param body Body - * @return Http response - * @throws IOException if a problem occurs - */ - HttpResponse execute(HttpMethod method, String targetURL, Map headers, HttpRequestBody body) - throws IOException; + /** + * Execute the requests + * + * @param method Http method + * @param targetURL target url + * @param headers Headers + * @param body Body + * @return Http response + * @throws IOException if a problem occurs + */ + HttpResponse execute(HttpMethod method, String targetURL, Map headers, HttpRequestBody body) + throws IOException; - //TODO: validate if need to change to only execute without to have to implement it in every class that extends HttpClient, maybe create an JsonCliente - HttpResponse executeJson(HttpMethod method, String targetURL, Map headers, HttpJsonRequestBody body) - throws IOException; + /** + * Execute the requests + * + * @param method Http method + * @param targetURL target url + * @param headers Headers + * @param body Body + * @return Http response + * @throws IOException if a problem occurs + */ + HttpResponse executeXML(HttpMethod method, String targetURL, Map headers, HttpXMLRequestBody body) + throws IOException; + + //TODO: validate if need to change to only execute without to have to implement it in every class that extends HttpClient, maybe create an JsonCliente + HttpResponse executeJson(HttpMethod method, String targetURL, Map headers, HttpJsonRequestBody body) + throws IOException; } diff --git a/source/src/main/java/br/com/uol/pagseguro/api/http/HttpXMLRequestBody.java b/source/src/main/java/br/com/uol/pagseguro/api/http/HttpXMLRequestBody.java new file mode 100644 index 0000000..0ee9ce5 --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/http/HttpXMLRequestBody.java @@ -0,0 +1,77 @@ +package br.com.uol.pagseguro.api.http; + +/** + * Body to http request + * + * @author PagSeguro Internet Ltda. + */ +public class HttpXMLRequestBody { + + private final String content; + private final String charset; + private final String contentType; + + /** + * Constructor + * + * @param contentType Content type + * @param content Content + * @param charset Encoding + */ + public HttpXMLRequestBody(String contentType, String content, String charset) { + if (content == null || contentType == null || charset == null) { + throw new IllegalArgumentException(); + } + this.content = content; + this.charset = charset; + this.contentType = contentType; + } + + /** + * Get content + * + * @return Content + */ + public String getContent() { + return content; + } + + /** + * Get content type with charset + * + * @return Content type with charset + */ + public String getContentTypeWithCharset() { + return getContentType() + "; charset=" + getCharset(); + } + + /** + * Get content type + * + * @return Content type + */ + public String getContentType() { + return contentType; + } + + /** + * Get charset + * + * @return Charset + */ + public String getCharset() { + return charset; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof HttpXMLRequestBody)) return false; + + HttpXMLRequestBody that = (HttpXMLRequestBody) o; + + if (content != null ? !content.equals(that.content) : that.content != null) return false; + if (charset != null ? !charset.equals(that.charset) : that.charset != null) return false; + return contentType != null ? contentType.equals(that.contentType) : that.contentType == null; + } +} \ No newline at end of file diff --git a/source/src/main/java/br/com/uol/pagseguro/api/http/JSEHttpClient.java b/source/src/main/java/br/com/uol/pagseguro/api/http/JSEHttpClient.java index 89c5c27..a10c7a9 100755 --- a/source/src/main/java/br/com/uol/pagseguro/api/http/JSEHttpClient.java +++ b/source/src/main/java/br/com/uol/pagseguro/api/http/JSEHttpClient.java @@ -44,276 +44,351 @@ */ public class JSEHttpClient implements HttpClient { - private static Log LOGGER = LoggerFactory.getLogger(JSEHttpClient.class.getName()); - private static String DEFAULT_RESPONSE_CHARSET = "ISO-8859-1"; - private final static String LIB_VERSION = "4.2.0"; - - /** - * Execute the communication with api. - * - * @param method Http method - * @param targetURL target url - * @param headers Headers - * @param body Body - * @return Http Response - */ - @Override - public HttpResponse execute(HttpMethod method, String targetURL, Map headers, - HttpRequestBody body) throws IOException { - - LOGGER.info(String.format("Executando [%s] em [%s]", method.toString(), targetURL)); - - HttpURLConnection connection = null; - try { - final URL url = new URL(targetURL); - LOGGER.info("Abrindo conexao"); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod(method.toString()); - connection.setUseCaches(false); - - writeHeaders(connection, headers); - LOGGER.info("Escrevendo body"); - writeBody(connection, body); - - // le response response - final String responseCharset = getResponseCharset(connection); - LOGGER.info("Lendo resposta"); - final InputStream responseStream = getResponseStream(connection); - final String responseString = getResponseString(responseStream, responseCharset); - return new HttpResponse(connection.getResponseCode(), responseString); - } finally { - if (connection != null) { - LOGGER.info("Fechando conexao"); - connection.disconnect(); - } - } - } - - /** - * Execute the communication with api. - * - * @param method Http method - * @param targetURL target url - * @param headers Headers - * @param body Body - * @return Http Response - */ - @Override - public HttpResponse executeJson(HttpMethod method, String targetURL, Map headers, - HttpJsonRequestBody body) throws IOException { - - LOGGER.info(String.format("Executando [%s] em [%s]", method.toString(), targetURL)); - - HttpURLConnection connection = null; - try { - final URL url = new URL(targetURL); - LOGGER.info("Abrindo conexao"); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod(method.toString()); - connection.setUseCaches(false); - - writeHeaders(connection, headers); - LOGGER.info("Escrevendo body"); - writeBody(connection, body); - - // le response response - final String responseCharset = getResponseCharset(connection); - LOGGER.info("Lendo resposta"); - final InputStream responseStream = getResponseStream(connection); - final String responseString = getResponseString(responseStream, responseCharset); - return new HttpResponse(connection.getResponseCode(), responseString); - } finally { - if (connection != null) { - LOGGER.info("Fechando conexao"); - connection.disconnect(); - } - } - } - //@TODO: documentar e ver se o cancel ainda funciona - public HttpResponse execute(HttpMethod method, String targetURL, Map headers) throws IOException { - - LOGGER.info(String.format("Executando [%s] em [%s]", method.toString(), targetURL)); - - HttpURLConnection connection = null; - try { - final URL url = new URL(targetURL); - LOGGER.info("Abrindo conexao"); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod(method.toString()); - connection.setUseCaches(false); - - writeHeaders(connection, headers); - - // le response response - final String responseCharset = getResponseCharset(connection); - LOGGER.info("Lendo resposta"); - final InputStream responseStream = getResponseStream(connection); - final String responseString = getResponseString(responseStream, responseCharset); - return new HttpResponse(connection.getResponseCode(), responseString); - } finally { - if (connection != null) { - LOGGER.info("Fechando conexao"); - connection.disconnect(); - } - } - } - - /** - * Write headers on request - * - * @param connection Connection - * @param headers Headers - */ - private static void writeHeaders(HttpURLConnection connection, Map headers) { - if (headers == null) { - headers = new HashMap(); - } + private static Log LOGGER = LoggerFactory.getLogger(JSEHttpClient.class.getName()); + private static String DEFAULT_RESPONSE_CHARSET = "ISO-8859-1"; + private final static String LIB_VERSION = "4.2.0"; - headers.put("lib-description", "java:" + LIB_VERSION); - headers.put("language-engine-description", "java:" + System.getProperty("java.version")); + /** + * Execute the communication with api. + * + * @param method Http method + * @param targetURL target url + * @param headers Headers + * @param body Body + * @return Http Response + */ + @Override + public HttpResponse execute(HttpMethod method, String targetURL, Map headers, + HttpRequestBody body) throws IOException { - for (Entry e : headers.entrySet()) { - connection.setRequestProperty(e.getKey(), e.getValue()); - } + LOGGER.info(String.format("Executando [%s] em [%s]", method.toString(), targetURL)); - } - - /** - * Write body on request - * - * @param connection Connection - * @param body Body - */ - private static void writeBody(HttpURLConnection connection, HttpRequestBody body) throws - IOException { - if (body == null) { - return; - } - final String charset = body.getCharset(); - final String content = body.getContent(); - //connection.setRequestProperty("Content-Type", body.getContentTypeWithCharset()); - //connection.setRequestProperty("Content-Length", Integer.toString(content.getBytes(charset).length)); - connection.setDoOutput(true); - - DataOutputStream wr = null; - BufferedWriter buffWr = null; - try { - wr = new DataOutputStream(connection.getOutputStream()); - buffWr = new BufferedWriter(new OutputStreamWriter(wr, charset)); - buffWr.write(content); - } finally { - if (buffWr != null) { - buffWr.close(); - } - if (wr != null) { - wr.close(); - } + HttpURLConnection connection = null; + try { + final URL url = new URL(targetURL); + LOGGER.info("Abrindo conexao"); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod(method.toString()); + connection.setUseCaches(false); + + writeHeaders(connection, headers); + LOGGER.info("Escrevendo body"); + writeBody(connection, body); + + // le response response + final String responseCharset = getResponseCharset(connection); + LOGGER.info("Lendo resposta"); + final InputStream responseStream = getResponseStream(connection); + final String responseString = getResponseString(responseStream, responseCharset); + return new HttpResponse(connection.getResponseCode(), responseString); + } finally { + if (connection != null) { + LOGGER.info("Fechando conexao"); + connection.disconnect(); + } + } } - } - - /** - * Write body on request - * - * @param connection Connection - * @param body Body - */ - private static void writeBody(HttpURLConnection connection, HttpJsonRequestBody body) throws - IOException { - if (body == null) { - return; + + /** + * Execute the communication with api. + * + * @param method Http method + * @param targetURL target url + * @param headers Headers + * @param body Body + * @return Http Response + */ + @Override + public HttpResponse executeXML(HttpMethod method, String targetURL, Map headers, + HttpXMLRequestBody body) throws IOException { + + LOGGER.info(String.format("Executando [%s] em [%s]", method.toString(), targetURL)); + + HttpURLConnection connection = null; + try { + final URL url = new URL(targetURL); + LOGGER.info("Abrindo conexao"); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod(method.toString()); + connection.setUseCaches(false); + + writeHeaders(connection, headers); + LOGGER.info("Escrevendo body"); + writeBody(connection, body); + + // le response response + final String responseCharset = getResponseCharset(connection); + LOGGER.info("Lendo resposta"); + final InputStream responseStream = getResponseStream(connection); + final String responseString = getResponseString(responseStream, responseCharset); + return new HttpResponse(connection.getResponseCode(), responseString); + } finally { + if (connection != null) { + LOGGER.info("Fechando conexao"); + connection.disconnect(); + } + } } - final String charset = body.getCharset(); - final String content = body.getContent(); - //connection.setRequestProperty("Content-Type", body.getContentTypeWithCharset()); - //connection.setRequestProperty("Content-Length", Integer.toString(content.getBytes(charset).length)); - connection.setDoOutput(true); - - DataOutputStream wr = null; - BufferedWriter buffWr = null; - try { - wr = new DataOutputStream(connection.getOutputStream()); - buffWr = new BufferedWriter(new OutputStreamWriter(wr, charset)); - buffWr.write(content); - } finally { - if (buffWr != null) { - buffWr.close(); - } - if (wr != null) { - wr.close(); - } + + /** + * Execute the communication with api. + * + * @param method Http method + * @param targetURL target url + * @param headers Headers + * @param body Body + * @return Http Response + */ + @Override + public HttpResponse executeJson(HttpMethod method, String targetURL, Map headers, + HttpJsonRequestBody body) throws IOException { + + LOGGER.info(String.format("Executando [%s] em [%s]", method.toString(), targetURL)); + + HttpURLConnection connection = null; + try { + final URL url = new URL(targetURL); + LOGGER.info("Abrindo conexao"); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod(method.toString()); + connection.setUseCaches(false); + + writeHeaders(connection, headers); + LOGGER.info("Escrevendo body"); + writeBody(connection, body); + + // le response response + final String responseCharset = getResponseCharset(connection); + LOGGER.info("Lendo resposta"); + final InputStream responseStream = getResponseStream(connection); + final String responseString = getResponseString(responseStream, responseCharset); + return new HttpResponse(connection.getResponseCode(), responseString); + } finally { + if (connection != null) { + LOGGER.info("Fechando conexao"); + connection.disconnect(); + } + } } - } - - /** - * Get response as string - * - * @param responseStream Response Stream - * @param responseCharset Response charset - * @return Response string - */ - private static String getResponseString(InputStream responseStream, String responseCharset) throws - IOException { - if (responseStream == null || responseCharset == null) { - throw new IllegalArgumentException(); + + //@TODO: documentar e ver se o cancel ainda funciona + public HttpResponse execute(HttpMethod method, String targetURL, Map headers) throws IOException { + + LOGGER.info(String.format("Executando [%s] em [%s]", method.toString(), targetURL)); + + HttpURLConnection connection = null; + try { + final URL url = new URL(targetURL); + LOGGER.info("Abrindo conexao"); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod(method.toString()); + connection.setUseCaches(false); + + writeHeaders(connection, headers); + + // le response response + final String responseCharset = getResponseCharset(connection); + LOGGER.info("Lendo resposta"); + final InputStream responseStream = getResponseStream(connection); + final String responseString = getResponseString(responseStream, responseCharset); + return new HttpResponse(connection.getResponseCode(), responseString); + } finally { + if (connection != null) { + LOGGER.info("Fechando conexao"); + connection.disconnect(); + } + } } - BufferedReader rd = null; - try { - rd = new BufferedReader(new InputStreamReader(responseStream, responseCharset)); - final StringBuilder responseString = new StringBuilder(); - String line; - while ((line = rd.readLine()) != null) { - responseString.append(line); - } - return responseString.toString(); - } finally { - if (rd != null) { - rd.close(); - } + + /** + * Write headers on request + * + * @param connection Connection + * @param headers Headers + */ + private static void writeHeaders(HttpURLConnection connection, Map headers) { + if (headers == null) { + headers = new HashMap(); + } + + headers.put("lib-description", "java:" + LIB_VERSION); + headers.put("language-engine-description", "java:" + System.getProperty("java.version")); + + for (Entry e : headers.entrySet()) { + connection.setRequestProperty(e.getKey(), e.getValue()); + } + } - } - - /** - * Get response stream - * - * @param connection Connection - * @return Input Stream - */ - private static InputStream getResponseStream(HttpURLConnection connection) throws IOException { - if (connection == null) { - throw new IllegalArgumentException(); + + /** + * Write body on request + * + * @param connection Connection + * @param body Body + */ + private static void writeBody(HttpURLConnection connection, HttpRequestBody body) throws + IOException { + if (body == null) { + return; + } + final String charset = body.getCharset(); + final String content = body.getContent(); + //connection.setRequestProperty("Content-Type", body.getContentTypeWithCharset()); + //connection.setRequestProperty("Content-Length", Integer.toString(content.getBytes(charset).length)); + connection.setDoOutput(true); + + DataOutputStream wr = null; + BufferedWriter buffWr = null; + try { + wr = new DataOutputStream(connection.getOutputStream()); + buffWr = new BufferedWriter(new OutputStreamWriter(wr, charset)); + buffWr.write(content); + } finally { + if (buffWr != null) { + buffWr.close(); + } + if (wr != null) { + wr.close(); + } + } } - InputStream errorStream = connection.getErrorStream(); - if (errorStream != null) { - return errorStream; + + /** + * Write body on request + * + * @param connection Connection + * @param body Body + */ + private static void writeBody(HttpURLConnection connection, HttpXMLRequestBody body) throws + IOException { + if (body == null) { + return; + } + final String charset = body.getCharset(); + final String content = body.getContent(); + //connection.setRequestProperty("Content-Type", body.getContentTypeWithCharset()); + //connection.setRequestProperty("Content-Length", Integer.toString(content.getBytes(charset).length)); + connection.setDoOutput(true); + + DataOutputStream wr = null; + BufferedWriter buffWr = null; + try { + wr = new DataOutputStream(connection.getOutputStream()); + buffWr = new BufferedWriter(new OutputStreamWriter(wr, charset)); + buffWr.write(content); + } finally { + if (buffWr != null) { + buffWr.close(); + } + if (wr != null) { + wr.close(); + } + } } - return connection.getInputStream(); - } - - /** - * Get response charset - * - * @param connection Coonection - * @return Response charset - */ - private static String getResponseCharset(HttpURLConnection connection) { - if (connection == null) { - throw new IllegalArgumentException(); + + /** + * Write body on request + * + * @param connection Connection + * @param body Body + */ + private static void writeBody(HttpURLConnection connection, HttpJsonRequestBody body) throws + IOException { + if (body == null) { + return; + } + final String charset = body.getCharset(); + final String content = body.getContent(); + //connection.setRequestProperty("Content-Type", body.getContentTypeWithCharset()); + //connection.setRequestProperty("Content-Length", Integer.toString(content.getBytes(charset).length)); + connection.setDoOutput(true); + + DataOutputStream wr = null; + BufferedWriter buffWr = null; + try { + wr = new DataOutputStream(connection.getOutputStream()); + buffWr = new BufferedWriter(new OutputStreamWriter(wr, charset)); + buffWr.write(content); + } finally { + if (buffWr != null) { + buffWr.close(); + } + if (wr != null) { + wr.close(); + } + } } - final String contentType = connection.getContentType(); - if (contentType == null) { - return DEFAULT_RESPONSE_CHARSET; + + /** + * Get response as string + * + * @param responseStream Response Stream + * @param responseCharset Response charset + * @return Response string + */ + private static String getResponseString(InputStream responseStream, String responseCharset) throws + IOException { + if (responseStream == null || responseCharset == null) { + throw new IllegalArgumentException(); + } + BufferedReader rd = null; + try { + rd = new BufferedReader(new InputStreamReader(responseStream, responseCharset)); + final StringBuilder responseString = new StringBuilder(); + String line; + while ((line = rd.readLine()) != null) { + responseString.append(line); + } + return responseString.toString(); + } finally { + if (rd != null) { + rd.close(); + } + } } - final String[] values = contentType.split(";"); - if (values == null) { - return DEFAULT_RESPONSE_CHARSET; + /** + * Get response stream + * + * @param connection Connection + * @return Input Stream + */ + private static InputStream getResponseStream(HttpURLConnection connection) throws IOException { + if (connection == null) { + throw new IllegalArgumentException(); + } + InputStream errorStream = connection.getErrorStream(); + if (errorStream != null) { + return errorStream; + } + return connection.getInputStream(); } - for (String value : values) { - value = value.trim(); - if (value.toLowerCase().startsWith("charset=")) { - return value.substring("charset=".length()); - } + + /** + * Get response charset + * + * @param connection Coonection + * @return Response charset + */ + private static String getResponseCharset(HttpURLConnection connection) { + if (connection == null) { + throw new IllegalArgumentException(); + } + final String contentType = connection.getContentType(); + if (contentType == null) { + return DEFAULT_RESPONSE_CHARSET; + } + final String[] values = contentType.split(";"); + + if (values == null) { + return DEFAULT_RESPONSE_CHARSET; + } + for (String value : values) { + value = value.trim(); + if (value.toLowerCase().startsWith("charset=")) { + return value.substring("charset=".length()); + } + } + return DEFAULT_RESPONSE_CHARSET; } - return DEFAULT_RESPONSE_CHARSET; - } } diff --git a/source/src/main/java/br/com/uol/pagseguro/api/utils/RequestXML.java b/source/src/main/java/br/com/uol/pagseguro/api/utils/RequestXML.java new file mode 100644 index 0000000..7ddb09d --- /dev/null +++ b/source/src/main/java/br/com/uol/pagseguro/api/utils/RequestXML.java @@ -0,0 +1,66 @@ +package br.com.uol.pagseguro.api.utils; + +import br.com.uol.pagseguro.api.http.HttpXMLRequestBody; + +import java.io.UnsupportedEncodingException; + +/** + * Class used to convert the data on a XML string to pass the parameters of the requests in api + * + * @author PagSeguro Internet Ltda. + */ +public class RequestXML { + + public String xmlBody = ""; + + public RequestXML() { + } + + public RequestXML(String xmlBody) { + this.xmlBody = xmlBody; + } + + public String getXmlBody() { + return xmlBody; + } + + public RequestXML setXmlBody(String xmlBody) { + this.xmlBody = xmlBody; + return this; + } + + /** + * Convert to http request body + * + * @param charset Encoding + * @return Http Request Body + * @see HttpXMLRequestBody + * @throws UnsupportedEncodingException if not accepted encode is used + */ + public HttpXMLRequestBody toHttpXMLRequestBody(String charset) throws UnsupportedEncodingException { + return new HttpXMLRequestBody( + String.format("application/xml; charset=%s", charset), + encodeBodyContent(xmlBody, charset), + charset); + } + + /** + * Encode the body content to PagSeguro API requirement + * + * @param toEncodeString String to be encoded + * @param charset Charset used to encode + * @return String body encoded by charset param + * @throws UnsupportedEncodingException if not accepted encode is used + */ + public String encodeBodyContent(String toEncodeString, String charset) throws UnsupportedEncodingException { + byte[] ptext = toEncodeString.getBytes(); + return new String(ptext, charset); + } + + @Override + public String toString() { + return "RequestXML{" + + "xmlBody='" + xmlBody + '\'' + + '}'; + } +} diff --git a/source/src/test/java/br/com/uol/pagseguro/api/common/domain/converter/CreditCardV2MapConverterTest.java b/source/src/test/java/br/com/uol/pagseguro/api/common/domain/converter/CreditCardV2MapConverterTest.java index 28e1db5..e30104f 100755 --- a/source/src/test/java/br/com/uol/pagseguro/api/common/domain/converter/CreditCardV2MapConverterTest.java +++ b/source/src/test/java/br/com/uol/pagseguro/api/common/domain/converter/CreditCardV2MapConverterTest.java @@ -41,7 +41,7 @@ public void setUp() throws Exception { .withValue("cpf") ) .addDocument(new DocumentBuilder() - .withType(DocumentType.CPNJ) + .withType(DocumentType.CNPJ) .withValue("cnpj") ) .withBithDate(dateFormat.parse("2016/11/09 00:00:00")) diff --git a/source/src/test/java/br/com/uol/pagseguro/api/common/domain/converter/CreditCardV3MapConverterTest.java b/source/src/test/java/br/com/uol/pagseguro/api/common/domain/converter/CreditCardV3MapConverterTest.java index ff622ae..e769e7c 100755 --- a/source/src/test/java/br/com/uol/pagseguro/api/common/domain/converter/CreditCardV3MapConverterTest.java +++ b/source/src/test/java/br/com/uol/pagseguro/api/common/domain/converter/CreditCardV3MapConverterTest.java @@ -41,7 +41,7 @@ public void setUp() throws Exception { .withValue("cpf") ) .addDocument(new DocumentBuilder() - .withType(DocumentType.CPNJ) + .withType(DocumentType.CNPJ) .withValue("cnpj") ) .withBithDate(dateFormat.parse("2016/11/09 00:00:00")) diff --git a/source/src/test/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalRequestSearchByIntervalTest.java b/source/src/test/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalRequestSearchByIntervalTest.java index d28f533..008a01e 100644 --- a/source/src/test/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalRequestSearchByIntervalTest.java +++ b/source/src/test/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalRequestSearchByIntervalTest.java @@ -1,138 +1,140 @@ -package br.com.uol.pagseguro.api.preapproval.search; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Iterator; - -import br.com.uol.pagseguro.api.Resource4Test; -import br.com.uol.pagseguro.api.common.domain.DataList; -import br.com.uol.pagseguro.api.common.domain.PreApprovalStatus; -import br.com.uol.pagseguro.api.exception.PagSeguroBadRequestException; -import br.com.uol.pagseguro.api.exception.PagSeguroLibException; -import br.com.uol.pagseguro.api.exception.ServerError; -import br.com.uol.pagseguro.api.exception.ServerErrors; -import br.com.uol.pagseguro.api.http.HttpMethod; -import br.com.uol.pagseguro.api.http.HttpRequestBody; -import br.com.uol.pagseguro.api.http.HttpResponse; - -import static org.junit.Assert.*; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -/** - * @author PagSeguro Internet Ltda. - */ -@RunWith(PowerMockRunner.class) -public class PreApprovalRequestSearchByIntervalTest extends Resource4Test { - - private PreApprovalSearchByInterval preApprovalSearchByInterval; - - @Before - public void setUp() throws Exception { - preApprovalSearchByInterval = new PreApprovalSearchByInterval(5); - } - - @Test - public void shouldSearch() throws Exception { - String responseAsString = "" + - "" + - "2" + - "1" + - "1" + - "2016-11-09T00:00:00.000-02:00" + - "" + - "" + - "Pre Approval 3" + - "code 3" + - "2016-11-09T00:00:00.000-02:00" + - "tracker" + - "INITIATED" + - "reference" + - "2016-11-09T23:59:59.000-02:00" + - "auto" + - "" + - "" + - "Pre Approval 4" + - "code 4" + - "2016-11-09T00:00:00.000-02:00" + - "tracker" + - "INITIATED" + - "reference" + - "2016-11-09T23:59:59.000-02:00" + - "auto" + - "" + - "" + - ""; - HttpResponse response = new HttpResponse(200, responseAsString); - when(httpClient.execute(any(HttpMethod.class), anyString(), anyMap(), - any(HttpRequestBody.class))).thenReturn(response); - - DataList data = preApprovalSearchByInterval.execute(pagSeguro, - httpClient); - - assertEquals(new Integer(1), data.getTotalPages()); - assertEquals(false, data.isEmpty()); - - Iterator authorizationSummaryIterator = - (Iterator) data.getData().iterator(); - - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - PreApprovalSummary preApproval = authorizationSummaryIterator.next(); - assertEquals("code 3", preApproval.getCode()); - assertEquals("Pre Approval 3", preApproval.getName()); - assertEquals("tracker", preApproval.getTracker()); - assertEquals(PreApprovalStatus.Status.INITIATED, preApproval.getStatus().getStatus()); - assertEquals("reference", preApproval.getReference()); - assertEquals(dateFormat.parse("2016-11-09 23:59:59"), preApproval.getLastEvent()); - assertEquals(dateFormat.parse("2016-11-09 00:00:00"), preApproval.getDate()); - assertEquals("auto", preApproval.getCharge()); - - preApproval = authorizationSummaryIterator.next(); - assertEquals("code 4", preApproval.getCode()); - assertEquals("Pre Approval 4", preApproval.getName()); - assertEquals("tracker", preApproval.getTracker()); - assertEquals(PreApprovalStatus.Status.INITIATED, preApproval.getStatus().getStatus()); - assertEquals("reference", preApproval.getReference()); - assertEquals(dateFormat.parse("2016-11-09 23:59:59"), preApproval.getLastEvent()); - assertEquals(dateFormat.parse("2016-11-09 00:00:00"), preApproval.getDate()); - assertEquals("auto", preApproval.getCharge()); - } - - @Test - public void shouldThrowsBadRequest() { - try { - String responseAsString = "" + - "" + - "" + - "0001" + - "Interval is required." + - "" + - ""; - HttpResponse response = new HttpResponse(400, responseAsString); - when(httpClient.execute(any(HttpMethod.class), anyString(), anyMap(), - any(HttpRequestBody.class))).thenReturn(response); - - preApprovalSearchByInterval.execute(pagSeguro, httpClient); - } catch (PagSeguroBadRequestException e) { - ServerErrors errors = e.getErrors(); - ServerError error = errors.getErrors().iterator().next(); - assertEquals(new Integer(0001), error.getCode()); - assertEquals("Interval is required.", error.getMessage()); - } catch (Exception e) { - } - } - - @Test(expected = PagSeguroLibException.class) - public void shouldThrowsErrorLib() throws Exception { - when(httpClient.execute(any(HttpMethod.class), anyString(), anyMap(), - any(HttpRequestBody.class))).thenThrow(new IOException()); - preApprovalSearchByInterval.execute(pagSeguro, httpClient); \ No newline at end of file +package br.com.uol.pagseguro.api.preapproval.search; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Iterator; + +import br.com.uol.pagseguro.api.Resource4Test; +import br.com.uol.pagseguro.api.common.domain.DataList; +import br.com.uol.pagseguro.api.common.domain.PreApprovalStatus; +import br.com.uol.pagseguro.api.exception.PagSeguroBadRequestException; +import br.com.uol.pagseguro.api.exception.PagSeguroLibException; +import br.com.uol.pagseguro.api.exception.ServerError; +import br.com.uol.pagseguro.api.exception.ServerErrors; +import br.com.uol.pagseguro.api.http.HttpMethod; +import br.com.uol.pagseguro.api.http.HttpRequestBody; +import br.com.uol.pagseguro.api.http.HttpResponse; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +/** + * @author PagSeguro Internet Ltda. + */ +@RunWith(PowerMockRunner.class) +public class PreApprovalRequestSearchByIntervalTest extends Resource4Test { + + private PreApprovalSearchByInterval preApprovalSearchByInterval; + + @Before + public void setUp() throws Exception { + preApprovalSearchByInterval = new PreApprovalSearchByInterval(5); + } + + @Test + public void shouldSearch() throws Exception { + String responseAsString = "" + + "" + + "2" + + "1" + + "1" + + "2016-11-09T00:00:00.000-02:00" + + "" + + "" + + "Pre Approval 3" + + "code 3" + + "2016-11-09T00:00:00.000-02:00" + + "tracker" + + "INITIATED" + + "reference" + + "2016-11-09T23:59:59.000-02:00" + + "auto" + + "" + + "" + + "Pre Approval 4" + + "code 4" + + "2016-11-09T00:00:00.000-02:00" + + "tracker" + + "INITIATED" + + "reference" + + "2016-11-09T23:59:59.000-02:00" + + "auto" + + "" + + "" + + ""; + HttpResponse response = new HttpResponse(200, responseAsString); + when(httpClient.execute(any(HttpMethod.class), anyString(), anyMap(), + any(HttpRequestBody.class))).thenReturn(response); + + DataList data = preApprovalSearchByInterval.execute(pagSeguro, + httpClient); + + assertEquals(new Integer(1), data.getTotalPages()); + assertEquals(false, data.isEmpty()); + + Iterator authorizationSummaryIterator = + (Iterator) data.getData().iterator(); + + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + PreApprovalSummary preApproval = authorizationSummaryIterator.next(); + assertEquals("code 3", preApproval.getCode()); + assertEquals("Pre Approval 3", preApproval.getName()); + assertEquals("tracker", preApproval.getTracker()); + assertEquals(PreApprovalStatus.Status.INITIATED, preApproval.getStatus().getStatus()); + assertEquals("reference", preApproval.getReference()); + assertEquals(dateFormat.parse("2016-11-09 23:59:59"), preApproval.getLastEvent()); + assertEquals(dateFormat.parse("2016-11-09 00:00:00"), preApproval.getDate()); + assertEquals("auto", preApproval.getCharge()); + + preApproval = authorizationSummaryIterator.next(); + assertEquals("code 4", preApproval.getCode()); + assertEquals("Pre Approval 4", preApproval.getName()); + assertEquals("tracker", preApproval.getTracker()); + assertEquals(PreApprovalStatus.Status.INITIATED, preApproval.getStatus().getStatus()); + assertEquals("reference", preApproval.getReference()); + assertEquals(dateFormat.parse("2016-11-09 23:59:59"), preApproval.getLastEvent()); + assertEquals(dateFormat.parse("2016-11-09 00:00:00"), preApproval.getDate()); + assertEquals("auto", preApproval.getCharge()); + } + + @Test + public void shouldThrowsBadRequest() { + try { + String responseAsString = "" + + "" + + "" + + "0001" + + "Interval is required." + + "" + + ""; + HttpResponse response = new HttpResponse(400, responseAsString); + when(httpClient.execute(any(HttpMethod.class), anyString(), anyMap(), + any(HttpRequestBody.class))).thenReturn(response); + + preApprovalSearchByInterval.execute(pagSeguro, httpClient); + } catch (PagSeguroBadRequestException e) { + ServerErrors errors = e.getErrors(); + ServerError error = errors.getErrors().iterator().next(); + assertEquals(new Integer(0001), error.getCode()); + assertEquals("Interval is required.", error.getMessage()); + } catch (Exception e) { + } + } + + @Test(expected = PagSeguroLibException.class) + public void shouldThrowsErrorLib() throws Exception { + when(httpClient.execute(any(HttpMethod.class), anyString(), anyMap(), + any(HttpRequestBody.class))).thenThrow(new IOException()); + preApprovalSearchByInterval.execute(pagSeguro, httpClient); + } +} diff --git a/source/src/test/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalRequestSearchV2MapConverterTest.java b/source/src/test/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalRequestSearchV2MapConverterTest.java index 5485e91..98aa0e0 100644 --- a/source/src/test/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalRequestSearchV2MapConverterTest.java +++ b/source/src/test/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalRequestSearchV2MapConverterTest.java @@ -51,4 +51,6 @@ public void shouldConvert() throws Exception { RequestMap map = mapConverter.convert(preApprovalSearch); assertEquals(expectedMap, map); + } +} \ No newline at end of file