[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="Palette2"> <component name="Palette2">
<group name="Swing"> <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"> <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" /> <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item> </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"> <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" /> <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item> </item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false"> <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" /> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item> </item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true"> <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" /> <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item> </item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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" /> <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values> <initial-values>
<property name="text" value="Button" /> <property name="text" value="Button" />
</initial-values> </initial-values>
</item> </item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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" /> <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values> <initial-values>
<property name="text" value="RadioButton" /> <property name="text" value="RadioButton" />
</initial-values> </initial-values>
</item> </item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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" /> <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values> <initial-values>
<property name="text" value="CheckBox" /> <property name="text" value="CheckBox" />
</initial-values> </initial-values>
</item> </item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false"> <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" /> <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values> <initial-values>
<property name="text" value="Label" /> <property name="text" value="Label" />
</initial-values> </initial-values>
</item> </item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true"> <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"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" /> <preferred-size width="150" height="-1" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true"> <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"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" /> <preferred-size width="150" height="-1" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true"> <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"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" /> <preferred-size width="150" height="-1" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true"> <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"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" /> <preferred-size width="150" height="50" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true"> <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"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" /> <preferred-size width="150" height="50" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true"> <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"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" /> <preferred-size width="150" height="50" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true"> <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" /> <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item> </item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" /> <preferred-size width="150" height="50" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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"> <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" /> <preferred-size width="150" height="50" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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"> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" /> <preferred-size width="150" height="50" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" /> <preferred-size width="200" height="200" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false"> <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"> <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" /> <preferred-size width="200" height="200" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true"> <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" /> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item> </item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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" /> <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item> </item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false"> <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" /> <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item> </item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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" /> <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item> </item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false"> <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"> <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" /> <preferred-size width="-1" height="20" />
</default-constraints> </default-constraints>
</item> </item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false"> <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" /> <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item> </item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false"> <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" /> <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item> </item>
</group> </group>
</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
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>pe.so.api.formulario</groupId> <groupId>pe.so.api.formulario</groupId>
<artifactId>formulario-api</artifactId> <artifactId>formulario-api</artifactId>
<version>1.0</version> <version>1.0</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>formulario-api</name> <name>formulario-api</name>
<properties> <properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.postgresql</groupId> <groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId> <artifactId>postgresql</artifactId>
<version>42.5.0</version> <version>42.5.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.json</groupId> <groupId>org.json</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
<version>20201115</version> <version>20201115</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.mail</groupId> <groupId>javax.mail</groupId>
<artifactId>mail</artifactId> <artifactId>mail</artifactId>
<version>1.5.0-b01</version> <version>1.5.0-b01</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.apis</groupId> <groupId>com.google.apis</groupId>
<artifactId>google-api-services-admin-directory</artifactId> <artifactId>google-api-services-admin-directory</artifactId>
<version>directory_v1-rev20191003-1.30.8</version> <version>directory_v1-rev20191003-1.30.8</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.http-client</groupId> <groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId> <artifactId>google-http-client-jackson2</artifactId>
<version>1.27.0</version> <version>1.27.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.lowagie</groupId> <groupId>com.lowagie</groupId>
<artifactId>itext</artifactId> <artifactId>itext</artifactId>
<version>2.1.7</version> <version>2.1.7</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.jsoup</groupId> <groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId> <artifactId>jsoup</artifactId>
<version>1.11.2</version> <version>1.11.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.2</version> <version>2.2</version>
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax</groupId> <groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId> <artifactId>javaee-web-api</artifactId>
<version>7.0</version> <version>7.0</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.googlecode.json-simple</groupId> <groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId> <artifactId>json-simple</artifactId>
<version>1.1.1</version> <version>1.1.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.auth0</groupId> <groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId> <artifactId>java-jwt</artifactId>
<version>3.17.0</version> <version>3.17.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.squareup.okhttp3</groupId> <groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId> <artifactId>okhttp</artifactId>
<version>4.9.1</version> <version>4.9.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>pe.mithsolutions</groupId> <groupId>pe.mithsolutions</groupId>
<artifactId>poqh-data-ficha</artifactId> <artifactId>poqh-data-ficha</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version> <version>3.1</version>
<configuration> <configuration>
<source>8</source> <source>8</source>
<target>8</target> <target>8</target>
<compilerArguments> <compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs> <endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments> </compilerArguments>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<version>2.3</version> <version>2.3</version>
<configuration> <configuration>
<failOnMissingWebXml>false</failOnMissingWebXml> <failOnMissingWebXml>false</failOnMissingWebXml>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version> <version>2.6</version>
<executions> <executions>
<execution> <execution>
<phase>validate</phase> <phase>validate</phase>
<goals> <goals>
<goal>copy</goal> <goal>copy</goal>
</goals> </goals>
<configuration> <configuration>
<outputDirectory>${endorsed.dir}</outputDirectory> <outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent> <silent>true</silent>
<artifactItems> <artifactItems>
<artifactItem> <artifactItem>
<groupId>javax</groupId> <groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId> <artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version> <version>7.0</version>
<type>jar</type> <type>jar</type>
</artifactItem> </artifactItem>
</artifactItems> </artifactItems>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<repositories> <repositories>
<repository> <repository>
<id>central</id> <id>central</id>
<name>Maven Plugin Repository</name> <name>Maven Plugin Repository</name>
<url>https://repo1.maven.org/maven2</url> <url>https://repo1.maven.org/maven2</url>
<layout>default</layout> <layout>default</layout>
<snapshots> <snapshots>
<enabled>false</enabled> <enabled>false</enabled>
</snapshots> </snapshots>
</repository> </repository>
<repository> <repository>
<id>snapshots-hosted</id> <id>snapshots-hosted</id>
<url>http://161.97.127.173:8081/repository/mvn-poqh-hosted-snapshot/</url> <url>http://161.97.127.173:8081/repository/mvn-poqh-hosted-snapshot/</url>
<releases> <releases>
<enabled>true</enabled> <enabled>true</enabled>
</releases> </releases>
<snapshots> <snapshots>
<enabled>true</enabled> <enabled>true</enabled>
</snapshots> </snapshots>
</repository> </repository>
<repository> <repository>
<id>snapshots</id> <id>snapshots</id>
<url>http://161.97.127.173:8081/repository/mvn-poqh-snapshot/</url> <url>http://161.97.127.173:8081/repository/mvn-poqh-snapshot/</url>
<releases> <releases>
<enabled>true</enabled> <enabled>true</enabled>
</releases> </releases>
<snapshots> <snapshots>
<enabled>true</enabled> <enabled>true</enabled>
</snapshots> </snapshots>
</repository> </repository>
<repository> <repository>
<id>releases</id> <id>releases</id>
<url>http://161.97.127.173:8081/repository/mvn-poqh-release/</url> <url>http://161.97.127.173:8081/repository/mvn-poqh-release/</url>
<releases> <releases>
<enabled>true</enabled> <enabled>true</enabled>
</releases> </releases>
<snapshots> <snapshots>
<enabled>true</enabled> <enabled>true</enabled>
</snapshots> </snapshots>
</repository> </repository>
</repositories> </repositories>
<distributionManagement> <distributionManagement>
<snapshotRepository> <snapshotRepository>
<id>nexus</id> <id>nexus</id>
<url>http://kira-poqh-mith.live:8081/repository/mvn-poqh-hosted-snapshot/</url> <url>http://kira-poqh-mith.live:8081/repository/mvn-poqh-hosted-snapshot/</url>
</snapshotRepository> </snapshotRepository>
</distributionManagement> </distributionManagement>
</project> </project>
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 javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Provider;
import pe.so.api.formulario.utilities.Commons; import pe.so.api.formulario.utilities.Commons;
@Provider @Provider
@Path("excel") @Path("excel")
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public class ExcelApi { public class ExcelApi {
private JSONObject MSJ_RESPUESTA = new JSONObject(); private JSONObject MSJ_RESPUESTA = new JSONObject();
@POST @POST
@Path("/encuesta") @Path("/encuesta")
public Response encuesta(String json) throws Exception { public Response encuesta(String json) throws Exception {
String[] jsonString = {"p_encuesta_id","p_grupo_encuesta","p_correo_alumno","p_documento","p_nombres"}; String[] jsonString = {"p_encuesta_id","p_grupo_encuesta","p_correo_alumno","p_documento","p_nombres"};
JSONObject entrada = new JSONObject(json); JSONObject entrada = new JSONObject(json);
JSONObject formato = Commons.formatoJSON(jsonString); JSONObject formato = Commons.formatoJSON(jsonString);
if(Commons.validarFormato(jsonString,json)){ if(Commons.validarFormato(jsonString,json)){
ExcelServices excelServices = new ExcelServices(); ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.execute_encuesta(entrada); MSJ_RESPUESTA = excelServices.execute_encuesta(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build(); return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
}else{ }else{
return Response.status(500).entity( return Response.status(500).entity(
MSJ_RESPUESTA.put("status", false) MSJ_RESPUESTA.put("status", false)
.put("mensaje", "Error en el formato de entrada") .put("mensaje", "Error en el formato de entrada")
.put("formato_esperado", formato).toString() .put("formato_esperado", formato).toString()
).build(); ).build();
} }
} }
@POST @POST
@Path("/balotario") @Path("/balotario")
public Response balotario(String json) throws Exception { public Response balotario(String json) throws Exception {
String[] jsonString = {"p_drive_respuesta","p_fila_drive","p_correo_alumno","p_nota","p_apellidos","p_nombres","p_sede","p_fecha_registro"}; String[] jsonString = {"p_drive_respuesta","p_fila_drive","p_correo_alumno","p_nota","p_apellidos","p_nombres","p_sede","p_fecha_registro"};
JSONObject entrada = new JSONObject(json); JSONObject entrada = new JSONObject(json);
JSONObject formato = Commons.formatoJSON(jsonString); JSONObject formato = Commons.formatoJSON(jsonString);
if(Commons.validarFormato(jsonString,json)){ if(Commons.validarFormato(jsonString,json)){
ExcelServices excelServices = new ExcelServices(); ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.execute_balotario(entrada); MSJ_RESPUESTA = excelServices.execute_balotario(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build(); return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
}else{ }else{
return Response.status(500).entity( return Response.status(500).entity(
MSJ_RESPUESTA.put("status", false) MSJ_RESPUESTA.put("status", false)
.put("mensaje", "Error en el formato de entrada") .put("mensaje", "Error en el formato de entrada")
.put("formato_esperado", formato).toString() .put("formato_esperado", formato).toString()
).build(); ).build();
} }
} }
@POST @POST
@Path("/ejecutar") @Path("/ejecutar")
public Response ejecutar(String json) throws Exception { public Response ejecutar(String json) throws Exception {
String[] jsonString = {"p_drive_origen", "p_drive_fila", "p_sede", "p_fecha_hora_registro", "p_medio_atencion", 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_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_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"}; "p_atencion_usuario", "p_atencion_fecha", "p_atencion_estado", "p_atencion_medio_atencion", "p_atencion_hora", "p_atencion_observacion"};
JSONObject entrada = new JSONObject(json); JSONObject entrada = new JSONObject(json);
JSONObject formato = Commons.formatoJSON(jsonString); JSONObject formato = Commons.formatoJSON(jsonString);
if(Commons.validarFormato(jsonString,json)){ if(Commons.validarFormato(jsonString,json)){
ExcelServices excelServices = new ExcelServices(); ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.ejecutar(entrada); MSJ_RESPUESTA = excelServices.ejecutar(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build(); return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
}else{ }else{
return Response.status(500).entity( return Response.status(500).entity(
MSJ_RESPUESTA.put("status", false) MSJ_RESPUESTA.put("status", false)
.put("mensaje", "Error en el formato de entrada") .put("mensaje", "Error en el formato de entrada")
.put("formato_esperado", formato).toString() .put("formato_esperado", formato).toString()
).build(); ).build();
} }
} }
@POST @POST
@Path("/ejecutar_avance") @Path("/ejecutar_avance")
public Response ejecutar_avance(String json) throws Exception { public Response ejecutar_avance(String json) throws Exception {
JSONObject entrada = new JSONObject(json); JSONObject entrada = new JSONObject(json);
ExcelServices excelServices = new ExcelServices(); ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.execute_avance(entrada); MSJ_RESPUESTA = excelServices.execute_avance(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build(); return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
} }
@POST @POST
@Path("/ejecutar_redes") @Path("/ejecutar_redes")
public Response ejecutar_redes(String json) throws Exception { public Response ejecutar_redes(String json) throws Exception {
JSONObject entrada = new JSONObject(json); JSONObject entrada = new JSONObject(json);
ExcelServices excelServices = new ExcelServices(); ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.execute_redes(entrada); MSJ_RESPUESTA = excelServices.execute_redes(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build(); return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
} }
@POST @POST
@Path("/ejecutar_reportevu") @Path("/ejecutar_reportevu")
public Response ejecutar_reportevu(String json) throws Exception { public Response ejecutar_reportevu(String json) throws Exception {
JSONObject entrada = new JSONObject(json); JSONObject entrada = new JSONObject(json);
ExcelServices excelServices = new ExcelServices(); ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.execute_VU(entrada); MSJ_RESPUESTA = excelServices.execute_VU(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build(); return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
} }
@POST @POST
@Path("/ejecutar_reporte_sedes") @Path("/ejecutar_reporte_sedes")
public Response ejecutar_reporte_sedes(String json) throws Exception { public Response ejecutar_reporte_sedes(String json) throws Exception {
JSONObject entrada = new JSONObject(json); JSONObject entrada = new JSONObject(json);
ExcelServices excelServices = new ExcelServices(); ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.execute_reporte_sedes(entrada); MSJ_RESPUESTA = excelServices.execute_reporte_sedes(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build(); return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
} }
@POST @POST
@Path("/ejecutar_reporte_correos") @Path("/ejecutar_reporte_correos")
public Response ejecutar_reporte_correos(String json) throws Exception { public Response ejecutar_reporte_correos(String json) throws Exception {
JSONObject entrada = new JSONObject(json); JSONObject entrada = new JSONObject(json);
ExcelServices excelServices = new ExcelServices(); ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.execute_reporte_correos(entrada); MSJ_RESPUESTA = excelServices.execute_reporte_correos(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build(); return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
} }
} @POST
@Path("/ejecutar_avance_encuestas")
public Response ejecutar_avance_encuestas(String json) throws Exception {
JSONObject entrada = new JSONObject(json);
ExcelServices excelServices = new ExcelServices();
MSJ_RESPUESTA = excelServices.execute_avance_encuesta(entrada);
return Response.status(200).entity(MSJ_RESPUESTA.toString()).build();
}
}
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 static pe.so.api.formulario.utilities.StringUtils.countChar; import static pe.so.api.formulario.utilities.StringUtils.countChar;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.sql.Array; import java.sql.Array;
import java.sql.CallableStatement; import java.sql.CallableStatement;
import java.sql.Connection; import java.sql.Connection;
import java.sql.Date; import java.sql.Date;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import java.sql.ResultSetMetaData;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Types; import java.sql.Types;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.postgresql.util.PGobject; import org.postgresql.util.PGobject;
/** /**
* *
* @author sistemas - Billy , Melani edición : Percy Oliver Quispe Huarcaya * @author sistemas - Billy , Melani edición : Percy Oliver Quispe Huarcaya
*/ */
public abstract class DAO { public abstract class DAO {
/** /**
* Este metodo ejecuta una sentencia sql de consulta(solamente selects) en * Este metodo ejecuta una sentencia sql de consulta(solamente selects) en
* la base de datos y devuelve como resultado en un JSONArray los registros * la base de datos y devuelve como resultado en un JSONArray los registros
* obtenidos * obtenidos
* *
* *
* @param cn objeto que representa la conexion a la base de datos * @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 query sentencia sql que se desea ejecutar en la base de datos
* -@param parametros parametros que vamos a pasar al query, *es opcional * -@param parametros parametros que vamos a pasar al query, *es opcional
* @return Devuelve como resultado los registros obtenidos por el query en * @return Devuelve como resultado los registros obtenidos por el query en
* un objeto JSONArray * un objeto JSONArray
* @throws Exception * @throws Exception
*/ */
protected static JSONArray queryPS(Connection cn, String query, boolean mode, JSONArray... params) 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 JSONArray jsonArray = new JSONArray();//objeto que almacena todas las filas obtenidas por el query
try { try {
try (PreparedStatement ps = cn.prepareStatement(query)) { try (PreparedStatement ps = cn.prepareStatement(query)) {
//validamos si existen parametros //validamos si existen parametros
if (params != null && params.length > 0) { if (params != null && params.length > 0) {
JSONArray _params = params[0]; JSONArray _params = params[0];
int index = 1; int index = 1;
//Recorremos la lista de parametros y lo seteamos en el preparedstatement //Recorremos la lista de parametros y lo seteamos en el preparedstatement
for (Object p : _params) { for (Object p : _params) {
setPreparedStatement(ps, index++, p); setPreparedStatement(ps, index++, p);
} }
} }
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
ResultSetMetaData rm = rs.getMetaData(); ResultSetMetaData rm = rs.getMetaData();
int numCols = rm.getColumnCount(); int numCols = rm.getColumnCount();
while (rs.next()) { while (rs.next()) {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
for (int i = 1; i <= numCols; i++) { for (int i = 1; i <= numCols; i++) {
setJSONObject(rs, rm, i, obj, mode); setJSONObject(rs, rm, i, obj, mode);
} }
// System.out.println("objeto " + obj); // System.out.println("objeto " + obj);
jsonArray.put(obj); jsonArray.put(obj);
} }
} }
} }
} catch (Exception ex) { } catch (Exception ex) {
throw ex; throw ex;
} finally { } finally {
try { try {
if (cn != null) { if (cn != null) {
cn.close(); cn.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage()); System.out.println("Error al liberar memoria " + e.getMessage());
} }
} }
return jsonArray; return jsonArray;
} }
protected static JSONObject queryPSSingle(Connection cn, String query, boolean mode, JSONArray... params) throws Exception { 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 JSONObject json = new JSONObject();//objeto que almacena todas las filas obtenidas por el query
//boolean status = false; //boolean status = false;
//String message = ""; //String message = "";
try (PreparedStatement ps = cn.prepareStatement(query);) { try (PreparedStatement ps = cn.prepareStatement(query);) {
int paramsCount = countChar(query, '?'); int paramsCount = countChar(query, '?');
for (int i = 0; i < paramsCount; i++) { for (int i = 0; i < paramsCount; i++) {
if (!params[0].isNull(i)) { if (!params[0].isNull(i)) {
setPreparedStatement(ps, i + 1, params[0].get(i)); setPreparedStatement(ps, i + 1, params[0].get(i));
} else { } else {
setPreparedStatement(ps, i + 1, JSONObject.NULL); setPreparedStatement(ps, i + 1, JSONObject.NULL);
} }
} }
System.out.println("Query ejecutado con queryPSSingle-->>>> \n" + ps); System.out.println("Query ejecutado con queryPSSingle-->>>> \n" + ps);
try (ResultSet rs = ps.executeQuery();) { try (ResultSet rs = ps.executeQuery();) {
ResultSetMetaData rm = rs.getMetaData(); ResultSetMetaData rm = rs.getMetaData();
int numCols = rm.getColumnCount(); int numCols = rm.getColumnCount();
if (rs.next()) { if (rs.next()) {
for (int i = 1; i <= numCols; i++) { for (int i = 1; i <= numCols; i++) {
setJSONObject(rs, rm, i, json, mode); setJSONObject(rs, rm, i, json, mode);
} }
json.put("status", json.has("status") ? json.getBoolean("status") : true); json.put("status", json.has("status") ? json.getBoolean("status") : true);
json.put("message", json.has("message") ? json.getString("message") : "Operación realizada correctamente."); json.put("message", json.has("message") ? json.getString("message") : "Operación realizada correctamente.");
} else { } else {
json.put("status", false).put("message", "Hubo un error al realizar la operación."); json.put("status", false).put("message", "Hubo un error al realizar la operación.");
} }
} }
} catch (Exception ex) { } catch (Exception ex) {
throw ex; throw ex;
} finally { } finally {
try { try {
if (cn != null) { if (cn != null) {
cn.close(); cn.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage()); System.out.println("Error al liberar memoria " + e.getMessage());
} }
} }
return json; return json;
} }
/** /**
* Este metodo nos permite ejecutar una sentencia sql en la base de datos y * 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 * devuelve como resultado en un JSONObject las filas afectadas por el
* query. * query.
* *
* @param cn objeto que representa la conexion a la base de datos * @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 query sentencia sql que se desea ejecutar en la base de datos
* @param parametros parametros que vamos a pasar al query, *es opcional * @param parametros parametros que vamos a pasar al query, *es opcional
* @return Devuelve la cantidad de filas afectadas por el query en un * @return Devuelve la cantidad de filas afectadas por el query en un
* JSONObject. * JSONObject.
* @throws Exception * @throws Exception
*/ */
protected static JSONObject executePS(Connection cn, String query, JSONArray... params) throws Exception { protected static JSONObject executePS(Connection cn, String query, JSONArray... params) throws Exception {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
try { try {
try (PreparedStatement ps = cn.prepareStatement(query);) { try (PreparedStatement ps = cn.prepareStatement(query);) {
if (params != null && params.length > 0) { if (params != null && params.length > 0) {
JSONArray _params = params[0]; JSONArray _params = params[0];
int index = 1; int index = 1;
for (Object parametro : _params) { for (Object parametro : _params) {
setPreparedStatement(ps, index++, parametro); setPreparedStatement(ps, index++, parametro);
} }
} }
int filas = ps.executeUpdate(); int filas = ps.executeUpdate();
obj.put("status", filas > 0); obj.put("status", filas > 0);
obj.put("message", "OK"); obj.put("message", "OK");
obj.put("data", filas); obj.put("data", filas);
} }
} catch (Exception ex) { } catch (Exception ex) {
obj.put("status", false); obj.put("status", false);
obj.put("message", ex); obj.put("message", ex);
obj.put("data", JSONObject.NULL); obj.put("data", JSONObject.NULL);
throw ex; throw ex;
} finally { } finally {
try { try {
if (cn != null) { if (cn != null) {
cn.close(); cn.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage()); System.out.println("Error al liberar memoria " + e.getMessage());
} }
} }
return obj; return obj;
} }
protected static JSONArray queryProcedure(Connection cn, String query, boolean mode, JSONArray... parameters) throws Exception { protected static JSONArray queryProcedure(Connection cn, String query, boolean mode, JSONArray... parameters) throws Exception {
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
JSONObject outputParamTypes = new JSONObject(); JSONObject outputParamTypes = new JSONObject();
JSONArray params = null; JSONArray params = null;
try { try {
try (CallableStatement cs = cn.prepareCall(query);) { try (CallableStatement cs = cn.prepareCall(query);) {
if (parameters != null && parameters.length > 0) { if (parameters != null && parameters.length > 0) {
params = parameters[0]; params = parameters[0];
int index = 1; int index = 1;
for (Object parameter : params) { for (Object parameter : params) {
if (parameter instanceof Class) { if (parameter instanceof Class) {
registerOutputParameter(cs, index++, parameter, outputParamTypes); registerOutputParameter(cs, index++, parameter, outputParamTypes);
} else { } else {
setPreparedStatement(cs, index++, parameter); setPreparedStatement(cs, index++, parameter);
} }
} }
} }
boolean isResultSet = cs.execute(); boolean isResultSet = cs.execute();
if (isResultSet) { if (isResultSet) {
try (final ResultSet rs = cs.getResultSet();) { try (final ResultSet rs = cs.getResultSet();) {
ResultSetMetaData rm = rs.getMetaData(); ResultSetMetaData rm = rs.getMetaData();
int columnCount = rm.getColumnCount(); int columnCount = rm.getColumnCount();
while (rs.next()) { while (rs.next()) {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
setJSONObject(rs, rm, columnIndex, obj, mode); setJSONObject(rs, rm, columnIndex, obj, mode);
} }
jsonArray.put(obj); jsonArray.put(obj);
} }
} }
} else { } else {
int rowsAffected = cs.getUpdateCount(); int rowsAffected = cs.getUpdateCount();
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("rowsAffected", rowsAffected); obj.put("rowsAffected", rowsAffected);
jsonArray.put(obj); jsonArray.put(obj);
} }
if (outputParamTypes.length() > 0) { if (outputParamTypes.length() > 0) {
clearJSONArray(params); clearJSONArray(params);
} }
for (String key : outputParamTypes.keySet()) { for (String key : outputParamTypes.keySet()) {
int indexOutputParams = Integer.parseInt(key); int indexOutputParams = Integer.parseInt(key);
int type = outputParamTypes.getInt(key); int type = outputParamTypes.getInt(key);
getOutputParameter(cs, indexOutputParams, type, params); getOutputParameter(cs, indexOutputParams, type, params);
} }
} }
} catch (Exception ex) { } catch (Exception ex) {
throw ex; throw ex;
} finally { } finally {
try { try {
if (cn != null) { if (cn != null) {
cn.close(); cn.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage()); System.out.println("Error al liberar memoria " + e.getMessage());
} }
} }
return jsonArray; return jsonArray;
} }
protected static JSONObject executeCS(Connection cn, String query, JSONArray... params) throws Exception { protected static JSONObject executeCS(Connection cn, String query, JSONArray... params) throws Exception {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
try { try {
try (CallableStatement cs = cn.prepareCall(query);) { try (CallableStatement cs = cn.prepareCall(query);) {
if (params != null && params.length > 0) { if (params != null && params.length > 0) {
JSONArray _params = params[0]; JSONArray _params = params[0];
int index = 1; int index = 1;
for (Object p : _params) { for (Object p : _params) {
setPreparedStatement(cs, index++, p); setPreparedStatement(cs, index++, p);
} }
} }
int filas = cs.executeUpdate(); int filas = cs.executeUpdate();
obj.put("status", filas > 0); obj.put("status", filas > 0);
obj.put("message", "OK"); obj.put("message", "OK");
obj.put("data", filas); obj.put("data", filas);
} }
} catch (Exception ex) { } catch (Exception ex) {
obj.put("status", false); obj.put("status", false);
obj.put("message", ex); obj.put("message", ex);
obj.put("data", JSONObject.NULL); obj.put("data", JSONObject.NULL);
throw ex; throw ex;
} finally { } finally {
try { try {
if (cn != null) { if (cn != null) {
cn.close(); cn.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage()); System.out.println("Error al liberar memoria " + e.getMessage());
} }
} }
return obj; return obj;
} }
/** /**
* Obtiene el valor de una columna de una tabla y lo guarda en el objeto * Obtiene el valor de una columna de una tabla y lo guarda en el objeto
* JSONObject con el tipo de dato que le corresponde. * JSONObject con el tipo de dato que le corresponde.
* *
* @param rs Objeto ResultSet para obtener el valor de una columna de una * @param rs Objeto ResultSet para obtener el valor de una columna de una
* tabla * tabla
* @param rsmd Objeto ResultSetMetaData nos permite obtener el nombre y tipo * @param rsmd Objeto ResultSetMetaData nos permite obtener el nombre y tipo
* de columna * de columna
* @param columnIndex Posicion de la columna en la sentencia sql * @param columnIndex Posicion de la columna en la sentencia sql
* @param obj Representa a un registro de la base de datos * @param obj Representa a un registro de la base de datos
* @throws SQLException * @throws SQLException
*/ */
private static void setJSONObject(ResultSet rs, ResultSetMetaData rm, int columnIndex, JSONObject obj, boolean mode) throws SQLException { private static void setJSONObject(ResultSet rs, ResultSetMetaData rm, int columnIndex, JSONObject obj, boolean mode) throws SQLException {
int type = rm.getColumnType(columnIndex); int type = rm.getColumnType(columnIndex);
switch (type) { switch (type) {
case Types.VARCHAR: case Types.VARCHAR:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getString(columnIndex) == null ? JSONObject.NULL : rs.getString(columnIndex)); obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getString(columnIndex) == null ? JSONObject.NULL : rs.getString(columnIndex));
break; break;
case Types.CHAR: case Types.CHAR:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getString(columnIndex) == null ? JSONObject.NULL : rs.getString(columnIndex)); obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getString(columnIndex) == null ? JSONObject.NULL : rs.getString(columnIndex));
break; break;
case Types.INTEGER: case Types.INTEGER:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getInt(columnIndex)); obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getInt(columnIndex));
break; break;
case Types.BIT: case Types.BIT:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getBoolean(columnIndex)); obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getBoolean(columnIndex));
break; break;
case Types.BINARY: case Types.BINARY:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getBytes(columnIndex)); obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getBytes(columnIndex));
break; break;
default: default:
obj.put(mode ? "" + columnIndex : rm.getColumnLabel(columnIndex), rs.getString(columnIndex) == null ? JSONObject.NULL : rs.getString(columnIndex)); 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 { private static void getOutputParameter(CallableStatement cs, int index, int type, JSONArray parameter) throws SQLException {
switch (type) { switch (type) {
case Types.INTEGER: case Types.INTEGER:
parameter.put(cs.getInt(index)); parameter.put(cs.getInt(index));
break; break;
case Types.VARCHAR: case Types.VARCHAR:
case Types.CHAR: case Types.CHAR:
parameter.put(cs.getString(index)); parameter.put(cs.getString(index));
break; break;
case Types.BOOLEAN: case Types.BOOLEAN:
parameter.put(cs.getBoolean(index)); parameter.put(cs.getBoolean(index));
break; break;
case Types.DOUBLE: case Types.DOUBLE:
parameter.put(cs.getDouble(index)); parameter.put(cs.getDouble(index));
break; break;
case Types.BINARY: case Types.BINARY:
parameter.put(cs.getBytes(index)); parameter.put(cs.getBytes(index));
break; break;
default: default:
parameter.put(cs.getString(index)); parameter.put(cs.getString(index));
} }
} }
private static void registerOutputParameter(CallableStatement cs, int index, Object p, JSONObject types) throws SQLException { private static void registerOutputParameter(CallableStatement cs, int index, Object p, JSONObject types) throws SQLException {
if (p.equals(Integer.class)) { if (p.equals(Integer.class)) {
cs.registerOutParameter(index, Types.INTEGER); cs.registerOutParameter(index, Types.INTEGER);
types.put(Integer.toString(index), Types.INTEGER); types.put(Integer.toString(index), Types.INTEGER);
} else if (p.equals(String.class)) { } else if (p.equals(String.class)) {
cs.registerOutParameter(index, Types.VARCHAR); cs.registerOutParameter(index, Types.VARCHAR);
types.put(Integer.toString(index), Types.VARCHAR); types.put(Integer.toString(index), Types.VARCHAR);
} else if (p.equals(Boolean.class)) { } else if (p.equals(Boolean.class)) {
cs.registerOutParameter(index, Types.BOOLEAN); cs.registerOutParameter(index, Types.BOOLEAN);
types.put(Integer.toString(index), Types.BOOLEAN); types.put(Integer.toString(index), Types.BOOLEAN);
} else if (p.equals(Double.class)) { } else if (p.equals(Double.class)) {
cs.registerOutParameter(index, Types.DOUBLE); cs.registerOutParameter(index, Types.DOUBLE);
types.put(Integer.toString(index), Types.DOUBLE); types.put(Integer.toString(index), Types.DOUBLE);
} }
} }
/** /**
* Setea en el prepared statement el valor del parametro segun su tipo de * Setea en el prepared statement el valor del parametro segun su tipo de
* dato. * dato.
* *
* @param ps representa el objeto PreparedStatement * @param ps representa el objeto PreparedStatement
* @param index indica la posicion del parametro en la consulta sql * @param index indica la posicion del parametro en la consulta sql
* @param p parametro de la consulta sql * @param p parametro de la consulta sql
* @throws SQLException * @throws SQLException
*/ */
private static void setPreparedStatement(PreparedStatement ps, int index, Object p) throws SQLException { private static void setPreparedStatement(PreparedStatement ps, int index, Object p) throws SQLException {
if (p instanceof Integer) { if (p instanceof Integer) {
ps.setInt(index, (int) p); ps.setInt(index, (int) p);
} else if (p instanceof String) { } else if (p instanceof String) {
ps.setString(index, p.toString()); ps.setString(index, p.toString());
} else if (p instanceof Double) { } else if (p instanceof Double) {
ps.setDouble(index, (double) p); ps.setDouble(index, (double) p);
} else if (p instanceof Boolean) { } else if (p instanceof Boolean) {
ps.setBoolean(index, (boolean) p); ps.setBoolean(index, (boolean) p);
} else if (p instanceof byte[]) { } else if (p instanceof byte[]) {
ps.setBytes(index, (byte[]) p); ps.setBytes(index, (byte[]) p);
} else if (p instanceof Date) { } else if (p instanceof Date) {
ps.setDate(index, (Date) p); ps.setDate(index, (Date) p);
} else if (p instanceof BigDecimal) { } else if (p instanceof BigDecimal) {
ps.setBigDecimal(index, (BigDecimal) p); ps.setBigDecimal(index, (BigDecimal) p);
} else if (p instanceof Long) { } else if (p instanceof Long) {
ps.setDate(index, new Date((long) p)); ps.setDate(index, new Date((long) p));
} else if (p instanceof Array) { } else if (p instanceof Array) {
ps.setArray(index, (Array) p); ps.setArray(index, (Array) p);
} else if (p == JSONObject.NULL) { } else if (p == JSONObject.NULL) {
ps.setNull(index, Types.NULL); ps.setNull(index, Types.NULL);
}else if (p instanceof JSONArray || p instanceof JSONObject) { }else if (p instanceof JSONArray || p instanceof JSONObject) {
PGobject object = new PGobject(); PGobject object = new PGobject();
object.setType("json"); object.setType("json");
object.setValue(p.toString()); object.setValue(p.toString());
ps.setObject(index, object); ps.setObject(index, object);
} }
} }
// private static void setParameterValueOrNullValue(PreparedStatement ps, int index, Object p, int sqlType) throws SQLException { // private static void setParameterValueOrNullValue(PreparedStatement ps, int index, Object p, int sqlType) throws SQLException {
// if (p != null) { // if (p != null) {
// ps.setObject(index, p, sqlType); // ps.setObject(index, p, sqlType);
// } else { // } else {
// ps.setNull(index, sqlType); // ps.setNull(index, sqlType);
// } // }
// } // }
private static void clearJSONArray(JSONArray jsonArray) { private static void clearJSONArray(JSONArray jsonArray) {
while (jsonArray != null && jsonArray.length() > 0) { while (jsonArray != null && jsonArray.length() > 0) {
jsonArray.remove(0); jsonArray.remove(0);
} }
} }
protected static JSONObject queryJSONObject(Connection cn, String query, JSONObject data) throws Exception { protected static JSONObject queryJSONObject(Connection cn, String query, JSONObject data) throws Exception {
/* ES SIMILAR AL MÉTODO queryWithPaging, pero adaptado para funcionar con JSON /* ES SIMILAR AL MÉTODO queryWithPaging, pero adaptado para funcionar con JSON
*/ */
JSONObject salida = new JSONObject(); JSONObject salida = new JSONObject();
// JSONArray jsonArray = new JSONArray();//objeto que almacena todas las filas obtenidas por el query // JSONArray jsonArray = new JSONArray();//objeto que almacena todas las filas obtenidas por el query
try { try {
try (PreparedStatement ps = cn.prepareStatement(query)) { try (PreparedStatement ps = cn.prepareStatement(query)) {
int paramsCount = countChar(query, '?'); // obtenido de Utils.StringUtils int paramsCount = countChar(query, '?'); // obtenido de Utils.StringUtils
JSONArray _params = data.has("params") ? data.getJSONArray("params") : new JSONArray(); JSONArray _params = data.has("params") ? data.getJSONArray("params") : new JSONArray();
if (data.has("length") && data.has("start")) { if (data.has("length") && data.has("start")) {
_params _params
.put(paramsCount - 3, data.getInt("length")) .put(paramsCount - 3, data.getInt("length"))
.put(paramsCount - 2, data.getInt("start")); .put(paramsCount - 2, data.getInt("start"));
} }
if (data.has("draw")) { if (data.has("draw")) {
_params.put(paramsCount - 1, data.getInt("draw")); _params.put(paramsCount - 1, data.getInt("draw"));
} }
for (int i = 0; i < paramsCount; i++) { for (int i = 0; i < paramsCount; i++) {
if (!_params.isNull(i)) { if (!_params.isNull(i)) {
setPreparedStatement(ps, i + 1, _params.get(i)); setPreparedStatement(ps, i + 1, _params.get(i));
} else { } else {
setPreparedStatement(ps, i + 1, JSONObject.NULL); setPreparedStatement(ps, i + 1, JSONObject.NULL);
} }
} }
System.out.println("QUERY EJECUTADO CON queryJSONObject ------->>>>\n" + ps); System.out.println("QUERY EJECUTADO CON queryJSONObject ------->>>>\n" + ps);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
// ResultSetMetaData rm = rs.getMetaData(); // ResultSetMetaData rm = rs.getMetaData();
// int numCols = rm.getColumnCount(); // int numCols = rm.getColumnCount();
if (rs.next()) { if (rs.next()) {
// for (int i = 1; i <= numCols; i++) { // for (int i = 1; i <= numCols; i++) {
// setJSONObject(rs, rm, i, salida, mode); // setJSONObject(rs, rm, i, salida, mode);
salida = new JSONObject(rs.getString("json")); salida = new JSONObject(rs.getString("json"));
// } // }
// System.out.println("INGRESA A LA CONDICIÓN RS.NEXT"); // System.out.println("INGRESA A LA CONDICIÓN RS.NEXT");
} else { } else {
salida.put("status", false).put("message", "No se encontraron registros para mostrar").put("data", new JSONArray()); salida.put("status", false).put("message", "No se encontraron registros para mostrar").put("data", new JSONArray());
if (data.has("length") && data.has("start")) { if (data.has("length") && data.has("start")) {
salida.put("recordsTotal", 0).put("recordsFiltered", 0); salida.put("recordsTotal", 0).put("recordsFiltered", 0);
} }
if (data.has("draw")) { if (data.has("draw")) {
salida.put("draw", data.getInt("draw")); salida.put("draw", data.getInt("draw"));
} }
// System.out.println("NO INGRESA A LA CONDICIÓN RS.NEXT"); // System.out.println("NO INGRESA A LA CONDICIÓN RS.NEXT");
} }
} }
} }
} catch (Exception ex) { } catch (Exception ex) {
salida.put("status", false); salida.put("status", false);
salida.put("message", "Hubo un error al realizar la consulta"); salida.put("message", "Hubo un error al realizar la consulta");
throw ex; throw ex;
} finally { } finally {
try { try {
if (cn != null) { if (cn != null) {
cn.close(); cn.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("Error al liberar memoria " + e.getMessage()); System.out.println("Error al liberar memoria " + e.getMessage());
} }
} }
return salida; return salida;
} }
} }
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.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import pe.so.api.formulario.dao.ExcelDAO; import pe.so.api.formulario.dao.ExcelDAO;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.Date; import java.util.Date;
public class PostgreSqlExcel implements ExcelDAO{ public class PostgreSqlExcel implements ExcelDAO{
@Override @Override
public JSONObject execute_encuesta(JSONObject json) throws Exception{ public JSONObject execute_encuesta(JSONObject json) throws Exception{
JSONObject respuesta=new JSONObject(); JSONObject respuesta=new JSONObject();
Connection conexion=null; Connection conexion=null;
try { try {
int p_encuensta_id=json.isNull("p_encuesta_id") ? 0 : json.getInt("p_encuesta_id"); int p_encuensta_id=json.isNull("p_encuesta_id") ? 0 : json.getInt("p_encuesta_id");
String p_grupo_encuesta=json.isNull("p_grupo_encuesta") ? "" : json.getString("p_grupo_encuesta"); String p_grupo_encuesta=json.isNull("p_grupo_encuesta") ? "" : json.getString("p_grupo_encuesta");
String p_correo_alumno=json.isNull("p_correo_alumno") ? "" : json.getString("p_correo_alumno"); String p_correo_alumno=json.isNull("p_correo_alumno") ? "" : json.getString("p_correo_alumno");
String p_documento = json.isNull("p_documento") ? "" : json.getString("p_documento"); String p_documento = json.isNull("p_documento") ? "" : json.getString("p_documento");
String p_nombres = json.isNull("p_nombres") ? "" : json.getString("p_nombres"); String p_nombres = json.isNull("p_nombres") ? "" : json.getString("p_nombres");
conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa"); conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa");
String sql="select horario.func_encuesta_procesar_alumno(?,?,?,?,?)"; String sql="select horario.func_encuesta_procesar_alumno(?,?,?,?,?)";
PreparedStatement ps=conexion.prepareStatement(sql); PreparedStatement ps=conexion.prepareStatement(sql);
ps.setInt(1,p_encuensta_id); ps.setInt(1,p_encuensta_id);
ps.setString(2,p_grupo_encuesta); ps.setString(2,p_grupo_encuesta);
ps.setString(3,p_correo_alumno); ps.setString(3,p_correo_alumno);
ps.setString(4,p_documento); ps.setString(4,p_documento);
ps.setString(5,p_nombres); ps.setString(5,p_nombres);
ResultSet rs=ps.executeQuery(); ResultSet rs=ps.executeQuery();
if(rs.next()){ if(rs.next()){
int columnCount=rs.getMetaData().getColumnCount(); int columnCount=rs.getMetaData().getColumnCount();
for (int i=1; i <= columnCount; i++) { for (int i=1; i <= columnCount; i++) {
respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i)); respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
} }
} }
respuesta.put("status",true); respuesta.put("status",true);
} catch (Exception e) { } catch (Exception e) {
respuesta.put("status",false); respuesta.put("status",false);
respuesta.put("mensaje",e.getMessage()); respuesta.put("mensaje",e.getMessage());
} finally { } finally {
if(conexion != null){ if(conexion != null){
conexion.close(); conexion.close();
} }
} }
return respuesta; return respuesta;
} }
@Override @Override
public JSONObject execute_balotario(JSONObject json) throws Exception{ public JSONObject execute_balotario(JSONObject json) throws Exception{
JSONObject respuesta=new JSONObject(); JSONObject respuesta=new JSONObject();
Connection conexion=null; Connection conexion=null;
try { try {
String p_drive_respuesta=json.isNull("p_drive_respuesta") ? "" : json.getString("p_drive_respuesta"); String p_drive_respuesta=json.isNull("p_drive_respuesta") ? "" : json.getString("p_drive_respuesta");
String p_fecha_registro=json.isNull("p_fecha_registro") ? "" : json.getString("p_fecha_registro"); String p_fecha_registro=json.isNull("p_fecha_registro") ? "" : json.getString("p_fecha_registro");
int p_fila_drive=json.isNull("p_fila_drive") ? 0 : json.getInt("p_fila_drive"); int p_fila_drive=json.isNull("p_fila_drive") ? 0 : json.getInt("p_fila_drive");
String p_correo_alumno=json.isNull("p_correo_alumno") ? "" : json.getString("p_correo_alumno"); String p_correo_alumno=json.isNull("p_correo_alumno") ? "" : json.getString("p_correo_alumno");
String p_nota=json.isNull("p_nota") ? "" : json.getString("p_nota"); String p_nota=json.isNull("p_nota") ? "" : json.getString("p_nota");
String p_apellidos=json.isNull("p_apellidos") ? "" : json.getString("p_apellidos"); String p_apellidos=json.isNull("p_apellidos") ? "" : json.getString("p_apellidos");
String p_nombres=json.isNull("p_nombres") ? "" : json.getString("p_nombres"); String p_nombres=json.isNull("p_nombres") ? "" : json.getString("p_nombres");
String p_sede=json.isNull("p_sede") ? "" : json.getString("p_sede"); String p_sede=json.isNull("p_sede") ? "" : json.getString("p_sede");
conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa"); conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa");
String sql="select academico.func_balotario_procesar_alumno(?,?,?,?,?,?,?,?)"; String sql="select academico.func_balotario_procesar_alumno(?,?,?,?,?,?,?,?)";
PreparedStatement ps=conexion.prepareStatement(sql); PreparedStatement ps=conexion.prepareStatement(sql);
ps.setString(1,p_drive_respuesta); ps.setString(1,p_drive_respuesta);
ps.setString(2,p_fecha_registro); ps.setString(2,p_fecha_registro);
ps.setInt(3,p_fila_drive); ps.setInt(3,p_fila_drive);
ps.setString(4,p_correo_alumno); ps.setString(4,p_correo_alumno);
ps.setString(5,p_nota); ps.setString(5,p_nota);
ps.setString(6,p_apellidos); ps.setString(6,p_apellidos);
ps.setString(7,p_nombres); ps.setString(7,p_nombres);
ps.setString(8,p_sede); ps.setString(8,p_sede);
ResultSet rs=ps.executeQuery(); ResultSet rs=ps.executeQuery();
if(rs.next()){ if(rs.next()){
int columnCount=rs.getMetaData().getColumnCount(); int columnCount=rs.getMetaData().getColumnCount();
for (int i=1; i <= columnCount; i++) { for (int i=1; i <= columnCount; i++) {
respuesta.put("mensaje",rs.getObject(i)); respuesta.put("mensaje",rs.getObject(i));
} }
} }
respuesta.put("status",true); respuesta.put("status",true);
} catch (Exception e) { } catch (Exception e) {
respuesta.put("status",false); respuesta.put("status",false);
respuesta.put("mensaje",e.getMessage()); respuesta.put("mensaje",e.getMessage());
} finally { } finally {
if(conexion != null){ if(conexion != null){
conexion.close(); conexion.close();
} }
} }
return respuesta; return respuesta;
} }
public JSONObject ejecutar(JSONObject json) throws Exception{ public JSONObject ejecutar(JSONObject json) throws Exception{
JSONObject respuesta=new JSONObject(); JSONObject respuesta=new JSONObject();
Connection conexion=null; Connection conexion=null;
try { try {
Date date=new Date(); Date date=new Date();
java.sql.Timestamp sqlTime=new java.sql.Timestamp(date.getTime()); java.sql.Timestamp sqlTime=new java.sql.Timestamp(date.getTime());
String p_drive_origen=json.getString("p_drive_origen"); String p_drive_origen=json.getString("p_drive_origen");
int p_drive_fila=json.getInt("p_drive_fila"); int p_drive_fila=json.getInt("p_drive_fila");
String p_sede=json.getString("p_sede"); String p_sede=json.getString("p_sede");
String p_medio_atencion=json.getString("p_medio_atencion"); String p_medio_atencion=json.getString("p_medio_atencion");
String p_contacto_nombres=json.getString("p_contacto_nombres"); String p_contacto_nombres=json.getString("p_contacto_nombres");
String p_contacto_apellidos=json.getString("p_contacto_apellidos"); String p_contacto_apellidos=json.getString("p_contacto_apellidos");
String p_numero_documento=json.getString("p_numero_documento"); String p_numero_documento=json.getString("p_numero_documento");
String p_contacto_correo=json.getString("p_contacto_correo"); String p_contacto_correo=json.getString("p_contacto_correo");
String p_atencion_usuario=json.getString("p_atencion_usuario"); String p_atencion_usuario=json.getString("p_atencion_usuario");
String p_grado=json.getString("p_grado"); String p_grado=json.getString("p_grado");
String p_contacto_telefono=json.getString("p_contacto_telefono"); String p_contacto_telefono=json.getString("p_contacto_telefono");
String p_colegio_procedencia=json.getString("p_colegio_procedencia"); String p_colegio_procedencia=json.getString("p_colegio_procedencia");
String p_distrito=json.getString("p_distrito"); String p_distrito=json.getString("p_distrito");
String p_atencion_fecha=json.getString("p_atencion_fecha"); String p_atencion_fecha=json.getString("p_atencion_fecha");
String p_atencion_estado=json.getString("p_atencion_estado"); String p_atencion_estado=json.getString("p_atencion_estado");
String p_atencion_medio_atencion=json.getString("p_atencion_medio_atencion"); String p_atencion_medio_atencion=json.getString("p_atencion_medio_atencion");
String p_atencion_hora=json.getString("p_atencion_hora"); String p_atencion_hora=json.getString("p_atencion_hora");
String p_atencion_observacion=json.getString("p_atencion_observacion"); String p_atencion_observacion=json.getString("p_atencion_observacion");
String p_medio_difusion_nombre=json.getString("p_medio_difusion_nombre"); String p_medio_difusion_nombre=json.getString("p_medio_difusion_nombre");
conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa"); conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa");
String sql="select matricula.func_informe_registrar(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String sql="select matricula.func_informe_registrar(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps=conexion.prepareStatement(sql); PreparedStatement ps=conexion.prepareStatement(sql);
ps.setString(1,p_drive_origen); ps.setString(1,p_drive_origen);
ps.setInt(2,p_drive_fila); ps.setInt(2,p_drive_fila);
ps.setString(3,sqlTime.toString()); ps.setString(3,sqlTime.toString());
ps.setString(4,p_sede); ps.setString(4,p_sede);
ps.setString(5,p_medio_atencion); ps.setString(5,p_medio_atencion);
ps.setString(6,p_contacto_nombres); ps.setString(6,p_contacto_nombres);
ps.setString(7,p_contacto_apellidos); ps.setString(7,p_contacto_apellidos);
ps.setString(8,p_numero_documento); ps.setString(8,p_numero_documento);
ps.setString(9,p_contacto_correo); ps.setString(9,p_contacto_correo);
ps.setString(10,p_contacto_telefono); ps.setString(10,p_contacto_telefono);
ps.setString(11,p_distrito); ps.setString(11,p_distrito);
ps.setString(12,p_grado); ps.setString(12,p_grado);
ps.setString(13,p_colegio_procedencia); ps.setString(13,p_colegio_procedencia);
ps.setString(14,p_medio_difusion_nombre); ps.setString(14,p_medio_difusion_nombre);
ps.setString(15,p_atencion_usuario); ps.setString(15,p_atencion_usuario);
ps.setString(16,p_atencion_fecha); ps.setString(16,p_atencion_fecha);
ps.setString(17,p_atencion_estado); ps.setString(17,p_atencion_estado);
ps.setString(18,p_atencion_medio_atencion); ps.setString(18,p_atencion_medio_atencion);
ps.setString(19,p_atencion_hora); ps.setString(19,p_atencion_hora);
ps.setString(20,p_atencion_observacion); ps.setString(20,p_atencion_observacion);
ResultSet rs=ps.executeQuery(); ResultSet rs=ps.executeQuery();
if(rs.next()){ if(rs.next()){
int columnCount=rs.getMetaData().getColumnCount(); int columnCount=rs.getMetaData().getColumnCount();
for (int i=1; i <= columnCount; i++) { for (int i=1; i <= columnCount; i++) {
respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i)); respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
} }
respuesta.put("status",respuesta.getString("func_informe_registrar").contains("_informe_id")); respuesta.put("status",respuesta.getString("func_informe_registrar").contains("_informe_id"));
} }
} catch (Exception e) { } catch (Exception e) {
respuesta.put("status",false); respuesta.put("status",false);
respuesta.put("mensaje",e.getMessage()); respuesta.put("mensaje",e.getMessage());
} finally { } finally {
if(conexion != null){ if(conexion != null){
conexion.close(); conexion.close();
} }
} }
return respuesta; return respuesta;
} }
@Override @Override
public JSONObject execute_avance(JSONObject json) throws Exception{ public JSONObject execute_avance(JSONObject json) throws Exception{
JSONObject respuesta=new JSONObject(); JSONObject respuesta=new JSONObject();
Connection conexion=null; Connection conexion=null;
try { try {
int p_tipo_operacion=json.getInt("p_tipo_operacion"); int p_tipo_operacion=json.getInt("p_tipo_operacion");
int p_aula_id=json.isNull("p_aula_id") ? 0 : json.getInt("p_aula_id"); int p_aula_id=json.isNull("p_aula_id") ? 0 : json.getInt("p_aula_id");
int p_curso_id=json.isNull("p_curso_id") ? 0 : json.getInt("p_curso_id"); int p_curso_id=json.isNull("p_curso_id") ? 0 : json.getInt("p_curso_id");
conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa"); conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa");
String sql="select academico.func_balotario_alumno(?,?,?)"; String sql="select academico.func_balotario_alumno(?,?,?)";
PreparedStatement ps=conexion.prepareStatement(sql); PreparedStatement ps=conexion.prepareStatement(sql);
Statement st=conexion.createStatement(); Statement st=conexion.createStatement();
ps.setInt(1,p_tipo_operacion); ps.setInt(1,p_tipo_operacion);
ps.setInt(2,p_aula_id); ps.setInt(2,p_aula_id);
ps.setInt(3,p_curso_id); ps.setInt(3,p_curso_id);
ResultSet rs=ps.executeQuery(); ResultSet rs=ps.executeQuery();
if(rs.next()){ if(rs.next()){
int columnCount=rs.getMetaData().getColumnCount(); int columnCount=rs.getMetaData().getColumnCount();
for (int i=1; i <= columnCount; i++) { for (int i=1; i <= columnCount; i++) {
respuesta.put(rs.getMetaData().getColumnName(i),new JSONObject(rs.getObject(i).toString())); respuesta.put(rs.getMetaData().getColumnName(i),new JSONObject(rs.getObject(i).toString()));
} }
} }
JSONArray data=respuesta.getJSONObject("func_balotario_alumno").getJSONArray("data"); JSONArray data=respuesta.getJSONObject("func_balotario_alumno").getJSONArray("data");
JSONArray respuesta2=new JSONArray(); JSONArray respuesta2=new JSONArray();
data.forEach(item -> { data.forEach(item -> {
JSONObject obj=(JSONObject)item; JSONObject obj=(JSONObject)item;
String sql2=obj.getString("script"); String sql2=obj.getString("script");
try { try {
st.executeQuery(sql2); st.executeQuery(sql2);
} catch (SQLException ignored) { } catch (SQLException ignored) {
} }
}); });
respuesta.put("salida",respuesta2); respuesta.put("salida",respuesta2);
} catch (Exception e) { } catch (Exception e) {
respuesta.put("error",e.getMessage()); respuesta.put("error",e.getMessage());
} finally { } finally {
if(conexion != null){ if(conexion != null){
conexion.close(); conexion.close();
} }
} }
return respuesta; return respuesta;
} }
@Override @Override
public JSONObject execute_redes(JSONObject json) throws Exception{ public JSONObject execute_redes(JSONObject json) throws Exception{
JSONObject respuesta=new JSONObject(); JSONObject respuesta=new JSONObject();
Connection conexion=null; Connection conexion=null;
try { try {
String p_tipo_vista=json.getString("p_tipo_vista"); String p_tipo_vista=json.getString("p_tipo_vista");
conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa"); conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa");
String sql = "SELECT * FROM matricula.func_redes_sociales(?)"; String sql = "SELECT * FROM matricula.func_redes_sociales(?)";
PreparedStatement ps=conexion.prepareStatement(sql); PreparedStatement ps=conexion.prepareStatement(sql);
ps.setString(1,p_tipo_vista); ps.setString(1,p_tipo_vista);
ResultSet rs=ps.executeQuery(); ResultSet rs=ps.executeQuery();
if(rs.next()){ if(rs.next()){
int columnCount=rs.getMetaData().getColumnCount(); int columnCount=rs.getMetaData().getColumnCount();
for (int i=1; i <= columnCount; i++) { for (int i=1; i <= columnCount; i++) {
respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i)); respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
} }
} }
} catch (Exception e) { } catch (Exception e) {
respuesta.put("error",e.getMessage()); respuesta.put("error",e.getMessage());
}finally { }finally {
if(conexion != null){ if(conexion != null){
conexion.close(); conexion.close();
} }
} }
return respuesta; return respuesta;
} }
@Override @Override
public JSONObject execute_VU(JSONObject json) throws Exception{ public JSONObject execute_VU(JSONObject json) throws Exception{
JSONObject respuesta=new JSONObject(); JSONObject respuesta=new JSONObject();
Connection conexion=null; Connection conexion=null;
conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa"); conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa");
try{ try{
String sql="SELECT * FROM matricula.func_reporte_general_vacacional()"; String sql="SELECT * FROM matricula.func_reporte_general_vacacional()";
ResultSet rs=conexion.prepareStatement(sql).executeQuery(); ResultSet rs=conexion.prepareStatement(sql).executeQuery();
if(rs.next()){ if(rs.next()){
int columnCount=rs.getMetaData().getColumnCount(); int columnCount=rs.getMetaData().getColumnCount();
for (int i=1; i <= columnCount; i++) { for (int i=1; i <= columnCount; i++) {
respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i)); respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
} }
} }
} catch (Exception e) { } catch (Exception e) {
respuesta.put("error",e.getMessage()); respuesta.put("error",e.getMessage());
}finally { }finally {
if(conexion != null){ if(conexion != null){
conexion.close(); conexion.close();
} }
} }
return respuesta; return respuesta;
} }
@Override @Override
public JSONObject execute_reporte_sedes(JSONObject json) throws Exception{ public JSONObject execute_reporte_sedes(JSONObject json) throws Exception{
JSONObject respuesta=new JSONObject(); JSONObject respuesta=new JSONObject();
Connection conexion=null; Connection conexion=null;
conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa"); conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa");
try{ try{
String sql="select * from matricula.func_reporte_general_matricula()"; String sql="select * from matricula.func_reporte_general_matricula()";
ResultSet rs=conexion.prepareStatement(sql).executeQuery(); ResultSet rs=conexion.prepareStatement(sql).executeQuery();
if(rs.next()){ if(rs.next()){
int columnCount=rs.getMetaData().getColumnCount(); int columnCount=rs.getMetaData().getColumnCount();
for (int i=1; i <= columnCount; i++) { for (int i=1; i <= columnCount; i++) {
respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i)); respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
} }
} }
} catch (Exception e) { } catch (Exception e) {
respuesta.put("error",e.getMessage()); respuesta.put("error",e.getMessage());
}finally { }finally {
if(conexion != null){ if(conexion != null){
conexion.close(); conexion.close();
} }
} }
return respuesta; return respuesta;
} }
@Override @Override
public JSONObject execute_reporte_correos(JSONObject json) throws Exception{ public JSONObject execute_reporte_correos(JSONObject json) throws Exception{
JSONObject respuesta=new JSONObject(); JSONObject respuesta=new JSONObject();
Connection conexion=null; Connection conexion=null;
conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa"); conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa");
try{ try{
String sql="select * from matricula.func_reporte_general_correos()"; String sql="select * from matricula.func_reporte_general_correos()";
ResultSet rs=conexion.prepareStatement(sql).executeQuery(); ResultSet rs=conexion.prepareStatement(sql).executeQuery();
if(rs.next()){ if(rs.next()){
int columnCount=rs.getMetaData().getColumnCount(); int columnCount=rs.getMetaData().getColumnCount();
for (int i=1; i <= columnCount; i++) { for (int i=1; i <= columnCount; i++) {
respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i)); respuesta.put(rs.getMetaData().getColumnName(i),rs.getObject(i));
} }
} }
} catch (Exception e) { } catch (Exception e) {
respuesta.put("error",e.getMessage()); respuesta.put("error",e.getMessage());
}finally { }finally {
if(conexion != null){ if(conexion != null){
conexion.close(); conexion.close();
} }
} }
return respuesta; return respuesta;
} }
}
@Override
public JSONObject execute_avance_encuesta(JSONObject json) throws Exception{
JSONObject respuesta=new JSONObject();
Connection conexion=null;
try {
int p_opt=json.getInt("p_opt");
conexion=PostgreSqlFactoryDAO.obtenerConexion("siiaa");
String sql="select academico.func_encuesta_total(?)";
PreparedStatement ps=conexion.prepareStatement(sql);
Statement st=conexion.createStatement();
ps.setInt(1,p_opt);
ResultSet rs=ps.executeQuery();
if(rs.next()){
int columnCount=rs.getMetaData().getColumnCount();
for (int i=1; i <= columnCount; i++) {
respuesta.put(rs.getMetaData().getColumnName(i),new JSONObject(rs.getObject(i).toString()));
}
}
JSONArray data=respuesta.getJSONObject("func_encuesta_total").getJSONArray("data");
JSONArray respuesta2=new JSONArray();
data.forEach(item -> {
JSONObject obj=(JSONObject)item;
String sql2=obj.getString("script");
try {
st.executeQuery(sql2);
} catch (SQLException ignored) {
}
});
respuesta.put("salida",respuesta2);
} catch (Exception e) {
respuesta.put("error",e.getMessage());
} finally {
if(conexion != null){
conexion.close();
}
}
return respuesta;
}
}
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;
} }
} }
package pe.so.api.formulario.utilities; package pe.so.api.formulario.utilities;
import java.util.Vector; import java.util.Vector;
public class StringUtils { public class StringUtils {
public static int countChar(String str, char c) { public static int countChar(String str, char c) {
int count = 0; int count = 0;
for (int i = 0; i < str.length(); i++) { for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) { if (str.charAt(i) == c) {
count++; count++;
} }
} }
return count; return count;
} }
/** /**
* Divide una cadena según el caracter indicado y un número máximo de * Divide una cadena según el caracter indicado y un número máximo de
* divisiones si así se desea. * divisiones si así se desea.
*/ */
public static String[] split(String str, char sep, int maxNum) { public static String[] split(String str, char sep, int maxNum) {
if (str == null || str.length() == 0) { if (str == null || str.length() == 0) {
/* [1] */ /* [1] */
return new String[0]; return new String[0];
} }
/* [2] */ /* [2] */
Vector results = maxNum == 0 ? new Vector() : new Vector(maxNum); Vector results = maxNum == 0 ? new Vector() : new Vector(maxNum);
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
for (int i = 0; i < str.length(); i++) { for (int i = 0; i < str.length(); i++) {
/* [3] */ /* [3] */
char c = str.charAt(i); char c = str.charAt(i);
if (c == sep) { if (c == sep) {
if (maxNum != 0) { if (maxNum != 0) {
/* [4] */ /* [4] */
if ((results.size() + 1) == maxNum) { if ((results.size() + 1) == maxNum) {
for (; i < str.length(); i++) { for (; i < str.length(); i++) {
buf.append(str.charAt(i)); buf.append(str.charAt(i));
} }
break; break;
} }
} }
results.addElement(buf.toString()); results.addElement(buf.toString());
buf.setLength(0); buf.setLength(0);
} else { } else {
buf.append(c); buf.append(c);
} }
} }
if (buf.length() > 0) { if (buf.length() > 0) {
results.addElement(buf.toString()); results.addElement(buf.toString());
} }
return toStringArray(results); return toStringArray(results);
/* [5] */ /* [5] */
} }
public static String[] toStringArray(Vector strings) { public static String[] toStringArray(Vector strings) {
String[] result = new String[strings.size()]; String[] result = new String[strings.size()];
for (int i = 0; i < strings.size(); i++) { for (int i = 0; i < strings.size(); i++) {
result[i] = strings.elementAt(i).toString(); result[i] = strings.elementAt(i).toString();
} }
return result; return result;
} }
/** /**
* Separa un texto en varios según el caracter o cadena usada como * Separa un texto en varios según el caracter o cadena usada como
* delimitadora. * delimitadora.
*/ */
public static String[] split(String strString, String strDelimiter) { public static String[] split(String strString, String strDelimiter) {
int iOccurrences = 0; int iOccurrences = 0;
int iIndexOfInnerString = 0; int iIndexOfInnerString = 0;
int iIndexOfDelimiter = 0; int iIndexOfDelimiter = 0;
int iCounter = 0; int iCounter = 0;
// Check for null input strings. // Check for null input strings.
if (strString == null) { if (strString == null) {
throw new NullPointerException("Input string cannot be null."); throw new NullPointerException("Input string cannot be null.");
} }
// Check for null or empty delimiter // Check for null or empty delimiter
// strings. // strings.
if (strDelimiter.length() <= 0 || strDelimiter == null) { if (strDelimiter.length() <= 0 || strDelimiter == null) {
throw new NullPointerException("Delimeter cannot be null or empty."); throw new NullPointerException("Delimeter cannot be null or empty.");
} }
// If strString begins with delimiter // If strString begins with delimiter
// then remove it in // then remove it in
// order // order
// to comply with the desired format. // to comply with the desired format.
if (strString.startsWith(strDelimiter)) { if (strString.startsWith(strDelimiter)) {
strString = strString.substring(strDelimiter.length()); strString = strString.substring(strDelimiter.length());
} }
// If strString does not end with the // If strString does not end with the
// delimiter then add it // delimiter then add it
// to the string in order to comply with // to the string in order to comply with
// the desired format. // the desired format.
if (!strString.endsWith(strDelimiter)) { if (!strString.endsWith(strDelimiter)) {
strString += strDelimiter; strString += strDelimiter;
} }
// Count occurrences of the delimiter in // Count occurrences of the delimiter in
// the string. // the string.
// Occurrences should be the same amount // Occurrences should be the same amount
// of inner strings. // of inner strings.
while ((iIndexOfDelimiter = strString.indexOf(strDelimiter, while ((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1) { iIndexOfInnerString)) != -1) {
iOccurrences += 1; iOccurrences += 1;
iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length(); iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
} }
// Declare the array with the correct // Declare the array with the correct
// size. // size.
String[] strArray = new String[iOccurrences]; String[] strArray = new String[iOccurrences];
// Reset the indices. // Reset the indices.
iIndexOfInnerString = 0; iIndexOfInnerString = 0;
iIndexOfDelimiter = 0; iIndexOfDelimiter = 0;
// Walk across the string again and this // Walk across the string again and this
// time add the // time add the
// strings to the array. // strings to the array.
while ((iIndexOfDelimiter = strString.indexOf(strDelimiter, while ((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1) { iIndexOfInnerString)) != -1) {
// Add string to // Add string to
// array. // array.
strArray[iCounter] = strString.substring(iIndexOfInnerString, strArray[iCounter] = strString.substring(iIndexOfInnerString,
iIndexOfDelimiter); iIndexOfDelimiter);
// Increment the // Increment the
// index to the next // index to the next
// character after // character after
// the next // the next
// delimiter. // delimiter.
iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length(); iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
// Inc the counter. // Inc the counter.
iCounter += 1; iCounter += 1;
} }
return strArray; return strArray;
} }
/** /**
* Reemplaza en un texto la primera aparición del patrón por el texto de * Reemplaza en un texto la primera aparición del patrón por el texto de
* reemplazo. * reemplazo.
*/ */
public static String replace(String source, String pattern, public static String replace(String source, String pattern,
String replacement) { String replacement) {
// If source is null then Stop // If source is null then Stop
// and return empty String. // and return empty String.
if (source == null) { if (source == null) {
return ""; return "";
} }
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
// Intialize Index to -1 // Intialize Index to -1
// to check against it later // to check against it later
int idx = -1; int idx = -1;
// Intialize pattern Index // Intialize pattern Index
int patIdx = 0; int patIdx = 0;
// Search source from 0 to first occurrence of pattern // Search source from 0 to first occurrence of pattern
// Set Idx equal to index at which pattern is found. // Set Idx equal to index at which pattern is found.
idx = source.indexOf(pattern, patIdx); idx = source.indexOf(pattern, patIdx);
// If Pattern is found, idx will not be -1 anymore. // If Pattern is found, idx will not be -1 anymore.
if (idx != -1) { if (idx != -1) {
// append all the string in source till the pattern starts. // append all the string in source till the pattern starts.
sb.append(source.substring(patIdx, idx)); sb.append(source.substring(patIdx, idx));
// append replacement of the pattern. // append replacement of the pattern.
sb.append(replacement); sb.append(replacement);
// Increase the value of patIdx // Increase the value of patIdx
// till the end of the pattern // till the end of the pattern
patIdx = idx + pattern.length(); patIdx = idx + pattern.length();
// Append remaining string to the String Buffer. // Append remaining string to the String Buffer.
sb.append(source.substring(patIdx)); sb.append(source.substring(patIdx));
} }
// Return StringBuffer as a String // Return StringBuffer as a String
if (sb.length() == 0) { if (sb.length() == 0) {
return source; return source;
} else { } else {
return sb.toString(); return sb.toString();
} }
} }
/** /**
* Igual que con el método replace pero con todas las apariciones del patrón. * Igual que con el método replace pero con todas las apariciones del patrón.
*/ */
public static String replaceAll(String source, String pattern, public static String replaceAll(String source, String pattern,
String replacement) { String replacement) {
// If source is null then Stop // If source is null then Stop
// and retutn empty String. // and retutn empty String.
if (source == null) { if (source == null) {
return ""; return "";
} }
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
// Intialize Index to -1 // Intialize Index to -1
// to check agaist it later // to check agaist it later
int idx = -1; int idx = -1;
// Search source from 0 to first occurrence of pattern // Search source from 0 to first occurrence of pattern
// Set Idx equal to index at which pattern is found. // Set Idx equal to index at which pattern is found.
String workingSource = source; String workingSource = source;
// Iterate for the Pattern till idx is not be -1. // Iterate for the Pattern till idx is not be -1.
while ((idx = workingSource.indexOf(pattern)) != -1) { while ((idx = workingSource.indexOf(pattern)) != -1) {
// append all the string in source till the pattern starts. // append all the string in source till the pattern starts.
sb.append(workingSource.substring(0, idx)); sb.append(workingSource.substring(0, idx));
// append replacement of the pattern. // append replacement of the pattern.
sb.append(replacement); sb.append(replacement);
// Append remaining string to the String Buffer. // Append remaining string to the String Buffer.
sb.append(workingSource.substring(idx + pattern.length())); sb.append(workingSource.substring(idx + pattern.length()));
// Store the updated String and check again. // Store the updated String and check again.
workingSource = sb.toString(); workingSource = sb.toString();
// Reset the StringBuffer. // Reset the StringBuffer.
sb.delete(0, sb.length()); sb.delete(0, sb.length());
} }
return workingSource; return workingSource;
} }
/** /**
* Comprueba que una cadena sea nula o vacía. * Comprueba que una cadena sea nula o vacía.
*/ */
public static boolean isNullOrEmpty(String cadena) { public static boolean isNullOrEmpty(String cadena) {
boolean nullOrEmpty = false; boolean nullOrEmpty = false;
if (cadena == null) { if (cadena == null) {
nullOrEmpty = true; nullOrEmpty = true;
} else if (cadena.length() == 0) { } else if (cadena.length() == 0) {
nullOrEmpty = true; nullOrEmpty = true;
} }
return nullOrEmpty; return nullOrEmpty;
} }
/** /**
* Reduce el tamaño de una cadena mayor al tamaño indicado. En ese caso se * 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. * indicará que esta es más larga acortando y añadiendo 3 puntos seguidos.
* *
* @param cadena - Cadena a comprobar. * @param cadena - Cadena a comprobar.
* @param size - Tamaño máximo. * @param size - Tamaño máximo.
* @return Cadena original o cortada. * @return Cadena original o cortada.
*/ */
public static String truncateString(String cadena, int size) { public static String truncateString(String cadena, int size) {
String truncatedString = cadena; String truncatedString = cadena;
if (truncatedString != null && truncatedString.length() > size) { if (truncatedString != null && truncatedString.length() > size) {
truncatedString = cadena.substring(0, size - 4); truncatedString = cadena.substring(0, size - 4);
truncatedString += "..."; truncatedString += "...";
} }
return truncatedString; return truncatedString;
} }
public static boolean isNumeric(String str) { public static boolean isNumeric(String str) {
try { try {
double d = Double.parseDouble(str); double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
return false; return false;
} }
return true; return true;
} }
/** /**
* Reduce el tamaño de una cadena mayor al tamaño indicado. En ese caso se * 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. * 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. * Además añadiremos al final de la cadena truncada la información indicada.
*/ */
//public static String truncateStringWithInfo(String cadena, int size, String info) { //public static String truncateStringWithInfo(String cadena, int size, String info) {
//return StringUtil.truncateString(cadena, size) + info; //return StringUtil.truncateString(cadena, size) + info;
//} //}
} }
<?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