141122

parent 8fb42b55
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="formulario-api" />
</profile>
</annotationProcessing>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="formulario-api" options="-endorseddirs D:\formulario-api\target/endorsed" />
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="siia" uuid="60957c5c-de91-49ed-adf8-d0fc940d62b3">
<driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql://172.16.2.207:5432/postgres</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="AndroidLintAllCaps" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="AndroidLintTypographyDashes" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="AndroidLintTypographyEllipsis" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="AndroidLintTypographyFractions" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="AndroidLintTypographyOther" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="WARNING" enabled_by_default="false" editorAttributes="WARNING_ATTRIBUTES">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="snapshots" />
<option name="name" value="snapshots" />
<option name="url" value="http://161.97.127.173:8081/repository/mvn-poqh-snapshot/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="releases" />
<option name="name" value="releases" />
<option name="url" value="http://161.97.127.173:8081/repository/mvn-poqh-release/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Plugin Repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="snapshots-hosted" />
<option name="name" value="snapshots-hosted" />
<option name="url" value="http://161.97.127.173:8081/repository/mvn-poqh-hosted-snapshot/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="corretto-11" project-jdk-type="JavaSDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/java/pe/so/api/formulario/postgresdao/PostgreSqlExcel.java" dialect="PostgreSQL" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
......@@ -16,17 +16,82 @@
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5.jre7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20201115</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-admin-directory</artifactId>
<version>directory_v1-rev20191003-1.30.8</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>1.27.0</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.17.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
<dependency>
<groupId>pe.mithsolutions</groupId>
<artifactId>poqh-data-ficha</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
......@@ -36,8 +101,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>8</source>
<target>8</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
......@@ -79,4 +144,57 @@
</plugins>
</build>
<repositories>
<repository>
<id>central</id>
<name>Maven Plugin Repository</name>
<url>https://repo1.maven.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>snapshots-hosted</id>
<url>http://161.97.127.173:8081/repository/mvn-poqh-hosted-snapshot/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>snapshots</id>
<url>http://161.97.127.173:8081/repository/mvn-poqh-snapshot/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>releases</id>
<url>http://161.97.127.173:8081/repository/mvn-poqh-release/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<distributionManagement>
<snapshotRepository>
<id>nexus</id>
<url>http://kira-poqh-mith.live:8081/repository/mvn-poqh-hosted-snapshot/</url>
</snapshotRepository>
</distributionManagement>
</project>
......@@ -2,8 +2,27 @@ package pe.so.api.formulario.api;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.*;
@ApplicationPath("api/v1")
public class ApiConfig extends Application {
private final Set<Object> singletons = new HashSet<>();
private final HashSet<Class<?>> classes = new HashSet<>();
public ApiConfig() {
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
@Override
public HashSet<Class<?>> getClasses() {
return classes;
}
}
package pe.so.api.formulario.api;
import org.json.JSONObject;
import pe.so.api.formulario.services.ExcelServices;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
@Provider
@Path("excel")
@Consumes("application/json")
@Produces("application/json")
public class ExcelApi{
private final String[] jsonString = {"p_drive_origen", "p_drive_fila", "p_sede", "p_fecha_hora_registro", "p_medio_atencion", "p_contacto_nombres", "p_contacto_apellidos", "p_numero_documento", "p_contacto_correo", "p_contacto_telefono", "p_distrito", "p_grado", "p_colegio_procedencia","p_medio_difusion_nombre", "p_atencion_usuario", "p_atencion_fecha", "p_atencion_estado", "p_atencion_medio_atencion", "p_atencion_hora", "p_atencion_observacion"};
private JSONObject MSJ_RESPUESTA = new JSONObject();
@POST
@Path("/execute")
public Response ejecutar(String json) throws Exception {
JSONObject entrada = new JSONObject(json);
JSONObject formato = formatoJSON(jsonString);
if(validarFormato(jsonString,json)){
ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.execute(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
}else{
return Response.status(500).entity(
MSJ_RESPUESTA.put("status", false)
.put("mensaje", "Error en el formato de entrada")
.put("formato_esperado", formato).toString()
).build();
}
}
private JSONObject formatoJSON (String[] formato){
JSONObject json = new JSONObject();
for (String key : formato) {
json.put(key, "valor");
}
return json;
}
private boolean validarFormato(String[] formato,String json) {
JSONObject entrada = new JSONObject(json);
for (String key : formato) {
if (!entrada.has(key)) {
return false;
}
}
return true;
}
}
package pe.so.api.formulario.dao;
import static pe.so.api.formulario.utilities.StringUtils.countChar;
import java.math.BigDecimal;
import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import org.json.JSONArray;
import org.json.JSONObject;
import org.postgresql.util.PGobject;
/**
*
* @author sistemas - Billy , Melani edición : Percy Oliver Quispe Huarcaya
*/
public abstract class DAO {
/**
* Este metodo ejecuta una sentencia sql de consulta(solamente selects) en
* la base de datos y devuelve como resultado en un JSONArray los registros
* obtenidos
*
*
* @param cn objeto que representa la conexion a la base de datos
* @param query sentencia sql que se desea ejecutar en la base de datos
* -@param parametros parametros que vamos a pasar al query, *es opcional
* @return Devuelve como resultado los registros obtenidos por el query en
* un objeto JSONArray
* @throws Exception
*/
protected static JSONArray queryPS(Connection cn, String query, boolean mode, JSONArray... params) throws Exception {
JSONArray jsonArray = new JSONArray();//objeto que almacena todas las filas obtenidas por el query
try {
try (PreparedStatement ps = cn.prepareStatement(query)) {
//validamos si existen parametros
if (params != null && params.length > 0) {
JSONArray _params = params[0];
int index = 1;
//Recorremos la lista de parametros y lo seteamos en el preparedstatement
for (Object p : _params) {
setPreparedStatement(ps, index++, p);
}
}
try (ResultSet rs = ps.executeQuery()) {
ResultSetMetaData rm = rs.getMetaData();
int numCols = rm.getColumnCount();
while (rs.next()) {
JSONObject obj = new JSONObject();
for (int i = 1; i <= numCols; i++) {
setJSONObject(rs, rm, i, obj, mode);
}
// System.out.println("objeto " + obj);
jsonArray.put(obj);
}
}
}
} catch (Exception ex) {
throw ex;
} finally {
try {
if (cn != null) {
cn.close();
}
} catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage());
}
}
return jsonArray;
}
protected static JSONObject queryPSSingle(Connection cn, String query, boolean mode, JSONArray... params) throws Exception {
JSONObject json = new JSONObject();//objeto que almacena todas las filas obtenidas por el query
//boolean status = false;
//String message = "";
try (PreparedStatement ps = cn.prepareStatement(query);) {
int paramsCount = countChar(query, '?');
for (int i = 0; i < paramsCount; i++) {
if (!params[0].isNull(i)) {
setPreparedStatement(ps, i + 1, params[0].get(i));
} else {
setPreparedStatement(ps, i + 1, JSONObject.NULL);
}
}
System.out.println("Query ejecutado con queryPSSingle-->>>> \n" + ps);
try (ResultSet rs = ps.executeQuery();) {
ResultSetMetaData rm = rs.getMetaData();
int numCols = rm.getColumnCount();
if (rs.next()) {
for (int i = 1; i <= numCols; i++) {
setJSONObject(rs, rm, i, json, mode);
}
json.put("status", json.has("status") ? json.getBoolean("status") : true);
json.put("message", json.has("message") ? json.getString("message") : "Operación realizada correctamente.");
} else {
json.put("status", false).put("message", "Hubo un error al realizar la operación.");
}
}
} catch (Exception ex) {
throw ex;
} finally {
try {
if (cn != null) {
cn.close();
}
} catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage());
}
}
return json;
}
/**
* Este metodo nos permite ejecutar una sentencia sql en la base de datos y
* devuelve como resultado en un JSONObject las filas afectadas por el
* query.
*
* @param cn objeto que representa la conexion a la base de datos
* @param query sentencia sql que se desea ejecutar en la base de datos
* @param parametros parametros que vamos a pasar al query, *es opcional
* @return Devuelve la cantidad de filas afectadas por el query en un
* JSONObject.
* @throws Exception
*/
protected static JSONObject executePS(Connection cn, String query, JSONArray... params) throws Exception {
JSONObject obj = new JSONObject();
try {
try (PreparedStatement ps = cn.prepareStatement(query);) {
if (params != null && params.length > 0) {
JSONArray _params = params[0];
int index = 1;
for (Object parametro : _params) {
setPreparedStatement(ps, index++, parametro);
}
}
int filas = ps.executeUpdate();
obj.put("status", filas > 0);
obj.put("message", "OK");
obj.put("data", filas);
}
} catch (Exception ex) {
obj.put("status", false);
obj.put("message", ex);
obj.put("data", JSONObject.NULL);
throw ex;
} finally {
try {
if (cn != null) {
cn.close();
}
} catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage());
}
}
return obj;
}
protected static JSONArray queryProcedure(Connection cn, String query, boolean mode, JSONArray... parameters) throws Exception {
JSONArray jsonArray = new JSONArray();
JSONObject outputParamTypes = new JSONObject();
JSONArray params = null;
try {
try (CallableStatement cs = cn.prepareCall(query);) {
if (parameters != null && parameters.length > 0) {
params = parameters[0];
int index = 1;
for (Object parameter : params) {
if (parameter instanceof Class) {
registerOutputParameter(cs, index++, parameter, outputParamTypes);
} else {
setPreparedStatement(cs, index++, parameter);
}
}
}
boolean isResultSet = cs.execute();
if (isResultSet) {
try (final ResultSet rs = cs.getResultSet();) {
ResultSetMetaData rm = rs.getMetaData();
int columnCount = rm.getColumnCount();
while (rs.next()) {
JSONObject obj = new JSONObject();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
setJSONObject(rs, rm, columnIndex, obj, mode);
}
jsonArray.put(obj);
}
}
} else {
int rowsAffected = cs.getUpdateCount();
JSONObject obj = new JSONObject();
obj.put("rowsAffected", rowsAffected);
jsonArray.put(obj);
}
if (outputParamTypes.length() > 0) {
clearJSONArray(params);
}
for (String key : outputParamTypes.keySet()) {
int indexOutputParams = Integer.parseInt(key);
int type = outputParamTypes.getInt(key);
getOutputParameter(cs, indexOutputParams, type, params);
}
}
} catch (Exception ex) {
throw ex;
} finally {
try {
if (cn != null) {
cn.close();
}
} catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage());
}
}
return jsonArray;
}
protected static JSONObject executeCS(Connection cn, String query, JSONArray... params) throws Exception {
JSONObject obj = new JSONObject();
try {
try (CallableStatement cs = cn.prepareCall(query);) {
if (params != null && params.length > 0) {
JSONArray _params = params[0];
int index = 1;
for (Object p : _params) {
setPreparedStatement(cs, index++, p);
}
}
int filas = cs.executeUpdate();
obj.put("status", filas > 0);
obj.put("message", "OK");
obj.put("data", filas);
}
} catch (Exception ex) {
obj.put("status", false);
obj.put("message", ex);
obj.put("data", JSONObject.NULL);
throw ex;
} finally {
try {
if (cn != null) {
cn.close();
}
} catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage());
}
}
return obj;
}
/**
* Obtiene el valor de una columna de una tabla y lo guarda en el objeto
* JSONObject con el tipo de dato que le corresponde.
*
* @param rs Objeto ResultSet para obtener el valor de una columna de una
* tabla
* @param rsmd Objeto ResultSetMetaData nos permite obtener el nombre y tipo
* de columna
* @param columnIndex Posicion de la columna en la sentencia sql
* @param obj Representa a un registro de la base de datos
* @throws SQLException
*/
private static void setJSONObject(ResultSet rs, ResultSetMetaData rm, int columnIndex, JSONObject obj, boolean mode) throws SQLException {
int type = rm.getColumnType(columnIndex);
switch (type) {
case Types.VARCHAR:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getString(columnIndex) == null ? JSONObject.NULL : rs.getString(columnIndex));
break;
case Types.CHAR:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getString(columnIndex) == null ? JSONObject.NULL : rs.getString(columnIndex));
break;
case Types.INTEGER:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getInt(columnIndex));
break;
case Types.BIT:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getBoolean(columnIndex));
break;
case Types.BINARY:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getBytes(columnIndex));
break;
default:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getString(columnIndex) == null ? JSONObject.NULL : rs.getString(columnIndex));
}
}
private static void getOutputParameter(CallableStatement cs, int index, int type, JSONArray parameter) throws SQLException {
switch (type) {
case Types.INTEGER:
parameter.put(cs.getInt(index));
break;
case Types.VARCHAR:
case Types.CHAR:
parameter.put(cs.getString(index));
break;
case Types.BOOLEAN:
parameter.put(cs.getBoolean(index));
break;
case Types.DOUBLE:
parameter.put(cs.getDouble(index));
break;
case Types.BINARY:
parameter.put(cs.getBytes(index));
break;
default:
parameter.put(cs.getString(index));
}
}
private static void registerOutputParameter(CallableStatement cs, int index, Object p, JSONObject types) throws SQLException {
if (p.equals(Integer.class)) {
cs.registerOutParameter(index, Types.INTEGER);
types.put(Integer.toString(index), Types.INTEGER);
} else if (p.equals(String.class)) {
cs.registerOutParameter(index, Types.VARCHAR);
types.put(Integer.toString(index), Types.VARCHAR);
} else if (p.equals(Boolean.class)) {
cs.registerOutParameter(index, Types.BOOLEAN);
types.put(Integer.toString(index), Types.BOOLEAN);
} else if (p.equals(Double.class)) {
cs.registerOutParameter(index, Types.DOUBLE);
types.put(Integer.toString(index), Types.DOUBLE);
}
}
/**
* Setea en el prepared statement el valor del parametro segun su tipo de
* dato.
*
* @param ps representa el objeto PreparedStatement
* @param index indica la posicion del parametro en la consulta sql
* @param p parametro de la consulta sql
* @throws SQLException
*/
private static void setPreparedStatement(PreparedStatement ps, int index, Object p) throws SQLException {
if (p instanceof Integer) {
ps.setInt(index, (int) p);
} else if (p instanceof String) {
ps.setString(index, p.toString());
} else if (p instanceof Double) {
ps.setDouble(index, (double) p);
} else if (p instanceof Boolean) {
ps.setBoolean(index, (boolean) p);
} else if (p instanceof byte[]) {
ps.setBytes(index, (byte[]) p);
} else if (p instanceof Date) {
ps.setDate(index, (Date) p);
} else if (p instanceof BigDecimal) {
ps.setBigDecimal(index, (BigDecimal) p);
} else if (p instanceof Long) {
ps.setDate(index, new Date((long) p));
} else if (p instanceof Array) {
ps.setArray(index, (Array) p);
} else if (p == JSONObject.NULL) {
ps.setNull(index, Types.NULL);
}else if (p instanceof JSONArray || p instanceof JSONObject) {
PGobject object = new PGobject();
object.setType("json");
object.setValue(p.toString());
ps.setObject(index, object);
}
}
// private static void setParameterValueOrNullValue(PreparedStatement ps, int index, Object p, int sqlType) throws SQLException {
// if (p != null) {
// ps.setObject(index, p, sqlType);
// } else {
// ps.setNull(index, sqlType);
// }
// }
private static void clearJSONArray(JSONArray jsonArray) {
while (jsonArray != null && jsonArray.length() > 0) {
jsonArray.remove(0);
}
}
protected static JSONObject queryJSONObject(Connection cn, String query, JSONObject data) throws Exception {
/* ES SIMILAR AL MÉTODO queryWithPaging, pero adaptado para funcionar con JSON
*/
JSONObject salida = new JSONObject();
// JSONArray jsonArray = new JSONArray();//objeto que almacena todas las filas obtenidas por el query
try {
try (PreparedStatement ps = cn.prepareStatement(query)) {
int paramsCount = countChar(query, '?'); // obtenido de Utils.StringUtils
JSONArray _params = data.has("params") ? data.getJSONArray("params") : new JSONArray();
if (data.has("length") && data.has("start")) {
_params
.put(paramsCount - 3, data.getInt("length"))
.put(paramsCount - 2, data.getInt("start"));
}
if (data.has("draw")) {
_params.put(paramsCount - 1, data.getInt("draw"));
}
for (int i = 0; i < paramsCount; i++) {
if (!_params.isNull(i)) {
setPreparedStatement(ps, i + 1, _params.get(i));
} else {
setPreparedStatement(ps, i + 1, JSONObject.NULL);
}
}
System.out.println("QUERY EJECUTADO CON queryJSONObject ------->>>>\n" + ps);
try (ResultSet rs = ps.executeQuery()) {
// ResultSetMetaData rm = rs.getMetaData();
// int numCols = rm.getColumnCount();
if (rs.next()) {
// for (int i = 1; i <= numCols; i++) {
// setJSONObject(rs, rm, i, salida, mode);
salida = new JSONObject(rs.getString("json"));
// }
// System.out.println("INGRESA A LA CONDICIÓN RS.NEXT");
} else {
salida.put("status", false).put("message", "No se encontraron registros para mostrar").put("data", new JSONArray());
if (data.has("length") && data.has("start")) {
salida.put("recordsTotal", 0).put("recordsFiltered", 0);
}
if (data.has("draw")) {
salida.put("draw", data.getInt("draw"));
}
// System.out.println("NO INGRESA A LA CONDICIÓN RS.NEXT");
}
}
}
} catch (Exception ex) {
salida.put("status", false);
salida.put("message", "Hubo un error al realizar la consulta");
throw ex;
} finally {
try {
if (cn != null) {
cn.close();
}
} catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage());
}
}
return salida;
}
}
package pe.so.api.formulario.dao;
import org.json.JSONObject;
public interface ExcelDAO{
public JSONObject execute (JSONObject json) throws Exception;
}
package pe.so.api.formulario.dao;
import pe.so.api.formulario.mongodbdao.MongoDBFactoryDAO;
import pe.so.api.formulario.postgresdao.PostgreSqlFactoryDAO;
public abstract class FactoryDAO{
public static final int MONGODB = 1;
public static final int POSTGRESQL = 2;
public static FactoryDAO getFactoryDAO(int whichFactory) {
switch (whichFactory) {
case MONGODB:
return new MongoDBFactoryDAO();
case POSTGRESQL:
return new PostgreSqlFactoryDAO();
default:
return null;
}
}
public abstract ExcelDAO getExcelDAO();
}
package pe.so.api.formulario.filters;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
@Provider
public class CorsFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException{
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
if(response.getHeader("Access-Control-Allow-Origin").equals("*")){
filterChain.doFilter(servletRequest, response);
}
else if(response.getHeader("Access-Control-Allow-Origin").contains(request.getRemoteHost())) {
filterChain.doFilter(servletRequest, response);
}else{
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
@Override
public void destroy(){
}
}
package pe.so.api.formulario.mongodbdao;
import pe.so.api.formulario.dao.ExcelDAO;
import pe.so.api.formulario.dao.FactoryDAO;
public class MongoDBFactoryDAO extends FactoryDAO{
@Override
public ExcelDAO getExcelDAO(){
return null;
}
}
package pe.so.api.formulario.postgresdao;
import org.json.JSONObject;
import pe.so.api.formulario.dao.ExcelDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
public class PostgreSqlExcel implements ExcelDAO{
@Override
public JSONObject execute(JSONObject json) throws Exception{
JSONObject respuesta = new JSONObject();
Connection conexion = null;
try {
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
java.sql.Timestamp sqlTime = new java.sql.Timestamp(date.getTime());
// String[] jsonString = {"p_drive_origen", "p_drive_fila", "p_fecha_hora_registro", "p_sede", "p_medio_atencion", "p_contacto_nombres", "p_contacto_apellidos", "p_numero_documento", "p_contacto_correo", "p_contacto_telefono", "p_distrito", "p_grado", "p_colegio_procedencia","p_medio_difusion_nombre", "p_atencion_usuario", "p_atencion_fecha", "p_atencion_estado", "p_atencion_medio_atencion", "p_atencion_hora", "p_atencion_observacion"};
String p_drive_origen = json.getString("p_drive_origen");
int p_drive_fila = json.getInt("p_drive_fila");
String p_fecha_hora_registro = json.isNull("p_fecha_hora_registro") ? sqlTime.toString() : json.getString("p_fecha_hora_registro");
String p_sede = json.getString("p_sede");
String p_medio_atencion = json.getString("p_medio_atencion");
String p_contacto_nombres = json.getString("p_contacto_nombres");
String p_contacto_apellidos = json.getString("p_contacto_apellidos");
String p_numero_documento = json.getString("p_numero_documento");
String p_contacto_correo = json.getString("p_contacto_correo");
String p_atencion_usuario = json.getString("p_atencion_usuario");
String p_grado = json.getString("p_grado");
String p_contacto_telefono = json.getString("p_contacto_telefono");
String p_colegio_procedencia = json.getString("p_colegio_procedencia");
String p_distrito = json.getString("p_distrito");
String p_atencion_fecha = json.getString("p_atencion_fecha");
String p_atencion_estado = json.getString("p_atencion_estado");
String p_atencion_medio_atencion = json.getString("p_atencion_medio_atencion");
String p_atencion_hora = json.getString("p_atencion_hora");
String p_atencion_observacion = json.getString("p_atencion_observacion");
String p_medio_difusion_nombre = json.getString("p_medio_difusion_nombre");
conexion = PostgreSqlFactoryDAO.obtenerConexion("siiaa");
String sql = "select matricula.func_informe_registrar(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = conexion.prepareStatement(sql);
ps.setString(1, p_drive_origen);
ps.setInt(2, p_drive_fila);
ps.setString(3, sqlTime.toString());
ps.setString(4, p_sede);
ps.setString(5, p_medio_atencion);
ps.setString(6, p_contacto_nombres);
ps.setString(7, p_contacto_apellidos);
ps.setString(8, p_numero_documento);
ps.setString(9, p_contacto_correo);
ps.setString(10, p_contacto_telefono);
ps.setString(11, p_distrito);
ps.setString(12, p_grado);
ps.setString(13, p_colegio_procedencia);
ps.setString(14, p_medio_difusion_nombre);
ps.setString(15, p_atencion_usuario);
ps.setString(16, p_atencion_fecha);
ps.setString(17, p_atencion_estado);
ps.setString(18, p_atencion_medio_atencion);
ps.setString(19, p_atencion_hora);
ps.setString(20, p_atencion_observacion);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int columnCount = ((ResultSet) rs).getMetaData().getColumnCount();
for (int i = 1; i <= columnCount; i++) {
respuesta.put(rs.getMetaData().getColumnName(i), rs.getObject(i));
}
if(respuesta.getString("func_informe_registrar").contains("_informe_id")){
respuesta.put("status", true);
}else{
respuesta.put("status", false);
}
}
} catch (Exception e) {
respuesta.put("status", false);
respuesta.put("mensaje", e.getMessage());
}finally{
if (conexion != null) {
conexion.close();
}
}
return respuesta;
}
}
package pe.so.api.formulario.postgresdao;
import org.json.JSONObject;
import pe.so.api.formulario.dao.ExcelDAO;
import pe.so.api.formulario.dao.FactoryDAO;
import pe.so.api.formulario.utilities.OsUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverManager;
import org.json.JSONException;
import static pe.so.api.formulario.utilities.Config.getConfig;
public class PostgreSqlFactoryDAO extends FactoryDAO{
static {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection obtenerConexion(String base) {
Connection conexion = null;
JSONObject dbConfig = new JSONObject();
OsUtils.OSType ostype = OsUtils.getOperatingSystemType();
switch (ostype) {
case Windows:
dbConfig = getConfig("C:/dotenv/formularios-api/config.json", "db_config", base);
break;
case Linux:
case MacOS:
dbConfig = getConfig("/opt/dotenv/formularios-api/config.json", "db_config", base);
break;
case Other:
break;
}
try {
conexion = DriverManager.getConnection(
"jdbc:postgresql://" + dbConfig.getString("host") + ":" + dbConfig.getString("port") + "/" + dbConfig.getString("db_name") + "",
dbConfig.getString("user"),
dbConfig.getString("password"));
} catch (SQLException | JSONException e) {
e.printStackTrace();
}
return conexion;
}
@Override
public ExcelDAO getExcelDAO(){
return new PostgreSqlExcel();
}
}
package pe.so.api.formulario.services;
import org.json.JSONObject;
import pe.so.api.formulario.dao.ExcelDAO;
import pe.so.api.formulario.dao.FactoryDAO;
import pe.so.api.formulario.postgresdao.PostgreSqlExcel;
public class ExcelServices{
ExcelDAO dao = FactoryDAO.getFactoryDAO(FactoryDAO.POSTGRESQL).getExcelDAO();
public JSONObject execute(JSONObject json) throws Exception{
return dao.execute(json);
}
}
package pe.so.api.formulario.utilities;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import org.json.JSONObject;
public class Config {
private static JSONObject getJsonFromFile(String path) {
JSONObject response = new JSONObject();
StringBuilder stringJson =new StringBuilder();
File file = new File(path);
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
stringJson.append(scanner.nextLine());
}
scanner.close();
response = new JSONObject(stringJson.toString());
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
public static JSONObject getConfig(String configPath, String config, String configName) {
JSONObject response;
JSONObject configJson = getJsonFromFile(configPath);
response = configJson.getJSONObject(config).getJSONObject(configName);
return response;
}
}
package pe.so.api.formulario.utilities;
import java.io.File;
import java.util.Locale;
public final class OsUtils {
public enum OSType {
Windows, MacOS, Linux, Other
};
// cached result of OS detection
private static String detectedOS;
private static OSType detectedTOS;
/**
* detect the operating system from the os.name System property and cache
* the result
*
* @return - the operating system detected
*/
public static String getOperatingSysstemType() {
if (detectedOS == null) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((OS.contains("mac")) || (OS.contains("darwin"))) {
detectedOS = "MacOS";
} else if (OS.contains("win")) {
detectedOS = "Windows";
} else if (OS.contains("nux")) {
detectedOS = "Linux";
} else {
detectedOS = "Other";
}
}
return detectedOS;
}
public static OSType getOperatingSystemType() {
if (detectedTOS == null) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((OS.contains("mac")) || (OS.contains("darwin"))) {
detectedTOS = OSType.MacOS;
} else if (OS.contains("win")) {
detectedTOS = OSType.Windows;
} else if (OS.contains("nux")) {
detectedTOS = OSType.Linux;
} else {
detectedTOS = OSType.Other;
}
}
return detectedTOS;
}
public static String getDotEnvPathUtil(String projectName) {
String path = "";
String detectedOs = OsUtils.getOperatingSysstemType();
switch (detectedOs) {
case "MacOS":
case "Linux":
path = "/opt/dotenv/"+projectName;
break;
case "Windows":
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
for (char letter : alphabet) {
path = letter + ":/dotenv/" + projectName;
File directory = new File(path);
if (directory.exists()) {
break;
}
}
break;
}
return path;
}
public static String getFilePath(String projectName) {
String path = "";
String detectedOs = OsUtils.getOperatingSysstemType();
switch (detectedOs) {
case "MacOS":
path = "";
break;
case "Windows":
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
for (char letter : alphabet) {
path = letter + ":/AppServ/www/" + projectName+"/";
File directory = new File(path);
if (directory.exists()) {
break;
}
}
break;
case "Linux":
path = "/var/www/html/"+projectName+"/";
break;
}
return path;
}
}
package pe.so.api.formulario.utilities;
import java.util.Vector;
public class StringUtils {
public static int countChar(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
/**
* Divide una cadena según el caracter indicado y un número máximo de
* divisiones si así se desea.
*/
public static String[] split(String str, char sep, int maxNum) {
if (str == null || str.length() == 0) {
/* [1] */
return new String[0];
}
/* [2] */
Vector results = maxNum == 0 ? new Vector() : new Vector(maxNum);
StringBuffer buf = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
/* [3] */
char c = str.charAt(i);
if (c == sep) {
if (maxNum != 0) {
/* [4] */
if ((results.size() + 1) == maxNum) {
for (; i < str.length(); i++) {
buf.append(str.charAt(i));
}
break;
}
}
results.addElement(buf.toString());
buf.setLength(0);
} else {
buf.append(c);
}
}
if (buf.length() > 0) {
results.addElement(buf.toString());
}
return toStringArray(results);
/* [5] */
}
public static String[] toStringArray(Vector strings) {
String[] result = new String[strings.size()];
for (int i = 0; i < strings.size(); i++) {
result[i] = strings.elementAt(i).toString();
}
return result;
}
/**
* Separa un texto en varios según el caracter o cadena usada como
* delimitadora.
*/
public static String[] split(String strString, String strDelimiter) {
int iOccurrences = 0;
int iIndexOfInnerString = 0;
int iIndexOfDelimiter = 0;
int iCounter = 0;
// Check for null input strings.
if (strString == null) {
throw new NullPointerException("Input string cannot be null.");
}
// Check for null or empty delimiter
// strings.
if (strDelimiter.length() <= 0 || strDelimiter == null) {
throw new NullPointerException("Delimeter cannot be null or empty.");
}
// If strString begins with delimiter
// then remove it in
// order
// to comply with the desired format.
if (strString.startsWith(strDelimiter)) {
strString = strString.substring(strDelimiter.length());
}
// If strString does not end with the
// delimiter then add it
// to the string in order to comply with
// the desired format.
if (!strString.endsWith(strDelimiter)) {
strString += strDelimiter;
}
// Count occurrences of the delimiter in
// the string.
// Occurrences should be the same amount
// of inner strings.
while ((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1) {
iOccurrences += 1;
iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
}
// Declare the array with the correct
// size.
String[] strArray = new String[iOccurrences];
// Reset the indices.
iIndexOfInnerString = 0;
iIndexOfDelimiter = 0;
// Walk across the string again and this
// time add the
// strings to the array.
while ((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1) {
// Add string to
// array.
strArray[iCounter] = strString.substring(iIndexOfInnerString,
iIndexOfDelimiter);
// Increment the
// index to the next
// character after
// the next
// delimiter.
iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
// Inc the counter.
iCounter += 1;
}
return strArray;
}
/**
* Reemplaza en un texto la primera aparición del patrón por el texto de
* reemplazo.
*/
public static String replace(String source, String pattern,
String replacement) {
// If source is null then Stop
// and return empty String.
if (source == null) {
return "";
}
StringBuffer sb = new StringBuffer();
// Intialize Index to -1
// to check against it later
int idx = -1;
// Intialize pattern Index
int patIdx = 0;
// Search source from 0 to first occurrence of pattern
// Set Idx equal to index at which pattern is found.
idx = source.indexOf(pattern, patIdx);
// If Pattern is found, idx will not be -1 anymore.
if (idx != -1) {
// append all the string in source till the pattern starts.
sb.append(source.substring(patIdx, idx));
// append replacement of the pattern.
sb.append(replacement);
// Increase the value of patIdx
// till the end of the pattern
patIdx = idx + pattern.length();
// Append remaining string to the String Buffer.
sb.append(source.substring(patIdx));
}
// Return StringBuffer as a String
if (sb.length() == 0) {
return source;
} else {
return sb.toString();
}
}
/**
* Igual que con el método replace pero con todas las apariciones del patrón.
*/
public static String replaceAll(String source, String pattern,
String replacement) {
// If source is null then Stop
// and retutn empty String.
if (source == null) {
return "";
}
StringBuffer sb = new StringBuffer();
// Intialize Index to -1
// to check agaist it later
int idx = -1;
// Search source from 0 to first occurrence of pattern
// Set Idx equal to index at which pattern is found.
String workingSource = source;
// Iterate for the Pattern till idx is not be -1.
while ((idx = workingSource.indexOf(pattern)) != -1) {
// append all the string in source till the pattern starts.
sb.append(workingSource.substring(0, idx));
// append replacement of the pattern.
sb.append(replacement);
// Append remaining string to the String Buffer.
sb.append(workingSource.substring(idx + pattern.length()));
// Store the updated String and check again.
workingSource = sb.toString();
// Reset the StringBuffer.
sb.delete(0, sb.length());
}
return workingSource;
}
/**
* Comprueba que una cadena sea nula o vacía.
*/
public static boolean isNullOrEmpty(String cadena) {
boolean nullOrEmpty = false;
if (cadena == null) {
nullOrEmpty = true;
} else if (cadena.length() == 0) {
nullOrEmpty = true;
}
return nullOrEmpty;
}
/**
* Reduce el tamaño de una cadena mayor al tamaño indicado. En ese caso se
* indicará que esta es más larga acortando y añadiendo 3 puntos seguidos.
*
* @param cadena - Cadena a comprobar.
* @param size - Tamaño máximo.
* @return Cadena original o cortada.
*/
public static String truncateString(String cadena, int size) {
String truncatedString = cadena;
if (truncatedString != null && truncatedString.length() > size) {
truncatedString = cadena.substring(0, size - 4);
truncatedString += "...";
}
return truncatedString;
}
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
/**
* Reduce el tamaño de una cadena mayor al tamaño indicado. En ese caso se
* indicará que esta es más larga acortando y añadiendo 3 puntos seguidos.
* Además añadiremos al final de la cadena truncada la información indicada.
*/
//public static String truncateStringWithInfo(String cadena, int size, String info) {
//return StringUtil.truncateString(cadena, size) + info;
//}
}
......@@ -9,4 +9,12 @@
30
</session-timeout>
</session-config>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>pe.so.api.formulario.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/api/v1/*</url-pattern>
</filter-mapping>
</web-app>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment