Erro no Class.forName (.....)

11 respostas
O

Bom dia tenho um erro que não consigo resolver alguém pode ajudar?

Código:

package Teste;

import java.sql.*;

public class Teste {

	public static void main(String args[])   {
		String dbtime;
		String dbUrl = "jdbc:unisys:dmsql:Unisys.DMSII:resource=BANCODADOS;" +
				"host=192.120.130.153;" +
				"port=1897;" +
				"user=COELHO;" +
				"password=XXXXX";
		
		String query = "Select * FROM D1";
try {

			Class.forName("com.unisys.jdbc.dmsql.Driver");

			Connection con = DriverManager.getConnection(dbUrl);

			Statement stmt = con.createStatement();

			ResultSet rs = stmt.executeQuery(query);

			while (rs.next()) {
				dbtime = rs.getString(1);
				System.out.println(dbtime);
			} // end while

			con.close();

	} catch (SQLException sqle){
		System.err.println("sql error = " + sqle);
		sqle.printStackTrace();
		
	} catch (Exception e){
		System.err.println("error = " + e);
		e.printStackTrace();
	}


	} // end main

} // end class

Erro é o seguinte:

Exception in thread “main” java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at Teste.Teste.main(Teste.java:17)
Caused by: java.lang.NullPointerException
at java.io.Reader.(Reader.java:78)
at java.io.InputStreamReader.(InputStreamReader.java:72)
at com.unisys.jdbc.dmsql.JDBCProperties.initSettings(JDBCProperties.java:240)
at com.unisys.jdbc.dmsql.JDBCProperties.getProp(JDBCProperties.java:268)
at com.unisys.jdbc.dmsql.Driver.(Driver.java:87)
… 3 more

11 Respostas

J

Segue um exemplo de de um gerenciador de conexão com o banco, adapta ele para oque você precisa e vê se te ajuda, aí quando vc precisar de uma Connection com o banco vc só chama o método getConnection().

package daos;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author josimar
 */
//public class ConnectionManager {
//}
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author josimar
 */
public class ConnectionManager {

    private Connection connection;
    private static Driver driverMySql;

    public Connection getConnection() throws SQLException {
        if (connection == null) {
            criaConexao();
        }
        return connection;

    }

    private void criaConexao() throws SQLException {
        driverMySql = new com.mysql.jdbc.Driver();
        DriverManager.registerDriver(driverMySql);
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/base", "user", "senha");
    }

    public void fechaConexao() throws SQLException {
        if (connection != null) {
            connection.close();
            DriverManager.deregisterDriver(driverMySql);
        }
    }
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        if(connection!=null){
        connection.close();
        DriverManager.deregisterDriver(driverMySql);
        }
    }
    
}
O

Obrigado Josiloch.

Fiz as alterações que recomendou mas o erro persiste.

------------------------------------------------------------------------------------------------

Exception in thread "main" java.lang.ExceptionInInitializerError
at Teste.ConnectionManager.criaConexao(ConnectionManager.java:26)
at Teste.ConnectionManager.getConnection(ConnectionManager.java:19)
at Teste.Teste.main(Teste.java:17)
Caused by: java.lang.NullPointerException
at java.io.Reader.(Reader.java:78)
at java.io.InputStreamReader.(InputStreamReader.java:72)
at com.unisys.jdbc.dmsql.JDBCProperties.initSettings(JDBCProperties.java:240)
at com.unisys.jdbc.dmsql.JDBCProperties.getProp(JDBCProperties.java:268)
at com.unisys.jdbc.dmsql.Driver.(Driver.java:87)
... 3 more
--------------------------------------------------------------------------------------------------

Transcrevo em baixo a classe Driver.

package com.unisys.jdbc.dmsql;

import java.io.Serializable;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.util.Properties;
import java.util.StringTokenizer;

public class Driver
  implements java.sql.Driver
{
  private static IDriver iDriver = null;

  private static String valNative = "MDriver";
  private static final String PRODUCTVERSION = "1,0";
  private static String defaultDMSQL = JDBCProperties.getProp(JDBCProperties.dmsqlProgid, defaultDMSQL);
  static final String id = "jdbcformcp";
  private static String strPackage = "com.unisys.jdbc.dmsql.";

  private static String strConnection = "Connection";

  static Driver globalDriver = null;

  public boolean acceptsURL(String url)
    throws java.sql.SQLException
  {
    Trace t = null;

    boolean result = (url.length() >= "jdbc:unisys:dmsql".length()) && ("jdbc:unisys:dmsql".equals(url.substring(0, "jdbc:unisys:dmsql".length())));

    return result;
  }

  public java.sql.Connection connect(String url, Properties info)
    throws java.sql.SQLException
  {
    if (info == null) {
      info = new Properties();
    }

    StringBuffer dmsqlProgId = new StringBuffer();
    if (!loadServer(url, dmsqlProgId, info)) {
      return null;
    }

    IConnection iConn = iDriver.connect(info);

    return new Connection(iConn, dmsqlProgId.toString(), url);
  }

  private boolean loadServer(String url, StringBuffer dmsqlProgId, Properties info)
    throws java.sql.SQLException
  {
    Trace t = null;

    if (!acceptsURL(url))
    {
      return false;
    }

    StringTokenizer token = new StringTokenizer(url, ":");
    for (int i = 0; i < 3; i++) {
      token.nextToken();
    }

    String progId = defaultDMSQL;
    if (token.hasMoreTokens()) {
      progId = token.nextToken();
    }
    dmsqlProgId.append(progId);

    String strProp = null;
    if (token.hasMoreTokens())
      strProp = token.nextToken();
    else if (info.size() == 0) {
      strProp = JDBCProperties.getProp(JDBCProperties.dmsqlProperties, null);
    }

    if (strProp != null) {
      StringTokenizer tokProp = new StringTokenizer(strProp, ";", false);
      while (tokProp.hasMoreTokens()) {
        String prop = tokProp.nextToken();
        StringTokenizer tokValue = new StringTokenizer(prop, "=", false);
        if (tokValue.hasMoreTokens()) {
          String key = tokValue.nextToken();
          String value = "";
          if (tokValue.hasMoreTokens()) {
            value = tokValue.nextToken("").substring(1);
          }

          if (key.equalsIgnoreCase("Extended Properties")) {
            StringBuffer bufValue = new StringBuffer(value);
            int inx = value.indexOf(',');
            while (inx != -1) {
              bufValue.setCharAt(inx, ';');
              inx = value.indexOf(',', inx + 1);
            }
            value = bufValue.toString();
          }

          info.put(key, value);
        }

      }

    }

    if (iDriver == null) {
      try {
        iDriver = (IDriver)Class.forName(strPackage + valNative).newInstance();
      }
      catch (ClassNotFoundException e)
      {
        throw new SQLException(1000036, new Object[] { valNative });
      }
      catch (InstantiationException e)
      {
        throw new SQLException(1000037, new Object[] { e.getMessage() });
      }
      catch (IllegalAccessException e)
      {
        throw new SQLException(1000037, new Object[] { e.getMessage() });
      }
    }

    return true;
  }

  public int getMajorVersion()
  {
    StringTokenizer tok = new StringTokenizer("1,0", ",");
    String major = tok.nextToken();
    return Integer.parseInt(major);
  }

  public int getMinorVersion()
  {
    StringTokenizer tok = new StringTokenizer("1,0", ",");
    tok.nextToken();
    String minor = tok.nextToken();
    return Integer.parseInt(minor);
  }

  public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
    throws java.sql.SQLException
  {
    Trace t = null;

    if (info == null) {
      info = new Properties();
    }

    StringBuffer dmsqlProgId = new StringBuffer();
    if (!loadServer(url, dmsqlProgId, info))
    {
      return null;
    }

    DriverPropertyInfo[] mvProp = iDriver.getPropertyInfo(info);

    DriverPropertyInfo[] result = new DriverPropertyInfo[mvProp.length];
    for (int i = 0; i < mvProp.length; i++) {
      result[i] = new DriverPropertyInfo(mvProp[i].name, mvProp[i].value);
      result[i].required = mvProp[i].required;
      result[i].choices = mvProp[i].choices;
    }

    return result;
  }

  public boolean jdbcCompliant()
  {
    return false;
  }

  static
  {
    globalDriver = new Driver();
    try {
      DriverManager.registerDriver(globalDriver);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  static class DriverPropertyInfo
    implements Serializable
  {
    String name = null;
    String value = null;
    boolean required = false;
    String[] choices = null;

    public String toString() { return this.name + "=" + this.value; }

  }
}

Obrigado.

A

O erro está aqui

private static String defaultDMSQL = JDBCProperties.getProp(JDBCProperties.dmsqlProgid, defaultDMSQL);

Repare que você inicializa a variável defaultDMSQL usando ela mesma para passar ao método JDBCProperties.getProp. Como ela não foi inicializada, ela vai como null e por isso você tem o NullPointerException.

Era só ler a mensagem de erro, estava na cara:

<blockquote>Caused by: java.lang.NullPointerException

at java.io.Reader.(Reader.java:78)

at java.io.InputStreamReader.(InputStreamReader.java:72)

at com.unisys.jdbc.dmsql.JDBCProperties.initSettings(JDBCProperties.java:240)

at com.unisys.jdbc.dmsql.JDBCProperties.getProp(JDBCProperties.java:268)

at com.unisys.jdbc.dmsql.Driver.(Driver.java:87) </blockquote>
O

Obrigado Ataxexe.

Mas não fui eu que fiz essa classe, ela é a classe decompilada do conetor de DMSII da Unisys.

Continuamos com o erro :frowning:

A

olitree:
Obrigado Ataxexe.

Mas não fui eu que fiz essa classe, ela é a classe decompilada do conetor de DMSII da Unisys.

Entendo, mas note que eu também não fiz a classe e mesmo assim consegui ver o erro.

Não estou sendo grosso e nem quero dar puxão de orelha. Só queria mostrar que o erro estava bem à mostra no stacktrace. Os NullPointerExceptions não são complicados de se resolver porque são mais fáceis de detectar (inclusive, alguns compiladores geram alertas ou erros em casos de NullPointerExceptions prováveis ou certos).

Ah! E cuidado ao descompilar classes. Algumas coisas podem se perder no meio do caminho (os syntax sugars, por exemplo) e outras podem vir meio bizarras dependendo do decompilador (métodos genéricos, por exemplo).

Mas como você solucionou o erro? Se colocou um valor null ali dentro em vez da variável vai continuar dando NPE.

O

Obrigado Ataxexe.

Não está fácil de resolver não.
Já segui o manual step by step e nada.

O compilador que uso é

http://java.decompiler.free.fr/

Abraços

A

Tente olhar a classe JDBCProperties pra ver como ela funciona e qual é o comportamento do getProp.

Uma dúvida: por quê está descompilando esse driver? Ele está com algum problema ou você quer implementar algo novo nele?

O

Só descompilei para consultar o código nada mais.

Porque se faço tudo direitinho como diz no Manual da Unisys porque não funciona)

:slight_smile:

Att,

António Oliveira

O

[color=darkblue]JDBCProperties[/color]

package com.unisys.jdbc.dmsql;

import com.unisys.dmsql.provider.Config;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Properties;

public class JDBCProperties
{
  private static Properties props = null;
  private static final String configName = "jdbcformcp.properties";
  private static final String configDir = System.getProperty("user.home") + File.separator + ".dmsql";

  private static final String configPath = configDir + File.separator + "jdbcformcp.properties";

  static String blobBlocksize = "blob.blocksize";

  static String dmsqlProgid = "dmsql.progid";

  static String dmsqlProperties = "dmsql.properties";

  private static synchronized String makeProviderDir()
  {
    File f = new File(configDir);
    f.mkdirs();
    return configDir;
  }
  private static synchronized void initSettings() {
    if (props != null) return;
    boolean f = true;
    props = new Properties();
    try {
      InputStream is = new FileInputStream(configPath);
      props.load(is);
    } catch (IOException ie) {
      f = false;
    }
    if (!f) {
      f = true;
      try {
        makeProviderDir();
        ClassLoader cl = Config.class.getClassLoader();
        InputStream is = cl.getResourceAsStream("jdbcformcp.properties");
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        OutputStream os = new FileOutputStream(configPath);
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
        String l;
        while ((l = r.readLine()) != null) {
          if ((l.length() > 0) && (l.charAt(0) != '#')) {
            pw.print('#');
          }
          pw.println(l);
        }
        pw.close();
      } catch (IOException ie) {
        f = false;
        ie.printStackTrace();
      }
    }
  }

  static String getProp(String prop, String def)
  {
    if (props == null) {
      initSettings();
    }

    return props.getProperty(prop, def);
  }

  static int getInt(String prop, int def)
  {
    String str = getProp(prop, null);
    if (str == null)
      return def;
    try
    {
      return Integer.decode(str).intValue(); } catch (NumberFormatException e) {
    }
    return def;
  }

  static boolean getBoolean(String prop, boolean def)
  {
    boolean result = def;
    String val = getProp(prop, null);
    if (val != null) {
      if (val.equalsIgnoreCase("true"))
        result = true;
      else if (val.equalsIgnoreCase("false")) {
        result = false;
      }
    }
    return result;
  }
}
O

Outra abordagem e o mesmo erro:

package Teste;

import java.sql.*;
import java.util.Properties;

public class Teste {

	public static void main(String args[])   {
		String dbtime;
		String dbUrl = "jdbc:unisys:dmsql:Unisys.DMSII:resource=BANCODADOS;" +
				"host=172.120.130.153;" +
				"port=1897;";
	
		String query = "Select * FROM D1";
		
		System.setProperty("jdbc.drivers","com.unisys.jdbc.dmsql.Driver");
	
		Properties prop = new Properties();
		prop.put("user","COELHO");
		prop.put("password","XXXXX");

		  try {  

		
		              Connection con = DriverManager.getConnection(dbUrl,prop);  
		    
		              
		              Statement stmt = con.createStatement();  
		    
		              ResultSet rs = stmt.executeQuery(query);  
		    
		              while (rs.next()) {  
		                  dbtime = rs.getString(1);  
		                  System.out.println(dbtime);  
		              } 
		    
		              con.close();  
		    
		      } catch (SQLException sqle){  
		          System.err.println("sql error = " + sqle);  
		          sqle.printStackTrace();  
		            
		      } catch (Exception e){  
		          System.err.println("error = " + e);  
		          e.printStackTrace();  
		      }  
		    
		    
		      } 
		    
		  }

Erro:

Exception in thread main java.lang.ExceptionInInitializerError

at java.lang.Class.forName0(Native Method)

at java.lang.Class.forName(Class.java:264)

at java.sql.DriverManager.loadInitialDrivers(DriverManager.java:538)

at java.sql.DriverManager.(DriverManager.java:99)

at Teste.Teste.main(Teste.java:25)

Caused by: java.lang.NullPointerException

at java.io.Reader.(Reader.java:78)

at java.io.InputStreamReader.(InputStreamReader.java:72)

at com.unisys.jdbc.dmsql.JDBCProperties.initSettings(JDBCProperties.java:240)

at com.unisys.jdbc.dmsql.JDBCProperties.getProp(JDBCProperties.java:268)

at com.unisys.jdbc.dmsql.Driver.(Driver.java:87)

 5 more
A

Analise o método initSettings com um depurador. Será bem mais simples ver o que ocasiona o NullPointer (já que você descompilou as classes).

Acredito que você não tem um arquivo jdbcformcp.properties no projeto

InputStream is = cl.getResourceAsStream("jdbcformcp.properties");

Da própria documentação do método getResourceAsStream:

Se o arquivo não existir, será retornado nulo. Neste trecho será lançada uma NPE:

BufferedReader r = new BufferedReader(new InputStreamReader(is));

Que bate com o erro no stacktrace:

Criado 18 de dezembro de 2012
Ultima resposta 18 de dez. de 2012
Respostas 11
Participantes 3