Compare commits

..

No commits in common. "master" and "Cola_impresion" have entirely different histories.

4575 changed files with 510978 additions and 60402 deletions

View File

@ -1,71 +0,0 @@
10
dir
4669
svn://172.17.26.185/COMACO/registro/portal
svn://172.17.26.185/COMACO
2016-03-18T19:28:02.833033Z
4511
fpazmino
a11ad980-3ca8-45f0-88f7-f0e618c262b7
ejb
dir
ear
dir
pom.xml
file
2022-07-28T03:45:37.714079Z
3a25df4f23bb0e667a9ff2f1a740b53d
2014-08-25T13:45:42.279378Z
348
dcruz
has-props
6781
web
dir

View File

@ -1,5 +0,0 @@
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -1,153 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
JBoss, Home of Professional Open Source
Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
contributors by the @authors tag. See the copyright.txt in the
distribution for a full listing of individual contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<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/maven-v4_0_0.xsd">
<name>portal</name>
<modelVersion>4.0.0</modelVersion>
<groupId>com.fp.armas</groupId>
<artifactId>portal</artifactId>
<version>2.1</version>
<packaging>pom</packaging>
<url>http://jboss.org/jbossas</url>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<distribution>repo</distribution>
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
</license>
</licenses>
<modules>
<module>ejb</module>
<module>web</module>
<module>ear</module>
</modules>
<properties>
<!-- Explicitly declaring the source encoding eliminates the following
message: -->
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
resources, i.e. build is platform dependent! -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- JBoss dependency versions -->
<version.jboss.maven.plugin>7.4.Final</version.jboss.maven.plugin>
<!-- Define the version of the JBoss BOMs we want to import to specify tested stacks. -->
<version.jboss.bom>1.0.7.Final</version.jboss.bom>
<!-- Alternatively, comment out the above line, and un-comment the line
below to use version 1.0.4.Final-redhat-4 which is a release certified to
work with JBoss EAP 6. It requires you have access to the JBoss EAP 6
maven repository. -->
<!-- <version.jboss.bom>1.0.4.Final-redhat-4</version.jboss.bom>> -->
<version.jboss.as>7.2.0.Final</version.jboss.as>
<!-- Alternatively, comment out the above line, and un-comment the
line below to use version 7.2.0.Final-redhat-8 which is a release certified
to work with JBoss EAP 6. It requires you have access to the JBoss EAP 6
maven repository. -->
<!-- <version.jboss.as>7.2.0.Final-redhat-8</version.jboss.as> -->
<!-- other plugin versions -->
<version.ear.plugin>2.6</version.ear.plugin>
<version.ejb.plugin>2.3</version.ejb.plugin>
<version.surefire.plugin>2.10</version.surefire.plugin>
<version.war.plugin>2.1.1</version.war.plugin>
<!-- maven-compiler-plugin -->
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
</properties>
<dependencyManagement>
<dependencies>
<!-- Define the version of the EJB jar so that we don't need
to repeat ourselves in every module -->
<dependency>
<groupId>com.fp.armas</groupId>
<artifactId>portal-ejb</artifactId>
<version>${project.version}</version>
<type>ejb</type>
</dependency>
<!-- Define the version of the WAR so that we don't need to repeat
ourselves in every module -->
<dependency>
<groupId>com.fp.armas</groupId>
<artifactId>portal-web</artifactId>
<version>${project.version}</version>
<type>war</type>
<scope>compile</scope>
</dependency>
<!-- JBoss distributes a complete set of Java EE 6 APIs including
a Bill of Materials (BOM). A BOM specifies the versions of a "stack" (or
a collection) of artifacts. We use this here so that we always get the correct
versions of artifacts. Here we use the jboss-javaee-6.0-with-tools stack
(you can read this as the JBoss stack of the Java EE 6 APIs, with some extras
tools for your project, such as Arquillian for testing) and the jboss-javaee-6.0-with-hibernate
stack you can read this as the JBoss stack of the Java EE 6 APIs, with extras
from the Hibernate family of projects) -->
<dependency>
<groupId>org.jboss.bom</groupId>
<artifactId>jboss-javaee-6.0-with-tools</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.jboss.bom</groupId>
<artifactId>jboss-javaee-6.0-with-hibernate</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<!-- The JBoss AS plugin deploys your ear to a local JBoss
AS container -->
<!-- Due to Maven's lack of intelligence with EARs we need
to configure the jboss-as maven plugin to skip deployment for all modules.
We then enable it specifically in the ear module. -->
<plugin>
<groupId>org.jboss.as.plugins</groupId>
<artifactId>jboss-as-maven-plugin</artifactId>
<version>${version.jboss.maven.plugin}</version>
<inherited>true</inherited>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

Binary file not shown.

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<netbeans.hint.jdkPlatform>ORACLE_JDK_1.8</netbeans.hint.jdkPlatform>
</properties>
</project-shared-configuration>

56
appletFirma/pom.xml Normal file
View File

@ -0,0 +1,56 @@
<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>
<groupId>com.fp.firma</groupId>
<artifactId>appletFirma</artifactId>
<version>2.1</version>
<packaging>jar</packaging>
<name>appletFirma</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcmail-jdk15on</artifactId>
<version>1.51</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-ext-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.3</version>
</dependency>
<dependency>
<groupId>io.rubrica</groupId>
<artifactId>rubrica</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,152 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.5" maxVersion="1.8" type="org.netbeans.modules.form.forminfo.JAppletFormInfo">
<NonVisualComponents>
<Component class="javax.swing.ButtonGroup" name="grupoRadios">
<AuxValues>
<AuxValue name="JavaCodeGenerator_allCodePost" type="java.lang.String" value="grupoRadios.add(tokenIkey);&#xa;grupoRadios.add(tokenAlladin);&#xa;grupoRadios.add(tokenSD);"/>
</AuxValues>
</Component>
</NonVisualComponents>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel1" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="41" max="-2" attributes="0"/>
<Component id="tokenIkey" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="tokenAlladin" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="tokenSD" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace pref="75" max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="tokenAlladin" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="tokenSD" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="tokenIkey" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="jPanel1" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="25" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel1">
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<Component id="labelArchivoFirma" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace min="12" pref="12" max="-2" attributes="0"/>
<Component id="btnFirmarArchivo" min="-2" max="-2" attributes="0"/>
</Group>
<Group type="102" attributes="0">
<Component id="txtRutaArchivo" min="-2" pref="139" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="btnExaminar" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="labelArchivoFirma" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtRutaArchivo" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnExaminar" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="btnFirmarArchivo" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="labelArchivoFirma">
<Properties>
<Property name="text" type="java.lang.String" value="Archivo a firmar"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtRutaArchivo">
<Properties>
<Property name="editable" type="boolean" value="false"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="btnExaminar">
<Properties>
<Property name="text" type="java.lang.String" value="Examinar"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnExaminarActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnFirmarArchivo">
<Properties>
<Property name="text" type="java.lang.String" value="Firmar"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnFirmarArchivoActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JRadioButton" name="tokenIkey">
<Properties>
<Property name="text" type="java.lang.String" value="iKey 2032"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenIkeyActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JRadioButton" name="tokenAlladin">
<Properties>
<Property name="text" type="java.lang.String" value="eTokenPro"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenAlladinActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JRadioButton" name="tokenSD">
<Properties>
<Property name="text" type="java.lang.String" value="Security Data"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenSDActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Form>

View File

@ -0,0 +1,345 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.applet;
import com.fp.firma.common.CertificateUtils;
import com.fp.firma.common.FirmMessages;
import com.itextpdf.text.Rectangle;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
/**
* Applet de firma electr&oacute;nica a trav&eacute;s de token
* @author dcruz
*/
public class FirmaApplet extends javax.swing.JApplet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String PREFIX = "firmado_";
private String rutaArchivoFirmar = "";
private static final Logger logger = Logger.getLogger(FirmaApplet.class .getName());
private String tipoFirma;
/**
* Initializes the applet FirmaApplet
*/
@Override
public void init() {
// FileHandler handler;
// try {
// handler = new FileHandler(System.getProperty("java.io.tmpdir")+"\\applet.txt");
// handler.setFormatter(new SimpleFormatter());
// logger.addHandler(handler);
// } catch (IOException ex) {
// Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
// } catch (SecurityException ex) {
// Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
// }
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* This method is called from within the init() method to initialize the form. WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
grupoRadios = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
labelArchivoFirma = new javax.swing.JLabel();
txtRutaArchivo = new javax.swing.JTextField();
btnExaminar = new javax.swing.JButton();
btnFirmarArchivo = new javax.swing.JButton();
tokenIkey = new javax.swing.JRadioButton();
tokenAlladin = new javax.swing.JRadioButton();
tokenSD = new javax.swing.JRadioButton();
grupoRadios.add(tokenIkey);
grupoRadios.add(tokenAlladin);
grupoRadios.add(tokenSD);
labelArchivoFirma.setText("Archivo a firmar");
txtRutaArchivo.setEditable(false);
btnFirmarArchivo.setEnabled(true);
btnExaminar.setEnabled(true);
btnExaminar.setText("Examinar");
btnExaminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExaminarActionPerformed(evt);
}
});
btnFirmarArchivo.setText("Firmar");
btnFirmarArchivo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFirmarArchivoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(labelArchivoFirma)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(btnFirmarArchivo))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnExaminar)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelArchivoFirma)
.addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnExaminar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnFirmarArchivo)
.addContainerGap())
);
tokenIkey.setText("iKey 2032");
tokenIkey.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenIkeyActionPerformed(evt);
}
});
tokenAlladin.setText("eTokenPro");
tokenAlladin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenAlladinActionPerformed(evt);
}
});
tokenSD.setText("Security Data");
tokenSD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenSDActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(tokenIkey)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tokenAlladin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tokenSD)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(75, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tokenAlladin)
.addComponent(tokenSD)
.addComponent(tokenIkey))
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25))
);
}// </editor-fold>//GEN-END:initComponents
private void btnExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExaminarActionPerformed
// TODO add your handling code here:
try
{
/**llamamos el metodo que permite cargar la ventana*/
JFileChooser fileChooser=new JFileChooser();
String rutaArchivo = txtRutaArchivo.getText();
File directorio = new File(rutaArchivo).getParentFile();
fileChooser.setCurrentDirectory(directorio);
// System.out.println("Directorio del archivo "+fileChooser.getCurrentDirectory() != null ? fileChooser.getCurrentDirectory().getAbsolutePath() : "");
/**abrimos el archivo seleccionado*/
int respuestaDialog = fileChooser.showOpenDialog(this);
if(respuestaDialog == JFileChooser.APPROVE_OPTION){
File fileSelected = fileChooser.getSelectedFile();
rutaArchivoFirmar = fileSelected.getAbsolutePath();
System.out.println("Ruta del archivo escogido "+rutaArchivoFirmar);
txtRutaArchivo.setText(rutaArchivoFirmar);
} else{
JOptionPane.showMessageDialog(null,"" +
"\nAccion cancelada por el usuario",
"ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
}
/**recorremos el archivo, lo leemos para plasmarlo
*en el area de texto*/
}catch(Throwable ex)
{
JOptionPane.showMessageDialog(null,ex+"" +
"\nNo se ha encontrado el archivo",
"ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_btnExaminarActionPerformed
private void btnFirmarArchivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFirmarArchivoActionPerformed
// TODO add your handling code here:
InputStream inputStream = null;
try{
String razon = getParameter("razon") != null ? getParameter("razon") : "";
String lugar = getParameter("lugar") != null ? getParameter("lugar") : "";
String nombreFirma = getParameter("firma") != null ? getParameter("firma") : "";
Float llx = Float.valueOf(getParameter("llx") != null ? Float.parseFloat(getParameter("llx")) : 0.0F);
Float lly = Float.valueOf(getParameter("lly") != null ? Float.parseFloat(getParameter("lly")) : 0.0F);
Float urx = Float.valueOf(getParameter("urx") != null ? Float.parseFloat(getParameter("urx")) : 0.0F);
Float ury = Float.valueOf(getParameter("ury") != null ? Float.parseFloat(getParameter("ury")) : 0.0F);
if(tipoFirma == null){
JOptionPane.showMessageDialog(null, "Debe seleccionar un Token con el cual firmar", "Tipo Firma", JOptionPane.ERROR_MESSAGE);
return;
}
if(txtRutaArchivo.getText() != null){
JPasswordField txtPasswordToken = new JPasswordField();
final JComponent[] components = new JComponent[]{new JLabel("Password:"), txtPasswordToken};
JOptionPane.showMessageDialog(null, components, "TOKEN", JOptionPane.PLAIN_MESSAGE);
if(txtPasswordToken.getPassword() == null){
throw new NullPointerException(FirmMessages.getString("FIR-0007"));
}
inputStream = new FileInputStream(txtRutaArchivo.getText());
byte[] datos = CertificateUtils.sign(inputStream, null, new String(txtPasswordToken.getPassword()), razon, lugar, Boolean.FALSE.booleanValue(), Boolean.FALSE.booleanValue(), new Rectangle(llx.floatValue(), lly.floatValue(), urx.floatValue(), ury.floatValue()), 1, nombreFirma, this.tipoFirma);
if(datos != null){
escribirArchivo(datos);
txtPasswordToken.setText("");
JOptionPane.showMessageDialog(null, "El archivo se modificado correctamente", "Archivo firmado", JOptionPane.INFORMATION_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(null, "Debe seleccionar un archivo", "Archivo no encontrado", JOptionPane.ERROR_MESSAGE);
}
btnFirmarArchivo.setEnabled(false);
btnExaminar.setEnabled(false);
} catch(IOException e){
JOptionPane.showMessageDialog(null, e.getMessage(), "IO Error", JOptionPane.ERROR_MESSAGE);
} catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} finally{
try {
if(inputStream != null){
inputStream.close();
}
} catch (IOException ex) {
Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_btnFirmarArchivoActionPerformed
public void escribirArchivo(byte[] data){
System.out.println("Ingreso a escribir el archivo");
FileOutputStream fo = null;
try {
File archivoFirmado = new File(txtRutaArchivo.getText());
fo = new FileOutputStream(archivoFirmado);
fo.write(data);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error archivo no encontrado", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error al escribir el archivo firmado", JOptionPane.ERROR_MESSAGE);
} finally {
try {
fo.close();
} catch (IOException ex) {
Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void tokenIkeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenIkeyActionPerformed
// TODO add your handling code here:
tipoFirma = "1";
}//GEN-LAST:event_tokenIkeyActionPerformed
private void tokenAlladinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenAlladinActionPerformed
// TODO add your handling code here:
tipoFirma = "2";
}//GEN-LAST:event_tokenAlladinActionPerformed
private void tokenSDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenSDActionPerformed
// TODO add your handling code here:
tipoFirma = "3";
}//GEN-LAST:event_tokenSDActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnExaminar;
private javax.swing.JButton btnFirmarArchivo;
private javax.swing.ButtonGroup grupoRadios;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel labelArchivoFirma;
private javax.swing.JRadioButton tokenAlladin;
private javax.swing.JRadioButton tokenIkey;
private javax.swing.JRadioButton tokenSD;
private javax.swing.JTextField txtRutaArchivo;
// End of variables declaration//GEN-END:variables
}

View File

@ -0,0 +1,584 @@
package com.fp.firma.common;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.fp.firma.dto.TfirmDatosFirmante;
import com.fp.firma.keystore.KeyStoreProvider;
import com.fp.firma.keystore.LinuxKeyStoreProvider;
import com.fp.firma.keystore.WindowsJDK6KeyStoreProvider;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.CertificateInfo;
import com.itextpdf.text.pdf.security.CertificateInfo.X500Name;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.OcspClient;
import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import com.itextpdf.text.pdf.security.TSAClient;
//import javax.persistence.NoResultException;
//import javax.persistence.Query;
/**
* Clase que contiene m&eacute;todos utilitarios para manejar certificados
*
* @author dcruz
*
*/
public class CertificateUtils {
/*
* CONSTANTES DESIGNADAS SEGUN LA NUEVA ESTRUCTURA DEL BCE
*/
// OIDs de Campos del Certificado:
public static final String OID_CEDULA_PASAPORTE = FirmMessages.getString("oid.cedula_pasaporte");
public static final String OID_NOMBRES = FirmMessages.getString("oid.nombres_persona");
public static final String OID_APELLIDO_1 = FirmMessages.getString("oid.apellido_persona1");
public static final String OID_APELLIDO_2 = FirmMessages.getString("oid.apellido_persona2");
public static final String OID_CARGO = FirmMessages.getString("oid.cargo");
public static final String OID_INSTITUCION = FirmMessages.getString("oid.institucion");
public static final String OID_DIRECCION = FirmMessages.getString("oid.direccion");
public static final String OID_TELEFONO = FirmMessages.getString("oid.telefono");
public static final String OID_CIUDAD = FirmMessages.getString("oid.ciudad");
public static final String OID_RAZON_SOCIAL = FirmMessages.getString("oid.razon_social");
public static final String OID_RUC = FirmMessages.getString("oid.ruc");
public static final String X509 = "X.509";
static {
BouncyCastleProvider provider = new BouncyCastleProvider();
Security.addProvider(provider);
}
/**
* Retorna el certificado del usuario contenido en la firma
*
* @param store el store en el que se va a buscar los certificados
* @param aliases los alias que estan dentro del keystore
* @return el {@link java.security.Certificate}
* @throws KeyStoreException
*/
public synchronized static Certificate obtainCertificateInAlias(KeyStore store, Enumeration<String> aliases) throws KeyStoreException {
Certificate certs[] = null;
synchronized (aliases) {
int i = 0;
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
System.out.println("Se imprime los alias: " + i + " " + alias);
certs = store.getCertificateChain(alias);
for (int j = 0; j < certs.length; j++) {
X509Certificate certificate = (X509Certificate) certs[j];
boolean[] usages = certificate.getKeyUsage();
System.out.println("Certificado en primera posicion usado: " + j + " " + usages[0]);
if (usages[0]) {
return certificate;
}
}
i++;
}
}
return null;
}
/**
* Se devuelve todos los datos de la firma del usuario en base al certificado enviado
*
* @param certificate el certificado enviado
* @return Los datos del certificado de dicho usuario
*/
public static TfirmDatosFirmante obtainDataForCertificate(Certificate certificate) {
X509Certificate signedCertificate = (X509Certificate) certificate;
TfirmDatosFirmante datosFirmante = new TfirmDatosFirmante();
if (signedCertificate.getExtensionValue(OID_CEDULA_PASAPORTE) != null) {
datosFirmante.setIdentificacion(new String(signedCertificate.getExtensionValue(OID_CEDULA_PASAPORTE)).trim());
}
if (signedCertificate.getExtensionValue(OID_NOMBRES) != null) {
datosFirmante.setNombre(new String(signedCertificate.getExtensionValue(OID_NOMBRES)).trim());
}
if (signedCertificate.getExtensionValue(OID_APELLIDO_1) != null) {
datosFirmante.setApellido1(new String(signedCertificate.getExtensionValue(OID_APELLIDO_1)).trim());
if (signedCertificate.getExtensionValue(OID_APELLIDO_2) != null) {
datosFirmante.setApellido2(new String(signedCertificate.getExtensionValue(OID_APELLIDO_2)).trim());
} else {
datosFirmante.setApellido2("");
}
}
if (signedCertificate.getExtensionValue(OID_TELEFONO) != null) {
datosFirmante.setTelefono(new String(signedCertificate.getExtensionValue(OID_TELEFONO)).trim());
}
if (signedCertificate.getExtensionValue(OID_CARGO) != null) {
datosFirmante.setCargo(new String(signedCertificate.getExtensionValue(OID_CARGO)).trim());
}
if (signedCertificate.getExtensionValue(OID_CIUDAD) != null) {
datosFirmante.setCiudad(new String(signedCertificate.getExtensionValue(OID_CIUDAD)).trim());
}
if (signedCertificate.getExtensionValue(OID_DIRECCION) != null) {
datosFirmante.setDireccion(new String(signedCertificate.getExtensionValue(OID_DIRECCION)).trim());
}
if (signedCertificate.getExtensionValue(OID_INSTITUCION) != null) {
datosFirmante.setInstitucion(new String(signedCertificate.getExtensionValue(OID_INSTITUCION)).trim());
}
if (signedCertificate.getExtensionValue(OID_RAZON_SOCIAL) != null) {
datosFirmante.setInstitucion(new String(signedCertificate.getExtensionValue(OID_RAZON_SOCIAL)).trim());
}
if (signedCertificate.getExtensionValue(OID_RUC) != null) {
datosFirmante.setRuc(new String(signedCertificate.getExtensionValue(OID_RUC)).trim());
}
datosFirmante.setFechaInicioVigencia(signedCertificate.getNotBefore());
datosFirmante.setFechaVigencia(signedCertificate.getNotAfter());
return datosFirmante;
}
/**
* Valida que el certificado del usuario sea un certificado valido contra el servicio OCSP del proveedor
*
* @param certificateUser
* @throws FileNotFoundException
* @throws CertificateException
*/
public static void validateOcsCertificate(Certificate certificateUser) throws FileNotFoundException, CertificateException {
System.out.println(((X509Certificate) certificateUser).getIssuerDN().getName());
CertificateFactory cf = CertificateFactory.getInstance(X509);
InputStream subordStream = new FileInputStream(FirmMessages.getString("dir.ruta.base.repositorio") + "/"
+ FirmMessages.getString("nombre.certificado.subordinado"));
X509Certificate subordCertificate = (X509Certificate) cf.generateCertificate(subordStream);
check((X509Certificate) certificateUser, subordCertificate);
}
/**
* Valida que los certificados enviados sean validos por la entidad certificadora
*
* @param issuerCert certificado del usuario
* @param x509Cert certificado que firmo el certificado expedido
*/
public static void check(X509Certificate issuerCert, X509Certificate x509Cert) {
// try {
//
// BigInteger serialNumber = issuerCert.getSerialNumber();
// X509CertificateHolder holder;
//
// try {
// holder = new X509CertificateHolder(x509Cert.getEncoded());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// CertificateID id = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build()
// .get(CertificateID.HASH_SHA1), holder, serialNumber);
//
// OCSPReqBuilder ocspGen = new OCSPReqBuilder();
// ocspGen.addRequest(id);
// OCSPReq ocspReq = ocspGen.build();
//
// // Ir al OCSP
// String ocspUrl = CertificateUtil.getOCSPURL(issuerCert);
//
// if (ocspUrl == null) {
// System.out.println("URL de OCSP is null");
// return;
// }
//
// URL url;
//
// try {
// url = new URL(ocspUrl);
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
//
// HttpURLConnection con;
// OCSPResp ocspResponse;
// DataOutputStream dataOut = null;
// try {
// con = (HttpURLConnection) url.openConnection();
//
// con.setRequestProperty("Content-Type", "application/ocsp-request");
// con.setRequestProperty("Accept", "application/ocsp-response");
// con.setDoOutput(true);
//
// OutputStream out = con.getOutputStream();
// dataOut = new DataOutputStream(new BufferedOutputStream(out));
// dataOut.write(ocspReq.getEncoded());
//
// System.out.println("Estado de respuesta de la peticion=" + con.getResponseCode());
//
// /*
// * Se parsea la respuesta y se obtiene el estado del certificado retornado por el OCSP
// */
// InputStream in = (InputStream) con.getContent();
// byte[] resp = read(in); // Read the reponse
// ocspResponse = new OCSPResp(resp);
// } catch (IOException e) {
// throw new FirmasException("ERROR AL ESTABLECER CONEXI\u00d3N AL SERVICIO: "+url);
// } finally{
// if(dataOut != null){
// try {
// dataOut.flush();
// dataOut.close();
// } catch (IOException e) {}
// }
// }
//
// int status = ocspResponse.getStatus();
// System.out.println("status=" + status);
//
// BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
//
// if (basicResponse != null) {
// SingleResp[] responses = basicResponse.getResponses();
// SingleResp response = responses[0];
// CertificateStatus certStatus = (CertificateStatus) response.getCertStatus();
//
// if (certStatus instanceof RevokedStatus) {
// System.out.println("REVOKED");
// RevokedStatus revokedStatus = (RevokedStatus) certStatus;
// System.out.println("Reason: " + revokedStatus.getRevocationReason());
// System.out.println("Date: " + revokedStatus.getRevocationTime());
//
// throw new FirmasException("ERROR, CERTIFICADO REVOCADO POR "+revokedStatus.getRevocationReason()+" CON FECHA "+ revokedStatus.getRevocationTime());
// }
// }
// } catch (OCSPException e) {
// throw new RuntimeException(e);
// } catch (CertificateEncodingException e) {
// throw new RuntimeException(e);
// }
}
/**
* Devuelve los nombres de firmas de un documento PDF
*
* @param docStream el documento a verificar
* @return un lista de nombres de firmas
*/
public static List<String> obtainNameSigns(InputStream docStream) {
try {
PdfReader docPdf = new PdfReader(docStream);
AcroFields af = docPdf.getAcroFields();
return af.getSignatureNames();
} catch (IOException e) {
System.err.println("Error al obtener los nombres del documentoss");
return null;
} finally{
}
}
/**
* M&eacute;todo para firmar documentos
* @param fileSrc
* @param usuario
* @param password
* @param compania
* @param reason
* @param location
* @param rectangle
* @param numPage
* @param nameSign
* @return
* @throws Exception
*/
public static byte[] sign(InputStream fileSrc, String usuario, String password, Integer compania, String reason, String location,
Rectangle rectangle, int numPage, String nameSign, String pathCertificate) throws Exception {
String path = pathCertificate;
FileInputStream ceritificateInputStream = new FileInputStream(path);
return sign(fileSrc, ceritificateInputStream, password, reason, location, false, true, rectangle, numPage, nameSign, null);
}
/**
* Metodo para firmar documentos
* @param fileSrc
* @param usuario
* @param password
* @param compania
* @param reason
* @param location
* @param rectangle
* @param numPage
* @param nameSign
* @return
* @throws Exception
*/
public static byte[] sign(InputStream fileSrc, String usuario, String password, Integer compania, String reason, String location,
Rectangle rectangle, int numPage, String nameSign) throws Exception {
String path = "";
FileInputStream ceritificateInputStream = new FileInputStream(path);
return sign(fileSrc, ceritificateInputStream, password, reason, location, false, true, rectangle, numPage, nameSign, null);
}
/**
* M&eacute;todo que firma un documento en base los par&aacute;metros indicados
*
* @param fileSrc archivo origen
* @param fileCert archivo firma en formato digital si no es null el firmado es con archivo caso contrario es token
* @param password contrasena
* @param reason raz&oacute;n o motivo de la firma.
* @param location localizaci&oacute;n coemtario adicional de la firma.
* @param withTS tiene TS estamapado de tiempo.
* @param withOCSP tiene OCSP verificacion de la firma por el la entidad certificadora BCE.
* @param rectangle lugar localizaci&acute;n firma
* @param numPage n&uacute;mero pagina
* @param nameSign nombre firma
* @param tipoFirma es el tipo de token que se usar&aacute;(Token que tipo?)
* @return el documento firmado
*/
public static byte[] sign(InputStream fileSrc, InputStream fileCert, String password, String reason, String location, boolean withTS,
boolean withOCSP, Rectangle rectangle, int numPage, String nameSign, String tipoFirma) {
OutputStream outputStream = null;
System.out.println("Ingreso a firmar");
try {
PdfReader pdfReader = new PdfReader(fileSrc);
outputStream = new ByteArrayOutputStream(512);
PdfStamper stamper = PdfStamper.createSignature(pdfReader, outputStream, '\0');
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
KeyStore store;
String alias;
// PrivateKey privateKey = null;
ExternalSignature signature = null;
if(fileCert != null){
store = KeyStore.getInstance("PKCS12");
store.load(fileCert, password.toCharArray());
alias = store.aliases().nextElement();
signature = new PrivateKeySignature((PrivateKey) store.getKey(alias, password.toCharArray()), DigestAlgorithms.SHA256,
"SunRsaSign");
} else{//firma por token
KeyStoreProvider provider = getKeyStoreProvider(tipoFirma);
store = provider.getKeystore(password.toCharArray());
alias = store.aliases().nextElement();
// privateKey = (PrivateKey) store.getKey(alias, null);
signature = new PrivateKeySignature((PrivateKey) store.getKey(alias, null), DigestAlgorithms.SHA1,
null);
}
// appearance.setCrypto(privateKey, store.getCertificateChain(alias), null, null);
appearance.setLayer2Text(generateSignText(store.getCertificateChain(alias), reason, location));
appearance.setLayer2Font(new Font(Font.FontFamily.UNDEFINED, 8F));
appearance.setVisibleSignature(rectangle, numPage, nameSign);
TSAClient tsc = null;
if (withTS) {
}
OcspClient ocsp = null;
if (withOCSP) {
ocsp = new OcspClientBouncyCastle();
}
// stamper.close();
ExternalDigest externalDigest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, externalDigest, signature, store.getCertificateChain(alias), null, ocsp, tsc, 15000,
CryptoStandard.CADES);
return ((ByteArrayOutputStream) outputStream).toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (DocumentException e) {
throw new RuntimeException(e);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (CertificateException e) {
throw new RuntimeException(e);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (FirmasException e) {
throw new RuntimeException(FirmMessages.getString("FIR-0006"));
} catch (Throwable e) {
throw new RuntimeException(e);
} finally{
try {
if(fileCert != null){
fileCert.close();
}
} catch (IOException e) {}
try {
fileSrc.close();
} catch (IOException e) {}
try {
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {}
}
}
/**
* Arma documento el texto a mostrar de la plantilla
* @param chains certificados
* @param reason raz&oacute;n
* @param location lugar
* @return una layout de la firma
*/
private static String generateSignText(Certificate[] chains, String reason, String location){
StringBuffer textLayout = new StringBuffer("Firmado digitalmente por: ");
String name = null;
X500Name x500name = CertificateInfo.getSubjectFields((X509Certificate)chains[0]);
if (x500name != null) {
name = x500name.getField("CN");
if (name == null)
name = x500name.getField("E");
}
if(name == null){
name = "";
}
textLayout.append(name).append("\n");
if(reason != null){
textLayout.append("Raz\u00f3n: ").append(reason).append("\n");
}
if(location != null){
textLayout.append("Lugar: ").append(location).append("\n");
}
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
textLayout.append("Fecha: ").append(format.format(new Date(System.currentTimeMillis())));
return textLayout.toString();
}
/**
* Retorna el keystore del token especificado
* @param tipoToken
* @return
* @throws KeyStoreException
*/
private static KeyStoreProvider getKeyStoreProvider(String tipoToken) {
String osName = System.getProperty("os.name");
KeyStoreProvider provider = null;
if(tipoToken == null){
return provider;
}
if (osName.toUpperCase().indexOf("WINDOWS") == 0) {
provider = new WindowsJDK6KeyStoreProvider();
if (tipoToken.equals("2")) {
provider = new WindowsJDK6KeyStoreProvider(); // trabaja con librerias sera para eToken
}else if (tipoToken.equals("1")) {
provider = new WindowsJDK6KeyStoreProvider(); // trabaja con librerias sera para iKey
}else if (tipoToken.equals("3")) {
provider = new WindowsJDK6KeyStoreProvider(); // trabaja con librerias sera para iKey
}
} else {
provider = new LinuxKeyStoreProvider();
}
return provider;
}
private static byte[] read(InputStream in) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = in.read();
while (next > -1) {
bos.write(next);
next = in.read();
}
bos.flush();
return bos.toByteArray();
}
/**
* Entrega el path en el que se encuentra el certificado digital.
*
* @param cusuario Codigo de usuario.
* @param ccompania Codigo de compania.
* @return String
* @throws Exception
*/
// private static String getPath(String cusuario, Integer ccompania) throws Exception {
// TfirmCertificado tfirmcertificado = getTfirmCertificado(cusuario);
// TgeneParametersKey tgeneParametersKey = new TgeneParametersKey("PATH_CERTIFICADO_BCE", ccompania);
// TgeneParameters tgeneParameters = TgeneParameters.find(PersistenceHelper.getEntityManager(), tgeneParametersKey);
// String path = tgeneParameters.getTextvalue() + "/" + tfirmcertificado.getPk().getIdcertificado();
// return path;
// }
/**
* Sentencia que entrega la defincion vigente de un certificado digital para un usuario.
*/
// private static final String JPQL = "from TfirmCertificado where t.codigousuario = :cusuario";
/**
* Entrega defincion de certificados digitales vigente.
*
* @param cusuario Codigo de usuario.
* @return TfirmCertificado.
* @throws Exception
*/
// private static TfirmCertificado getTfirmCertificado(String cusuario) throws Exception {
// TfirmCertificado tfirmCertificado = null;
// Query qry = PersistenceHelper.getEntityManager().createQuery(JPQL);
// qry.setParameter("cusuario", cusuario);
// try {
// tfirmCertificado = (TfirmCertificado) qry.getSingleResult();
// } catch (NoResultException e) {
// throw new FirmasException("FIR-0001", "PARAMETROS DEL CERTIFICADO DIGITAL NO DEFINIDO PARA EL USUARIO: {0}", cusuario);
// }
// return tfirmCertificado;
// }
/*
public static boolean validatePassword(InputStream fileSrc, String usuario, String password, Integer compania, String reason, String location,
Rectangle rectangle, int numPage, String nameSign) throws Exception {
String path = getPath(usuario, compania);
FileInputStream ceritificateInputStream = new FileInputStream(path);
return pass(fileSrc, ceritificateInputStream, password, reason, location, false, true, rectangle, numPage, nameSign);
}
private static boolean pass(InputStream fileSrc, InputStream fileCert, String password, String reason, String location, boolean withTS,
boolean withOCSP, Rectangle rectangle, int numPage, String nameSign) {
try {
PdfReader pdfReader = new PdfReader(fileSrc);
OutputStream outputStream = new ByteArrayOutputStream(512);
PdfStamper stamper = PdfStamper.createSignature(pdfReader, outputStream, '\0');
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(fileCert, password.toCharArray());
String alias = store.aliases().nextElement();
ExternalSignature signature = new PrivateKeySignature((PrivateKey) store.getKey(alias, password.toCharArray()), DigestAlgorithms.SHA256,
"SunRsaSign");
return true;
} catch (Exception e) {
return false;
}
}
*/
}

View File

@ -0,0 +1,19 @@
package com.fp.firma.common;
import java.util.ResourceBundle;
public class FirmMessages {
private final static String RESOURCE = "firmessages_es";
private final static ResourceBundle firmessages;
static{
firmessages = ResourceBundle.getBundle(RESOURCE);
}
public static String getString(String key) {
return firmessages.getString(key);
}
}

View File

@ -0,0 +1,30 @@
package com.fp.firma.common;
/**
* Clase que manejar&aacute; todos los errores relacionados con la firma digital
*
* @author dcruz
*
*/
public class FirmasException extends RuntimeException {
private static final long serialVersionUID = -599185902882644036L;
public FirmasException(String message) {
super(message);
}
public FirmasException(String message, Throwable cause) {
super(message, cause);
}
public FirmasException(Throwable cause) {
super(cause);
}
public FirmasException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -0,0 +1,53 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
/**
* Dialog que permite el ingreso del password del token para la firma
* @author dcruz
*/
public class PasswordDialog extends JDialog implements ActionListener, PropertyChangeListener{
private JPasswordField txtPasswordCertificado;
public PasswordDialog(){
super();
txtPasswordCertificado = new JPasswordField();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent ce) {
txtPasswordCertificado.requestFocusInWindow();
}
});
txtPasswordCertificado.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void propertyChange(PropertyChangeEvent evt) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/** This method clears the dialog and hides it. */
public void clearAndHide() {
txtPasswordCertificado.setText(null);
setVisible(false);
}
}

View File

@ -0,0 +1,169 @@
package com.fp.firma.dto;
import java.io.Serializable;
import java.util.Date;
/**
* Clase que contiene los datos del usuario que es dueno de la firma y en la cual
*
* @author dcruz
*
*/
public class TfirmDatosFirmante implements
Serializable, Cloneable {
private static final long serialVersionUID = 4232773513442100177L;
private String aliasCertificado;
private String identificacion;
private String nombre;
private String apellido1;
private String apellido2;
private String cargo;
private String institucion;
private String direccion;
private String telefono;
private String ciudad;
private String razonSocial;
private String ruc;
private Date fechaInicioVigencia;
private Date fechaVigencia;
public TfirmDatosFirmante(){}
public TfirmDatosFirmante(String identificacion, String nombre,
String apellido1, String apellido2, String cargo,
String institucion, String direccion, String telefono,
String ciudad, String razonSocial, String ruc) {
super();
this.identificacion = identificacion;
this.nombre = nombre;
this.apellido1 = apellido1;
this.apellido2 = apellido2;
this.cargo = cargo;
this.institucion = institucion;
this.direccion = direccion;
this.telefono = telefono;
this.ciudad = ciudad;
this.razonSocial = razonSocial;
this.ruc = ruc;
}
public String getIdentificacion() {
return identificacion;
}
public void setIdentificacion(String identificacion) {
this.identificacion = identificacion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido1() {
return apellido1;
}
public void setApellido1(String apellido1) {
this.apellido1 = apellido1;
}
public String getApellido2() {
return apellido2;
}
public void setApellido2(String apellido2) {
this.apellido2 = apellido2;
}
public String getCargo() {
return cargo;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
public String getInstitucion() {
return institucion;
}
public void setInstitucion(String institucion) {
this.institucion = institucion;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public String getRazonSocial() {
return razonSocial;
}
public void setRazonSocial(String razonSocial) {
this.razonSocial = razonSocial;
}
public String getRuc() {
return ruc;
}
public void setRuc(String ruc) {
this.ruc = ruc;
}
public Object cloneMe() throws CloneNotSupportedException {
return this.clone();
}
public Date getFechaVigencia() {
return fechaVigencia;
}
public void setFechaVigencia(Date fechaVigencia) {
this.fechaVigencia = fechaVigencia;
}
public Date getFechaInicioVigencia() {
return fechaInicioVigencia;
}
public void setFechaInicioVigencia(Date fechaInicioVigencia) {
this.fechaInicioVigencia = fechaInicioVigencia;
}
public String getAliasCertificado() {
return aliasCertificado;
}
public void setAliasCertificado(String aliasCertificado) {
this.aliasCertificado = aliasCertificado;
}
}

View File

@ -0,0 +1,45 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
/**
* Implementacion de <code>KeyStoreProvider</code> para el
* sistema operativo Mac OS X.
*
*/
public class AppleKeyStoreProvider implements KeyStoreProvider {
private static final String APPLE_PROVIDER_TYPE = "KeychainStore";
private static final String APPLE_PROVIDER_NAME = "Apple";
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance(APPLE_PROVIDER_TYPE, APPLE_PROVIDER_NAME);
keyStore.load(null, null);
return keyStore;
} catch (NoSuchProviderException e) {
throw new KeyStoreException(e);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,48 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
/**
* Implementaci&oacute;n de KeyStoreProvider para leer de un archivo.
*
*/
public class FileKeyStoreProvider implements KeyStoreProvider {
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
InputStream input = new FileInputStream(System.getProperty("user.home") + File.separator + ".keystore");
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(input, password);
return keyStore;
} catch (FileNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
} finally {
// TODO: Close InputStream
}
}
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.security.KeyStore;
import java.security.KeyStoreException;
/**
* Obtiene un KeyStore.
*
*/
public interface KeyStoreProvider {
/**
* Obtiene un KeyStore protegido por un password.
*
* @param password
* @return
* @throws KeyStoreException
*/
KeyStore getKeystore(char[] password) throws KeyStoreException;
}

View File

@ -0,0 +1,40 @@
package com.fp.firma.keystore;
import java.util.logging.Logger;
/**
* Obtiene la implementacion correcta de KeyStoreProvider de acuerdo al sistema
* operativo.
*/
public class KeyStoreProviderFactory {
private static final Logger log = Logger.getLogger(KeyStoreProviderFactory.class.getName());
/**
* Obtiene la implementacion correcta de KeyStoreProvider de acuerdo al
* sistema operativo.
*
* @return implementacion de KeyStoreProvider
*/
public static KeyStoreProvider createKeyStoreProvider() {
String osName = System.getProperty("os.name");
String javaVersion = System.getProperty("java.version");
log.finer("Operating System:" + osName);
log.finer("Java Version:" + javaVersion);
if (osName.toUpperCase().indexOf("WINDOWS") == 0) {
if (javaVersion.indexOf("1.6") == 0) {
return new WindowsJDK6KeyStoreProvider();
} else {
return new WindowsJDK5KeyStoreProvider();
}
} else if (osName.toUpperCase().indexOf("LINUX") == 0) {
return new LinuxKeyStoreProvider();
} else if (osName.toUpperCase().indexOf("MAC") == 0) {
return new AppleKeyStoreProvider();
} else {
throw new IllegalArgumentException("Sistema operativo no soportado!");
}
}
}

View File

@ -0,0 +1,123 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
/**
* Implementacion de <code>KeyStoreProvider</code> para utilizar con librerias
* PKCS#11 del sistema operativo Linux.
*
* Utiza OpenCT para acceder a un Token USB.
*
*
*/
public class LinuxKeyStoreProvider implements KeyStoreProvider {
//MAC: /usr/local/lib/libsfntpkcs11.dylib\nslot = 1
private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = /usr/local/SafeNet/lib/libsfntpkcs11.so\nslot = 1 \n showInfo = true".getBytes(); // /usr/local/SafeNet/lib/libsfntpkcs11.so\nslot = 1
///usr/local/lib/libsfntpkcs11.dylib
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
// Eestas lineas se ±adieron para poder hacer un logout del keystore
//
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection( new SimpleCallbackHandler(null,password ) )); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
//
aprov = (AuthProvider) Security.getProvider( sunPKCS11Provider.getName() );
aprov.setCallbackHandler( new SimpleCallbackHandler(null,password ) ); //cmdLineHdlr
try {
aprov.login(null, null);
} catch (LoginException ex) {
Logger.getLogger(LinuxKeyStoreProvider.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginException( /*ex*/ );
}
// KeyStore keyStore = KeyStore.getInstance("PKCS11");
//
// keyStore.load(null, password); //null
System.out.println("Dentro LinuxKeystore anntes de ks:" + ks);
// aprov.logout();
return ks; //keyStore
// } catch (CertificateException e) {
// throw new KeyStoreException(e);
// } catch (NoSuchAlgorithmException e) {
// throw new KeyStoreException(e);
// } catch (IOException e) {
// throw new KeyStoreException(e);
// }
} catch (Exception e){
System.out.println("Error en el keystore:" + e);
e.printStackTrace();
throw new KeyStoreException(e);
}
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException{
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
/**
* Implementacion de KeyStoreProvider para pruebas.
*
*/
public class MockKeyStoreProvider implements KeyStoreProvider {
private static final String KEYSTORE_FILE = "/home/ricardo/ricardostore";
// private static final String KEYSTORE_ALIAS = "firmadigital";
// private static final char[] KEYSTORE_PASSWORD = "abc123".toCharArray();
// private static final char[] KEY_PASSWORD = "ricardo".toCharArray();
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
FileInputStream ksfis;
ksfis = new FileInputStream(KEYSTORE_FILE);
BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
keyStore.load(ksbufin, password);
// PrivateKey priv = (PrivateKey) keyStore.getKey(KEYSTORE_ALIAS,
// KEY_PASSWORD);
return keyStore;
} catch (FileNotFoundException e) {
throw new KeyStoreException(e);
} catch (GeneralSecurityException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CertificateException;
/**
* Implementacion de <code>KeyStoreProvider</code> para utilizar con librerias
* PKCS#11 del sistema operativo.
*
* Utiza OpenCT para acceder a un Token USB.
*
*
*/
public abstract class PKCS11KeyStoreProvider implements KeyStoreProvider {
/**
* Obtiene la configuraci&oacute;n para el Provider, seg&uacute;n el sistema operativo que se utilice.
*
* @return
*/
public abstract String getConfig();
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
InputStream configStream = new ByteArrayInputStream(getConfig().getBytes());
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore keyStore = KeyStore.getInstance("PKCS11");
keyStore.load(null, password);
return keyStore;
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName("sun.security.pkcs11.SunPKCS11");
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
return (Provider) pkcs11Constr.newInstance(configStream);
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,49 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.keystore;
/**
*
* @author subinfo
*/
import javax.security.auth.callback.*;
/**
* This simple callback handler presents the given user name and password.
* @version 1.0 2004-09-14
* @author Cay Horstmann
*/
public class SimpleCallbackHandler implements CallbackHandler
{
/**
* Constructs the callback handler.
* @param username the user name
* @param password a character array containing the password
*/
public SimpleCallbackHandler(String username, char[] password)
{
this.username = username;
this.password = password;
}
public void handle(Callback[] callbacks)
{
for (Callback callback : callbacks)
{
if (callback instanceof NameCallback)
{
((NameCallback) callback).setName(username);
}
else if (callback instanceof PasswordCallback)
{
((PasswordCallback) callback).setPassword(password);
}
}
}
private String username;
private char[] password;
}

View File

@ -0,0 +1,129 @@
/** Programa para La firma electrónica de archivos
* Desarrollado y Modificado por la Subsecretaría de Tecnologías de la Información
* de la Secretaría Nacional de la Administración Pública del Ecuador
* Firma Digital firmadigital.informatica.gob.ec
*------------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or
modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
License
* along with this program. If not, see http://www.gnu.org/licenses. [^]
*------------------------------------------------------------------------------
**/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.ProviderException;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.ReflectionException;
import javax.security.auth.login.LoginException;
/**
* maneja el keystore de windows, no el CAPI, accede a travez de librerias, en esta se usa librerias para eTokenPro
**/
public class WindowsJDK5KeyStoreProvider implements KeyStoreProvider {
//private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = C:\\WINDOWS\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS }".getBytes();
private static String windowsDir = "name = SmartCard\nlibrary = " + System.getenv("WINDIR") + "\\SYSTEM32\\eTPKCS11.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS } \n showInfo = true"; //showInfo = true
private static final byte[] PKCS11_CONFIG = windowsDir.getBytes();
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
System.out.println("Tiene PKCS11: " + PKCS11_CONFIG);
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection(new SimpleCallbackHandler(null, password))); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
aprov = (AuthProvider) Security.getProvider(sunPKCS11Provider.getName());
aprov.setCallbackHandler(new SimpleCallbackHandler(null, password)); //cmdLineHdlr
aprov.login(null, null);
//
return ks; //keyStore
//
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("error en el loginExcep" + ex);
} catch (KeyStoreException e) {
System.out.println("e:" + e.getCause().toString().length());
throw new KeyStoreException(e);
}
// catch (Exception e){
// System.out.println("Error en el keystore:" + e.getCause().toString().length() );
// throw new KeyStoreException( e.getMessage() ,e.getCause());
// }
return null;
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException {
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws ProviderException, KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e.getMessage(), e.getCause());
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,139 @@
/** Programa para La firma electrónica de archivos
* Desarrollado y Modificado por la Subsecretaría de Tecnologías de la Información
* de la Secretaría Nacional de la Administración Pública del Ecuador
* Firma Digital firmadigital.informatica.gob.ec
*------------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or
modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
License
* along with this program. If not, see http://www.gnu.org/licenses. [^]
*------------------------------------------------------------------------------
**/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
/**
* Esta clase se usa para obtener el keystore (Con el se pueden obtener luego los certificados dentro del token) en Windows
*/
public class WindowsJDK5KeyStoreProvider_SD implements KeyStoreProvider {
//private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = C:\\WINDOWS\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS }".getBytes();
// esta linea corrige el error de la ubicación de Windows
// para trabajar con iKey
private static final String windowsDir_SD = "name = ePass3003\nlibrary = C:\\WINDOWS\\SYSTEM32\\SecurityDataCsp11_3003.dll \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS } \n\r showInfo = true";
private static final byte[] PKCS11_CONFIG_SD = windowsDir_SD.getBytes();
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
/**
* <code> getKeystore </code>
* Esta funcion se utiliza para obtener el keystore de java para manejar luego la clave privada y los certificados dentro del token
* @param password Se pasa la clave del token
* @return
* @throws java.security.KeyStoreException
*/
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
// empieza intentando con eToken
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG_SD);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection(new SimpleCallbackHandler(null, password))); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
// Estas lineas se añadieron para controlar mejor el logout del token
aprov = (AuthProvider) Security.getProvider(sunPKCS11Provider.getName());
aprov.setCallbackHandler(new SimpleCallbackHandler(null, password)); //cmdLineHdlr
try {
aprov.login(null, null);
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_SD.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginException( /*ex*/);
}
return ks; //keyStore
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_SD.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("error en el loginExcep" + ex);
} catch (KeyStoreException e) {
System.out.println("e:" + e.getCause().toString().length());
throw new KeyStoreException(e);
}
// } catch (Exception e){
// System.out.println("Error en el keystore:" + e);
// throw new KeyStoreException(e);
// }
return null;
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException {
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,144 @@
/** Programa para La firma electrónica de archivos
* Desarrollado y Modificado por la Subsecretaría de Tecnologías de la Información
* de la Secretaría Nacional de la Administración Pública del Ecuador
* Firma Digital firmadigital.informatica.gob.ec
*------------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or
modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
License
* along with this program. If not, see http://www.gnu.org/licenses. [^]
*------------------------------------------------------------------------------
**/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
/**
* Esta clase se usa para obtener el keystore (Con el se pueden obtener luego los certificados dentro del token iKEY) en Windows
*/
public class WindowsJDK5KeyStoreProvider_iKey implements KeyStoreProvider {
//private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = C:\\WINDOWS\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS }".getBytes();
// esta linea corrige el error de la ubicación de Windows
// para trabajar con iKey
private static String windowsDir_iKey ="name = SmartCard\nlibrary = "+ System.getenv("WINDIR") + "\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS } \n showInfo = true";
private static final byte[] PKCS11_CONFIG_IKEY = windowsDir_iKey.getBytes();
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
/**
* <code> getKeystore </code>
* Esta funcion se utiliza para obtener el keystore de java para manejar luego la clave privada y los certificados dentro del token
* @param password Se pasa la clave del token
* @return
* @throws java.security.KeyStoreException
*/
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
// empieza intentando con eToken
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG_IKEY);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection( new SimpleCallbackHandler(null,password ) )); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
// Estas lineas se añadieron para controlar mejor el logout del token
aprov = (AuthProvider) Security.getProvider( sunPKCS11Provider.getName() );
aprov.setCallbackHandler( new SimpleCallbackHandler(null,password ) ); //cmdLineHdlr
try {
aprov.login(null, null);
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_iKey.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginException( /*ex*/ );
}
return ks; //keyStore
}
catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_iKey.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("error en el loginExcep" + ex);
} catch (KeyStoreException e) {
System.out.println("e:"+ e.getCause().toString().length() );
throw new KeyStoreException(e);
}
// } catch (Exception e){
// System.out.println("Error en el keystore:" + e);
// throw new KeyStoreException(e);
// }
return null;
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException{
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import com.fp.firma.common.FirmasException;
/**
* Implementaci&oacute;n de KeyStoreProvider para acceder al keystore del sistema operativo
* Microsoft Windows.
*
* Utiliza funcionalidad disponible desde el JDK6 en adelante para acceder al MS CAPI.
*
*/
public class WindowsJDK6KeyStoreProvider implements KeyStoreProvider {
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance("Windows-MY");
keyStore.load(null, password);
return keyStore;
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
if(e.getCause() instanceof UnrecoverableKeyException){
throw new FirmasException(e);
} else{
throw new KeyStoreException(e);
}
} catch (Throwable e) {
if ((e instanceof UnrecoverableKeyException)) {
throw new FirmasException(e);
} else{
throw new KeyStoreException(e);
}
}
}
}

View File

@ -0,0 +1,43 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
/**
* Implementacion de KeyStoreProvider para acceder al keystore del sistema operativo
* Microsoft Windows.
*
* Utiliza funcionalidad disponible desde el JDK6 en adelante para acceder al MS CAPI.
*
*/
public class WindowsKeyStoreProvider implements KeyStoreProvider {
private static final String MICROSOFT_WINDOWS_PROVIDER_TYPE = "Windows-MY";
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance(MICROSOFT_WINDOWS_PROVIDER_TYPE);
keyStore.load(null, password);
return keyStore;
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,48 @@
###################################################
##### S\u00edmbolos unicode
#####\u00e1 -> á
#####\u00e9 -> é
#####\u00ed -> í
#####\u00f3 -> ó
#####\u00fa -> ú
#####\u00c1 -> Á
#####\u00c9 -> É
#####\u00cd -> Í
#####\u00d3 -> Ó
#####\u00da -> Ú
#####\u00f1 -> ñ
#####\u00d1 -> Ñ
#####\u0020 -> Espacio en blanco
###################################################
#========================================================================================
#=======CODIGO EXCEPCIONES===============================================================
#========================================================================================
FIR-0001=ERROR AL ESTABLECER CONEXI\u00D3N AL SERVICIO\: {0}
FIR-0002=ERROR, CERTIFICADO REVOCADO POR {0} CON FECHA {1}
FIR-0005=ERROR, ES OBLIGATORIO CARGAR UN ARCHIVO
FIR-0006=ERROR, LA CONTRASE\u00d1A INGRESADA ES INCORRECTA
FIR-0007=ERROR, EL CAMPO PASSWORD ES OBLIGATORIO
#========================================================================================
#=======OIDs GENERALES DE IDENTIFICACION DEL USUARIO EN EL CERTIFICADO===================
#========================================================================================
oid.cedula_pasaporte=1.3.6.1.4.1.37947.3.1
oid.nombres_persona=1.3.6.1.4.1.37947.3.2
oid.apellido_persona1=1.3.6.1.4.1.37947.3.3
oid.apellido_persona2=1.3.6.1.4.1.37947.3.4
oid.cargo=1.3.6.1.4.1.37947.3.5
oid.institucion=1.3.6.1.4.1.37947.3.6
oid.direccion=1.3.6.1.4.1.37947.3.7
oid.telefono=1.3.6.1.4.1.37947.3.8
oid.ciudad=1.3.6.1.4.1.37947.3.9
oid.razon_social=1.3.6.1.4.1.37947.3.10
oid.ruc=1.3.6.1.4.1.37947.3.11
#========================================================================================
#=======RUTAS DE LOS DIRECTORIOS DEL REPOSITORIO DE CERTIFICADOS=========================
#========================================================================================
dir.ruta.base.repositorio=/media/store/maia/jboss-eap-6.0/digital_repository
dir.nombre.carpeta.usuarios=users
nombre.certificado.raiz=CARAIZ.cer
nombre.certificado.subordinado=CASUBORDINADO.cer
service.url.address.ocsp=http://ocsp.digsigtrust.com:80
#service.url.address.ocsp=http://ocsp.openvalidation.org:80

View File

@ -0,0 +1,38 @@
package com.fp.firma.applet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

View File

@ -0,0 +1,39 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.applet;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.fp.firma.common.CertificateUtils;
import com.itextpdf.text.Rectangle;
/**
*
* @author dcruz
*/
public class PruebaFirma {
// @Test
public static void main(String[] args){
try {
InputStream is = new FileInputStream("C:\\Users\\abenalcazar\\dwhelper\\Downloads\\Tutorial_de_Maven_3_Erick_Camacho.pdf");
String password = "Password#1";
byte[] array = CertificateUtils.sign(is, null, password, "Firmado digitalmente", "Por firmar", Boolean.FALSE, Boolean.FALSE, new Rectangle(50, 50, 200, 200), 1, "Firma 2", "2");
is.close();
System.out.println("Tam array "+ array != null ? array.length:0);
FileOutputStream os = new FileOutputStream("C:\\Users\\abenalcazar\\dwhelper\\Downloads\\Tutorial_de_Maven_3_Erick_Camacho.pdf");
os.write(array);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Throwable e){
e.printStackTrace();
}
}
}

Binary file not shown.

View File

@ -0,0 +1,48 @@
###################################################
##### S\u00edmbolos unicode
#####\u00e1 -> á
#####\u00e9 -> é
#####\u00ed -> í
#####\u00f3 -> ó
#####\u00fa -> ú
#####\u00c1 -> Á
#####\u00c9 -> É
#####\u00cd -> Í
#####\u00d3 -> Ó
#####\u00da -> Ú
#####\u00f1 -> ñ
#####\u00d1 -> Ñ
#####\u0020 -> Espacio en blanco
###################################################
#========================================================================================
#=======CODIGO EXCEPCIONES===============================================================
#========================================================================================
FIR-0001=ERROR AL ESTABLECER CONEXI\u00D3N AL SERVICIO\: {0}
FIR-0002=ERROR, CERTIFICADO REVOCADO POR {0} CON FECHA {1}
FIR-0005=ERROR, ES OBLIGATORIO CARGAR UN ARCHIVO
FIR-0006=ERROR, LA CONTRASE\u00d1A INGRESADA ES INCORRECTA
FIR-0007=ERROR, EL CAMPO PASSWORD ES OBLIGATORIO
#========================================================================================
#=======OIDs GENERALES DE IDENTIFICACION DEL USUARIO EN EL CERTIFICADO===================
#========================================================================================
oid.cedula_pasaporte=1.3.6.1.4.1.37947.3.1
oid.nombres_persona=1.3.6.1.4.1.37947.3.2
oid.apellido_persona1=1.3.6.1.4.1.37947.3.3
oid.apellido_persona2=1.3.6.1.4.1.37947.3.4
oid.cargo=1.3.6.1.4.1.37947.3.5
oid.institucion=1.3.6.1.4.1.37947.3.6
oid.direccion=1.3.6.1.4.1.37947.3.7
oid.telefono=1.3.6.1.4.1.37947.3.8
oid.ciudad=1.3.6.1.4.1.37947.3.9
oid.razon_social=1.3.6.1.4.1.37947.3.10
oid.ruc=1.3.6.1.4.1.37947.3.11
#========================================================================================
#=======RUTAS DE LOS DIRECTORIOS DEL REPOSITORIO DE CERTIFICADOS=========================
#========================================================================================
dir.ruta.base.repositorio=/media/store/maia/jboss-eap-6.0/digital_repository
dir.nombre.carpeta.usuarios=users
nombre.certificado.raiz=CARAIZ.cer
nombre.certificado.subordinado=CASUBORDINADO.cer
service.url.address.ocsp=http://ocsp.digsigtrust.com:80
#service.url.address.ocsp=http://ocsp.openvalidation.org:80

View File

@ -0,0 +1,5 @@
#Generated by Maven
#Tue Jan 17 16:56:13 ECT 2023
version=2.1
groupId=com.fp.firma
artifactId=appletFirma

View File

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8" ?>
<testsuite tests="1" failures="0" name="com.fp.firma.applet.AppTest" time="0.003" errors="0" skipped="0">
<properties>
<property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/>
<property name="sun.boot.library.path" value="/usr/local/java/jdk1.8.0_202/jre/lib/amd64"/>
<property name="java.vm.version" value="25.202-b08"/>
<property name="java.vm.vendor" value="Oracle Corporation"/>
<property name="java.vendor.url" value="http://java.oracle.com/"/>
<property name="path.separator" value=":"/>
<property name="guice.disable.misplaced.annotation.check" value="true"/>
<property name="java.vm.name" value="Java HotSpot(TM) 64-Bit Server VM"/>
<property name="file.encoding.pkg" value="sun.io"/>
<property name="user.country" value="EC"/>
<property name="sun.java.launcher" value="SUN_STANDARD"/>
<property name="sun.os.patch.level" value="unknown"/>
<property name="java.vm.specification.name" value="Java Virtual Machine Specification"/>
<property name="user.dir" value="/home/developer2/NetBeansProjects/sources/appletFirma"/>
<property name="java.runtime.version" value="1.8.0_202-b08"/>
<property name="java.awt.graphicsenv" value="sun.awt.X11GraphicsEnvironment"/>
<property name="java.endorsed.dirs" value="/usr/local/java/jdk1.8.0_202/jre/lib/endorsed"/>
<property name="os.arch" value="amd64"/>
<property name="java.io.tmpdir" value="/tmp"/>
<property name="line.separator" value="
"/>
<property name="java.vm.specification.vendor" value="Oracle Corporation"/>
<property name="os.name" value="Linux"/>
<property name="maven.ext.class.path" value="/home/developer2/data/netbeans15/netbeans/java/maven-nblib/netbeans-eventspy.jar"/>
<property name="classworlds.conf" value="/home/developer2/data/IDDESARROLLO/apache-maven-3.1.1/bin/m2.conf"/>
<property name="sun.jnu.encoding" value="UTF-8"/>
<property name="java.library.path" value="/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib"/>
<property name="java.specification.name" value="Java Platform API Specification"/>
<property name="java.class.version" value="52.0"/>
<property name="sun.management.compiler" value="HotSpot 64-Bit Tiered Compilers"/>
<property name="os.version" value="5.15.0-58-generic"/>
<property name="user.home" value="/home/developer2"/>
<property name="user.timezone" value="America/Guayaquil"/>
<property name="java.awt.printerjob" value="sun.print.PSPrinterJob"/>
<property name="file.encoding" value="UTF-8"/>
<property name="java.specification.version" value="1.8"/>
<property name="user.name" value="developer2"/>
<property name="java.class.path" value="/home/developer2/data/IDDESARROLLO/apache-maven-3.1.1/boot/plexus-classworlds-2.5.1.jar"/>
<property name="org.slf4j.simpleLogger.defaultLogLevel" value="info"/>
<property name="java.vm.specification.version" value="1.8"/>
<property name="sun.arch.data.model" value="64"/>
<property name="java.home" value="/usr/local/java/jdk1.8.0_202/jre"/>
<property name="sun.java.command" value="org.codehaus.plexus.classworlds.launcher.Launcher -Dmaven.ext.class.path=/home/developer2/data/netbeans15/netbeans/java/maven-nblib/netbeans-eventspy.jar clean install"/>
<property name="java.specification.vendor" value="Oracle Corporation"/>
<property name="user.language" value="es"/>
<property name="awt.toolkit" value="sun.awt.X11.XToolkit"/>
<property name="java.vm.info" value="mixed mode"/>
<property name="java.version" value="1.8.0_202"/>
<property name="java.ext.dirs" value="/usr/local/java/jdk1.8.0_202/jre/lib/ext:/usr/java/packages/lib/ext"/>
<property name="securerandom.source" value="file:/dev/./urandom"/>
<property name="sun.boot.class.path" value="/usr/local/java/jdk1.8.0_202/jre/lib/resources.jar:/usr/local/java/jdk1.8.0_202/jre/lib/rt.jar:/usr/local/java/jdk1.8.0_202/jre/lib/sunrsasign.jar:/usr/local/java/jdk1.8.0_202/jre/lib/jsse.jar:/usr/local/java/jdk1.8.0_202/jre/lib/jce.jar:/usr/local/java/jdk1.8.0_202/jre/lib/charsets.jar:/usr/local/java/jdk1.8.0_202/jre/lib/jfr.jar:/usr/local/java/jdk1.8.0_202/jre/classes"/>
<property name="java.vendor" value="Oracle Corporation"/>
<property name="maven.home" value="/home/developer2/data/IDDESARROLLO/apache-maven-3.1.1"/>
<property name="file.separator" value="/"/>
<property name="java.vendor.url.bug" value="http://bugreport.sun.com/bugreport/"/>
<property name="sun.cpu.endian" value="little"/>
<property name="sun.io.unicode.encoding" value="UnicodeLittle"/>
<property name="sun.cpu.isalist" value=""/>
</properties>
<testcase classname="com.fp.firma.applet.AppTest" name="testApp" time="0.003"/>
</testsuite>

View File

@ -0,0 +1,4 @@
-------------------------------------------------------------------------------
Test set: com.fp.firma.applet.AppTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.022 sec

121
base/bpm/bpmlib/pom.xml Normal file
View File

@ -0,0 +1,121 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<parent>
<artifactId>bpm</artifactId>
<groupId>com.fp.base</groupId>
<version>2.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.fp.base.bpm</groupId>
<artifactId>bpmlib</artifactId>
<name>fp Platform - BPMLib </name>
<dependencies>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.1_spec</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fp.base.dto</groupId>
<artifactId>dto</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fp.base.dto</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fp.base.persistence</groupId>
<artifactId>pbpm</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fp.base.persistence</groupId>
<artifactId>pgeneral</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fp.base.persistence</groupId>
<artifactId>util</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fp.base.bpm</groupId>
<artifactId>simple</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.fp.base.core</groupId>
<artifactId>bpm</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<!-- dependencias de jbpm y drools -->
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-flow</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-flow-builder</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-bpmn2</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-persistence-jpa</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-human-task-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-runtime-manager</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jbpm</groupId>
<artifactId>jbpm-kie-services</artifactId>
<scope>provided</scope>
<exclusions>
<!-- to enable all examples run together on the same app server -->
<exclusion>
<groupId>org.jboss.netty</groupId>
<artifactId>netty</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>jdbc/JBPM</jndi-name>
<use-java-context>false</use-java-context>
<connection-url>jdbc:mysql://localhost:3306/jbpm</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password></password>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<prepared-statement-cache-size>80</prepared-statement-cache-size>
<idle-timeout-minutes>0</idle-timeout-minutes>
<metadata>
<type-mapping>MySql</type-mapping>
</metadata>
</local-tx-datasource>
<no-tx-datasource>
<jndi-name>jdbc/TASKS</jndi-name>
<use-java-context>false</use-java-context>
<connection-url>jdbc:mysql://localhost:3306/jbpm</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password></password>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<prepared-statement-cache-size>80</prepared-statement-cache-size>
<idle-timeout-minutes>0</idle-timeout-minutes>
<metadata>
<type-mapping>MySql</type-mapping>
</metadata>
</no-tx-datasource>
</datasources>

View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<!--local-tx-datasource>
<jndi-name>jdbc/JBPM</jndi-name>
<use-java-context>false</use-java-context>
<connection-url>jdbc:mysql://localhost:3306/jbpm</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password></password>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<prepared-statement-cache-size>80</prepared-statement-cache-size>
<valid-connection-checker-class-name> com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker </valid-connection-checker-class-name>
<idle-timeout-minutes>0</idle-timeout-minutes>
<metadata>
<type-mapping>MySql</type-mapping>
</metadata>
</local-tx-datasource-->
<xa-datasource>
<jndi-name>jdbc/JBPM</jndi-name>
<xa-datasource-property name="URL">jdbc:mysql://localhost:3306/jbpm?autoReconnect=true&amp;autoReconnectForPools=true</xa-datasource-property>
<xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
<user-name>root</user-name>
<password></password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
<valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
<min-pool-size>50</min-pool-size>
<max-pool-size>200</max-pool-size>
<idle-timeout-minutes>10</idle-timeout-minutes>
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</xa-datasource>
<no-tx-datasource>
<jndi-name>jdbc/TASKS</jndi-name>
<use-java-context>false</use-java-context>
<connection-url>jdbc:mysql://localhost:3306/jbpm?autoReconnect=true&amp;autoReconnectForPools=true</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password></password>
<min-pool-size>50</min-pool-size>
<max-pool-size>200</max-pool-size>
<prepared-statement-cache-size>80</prepared-statement-cache-size>
<idle-timeout-minutes>0</idle-timeout-minutes>
<metadata>
<type-mapping>MySql</type-mapping>
</metadata>
</no-tx-datasource>
</datasources>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<no-tx-datasource>
<jndi-name>jdbc/JBPM</jndi-name>
<use-java-context>false</use-java-context>
<connection-url>jdbc:oracle:thin:@192.168.2.201:1521:maia</connection-url>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<user-name>jbpm5</user-name>
<password>jbpm5</password>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<prepared-statement-cache-size>80</prepared-statement-cache-size>
<idle-timeout-minutes>0</idle-timeout-minutes>
<metadata>
<type-mapping>Oracle</type-mapping>
</metadata>
</no-tx-datasource>
<no-tx-datasource>
<jndi-name>jdbc/TASKS</jndi-name>
<use-java-context>false</use-java-context>
<connection-url>jdbc:oracle:thin:@192.168.2.201:1521:maia</connection-url>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<user-name>jbpm5</user-name>
<password>jbpm5</password>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<prepared-statement-cache-size>80</prepared-statement-cache-size>
<idle-timeout-minutes>0</idle-timeout-minutes>
<metadata>
<type-mapping>Oracle</type-mapping>
</metadata>
</no-tx-datasource>
</datasources>

View File

@ -0,0 +1,48 @@
/*
*
*/
package com.fp.bpmlib;
import java.util.Date;
// TODO: Auto-generated Javadoc
/**
* Class Common encargada de.
*
* @author gfiallos
*/
public final class Common {
/** El valor de instance. */
private static Common instance = null;
/**
* Obtiene la única instancia de Common.
*
* @return única instancia de Common
*/
public static Common getInstance() {
synchronized (Common.class) {
if (Common.instance == null) {
Common.instance = new Common();
}
return Common.instance;
}
}
/**
* Crea una nueva instancia de common.
*/
private Common() {
}
/**
* Obtiene el valor de current date.
*
* @return Valor de current date
* @throws Exception la exception
*/
public Date getCurrentDate() throws Exception {
return new Date();
}
}

View File

@ -0,0 +1,115 @@
/*
*
*/
package com.fp.bpmlib;
import org.apache.log4j.Logger;
// TODO: Auto-generated Javadoc
/**
* The listener interface for receiving customSystemEvent events. The class that is interested in processing a
* customSystemEvent event implements this interface, and the object created with that class is registered with a
* component using the component's <code>addCustomSystemEventListener<code> method. When
* the customSystemEvent event occurs, that object's appropriate
* method is invoked.
*
*/
public class CustomSystemEventListener implements org.kie.internal.SystemEventListener {
/** Constante LOG. */
private static final Logger LOG = Logger.getLogger(CustomSystemEventListener.class);
/**
* Debug.
*
* @param message the message
*/
@Override
public void debug(String message) {
CustomSystemEventListener.LOG.debug(message);
}
/**
* Debug.
*
* @param message the message
* @param object the object
*/
@Override
public void debug(String message, Object object) {
CustomSystemEventListener.LOG.debug(message + " " + object);
}
/**
* Exception.
*
* @param message the message
* @param e the e
*/
@Override
public void exception(String message, Throwable e) {
CustomSystemEventListener.LOG.error(message, e);
}
/**
* Exception.
*
* @param e the e
*/
@Override
public void exception(Throwable e) {
CustomSystemEventListener.LOG.error(e, e);
}
/**
* Info.
*
* @param message the message
*/
@Override
public void info(String message) {
CustomSystemEventListener.LOG.info(message);
}
/**
* Info.
*
* @param message the message
* @param object the object
*/
@Override
public void info(String message, Object object) {
CustomSystemEventListener.LOG.info(message + " " + object);
}
/**
* Warning.
*
* @param message the message
*/
@Override
public void warning(String message) {
CustomSystemEventListener.LOG.warn(message);
}
/**
* Warning.
*
* @param message the message
* @param object the object
*/
@Override
public void warning(String message, Object object) {
CustomSystemEventListener.LOG.warn(message + " " + object);
}
}

View File

@ -0,0 +1,137 @@
package com.fp.bpmlib;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.naming.InitialContext;
import org.jbpm.process.instance.event.listeners.TriggerRulesEventListener;
import org.jbpm.services.task.lifecycle.listeners.BAMTaskEventListener;
import org.jbpm.services.task.lifecycle.listeners.TaskLifeCycleEventListener;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.task.TaskService;
import org.kie.internal.task.api.EventService;
import com.fp.base.persistence.util.helper.MessageManager;
import com.fp.bpmlib.ejb.local.JbpmBeanLocal;
import com.fp.bpmlib.task.MaiaWorkItemHandler;
import com.fp.common.logger.APPLogger;
import com.fp.dto.Request;
import com.fp.dto.save.SaveRequest;
import com.fp.simple.flow.DataMap;
/**
* Class encargada del inicio de un flujo de trabajo.
*
* @author jvaca
* @version 2.1
*/
public class Flujo {
private KieSession kiesession;
private ProcessInstance processInstance = null;
private TaskService taskService;
/**
* Crea una instancia de flujo.
*/
public Flujo() throws Exception{
JbpmBeanLocal local = (JbpmBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/jbpmbean");
RuntimeManager manager = local.getRuntimeManager();
RuntimeEngine runtime = manager.getRuntimeEngine(null);
taskService = runtime.getTaskService();
kiesession = runtime.getKieSession();
kiesession.addEventListener(new TriggerRulesEventListener(kiesession));
kiesession.getWorkItemManager().registerWorkItemHandler("Human Task", new MaiaWorkItemHandler());
this.addListeners(runtime);
}
/**
* Crea una instancia de flujo y obtiene una instancia del proceso.
* @param processid Id de una instancia de proceso.
* @throws Exception
*/
public Flujo(Long processid) throws Exception {
this();
processInstance = kiesession.getProcessInstance(processid);
}
/**
* Adiciona listener, para el manejo del bam de tareas.
* @param engine
*/
@SuppressWarnings("unchecked")
private void addListeners(RuntimeEngine engine) {
EventService<TaskLifeCycleEventListener> eventService = (EventService<TaskLifeCycleEventListener>) engine.getTaskService();
boolean hasBamEventListener = false;
for (TaskLifeCycleEventListener listener : eventService.getTaskEventListeners()) {
if (listener instanceof BAMTaskEventListener) {
hasBamEventListener = true;
break;
}
}
if (!hasBamEventListener) {
BAMTaskEventListener bamTaskEventListener = new BAMTaskEventListener();
eventService.registerTaskEventListener(bamTaskEventListener);
}
}
/**
* Inicia la ejecucion de un flujo de trabajo.
* @param flujo Id del flujo se toma del archivo.jbpm
* @param parametros Parametros con los que inicia la ejeccion de un flujo.
* @throws Exception
*/
public Long iniciar(String idproceso, Request request) throws Exception {
APPLogger.getLogger().info("Prepara Flujo");
//Se crea un nuevo request para grabar en el bpm la minima informacion.
SaveRequest sr = new SaveRequest();
sr.setJsf(true);
request.copy(sr);
request.copyMapValuesWithOutSaveBean(sr);
sr.mbeans.clear();
sr.remove("MSAVE");
sr.remove("MQUERY");
sr.remove("lOrderPersistentBeans");
sr.setResponse(null);
Map<String, Object> m = new HashMap<String, Object>();
m.put(ProcessUtil.TASKS_METADATA, new LinkedHashMap<String, Object>());
Map<String, Object> data = new DataMap();
// Map<String, Object> data = new HashMap<>();
if ((sr.getSubject() == null) || (sr.getSubject().compareTo("") == 0)) {
sr.setSubject(MessageManager.getMessage(request));
}
data.put(ProcessUtil.REQUEST, sr);
m.put(ProcessUtil.DATA, data);
processInstance = kiesession.startProcess(idproceso, m);
APPLogger.getLogger().info("Flujo preparado");
return processInstance.getId();
}
/**
* Cierra la session de trabajo.
*/
public void close() {
// no cerrar la session, esta se cierra en el commit trabaja con JTA.
}
public KieSession getKiesession() {
return kiesession;
}
public ProcessInstance getProcessInstance() {
return processInstance;
}
}

View File

@ -0,0 +1,252 @@
/*
*
*/
package com.fp.bpmlib;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.jbpm.services.task.audit.impl.model.BAMTaskSummaryImpl;
import org.kie.api.task.model.Task;
import org.kie.api.task.model.TaskData;
import com.fp.base.persistence.util.helper.GeneralDescriptions;
import com.fp.bpmlib.db.DataHelper;
import com.fp.bpmlib.flow.Monitor;
import com.fp.dto.Request;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pgeneral.log.TgeneTransactionLog;
import com.fp.simple.dto.TaskInfo;
// TODO: Auto-generated Javadoc
/**
* Class ProcessUtil encargada de.
*
* @author gfiallos
*/
public final class ProcessUtil {
/** Constante ACTUAL_TASK. */
public static final String ACTUAL_TASK = "actualTask";
/** Constante DATA. */
public static final String DATA = "maia";
/** El valor de instance. */
private static ProcessUtil instance = null;
/** Constante PID. */
public static final String PID = "pid";
/** Constante REQUEST. */
public static final String REQUEST = "request";
/** Constante SNAPSHOT. */
public static final String SNAPSHOT = "snapshot";
/** Constante TASK_METADATA. */
public static final String TASK_METADATA = "taskMetaData";
/** Constante TASKS_METADATA. */
public static final String TASKS_METADATA = "tasksMetaData";
/**
* Obtiene el valor de done task meta data.
*
* @param pProcess the process
* @param pName the name
* @return Valor de done task meta data
* @throws Exception la exception
*/
@SuppressWarnings("unchecked")
public static Object getDoneTaskMetaData(Monitor monitor, String pName) throws Exception {
Object tasks = monitor.getVariable(ProcessUtil.TASKS_METADATA);
if (tasks != null) {
Map<String, Object> m = (Map<String, Object>) tasks;
Map<String, Object> record = new HashMap<String, Object>();
record.put(pName, ProcessUtil.manageHistory(monitor,(List<TaskInfo>) m.get(pName)));
return record;
}
return null;
}
/**
* Obtiene el valor de first done task meta data.
*
* @param pProcess the process
* @return Valor de first done task meta data
* @throws Exception la exception
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> getFirstDoneTaskMetaData(Monitor monitor) throws Exception {
Object tasks = monitor.getVariable(ProcessUtil.TASKS_METADATA);
if (tasks != null) {
Map<String, Object> m = (Map<String, Object>) tasks;
for (Entry<String, Object> entry : m.entrySet()) {
Map<String, Object> record = new HashMap<String, Object>();
record.put(entry.getKey(), ProcessUtil.getDoneTaskMetaData(monitor, entry.getKey()));
return record;
}
}
return null;
}
/**
* Obtiene la única instancia de ProcessUtil.
*
* @return única instancia de ProcessUtil
*/
public static ProcessUtil getInstance() {
synchronized (ProcessUtil.class) {
if (ProcessUtil.instance == null) {
ProcessUtil.instance = new ProcessUtil();
}
return ProcessUtil.instance;
}
}
/**
* Manage history.
*
* @param pHistory the history
* @return list
* @throws Exception la exception
*/
protected static List<TaskInfo> manageHistory(Monitor monitor,List<TaskInfo> pHistory) throws Exception {
if (pHistory == null) {
return null;
}
for (TaskInfo taskInfo : pHistory) {
Object tid = taskInfo.getTaskId();
if (tid == null) {
tid = taskInfo.getTaskId();
}
if (tid != null) {
ProcessUtil.manageTaskId(monitor, taskInfo, Long.valueOf("" + tid));
}
}
return pHistory;
}
/**
* Manage task id.
*
* @param pTask the task
* @param pTID the tID
* @throws Exception la exception
*/
private static void manageTaskId(Monitor monitor,TaskInfo pTask, Long pTID) throws Exception {
pTask.setTaskId(pTID);
Map<Object, Object> aditionalData = pTask.getAditionalData();
Task t = monitor.getTaskService().getTaskById(pTID);
BAMTaskSummaryImpl bam = monitor.getBAMTaskSummaryImpl(pTID);
pTask.setCreated(new Timestamp(t.getTaskData().getCreatedOn().getTime()) );
pTask.setStarted(new Timestamp(bam.getStartDate().getTime()) );
pTask.setCompleted(new Timestamp(bam.getEndDate().getTime()));
TaskData td = t.getTaskData();
aditionalData.put("status", td.getStatus().name());
aditionalData.put("userId", td.getActualOwner().getId());
aditionalData.put("name", GeneralDescriptions.getUsername(td.getActualOwner().getId()));
}
/**
* Crea una nueva instancia de process util.
*/
private ProcessUtil() {
}
/**
* Prepare record.
*
* @param pName the name
* @param pValue the value
* @param pRequest the request
* @param label the label
* @return map
* @throws Exception la exception
*/
public Map<String, Object> prepareRecord(String pName, Object pValue, Request pRequest, boolean label) throws Exception {
Map<String, Object> m = new HashMap<String, Object>();
if (label) {
m.put("NAME", GeneralDescriptions.getLabel(pName, pRequest.getLanguage(), pRequest.getChannelCode()));
} else {
m.put("NAME", pName);
}
m.put("VALUE", pValue);
m.put("CODE", pName);
return m;
}
/**
* Prepare record.
*
* @param pName the name
* @param pValue the value
* @param pRequest the request
* @return map
* @throws Exception la exception
*/
public Map<String, Object> prepareRecord(String pName, Object pValue, Request pRequest) throws Exception {
return this.prepareRecord(pName, pValue, pRequest, true);
}
/**
* Transaction data.
*
* @param pJournalId the journal id
* @param pRequest the request
* @param label the label
* @return list
* @throws Exception la exception
*/
public List<Map<String, Object>> transactionData(String pJournalId, Request pRequest, boolean label) throws Exception {
TgeneTransactionLog log = TgeneTransactionLog.find(PersistenceHelper.getEntityManager(), pJournalId);
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
SimpleDateFormat sdf = DataHelper.getInstance().getDateTimeFormat(pRequest.getCompany());
if(log!=null){
data.add(this.prepareRecord("creationdate", sdf.format(log.getRealdate()), pRequest, label));
data.add(this.prepareRecord("user", log.getUsercode(), pRequest, label));
data.add(this.prepareRecord("name", GeneralDescriptions.getOfficername(log.getUsercode()), pRequest, label));
data.add(this.prepareRecord("email", GeneralDescriptions.getEmailByUser(log.getUsercode()), pRequest, label));
data.add(this.prepareRecord("branch",
log.getBranchcode() + " " + GeneralDescriptions.getBranchdesc(log.getBranchcode(), pRequest.getCompany()), pRequest, label));
data.add(this.prepareRecord("office",
log.getOfficecode() + " " + GeneralDescriptions.getOfficedesc(log.getOfficecode(), log.getBranchcode(), pRequest.getCompany()),
pRequest, label));
data.add(this.prepareRecord("transaction", log.getTransactionmodule() + "-" + log.getTransactioncode() + "-" + log.getTransactionversion()
+ " " + GeneralDescriptions.getTransactiondesc(log.getTransactionmodule(), log.getTransactioncode(), log.getTransactionversion()),
pRequest, label));
if (log.getAditionaldata() != null) {
data.add(this.prepareRecord("message", log.getAditionaldata(), pRequest, label));
}
}
return data;
}
/**
* Transaction data.
*
* @param pJournalId the journal id
* @param pRequest the request
* @return list
* @throws Exception la exception
*/
public List<Map<String, Object>> transactionData(String pJournalId, Request pRequest) throws Exception {
return this.transactionData(pJournalId, pRequest, true);
}
}

View File

@ -0,0 +1,63 @@
/*
*
*/
package com.fp.bpmlib;
import com.fp.common.helper.Constant;
import com.fp.common.logger.APPLogger;
import com.fp.dto.save.SaveRequest;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pbpm.gene.TbpmProcessInstance;
/**
* Class RegisterFlow encargada de.
*
* @author jvaca
* @version 2.1
*/
public class RegisterFlow {
/** El valor de process. */
private Flujo flujo;
/** El valor de request. */
private SaveRequest request;
/**
* Crea una nueva instancia de register flow.
*
* @param pProcess the process
* @param pRequest the request
* @param pCompany the company
* @throws Exception la exception
*/
public RegisterFlow(Flujo flujo, SaveRequest pRequest) throws Exception {
this.flujo = flujo;
this.request = pRequest;
}
/**
* Register flow.
*
* @throws Exception la exception
*/
public void registerFlow() throws Exception {
APPLogger.getLogger().info("registro Instancia de Flujo");
TbpmProcessInstance pi = new TbpmProcessInstance(this.request.getJournalId(), this.flujo.getKiesession().getId(), FormatDates.getInstance()
.getDataBaseDate());
pi.setProcessid(this.flujo.getProcessInstance().getId());
pi.setFinalized(Constant.STR_N);
PersistenceHelper.persist(pi);
APPLogger.getLogger().info("Graba Instancia de Flujo " + pi.getProcessid());
}
}

View File

@ -0,0 +1,85 @@
/*
*
*/
package com.fp.bpmlib.db;
import com.fp.common.properties.PropertiesHandler;
// TODO: Auto-generated Javadoc
/**
* Class BPMProperties encargada de.
*
* @author gfiallos
*/
public final class BPMProperties extends PropertiesHandler {
/** Constante GUVNOR_URL. */
public static final String GUVNOR_URL = "guvnor.url";
/** Constante GUVNOR_CHANGE_SET. */
public static final String GUVNOR_CHANGE_SET = "guvnor.change.set";
/** Constante GUVNOR_REFRESH. */
public static final String GUVNOR_REFRESH = "guvnor.refresh";
/** Constante BPM_MEMORY. */
public static final String BPM_MEMORY = "bpm.memory";
/** Constante TASK_IP. */
public static final String TASK_IP = "task.ip";
/** Constante TASK_IP_SERVER. */
public static final String TASK_IP_SERVER = "task.ip.server";
/** Constante TASK_PORT. */
public static final String TASK_PORT = "task.port";
/** Constante FLOWS_PACKAGE. */
public static final String FLOWS_PACKAGE = "flows.package";
/** Constante FLOWS_SNAPSHOT. */
public static final String FLOWS_SNAPSHOT = "flows.snapshot";
/** Constante INBOX_ICON_PATH. */
public static final String INBOX_ICON_PATH = "inbox.icon.path";
/** Constante INBOX_ICON_EXTENSION. */
public static final String INBOX_ICON_EXTENSION = "inbox.icon.extension";
/** Constante GUVNOR_SECURITY_BASIC_AUTHENTICATION. */
public static final String GUVNOR_SECURITY_BASIC_AUTHENTICATION = "guvnor.security.basicAuthentication";
/** Constante GUVNOR_SECURITY_USERNAME. */
public static final String GUVNOR_SECURITY_USERNAME = "guvnor.security.username";
/** Constante GUVNOR_SECURITY_PASSWORD. */
public static final String GUVNOR_SECURITY_PASSWORD = "guvnor.security.password";
/** El valor de instance. */
private static BPMProperties instance = null;
/**
* Obtiene la Unica instancia de BPMProperties.
*
* @return Unica instancia de BPMProperties
* @throws Exception
*/
public static BPMProperties getInstance() throws Exception {
synchronized (BPMProperties.class) {
if (BPMProperties.instance == null) {
BPMProperties.instance = new BPMProperties();
}
return BPMProperties.instance;
}
}
/**
* Crea una nueva instancia de bPM properties.
*
* @throws Exception la exception
*/
private BPMProperties() throws Exception {
super("bpm");
}
}

View File

@ -0,0 +1,83 @@
/*
* Acceso a Datos
*/
package com.fp.bpmlib.db;
import java.text.SimpleDateFormat;
import com.fp.general.exception.GeneralException;
import com.fp.persistence.commondb.HqlStatement;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pbpm.gene.TbpmProcessInstance;
import com.fp.persistence.pgeneral.gene.TgeneParameters;
import com.fp.persistence.pgeneral.gene.TgeneParametersKey;
// TODO: Auto-generated Javadoc
/**
* Clase utilitaria para el manejo de Caché del proyecto BPMLIB.
*
* @author GF
* @version 2.1
*/
public final class DataHelper {
/** Almacena una instancia de DataHelper. */
private static DataHelper cache;
/** Constante HQL_PROCESS. */
private static final String HQL_PROCESS = "from TbpmProcessInstance tb " + " where tb.processid=:pid ";
/**
* Entrega una instancia de DataHelper.
*
* @return DataHelper
*/
public static DataHelper getInstance() {
synchronized (DataHelper.class) {
if (DataHelper.cache != null) {
return DataHelper.cache;
}
if (DataHelper.cache == null) {
DataHelper.cache = new DataHelper();
}
}
return DataHelper.cache;
}
/**
* Obtiene el valor de date time format.
*
* @param pCompany the company
* @return Valor de date time format
* @throws Exception la exception
*/
public SimpleDateFormat getDateTimeFormat(Integer pCompany) throws Exception {
TgeneParametersKey k = new TgeneParametersKey("FORMATDATE", pCompany);
TgeneParameters f = TgeneParameters.find(PersistenceHelper.getEntityManager(), k);
return new SimpleDateFormat(f.getTextvalue() + " HH:mm");
}
/**
* Obtiene el valor de tbpm process instance.
*
* @param pId the id
* @return Valor de tbpm process instance
* @throws Exception la exception
*/
public TbpmProcessInstance getTbpmProcessInstance(Long pId) throws Exception {
TbpmProcessInstance process = null;
HqlStatement hql = new HqlStatement(DataHelper.HQL_PROCESS);
hql.setLong("pid", pId);
process = hql.getObject(TbpmProcessInstance.class);
if (process == null) {
throw new GeneralException("BPM-0004", "LA INSTANCIA {0} NO ESTA DISPONIBLE O YA FUE FINALIZADA", pId);
}
return process;
}
}

View File

@ -0,0 +1,4 @@
/**
* Provee los utilitarios para el acceso a la Base de Datos.
*/
package com.fp.bpmlib.db;

View File

@ -0,0 +1,123 @@
package com.fp.bpmlib.ejb;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.manager.RuntimeEnvironment;
import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.manager.RuntimeManagerFactory;
import org.kie.internal.io.ResourceFactory;
import com.fp.bpmlib.ejb.local.JbpmBeanLocal;
import com.fp.bpmlib.task.util.MaiaUserGroupCallback;
import com.fp.common.logger.APPLogger;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.PersistenceManager;
import com.fp.persistence.pbpm.gene.TbpmRules;
/**
* Clase utilitaria, utilizada para creacion de base de conocimento y RuntimeManager
*
* @author Jvc
* @version 2.1
*/
@Startup
@Singleton(name = "jbpmbean")
public class JbpmBean implements JbpmBeanLocal {
@PersistenceUnit(unitName = "org.jbpm.domain")
private EntityManagerFactory emf;
private RuntimeManager runtimemanager;
@PostConstruct
private final void crearSingletonManager() {
try {
if (emf == null) {
emf = PersistenceManager.getInstance().getEntityManagerFactoryAuxiliar("org.jbpm.domain");
}
} catch (Exception e) {
APPLogger.getLogger().error(e);
}
}
@PreDestroy
private void close() {
try {
runtimemanager.close();
} catch (Exception e) {
// no hacer nada.
}
}
/**
* Crea un RuntimeManagerFactory.
*
* @param emf Entiy manager factury utilizado en el manejo de flujos de trabajo.
* @return RuntimeEnvironment
* @throws Exception
*/
private RuntimeEnvironment crearRuntimeManager(EntityManagerFactory emf) throws Exception {
MaiaUserGroupCallback usergroupCallback = new MaiaUserGroupCallback();
RuntimeEnvironmentBuilder builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf);
builder.userGroupCallback(usergroupCallback);
this.adicionarFlujos(builder);
RuntimeEnvironment environment = builder.get();
environment.getEnvironment().set(EnvironmentName.USE_PESSIMISTIC_LOCKING, true);
return environment;
}
@Override
public RuntimeManager getRuntimeManager() throws Exception {
if (runtimemanager == null) {
RuntimeEnvironment environment = this.crearRuntimeManager(emf);
runtimemanager = RuntimeManagerFactory.Factory.get().newPerRequestRuntimeManager(environment);
}
return runtimemanager;
}
/**
* Adiciona definiciones de flujos a un map con los cuales se crea la base de conocimiento.
*
* @param resources Map que contiene definicion de flujos y reglas con los cuales se crea la base de conocimiento.
* @throws Exception
*/
private void adicionarFlujos(RuntimeEnvironmentBuilder builder) throws Exception {
List<TbpmRules> ldata = TbpmRules.findRules(PersistenceHelper.getEntityManager());
// adiciona subprocesos.
for (TbpmRules obj : ldata) {
if (obj.getFiletype().equals("F")) {
builder.addAsset(ResourceFactory.newClassPathResource(obj.getPath(), "UTF-8"), ResourceType.BPMN2);
} else {
builder.addAsset(ResourceFactory.newClassPathResource(obj.getPath(), "UTF-8"), ResourceType.DTABLE);
}
}
}
/**
* Entrega el entitymanagerfactory asociado al manejo de jbpm.
*
* @return
*/
@Override
public EntityManagerFactory getEmf() {
return emf;
}
}

View File

@ -0,0 +1,94 @@
package com.fp.bpmlib.ejb;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.fp.bpmlib.ejb.local.LogMailBeanLocal;
import com.fp.common.logger.APPLogger;
import com.fp.persistence.commondb.data.SessionData;
import com.fp.persistence.commondb.data.ThreadFacade;
import com.fp.persistence.pbpm.gene.TbpmLogMail;
/**
* Clase utilitaria, utilizada para creacion de base de conocimento y RuntimeManager
*
* @author Jvc
* @version 2.1
*/
@Stateless(name="logMailBean")
public class LogMailBean implements LogMailBeanLocal {
// @PersistenceUnit(unitName = "local1")
private EntityManagerFactory emf;
@PostConstruct
private final void crearManager() {
try {
if (emf == null) {
Map<String, Object> configOverrides = new HashMap<String, Object>();
configOverrides.put("hibernate.ejb.cfgfile", "hibernateFlipMapping.cfg.xml");
emf = Persistence.createEntityManagerFactory("local1" , configOverrides);
}
SessionData sessionData = new SessionData();
sessionData.setCompany(1);
sessionData.setIsEjb(Boolean.FALSE);
ThreadFacade.setSaveRequest(sessionData);
} catch (Exception e) {
APPLogger.getLogger().error(e);
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void logMail(Map<String, Object> mapMail) throws Exception {
System.out.println("Ingresa al log del mail...................................");
EntityManager em=emf.createEntityManager();
TbpmLogMail logMail= new TbpmLogMail();
//logMail.setPk(getCodigo("CLOGMAIL"));
if(mapMail.get("subject")!=null){
logMail.setAsunto(mapMail.get("subject").toString());
}
if(mapMail.get("cont")!=null){
logMail.setContenido(mapMail.get("cont").toString());
}
if(mapMail.get("to")!=null){
logMail.setCorreo(mapMail.get("to").toString());
}
if(mapMail.get("error")!=null){
logMail.setDescripcionerror(mapMail.get("error").toString());
}
if(mapMail.get("estado")!=null){
logMail.setEstado(mapMail.get("estado").toString());
}
logMail.setFecharegistro(new Timestamp(new Date().getTime()));
if(em==null){
crearManager();
em=emf.createEntityManager();
}
em.clear();
em.persist(logMail);
em.flush();
em.close();
}
/**
* Entrega el entitymanagerfactory
*
* @return
*/
@Override
public EntityManagerFactory getEmf() {
return emf;
}
}

View File

@ -0,0 +1,15 @@
package com.fp.bpmlib.ejb.local;
import javax.ejb.Local;
import javax.persistence.EntityManagerFactory;
import org.kie.api.runtime.manager.RuntimeManager;
@Local
public interface JbpmBeanLocal {
public RuntimeManager getRuntimeManager() throws Exception;
public EntityManagerFactory getEmf();
}

View File

@ -0,0 +1,14 @@
package com.fp.bpmlib.ejb.local;
import java.util.Map;
import javax.ejb.Local;
import javax.persistence.EntityManagerFactory;
@Local
public interface LogMailBeanLocal {
public EntityManagerFactory getEmf();
public void logMail(Map<String, Object> mapMail) throws Exception;
}

View File

@ -0,0 +1,323 @@
package com.fp.bpmlib.flow;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fp.dto.Request;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pgeneral.gene.TgeneParameters;
import com.fp.persistence.pgeneral.gene.TgeneParametersKey;
import com.fp.simple.action.TaskAction;
import com.fp.simple.dto.Kind;
import com.fp.simple.dto.TaskInfo;
import com.fp.simple.flow.FlowClass;
import com.fp.simple.maia.MailRecipient;
import com.fp.simple.maia.MailRecipientGroup;
// TODO: Auto-generated Javadoc
/**
* Class FlowUtil encargada de.
*
* @author gfiallos
*/
public final class FlowUtil {
/**
* Crea una nueva instancia de flow util.
*/
private FlowUtil() {
}
/**
* Crea la instancia de task info.
*
* @param pModule the module
* @param pTransaction the transaction
* @param pVersion the version
* @param pMinutes the minutes
* @param pKind the kind
* @return task info
* @throws Exception la exception
*/
private static TaskInfo create(String pModule, Integer pTransaction, Integer pVersion, long pMinutes, String pKind) throws Exception {
TaskInfo ti = new TaskInfo();
ti.setModule(pModule);
ti.setTransaction(pTransaction);
ti.setVersion(pVersion);
ti.setExpectedTime(pMinutes * 60000);
ti.setKind(Kind.OK_NO);
if (pKind.equals("OK")) {
ti.setKind(Kind.OK);
}
if (pKind.equals("OK_NO_REVIEW")) {
ti.setKind(Kind.OK_NO_REVIEW);
}
return ti;
}
/**
* Crea la instancia de task info.
*
* @param pModule the module
* @param pTransaction the transaction
* @param pVersion the version
* @param pMinutes the minutes
* @param pRule the rule
* @param pKind the kind
* @return task info
* @throws Exception la exception
*/
public static TaskInfo createTaskInfo(String pModule, Integer pTransaction, Integer pVersion, long pMinutes, String pRule, String pKind)
throws Exception {
TaskInfo ti = FlowUtil.create(pModule, pTransaction, pVersion, pMinutes, pKind);
ti.setRuleCode(pRule);
return ti;
}
/**
* Crea la instancia de task info.
*
* @param pModule the module
* @param pTransaction the transaction
* @param pVersion the version
* @param pMinutes the minutes
* @param pKind the kind
* @return task info
* @throws Exception la exception
*/
public static TaskInfo createTaskInfo(String pModule, Integer pTransaction, Integer pVersion, long pMinutes,
String taskName, Integer pMessageCode, String pKind) throws Exception {
TaskInfo ti = FlowUtil.create(pModule, pTransaction, pVersion, pMinutes, pKind);
ti.setMessageCode(pMessageCode);
ti.setTname(taskName);
return ti;
}
/**
* Crea la instancia de task info.
*
* @param pModule the module
* @param pTransaction the transaction
* @param pVersion the version
* @param pMinutes the minutes
* @param pClassName Paquete clase encargado de obtener el responsable de ejecutar una tarea.
* @param pKind the kind
* @return task info
* @throws Exception la exception
*/
public static TaskInfo createTaskInfoByClassName(String pModule, Integer pTransaction, Integer pVersion, long pMinutes, String pClassName,
String taskName, Integer pMessageCode, String pKind) throws Exception {
TaskInfo ti = FlowUtil.create(pModule, pTransaction, pVersion, pMinutes, pKind);
ti.setClassCode(pClassName);
ti.setMessageCode(pMessageCode);
ti.setTname(taskName);
return ti;
}
/**
* Eval rule.
*
* @param pName the name
* @param pParam the param
* @throws Exception la exception
*/
public static void evalRule(String pName, Object pParam) throws Exception {
if (pName == null) {
return;
}
Class<?> c = Class.forName("com.fp.bpmlib.GuvnorClient");
Object obj = c.getConstructor(String.class).newInstance(pName);
c.getMethod("eval", Object.class).invoke(obj, pParam);
}
/**
* Eval rule.
*
* @param pName the name
* @param pContext the context
* @param pVar the var
* @throws Exception la exception
*/
public static void evalRule(String pName, Object pContext, String pVar) throws Exception {
if (pName == null) {
return;
}
Object val = FlowUtil.getVariable(pContext, pVar);
FlowUtil.evalRule(pName, val);
FlowUtil.setVariable(pContext, pVar, val);
}
/**
* Eval rule.
*
* @param pName the name
* @param pParam the param
* @throws Exception la exception
*/
public static void executeClass(String pClassName, Object pParam) throws Exception {
if (pClassName == null) {
return;
}
TaskAction taction = (TaskAction) Class.forName(pClassName).newInstance();
taction.assignOwner(pParam);
}
/**
* Obtiene el valor de variable.
*
* @param pContext the context
* @param pVar the var
* @return Valor de variable
* @throws Exception la exception
*/
public static Object getVariable(Object pContext, String pVar) throws Exception {
return pContext.getClass().getMethod("getVariable", String.class).invoke(pContext, pVar);
}
/**
* Fija el valor de variable.
*
* @param pContext the context
* @param pVar the var
* @param pVal the val
* @throws Exception la exception
*/
public static void setVariable(Object pContext, String pVar, Object pVal) throws Exception {
pContext.getClass().getMethod("setVariable", String.class, Object.class).invoke(pContext, pVar, pVal);
}
/**
* End flow.
*
* @param pContext the context
* @throws Exception la exception
*/
public static void endFlow(Object pContext) throws Exception {
Class<?> c = Class.forName("com.fp.bpmlib.query.monitor.FlowEnd");
FlowClass o = (FlowClass) c.getConstructor(Object.class).newInstance(pContext);
o.process();
}
/**
* Metodo que se encarga de enviar mails a un grupo de usuarios bpm definidos en TbpmGroupsUsers.
*
* @param pClassName Paquete clase, que se encarga de obtener la lista de email asociados a un grupo.
* @param pParam Request con los parametros de un flujo.
* @param pSubjectTemplate Codigo de plantilla para generar el asusnto del mail.
* @param pContentTemplate Codigo de plantilla para generar el contenido del maial.
* @param pGroupCode Codigo de grupo del bpm.
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static void mailGroup(String pClassName, Object pParam, TaskInfo taskinfo, Integer pSubjectTemplate, Integer pContentTemplate,
String pGroupCode) throws Exception {
RuleUtil.setSubjectTemplate(pSubjectTemplate);
RuleUtil.setContentTemplate(pContentTemplate);
List<String> lemail = new ArrayList<String>();
if (pClassName != null) {
MailRecipientGroup mail = (MailRecipientGroup) Class.forName(pClassName).newInstance();
Map<String, Object> mresp = mail.getEmailAddress(pParam, pGroupCode);
lemail = (List<String>) mresp.get("lemail");
}
for (String email : lemail) {
RuleUtil.toField(email);
}
if (!lemail.isEmpty()) {
HashMap<String, Object> m = (HashMap<String, Object>) pParam;
((Request) m.get("request")).put("cusuariobpm", taskinfo.getUserId());
RuleUtil.sendMail((Request) m.get("request"));
}
}
/**
* Metodo que se encarga del envio de emails a destinatarios enteragdos por la clase que llega como parametro.
*
* @param pClassName Paquete clase, que se encarga de obtener la lista de email a los cuales se envia
* notificaciones.
* @param pParam Request con los parametros de un flujo.
* @param pSubjectTemplate Codigo de plantilla para generar el asusnto del mail.
* @param pContentTemplate Codigo de plantilla para generar el contenido del maial.
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static void mail(String pClassName, Object pParam, TaskInfo taskinfo, Integer pSubjectTemplate, Integer pContentTemplate) throws Exception {
RuleUtil.setSubjectTemplate(pSubjectTemplate);
RuleUtil.setContentTemplate(pContentTemplate);
List<String> lemail = new ArrayList<String>();
if (pClassName != null) {
MailRecipient mail = (MailRecipient) Class.forName(pClassName).newInstance();
Map<String, Object> mresp = mail.getEmailAddress(pParam);
lemail = (List<String>) mresp.get("lemail");
}
for (String email : lemail) {
RuleUtil.toAddress(email);
}
if (!lemail.isEmpty()) {
HashMap<String, Object> m = (HashMap<String, Object>) pParam;
((Request) m.get("request")).put("cusuariobpm", taskinfo.getUserId());
if(taskinfo!=null && taskinfo.getAditionalData()!=null && taskinfo.getAditionalData().get("datosmail")!=null && !taskinfo.getAditionalData().get("datosmail").equals("")){
((Request) m.get("request")).putAll((Map)taskinfo.getAditionalData().get("datosmail"));
}
RuleUtil.sendMail((Request) m.get("request"));
}else{
RuleUtil.setSubjectTemplate(63);
TgeneParameters addres=TgeneParameters.find(PersistenceHelper.getEntityManager(), new TgeneParametersKey("MAIL.CENTRAL", 1));
RuleUtil.toAddress(addres.getTextvalue());
HashMap<String, Object> m = (HashMap<String, Object>) pParam;
((Request) m.get("request")).put("cusuariobpm", taskinfo.getUserId());
if(taskinfo!=null && taskinfo.getAditionalData()!=null && taskinfo.getAditionalData().get("datosmail")!=null && !taskinfo.getAditionalData().get("datosmail").equals("")){
((Request) m.get("request")).putAll((Map)taskinfo.getAditionalData().get("datosmail"));
}
RuleUtil.sendMail((Request) m.get("request"));
}
}
/**
* Metodo que se encarga del envio de emails a destinatarios enteragdos por la clase que llega como parametro.
*
* @param pClassName Paquete clase, que se encarga de obtener la lista de email a los cuales se envia
* notificaciones.
* @param pParam Request con los parametros de un flujo.
* @param pSubjectTemplate Codigo de plantilla para generar el asusnto del mail.
* @param pContentTemplate Codigo de plantilla para generar el contenido del maial.
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static void mailDocumentoAdjunto(String pClassName, Object pParam, TaskInfo taskinfo, Integer pSubjectTemplate, Integer pContentTemplate) throws Exception {
RuleUtil.setSubjectTemplate(pSubjectTemplate);
RuleUtil.setContentTemplate(pContentTemplate);
List<String> lemail = new ArrayList<String>();
if (pClassName != null) {
MailRecipient mail = (MailRecipient) Class.forName(pClassName).newInstance();
Map<String, Object> mresp = mail.getEmailAddress(pParam);
lemail = (List<String>) mresp.get("lemail");
}
for (String email : lemail) {
RuleUtil.toAddress(email);
}
if (!lemail.isEmpty()) {
HashMap<String, Object> m = (HashMap<String, Object>) pParam;
((Request) m.get("request")).put("cusuariobpm", taskinfo.getUserId());
if(taskinfo!=null && taskinfo.getAditionalData()!=null && taskinfo.getAditionalData().get("datosmail")!=null){
((Request) m.get("request")).putAll((Map)taskinfo.getAditionalData().get("datosmail"));
}
RuleUtil.sendMail((Request) m.get("request"));
}else{
RuleUtil.setSubjectTemplate(63);
TgeneParameters addres=TgeneParameters.find(PersistenceHelper.getEntityManager(), new TgeneParametersKey("MAIL.CENTRAL", 1));
RuleUtil.toAddress(addres.getTextvalue());
HashMap<String, Object> m = (HashMap<String, Object>) pParam;
((Request) m.get("request")).put("cusuariobpm", taskinfo.getUserId());
if(taskinfo!=null && taskinfo.getAditionalData()!=null && taskinfo.getAditionalData().get("datosmail")!=null){
((Request) m.get("request")).putAll((Map)taskinfo.getAditionalData().get("datosmail"));
}
RuleUtil.sendMail((Request) m.get("request"));
}
}
}

View File

@ -0,0 +1,263 @@
package com.fp.bpmlib.flow;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import org.drools.core.common.InternalKnowledgeRuntime;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.StatefulKnowledgeSessionImpl;
import org.jbpm.ruleflow.instance.RuleFlowProcessInstance;
import org.jbpm.services.task.audit.impl.model.AuditTaskImpl;
import org.jbpm.services.task.audit.impl.model.BAMTaskSummaryImpl;
import org.jbpm.workflow.instance.node.HumanTaskNodeInstance;
import org.jbpm.workflow.instance.node.SubProcessNodeInstance;
import org.kie.api.definition.process.Node;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.process.NodeInstance;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.task.TaskService;
import org.kie.api.task.model.Task;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
import com.fp.bpmlib.ProcessUtil;
import com.fp.bpmlib.ejb.local.JbpmBeanLocal;
import com.fp.bpmlib.task.client.HumanTaskClient;
import com.fp.simple.dto.TaskInfo;
import com.fp.simple.dto.metadata.ProcessInstanceMeta;
public class Monitor {
private KieSession kiesession;
private ProcessInstance processInstance = null;
private TaskService taskService;
private RuntimeManager runtimeManager;
private RuntimeEngine runtimeEngine;
private EntityManagerFactory emf;
/**
* Crea una instancia de flujo.
*/
public Monitor(Long processid) throws Exception {
JbpmBeanLocal local = (JbpmBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/jbpmbean");
runtimeManager = local.getRuntimeManager();
emf = local.getEmf();
runtimeEngine = runtimeManager.getRuntimeEngine(ProcessInstanceIdContext.get(processid));
taskService = runtimeEngine.getTaskService();
kiesession = runtimeEngine.getKieSession();
processInstance = kiesession.getProcessInstance(processid);
}
/**
* Cierra la session de trabajo.
*/
public void close() {
// no cerrar la session, esta se cierra en el commit trabaja con JTA.
}
public KieSession getKiesession() {
return kiesession;
}
public TaskService getTaskService() {
return taskService;
}
public ProcessInstance getProcessInstance() {
return processInstance;
}
/**
* Obtiene el valor de variable.
*
* @param pName Nombre de la varibale a buscar en una instancia de proceso.
* @return Valor de variable
* @throws Exception la exception
*/
public Object getVariable(String pName) throws Exception {
RuleFlowProcessInstance rfpi = (RuleFlowProcessInstance) this.processInstance;
return rfpi.getVariable(pName);
}
/**
* Obtiene el valor de status.
*
* @param pVariables the variables
* @return Valor de status
* @throws Exception la exception
*/
@SuppressWarnings("unchecked")
public List<ProcessInstanceMeta> getStatus() throws Exception {
List<ProcessInstanceMeta> data = new ArrayList<ProcessInstanceMeta>();
if (this.processInstance == null) {
return data;
}
RuleFlowProcessInstance rfpi = (RuleFlowProcessInstance) this.processInstance;
InternalKnowledgeRuntime internal = rfpi.getKnowledgeRuntime();
if (internal == null) {
internal = new StatefulKnowledgeSessionImpl(1, (InternalKnowledgeBase) this.kiesession.getKieBase());
rfpi.setKnowledgeRuntime(internal);
}
Collection<NodeInstance> nl = rfpi.getNodeInstances();
for (NodeInstance ni : nl) {
ProcessInstanceMeta pim = new ProcessInstanceMeta(this.processInstance.getId());
data.add(pim);
Map<String, Object> m = ni.getNode().getMetaData();
pim.setH(Integer.valueOf("" + m.get("height")));
pim.setW(Integer.valueOf("" + m.get("width")));
pim.setX(Integer.valueOf("" + m.get("x")));
pim.setY(Integer.valueOf("" + m.get("y")));
pim.setName(processInstance.getProcessName());
pim.setVersion(processInstance.getProcess().getVersion());
pim.setActivity(ni.getNodeName());
pim.setPmetaid(ni.getNodeId());
Map<String, Object> var = pim.getVariables();
Object tasks = this.getVariable(ProcessUtil.TASKS_METADATA);
boolean req = true;
if (tasks != null) {
var.put(ProcessUtil.TASKS_METADATA, this.manageTasksMetaData((Map<String, Object>) tasks));
req = false;
}
if (req) {
tasks = this.getVariable(ProcessUtil.ACTUAL_TASK);
if (tasks != null) {
var.put(ProcessUtil.ACTUAL_TASK, tasks);
}
}
this.manageNode(pim, ni);
}
return data;
}
/**
* Manage node.
*
* @param pim the pim
* @param ni the ni
* @param pVariables the variables
* @throws Exception la exception
*/
private void manageNode(ProcessInstanceMeta pim, NodeInstance ni) throws Exception {
if (ni instanceof HumanTaskNodeInstance) {
HumanTaskNodeInstance sub = (HumanTaskNodeInstance) ni;
pim.setWorkItem(sub.getWorkItemId());
Task t = this.taskService.getTaskByWorkItemId(pim.getWorkItem());
// getDocumentContentId es el contenido de entrada de la tarea.
Map<String, Object> input = HumanTaskClient.getContenido(taskService.getContentById(t.getTaskData().getDocumentContentId()));
TaskInfo info = (TaskInfo) input.get("taskMetaData");
info.getAditionalData().put("workItem", sub.getWorkItemId());
pim.addAddtionalInfo("taskMetaData", info);
return;
}
if (ni instanceof SubProcessNodeInstance) {
SubProcessNodeInstance sub = (SubProcessNodeInstance) ni;
Monitor subflujo = new Monitor(sub.getProcessInstanceId());
for (ProcessInstanceMeta pi : subflujo.getStatus()) {
pim.addSubProcess(pi);
}
return;
}
}
/**
* Manage tasks meta data.
*
* @param pTasksMetaData the tasks meta data
* @return map
* @throws Exception la exception
*/
private Map<String, Object> manageTasksMetaData(Map<String, Object> pTasksMetaData) throws Exception {
Map<String, Object> data = new HashMap<String, Object>();
RuleFlowProcessInstance instance = (RuleFlowProcessInstance) processInstance;
for (Entry<String, Object> element : pTasksMetaData.entrySet()) {
Map<String, Object> record = new HashMap<String, Object>();
Node[] ns = instance.getRuleFlowProcess().getNodes();
for (Node n : ns) {
if (n.getName().compareTo(element.getKey()) == 0) {
Map<String, Object> m = n.getMetaData();
record.put("h", Integer.valueOf("" + m.get("height")));
record.put("w", Integer.valueOf("" + m.get("width")));
record.put("x", Integer.valueOf("" + m.get("x")));
record.put("y", Integer.valueOf("" + m.get("y")));
record.put("name", n.getName());
break;
}
}
// record.put(ProcessUtil.TASK_METADATA, element.getValue());
data.put(element.getKey(), record);
}
return data;
}
/**
* JPQL TAREA_SUMMARY
*/
private static final String TAREA_SUMMARY = "select t from BAMTaskSummaryImpl t where t.taskId = :idtarea";
/**
* Obtiene el valor de unfinished tasks por Grupo.
*
* @param pGroupId the user id
* @param pCri the cri
* @return Valor de unfinished tasks
* @throws Exception la exception
*/
public BAMTaskSummaryImpl getBAMTaskSummaryImpl(long idtarea) throws Exception {
EntityManager em = null;
BAMTaskSummaryImpl dato = null;
try {
em = emf.createEntityManager();
Query qry = em.createQuery(Monitor.TAREA_SUMMARY);
qry.setParameter("idtarea", idtarea);
dato = (BAMTaskSummaryImpl) qry.getSingleResult();
} catch (NoResultException e) {
// retorna el objeto en null.
} finally {
if (em.isOpen()) {
em.close();
}
}
return dato;
}
/**
* JPQL TAREA_SUMMARY
*/
private static final String TAREA_AUDIT_IMP = "select t from AuditTaskImpl t where t.taskId = :idtarea";
public AuditTaskImpl getAuditTaskImpl(long idtarea) throws Exception {
EntityManager em = null;
AuditTaskImpl dato = null;
try {
em = emf.createEntityManager();
Query qry = em.createQuery(Monitor.TAREA_AUDIT_IMP);
qry.setParameter("idtarea", idtarea);
dato = (AuditTaskImpl) qry.getSingleResult();
} catch (NoResultException e) {
// retorna el objeto en null.
} finally {
if (em.isOpen()) {
em.close();
}
}
return dato;
}
}

View File

@ -0,0 +1,284 @@
package com.fp.bpmlib.flow;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fp.dto.Request;
import com.fp.dto.save.SaveRequest;
import com.fp.simple.flow.Asign;
// TODO: Auto-generated Javadoc
/**
* Class RuleUtil encargada del manejo de las operaciones de una Regla.
*
* @author gfiallos
*/
public final class RuleUtil {
/**
* Crea una nueva instancia de rule util.
*/
private RuleUtil() {
}
/** El valor de message. */
private static ThreadLocal<Map<String, Object>> message = new ThreadLocal<Map<String, Object>>();
/**
* Asign.
*
* @param pMaia the maia
* @param pClass the class
* @throws Exception la exception
*/
public static void asign(Map<String, Object> pMaia, String pClass) throws Exception {
Asign asign = (Asign) Class.forName(pClass).newInstance();
asign.setRequest(RuleUtil.getRequest(pMaia));
RuleUtil.setAction(pMaia, "A");
if (!asign.isGroup()) {
RuleUtil.setUser(pMaia, asign.getId());
} else {
RuleUtil.setGroup(pMaia, asign.getId());
}
}
/**
* Asign officer.
*
* @param pMaia the maia
*/
public static void asignOfficer(Map<String, Object> pMaia) {
String officer = RuleUtil.getRequest(pMaia).getString("officer");
RuleUtil.setUser(pMaia, officer);
RuleUtil.setAction(pMaia, "A");
}
/**
* Obtiene el valor de amount.
*
* @param pMaia the maia
* @return Valor de amount
*/
public static BigDecimal getAmount(Map<String, Object> pMaia) {
return RuleUtil.getRequest(pMaia).getBigDecimal("amount");
}
/**
* Obtiene el valor de financial amount.
*
* @param pMaia the maia
* @return Valor de financial amount
*/
public static BigDecimal getFinancialAmount(Map<String, Object> pMaia) {
return RuleUtil.getRequest(pMaia).getBigDecimal("financialamount");
}
/**
* Obtiene el valor de rate.
*
* @param pMaia the maia
* @return Valor de rate
*/
public static BigDecimal getRate(Map<String, Object> pMaia) {
return RuleUtil.getRequest(pMaia).getBigDecimal("rate");
}
/**
* Obtiene el valor de request.
*
* @param pMaia the maia
* @return Valor de request
*/
public static Request getRequest(Map<String, Object> pMaia) {
return (Request) pMaia.get("request");
}
/**
* Obtiene el valor de save request.
*
* @param pMaia the maia
* @return Valor de save request
*/
public static SaveRequest getSaveRequest(Map<String, Object> pMaia) {
return (SaveRequest) RuleUtil.getRequest(pMaia);
}
/**
* Obtiene el valor de term.
*
* @param pMaia the maia
* @return Valor de term
*/
public static Integer getTerm(Map<String, Object> pMaia) {
return RuleUtil.getRequest(pMaia).getInteger("term");
}
/**
* Fija el valor de action.
*
* @param pMaia the maia
* @param pAction the action
*/
public static void setAction(Map<String, Object> pMaia, String pAction) {
pMaia.put("action", pAction);
}
/**
* Fija el valor de action intermediate.
*
* @param pMaia the maia
* @param pAction the action
*/
public static void setActionIntermediate(Map<String, Object> pMaia, String pAction) {
pMaia.put("action", pAction);
pMaia.put("internalCode", "Y");
}
/**
* Fija el valor de group.
*
* @param pMaia the maia
* @param pGroup the group
*/
public static void setGroup(Map<String, Object> pMaia, String pGroup) {
pMaia.put("groupId", pGroup);
RuleUtil.toGroup(pGroup);
}
/**
* Fija el valor de user.
*
* @param pMaia the maia
* @param pUser the user
*/
public static void setUser(Map<String, Object> pMaia, String pUser) {
pMaia.put("userId", pUser);
}
/**
* Obtiene el valor de message.
*
* @return Valor de message
*/
private static Map<String, Object> getMessage() {
Map<String, Object> msg = null;
synchronized (RuleUtil.message) {
msg = RuleUtil.message.get();
if (msg == null) {
msg = new HashMap<String, Object>();
RuleUtil.message.set(msg);
}
}
return msg;
}
/**
* To user.
*
* @param pUser the user
*/
public static void toUser(String pUser) {
Map<String, Object> msg = RuleUtil.getMessage();
@SuppressWarnings("unchecked")
List<String> user = (List<String>) msg.get("user");
if (user == null) {
user = new ArrayList<String>();
msg.put("user", user);
}
user.add(pUser);
}
/**
* To group.
*
* @param pGroup the group
*/
public static void toGroup(String pGroup) {
Map<String, Object> msg = RuleUtil.getMessage();
@SuppressWarnings("unchecked")
List<String> group = (List<String>) msg.get("group");
if (group == null) {
group = new ArrayList<String>();
msg.put("group", group);
}
group.add(pGroup);
}
/**
* To field.
*
* @param pField the field
*/
public static void toField(String pField) {
Map<String, Object> msg = RuleUtil.getMessage();
@SuppressWarnings("unchecked")
List<String> field = (List<String>) msg.get("field");
if (field == null) {
field = new ArrayList<String>();
msg.put("field", field);
}
field.add(pField);
}
/**
* To address.
*
* @param pField the field
*/
public static void toAddress(String pAddress) {
Map<String, Object> msg = RuleUtil.getMessage();
@SuppressWarnings("unchecked")
List<String> laddress = (List<String>) msg.get("address");
if (laddress == null) {
laddress = new ArrayList<String>();
msg.put("address", laddress);
}
if (!laddress.contains(pAddress)) {
laddress.add(pAddress);
}
}
/**
* Fija el valor de subject template.
*
* @param pTemplate es el valor nuevo de subject template
*/
public static void setSubjectTemplate(Integer pTemplate) {
Map<String, Object> msg = RuleUtil.getMessage();
msg.put("subject", pTemplate);
}
/**
* Fija el valor de content template.
*
* @param pTemplate es el valor nuevo de content template
*/
public static void setContentTemplate(Integer pTemplate) {
Map<String, Object> msg = RuleUtil.getMessage();
msg.put("content", pTemplate);
}
/**
* Send mail.
*
* @param pRequest the request
* @throws Exception la exception
*/
public static void sendMail(Request pRequest) throws Exception {
Class<?> c = Class.forName("com.fp.bpmlib.mail.MailCommand");
Map<String, Object> msg = RuleUtil.getMessage();
msg.put("request", pRequest);
Constructor<?> con = c.getConstructor(Map.class);
Object obj = con.newInstance(msg);
Method m = c.getMethod("send");
m.invoke(obj);
}
}

View File

@ -0,0 +1,89 @@
/*
*
*/
package com.fp.bpmlib.mail;
import java.util.List;
import java.util.Map;
import com.fp.common.logger.APPLogger;
import com.fp.dto.Request;
// TODO: Auto-generated Javadoc
/**
* MailCommand encargada del envío de correos a partir de una regla.
*
* @author gfiallos
*/
public class MailCommand {
/** El valor de parameters. */
private final Map<String, Object> parameters;
/** El valor de request. */
private final Request request;
/** El valor de m. */
private final Mailer m;
/**
* Crea una nueva instancia de mail command.
*
* @param pParameters the parameters
* @throws Exception la exception
*/
public MailCommand(Map<String, Object> pParameters) throws Exception {
APPLogger.getLogger().info(pParameters);
parameters = pParameters;
request = (Request) parameters.get("request");
m = new Mailer(request);
}
/**
* Send.
*
* @throws Exception la exception
*/
public void send() throws Exception {
this.manageTo();
m.setSubject((Integer) parameters.get("subject"));
m.setContent((Integer) parameters.get("content"));
MailThread mt = new MailThread(m);
mt.start();
// this.m.send();
}
/**
* Maneja el campo to.
*
* @throws Exception la exception
*/
@SuppressWarnings("unchecked")
private void manageTo() throws Exception {
List<String> users = (List<String>) parameters.get("user");
if (users != null) {
for (String user : users) {
m.setToUser(user);
}
}
List<String> groups = (List<String>) parameters.get("group");
if (groups != null) {
for (String group : groups) {
m.setToGroup(group);
}
}
List<String> fields = (List<String>) parameters.get("field");
if (fields != null) {
for (String field : fields) {
m.setTo(request.getString(field));
}
}
List<String> ladress = (List<String>) parameters.get("address");
if (ladress != null) {
for (String address : ladress) {
m.setTo(address);
}
parameters.remove("address");
}
}
}

View File

@ -0,0 +1,99 @@
/*
*
*/
package com.fp.bpmlib.mail;
import java.util.NoSuchElementException;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.data.ThreadFacade;
import com.fp.persistence.pgeneral.gene.TgeneParameters;
import com.fp.persistence.pgeneral.gene.TgeneParametersKey;
// TODO: Auto-generated Javadoc
/**
* Parámetros del Sistema empleados para el manejo del Envío de Correos.
*
* @author gfiallos
*
*/
public enum MailParameters {
/** REMITENTE. */
MAIL_FROM("MAIL.FROM"),
/** INDICADOR SI SE REQUIERE AUTENTICACIÓN CON EL SERVIDOR. */
MAIL_SMTP_AUTH("MAIL.SMTP.AUTH"),
/** PASSWORD DE INGRESO AL SERVIDOR SMTP. */
MAIL_SMTP_PASSWORD("MAIL.SMTP.PASSWORD"),
/** PUERTO SMTP. */
MAIL_SMTP_PORT("MAIL.SMTP.PORT"),
/** SERVIDOR SMTP. */
MAIL_SMTP_SERVER("MAIL.SMTP.SERVER"),
/** USUARIO DE INGRESO AL SERVIDOR SMTP. */
MAIL_SMTP_USER("MAIL.SMTP.USER"),
/** INDICADOR SI EL SERVIDOR MANEJA PROTOCOLO SEGURO. */
MAIL_SMTPS("MAIL.SMTPS");
/** El valor de name. */
private String name;
/**
* Crea una nueva instancia de mail parameters.
*
* @param pName the name
*/
private MailParameters(String pName) {
this.name = pName;
}
/**
* Obtiene el valor de parameter.
*
* @return Valor de parameter
* @throws Exception la exception
*/
private TgeneParameters getParameter() throws Exception {
TgeneParametersKey k = new TgeneParametersKey(this.name, ThreadFacade.getSessionData().getCompany());
TgeneParameters p = TgeneParameters.find(PersistenceHelper.getEntityManager(), k);
if (p != null) {
return p;
}
throw new NoSuchElementException();
}
/**
* Obtiene el valor de string value.
*
* @return Valor de string value
* @throws Exception la exception
*/
public String getStringValue() throws Exception {
return this.getParameter().getTextvalue();
}
/**
* Obtiene el valor de int value.
*
* @return Valor de int value
* @throws Exception la exception
*/
public Integer getIntValue() throws Exception {
return this.getParameter().getNumbervalue().intValue();
}
/**
* Obtiene el valor de boolean value.
*
* @return Valor de boolean value
* @throws Exception la exception
*/
public boolean isBooleanValue() throws Exception {
return Boolean.valueOf(this.getStringValue());
}
}

View File

@ -0,0 +1,40 @@
/*
*
*/
package com.fp.bpmlib.mail;
import com.fp.common.logger.APPLogger;
// TODO: Auto-generated Javadoc
/**
* Class MailThread encargada de.
*
* @author gfiallos
*/
public class MailThread extends Thread {
/** El valor de m. */
private Mailer m;
/**
* Crea una nueva instancia de mail thread.
*
* @param pMaler the maler
*/
public MailThread(Mailer pMaler) {
this.m = pMaler;
}
/**
* Run.
*/
@Override
public void run() {
try {
this.m.send();
} catch (Exception e) {
APPLogger.getLogger().warn(e, e);
}
}
}

View File

@ -0,0 +1,40 @@
/*
*
*/
package com.fp.bpmlib.mail;
import com.fp.common.logger.APPLogger;
// TODO: Auto-generated Javadoc
/**
* Class MailThread encargada de.
*
* @author gfiallos
*/
public class MailThreadWithAttachment extends Thread {
/** El valor de m. */
private Mailer m;
/**
* Crea una nueva instancia de mail thread.
*
* @param pMaler the maler
*/
public MailThreadWithAttachment(Mailer pMaler) {
this.m = pMaler;
}
/**
* Run.
*/
@Override
public void run() {
try {
this.m.sendWithAttachment();
} catch (Exception e) {
APPLogger.getLogger().warn(e, e);
}
}
}

View File

@ -0,0 +1,252 @@
/*
*
*/
package com.fp.bpmlib.mail;
import java.util.HashMap;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.fp.base.persistence.util.helper.GeneralDescriptions;
import com.fp.bpmlib.ejb.local.LogMailBeanLocal;
import com.fp.bpmlib.messages.MessageManager;
import com.fp.common.logger.APPLogger;
import com.fp.dto.Request;
import com.fp.mail.Mail;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.data.ThreadFacade;
import com.fp.persistence.pbpm.gene.TbpmGroups;
import com.fp.persistence.pbpm.gene.TbpmGroupsKey;
// TODO: Auto-generated Javadoc
/**
* Class Mailer encargada del envío de Correos.
*
* @author gfiallos
*/
public class Mailer {
/** El valor de mail. */
private Mail mail = null;
/** El valor de request. */
private final Request request;
/**
* Crea una nueva instancia de mailer.
*
* @param pRequest the request
* @throws Exception la exception
*/
public Mailer(Request pRequest) throws Exception {
request = pRequest;
mail = new Mail(null, null, null, null, null, false);
this.config();
}
/**
* Config.
*
* @throws Exception la exception
*/
private void config() throws Exception {
System.out.println("---------------------------"+MailParameters.MAIL_SMTP_SERVER.getStringValue());
System.out.println("---------------------------"+ MailParameters.MAIL_SMTP_PORT.getIntValue());
mail.config(MailParameters.MAIL_FROM.getStringValue(), MailParameters.MAIL_SMTP_SERVER.getStringValue(),
MailParameters.MAIL_SMTP_PORT.getIntValue(), MailParameters.MAIL_SMTP_USER.getStringValue(),
MailParameters.MAIL_SMTP_PASSWORD.getStringValue(), MailParameters.MAIL_SMTP_AUTH.isBooleanValue(),
MailParameters.MAIL_SMTPS.isBooleanValue());
}
/**
* Prepare message manager.
*
* @param pTemplate the template
* @return message manager
* @throws Exception la exception
*/
private MessageManager prepareMessageManager(Integer pTemplate) throws Exception {
MessageManager m = new MessageManager(pTemplate, request.getLanguage(), null);
m.setValue("request", request);
return m;
}
/**
* Fija el valor de subject.
*
* @param pTemplate es el valor nuevo de subject
* @throws Exception la exception
*/
public void setSubject(Integer pTemplate) throws Exception {
mail.setSubject(this.prepareMessageManager(pTemplate).getMessage());
}
/**
* Fija el valor de content.
*
* @param pTemplate es el valor nuevo de content
* @throws Exception la exception
*/
public void setContent(Integer pTemplate) throws Exception {
mail.setCont(this.prepareMessageManager(pTemplate).getMessage());
}
/**
* Fija el valor de to.
*
* @param pRef es el valor nuevo de to
* @throws Exception la exception
*/
public void setTo(String pRef) throws Exception {
String to = mail.getTo();
if (to == null) {
mail.setTo(pRef);
} else {
mail.setTo(to + "," + pRef);
}
}
/**
* Fija el valor de to user.
*
* @param pUser es el valor nuevo de to user
* @throws Exception la exception
*/
public void setToUser(String pUser) throws Exception {
this.setTo(GeneralDescriptions.getEmailByUser(pUser));
}
/**
* Fija el valor de to group.
*
* @param pGroup es el valor nuevo de to group
* @throws Exception la exception
*/
public void setToGroup(String pGroup) throws Exception {
TbpmGroupsKey k = new TbpmGroupsKey(pGroup, ThreadFacade.getSessionData().getCompany());
TbpmGroups g = TbpmGroups.find(PersistenceHelper.getEntityManager(), k);
if (g == null) {
throw new Exception("GRUPO NO EXISTE |" + pGroup + "|");
}
this.setTo(g.getEmail());
}
/**
* Envía el Correo.
*
* @throws Exception la exception
*/
public void send() throws Exception {
try {
if ((mail.getTo() == null) || (mail.getSubject() == null) || (mail.getCont() == null)) {
throw new Exception(mail.getTo() + " " + mail.getSubject() + " " + (mail.getCont() != null));
}
String [] correosl=mail.getTo().split(",");
LogMailBeanLocal beanLocal = (LogMailBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/logMailBean");
for(String para:correosl){
try{
mail.setTo(para);
APPLogger.getLogger().info("Mensaje a enviar " + mail.getSubject() + " para " + mail.getTo());
mail.send();
try {
Map<String, Object> mapaMail = new HashMap<String, Object>();
mapaMail.put("to", mail.getTo());
mapaMail.put("subject", mail.getSubject());
mapaMail.put("cont", mail.getCont());
mapaMail.put("estado", "Y");
beanLocal.logMail(mapaMail);
} catch (Exception e) {
e.getMessage();
APPLogger.getLogger().error("1.-Excepcion en seteo mail");
}
}catch (Exception e) {
APPLogger.getLogger().warn("El mensaje" + mail.getSubject() + " para " + mail.getTo() + " no se ha podido enviar ");
APPLogger.getLogger().error(e, e);
try {
//LogMailBeanLocal beanLocal = (LogMailBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/logMailBean");
Map<String, Object> mapaMail = new HashMap<String, Object>();
mapaMail.put("to", mail.getTo());
mapaMail.put("subject", mail.getSubject());
mapaMail.put("cont", mail.getCont());
mapaMail.put("estado", "N");
mapaMail.put("error", e.getMessage());
beanLocal.logMail(mapaMail);
} catch (Exception e2) {
e.getMessage();
APPLogger.getLogger().error("2.-Excepcion en seteo mail");
}
}
}
}catch (NamingException e) {
e.getMessage();
APPLogger.getLogger().error("Servicio no encontrado");
}
catch (Exception e) {
e.getMessage();
APPLogger.getLogger().error("Excepcion al enviar mail");
}
}
/**
* Envía el Correo.
*
* @throws Exception la exception
*/
public void sendWithAttachment() throws Exception {
try {
if ((mail.getTo() == null) || (mail.getSubject() == null) || (mail.getCont() == null)) {
throw new Exception(mail.getTo() + " " + mail.getSubject() + " " + (mail.getCont() != null));
}
String [] correosl=mail.getTo().split(",");
LogMailBeanLocal beanLocal = (LogMailBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/logMailBean");
for(String para:correosl){
try{
mail.setTo(para);
APPLogger.getLogger().info("Mensaje a enviar " + mail.getSubject() + " para " + mail.getTo());
mail.send();
try {
Map<String, Object> mapaMail = new HashMap<String, Object>();
mapaMail.put("to", mail.getTo());
mapaMail.put("subject", mail.getSubject());
mapaMail.put("cont", mail.getCont());
mapaMail.put("estado", "Y");
beanLocal.logMail(mapaMail);
} catch (Exception e) {
e.getMessage();
APPLogger.getLogger().error("1.-Excepcion en seteo mail");
}
}catch (Exception e) {
APPLogger.getLogger().warn("El mensaje" + mail.getSubject() + " para " + mail.getTo() + " no se ha podido enviar ");
APPLogger.getLogger().error(e, e);
try {
//LogMailBeanLocal beanLocal = (LogMailBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/logMailBean");
Map<String, Object> mapaMail = new HashMap<String, Object>();
mapaMail.put("to", mail.getTo());
mapaMail.put("subject", mail.getSubject());
mapaMail.put("cont", mail.getCont());
mapaMail.put("estado", "N");
mapaMail.put("error", e.getMessage());
beanLocal.logMail(mapaMail);
} catch (Exception e2) {
e.getMessage();
APPLogger.getLogger().error("2.-Excepcion en seteo mail");
}
}
}
}catch (NamingException e) {
e.getMessage();
APPLogger.getLogger().error("Servicio no encontrado");
}
catch (Exception e) {
e.getMessage();
APPLogger.getLogger().error("Excepcion al enviar mail");
}
}
}

View File

@ -0,0 +1,4 @@
/**
* Provee las clases para el envío de correos electrónicos
*/
package com.fp.bpmlib.mail;

View File

@ -0,0 +1,69 @@
/*
*
*/
package com.fp.bpmlib.messages;
import java.util.Map;
import java.util.Map.Entry;
import com.fp.bpmlib.BPMException;
import com.fp.common.messages.MessageUtil;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pgeneral.message.TgeneMessageTemplatesDesc;
import com.fp.persistence.pgeneral.message.TgeneMessageTemplatesDescKey;
// TODO: Auto-generated Javadoc
/**
* Class MessageManager encargada de.
*
* @author gfiallos
*/
public class MessageManager {
/** El valor de msg. */
private MessageUtil msg;
/**
* Crea una nueva instancia de message manager.
*
* @param pMessageCode the message code
* @param pLanguage the language
* @param pReferences the references
* @throws Exception la exception
*/
public MessageManager(Integer pMessageCode, String pLanguage, Map<String, Object> pReferences) throws Exception {
TgeneMessageTemplatesDescKey tk = new TgeneMessageTemplatesDescKey(pMessageCode, pLanguage);
TgeneMessageTemplatesDesc t = TgeneMessageTemplatesDesc.find(PersistenceHelper.getEntityManager(), tk);
if (t == null) {
throw new BPMException("BPM-0011", "NO SE HA PODIDO ENCONTRAR LA PLANTILLA {0}", pMessageCode);
}
String template = t.getTemplate();
this.msg = new MessageUtil(pLanguage, template);
if (pReferences != null) {
for (Entry<String, Object> e : pReferences.entrySet()) {
this.msg.setValue(e.getKey(), e.getValue());
}
}
}
/**
* Fija el valor de value.
*
* @param pName the name
* @param pValue the value
* @throws Exception la exception
*/
public void setValue(String pName, Object pValue) throws Exception {
this.msg.setValue(pName, pValue);
}
/**
* Obtiene el valor de message.
*
* @return Valor de message
* @throws Exception la exception
*/
public String getMessage() throws Exception {
return this.msg.getMessage();
}
}

View File

@ -0,0 +1,4 @@
/**
* Provee las clases para el manejo de Plantillas y mensajes
*/
package com.fp.bpmlib.messages;

View File

@ -0,0 +1,4 @@
/**
* Provee los utilitarios para el transporte de la información de los Flujos
*/
package com.fp.bpmlib.metadata;

View File

@ -0,0 +1,4 @@
/**
* Provee los utilitarios para el acceso a GUVNOR
*/
package com.fp.bpmlib;

View File

@ -0,0 +1,139 @@
/*
*
*/
package com.fp.bpmlib.query;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import com.fp.dto.Response;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pbpm.gene.TbpmTaskComments;
import com.fp.persistence.pgeneral.log.TgeneTransactionLog;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;
import com.fp.persistence.pgeneral.trans.TgeneTransactionKey;
// TODO: Auto-generated Javadoc
/**
* Class EndedFlowDetail encargada de.
*
* @author gfiallos
*/
public class EndedFlowDetail extends QueryRule {
/** serialVersionUID. */
private static final long serialVersionUID = 1L;
/** Constante SQL. */
private static final String SQL = "SELECT "
+ " a.activityname,a.sequence,a.usercode,a.groupcode,a.created,a.completed,a.expectedtime,a.response ,a.module,a.transaction,a.version, ( "
+ " SELECT " + " z.name " + " FROM " + " tgenetransaction z " + " WHERE "
+ " z.transactionmodule=a.module " + " AND z.transactioncode=a.transaction "
+ " AND z.transactionversion=a.version),a.taskid " + " FROM " + " tbpmactivities a " + " WHERE "
+ " a.journalid=:journal " + " ORDER BY " + " created";
/** El valor de id. */
private String id;
/** El valor de resp. */
private Response resp;
/** El valor de sdf1. */
private SimpleDateFormat sdf1;
/**
* Process.
*
* @param pQueryRequest the query request
* @return query request
* @throws Exception la exception
*/
@Override
public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
this.sdf1 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
this.id = pQueryRequest.getString("ID");
this.resp = pQueryRequest.getResponse();
TgeneTransactionLog tl = TgeneTransactionLog.find(PersistenceHelper.getEntityManager(), this.id);
this.resp.put("DATA", tl.getAditionaldata());
TgeneTransaction t = TgeneTransaction.find(PersistenceHelper.getEntityManager(),
new TgeneTransactionKey(tl.getTransactionmodule(), tl.getTransactioncode(), tl.getTransactionversion()));
this.resp.put("TRN", t.getName());
this.manageActivities();
return pQueryRequest;
}
/**
* Manage activities.
*
* @throws Exception la exception
*/
public void manageActivities() throws Exception {
Query q = PersistenceHelper.createNativeQuery(EndedFlowDetail.SQL);
q.setParameter("journal", this.id);
@SuppressWarnings("unchecked")
List<Object> l = q.getResultList();
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
DecimalFormat df = new DecimalFormat("00");
for (Object obj : l) {
Map<String, Object> rec = new HashMap<String, Object>();
Object[] oData = (Object[]) obj;
rec.put("activityname", oData[0] + " (" + oData[11] + ")");
rec.put("sequence", oData[1]);
rec.put("usercode", oData[2]);
rec.put("groupcode", oData[3]);
Timestamp completed = ((Timestamp) oData[5]);
Timestamp created = ((Timestamp) oData[4]);
rec.put("created", this.sdf1.format(created));
rec.put("completed", this.sdf1.format(completed));
Long exp = Long.valueOf("" + oData[6]) / 1000;
BigDecimal aux = new BigDecimal(exp / 60);
rec.put("expectedtime", df.format(aux.intValue()) + ":" + df.format(exp % 60));
Long real = Long.valueOf("" + (completed.getTime() - created.getTime())) / 1000;
aux = new BigDecimal(real / 60);
rec.put("realtime", df.format(aux.intValue()) + ":" + df.format(real % 60));
rec.put("response", oData[7]);
rec.put("obs", this.getComments(Long.valueOf("" + oData[12])));
data.add(rec);
}
this.resp.put("TBPMACTIVITIES", data);
}
/**
* Obtiene el valor de comments.
*
* @param pTID the tID
* @return Valor de comments
* @throws Exception la exception
*/
private String getComments(long pTID) throws Exception {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
String jpql = "from TbpmTaskComments tc where tc.taskid=:tid";
Query q = PersistenceHelper.createQuery(jpql);
q.setParameter("tid", pTID);
@SuppressWarnings("unchecked")
List<TbpmTaskComments> tc = q.getResultList();
for (TbpmTaskComments tbpmTaskComments : tc) {
pw.println(tbpmTaskComments.getUsercode() + " : " + this.sdf1.format(tbpmTaskComments.getAdded()));
pw.println(tbpmTaskComments.getText());
}
} finally {
pw.close();
}
return sw.toString();
}
}

View File

@ -0,0 +1,102 @@
/*
*
*/
package com.fp.bpmlib.query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.query.QueryBean;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.GeneralQuery;
import com.fp.persistence.commondb.PersistenceHelper;
// TODO: Auto-generated Javadoc
/**
* Clase que se encarga de presentar en el lov las transacciones que contiene la tabla TgeneTransactionLog.
*
* @author gfiallos
*/
public class EndedFlows extends QueryRule {
/** Constante serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Metodo que presenta la lista de transacciones en vuelo.
*
* @param qr the qr
* @return query request
* @throws Exception la exception
*/
@Override
public QueryRequest process(QueryRequest qr) throws Exception {
if(qr.isJsf()){
}else{
}
Response response = qr.getResponse();
StringBuilder jpql = new StringBuilder(400);
jpql.append("select t.pk.transactionmodule,t.pk.transactioncode,t.pk.transactionversion,t.name "
+ "from TgeneTransaction t where exists ( select 1 "
+ "from TgeneTransactionLog r where exists(select 1 from TbpmProcessInstance o "
+ "where o.pk = r.pk and coalesce(o.finalized, 'N')='Y') and t.pk.transactionmodule=r.transactionmodule "
+ "and t.pk.transactioncode=r.transactioncode and t.pk.transactionversion=r.transactionversion ) ");
//Ingresa y verifica el frontend
Query qry = this.processQuery(qr, jpql);
List<?> ltransaction = qry.getResultList();
List<Map<String, Object>> detailgrid = new ArrayList<Map<String, Object>>();
for (int i = 0; i < ltransaction.size(); i++) {
Map<String, Object> detail = new HashMap<String, Object>();
Object[] datos = (Object[]) ltransaction.get(i);
detail.put("pk_transactionmodule", datos[0]);
detail.put("pk_transactioncode", datos[1]);
detail.put("pk_transactionversion", datos[2]);
detail.put("name", datos[3]);
// detail.put("solicitudenumber", datos[4]);
detailgrid.add(detail);
}
response.put("TGENETRANSACTION", detailgrid);
return qr;
}
/**
* Direcciona la consulta jsf y dojo
* @param qr
* @param jpql
* @return
* @throws Exception
*/
private Query processQuery(QueryRequest qr, StringBuilder jpql) throws Exception {
Query qry = null;
if(qr.isJsf()){
DtoQuery dto = (DtoQuery)qr.getQueryTables().get("TGENETRANSACTION");
GeneralQuery.addParametersJSF(jpql, dto);
qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
GeneralQuery.setParametersJSF(jpql, dto, qry);
}else{
QueryBean qb = (QueryBean) qr.get("TGENETRANSACTION");
Map<String, Object> criteria = new HashMap<String, Object>();
GeneralQuery.addParameters(qb, jpql, criteria);
qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
/*
* qry.setParameter("init", qr.getDate("creationdate")); qry.setParameter("end", qr.getDate("enddate"));
*/
GeneralQuery.setParameters(qb, criteria, qry);
}
return qry;
}
}

View File

@ -0,0 +1,145 @@
/*
*
*/
package com.fp.bpmlib.query;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.query.QueryBean;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.GeneralQuery;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.APPDates;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pbpm.gene.TbpmProcessInstance;
// TODO: Auto-generated Javadoc
/**
* Clase que se encarga de presentar las transactiones que estan en vuelo en la TGENETRANSACTIONLOG.
*
* @author gfiallos
*/
public class EndedFlowsResults extends QueryRule {
/** serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Metodo que presenta las transacciones en vuelo.
*
* @param qr the qr
* @return query request
* @throws Exception la exception
*/
@Override
public QueryRequest process(QueryRequest qr) throws Exception {
Response response = qr.getResponse();
Query qry = this.prepareQuery(qr);
List<?> ltransactionLog = qry.getResultList();
List<Map<String, Object>> detailgrid = new ArrayList<Map<String, Object>>();
for (int i = 0; i < ltransactionLog.size(); i++) {
Map<String, Object> detail = new HashMap<String, Object>();
Object[] datos = (Object[]) ltransactionLog.get(i);
detail.put("solicitudenumber", datos[0]);
detail.put("usercode", datos[1]);
// detail.put("terminalcode", datos[1]);
detail.put("aditionaldata", datos[5]);
TbpmProcessInstance pi = (TbpmProcessInstance) datos[6];
detail.put("id", pi.getPk());
detail.put("init", pi.getCreationdate());
detail.put("end", pi.getEnddate());
detail.put("duration",
FormatDates.getInstance().getTimeFormat().format(new Date(pi.getEnddate().getTime() - pi.getCreationdate().getTime())));
detailgrid.add(detail);
}
response.put("TRANSACTIONLOG", detailgrid);
return qr;
}
/**
* Prepare query.
*
* @param qr the qr
* @return query
* @throws Exception la exception
*/
private Query prepareQuery(QueryRequest qr) throws Exception {
StringBuilder jpql = new StringBuilder(300);
jpql.append("select t.solicitudenumber, t.usercode,t.terminalcode,t.duration, t.realdate as time,t.aditionaldata,o "
+ " from TgeneTransactionLog t ,TbpmProcessInstance o"
+ " where t.pk in (select i.pk from TbpmProcessInstance i where coalesce(i.finalized, 'N')='Y') and t.pk = o.pk ");
String creation = "" + qr.get("creationdate");
creation = (creation.compareTo("") == 0) ? null : creation;
String enddate = "" + qr.get("enddate");
enddate = (enddate.compareTo("") == 0) ? null : enddate;
if ((creation != null) && (enddate != null)) {
jpql.append(" and o.creationdate>=:creationdate ");
jpql.append(" and o.enddate<=:enddate ");
}
return this.manageParameters(qr, jpql, creation, enddate);
}
/**
* Manage parameters.
*
* @param qr the qr
* @param jpql the jpql
* @param creation the creation
* @param enddate the enddate
* @return query
* @throws Exception la exception
*/
private Query manageParameters(QueryRequest qr, StringBuilder jpql, String creation, String enddate) throws Exception {
//Verifica consulta frontend jsf/dojo
Query qry = this.processQuery(qr, jpql);
if ((creation != null) && (enddate != null)) {
qry.setParameter("creationdate", (Date)qr.get("creationdate"));
APPDates ad = new APPDates((Date) qr.get("enddate"));
ad.addField(Calendar.DAY_OF_YEAR, 1);
qry.setParameter("enddate", ad.getDate());
}
return qry;
}
/**
* Metodo que maneja la peticion del frontend jsf/dojo
* @param qr
* @param jpql
* @return
* @throws Exception
*/
private Query processQuery(QueryRequest qr, StringBuilder jpql) throws Exception{
Query qry = null;
if(qr.isJsf()){
DtoQuery dto = (DtoQuery)qr.getQueryTables().get("TRANSACTIONLOG");
GeneralQuery.addParametersJSF(jpql, dto);
qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
GeneralQuery.setParametersJSF(jpql, dto, qry);
}else{
QueryBean qb = (QueryBean) qr.get("TRANSACTIONLOG");
Map<String, Object> criteria = new HashMap<String, Object>();
GeneralQuery.addParameters(qb, jpql, criteria);
jpql.append(",creationdate");
qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
GeneralQuery.setParameters(qb, criteria, qry);
}
return qry;
}
/** Sentencia que consulta el nombre del usuario. */
public static final String SQL = "select a.name from TcustPersonDetail a ,TsafeUser b" + " where a.pk.personcode = b.personcode"
+ " and b.pk=:usercode" + " and a.pk.dateto=:dateto";
}

View File

@ -0,0 +1,34 @@
/*
*
*/
package com.fp.bpmlib.query;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
// TODO: Auto-generated Javadoc
/**
* Clase encargada de disparar reglas dada una petición de consulta.
*
* @author gfiallos
*/
public class RuleTrigger extends QueryRule {
/** serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Process.
*
* @param pRequest the request
* @return query request
* @throws Exception la exception
*/
@Override
public QueryRequest process(QueryRequest pRequest) throws Exception {
//GuvnorClient gc = new GuvnorClient(this.rule, pRequest.getCompany());
//gc.eval(pRequest);
return pRequest;
}
}

View File

@ -0,0 +1,101 @@
/*
*
*/
package com.fp.bpmlib.query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.query.QueryBean;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.GeneralQuery;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
// TODO: Auto-generated Javadoc
/**
* Clase que se encarga de presentar las transactiones que estan en vuelo en la TGENETRANSACTIONLOG.
*
* @author jarias
*/
public class TransactionLogResults extends QueryRule {
/** serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Metodo que presenta las transacciones en vuelo.
*
* @param qr the qr
* @return query request
* @throws Exception la exception
*/
@Override
public QueryRequest process(QueryRequest qr) throws Exception {
Response response = qr.getResponse();
StringBuilder jpql = new StringBuilder(300);
jpql.append("select t.usercode,t.terminalcode,t.duration," + " t.realdate as time,t.aditionaldata,o.processid,o.sessionid,t.solicitudenumber "
+ " from TgeneTransactionLog t ,TbpmProcessInstance o"
+ " where t.pk in (select i.pk from TbpmProcessInstance i where coalesce(i.finalized, 'N')='N')" + " and t.pk = o.pk ");
Query qry = null;
if (qr.isJsf()) {
DtoQuery dto = qr.getQueryTables().get("TRANSACTIONLOG");
GeneralQuery.addParametersJSF(jpql, dto, false);
jpql.append(" order by t.realdate desc");
qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
GeneralQuery.setParametersJSF(jpql, dto, qry);
} else {
QueryBean qb = (QueryBean) qr.get("TRANSACTIONLOG");
Map<String, Object> criteria = new HashMap<String, Object>();
GeneralQuery.addParameters(qb, jpql, criteria);
qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
GeneralQuery.setParameters(qb, criteria, qry);
}
List<?> ltransactionLog = qry.getResultList();
List<Map<String, Object>> detailgrid = new ArrayList<Map<String, Object>>();
for (int i = 0; i < ltransactionLog.size(); i++) {
Map<String, Object> detail = new HashMap<String, Object>();
Object[] datos = (Object[]) ltransactionLog.get(i);
detail.put("usercode", datos[0]);
detail.put("name", this.consulta(datos[0].toString()));
detail.put("terminalcode", datos[1]);
detail.put("duration", datos[2]);
detail.put("time", datos[3]);
detail.put("aditionaldata", datos[4]);
detail.put("processid", datos[5]);
detail.put("sessionid", datos[6]);
detail.put("solicitudenumber", datos[7]);
detailgrid.add(detail);
}
response.put("TRANSACTIONLOG", detailgrid);
return qr;
}
/**
* Metodo que me retorna el nombre de usuario.
*
* @param usercode the usercode
* @return nombre del usuario
* @throws Exception la exception
*/
private String consulta(String usercode) throws Exception {
javax.persistence.Query qr = PersistenceHelper.getEntityManager().createQuery(TransactionLogResults.SQL);
qr.setParameter("usercode", usercode);
qr.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
return (String) qr.getSingleResult();
}
/** Sentencia que consulta el nombre del usuario. */
public static final String SQL = "select a.name from TcustPersonDetail a ,TsafeUser b" + " where a.pk.personcode = b.personcode"
+ " and b.pk=:usercode" + " and a.pk.dateto=:dateto";
}

View File

@ -0,0 +1,74 @@
/*
*
*/
package com.fp.bpmlib.query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import com.fp.dto.Response;
import com.fp.dto.query.QueryBean;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.GeneralQuery;
import com.fp.persistence.commondb.PersistenceHelper;
// TODO: Auto-generated Javadoc
/**
* Clase que se encarga de presentar en el lov las transacciones que contiene la tabla TgeneTransactionLog.
*
* @author jarias
*/
public class TransactionsLog extends QueryRule {
/** Constante serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Metodo que presenta la lista de transacciones en vuelo.
*
* @param qr the qr
* @return query request
* @throws Exception la exception
*/
@Override
public QueryRequest process(QueryRequest qr) throws Exception {
Response response = qr.getResponse();
QueryBean qb = (QueryBean) qr.get("TGENETRANSACTION");
StringBuilder jpql = new StringBuilder(400);
jpql.append("select t.pk.transactionmodule,t.pk.transactioncode,t.pk.transactionversion,t.name "
+ "from TgeneTransaction t where exists ( select 1 "
+ "from TgeneTransactionLog r where exists(select 1 from TbpmProcessInstance o "
+ "where o.pk = r.pk and coalesce(o.finalized, 'N')='N') and t.pk.transactionmodule=r.transactionmodule "
+ "and t.pk.transactioncode=r.transactioncode and t.pk.transactionversion=r.transactionversion ) ");
Map<String, Object> criteria = new HashMap<String, Object>();
GeneralQuery.addParameters(qb, jpql, criteria);
Query qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
GeneralQuery.setParameters(qb, criteria, qry);
List<?> ltransaction = qry.getResultList();
List<Map<String, Object>> detailgrid = new ArrayList<Map<String, Object>>();
for (int i = 0; i < ltransaction.size(); i++) {
Map<String, Object> detail = new HashMap<String, Object>();
Object[] datos = (Object[]) ltransaction.get(i);
detail.put("pk_transactionmodule", datos[0]);
detail.put("pk_transactioncode", datos[1]);
detail.put("pk_transactionversion", datos[2]);
detail.put("name", datos[3]);
detailgrid.add(detail);
}
if (ltransaction.isEmpty()) {
Map<String, Object> detail = new HashMap<String, Object>();
detail.put("pk_transactionmodule", "");
detail.put("pk_transactioncode", "");
detail.put("pk_transactionversion", "");
detail.put("name", "");
detailgrid.add(detail);
}
response.put("TGENETRANSACTION", detailgrid);
return qr;
}
}

View File

@ -0,0 +1,55 @@
package com.fp.bpmlib.query.groups;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import com.fp.dto.query.QueryBean;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
/**
* Lista de Valores de Usuarios
*
* @author gfiallos
*
*/
public class UserLov extends QueryRule {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Consulta
*/
private static final String SQL = "select u.usercode, (select d.name from tcustpersondetail d where d.dateto=u.dateto and d.personcode=u.personcode)"
+ " from tsafeuserdetail u where u.isuserbpm='Y' and u.dateto=:dateto and not exists( "
+ " select 1 from tbpmgroupsusers i where i.companycode=:cia and i.groupcode=:group and i.usercode=u.usercode)";
@Override
public QueryRequest process(QueryRequest pRequest) throws Exception {
QueryBean qb = (QueryBean) pRequest.get("TSAFEUSERDETAILLOV");
Query qry = PersistenceHelper.createNativeQuery(UserLov.SQL);
qry.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
qry.setParameter("cia", pRequest.getCompany());
qry.setParameter("group", qb.getCriteriaValue("group"));
@SuppressWarnings("unchecked")
List<Object[]> l = qry.getResultList();
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
for (Object[] objects : l) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("pk_usercode", objects[0]);
m.put("name", objects[1]);
data.add(m);
}
pRequest.getResponse().put("TSAFEUSERDETAILLOV", data);
return pRequest;
}
}

View File

@ -0,0 +1,64 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.bpmlib.query.groups;
import java.util.List;
import javax.persistence.EntityManager;
import com.fp.bpm.query.Query;
import com.fp.dto.Response;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pbpm.gene.TbpmGroupsUsers;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pcustomer.gene.TcustPersonDetailKey;
import com.fp.persistence.pgeneral.safe.TsafeUser;
// TODO: Auto-generated Javadoc
/**
* Class UserToGroup encargada de.
*
* @author BPTWPA
*/
public class UserToGroup extends QueryRule {
/** Constante serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Process.
*
* @param pQueryRequest the query request
* @return query request
* @throws Exception la exception
*/
@Override
public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
EntityManager em = PersistenceHelper.getEntityManager();
Response response = pQueryRequest.getResponse();
Query qry = new Query();
qry.process(pQueryRequest);
@SuppressWarnings("unchecked")
List<Object> lobjects = (List<Object>) response.get("TBPMGROUPSUSERS");
if (!lobjects.isEmpty()) {
for (Object obj : lobjects) {
TbpmGroupsUsers tbpmGroupsUsers = (TbpmGroupsUsers) obj;
if (tbpmGroupsUsers.getPk().getUsercode() != null) {
TsafeUser tsafeUser = TsafeUser.find(em, tbpmGroupsUsers.getPk().getUsercode());
if (tsafeUser != null) {
TcustPersonDetailKey custPersonDetailKey = new TcustPersonDetailKey(tsafeUser.getPersoncode(),
FormatDates.getDefaultExpiryTimestamp());
TcustPersonDetail tcutPersonDetail = TcustPersonDetail.find(em, custPersonDetailKey);
tbpmGroupsUsers.addAddtionalInfo("username", ((tcutPersonDetail == null) ? "" : tcutPersonDetail.getName()));
}
}
}
}
return pQueryRequest;
}
}

View File

@ -0,0 +1,4 @@
/**
* Provee las clases para el manejo de Grupos
*/
package com.fp.bpmlib.query.groups;

Some files were not shown because too many files have changed in this diff Show More