[ADD] SE AGREGO NUEVO ENDPOINT PARA AVANCES DE ENCUESTAS

parent 2200f7ef
nb-configuration.xml nb-configuration.xml
target/ target/
.idea .idea
idea idea
\ No newline at end of file
# Default ignored files # Default ignored files
/shelf/ /shelf/
/workspace.xml /workspace.xml
# Editor-based HTTP Client requests # Editor-based HTTP Client requests
/httpRequests/ /httpRequests/
# Datasource local storage ignored files # Datasource local storage ignored files
/dataSources/ /dataSources/
/dataSources.local.xml /dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="CompilerConfiguration"> <component name="CompilerConfiguration">
<annotationProcessing> <annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true"> <profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" /> <sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" /> <sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" /> <outputRelativeToContentRoot value="true" />
<module name="formulario-api" /> <module name="formulario-api" />
</profile> </profile>
</annotationProcessing> </annotationProcessing>
</component> </component>
<component name="JavacSettings"> <component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE"> <option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="formulario-api" options="-endorseddirs D:\formulario-api\target/endorsed" /> <module name="formulario-api" options="-endorseddirs $PROJECT_DIR$/target/endorsed" />
</option> </option>
</component> </component>
</project> </project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true"> <component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="siia" uuid="60957c5c-de91-49ed-adf8-d0fc940d62b3"> <data-source source="LOCAL" name="siia" uuid="60957c5c-de91-49ed-adf8-d0fc940d62b3">
<driver-ref>postgresql</driver-ref> <driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize> <synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver> <jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql://172.16.2.207:5432/postgres</jdbc-url> <jdbc-url>jdbc:postgresql://172.16.2.207:5432/postgres</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir> <working-dir>$ProjectFileDir$</working-dir>
</data-source> </data-source>
</component> </component>
</project> </project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="Encoding"> <component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component> </component>
</project> </project>
\ No newline at end of file
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
</inspection_tool> </inspection_tool>
<inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true"> <inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<Languages> <Languages>
<language minSize="48" name="Java" /> <language minSize="50" name="Java" />
</Languages> </Languages>
</inspection_tool> </inspection_tool>
<inspection_tool class="SpellCheckingInspection" enabled="false" level="WARNING" enabled_by_default="false" editorAttributes="WARNING_ATTRIBUTES"> <inspection_tool class="SpellCheckingInspection" enabled="false" level="WARNING" enabled_by_default="false" editorAttributes="WARNING_ATTRIBUTES">
...@@ -19,5 +19,6 @@ ...@@ -19,5 +19,6 @@
<option name="processLiterals" value="true" /> <option name="processLiterals" value="true" />
<option name="processComments" value="true" /> <option name="processComments" value="true" />
</inspection_tool> </inspection_tool>
<inspection_tool class="VulnerableCodeUsages" enabled="false" level="WARNING" enabled_by_default="false" />
</profile> </profile>
</component> </component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="RemoteRepositoriesConfiguration"> <component name="RemoteRepositoriesConfiguration">
<remote-repository> <remote-repository>
<option name="id" value="snapshots" /> <option name="id" value="snapshots" />
<option name="name" value="snapshots" /> <option name="name" value="snapshots" />
<option name="url" value="http://161.97.127.173:8081/repository/mvn-poqh-snapshot/" /> <option name="url" value="http://161.97.127.173:8081/repository/mvn-poqh-snapshot/" />
</remote-repository> </remote-repository>
<remote-repository> <remote-repository>
<option name="id" value="central" /> <option name="id" value="central" />
<option name="name" value="Central Repository" /> <option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" /> <option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository> </remote-repository>
<remote-repository> <remote-repository>
<option name="id" value="releases" /> <option name="id" value="releases" />
<option name="name" value="releases" /> <option name="name" value="releases" />
<option name="url" value="http://161.97.127.173:8081/repository/mvn-poqh-release/" /> <option name="url" value="http://161.97.127.173:8081/repository/mvn-poqh-release/" />
</remote-repository> </remote-repository>
<remote-repository> <remote-repository>
<option name="id" value="central" /> <option name="id" value="central" />
<option name="name" value="Maven Plugin Repository" /> <option name="name" value="Maven Plugin Repository" />
<option name="url" value="https://repo1.maven.org/maven2" /> <option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository> </remote-repository>
<remote-repository> <remote-repository>
<option name="id" value="central" /> <option name="id" value="central" />
<option name="name" value="Maven Central repository" /> <option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" /> <option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository> </remote-repository>
<remote-repository> <remote-repository>
<option name="id" value="jboss.community" /> <option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" /> <option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" /> <option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository> </remote-repository>
<remote-repository> <remote-repository>
<option name="id" value="snapshots-hosted" /> <option name="id" value="snapshots-hosted" />
<option name="name" value="snapshots-hosted" /> <option name="name" value="snapshots-hosted" />
<option name="url" value="http://161.97.127.173:8081/repository/mvn-poqh-hosted-snapshot/" /> <option name="url" value="http://161.97.127.173:8081/repository/mvn-poqh-hosted-snapshot/" />
</remote-repository> </remote-repository>
</component> </component>
</project> </project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="JpaBuddyIdeaProjectConfig"> <component name="JpaBuddyIdeaProjectConfig">
<option name="defaultUnitInitialized" value="true" /> <option name="defaultUnitInitialized" value="true" />
<option name="renamerInitialized" value="true" /> <option name="renamerInitialized" value="true" />
</component> </component>
</project> </project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" /> <component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration"> <component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" /> <file type="web" url="file://$PROJECT_DIR$" />
</component> </component>
<component name="MavenProjectsManager"> <component name="MavenProjectsManager">
<option name="originalFiles"> <option name="originalFiles">
<list> <list>
<option value="$PROJECT_DIR$/pom.xml" /> <option value="$PROJECT_DIR$/pom.xml" />
</list> </list>
</option> </option>
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="corretto-11" project-jdk-type="JavaSDK" /> <component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="corretto-11" project-jdk-type="JavaSDK" />
<component name="ProjectType"> <component name="ProjectType">
<option name="id" value="jpab" /> <option name="id" value="jpab" />
</component> </component>
</project> </project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="SaveActionSettings"> <component name="SaveActionSettings">
<option name="actions"> <option name="actions">
<set> <set>
<option value="activateOnShortcut" /> <option value="activateOnShortcut" />
<option value="reload" /> <option value="reload" />
<option value="executeAction" /> <option value="executeAction" />
</set> </set>
</option> </option>
<option name="configurationPath" value="" /> <option name="configurationPath" value="" />
<option name="quickLists"> <option name="quickLists">
<list> <list>
<option value="-1109336397" /> <option value="-1109336397" />
</list> </list>
</option> </option>
</component> </component>
</project> </project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="SqlDialectMappings"> <component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/java/pe/so/api/formulario/postgresdao/PostgreSqlExcel.java" dialect="PostgreSQL" /> <file url="file://$PROJECT_DIR$/src/main/java/pe/so/api/formulario/postgresdao/PostgreSqlExcel.java" dialect="PostgreSQL" />
</component> </component>
</project> </project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="VcsDirectoryMappings"> <component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" /> <mapping directory="" vcs="Git" />
</component> </component>
</project> </project>
\ No newline at end of file
# Trismegisto-mongo API # Trismegisto-mongo API
API Rest especifica para formularios API Rest especifica para formularios
\ No newline at end of file
package pe.so.api.formulario.api; package pe.so.api.formulario.api;
import pe.so.api.formulario.filters.CorsFilter; import pe.so.api.formulario.filters.CorsFilter;
import javax.ws.rs.ApplicationPath; import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application; import javax.ws.rs.core.Application;
import java.util.*; import java.util.*;
@ApplicationPath("api/v1") @ApplicationPath("api/v1")
public class ApiConfig extends Application { public class ApiConfig extends Application {
private final Set<Object> singletons = new HashSet<>(); private final Set<Object> singletons = new HashSet<>();
private final HashSet<Class<?>> classes = new HashSet<>(); private final HashSet<Class<?>> classes = new HashSet<>();
public ApiConfig() { public ApiConfig() {
singletons.add(new CorsFilter()); singletons.add(new CorsFilter());
classes.add(ExcelApi.class); classes.add(ExcelApi.class);
classes.add(TablaApi.class); classes.add(TablaApi.class);
} }
@Override @Override
public Set<Object> getSingletons() { public Set<Object> getSingletons() {
return singletons; return singletons;
} }
@Override @Override
public HashSet<Class<?>> getClasses() { public HashSet<Class<?>> getClasses() {
return classes; return classes;
} }
} }
package pe.so.api.formulario.api; package pe.so.api.formulario.api;
import org.json.JSONObject; import org.json.JSONObject;
import pe.so.api.formulario.services.ExcelServices; import pe.so.api.formulario.services.ExcelServices;
import pe.so.api.formulario.services.TablasServices; import pe.so.api.formulario.services.TablasServices;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Provider;
@Provider @Provider
@Path("tabla") @Path("tabla")
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public class TablaApi{ public class TablaApi{
@Path("/ids") @Path("/ids")
@POST @POST
public Response tablaIds(String json) throws Exception{ public Response tablaIds(String json) throws Exception{
TablasServices tablasServices = new TablasServices(); TablasServices tablasServices = new TablasServices();
JSONObject MSJ_RESPUESTA=tablasServices.tablaIds(new JSONObject(json)); JSONObject MSJ_RESPUESTA=tablasServices.tablaIds(new JSONObject(json));
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build(); return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
} }
} }
package pe.so.api.formulario.dao; package pe.so.api.formulario.dao;
import org.json.JSONObject; import org.json.JSONObject;
public interface ExcelDAO{ public interface ExcelDAO{
JSONObject execute_encuesta (JSONObject json) throws Exception; JSONObject execute_encuesta (JSONObject json) throws Exception;
JSONObject execute_balotario (JSONObject json) throws Exception; JSONObject execute_balotario (JSONObject json) throws Exception;
JSONObject ejecutar(JSONObject json) throws Exception; JSONObject ejecutar(JSONObject json) throws Exception;
JSONObject execute_avance (JSONObject json) throws Exception; JSONObject execute_avance (JSONObject json) throws Exception;
JSONObject execute_redes (JSONObject json) throws Exception; JSONObject execute_redes (JSONObject json) throws Exception;
JSONObject execute_VU (JSONObject json) throws Exception; JSONObject execute_VU (JSONObject json) throws Exception;
JSONObject execute_reporte_sedes (JSONObject json) throws Exception; JSONObject execute_reporte_sedes (JSONObject json) throws Exception;
JSONObject execute_reporte_correos (JSONObject json) throws Exception; JSONObject execute_reporte_correos (JSONObject json) throws Exception;
} JSONObject execute_avance_encuesta (JSONObject json) throws Exception;
}
package pe.so.api.formulario.dao; package pe.so.api.formulario.dao;
import pe.so.api.formulario.mongodbdao.MongoDBFactoryDAO; import pe.so.api.formulario.mongodbdao.MongoDBFactoryDAO;
import pe.so.api.formulario.postgresdao.PostgreSqlFactoryDAO; import pe.so.api.formulario.postgresdao.PostgreSqlFactoryDAO;
public abstract class FactoryDAO{ public abstract class FactoryDAO{
public static final int MONGODB = 1; public static final int MONGODB = 1;
public static final int POSTGRESQL = 2; public static final int POSTGRESQL = 2;
public static FactoryDAO getFactoryDAO(int whichFactory) { public static FactoryDAO getFactoryDAO(int whichFactory) {
switch (whichFactory) { switch (whichFactory) {
case MONGODB: case MONGODB:
return new MongoDBFactoryDAO(); return new MongoDBFactoryDAO();
case POSTGRESQL: case POSTGRESQL:
return new PostgreSqlFactoryDAO(); return new PostgreSqlFactoryDAO();
default: default:
return null; return null;
} }
} }
public abstract ExcelDAO getExcelDAO(); public abstract ExcelDAO getExcelDAO();
public abstract TablasDAO getTablasDAO(); public abstract TablasDAO getTablasDAO();
} }
package pe.so.api.formulario.dao; package pe.so.api.formulario.dao;
import org.json.JSONObject; import org.json.JSONObject;
public interface TablasDAO { public interface TablasDAO {
JSONObject tablaIds (JSONObject json) throws Exception; JSONObject tablaIds (JSONObject json) throws Exception;
} }
package pe.so.api.formulario.filters; package pe.so.api.formulario.filters;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import pe.so.api.formulario.postgresdao.PostgreSqlTabla; import pe.so.api.formulario.postgresdao.PostgreSqlTabla;
import javax.servlet.*; import javax.servlet.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Provider;
import java.io.IOException; import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@Provider @Provider
public class CorsFilter implements Filter{ public class CorsFilter implements Filter{
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException{ public void init(FilterConfig filterConfig) throws ServletException{
} }
@Override @Override
public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException{ public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException{
String[] ExcelIds={"1ItAa2YGBj60AVghmsCfMJZYooDRQGN2gyPWpgtvGHxA", String[] ExcelIds={"1ItAa2YGBj60AVghmsCfMJZYooDRQGN2gyPWpgtvGHxA",
"1puh5xCtsGwwFaqKSgPcRt5II23MtZ2C9u0C_ussVYyc"}; "1puh5xCtsGwwFaqKSgPcRt5II23MtZ2C9u0C_ussVYyc"};
HttpServletResponse response=(HttpServletResponse)servletResponse; HttpServletResponse response=(HttpServletResponse)servletResponse;
HttpServletRequest request=(HttpServletRequest)servletRequest; HttpServletRequest request=(HttpServletRequest)servletRequest;
response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS,HEAD"); response.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS,HEAD");
response.setHeader("Access-Control-Max-Age","3600"); response.setHeader("Access-Control-Max-Age","3600");
response.setHeader("Access-Control-Allow-Headers","x-requested-with, Content-Type, Authorization"); response.setHeader("Access-Control-Allow-Headers","x-requested-with, Content-Type, Authorization");
response.setHeader("Access-Control-Allow-Credentials","true"); response.setHeader("Access-Control-Allow-Credentials","true");
try { try {
if((response.getHeader("Access-Control-Allow-Origin").equals("*") || if((response.getHeader("Access-Control-Allow-Origin").equals("*") ||
response.getHeader("Access-Control-Allow-Origin").contains(request.getRemoteHost())) && response.getHeader("Access-Control-Allow-Origin").contains(request.getRemoteHost())) &&
(Arrays.asList(ExcelIds).contains(request.getHeader("Authorization")) || existeId(request.getHeader("Authorization")))){ (Arrays.asList(ExcelIds).contains(request.getHeader("Authorization")) || existeId(request.getHeader("Authorization")))){
filterChain.doFilter(servletRequest,response); filterChain.doFilter(servletRequest,response);
} else { } else {
response.setContentType("application/json"); response.setContentType("application/json");
response.setStatus(401); response.setStatus(401);
response.getWriter().write("{\"mensaje\":\"No estas autorizado a usar este recurso.\",\"status\":false}"); response.getWriter().write("{\"mensaje\":\"No estas autorizado a usar este recurso.\",\"status\":false}");
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@Override @Override
public void destroy(){ public void destroy(){
} }
private Boolean existeId(String id) throws SQLException{ private Boolean existeId(String id) throws SQLException{
AtomicReference<Boolean> existe=new AtomicReference<>(false); AtomicReference<Boolean> existe=new AtomicReference<>(false);
JSONArray data=new PostgreSqlTabla().tablaIds(new JSONObject().put("tabla","ac_encuesta_plc")).getJSONArray("data"); JSONArray data=new PostgreSqlTabla().tablaIds(new JSONObject().put("tabla","ac_encuesta_plc")).getJSONArray("data");
JSONArray data2=new PostgreSqlTabla().tablaIds(new JSONObject().put("tabla","ac_balotario")).getJSONArray("data"); JSONArray data2=new PostgreSqlTabla().tablaIds(new JSONObject().put("tabla","ac_balotario")).getJSONArray("data");
data.forEach(obj -> { data.forEach(obj -> {
JSONObject o=(JSONObject)obj; JSONObject o=(JSONObject)obj;
if(o.getString("id").equals(id)){ if(o.getString("id").equals(id)){
existe.set(true); existe.set(true);
} }
}); });
data2.forEach(obj -> { data2.forEach(obj -> {
JSONObject o=(JSONObject)obj; JSONObject o=(JSONObject)obj;
if(o.getString("id").equals(id)){ if(o.getString("id").equals(id)){
existe.set(true); existe.set(true);
} }
}); });
return existe.get(); return existe.get();
} }
} }
package pe.so.api.formulario.mongodbdao; package pe.so.api.formulario.mongodbdao;
import pe.so.api.formulario.dao.ExcelDAO; import pe.so.api.formulario.dao.ExcelDAO;
import pe.so.api.formulario.dao.FactoryDAO; import pe.so.api.formulario.dao.FactoryDAO;
import pe.so.api.formulario.dao.TablasDAO; import pe.so.api.formulario.dao.TablasDAO;
public class MongoDBFactoryDAO extends FactoryDAO{ public class MongoDBFactoryDAO extends FactoryDAO{
@Override @Override
public ExcelDAO getExcelDAO(){ public ExcelDAO getExcelDAO(){
return null; return null;
} }
@Override @Override
public TablasDAO getTablasDAO(){ public TablasDAO getTablasDAO(){
return null; return null;
} }
} }
package pe.so.api.formulario.postgresdao; package pe.so.api.formulario.postgresdao;
import org.json.JSONObject; import org.json.JSONObject;
import pe.so.api.formulario.dao.ExcelDAO; import pe.so.api.formulario.dao.ExcelDAO;
import pe.so.api.formulario.dao.FactoryDAO; import pe.so.api.formulario.dao.FactoryDAO;
import pe.so.api.formulario.dao.TablasDAO; import pe.so.api.formulario.dao.TablasDAO;
import pe.so.api.formulario.utilities.OsUtils; import pe.so.api.formulario.utilities.OsUtils;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.DriverManager; import java.sql.DriverManager;
import org.json.JSONException; import org.json.JSONException;
import static pe.so.api.formulario.utilities.Config.getConfig; import static pe.so.api.formulario.utilities.Config.getConfig;
public class PostgreSqlFactoryDAO extends FactoryDAO{ public class PostgreSqlFactoryDAO extends FactoryDAO{
static { static {
try { try {
Class.forName(" org.postgresql.Driver"); Class.forName(" org.postgresql.Driver");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static Connection obtenerConexion(String base) { public static Connection obtenerConexion(String base) {
Connection conexion = null; Connection conexion = null;
JSONObject dbConfig = new JSONObject(); JSONObject dbConfig = new JSONObject();
OsUtils.OSType ostype = OsUtils.getOperatingSystemType(); OsUtils.OSType ostype = OsUtils.getOperatingSystemType();
switch (ostype) { switch (ostype) {
case Windows: case Windows:
dbConfig = getConfig("C:/dotenv/formularios-api/config.json", "db_config", base); dbConfig = getConfig("C:/dotenv/formularios-api/config.json", "db_config", base);
break; break;
case Linux: case Linux:
case MacOS: case MacOS:
dbConfig = getConfig("/opt/dotenv/formularios-api/config.json", "db_config", base); dbConfig = getConfig("/opt/dotenv/formularios-api/config.json", "db_config", base);
break; break;
case Other: case Other:
break; break;
} }
try { try {
conexion = DriverManager.getConnection( conexion = DriverManager.getConnection(
"jdbc:postgresql://" + dbConfig.getString("host") + ":" + dbConfig.getString("port") + "/" + dbConfig.getString("db_name") + "", "jdbc:postgresql://" + dbConfig.getString("host") + ":" + dbConfig.getString("port") + "/" + dbConfig.getString("db_name") + "",
dbConfig.getString("user"), dbConfig.getString("user"),
dbConfig.getString("password")); dbConfig.getString("password"));
} catch (SQLException | JSONException e) { } catch (SQLException | JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
return conexion; return conexion;
} }
@Override @Override
public ExcelDAO getExcelDAO(){ public ExcelDAO getExcelDAO(){
return new PostgreSqlExcel(); return new PostgreSqlExcel();
} }
public TablasDAO getTablasDAO(){ public TablasDAO getTablasDAO(){
return new PostgreSqlTabla(); return new PostgreSqlTabla();
} }
} }
package pe.so.api.formulario.postgresdao; package pe.so.api.formulario.postgresdao;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import pe.so.api.formulario.dao.TablasDAO; import pe.so.api.formulario.dao.TablasDAO;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
public class PostgreSqlTabla implements TablasDAO{ public class PostgreSqlTabla implements TablasDAO{
@Override @Override
public JSONObject tablaIds(JSONObject json) throws SQLException{ public JSONObject tablaIds(JSONObject json) throws SQLException{
JSONArray data = new JSONArray(); JSONArray data = new JSONArray();
JSONObject respuesta = new JSONObject(); JSONObject respuesta = new JSONObject();
Connection conexion = null; Connection conexion = null;
String[] columnas = {}; String[] columnas = {};
if(json.getString("tabla").equals("ac_encuesta_plc")){ if(json.getString("tabla").equals("ac_encuesta_plc")){
columnas = new String[]{"grupo_encuesta","respuesta_encuesta_drive_id"}; columnas = new String[]{"grupo_encuesta","respuesta_encuesta_drive_id"};
} else if(json.getString("tabla").equals("ac_balotario")){ } else if(json.getString("tabla").equals("ac_balotario")){
columnas = new String[]{"formulario_titulo","formulario_respuesta_url"}; columnas = new String[]{"formulario_titulo","formulario_respuesta_url"};
} }
try{ try{
conexion = PostgreSqlFactoryDAO.obtenerConexion("siiaa"); conexion = PostgreSqlFactoryDAO.obtenerConexion("siiaa");
String sql = ""; String sql = "";
sql = "SELECT * FROM academico."+json.getString("tabla")+""; sql = "SELECT * FROM academico."+json.getString("tabla")+"";
Statement st = conexion.createStatement(); Statement st = conexion.createStatement();
ResultSet rs = st.executeQuery(sql); ResultSet rs = st.executeQuery(sql);
while(rs.next()){ while(rs.next()){
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("nombre", rs.getString(columnas[0])); obj.put("nombre", rs.getString(columnas[0]));
obj.put("id", rs.getString(columnas[1])); obj.put("id", rs.getString(columnas[1]));
data.put(obj); data.put(obj);
} }
respuesta.put("data", data); respuesta.put("data", data);
respuesta.put("status", true); respuesta.put("status", true);
respuesta.put("mensaje", "OK"); respuesta.put("mensaje", "OK");
}catch (Exception e){ }catch (Exception e){
respuesta.put("mensaje", e.getMessage()); respuesta.put("mensaje", e.getMessage());
return respuesta; return respuesta;
}finally { }finally {
if (conexion != null) { if (conexion != null) {
conexion.close(); conexion.close();
} }
} }
return respuesta; return respuesta;
} }
} }
package pe.so.api.formulario.services; package pe.so.api.formulario.services;
import org.json.JSONObject; import org.json.JSONObject;
import pe.so.api.formulario.dao.ExcelDAO; import pe.so.api.formulario.dao.ExcelDAO;
import pe.so.api.formulario.dao.FactoryDAO; import pe.so.api.formulario.dao.FactoryDAO;
public class ExcelServices{ public class ExcelServices{
ExcelDAO dao = FactoryDAO.getFactoryDAO(FactoryDAO.POSTGRESQL).getExcelDAO(); ExcelDAO dao = FactoryDAO.getFactoryDAO(FactoryDAO.POSTGRESQL).getExcelDAO();
public JSONObject execute_encuesta(JSONObject json) throws Exception{ public JSONObject execute_encuesta(JSONObject json) throws Exception{
return dao.execute_encuesta(json); return dao.execute_encuesta(json);
} }
public JSONObject execute_balotario(JSONObject json) throws Exception{ public JSONObject execute_balotario(JSONObject json) throws Exception{
return dao.execute_balotario(json); return dao.execute_balotario(json);
} }
public JSONObject ejecutar(JSONObject json) throws Exception{ public JSONObject ejecutar(JSONObject json) throws Exception{
return dao.ejecutar(json); return dao.ejecutar(json);
} }
public JSONObject execute_avance(JSONObject json) throws Exception{ public JSONObject execute_avance(JSONObject json) throws Exception{
return dao.execute_avance(json); return dao.execute_avance(json);
} }
public JSONObject execute_redes(JSONObject json) throws Exception{ public JSONObject execute_redes(JSONObject json) throws Exception{
return dao.execute_redes(json); return dao.execute_redes(json);
} }
public JSONObject execute_VU(JSONObject json) throws Exception{ public JSONObject execute_VU(JSONObject json) throws Exception{
return dao.execute_VU(json); return dao.execute_VU(json);
} }
public JSONObject execute_reporte_sedes(JSONObject json) throws Exception{ public JSONObject execute_reporte_sedes(JSONObject json) throws Exception{
return dao.execute_reporte_sedes(json); return dao.execute_reporte_sedes(json);
} }
public JSONObject execute_reporte_correos(JSONObject json) throws Exception{ public JSONObject execute_reporte_correos(JSONObject json) throws Exception{
return dao.execute_reporte_correos(json); return dao.execute_reporte_correos(json);
} }
}
public JSONObject execute_avance_encuesta(JSONObject json) throws Exception{
return dao.execute_avance_encuesta(json);
}
}
package pe.so.api.formulario.services; package pe.so.api.formulario.services;
import org.json.JSONObject; import org.json.JSONObject;
import pe.so.api.formulario.dao.FactoryDAO; import pe.so.api.formulario.dao.FactoryDAO;
import pe.so.api.formulario.dao.TablasDAO; import pe.so.api.formulario.dao.TablasDAO;
public class TablasServices{ public class TablasServices{
TablasDAO dao =FactoryDAO.getFactoryDAO(FactoryDAO.POSTGRESQL).getTablasDAO(); TablasDAO dao =FactoryDAO.getFactoryDAO(FactoryDAO.POSTGRESQL).getTablasDAO();
public JSONObject tablaIds(JSONObject json) throws Exception{ public JSONObject tablaIds(JSONObject json) throws Exception{
return dao.tablaIds(json); return dao.tablaIds(json);
} }
} }
package pe.so.api.formulario.utilities; package pe.so.api.formulario.utilities;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class Commons{ public class Commons{
public static JSONObject formatoJSON (String[] formato){ public static JSONObject formatoJSON (String[] formato){
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
for (String key : formato) { for (String key : formato) {
json.put(key, "valor"); json.put(key, "valor");
} }
return json; return json;
} }
public static boolean validarFormato(String[] formato,String json) { public static boolean validarFormato(String[] formato,String json) {
JSONObject entrada = new JSONObject(json); JSONObject entrada = new JSONObject(json);
for (String key : formato) { for (String key : formato) {
if (!entrada.has(key)) { if (!entrada.has(key)) {
return false; return false;
} }
} }
return true; return true;
} }
public static boolean like(final String str, final String expr) public static boolean like(final String str, final String expr)
{ {
String regex = quotemeta(expr); String regex = quotemeta(expr);
regex = regex.replace("_", ".").replace("%", ".*?"); regex = regex.replace("_", ".").replace("%", ".*?");
Pattern p = Pattern.compile(regex, Pattern p = Pattern.compile(regex,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
return p.matcher(str).matches(); return p.matcher(str).matches();
} }
public static String quotemeta(String s) public static String quotemeta(String s)
{ {
if (s == null) if (s == null)
{ {
throw new IllegalArgumentException("String cannot be null"); throw new IllegalArgumentException("String cannot be null");
} }
int len = s.length(); int len = s.length();
if (len == 0) if (len == 0)
{ {
return ""; return "";
} }
StringBuilder sb = new StringBuilder(len * 2); StringBuilder sb = new StringBuilder(len * 2);
for (int i = 0; i < len; i++) for (int i = 0; i < len; i++)
{ {
char c = s.charAt(i); char c = s.charAt(i);
if ("[](){}.*+?$^|#\\".indexOf(c) != -1) if ("[](){}.*+?$^|#\\".indexOf(c) != -1)
{ {
sb.append("\\"); sb.append("\\");
} }
sb.append(c); sb.append(c);
} }
return sb.toString(); return sb.toString();
} }
} }
package pe.so.api.formulario.utilities; package pe.so.api.formulario.utilities;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Scanner; import java.util.Scanner;
import org.json.JSONObject; import org.json.JSONObject;
public class Config { public class Config {
private static JSONObject getJsonFromFile(String path) { private static JSONObject getJsonFromFile(String path) {
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
StringBuilder stringJson =new StringBuilder(); StringBuilder stringJson =new StringBuilder();
File file = new File(path); File file = new File(path);
try { try {
Scanner scanner = new Scanner(file); Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) { while (scanner.hasNextLine()) {
stringJson.append(scanner.nextLine()); stringJson.append(scanner.nextLine());
} }
scanner.close(); scanner.close();
response = new JSONObject(stringJson.toString()); response = new JSONObject(stringJson.toString());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return response; return response;
} }
public static JSONObject getConfig(String configPath, String config, String configName) { public static JSONObject getConfig(String configPath, String config, String configName) {
JSONObject response; JSONObject response;
JSONObject configJson = getJsonFromFile(configPath); JSONObject configJson = getJsonFromFile(configPath);
response = configJson.getJSONObject(config).getJSONObject(configName); response = configJson.getJSONObject(config).getJSONObject(configName);
return response; return response;
} }
} }
package pe.so.api.formulario.utilities; package pe.so.api.formulario.utilities;
import java.io.File; import java.io.File;
import java.util.Locale; import java.util.Locale;
public final class OsUtils { public final class OsUtils {
public enum OSType { public enum OSType {
Windows, MacOS, Linux, Other Windows, MacOS, Linux, Other
}; };
// cached result of OS detection // cached result of OS detection
private static String detectedOS; private static String detectedOS;
private static OSType detectedTOS; private static OSType detectedTOS;
/** /**
* detect the operating system from the os.name System property and cache * detect the operating system from the os.name System property and cache
* the result * the result
* *
* @return - the operating system detected * @return - the operating system detected
*/ */
public static String getOperatingSysstemType() { public static String getOperatingSysstemType() {
if (detectedOS == null) { if (detectedOS == null) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((OS.contains("mac")) || (OS.contains("darwin"))) { if ((OS.contains("mac")) || (OS.contains("darwin"))) {
detectedOS = "MacOS"; detectedOS = "MacOS";
} else if (OS.contains("win")) { } else if (OS.contains("win")) {
detectedOS = "Windows"; detectedOS = "Windows";
} else if (OS.contains("nux")) { } else if (OS.contains("nux")) {
detectedOS = "Linux"; detectedOS = "Linux";
} else { } else {
detectedOS = "Other"; detectedOS = "Other";
} }
} }
return detectedOS; return detectedOS;
} }
public static OSType getOperatingSystemType() { public static OSType getOperatingSystemType() {
if (detectedTOS == null) { if (detectedTOS == null) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((OS.contains("mac")) || (OS.contains("darwin"))) { if ((OS.contains("mac")) || (OS.contains("darwin"))) {
detectedTOS = OSType.MacOS; detectedTOS = OSType.MacOS;
} else if (OS.contains("win")) { } else if (OS.contains("win")) {
detectedTOS = OSType.Windows; detectedTOS = OSType.Windows;
} else if (OS.contains("nux")) { } else if (OS.contains("nux")) {
detectedTOS = OSType.Linux; detectedTOS = OSType.Linux;
} else { } else {
detectedTOS = OSType.Other; detectedTOS = OSType.Other;
} }
} }
return detectedTOS; return detectedTOS;
} }
public static String getDotEnvPathUtil(String projectName) { public static String getDotEnvPathUtil(String projectName) {
String path = ""; String path = "";
String detectedOs = OsUtils.getOperatingSysstemType(); String detectedOs = OsUtils.getOperatingSysstemType();
switch (detectedOs) { switch (detectedOs) {
case "MacOS": case "MacOS":
case "Linux": case "Linux":
path = "/opt/dotenv/"+projectName; path = "/opt/dotenv/"+projectName;
break; break;
case "Windows": case "Windows":
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray(); char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
for (char letter : alphabet) { for (char letter : alphabet) {
path = letter + ":/dotenv/" + projectName; path = letter + ":/dotenv/" + projectName;
File directory = new File(path); File directory = new File(path);
if (directory.exists()) { if (directory.exists()) {
break; break;
} }
} }
break; break;
} }
return path; return path;
} }
public static String getFilePath(String projectName) { public static String getFilePath(String projectName) {
String path = ""; String path = "";
String detectedOs = OsUtils.getOperatingSysstemType(); String detectedOs = OsUtils.getOperatingSysstemType();
switch (detectedOs) { switch (detectedOs) {
case "MacOS": case "MacOS":
path = ""; path = "";
break; break;
case "Windows": case "Windows":
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray(); char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
for (char letter : alphabet) { for (char letter : alphabet) {
path = letter + ":/AppServ/www/" + projectName+"/"; path = letter + ":/AppServ/www/" + projectName+"/";
File directory = new File(path); File directory = new File(path);
if (directory.exists()) { if (directory.exists()) {
break; break;
} }
} }
break; break;
case "Linux": case "Linux":
path = "/var/www/html/"+projectName+"/"; path = "/var/www/html/"+projectName+"/";
break; break;
} }
return path; return path;
} }
} }
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<jboss-web version="8.0" xmlns="http://www.jboss.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/schema/jbossas/jboss-web_8_0.xsd"> <jboss-web version="8.0" xmlns="http://www.jboss.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/schema/jbossas/jboss-web_8_0.xsd">
<context-root>/formulario-api</context-root> <context-root>/formulario-api</context-root>
</jboss-web> </jboss-web>
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"> version="3.1">
<session-config> <session-config>
<session-timeout> <session-timeout>
30 30
</session-timeout> </session-timeout>
</session-config> </session-config>
<filter> <filter>
<filter-name>CorsFilter</filter-name> <filter-name>CorsFilter</filter-name>
<filter-class>pe.so.api.formulario.filters.CorsFilter</filter-class> <filter-class>pe.so.api.formulario.filters.CorsFilter</filter-class>
</filter> </filter>
<filter-mapping> <filter-mapping>
<filter-name>CorsFilter</filter-name> <filter-name>CorsFilter</filter-name>
<url-pattern>/api/v1/*</url-pattern> <url-pattern>/api/v1/*</url-pattern>
</filter-mapping> </filter-mapping>
</web-app> </web-app>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<title>FORMULARIO-API</title> <title>FORMULARIO-API</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head> </head>
<body> <body>
<h1>FORMULARIO-API</h1> <h1>FORMULARIO-API</h1>
</body> </body>
</html> </html>
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