Archive for Programacion
August 17, 2010 a las 10:43 pm por Edwin Plauchu · Archivado en NetBSD , Programacion
Mod_python es un modulo Apache que embebe el Interprete de Python dentro del el servidor. Con mod_python tu podras escribir aplicaciones webs basada en aplicaciones Python que correran mucho mas rapido que las aplicaciones tradicionales de CGI ademas de tener acceso a las caracteristicas avanzadas de retener conecciones a bases de datos y acceso a funciones internas de Apache.
Instalando el Port en NetBSD 5.X
# cd /usr/pkgsrc/www/ap2-python && make && make install
Luego hay que editar el httpd.conf, agregando la siguiente línea para cargar el módulo.
LoadModule python_module /usr/pkg/lib/httpd/mod_python.so
Mod_python handlers
Apache procesa las requests en fases. Un Handler es una funcion que procesas una particular parte del request. Los Handlers son proporcionados por Apache y por sus modulos como , mod_python.
El Handler Publisher permite accesar a funciones y variables dentro de un modulo via URLs. Evitandoce asi el codigo spagetthi.
Para probar el funcionamiento del módulo debemos hacer lo siguiente. En primer lugar, vamos a necesitar definir un handler de python para los requests en un .htaccess. Allí escribimos algo como lo siguiente:
AddHandler mod_python .py
PythonHandler mod_python.publisher
PythonOption session DbmSession
PythonOption session_dbm /home/user/domains/test.com/session.dbm
PythonOption ApplicationPath /
PythonDebug On ## Turn this off when done with debugging
DirectoryIndex index.py
Por supuesto, habrá que ajustar los datos a lo que sea necesario.
Luego, creamos el índice de nuestro sitio, en este caso en /home/user/domains/test.com/public_html/index.py con el siguiente código:
## index.py
from mod_python import apache
def index(req):
req.content_type = 'text/plain'
req.write('Hello from mod_pythonn')
return apache.OK
Luego accedemos a http://test.com/ y si vemos “Hello from mod_python”, es que hemos instalado correctamente mod_python.
May 1, 2010 a las 1:03 pm por Edwin Plauchu · Archivado en Programacion
http://twitter.com/pianodaemon/jquery-masters
April 23, 2010 a las 3:05 pm por Edwin Plauchu · Archivado en Programacion
De las pocas cosas que me gustan de java… esta su parser SAX…..que tambien valida esquemas….
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.w3c.dom.Document;
public class ValidateXmlWithSchema{
public boolean validate(String file_path){
boolean valor_retono = true;
final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
final String MY_SCHEMA = new OsVars().getSchemaDir() + "cfdv2.xsd";
final String MY_XML= file_path;
// Creando la factoria e indicando que hay validacion
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setValidating(true);
try {
//Configurando el Schema de validacion
documentBuilderFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
documentBuilderFactory.setAttribute(JAXP_SCHEMA_SOURCE, new File(MY_SCHEMA));
// Parseando el documento
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setErrorHandler(new ParserErrorHandler());
@SuppressWarnings("unused")
Document parse = documentBuilder.parse(new File(MY_XML));
} catch (SAXException saxEx){
valor_retono = false;
System.out.println(saxEx.toString());
} catch (Exception ex) {
valor_retono = false;
System.out.println(ex.toString());
}
return valor_retono;
}
private class ParserErrorHandler extends DefaultHandler {
@Override
public void warning(SAXParseException e) throws SAXException {
System.out.println("Warning: ");
printInfo(e);
}
@Override
public void error(SAXParseException e) throws SAXException {
System.out.println("Error: ");
printInfo(e);
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("Error Fatal: ");
printInfo(e);
}
private void printInfo(SAXParseException e) {
System.out.println(" Publico ID: "+e.getPublicId());
System.out.println(" Sistema ID: "+e.getSystemId());
System.out.println(" Linea numero: "+e.getLineNumber());
System.out.println(" Columna number: "+e.getColumnNumber());
System.out.println(" Mensaje: "+e.getMessage());
}
}
}
April 23, 2010 a las 3:01 pm por Edwin Plauchu · Archivado en Programacion
Para vivir tengo que escribir kilometros y kilometros de codigo en este mugre lenguaje (oseace java)….
Para que ustedes no pasen por lo mismo… ahi les dejo algo hecho para pasar de JSON a java
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Iterator;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.util.HashMap;
public class Json2Java {
/**
* getList provides a List representation of the JSON Object
* @param jsonResponse The JSON array string
* @return List of JSONObject.
**/
public List getList(String jsonResponse) throws Exception {
List listResponse = new ArrayList();
if (jsonResponse.startsWith(”[”)) {
JSONArray jsonArray = JSONArray.fromObject(jsonResponse);
toJavaList(jsonArray, listResponse);
} else {
throw new Exception(”MalFormed JSON Array Response.”);
}
return listResponse;
}
/**
* getMap provides a Map representation of the JSON Object
* @param jsonResponse The JSON object string
* @return Map of JSONObject.
**/
public Map getMap(String jsonResponse ) throws Exception {
Map mapResponse = new HashMap();
if (jsonResponse.startsWith(”{”)) {
JSONObject jsonObj = JSONObject.fromObject(jsonResponse);
toJavaMap(jsonObj, mapResponse);
} else {
throw new Exception(”MalFormed JSON Array Response.”);
}
return mapResponse;
}
/**
* toJavaMap converts the JSONObject into a Java Map
* @param o
* JSONObject to be converted to Java Map
* @param b
* Java Map to hold converted JSONObject response.
**/
@SuppressWarnings(”unchecked”)
private static void toJavaMap(JSONObject o, Map b) {
Iterator ji = o.keys();
while (ji.hasNext()) {
String key = (String) ji.next();
Object val = o.get(key);
if (val.getClass() == JSONObject.class) {
Map sub = new HashMap();
toJavaMap((JSONObject) val, sub);
b.put(key, sub);
} else if (val.getClass() == JSONArray.class) {
List l = new ArrayList();
JSONArray arr = (JSONArray) val;
for (int a = 0; a < arr.size(); a++) {
Map sub = new HashMap();
Object element = arr.get(a);
if (element instanceof JSONObject) {
toJavaMap((JSONObject) element, sub);
l.add(sub);
} else {
l.add(element);
}
}
b.put(key, l);
} else {
b.put(key, val);
}
}
}
/**
* toJavaList converts JSON’s array response into Java’s List
* @param ar
* JSONArray to be converted to Java List
* @param ll
* Java List to hold the converted JSONArray response
**/
private static void toJavaList(JSONArray ar, List ll) {
int i = 0;
while (i < ar.size()) {
Object val = ar.get(i);
if (val.getClass() == JSONObject.class) {
Map sub = new HashMap();
toJavaMap((JSONObject) val, sub);
ll.add(sub);
} else if (val.getClass() == JSONArray.class) {
List l = new ArrayList();
JSONArray arr = (JSONArray) val;
for (int a = 0; a < arr.size(); a++) {
Map sub = new HashMap();
Object element = arr.get(a);
if (element instanceof JSONObject) {
toJavaMap((JSONObject) element, sub);
ll.add(sub);
} else {
ll.add(element);
}
}
l.add(l);
} else {
ll.add(val);
}
i++;
}
}
}
April 23, 2010 a las 2:58 pm por Edwin Plauchu · Archivado en Programacion
Usen estas funciones y ya no se metan en detalles…. hacen lo que tienen que hacer y punto….
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class FileHelper {
public static boolean addText2File(String file,String text){
boolean valor_retorno = true;
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file,true)) ;
writer.write(text) ;
writer.close();
}
catch (IOException e) {
valor_retorno = false;
}
return valor_retorno;
}
public static boolean createFileWithText(String dir_fichero,String archivo,String cadena_impresa){
boolean valor_retorno = true;
File fichero = new File (dir_fichero,archivo);
try {
if (fichero.createNewFile()){
System.out.println("Se ha creado el Fichero: " + dir_fichero + archivo);
}
else{
System.out.println("No se ha creado el Fichero: " + dir_fichero + archivo);
}
} catch (IOException ioe) {
ioe.printStackTrace();
valor_retorno = false;
}
try{
System.out.println("Alimentando contenido al Fichero: " + dir_fichero + "/" + archivo);
PrintWriter fileOut = new PrintWriter(fichero);
fileOut.println(cadena_impresa);
fileOut.close();
System.out.println("Contenido alimentado con exito al Fichero: " + dir_fichero + "/" + archivo);
}catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("No se ha alimentado el contenido para el Fichero: " + dir_fichero + "/" + archivo);
valor_retorno = false;
}
return valor_retorno;
}
public static boolean createFileWithText(String archivo,String cadena_impresa){
boolean valor_retorno = true;
File fichero = new File (archivo);
try {
if (fichero.createNewFile()){
System.out.println("Se ha creado el Fichero: " + archivo);
}
else{
System.out.println("No se ha creado el Fichero: " + archivo);
}
} catch (IOException ioe) {
ioe.printStackTrace();
valor_retorno = false;
}
try{
System.out.println("Alimentando contenido al Fichero: " + archivo);
PrintWriter fileOut = new PrintWriter(fichero);
fileOut.println(cadena_impresa);
fileOut.close();
System.out.println("Contenido alimentado con exito al Fichero: " + archivo);
}catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("No se ha alimentado el contenido para el Fichero: " + archivo);
valor_retorno = false;
}
return valor_retorno;
}
public void move(String fromFileName, String toFileName) throws IOException {
copy(fromFileName, toFileName);
delete(fromFileName);
}
public void copy(String fromFileName, String toFileName) throws IOException {
File fromFile = new File(fromFileName);
File toFile = new File(toFileName);
if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName);
if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName);
if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName);
if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName());
if (toFile.exists()) {
if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName);
System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): ");
System.out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String response = in.readLine();
if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten.");
} else {
String parent = toFile.getParent();
if (parent == null) parent = System.getProperty("user.dir");
File dir = new File(parent);
if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent);
}
FileInputStream from = null;
FileOutputStream to = null;
try {
from = new FileInputStream(fromFile);
to = new FileOutputStream(toFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead); // write
} finally {
if (from != null)
try {
from.close();
} catch (IOException e) {
;
}
if (to != null)
try {
to.close();
} catch (IOException e) {
;
}
}
}
public static void delete(String fileName) {
// A File object to represent the filename
File f = new File(fileName);
// Make sure the file or directory exists and isn't write protected
if (!f.exists())
throw new IllegalArgumentException(
"Delete: no such file or directory: " + fileName);
if (!f.canWrite())
throw new IllegalArgumentException("Delete: write protected: "
+ fileName);
// If it is a directory, make sure it is empty
if (f.isDirectory()) {
String[] files = f.list();
if (files.length > 0)
throw new IllegalArgumentException(
"Delete: directory not empty: " + fileName);
}
// Attempt to delete it
boolean success = f.delete();
if (!success) throw new IllegalArgumentException("Delete: deletion failed");
}
public String obtenerNombreArchivo( String in ){
String cadena_retorno = null;
File fichero = new File(in);
if(fichero.exists()){
cadena_retorno = fichero.getName();
}
return cadena_retorno;
}
}
April 23, 2010 a las 1:59 pm por Edwin Plauchu · Archivado en Programacion
import java.util.*;
import java.io.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author pianodaemon
*/
public class CadenaOrginalFromCFD{
private String nc_version;
private String nc_serie;
private String nc_folio;
private String nc_fecha;
private String nc_noAprobacion;
private String nc_anioAprobacion;
private String nc_tipoDeComprobante;
private String nc_formaDePago;
private String nc_condicionesDePago;
private String nc_subTotal;
private String nc_descuento;
private String nc_total;
private String ne_rfc;
private String ne_nombre;
private String df_calle;
private String df_noExterior;
private String df_noInterior;
private String df_colonia;
private String df_localidad;
private String df_referencia;
private String df_municipio;
private String df_estado;
private String df_pais;
private String df_codigoPostal;
private String ee_calle;
private String ee_noExterior;
private String ee_noInterior;
private String ee_colonia;
private String ee_localidad;
private String ee_referencia;
private String ee_municipio;
private String ee_estado;
private String ee_pais;
private String ee_codigoPostal;
private String nr_rfc;
private String nr_nombre;
private String nd_calle;
private String nd_noExterior;
private String nd_noInterior;
private String nd_colonia;
private String nd_localidad;
private String nd_referencia;
private String nd_municipio;
private String nd_estado;
private String nd_pais;
private String nd_codigoPostal;
private ArrayList concepto = new ArrayList();
private String nc_cantidad;
private String nc_unidad;
private String nc_noIdentificacion;
private String nc_descripcion;
private String nc_valorUnitario;
private String nc_importe;
private ArrayList retencion = new ArrayList();
private String nr_impuesto;
private String nr_importe;
private String totalImpuestosRetenidos;
private ArrayList traslado = new ArrayList();
private String nt_impuesto;
private String nt_tasa;
private String nt_importe;
private String totalImpuestosTrasladados;
private String cadenaOriginal;
private String nc_noCertificado;
public void leerxml(InputStream url){
try{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
sp.parse(url, new parsexml() );
}
catch(ParserConfigurationException e){
System.err.println("error de parseo");
}
catch(SAXException e2){
System.err.println("error de sax: " + e2.getStackTrace());
}
catch (IOException e3) {
System.err.println("error de io: " + e3.getMessage() );
}
}
private class parsexml extends DefaultHandler {
public void startElement(String namespaceURI, String localName, String qName, Attributes atts)throws SAXException{
if ("Comprobante".equals(qName)) {
for(int i=0; i < atts.getLength(); i++){
String valor = atts.getQName(i);
if("anoAprobacion".equals(valor)){
String nc_anioAprobacion = atts.getValue(i);
set_nc_anioAprobacion(nc_anioAprobacion);
}
if("condicionesDePago".equals(valor)){
String nc_condicionesDePago = atts.getValue(i);
set_nc_condicionesDePago(nc_condicionesDePago);
}
if("descuento".equals(valor)){
String nc_descuento = atts.getValue(i);
set_nc_descuento(nc_descuento);
}
if("fecha".equals(valor)){
String nc_fecha = atts.getValue(i);
set_nc_fecha(nc_fecha);
}
if("folio".equals(valor)){
String nc_folio = atts.getValue(i);
set_nc_folio(nc_folio);
}
if("formaDePago".equals(valor)){
String nc_formaDePago = atts.getValue(i);
set_nc_formaDePago(nc_formaDePago);
}
if("noAprobacion".equals(valor)){
String nc_noAprobacion = atts.getValue(i);
set_nc_noAprobacion(nc_noAprobacion);
}
if("serie".equals(valor)){
String nc_serie = atts.getValue(i);
set_nc_serie(nc_serie);
}
if("subTotal".equals(valor)){
String nc_subTotal = atts.getValue(i);
set_nc_subTotal(nc_subTotal);
}
if("tipoDeComprobante".equals(valor)){
String nc_tipoDeComprobante = atts.getValue(i);
set_nc_tipoDeComprobante(nc_tipoDeComprobante);
}
if("total".equals(valor)){
String nc_total = atts.getValue(i);
set_nc_total(nc_total);
}
if("version".equals(valor)){
String nc_version = atts.getValue(i);
set_nc_version(nc_version);
}
if("noCertificado".equals(valor)){
set_nc_noCertificado(atts.getValue(i));
}
}
}
if ("Emisor".equals(qName)) {
for(int i=0; i < atts.getLength();i++){
String valor = atts.getQName(i);
if("nombre".equals(valor)){
String ne_nombre = atts.getValue(i);
set_ne_nombre(ne_nombre);
}
if("rfc".equals(valor)){
String ne_rfc = atts.getValue(i);
set_ne_rfc(ne_rfc);
}
}
}
if ("DomicilioFiscal".equals(qName)) {
for(int i=0; i < atts.getLength();i++){
String valor = atts.getQName(i);
if("calle".equals(valor)){
String df_calle = atts.getValue(i);
set_df_calle(df_calle);
}
if("codigoPostal".equals(valor)){
String df_codigoPostal = atts.getValue(i);
set_df_codigoPostal(df_codigoPostal);
}
if("colonia".equals(valor)){
String df_colonia = atts.getValue(i);
set_df_colonia(df_colonia);
}
if("estado".equals(valor)){
String df_estado = atts.getValue(i);
set_df_estado(df_estado);
}
if("localidad".equals(valor)){
String df_localidad = atts.getValue(i);
set_df_localidad(df_localidad);
}
if("municipio".equals(valor)){
String df_municipio = atts.getValue(i);
set_df_municipio(df_municipio);
}
if("noExterior".equals(valor)){
String df_noExterior = atts.getValue(i);
set_df_noExterior(df_noExterior);
}
if("noInterior".equals(valor)){
String df_noInterior = atts.getValue(i);
set_df_noInterior(df_noInterior);
}
if("pais".equals(valor)){
String df_pais = atts.getValue(i);
set_df_pais(df_pais);
}
if("referencia".equals(valor)){
String df_referencia = atts.getValue(i);
set_df_referencia(df_referencia);
}
}
}
if ("ExpedidoEn".equals(qName)) {
for(int i=0; i < atts.getLength();i++){
String valor = atts.getQName(i);
if("calle".equals(valor)){
String ee_calle = atts.getValue(i);
set_ee_calle(ee_calle);
}
if("codigoPostal".equals(valor)){
String ee_codigoPostal = atts.getValue(i);
set_ee_codigoPostal(ee_codigoPostal);
}
if("colonia".equals(valor)){
String ee_colonia = atts.getValue(i);
set_ee_colonia(ee_colonia);
}
if("estado".equals(valor)){
String ee_estado = atts.getValue(i);
set_ee_estado(ee_estado);
}
if("localidad".equals(valor)){
String ee_localidad = atts.getValue(i);
set_ee_localidad(ee_localidad);
}
if("municipio".equals(valor)){
String ee_municipio = atts.getValue(i);
set_ee_municipio(ee_municipio);
}
if("noExterior".equals(valor)){
String ee_noExterior = atts.getValue(i);
set_ee_noExterior(ee_noExterior);
}
if("noInterior".equals(valor)){
String ee_noInterior = atts.getValue(i);
set_ee_noInterior(ee_noInterior);
}
if("pais".equals(valor)){
String ee_pais = atts.getValue(i);
set_ee_pais(ee_pais);
}
if("referencia".equals(valor)){
String ee_referencia = atts.getValue(i);
set_ee_referencia(ee_referencia);
}
}
}
if ("Receptor".equals(qName)) {
for(int i=0; i < atts.getLength();i++){
String valor = atts.getQName(i);
if("nombre".equals(valor)){
String nr_nombre = atts.getValue(i);
set_nr_nombre(nr_nombre);
}
if("rfc".equals(valor)){
String nr_rfc = atts.getValue(i);
set_nr_rfc(nr_rfc);
}
}
}
if ("Domicilio".equals(qName)) {
for(int i=0; i < atts.getLength();i++){
String valor = atts.getQName(i);
if("calle".equals(valor)){
String nd_calle = atts.getValue(i);
set_nd_calle(nd_calle);
}
if("codigoPostal".equals(valor)){
String nd_codigoPostal = atts.getValue(i);
set_nd_codigoPostal(nd_codigoPostal);
}
if("colonia".equals(valor)){
String nd_colonia = atts.getValue(i);
set_nd_colonia(nd_colonia);
}
if("estado".equals(valor)){
String nd_estado = atts.getValue(i);
set_nd_estado(nd_estado);
}
if("localidad".equals(valor)){
String nd_localidad = atts.getValue(i);
set_nd_localidad(nd_localidad);
}
if("municipio".equals(valor)){
String nd_municipio = atts.getValue(i);
set_nd_municipio(nd_municipio);
}
if("noExterior".equals(valor)){
String nd_noExterior = atts.getValue(i);
set_nd_noExterior(nd_noExterior);
}
if("noInterior".equals(valor)){
String nd_noInterior = atts.getValue(i);
set_nd_noInterior(nd_noInterior);
}
if("pais".equals(valor)){
String nd_pais = atts.getValue(i);
set_nd_pais(nd_pais);
}
if("referencia".equals(valor)){
String nd_referencia = atts.getValue(i);
set_nd_referencia(nd_referencia);
}
}
}
if ("Concepto".equals(qName)) {
for(int i=0; i < atts.getLength();i++){
String valor = atts.getQName(i);
if("cantidad".equals(valor)){
String nc_cantidad = atts.getValue(i);
set_nc_cantidad(nc_cantidad);
}
if("descripcion".equals(valor)){
String nc_descripcion = atts.getValue(i);
set_nc_descripcion(nc_descripcion);
}
if("importe".equals(valor)){
String nc_importe = atts.getValue(i);
set_nc_importe(nc_importe);
}
if("noIdentificacion".equals(valor)){
String nc_noIdentificacion = atts.getValue(i);
set_nc_noIdentificacion(nc_noIdentificacion);
}
if("unidad".equals(valor)){
String nc_unidad = atts.getValue(i);
set_nc_unidad(nc_unidad);
}
if("valorUnitario".equals(valor)){
String nc_valorUnitario = atts.getValue(i);
set_nc_valorUnitario(nc_valorUnitario);
}
}
set_concepto();
}
if ("Impuestos".equals(qName)) {
for(int i=0; i < atts.getLength();i++){
String valor = atts.getQName(i);
if("totalImpuestosRetenidos".equals(valor)){
String totalImpuestosRetenidos = atts.getValue(i);
set_totalImpuestosRetenidos(totalImpuestosRetenidos);
}
if("totalImpuestosTrasladados".equals(valor)){
String totalImpuestosTrasladados = atts.getValue(i);
set_totalImpuestosTrasladados(totalImpuestosTrasladados);
}
}
}
if ("Retencion".equals(qName)) {
for(int i=0; i < atts.getLength();i++){
String valor = atts.getQName(i);
if("importe".equals(valor)){
String nr_importe = atts.getValue(i);
set_nr_importe(nr_importe);
}
if("impuesto".equals(valor)){
String nr_impuesto = atts.getValue(i);
set_nr_impuesto(nr_impuesto);
}
}
set_retencion();
}
if ("Traslado".equals(qName)) {
for(int i=0; i < atts.getLength();i++){
String valor = atts.getQName(i);
if("importe".equals(valor)){
String nt_importe = atts.getValue(i);
set_nt_importe(nt_importe);
}
if("impuesto".equals(valor)){
String nt_impuesto = atts.getValue(i);
set_nt_impuesto(nt_impuesto);
}
if("tasa".equals(valor)){
String nt_tasa = atts.getValue(i);
set_nt_tasa(nt_tasa);
}
}
set_traslado();
}
}
}
private void set_nc_version(String nc_version){
this.nc_version = nc_version;
}
public String get_nc_version(){
return nc_version;
}
private void set_nc_serie(String nc_serie){
this.nc_serie = nc_serie;
}
public String get_nc_serie(){
return nc_serie;
}
private void set_nc_folio(String nc_folio){
this.nc_folio = nc_folio;
}
public String get_nc_folio(){
return nc_folio;
}
private void set_nc_fecha(String nc_fecha){
this.nc_fecha = nc_fecha;
}
public String get_nc_fecha(){
return nc_fecha;
}
private void set_nc_noAprobacion(String nc_noAprobacion){
this.nc_noAprobacion = nc_noAprobacion;
}
public String get_nc_noAprobacion(){
return nc_noAprobacion;
}
private void set_nc_anioAprobacion(String nc_anioAprobacion){
this.nc_anioAprobacion = nc_anioAprobacion;
}
public String get_nc_anioAprobacion(){
return nc_anioAprobacion;
}
private void set_nc_tipoDeComprobante(String nc_tipoDeComprobante){
this.nc_tipoDeComprobante = nc_tipoDeComprobante;
}
public String get_nc_tipoDeComprobante(){
return nc_tipoDeComprobante;
}
private void set_nc_formaDePago(String nc_formaDePago){
this.nc_formaDePago = nc_formaDePago;
}
public String get_nc_formaDePago(){
return nc_formaDePago;
}
private void set_nc_condicionesDePago(String nc_condicionesDePago){
this.nc_condicionesDePago = nc_condicionesDePago;
}
public String get_nc_condicionesDePago(){
return nc_condicionesDePago;
}
private void set_nc_subTotal(String nc_subTotal){
this.nc_subTotal = nc_subTotal;
}
public String get_nc_subTotal(){
return nc_subTotal;
}
private void set_nc_descuento(String nc_descuento){
this.nc_descuento = nc_descuento;
}
public String get_nc_descuento(){
return nc_descuento;
}
private void set_nc_total(String nc_total){
this.nc_total = nc_total;
}
public String get_nc_total(){
return nc_total;
}
private void set_ne_rfc(String ne_rfc){
this.ne_rfc = ne_rfc;
}
public String get_ne_rfc(){
return ne_rfc;
}
private void set_ne_nombre(String ne_nombre){
this.ne_nombre = ne_nombre;
}
public String get_ne_nombre(){
return ne_nombre;
}
private void set_df_calle(String df_calle){
this.df_calle = df_calle;
}
public String get_df_calle(){
return df_calle;
}
private void set_df_noExterior(String df_noExterior){
this.df_noExterior = df_noExterior;
}
public String get_df_noExterior(){
return df_noExterior;
}
private void set_df_noInterior(String df_noInterior){
this.df_noInterior = df_noInterior;
}
public String get_df_noInterior(){
return df_noInterior;
}
private void set_df_colonia(String df_colonia){
this.df_colonia = df_colonia;
}
public String get_df_colonia(){
return df_colonia;
}
private void set_df_localidad(String df_localidad){
this.df_localidad = df_localidad;
}
public String get_df_localidad(){
return df_localidad;
}
private void set_df_referencia(String df_referencia){
this.df_referencia = df_referencia;
}
public String get_df_referencia(){
return df_referencia;
}
private void set_df_municipio(String df_municipio){
this.df_municipio = df_municipio;
}
public String get_df_municipio(){
return df_municipio;
}
private void set_df_estado(String df_estado){
this.df_estado = df_estado;
}
public String get_df_estado(){
return df_estado;
}
private void set_df_pais(String df_pais){
this.df_pais = df_pais;
}
public String get_df_pais(){
return df_pais;
}
private void set_df_codigoPostal(String df_codigoPostal){
this.df_codigoPostal = df_codigoPostal;
}
public String get_df_codigoPostal(){
return df_codigoPostal;
}
private void set_ee_calle(String ee_calle){
this.ee_calle = ee_calle;
}
public String get_ee_calle(){
return ee_calle;
}
private void set_ee_noExterior(String ee_noExterior){
this.ee_noExterior = ee_noExterior;
}
public String get_ee_noExterior(){
return ee_noExterior;
}
private void set_ee_noInterior(String ee_noInterior){
this.ee_noInterior = ee_noInterior;
}
public String get_ee_noInterior(){
return ee_noInterior;
}
private void set_ee_colonia(String ee_colonia){
this.ee_colonia = ee_colonia;
}
public String get_ee_colonia(){
return ee_colonia;
}
private void set_ee_localidad(String ee_localidad){
this.ee_localidad = ee_localidad;
}
public String get_ee_localidad(){
return ee_localidad;
}
private void set_ee_referencia(String ee_referencia){
this.ee_referencia = ee_referencia;
}
public String get_ee_referencia(){
return ee_referencia;
}
private void set_ee_municipio(String ee_municipio){
this.ee_municipio = ee_municipio;
}
public String get_ee_municipio(){
return ee_municipio;
}
private void set_ee_estado(String ee_estado){
this.ee_estado = ee_estado;
}
public String get_ee_estado(){
return ee_estado;
}
private void set_ee_pais(String ee_pais){
this.ee_pais = ee_pais;
}
public String get_ee_pais(){
return ee_pais;
}
private void set_ee_codigoPostal(String ee_codigoPostal){
this.ee_codigoPostal = ee_codigoPostal;
}
public String get_ee_codigoPostal(){
return ee_codigoPostal;
}
private void set_nr_rfc(String nr_rfc){
this.nr_rfc = nr_rfc;
}
public String get_nr_rfc(){
return nr_rfc;
}
private void set_nr_nombre(String nr_nombre){
this.nr_nombre = nr_nombre;
}
public String get_nr_nombre(){
return nr_nombre;
}
private void set_nd_calle(String nd_calle){
this.nd_calle = nd_calle;
}
public String get_nd_calle(){
return nd_calle;
}
private void set_nd_noExterior(String nd_noExterior){
this.nd_noExterior = nd_noExterior;
}
public String get_nd_noExterior(){
return nd_noExterior;
}
private void set_nd_noInterior(String nd_noInterior){
this.nd_noInterior = nd_noInterior;
}
public String get_nd_noInterior(){
return nd_noInterior;
}
private void set_nd_colonia(String nd_colonia){
this.nd_colonia = nd_colonia;
}
public String get_nd_colonia(){
return nd_colonia;
}
private void set_nd_localidad(String nd_localidad){
this.nd_localidad = nd_localidad;
}
public String get_nd_localidad(){
return nd_localidad;
}
private void set_nd_referencia(String nd_referencia){
this.nd_referencia = nd_referencia;
}
public String get_nd_referencia(){
return nd_referencia;
}
private void set_nd_municipio(String nd_municipio){
this.nd_municipio = nd_municipio;
}
public String get_nd_municipio(){
return nd_municipio;
}
private void set_nd_estado(String nd_estado){
this.nd_estado = nd_estado;
}
public String get_nd_estado(){
return nd_estado;
}
private void set_nd_pais(String nd_pais){
this.nd_pais = nd_pais;
}
public String get_nd_pais(){
return nd_pais;
}
private void set_nd_codigoPostal(String nd_codigoPostal){
this.nd_codigoPostal = nd_codigoPostal;
}
public String get_nd_codigoPostal(){
return nd_codigoPostal;
}
private void set_nc_cantidad(String nc_cantidad){
this.nc_cantidad = nc_cantidad;
}
private void set_nc_unidad(String nc_unidad){
this.nc_unidad = nc_unidad;
}
private void set_nc_noIdentificacion(String nc_noIdentificacion){
this.nc_noIdentificacion = nc_noIdentificacion;
}
private void set_nc_descripcion(String nc_descripcion){
this.nc_descripcion = nc_descripcion;
}
private void set_nc_valorUnitario(String nc_valorUnitario){
this.nc_valorUnitario = nc_valorUnitario;
}
private void set_nc_importe(String nc_importe){
this.nc_importe = nc_importe;
}
private void set_concepto(){
String conceptoN="";
conceptoN = nc_cantidad + "|" + nc_unidad +"|" + nc_noIdentificacion + "|" + nc_descripcion + "|" + nc_valorUnitario + "|" + nc_importe;
this.concepto.add(conceptoN);
nc_cantidad = "";
nc_unidad = "";
nc_noIdentificacion = "";
nc_descripcion = "";
nc_valorUnitario = "";
nc_importe = "";
}
public String get_concepto(){
String conceptos = "";
Iterator it = concepto.iterator();
while (it.hasNext()){
conceptos += it.next() + "|";
}
return conceptos;
}
private void set_nr_impuesto(String nr_impuesto){
this.nr_impuesto = nr_impuesto;
}
private void set_nr_importe(String nr_importe){
this.nr_importe = nr_importe;
}
private void set_retencion(){
String retencionN="";
retencionN = nr_impuesto + "|" + nr_importe;
this.retencion.add(retencionN);
nr_impuesto = "";
nr_importe = "";
}
public String get_retencion(){
String retenciones = "";
Iterator it = retencion.iterator();
while (it.hasNext()){
retenciones += it.next() + "|";
}
return retenciones;
}
private void set_totalImpuestosRetenidos(String totalImpuestosRetenidos){
this.totalImpuestosRetenidos = totalImpuestosRetenidos;
}
public String get_totalImpuestosRetenidos(){
return totalImpuestosRetenidos;
}
private void set_nt_impuesto(String nt_impuesto){
this.nt_impuesto = nt_impuesto;
}
private void set_nt_tasa(String nt_tasa){
this.nt_tasa = nt_tasa;
}
private void set_nt_importe(String nt_importe){
this.nt_importe = nt_importe;
}
private void set_traslado(){
String trasladoN="";
trasladoN = nt_impuesto + "|" + nt_tasa + "|" + nt_importe;
this.traslado.add(trasladoN);
nt_impuesto = "";
nt_tasa = "";
nt_importe = "";
}
public String get_traslado(){
String traslados = "";
Iterator it = traslado.iterator();
while (it.hasNext()){
traslados += it.next() + "|";
}
return traslados;
}
private void set_totalImpuestosTrasladados(String totalImpuestosTrasladados){
this.totalImpuestosTrasladados = totalImpuestosTrasladados;
}
public String get_totalImpuestosTrasladados(){
return totalImpuestosTrasladados;
}
public String getCadenaOriginal() {
return ("||" + this.get_nc_version() + "|" + this.get_nc_serie() + "|" + this.get_nc_folio() + "|" + this.get_nc_fecha() + "|" + this.get_nc_noAprobacion() + "|" + this.get_nc_anioAprobacion() + "|" + this.get_nc_tipoDeComprobante() + "|" + this.get_nc_formaDePago() + "|" + this.get_nc_condicionesDePago() + "|" + this.get_nc_subTotal() + "|" + this.get_nc_descuento() + "|" + this.get_nc_total() + "|" + this.get_ne_rfc() + "|" + this.get_ne_nombre() + "|" + this.get_df_calle() + "|" + this.get_df_noExterior() + "|" + this.get_df_noInterior() + "|" + this.get_df_colonia() + "|" + this.get_df_localidad() + "|" + this.get_df_referencia() + "|" + this.get_df_municipio() + "|" + this.get_df_estado() + "|" + this.get_df_pais() + "|" + this.get_df_codigoPostal() + "|" + this.get_ee_calle() + "|" + this.get_ee_noExterior() + "|" + this.get_ee_noInterior() + "|" + this.get_ee_colonia() + "|" + this.get_ee_localidad() + "|" + this.get_ee_referencia() + "|" + this.get_ee_municipio() + "|" + this.get_ee_estado() + "|" + this.get_ee_pais() + "|" + this.get_ee_codigoPostal() + "|" + this.get_nr_rfc() + "|" + this.get_nr_nombre() + "|" + this.get_nd_calle() + "|" + this.get_nd_noExterior() + "|" + this.get_nd_noInterior() + "|" + this.get_nd_colonia() + "|" + this.get_nd_localidad() + "|" + this.get_nd_referencia() + "|" + this.get_nd_municipio() + "|" + this.get_nd_estado() + "|" + this.get_nd_pais() + "|" + this.get_nd_codigoPostal() + "|" + this.get_concepto() + this.get_retencion() + this.get_totalImpuestosRetenidos() + "|" + this.get_traslado() + this.get_totalImpuestosTrasladados() + "||");
}
public void set_nc_noCertificado(String nc_noCertificado) {
this.nc_noCertificado = nc_noCertificado;
}
public String get_nc_noCertificado() {
return nc_noCertificado;
}
February 28, 2010 a las 8:31 pm por Edwin Plauchu · Archivado en Programacion
1.- Primero Activamos los Groovlets
2.- Agregandole Velocity al asunto:
Para esto escribi una clase en java llamanda Plantilla, esta clase recibira un Map, este para los datos que manejaremos en nuestra plantilla para la vista
package agnux.util.web;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
public class Plantilla {
private static VelocityContext convert2context( LinkedHashMap params){
VelocityContext context = new VelocityContext();
Iterator it = params.keySet().iterator();
while (it.hasNext()) {
String key = ( String ) it.next();
String value = ( String ) params.get( key );
context.put(key , value);
}
return context;
}
public static String pegarDatosConPlantilla(String filevm , LinkedHashMap params,HttpServletRequest request){
String valor_retorno = null;
Template template = null;
StringWriter writer = new StringWriter();
VelocityEngine engine = new VelocityEngine();
String servlet_root = request.getSession().getServletContext().getRealPath(”/”);
Properties p = new Properties();
p.setProperty(”resource.loader”, “file”);
p.setProperty(”runtime.log.logsystem.class”, “org.apache.velocity.runtime.log.SimpleLog4JLogSystem”);
p.setProperty(”runtime.log.logsystem.log4j.category”,”org.apache.velocity.runtime.log.SimpleLog4JLogSystem”);
p.setProperty(”file.resource.loader.cache”,”false”);
p.setProperty(”file.resource.loader.modificationCheckInterval”,”2″);
p.setProperty(”file.resource.loader.class”,”org.apache.velocity.runtime.resource.loader.FileResourceLoader”);
p.setProperty(”file.resource.loader.path”,servlet_root + “templates/”);
try {
engine.init(p);
template = engine.getTemplate(filevm);
template.merge( convert2context(params) , writer );
valor_retorno = writer.toString();
} catch( Exception e ) {
System.out.println(”Exception caught: ” + e.toString());
}
return valor_retorno;
}
}
Aqui mi plantilla de velocity “login.vm”: (genere una directorio llamado templates… este esta a mismo nivel que WEB-INF en el arbol de el proyecto).
Y Aqui mi groovlet que manda a llamar la plantilla:
August 23, 2009 a las 7:25 pm por Edwin Plauchu · Archivado en Programacion
Les mando este menu al estilo XP, de mi para ustedes con amor jojojo
Aqui la liga para descargarlo ..es un archivo rar… solo cambiale la extension de DOC a RAR
August 14, 2009 a las 11:48 am por Edwin Plauchu · Archivado en Programacion
Paquetes que fueron requeridos para la instalacion del GCC con Threads support
NOTA: Los paquetes solo pudieron ser instalados siguiendo este orden:
rpm -Uvh libgcc-4.2.4-1.aix5.3.ppc.rpm
rpm -Uvh openssl-0.9.8k-1.aix5.1.ppc.rpm
rpm -Uvh mhash-0.9.2-1.aix5.1.ppc.rpm
rpm -Uvh libstdc++-4.2.4-1.aix5.3.ppc.rpm
rpm -Uvh zlib-1.2.3-5.aix5.1.ppc.rpm
rpm -Uvh lzo-2.03-1.aix5.1.ppc.rpm
rpm -Uvh patch-2.5.9-1.aix5.1.ppc.rpm
rpm -Uvh netcat-1.10-2.aix5.1.ppc.rpm
rpm -Uvh unzip-6.0-1.aix5.1.ppc.rpm
rpm -Uvh gmp-4.3.1-1.aix5.1.ppc.rpm
rpm -Uvh gettext-0.10.40-1.aix5.1.ppc.rpm
rpm -Uvh info-4.6-1.aix5.1.ppc.rpm
rpm -Uvh gcc-4.2.4-1.aix5.3.ppc.rpm
rpm -Uvh expat-2.0.1-2.aix5.1.ppc.rpm
rpm -Uvh gdb-6.8-1.aix5.1.ppc.rpm
rpm -Uvh nano-2.0.7-1.aix5.1.ppc.rpm
rpm -Uvh readline-5.2-2.aix5.1.ppc.rpm
rpm -Uvh flex-2.5.35-1.aix5.1.ppc.rpm
rpm -Uvh gcc-cpp-4.2.4-1.aix5.3.ppc.rpm
rpm -Uvh lzlib-0.5-1.aix5.1.ppc.rpm
rpm -Uvh libstdc++-devel-4.2.4-1.aix5.3.ppc.rpm
rpm -Uvh gcc-c++-4.2.4-1.aix5.3.ppc.rpm
rpm -Uvh emacs-21.3-1.aix5.1.ppc.rpm
rpm -Uvh rpm -Uvh bzip2-1.0.5-1.aix5.1.ppc.rpm
rpm -Uvh zip-3.0-1.aix5.1.ppc.rpm
rpm -Uvh gzip-1.3.12-1.aix5.1.ppc.rpm
rpm -Uvh ncurses-5.6-1.aix5.1.ppc.rpm
rpm -Uvh patchutils-0.3.0-1.aix5.1.ppc.rpm
rpm -Uvh emacs-nox-21.3-1.aix5.1.ppc.rpm
rpm -Uvh pcre-7.9-1.aix5.1.ppc.rpm
Tube la necesidad de ampliar el espacio del punto de montaje /opt, ya que
todos los paquetes rpms, que se instalaron caen dentro de esta ruta
chfs -a size=+131072 /opt
August 13, 2009 a las 4:25 pm por Edwin Plauchu · Archivado en Programacion , FreeBSD
Se pueden tener apuntadores a cualquier tipo de variable.
Para entender perfectamente este desmadre de los apuntadores… aprendete estas reglas magicas:
1.- Un apuntador es una variable que contiene la dirección en memoria de otra variable.
main()
{
int x = 1;
int *ap; //Apuntador que permite
//ser usado con variables enteras
ap = &x; //Se le asigna la direccion
//de memoria que alverga el valor 1
printf("Direccion de el apuntador ap:%x",ap);
}
La consola termina imprimiendonos esto:
Imprime la direccion de el apuntador ap:bf9ed410
2.- Un apuntador puede ser desreferenciado, para accesar a el valor que contiene (a esto se le llama acceso indirecto) esto se logra agregando el * al identificador del apuntador:
main()
{
int x = 1;
int *ap; //Apuntador que permite
//ser usado con variables enteras
ap = &x; //La direccion de memoria de x
//se asigna a la direccion de
// memoria que alberga el apunt
// ador ap
printf("Valor de el apuntador ap:%d",*ap);
}
La consola termina imprimiendonos esto:
Valor de el apuntador ap :1
3.- C no es muy estricto en la asignación de valores de diferente tipo (entero a apuntador - apuntador a entero). Así que es perfectamente legal (aunque el compilador genera un aviso de cuidado).
main()
{
int x;
int y;
int *ap;
y = 3;
ap = y; //Ahora se apunta
// a la localidad de
// memoria 3
x = ap; //Aqui x recibe el valor
//3
printf("Localidad de memoria:%d",x);
}
La consola termina imprimiendonos esto:
Localidad de memoria x :3
4.- No se puede usar un apuntador, si no esta este previamente inicializado
Por lo que:
main()
{
int *ap;
*ap = 100;
}
puede generar un error en tiempo de ejecución o presentar un comportamiento errático.
El uso correcto será:
main()
{
int *ap;
int x;
ap = &x;
*ap = 100;
}
5.- En los apuntadores a estructuras: Se usa la notación p->member
main()
{
typedef struct {
char member_1;
int member_2;
} s_type;
s_type x={'U',2}, *p = &x;
p->member_1 = 'R'; // Equivale a (*p).member_1 = 'R';
//Observece como sacamos el contenido de uno de
// los elementos de la estructura de forma indirecta
printf("Caracter encontrado:%c",(*p).member_1);
}
Imprime en consola
Caracter encontrado:R
Con estas reglas basica ahora podras comprender la fabulosa Aritmetica de punteros