Mostrando entradas con la etiqueta Java. Mostrar todas las entradas
Mostrando entradas con la etiqueta Java. Mostrar todas las entradas

martes, 2 de diciembre de 2014

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present

¡Problemas para consumir un Web Services con SSL!!...

dump Error:
"Exception in thread "main" com.sun.xml.internal.ws.client.ClientTransportException: HTTP transport error: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names matching IP address IP found"

Explicación del problema:

No subject alternative names present

Sample Alt Name Stack Trace
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present
In most cases this is a hostname/SSL certificate CN mismatch. This commonly happens when a self-signed certificate issued to localhost is placed on a machine that is accessed by IP address. It should be noted that generating a certificate with an IP address for a common name, e.g. CN=192.168.1.1,OU=Middleware,dc=vt,dc=edu, will not work in most cases where the client making the connection is Java. For example the Java CAS client will throw SSL errors on connecting to a CAS server secured with a certificate containing an IP address in the CN.


La Solución es sobre escribir el método Java de verificación del HostName sobre la aplicación que consume el Web Service de la siguiente manera:
  static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) {
        if (hostname.equals("IP.IP.IP.IP")) {
          return true;
        }
        return false;
      }
    });
  }


Saludos!! Armando Mateu.

jueves, 17 de julio de 2014

Como eliminar la ultima linea en blanco de un archivo con Java


Este programa muestra como eliminar el ultimo salto de línea de un archivo utilizando RandomAccessFile, sin la necesidad de recorrerlo línea por línea, esto es muy rápido y útil para archivos con más de 100 Mb que no se pueden abrir fácilmente y es mas tardado abrir el archivo para eliminar la linea a mano que utilizando este programa.

Código Java:

El programa recibe como parámetro un nombre de un archivo, que  buscara y validara que su ultima línea sea retorno de carro “\r” y la borrara.
Ejemplo:


Como ejecutar el ejecutar el programa desde una consola o terminal:

Java –jar UltimoSpacio.jar PRUEBA.txt



Si no eres mucho de utilizar la consola utiliza este pequeño bat :

@ECHO OFF 
SET /P file=Nombre del Archivo: 
java -jar UltimoSpacio.jar %file%
pause
exit

Ejecución del BAT:


Saludos !!
Armando Mateu.

martes, 28 de mayo de 2013

ABAP + Transacción SM69 o SM49 + TELNET + Script + Java


Hola que tal a todos lo lectores de este blogg, como bien saben la finalidad de este espacio es para contar mis historias, ayudas, memorias, notas, etc y compartir la solución a diversas situaciones.

Conocimientos previos:

-Unix ( especialmente en Bash )
-Comunicaciones TCP/IP
-Sockets
-Java
-ABAP

La problemática:
Surgió la "necesidad" de comunicar en un sistema SAP R/3, que por medio de un programa "ABAP", se conectara a un Socket (IP / PORT)  y es aquí donde surgió la polémica discusión   

:::: no!! se puede,
:::::si!! se puede,
::::::que no!! se puede...


y salieron las palabras "TE RETO A QUE LO HAGAS..." ( chan chan chan chaaan )

Mi respuesta fue:


jueves, 25 de abril de 2013

Combinar datos , eliminar Duplicados y Ordenarlos con List, HashSet y SortedSet JAVA





        String[] arr = {"1", "2", "3", "3"};
        List<String> lista1 = java.util.Arrays.asList(arr);
        List<String> lista2 = java.util.Arrays.asList("8", "6", "5");

        List<String> combinar = new ArrayList<String>();
        combinar.addAll(lista1);
        combinar.addAll(lista2);

        for (String s : combinar) {
            System.out.print(s + " ");
        }
        System.out.println();

        HashSet duplicado = new HashSet();
        duplicado.addAll(combinar);

        Iterator iterador = duplicado.iterator();
        while (iterador.hasNext()) {
            String elemento = (String) iterador.next();
            System.out.print(elemento + " ");
        }
        System.out.println();

        SortedSet ordenado = new TreeSet();
        ordenado.addAll(duplicado);

        iterador = ordenado.iterator();
        while (iterador.hasNext()) {
            String elemento = String.valueOf(iterador.next());
            System.out.print(elemento + " ");
        }
        System.out.println();




Salida:
1 2 3 3 8 6 5
3 2 1 6 5 8
1 2 3 5 6 8


Saludos!!
Armando Mateu

lunes, 15 de abril de 2013

Applet + MySQL ... Usar un Applet y Conectar a MySQL



Usar un Applet y Conectar a MySQL


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import javax.swing.table.DefaultTableModel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author ahmateu
 */
public class Principal extends javax.swing.JApplet {

    /**
     * Initializes the applet Principal
     */
    @Override
    public void init() {
        /* 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(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.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();
                }
            });

miércoles, 6 de febrero de 2013

Fechas en Java fácil o dificil?

Metodo logico Dificil():


    public static String fecha() {
        Date fecha = new Date();
        String f = "";
        String d = "";
        String m = "";
        String min = "";
        String hr = "";

        int dia = fecha.getDate();
        int minuto = fecha.getMinutes();
        int segundos = fecha.getSeconds();
        int mes = fecha.getMonth() + 1;
        int hora = fecha.getHours();

        if (dia < 10) {
            d = "0" + dia;
        } else {
            d = "" + dia;
        }
        if (minuto < 10) {
            min = "0" + minuto;
        } else {
            min = "" + minuto;
        }
        if (mes < 10) {
            m = "0" + mes;
        } else {
            m = "" + mes;
        }

martes, 20 de diciembre de 2011

Leer Atributos de una Etiqueta XML

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;


public class LeerAtributoXML {
  public static void main(String[] argv) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();

miércoles, 7 de diciembre de 2011

Clase Java FTP

Para los envíos, descargas y navegación desde java en FTP solo hace falta instalar la librería de Oracle FTP y lista .

package FTP;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;


/**
 *
 * @author ahmateu
 */
public class FTP {
    /**
     *
     @param ftp es la instanci para la calse de FTP
     */
    public static FTPClient ftp = null;
    private static FileInputStream fis = null;
    private static FileOutputStream fos = null;
   
    private static String ip = "";
    private static String user = "";
    private static String pass = "";
    private static String localFile = "";