diff --git a/.idea/$PRODUCT_WORKSPACE_FILE$ b/.idea/$PRODUCT_WORKSPACE_FILE$ new file mode 100644 index 0000000..4b7d2f5 --- /dev/null +++ b/.idea/$PRODUCT_WORKSPACE_FILE$ @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..5c98b42 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,2 @@ +# Default ignored files +/workspace.xml \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..d22efeb --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..b26911b --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__commons_codec_commons_codec_1_6.xml b/.idea/libraries/Maven__commons_codec_commons_codec_1_6.xml new file mode 100644 index 0000000..e8a6a9f --- /dev/null +++ b/.idea/libraries/Maven__commons_codec_commons_codec_1_6.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__commons_logging_commons_logging_1_1_3.xml b/.idea/libraries/Maven__commons_logging_commons_logging_1_1_3.xml new file mode 100644 index 0000000..01c7b8e --- /dev/null +++ b/.idea/libraries/Maven__commons_logging_commons_logging_1_1_3.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__junit_junit_4_10.xml b/.idea/libraries/Maven__junit_junit_4_10.xml new file mode 100644 index 0000000..ed8bf5f --- /dev/null +++ b/.idea/libraries/Maven__junit_junit_4_10.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_httpcomponents_httpclient_4_3_5.xml b/.idea/libraries/Maven__org_apache_httpcomponents_httpclient_4_3_5.xml new file mode 100644 index 0000000..5601459 --- /dev/null +++ b/.idea/libraries/Maven__org_apache_httpcomponents_httpclient_4_3_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_httpcomponents_httpcore_4_3_2.xml b/.idea/libraries/Maven__org_apache_httpcomponents_httpcore_4_3_2.xml new file mode 100644 index 0000000..1c14963 --- /dev/null +++ b/.idea/libraries/Maven__org_apache_httpcomponents_httpcore_4_3_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_1.xml b/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_1.xml new file mode 100644 index 0000000..acdf443 --- /dev/null +++ b/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_json_json_20090211.xml b/.idea/libraries/Maven__org_json_json_20090211.xml new file mode 100644 index 0000000..e57dc0a --- /dev/null +++ b/.idea/libraries/Maven__org_json_json_20090211.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..dc86db4 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,13 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..1e1da57 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 8d7592c..dd675c1 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,3 @@ commons-do [![Build Status](https://travis-ci.org/developersdo/commons-do.svg?branch=master)](https://travis-ci.org/developersdo/commons-do) ========== Inspirado en data.developers.do está a disposición de los Developers Dominicanos el proyecto commons-do. Tiene como enfoque principal suplir de los algoritmos y funcionalidades más comunes y usadas con frecuencia. - -El proyecto inicialmente contempla todo el API hasta el momento disponible por http://data.developers.do y puesto como librería de dependencias desde Maven para desarrolladores Java. Para colaborar pueden hacer fork al proyecto en https://github.com/developersdo/commons-do. - -####Instalación: -En el POM.xml de su proyecto debe agregar: - -######Repositorio -```XML - - devdom - Developers Dominicanos Repository - http://50.19.213.136:8090/repository/ - -``` -######Dependencia -```XML - - org.devdom - commons-do - 0.8.1 - jar - -``` \ No newline at end of file diff --git a/commons-do.iml b/commons-do.iml new file mode 100644 index 0000000..b195f93 --- /dev/null +++ b/commons-do.iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 296179b..da237c7 100644 --- a/pom.xml +++ b/pom.xml @@ -7,8 +7,8 @@ jar UTF-8 - 1.5 - 1.5 + 1.8 + 1.8 Comunes para Developers Dominicanos @@ -56,19 +56,19 @@ m2.java.net Java.net Maven 2 Repository default - http://download.java.net/maven/2 - + http://download.java.net/maven/2 + eclipselink default Repository for library EclipseLink (JPA 2.0) http://download.eclipse.org/rt/eclipselink/maven.repo/ - + jetty-releases Jetty Releases https://oss.sonatype.org/content/repositories/jetty-releases - + Inspirado por http://data.developers.do se creó un API para consumir la data expuesta en http://data.developers.do - \ No newline at end of file + diff --git a/src/main/java/org/devdom/commons/Combustibles.java b/src/main/java/org/devdom/commons/Combustibles.java index 62bdaff..5888f96 100644 --- a/src/main/java/org/devdom/commons/Combustibles.java +++ b/src/main/java/org/devdom/commons/Combustibles.java @@ -27,12 +27,10 @@ import java.io.InputStream; import java.net.URL; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; +import java.util.*; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Characters; import javax.xml.stream.events.XMLEvent; @@ -45,47 +43,50 @@ *
  • RSS feed: http://www.seic.gov.do/rss/combustibles.aspx
  • *
  • Histórico de precios: http://www.seic.gov.do/hidrocarburos/precios-de-combustibles.aspx
  • * - * + * * @author Carlos Vásquez Polanco + * @author gullermo de los santos || 2019 + * * @see #RSS_COMBUSTIBLES - * @see #URL_HISTORICO_COMBUSTIBLES * @since 0.6.7 */ public class Combustibles { - private final String title; - private final Date publishDate; - private final List combustibles; - /** * URL del RSS feed de los precios de los combustibles. */ - public static final String RSS_COMBUSTIBLES = "http://www.seic.gov.do/rss/combustibles.aspx"; + public static final String RSS_COMBUSTIBLES = "https://www.micm.gob.do/rss/combustibles.aspx"; + +// /** +// * URL de la pagina donde se publica el historico de los precios de los combustibles. +// */ +// public static final String URL_HISTORICO_COMBUSTIBLES = "https://www.micm.gob.do/combustibles.aspx/hidrocarburos/precios-de-combustibles.aspx"; + + private final String title; + private final Date publishDate; + private final List combustibles; - /** - * URL de la pagina donde se publica el historico de los precios de los combustibles. - */ - public static final String URL_HISTORICO_COMBUSTIBLES = "http://www.seic.gov.do/hidrocarburos/precios-de-combustibles.aspx"; private Combustibles(String title, Date publishDate, List combustibles) { this.title = title; this.publishDate = publishDate; this.combustibles = combustibles; } - + /** * Obtener instancia de {@link Combustibles} con los precios actuales. * @throws org.devdom.commons.CommonsException * @see Combustible - * @return + * @return */ public static Combustibles getCurrentPrices() throws CommonsException { Combustibles combustibles = null; List list = new ArrayList(); InputStream input = null; - final String dateFormat = "yyyy-MM-dd'T'HH:mm:ss"; + final String dateFormat = "EEEE', 'dd 'de' MMM 'de' yyyy HH:mm:ss Z"; +// final String dateFormat = "yyyy-MM-dd'T'HH:mm:ss"; String title = null; Date publishDate = null; - + try{ input = new URL(RSS_COMBUSTIBLES).openStream(); XMLInputFactory xif = XMLInputFactory.newFactory(); @@ -94,16 +95,21 @@ public static Combustibles getCurrentPrices() throws CommonsException { while (eventReader.hasNext()) { event = eventReader.nextEvent(); - + if (event.isStartElement()) { String value = getCharacterData(event, eventReader); String item = event.asStartElement().getName().getLocalPart(); if("pubDate".equals(item)){ - publishDate = new SimpleDateFormat(dateFormat).parse(value); + value=value.toLowerCase().replace("- ","-"); + publishDate = new SimpleDateFormat(dateFormat, new Locale("es", "MX")).parse(value); + }else if("title".equals(item)){ title = value; - }else{ + }else if("description".equals(item)){ + +// System.out.println(item); +// System.out.println(value); appendCombustible(list, item, value); } } @@ -120,58 +126,97 @@ public static Combustibles getCurrentPrices() throws CommonsException { return combustibles; } + /** * Método utilizado para extraer el valor de un campo * @param event * @param eventReader * @return - * @throws XMLStreamException + * @throws XMLStreamException */ - private static String getCharacterData(XMLEvent event, XMLEventReader eventReader) - throws XMLStreamException { + private static String getCharacterData(XMLEvent event, XMLEventReader eventReader) throws XMLStreamException { String result = ""; event = eventReader.nextEvent(); if (event instanceof Characters) { result = event.asCharacters().getData(); } + if(result.trim().isEmpty()) { + switch (event.getEventType()) { + case XMLStreamConstants.CHARACTERS: + case XMLStreamConstants.CDATA: +// System.out.println(eventReader.nextEvent().toString()); + result = eventReader.nextEvent().toString(); + + break; + + default: + break; + } + } + +// System.out.println( event.asCharacters().isCData()?"true":"false"); return result; } private static void appendCombustible(List list, String item, String value) throws Exception { - if("gas95".equals(item)) { - list.add(new Combustible(Double.parseDouble(value), Combustible.Tipos.GASOLINA_PREMIUM)); - } - if("gas89".equals(item)){ - list.add(new Combustible(Double.parseDouble(value), Combustible.Tipos.GASOLINA_REGULAR)); - } + String data=clearData(value); + String[] items= data.split("item"); - if("gasoilp".equals(item)){ - list.add(new Combustible(Double.parseDouble(value), Combustible.Tipos.GASOIL_PREMIUM)); - } + if(items.length<2) return; - if("gasoilr".equals(item)){ - list.add(new Combustible(Double.parseDouble(value), Combustible.Tipos.GASOIL_REGULAR)); - } + for( int i=0; i","item ") + .replace("","") + .replace("$","") + .replace("",""); + } + /** * Retorna el encabezado de la publicación de los precios de los {@link #getCombustibles() combustibles}. * Eg.: {@code Precios de Combustibles: 4 al 10 de octubre de 2014} - * @return + * @return */ public String getTitle() { return title; @@ -179,7 +224,7 @@ public String getTitle() { /** * Retorna la fecha de publicación de los {@link #getCombustibles() combustibles}. - * @return + * @return */ public Date getPublishDate() { return publishDate; @@ -198,4 +243,4 @@ public List getCombustibles() { public String toString() { return "Combustibles{" + "title=" + title + ", publishDate=" + publishDate + ", combustibles=" + combustibles + '}'; } -} \ No newline at end of file +} diff --git a/src/main/java/org/devdom/commons/Feriados.java b/src/main/java/org/devdom/commons/Feriados.java index 113aabd..2674704 100644 --- a/src/main/java/org/devdom/commons/Feriados.java +++ b/src/main/java/org/devdom/commons/Feriados.java @@ -44,20 +44,20 @@ /** * Clase utilizada para manejar los días feriados en la República Dominicana * para el año en curso. - * + * * @author Carlos Vásquez Polanco * @see Feriado * @since 0.5.1 */ public class Feriados extends Listable { - + public Feriados() { super(Configuration.DATA_FERIADOS_URL, "UTF-8"); } /** - * + * * Listado de días feriados según el Ministerio de Trabajo de la República Dominicana - * + * * @return ArrayList de objetos Feriado * @see Feriado * @throws RequesterInformationException si hubo error en la recepción de información @@ -66,39 +66,39 @@ public Feriados() { */ @Override public List getList() throws RequesterInformationException, ParseException{ - + Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); - + return getList(year); } /** - * + * *

    Listado de días feriados según el Ministerio de Trabajo de la República Dominicana. * El método recibe el año que se desea evaluar. - * - *

    Este método aun funciona con el año en curso, de intentar ver un año pasado será - * lanzada una excepción. El método fue pensado para cuando esta restricción del + * + *

    Este método aun funciona con el año en curso, de intentar ver un año pasado será + * lanzada una excepción. El método fue pensado para cuando esta restricción del * servicio sea liberada. - * + * * @param year año a ser evaluado * @return ArrayList de objetos Feriado * @see Feriado * @throws RequesterInformationException si hubo error en la recepción de información * @throws MalformedJSONException si hubo error en el formato o validación del JSON - * @throws ParseException si hubo error de parseo + * @throws ParseException si hubo error de parseo */ - public List getList(int year) + public List getList(int year) throws RequesterInformationException, ParseException{ String json = getResponse(buildURL(FormatType.JSON, String.valueOf(year))); List list = new ArrayList(); - + //Verificar el formato de la información retornada para parsearla JSONArray jsonArray = parseJSONArray(json); int len = jsonArray.length(); - + /* Extraer todos los objetos y convertirlos a entidades de tipo feriado para añadirlos a la lista. @@ -114,33 +114,33 @@ public List getList(int year) return list; } - + /** - * + * *

    Método utilizado para saber si el día en curso es feriado. - * + * *

    Primero es verificada la fecha a la que fue movida por disposición * de la ley Dominicana. Si la fecha festiva no es movida se revisa su fecha * original. - * + * * @return boolean que determina si el día actual es feriado * @throws RequesterInformationException si hubo error en la recepción de información * @throws MalformedJSONException si hubo error en el formato o validación del JSON * @throws ParseException si hubo error de parseo */ - public boolean isTodayHoliday() + public boolean isTodayHoliday() throws RequesterInformationException, ParseException{ - + TimeZone timeZone = TimeZone.getTimeZone(Configuration.DR_TIME_ZONE); Calendar calendar = Calendar.getInstance(timeZone); int currentDayOfYear = calendar.get(Calendar.DAY_OF_YEAR); int year = calendar.get(Calendar.YEAR); List list = getList(year); - + for(Feriado feriado : list){ Date holiday = feriado.getFechaMovido(); - + if(holiday==null){ holiday = feriado.getFechaOriginal(); } @@ -159,15 +159,15 @@ public boolean isTodayHoliday() } /** - * + * * Obtener la definición de un día feriado según el Objeto JSON suplido - * + * * @param json RAW del JSON recibido para ser formateado * @return Objeto Feriado * @see Feriado * @throws MalformedJSONException si hubo error en el formato o validación del JSON */ - private static Feriado getFeriadoObject(JSONObject json) + private static Feriado getFeriadoObject(JSONObject json) throws MalformedJSONException, ParseException{ try { @@ -181,27 +181,27 @@ private static Feriado getFeriadoObject(JSONObject json) throw new MalformedJSONException(ex.getMessage(),ex); } } - + /** * Obtener objeto Feriado según la posición solicitada - * + * * @param id posición de día feriado * @return Objeto Feriado * @see Feriado * @throws RequesterInformationException si hubo error en la recepción de información * @throws ParseException si hubo error de parseo */ - public Feriado get(int id) + public Feriado get(int id) throws RequesterInformationException, ParseException { - + Calendar calendar = Calendar.getInstance(); - + return this.get(id, calendar.get(Calendar.YEAR)); } - + /** * Obtener objeto Feriado según la posición solicitada - * + * * @param id posición de día feriado * @param year año deseado * @return Objeto Feriado @@ -209,9 +209,9 @@ public Feriado get(int id) * @throws RequesterInformationException si hubo error en la recepción de información * @throws ParseException si hubo error de parseo */ - public Feriado get(int id, int year) + public Feriado get(int id, int year) throws RequesterInformationException, ParseException{ - + for(Feriado feriado : this.getList(year)){ if(feriado.getId()==id){ return feriado; @@ -222,7 +222,7 @@ public Feriado get(int id, int year) /** * Obtener objeto Feriado según la posición solicitada - * + * * @param id posición de día feriado * @return Objeto Feriado * @see Feriado @@ -231,14 +231,14 @@ public Feriado get(int id, int year) * @throws NumberFormatException si hubo un intento de pasar caracteres por valores numéricos */ @Override - public Feriado get(String id) + public Feriado get(String id) throws RequesterInformationException, ParseException, NumberFormatException { - + if(!Utils.hasOnlyDigits(id)){ throw new NumberFormatException("Solo se permiten dígitos"); } - + return get(Integer.parseInt(id)); } - + } diff --git a/src/main/java/org/devdom/commons/JsonGetter.java b/src/main/java/org/devdom/commons/JsonGetter.java index 8628280..b5c349e 100644 --- a/src/main/java/org/devdom/commons/JsonGetter.java +++ b/src/main/java/org/devdom/commons/JsonGetter.java @@ -16,28 +16,28 @@ public abstract class JsonGetter extends Requester { private final String BASE_URL; - + public JsonGetter(String baseUri, String charset) { super(charset); this.BASE_URL = baseUri; } - - public abstract T get(String id) throws RequesterInformationException, ParseException; - + + public abstract T get(String id) throws RequesterInformationException, ParseException, JSONException; + /** *

    Obtener un JSONObject a partir de la llamada al API de http://data.developers.do - * - *

    Aun así, el método puede ser utilizado para llamar recursos desde otros + * + *

    Aun así, el método puede ser utilizado para llamar recursos desde otros * recursos siempre que retornen un JSON. - * + * * @param response * @return Objeto JSONObject * @throws RequesterInformationException si hubo error en la recepción de información * @throws MalformedJSONException si hubo error en el formato o validación del JSON */ - public JSONObject getJSONObjectResponse(String response) + public JSONObject getJSONObjectResponse(String response) throws RequesterInformationException { - + if(!isValidJSONObjectString(response)){ throw new MalformedJSONException("La respuesta no es un objeto JSON válido"); } @@ -46,7 +46,7 @@ public JSONObject getJSONObjectResponse(String response) } - + /** * Convetir a objeto JSONObject un string * @param response @@ -65,18 +65,18 @@ public JSONObject parseJSONObject(String response) { /** * Validar si el string suplido puede ser un JSONObject válido - * + * * @param response * @return boolean */ public boolean isValidJSONObjectString(String response){ return (response.startsWith("{")); } - + /** - * Retorna la url con las partes agregadas. + * Retorna la url con las partes agregadas. * @param format - * Formato de la respuesta esperada. + * Formato de la respuesta esperada. * @param parts * Las partes de la dirección http a ser agregadas. * @return @@ -89,6 +89,7 @@ public String buildURL(FormatType format, String... parts) { uriString.append("/").append(part); } try { + uri = new URI(uriString.toString() + format.getExtension()); } catch (URISyntaxException e) { throw new MalformedJSONException(e.getMessage()); diff --git a/src/main/java/org/devdom/commons/Listable.java b/src/main/java/org/devdom/commons/Listable.java index e8496df..7d2171e 100644 --- a/src/main/java/org/devdom/commons/Listable.java +++ b/src/main/java/org/devdom/commons/Listable.java @@ -7,60 +7,64 @@ import org.devdom.commons.exceptions.RequesterInformationException; import org.json.JSONArray; import org.json.JSONException; +import org.json.JSONObject; public abstract class Listable extends JsonGetter { public Listable(String baseUri, String charset) { super(baseUri, charset); } - + public abstract List getList() throws RequesterInformationException, ParseException; - + /** *

    Obtener un JSONArray a partir de la llamada al API de http://data.developers.do - * - *

    Aun así, el método puede ser utilizado para llamar recursos desde otros + * + *

    Aun así, el método puede ser utilizado para llamar recursos desde otros * recursos siempre que retornen un JSON. - * + * * @param response * @return Objeto JSONArray * @throws RequesterInformationException si hubo error en la recepción de información * @throws MalformedJSONException si hubo error en el formato o validación del JSON */ - public JSONArray getJSONArrayResponse(String response) + public JSONArray getJSONArrayResponse(String response) throws RequesterInformationException{ - + if(!isValidJSONArrayString(response)){ throw new MalformedJSONException("La respuesta no es un objeto JSON válido"); } return parseJSONArray(response); } - - + + /** * Convertir a objeto JSONAray un string * @param response * @return objeto JSONArray * @see JSONArray - * @throws MalformedJSONException + * @throws MalformedJSONException */ public JSONArray parseJSONArray(String response) { try { - return (new JSONArray(response)); +// System.out.println(response); + JSONArray data = (new JSONObject(response)).getJSONArray("data"); +// System.out.println(data); + return data; } catch (JSONException ex) { throw new MalformedJSONException(ex.getMessage(),ex); } } /** * Validar si el string suplido puede ser un JSONArray válido - * + * * @param response * @return boolean */ public boolean isValidJSONArrayString(String response){ - return (response.startsWith("[{")); + return (response.startsWith("{")); } - + } diff --git a/src/main/java/org/devdom/commons/Municipios.java b/src/main/java/org/devdom/commons/Municipios.java index 2f7de1c..0ce51e3 100644 --- a/src/main/java/org/devdom/commons/Municipios.java +++ b/src/main/java/org/devdom/commons/Municipios.java @@ -38,9 +38,9 @@ import org.json.JSONObject; /** - * Clase utilizada para manejar la información referente a Municipios de la + * Clase utilizada para manejar la información referente a Municipios de la * República Dominicana. - * + * * @see Municipio * @see Provincia * @author Carlos Vásquez Polanco @@ -53,10 +53,10 @@ public Municipios() { } /** - * - * Retorna una lista de objetos de tipo Municipio con la referencia al + * + * Retorna una lista de objetos de tipo Municipio con la referencia al * objeto Provincia a la que pertenece. - * + * * @return ArrayList de objetos Municipio * @throws RequesterInformationException si hubo error en la recepción de información * @throws java.text.ParseException @@ -64,10 +64,10 @@ public Municipios() { * @see Municipio * @see Provincia */ - public List getList() + public List getList() throws RequesterInformationException, ParseException { - String url = Configuration.DATA_MUNICIPIOS_URL + ".json"; + String url = Configuration.DATA_MUNICIPIOS_URL; ArrayList list = new ArrayList(); String json = getResponse(url); @@ -101,7 +101,7 @@ public List getList() /** * Obtener la información de un municipio - * + * * @param id id del objeto del Municipio que se desea obtener * @return objeto Municipio * @throws java.text.ParseException @@ -110,23 +110,23 @@ public List getList() * @throws MalformedJSONException si hubo error en el formato o validación del JSON */ public Municipio get(String id) - throws RequesterInformationException, ParseException { + throws RequesterInformationException, ParseException, JSONException { String url = Configuration.DATA_MUNICIPIOS_URL + "/" + id + ".json"; String json = getResponse(url); - if (isValidJSONArrayString(json)) { - // si la llamada retorna más de un elemento, da un error de documento mal formado - throw new MalformedJSONException(); - } +// if (isValidJSONArrayString(json)) { +// // si la llamada retorna más de un elemento, da un error de documento mal formado +// throw new MalformedJSONException(); +// } - return getMunicipioObject(parseJSONObject(json)); + return getMunicipioObject((JSONObject) parseJSONObject(json).getJSONArray("data").get(0)); } /** - * + * * @param json RAW del JSON recibido para ser formateado * @return objeto Municipio * @see Municipio @@ -137,15 +137,17 @@ private Municipio getMunicipioObject(JSONObject json) throws MalformedJSONException { try { - Municipio municipio = new Municipio(json.getInt("id")); + Municipio municipio = new Municipio(json.getInt("codigo")); municipio.setName(json.getString("nombre")); - JSONObject jsonProvincia = json.getJSONObject("provincia"); - - Provincia provincia = new Provincia(jsonProvincia.getInt("id")); - provincia.setNombre(jsonProvincia.getString("nombre")); - - municipio.setProvincia(provincia); +// JSONObject jsonProvincia = json.getJSONObject("provincia"); +// +// Provincias p= new Provincias(); +// p.get() +// Provincia provincia = new Provincia(jsonProvincia.getInt(" codigo")); +// provincia.setNombre(jsonProvincia.getString("nombre")); +// +// municipio.setProvincia(provincia); return municipio; } catch (JSONException ex) { diff --git a/src/main/java/org/devdom/commons/Provincias.java b/src/main/java/org/devdom/commons/Provincias.java index 3acfd61..cfab8cd 100644 --- a/src/main/java/org/devdom/commons/Provincias.java +++ b/src/main/java/org/devdom/commons/Provincias.java @@ -37,46 +37,46 @@ import org.json.JSONObject; /** - * Clase Utilizada para manejar la información referente a provincias de la + * Clase Utilizada para manejar la información referente a provincias de la * República Dominicana. - * + * * @author Carlos Vásquez Polanco * @since 0.3.0 */ public class Provincias extends Listable { - + public Provincias() { super(Configuration.DATA_PROVINCIAS_URL, "UTF-8"); } /** * Listado de provincias de la República Dominiciana - * - * @return ArrayList de objetos Provincia + * + * @return ArrayList de objetos Provincia * @see Provincia * @throws RequesterInformationException si hubo error en la recepción de información * @throws MalformedJSONException si hubo error en el formato o validación del JSON */ - public List getList() - throws RequesterInformationException { + public List getList() throws RequesterInformationException { ArrayList list = new ArrayList(); String json = getResponse(buildURL(FormatType.JSON)); - + //Verificar el formato de la información retornada para parsearla if(isValidJSONArrayString(json)){ +// System.out.println("llegue aqui "); JSONArray jsonArray = parseJSONArray(json); - int len = jsonArray.length(); - + + int size = jsonArray.length(); /* Extraer todos los objetos y convertirlos a entidades de provincias para añadirlos a la lista. */ - for(int i = 0; i getList() return list; } - + /** * Obtener la información de una provincia - * + * * @param id id del objeto de provincia que se desea obtener * @return objeto Provincia * @see Provincia * @throws RequesterInformationException si hubo error en la recepción de información * @throws MalformedJSONException si hubo error en el formato o validación del JSON */ - public Provincia get(String id) - throws RequesterInformationException, MalformedJSONException{ - + public Provincia get(String id) + throws RequesterInformationException, MalformedJSONException, JSONException { + String json = getResponse(buildURL(FormatType.JSON, id)); - - if(isValidJSONArrayString(json)){ - // si la llamada retorna más de un elemento, da un error de documento mal formado - throw new MalformedJSONException(); - } - - return getProvinciaObject(parseJSONObject(json) ); +// +// if(isValidJSONArrayString(json)){ +// System.out.println(json); +// // si la llamada retorna más de un elemento, da un error de documento mal formado +// throw new MalformedJSONException(); +// } + + return getProvinciaObject((JSONObject) parseJSONObject(json).getJSONArray("data").get(0)); } - + /** - * + * * @param json RAW del JSON recibido para ser formateado * @return objeto Provincia * @see Provincia * @throws MalformedJSONException si hubo error en el formato o validación del JSON */ - private static Provincia getProvinciaObject(JSONObject json) + private static Provincia getProvinciaObject(JSONObject json) throws MalformedJSONException{ try { - return new Provincia(json.getInt("id"), json.getString("nombre")); + return new Provincia(json.getInt("codigo"), json.getString("nombre")); } catch (JSONException ex) { throw new MalformedJSONException(ex.getMessage(),ex); } diff --git a/src/main/java/org/devdom/commons/dto/BaseModel.java b/src/main/java/org/devdom/commons/dto/BaseModel.java index 381ac6c..0a810e3 100644 --- a/src/main/java/org/devdom/commons/dto/BaseModel.java +++ b/src/main/java/org/devdom/commons/dto/BaseModel.java @@ -1,6 +1,8 @@ package org.devdom.commons.dto; public class BaseModel { + + protected int id; public int getId() { @@ -30,6 +32,6 @@ public boolean equals(Object obj) { BaseModel other = (BaseModel) obj; return id == other.id; } - - + + } diff --git a/src/main/java/org/devdom/commons/dto/Feriado.java b/src/main/java/org/devdom/commons/dto/Feriado.java index 95dd69b..d016908 100644 --- a/src/main/java/org/devdom/commons/dto/Feriado.java +++ b/src/main/java/org/devdom/commons/dto/Feriado.java @@ -31,7 +31,7 @@ * @author Carlos Vásquez Polanco */ public class Feriado extends BaseModel { - + private Date fechaOriginal; private Date fechaMovido; private String motivo; diff --git a/src/main/java/org/devdom/commons/dto/Municipio.java b/src/main/java/org/devdom/commons/dto/Municipio.java index fdb7782..2519e25 100644 --- a/src/main/java/org/devdom/commons/dto/Municipio.java +++ b/src/main/java/org/devdom/commons/dto/Municipio.java @@ -30,7 +30,7 @@ * @author Carlos Vásquez Polanco */ public class Municipio extends BaseModel { - + private String name; private Provincia provincia; @@ -69,5 +69,5 @@ public void setProvincia(Provincia provincia) { public String toString() { return "Municipio{" + "id=" + id + ", name=" + name + ", provincia=" + provincia.toString() + '}'; } - + } diff --git a/src/main/java/org/devdom/commons/util/Configuration.java b/src/main/java/org/devdom/commons/util/Configuration.java index 8e9a843..97bff96 100644 --- a/src/main/java/org/devdom/commons/util/Configuration.java +++ b/src/main/java/org/devdom/commons/util/Configuration.java @@ -31,15 +31,15 @@ */ public interface Configuration { //URI del API de Developers Dominicanos - String DATA_DEVDO_URI_V1 = "http://data.developers.do/api/v1/"; - + String DATA_DEVDO_URI_V1 = "http://provinciasrd.raydelto.org/"; + String DATA_RNC_URL = DATA_DEVDO_URI_V1 + "empresas/"; - + String DATA_PROVINCIAS_URL = DATA_DEVDO_URI_V1 + "provincias"; - + String DATA_MUNICIPIOS_URL = DATA_DEVDO_URI_V1 + "municipios"; String DATA_FERIADOS_URL = DATA_DEVDO_URI_V1 + "feriados"; - + String DR_TIME_ZONE = "Etc/GMT+4"; } diff --git a/src/main/java/org/devdom/commons/util/Utils.java b/src/main/java/org/devdom/commons/util/Utils.java index e0c2df0..1c0b242 100644 --- a/src/main/java/org/devdom/commons/util/Utils.java +++ b/src/main/java/org/devdom/commons/util/Utils.java @@ -29,6 +29,7 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpResponse; @@ -39,36 +40,39 @@ /** * * @author Carlos Vásquez Polanco + * */ public class Utils { - + + public static final Locale LOCALE_MX = new Locale("es", "MX"); + /** - * + * * @param value - * @return + * @return */ public static boolean hasOnlyDigits(String value){ return value.matches("[0-9]+"); } - + /** - * + * * Extraer fecha formateada - * + * * @param date - * @return + * @return */ public static String getDateFormatted(Date date){ return getDateFormatted(date, "dd/MM/yyyy"); } - + /** - * - * Extraer fecha formateada, indicando cual es el formato - * + * + * Extraer fecha formateada, indicando cual es el formato + * * @param date * @param format - * @return + * @return */ public static String getDateFormatted(Date date, String format){ DateFormat formatter = new SimpleDateFormat(format); @@ -76,26 +80,26 @@ public static String getDateFormatted(Date date, String format){ } /** - * - * Método utilizado para convertir un objeto Strign en un objeto fecha. - * + * + * Método utilizado para convertir un objeto Strign en un objeto fecha. + * * @param date * @return - * @throws ParseException + * @throws ParseException */ public static Date convertStringToDate(String date) throws ParseException{ return convertStringToDate(date,"yyyy-MM-dd"); } - + /** - * - * Método utilizado para convertir un objeto Strign en un objeto fecha + * + * Método utilizado para convertir un objeto Strign en un objeto fecha * indicando el formato en el segundo parámetro. - * + * * @param date * @param format * @return - * @throws ParseException + * @throws ParseException */ public static Date convertStringToDate(String date, String format) throws ParseException{ SimpleDateFormat sdf = new SimpleDateFormat(format); @@ -103,6 +107,21 @@ public static Date convertStringToDate(String date, String format) throws ParseE } + public static String dateFormatter(String inputFormat, String outputFormat, String inputDate){ + //Define formato default de entrada. + String input = inputFormat.isEmpty()? "yyyy-MM-dd hh:mm:ss" : inputFormat; + //Define formato default de salida. + String output = outputFormat.isEmpty()? "d 'de' MMMM 'del' yyyy" : outputFormat; + String outputDate = inputDate; + try { + outputDate = new SimpleDateFormat(output, LOCALE_MX).format(new SimpleDateFormat(input, LOCALE_MX).parse(inputDate)); + } catch (Exception e) { + System.out.println("dateFormatter(): " + e.getMessage()); + } + return outputDate; + } + + public static InputStream httpGet(String url, Map headers) throws Exception { InputStream result = null; HttpGet get = new HttpGet(url); diff --git a/src/test/java/org/devdom/commons/MunicipiosTest.java b/src/test/java/org/devdom/commons/MunicipiosTest.java index f1c00e7..27e689d 100644 --- a/src/test/java/org/devdom/commons/MunicipiosTest.java +++ b/src/test/java/org/devdom/commons/MunicipiosTest.java @@ -11,13 +11,13 @@ public class MunicipiosTest { Municipios municipioService; //Provincias provinciaService; - + @Before public void setup() { municipioService = new Municipios(); //provinciaService = new Provincias(); } - + @Test public void getAll() { try { @@ -28,33 +28,33 @@ public void getAll() { Assert.fail(e.getMessage()); } } - + @Test public void get() { try { List municipios = municipioService.getList(); - + Municipio municipio = municipios.get(new Random().nextInt(municipios.size())); - + Municipio external = municipioService.get(String.valueOf(municipio.getId())); Assert.assertEquals(municipio, external); } catch (Exception e) { Assert.fail(e.getMessage()); } } - + // @Test -// TODO to be implemented +// TODO to be implemented // getMunicipios by city // public void getMunicipiosByProvincia() { // try { // List pronvincias = provinciaService.getList(); // Provincia municipio = pronvincias.get(new Random().nextInt(pronvincias.size())); -// -// +// +// // } catch (Exception e) { // Assert.fail(e.getMessage()); // } // } - + } diff --git a/src/test/java/org/devdom/commons/ProvinciasTest.java b/src/test/java/org/devdom/commons/ProvinciasTest.java index c3b57f4..17795a2 100644 --- a/src/test/java/org/devdom/commons/ProvinciasTest.java +++ b/src/test/java/org/devdom/commons/ProvinciasTest.java @@ -10,12 +10,12 @@ public class ProvinciasTest { Provincias provinciaService; - + @Before public void setup() { provinciaService = new Provincias(); } - + @Test public void getAll() { try { @@ -26,19 +26,19 @@ public void getAll() { Assert.fail(e.getMessage()); } } - + @Test public void get() { try { List pronvincias = provinciaService.getList(); - + Provincia provincia = pronvincias.get(new Random().nextInt(pronvincias.size())); - + Provincia external = provinciaService.get(String.valueOf(provincia.getId())); Assert.assertEquals(provincia, external); } catch (Exception e) { Assert.fail(e.getMessage()); } } - + }