Close URL Connection netstat

hello all,
I hope you can help me.
Please have a look at my code below
I open an URL Connection but I can't close it.
If i type in a DOS Box netstat I see a lot of connection.
Now my question is how can I close the connection.
m_http.disconnect() seems not to work.
public class Unbenannt1 extends Applet
  Button button1 = new Button();
  private HttpURLConnection m_http = null;
  private URL m_MyAlarmURL = null;
  private URLConnection m_MyURLConnection = null;
  private long m_TimeAlarmXML = 0;
  private boolean m_TimeUpdate = true;
  /**Das Applet initialisieren*/
  public void init()
    String a_str = "http://"+ getCodeBase().getHost() + "/x.xml";
    try
      m_MyAlarmURL = new URL( a_str );
    catch ( MalformedURLException ie )
    try
      jbInit();
    catch(Exception e)
      e.printStackTrace();
  /**Initialisierung der Komponenten*/
  private void jbInit() throws Exception
    button1.setLabel("button1");
    button1.setBounds(new Rectangle(27, 28, 78, 27));
    button1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        button1_actionPerformed(e);
    setLayout(null);
    setBackground(java.awt.Color.lightGray);
    setSize(426,266);
    this.add(button1, null);
  void button1_actionPerformed(ActionEvent e)
    int a_int = 0;
    try
        m_MyURLConnection = m_MyAlarmURL.openConnection();
        m_http = (HttpURLConnection)m_MyURLConnection;
        m_http.setRequestMethod( "HEAD" );
        m_http.setUseCaches(false);
        m_http.connect();
        a_int = m_http.getResponseCode();
        m_http.disconnect();
        m_http = null;
        m_MyURLConnection = null;
        System.gc();
      catch ( java.io.IOException ioe  )
        a_int = 404;
}Thanks a lot
Prediger

Usually those connections linger around for some time, and will then be closed by the OS once a certain timeout has been reached. I don't know how to change that timeout, though.
Btw: the docs don't claim that the connection will be closed. The description for disconnect() is "Indicates that other requests to the server are unlikely in the near future"
If you still see the connection after a while, then something is wrong, but I've seen connections like that hang around for several minutes even after the JVM was terminated.
Thomas

Similar Messages

  • HttpsURLConnection URL connection issue

    Hi All,
    I need to create URL connection with HTTPS URL. I can run Main java class successfully in machine which hosted in SAP Java server, but fail to run integrate it with e-commence application. When depployed in to SAP Java server cannot open HttpsURLConnection and always return CalssCastexception. However same code run as Java Main class
    Is this can be a (SSL) Handshake? or is this SSL issue?
    MyCode:
    String httpsURL = "https://encrypted.google.com/";
        URL myurl = new URL(httpsURL);
        HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
        InputStream ins = con.getInputStream();
        InputStreamReader isr = new InputStreamReader(ins);
        BufferedReader in = new BufferedReader(isr);
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
          System.out.println(inputLine);
        in.close();
    Thank You

    This is purely ssl issue. You can try adding the below logic first.. This code basically sets ssl properties for us.
    import java.security.Security;
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    Properties properties = System.getProperties();
    String handlers = System.getProperty("java.protocol.handler.pkgs");
    if (handlers == null) {
        // nothing specified yet (expected case)
        properties.put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    else {
        // something already there, put ourselves out front
        properties.put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol|".concat(handlers));     
    System.setProperties(properties);
    Below you start your code....

  • Do I close my connection yet? How to improve it

    Hi all,
    my connection pool is not working well, the connection is not release back to pool. why??
    package formate;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import javax.sql.*;
    import pool.ConnectionPool;
    * TryJdbc.java
    * This servlet demonstrates using JDBC
    public class Formate extends HttpServlet {
       Statement stmt =null;
        ResultSet rs = null;
        Connection conn = null;
      ConnectionPool connectionPool = null;
    * Creates a connection pool.
    public void init() throws ServletException
    String jdbcDriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    String dbURL ="jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sequences";
    try
    //instantiate the connection pool object by passing the
    //jdbc driver, database URL, username, and password
    connectionPool = new ConnectionPool(jdbcDriver, dbURL,
    "A#$","RE@89");
    //specify the initial number of connections to establish
    connectionPool.setInitialConnections(5);
    //specify number of incremental connections to create if
    //pool is exhausted of available connections
    connectionPool.setIncrementalConnections(5);
    //specify absolute maximum number of connections to create
    connectionPool.setMaxConnections(20);
    connectionPool.createPool(); //create the connection pool
    catch(Exception e)
    System.out.println("Error: " + e);
    }in my doget I have
    conn = connectionPool.getConnection();
         stmt = conn.createStatement();
    ...query
    finally {
    try {
    if(rs != null)
    rs.close();
    rs = null;
    if(stmt != null)
    stmt .close();
    stmt = null;
    if(conn != null)
    conn.close();
    conn = null;
    connection.returnConnection(conn); }
    package pool;
    import java.sql.*;
    import java.util.*;
    public class ConnectionPool
    private String jdbcDriver = "";
    private String dbUrl = "";
    private String dbUsername = "";
    private String dbPassword = "";
    private int initialConnections = 10;
    private int incrementalConnections =5;
    private int maxConnections = 50;
    private Vector connections = null;
    * Constructor stores the parameters passed by the calling
    * object.
    * @param jdbcDriver String containing the fully qualified name
    * of the jdbc driver (class name and full package info)
    * @param dbUrl String containing the database URL
    * @param dbUsername String containing the username to use when
    * logging into the database
    * @param dbPassword String containing the password to use when
    * logging into the database
    public ConnectionPool(String jdbcDriver, String dbUrl,
    String dbUsername, String dbPassword)
    this.jdbcDriver = jdbcDriver;
    this.dbUrl = dbUrl;
    this.dbUsername = dbUsername;
    this.dbPassword = dbPassword;
    * Returns the initial number of connections to create.
          * @return Initial number of connections to create.
    public int getInitialConnections()
    return initialConnections;
          * Sets the initial number of connections to create.
    * @param initialConnections Initial number of connections to
    * create
    public void setInitialConnections(int initialConnections)
    this.initialConnections = initialConnections;
    * Returns the number of incremental connections to create if
    * the initial connections are all in use.
    * @return Number of incremental connections to create.
    public int getIncrementalConnections()
    return incrementalConnections;
    * Sets the number of incremental connections to create if
    * the initial connections are all in use.
    *@param incrementalConnections Number of incremental
    * connections to create.
    public void setIncrementalConnections(
    int incrementalConnections)
    this.incrementalConnections = incrementalConnections;
    * Returns the absolute maximum number of connections to
          * create. If all connections are in use, the getConnection()
    * method will block until one becomes free.
    * @return Maximum number of connections to create.
    public int getMaxConnections()
    return maxConnections;
    * Sets the absolute maximum number of connections to create.
    * If all connections are in use, the getConnection() method
    * will block until one becomes free.
    * @param maxConnections Maximum number of connections to
    * create.
    public void setMaxConnections(int maxConnections)
    this.maxConnections = maxConnections;
    * Creates a pool of connections. Number of connections is
    * determined by the value of the initialConnections property.
    public synchronized void createPool() throws Exception
    //make sure that createPool hasn't already been called
    if (connections!=null)
    return; //the pool has already been created, return
    //instantiate JDBC driver object from init param jdbcDriver
    Driver driver = (Driver)
    (Class.forName(jdbcDriver).newInstance());
    DriverManager.registerDriver(driver); //register JDBC driver
    connections = new Vector();
    //creates the proper number of initial connections
    createConnections(initialConnections);
    * Creates the specified number of connections, places them in
    * a PooledConnection object, and adds the PooledConnection to
    * the connections vector.
    * @param numConnections Number of connections to create.
    private void createConnections(int numConnections) throws
    SQLException
    //create the specified number of connections
    for (int x=0; x < numConnections; x++)
    //have the maximum number of connections been created?
    //a maxConnections value of zero indicates no limit
    if (maxConnections > 0 &&
    connections.size() >= maxConnections)
    break; //break out of loop because we're at the maximum
    //add a new PooledConnection object to connections vector
    connections.addElement(new PooledConnection(
    newConnection()));
    System.out.println("Database connection created...");
    * Creates a new database connection and returns it.
    * @return New database connection.
    private Connection newConnection() throws SQLException
    //create a new database connection
    Connection conn = DriverManager.getConnection (dbUrl,
    dbUsername, dbPassword);
    //if this is the first connection, check the maximum number
    //of connections supported by this database/driver
    if (connections.size()== 0)
    DatabaseMetaData metaData = conn.getMetaData();
    int driverMaxConnections = metaData.getMaxConnections();
    //driverMaxConnections value of zero indicates no maximum
    //or unknown maximum
    if (driverMaxConnections > 0 &&
    maxConnections > driverMaxConnections)
    maxConnections = driverMaxConnections;
    return conn; //return the new connection
    * Attempts to retrieve a connection from the connections
    * vector by calling getFreeConnection(). If no connection is
    * currently free, and more can not be created, getConnection()
    * waits for a short amount of time and tries again.
    * @return Connection object
    public synchronized Connection getConnection()throws
    SQLException
    //make sure that createPool has been called
    if (connections == null)
    return null; //the pool has not been created
    Connection conn = getFreeConnection();//get free connection
    while (conn == null) //no connection was currently free
    //sleep for a quarter of a second and then check to see if
    //a connection is free
    wait(250);
    conn = getFreeConnection(); //try again to get connection
    return conn;
    * Returns a free connection from the connections vector. If no
    * connection is available, a new batch of connections is
    * created according to the value of the incrementalConnections
    * variable. If all connections are still busy after creating
    * incremental connections, the method will return null.
    * @return Database connection object
    private Connection getFreeConnection() throws SQLException
    //look for a free connection in the pool
    Connection conn = findFreeConnection();
    if (conn == null)
    //no connection is free, create additional connections
    createConnections(incrementalConnections);
    //try again to find a free connection
    conn = findFreeConnection();
    if (conn == null)
    //there are still no free connections, return null
    return null;
    return conn;
    * Searches through all of the pooled connections looking for
    * a free connection. If a free connection is found, its
    * integrity is verified and it is returned. If no free
    * connection is found, null is returned.
    * @return Database connection object.
    private Connection findFreeConnection()throws SQLException
    Connection conn = null;
    PooledConnection pConn = null;
    Enumeration enum = connections.elements();
    //iterate through the pooled connections looking for free one
    while (enum.hasMoreElements())
    pConn =(PooledConnection)enum.nextElement();
    if (!pConn.isBusy())
    //this connection is not busy, get a handle to it
    conn = pConn.getConnection();
    pConn.setBusy(true); //set connection to busy
    //connection is no longer valid, create a new one
    conn = newConnection();
    //replace invalid connection with new connection
    pConn.setConnection(conn);
    break; //we found a free connection, stop looping
    return conn;
    * Test the connection to make sure it is still valid. If not,
    * close it and return FALSE.
    * @param conn Database connection object to test.
    * @return True indicates connection object is valid.
    * Turns off the busy flag for the current pooled connection.
    * All ConnectionPool clients should call returnConnection() as
    * soon as possible following any database activity (within a
    * finally block).
    * @param conn Connection object
    public void returnConnection(Connection conn)
    //make sure that createPool has been called
    if (connections== null)
    return; //the pool has not been created
    PooledConnection pConn = null;
    Enumeration enum = connections.elements();
    //iterate through the pooled connections looking for the
    //returned connection
    while (enum.hasMoreElements())
    pConn =(PooledConnection)enum.nextElement();
    //determine if this pooled connection contains the returned
    //connection
    if (conn == pConn.getConnection())
    //the connection has been returned, turn off busy flag
    pConn.setBusy(false);
    break;
    * Refreshes all of the connections in the connection pool.
    public synchronized void refreshConnections()throws
    SQLException
    //make sure that createPool has been called
    if (connections == null)
    return; //the pool has not been created
    PooledConnection pConn = null;
    Enumeration enum = connections.elements();
    while (enum.hasMoreElements())
    pConn =(PooledConnection)enum.nextElement();
    if (!pConn.isBusy())
    wait(10000); //wait 5 seconds
    closeConnection(pConn.getConnection());
              pConn.setConnection(newConnection());
              pConn.setBusy(false);
    * Closes all of the connections and empties the connection
    * pool. Once this method has been called, the createPool()
    * method can again be called.
    public synchronized void closeConnections() throws SQLException
    //make sure that createPool has been called
    if (connections == null)
    return; //the pool has not been created
    PooledConnection pConn = null;
    Enumeration enum = connections.elements();
    while (enum.hasMoreElements())
    pConn = (PooledConnection)enum.nextElement();
    if (!pConn.isBusy())
    wait(5000); //wait 5 seconds
    closeConnection(pConn.getConnection());
    connections.removeElement(pConn);
    connections = null;
    * Closes a database connection.
    * @param conn Database connection to close.
    private void closeConnection(Connection conn)
    try
    conn.close();
    catch (SQLException e)
    * Sleeps for a specified number of milliseconds.
    *@param mSeconds Number of seconds to sleep.
    private void wait(int mSeconds)
    try
    Thread.sleep(mSeconds);
    catch (InterruptedException e)
    * Inner class encapsulating the properties of a pooled
    * connection object. These properties include a JDBC database
    * connection object and a flag indicating whether or not the
    * database object is currently in use (busy).
    class PooledConnection
    Connection connection = null;
    boolean busy = false;
    public PooledConnection(Connection connection)
    this.connection = connection;
    public Connection getConnection()
    return connection;
    public void setConnection(Connection connection)
    this.connection = connection;
    public boolean isBusy()
    return busy;
    public void setBusy(boolean busy)
    this.busy = busy;
    }thank you

    If you are using connection pooling then those places in your code where you used to close a connection need to be replaced by code that returns the connection to the pool.
    It's the job of the pool implementation to decide whether or not connections need closing (or opening), depending on the rules you set up for the pooler.

  • Opening URL Connection

    Hi all,
    I'm having a problem when connecting to a URL that is non-esisting using a while loop to catch the exception but no exception is being thrown.
    while(myConn == null || !found)
    try
    myConn = url.openConnection();
    } //IOException
    catch (Exception Expt)
    System.out.println("Cannot open URL connection");
    java.lang.Thread.sleep(3000);
    myConn = null;
    continue;
    Cheers
    JavaJimmyD

        BufferedReader inp = null;
        try {
          URL url = new URL(urlString);
          URLConnection conn = url.openConnection();
          conn.setDoInput(true); // or setDoOutput(true)
          /* really open connection */
          conn.connect(); // establish connection
          inp = new BufferedReader(
                  new InputStreamReader(conn.getInputStream()));
          String result = inp.readLine(); // or your stuff
          inp.close();  // close connection
          inp = null;
        catch (MalformedURLException ue) {}
        catch (Exception e) {}
        finally {
          try { if (inp != null) inp.close(); } catch(IOException e) {}
        }

  • Big headache with URL connection

    Hi, guys.
    i wrote an applet that measures response time of some html components, like gifs! The applet should return this wasted time by the actionperform method be executed, since this method opens a url connection with a html component. So it might return the final response time, but the result is always 0 !!! Please, could anybody help me?
    Regards Euclides.
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    long valor;
    Integer valornovo;
    String valor1,tam1,tarefa1;
    JTextField aux;
    tam1 = (String)ivjJComboBox1.getSelectedItem();
    tarefa1 = (String)ivjJComboBox2.getSelectedItem();
    valor = mandabala(tam1,tarefa1);
    valor1 = Long.toString(valor);
    //delayField = new JTextField(Long.toString(delay), 6);
    //valor1 = Long.toString(valor);
    ivjJTextField1.setEnabled( true );
    ivjJTextField1.setText(valor1);
    validate();
    public long mandabala(String param, String param1) {
    long time;
    long time1;
    BufferedInputStream in;
    java.net.HttpURLConnection conn;
    java.net.URL url;
    url = null;
    if (param == "100")
    byte[] buffer = new byte[99990000];
    try {
    url = new java.net.URL("http://10.0.135.15/teste.gif");
    // url = constructURL("http://10.0.135.15/performance/teste.gif");
    conn = (HttpURLConnection)url.openConnection();
    time = System.currentTimeMillis();
    //conn("http://www.dataprev.gov.br/performance/teste.gif");
    //conn("http://10.0.135.15/performance/teste.gif");
    conn.connect();
    time1 = System.currentTimeMillis();
    in = new BufferedInputStream(conn.getInputStream());
    int x = 0;
    while((x = in.read(buffer))!=-1)
    timedif = System.currentTimeMillis() - time;
    in.close();
    catch(Exception e) {
    System.out.println("Erro de conexao");

    I read it really quickly, so I apologize if you've checked this already...
    Your while loop is not executing the statement you are using to compute the timediff variable. The while loop in.read() method returns with a value of say '63000' when the .gif file is read. Since 63000!=-1 the loop exits immediately without executing the statement (System.currentTime()) in the middle.
    To correct this, you should do the following.
    long timediff=0;
    long starttime=System.currentTimeInMillis();
    int character=0;
    while( (character=in.read()) != -1 );
    timediff = System.currentTimeINMillis() - starttime;
    //return timediff;

  • Close physical connection failed!

    Hi!
    I meet a problem in a live system using Oracle 8.1.7, i.e., the physical connection cann't be closed normally in some unknown occasion. I don't know the reason and how
    to solve the problem.
    I show some code of my PooledConnection class here:
    // get physical connection here
    Connection conn = DriverManager.getConnection(url, username, password);
    Connection getConnection()
    return conn;
    // close physical connection here
    try {
    closeStatements(); // I close the statement recorded in PooledConnection object
    } catch (SQLException e) {
    e.printStackTrace();
    try {
    getConnection().rollback();
    // My problem is located here!!
    // I've had problems when trying to close a connection.
    // The following close() method may be no response for a long time.
    getConnection().close();
    catch (SQLException e) {
    e.printStackTrace();
    catch (Exception e) {
    e.printStackTrace();
    Help me please!
    Thanks a lot!
    Meyor

    Make sure you have closed all statements for that connection.
    If there is any statement still running in the database, you can't close connection.
    If you use transation, and didn't explicitly call commit() or rollback(), closing connection will automatically commit your transactions. Unless you transation has lots of changes, it shouldn't take long.

  • Properly close database connection - Oracle

    I have an unusuall application that has a main in it and runs off of a cron job.
    We have orders that have to be filled, and if the approver of that order does not reject it after 30 minutes its automatically filled.
    The weird thing is that alot of these stored procedures were already in place before I got there so I just went ahead and called them to get the data that I needed.
    So, we have a shell script that just calls my class. The main kicks off and gets the time of the orders placed on that day. If the current time minus the time the order was placed is greater than 30 minutes approve the order.
    Now, I have about 3 - stored procedures that I call in one method. Actually I have about 3 or 4 methods that in turns calls these stored procedures. I have callable statements for each method. and I do a try - catch in each of the other methods, but not a connection close. In the one method that does all the work and calls the other methods, I have a try - catch - and a then a finally. I then do a conn.close() in the finally of this method.
    My question is? Is this correct. Should I do a try catch finally in my main() method.
    So, this is sort of what it looks like.
    class DoSomething
       Connection conn;
       method1()
          try
             CallableStatement cs;
             ResultSet rs;
             rs.close;
             cs.close;
          catch
          return something1;
       method2()
          try
             CallableStatement cs;
             ResultSet rs;
             rs.close;
             cs.close;
          catch
          return Something2;
       method3()
          try
             CallableStatement cs;
             ResultSet rs;
             rs.close;
             cs.close;
          catch
          return Something3;
       doSomethingMethod()
          try
             CallableStatement cs;
             ResultSet rs;
            // call the other methods to get all data needed.
            ds.method1;
            ds.method2;
            ds.method3;
             rs.close;
             cs.close;
          catch
          finally
              conn.close();
       main()
          DoSomething ds = new DoSomething();
          ds.doSomethingMethod();
    }orozcom

    Well, The catch blocks are not empty. I assure you. I
    just didn't feel like writing down all of my code.
    plus I did not want to cloud the example with to much
    code. Very good.
    All I wanted to know is when and where to close
    my resultset, callable statements, and connection.OK, you should close each one in its own individual try/catch block in a finally block inside the method in which they were called.
    If the stored procs are a unit of work, you'll have to share the Connection.
    Please also realize that this is a web based
    application as well. I take in parameters from a URL.
    I pass those parameters to the stored procs (which
    are already there). If you're doing that in a JSP, I'd say you've got a bad design.
    Now sometimes one method needs
    information from another method. So, I run that
    method. pass the info to another method or stored
    proc which gives me my info. All this should be happening in a service layer.
    I was told that a finally block always runs. So, I
    thought if I atleast put my conn.close in the
    finally. then it will always close the connection.As long as it doesn't throw an exception. And you should close ResultSets and Statements, regardless of what the javadocs say.
    Also, there is only one database that I call. Now the
    stored procs are all on the same database, but they
    are in different packages. which is why I use the
    callable statements.That's fine.
    Also, I do not only call stored procs. I usually only
    call a stored proc to get information back, and then
    give it to a class to manipulate the data.Sounds inefficient. Would a JOIN do as well? You might fall into the (n+1) query trap, where you run a query to get a ResultSet and then iterate through it and run another query per iteration. This is inefficient as n gets large.
    %

  • Change url connection to socket

    hello i have a problem about a socket connection can you help me
    i want to change url connection to socket connection
    here is
              java.net.URL url = new java.net.URL("http://64.74.75.74/approot/webapp/ZOR/bare");
              connection = new sun.net.www.protocol.http.HttpURLConnection(url, " ", 0);
              connection.setRequestMethod("POST");
              connection.setDoInput(true);
              connection.setDoOutput(true);
              connection.setUseCaches(false);
              java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(connection.getOutputStream());
              out.writeObject(getTextFieldGiden().getText());
              out.flush();
              out.close();
              return (String) (new java.io.ObjectInputStream(connection.getInputStream()).readObject());how can i change it to
    socket connection because i must write it in c++
    thank you very much

    why are you replaying if you don' t have a solution peter?
    i have a big c++ project and in it somewhere must do the job the code i send in java do.
    &#304; also want to say i dont want it's c++ code ,i want to know how it can be with java sockets.

  • How to close RFC connection in one script coding

    In one script, I am using the REF command to call another 2 scripts and these called scripts shd be run on same C36 ( test system). I shd close RFC connection between these 2 scripts.
    That is , once the 1s script over the RFC shd be closed and the user has to give usename and pwd  then  2nd script shd run.
    I have tried with the following code…. But it says RFC is not open……
    REF ( Y04S_FC_RM_CJ88_112 , Y04S_FC_RM_CJ88_1 , C36_999 ).   (when execute this script RFC to C36 will be created and after execution that RFC shd be closed so I included following ABAP code)
    ABAP.
      data : dest type RFCDEST.
      move 'S4_SAPC36999' to dest.                                       
      move dest to v_dest.
    *--Close the connection before opening it incase it is opened
              call function 'RFC_CONNECTION_CLOSE'
                   exporting
                        destination          = dest
                   exceptions
                        destination_not_open = 1
                        others               = 2.
              if sy-subrc <> 0.
              endif.
              move sy-subrc to v_subrc.
    ENDABAP.
    REF ( Y04S_FC_RM_CJ44_112 , Y04S_FC_RM_CJ44_1 , C36_999 ). (here agagin the RFC will be created and this script will be exectued.)

    In one script, I am using the REF command to call another 2 scripts and these called scripts shd be run on same C36 ( test system). I shd close RFC connection between these 2 scripts.
    That is , once the 1s script over the RFC shd be closed and the user has to give usename and pwd  then  2nd script shd run.
    I have tried with the following code…. But it says RFC is not open……
    REF ( Y04S_FC_RM_CJ88_112 , Y04S_FC_RM_CJ88_1 , C36_999 ).   (when execute this script RFC to C36 will be created and after execution that RFC shd be closed so I included following ABAP code)
    ABAP.
      data : dest type RFCDEST.
      move 'S4_SAPC36999' to dest.                                       
      move dest to v_dest.
    *--Close the connection before opening it incase it is opened
              call function 'RFC_CONNECTION_CLOSE'
                   exporting
                        destination          = dest
                   exceptions
                        destination_not_open = 1
                        others               = 2.
              if sy-subrc <> 0.
              endif.
              move sy-subrc to v_subrc.
    ENDABAP.
    REF ( Y04S_FC_RM_CJ44_112 , Y04S_FC_RM_CJ44_1 , C36_999 ). (here agagin the RFC will be created and this script will be exectued.)

  • Open and close RFC connection with portals...

    Hi Experts,
    I created a RFC having a query which is taking a long time to execute. So i want to close RFC connection with portals which is via java connector(JCO)  before that query and open the connction again after that query.
    Please advice is it possible to achieve this. If yes, then how.
    Regards,
    Guddan

    Hi Guddan,
    I created a RFC having a query which is taking a long time to execute. So i want to close RFC connection with portals which is via java connector(JCO) before that query and open the connction again after that query.
    I guess i will need to understand your requirement a little more in detail, as i understand you have an RFC which has a query within to fetch some data and is taking a long time to do so. In the meantime you don't want to keep the connection open?
    My question would be, Is the role of this RFC to only execute the query and fetch the data or does it do something else?
    If it does other things and these are independent of the query execution, then you can span a parallel call within the RFC to execute the query and in the meantime the RFC does the other things (or vice versa) hence reducing the overall time taken.
    If the sole purpose of this RFC is to execute the query, then you will not be able(i mean to say there is no simple and direct way of doing this) to close the connection after the Query is started and re-establish the connection after its execution, for a simple reason that - how will you know if the query has completed it's execution, so that you can establish the connection back.
    Alternate solutions, make this a two way asynchronous call, 1) You invoke the RFC asynchronously and close the connection, the RFC in turn will execute the query and transfer the data to JCO via another RFC call.
    If this needs to be a synchronous call, then you will need to optimize the query to its best.
    Regards,
    Chen

  • Open and close database connection jsp page

    hi there, i wanna know about how to open database connection to Mysql at the beginning of the page and close the connection at the end of the page. The jsp page contain all processing code.
    plz help me...thx thx

    <html>
    <head>
    <basefont face="Arial">
    </head>
    <body>
    <%@ page language="java" import="java.sql.*" %>
    <%!
    // define variables
    String id;
    String firstName;
    String lastName;
    // define database parameters, change this according to your needs
    String host="localhost";
    String user="root";
    String pass="";
    String db="test";
    String conn;
    %>
    <table border="1" cellspacing="1" cellpadding="5">
    <tr>
    <td><b>id</b></td>
    <td><b>first name</b></td>
    <td><b>last name</b></td>
    </tr>
    <%
    Class.forName("org.gjt.mm.mysql.Driver");
    // create connection string
    conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user 
    + "&password=" + pass;
    // pass database parameters to JDBC driver
    Connection Conn = DriverManager.getConnection(conn);
    // query statement
    Statement SQLStatement = Conn.createStatement();
    // generate query
    // change this query according to your needs
    String Query = "SELECT id, firstname, lastname FROM abook";
    // get result
    ResultSet SQLResult = SQLStatement.executeQuery(Query);
    while(SQLResult.next())
       id = SQLResult.getString("id");
       firstName = SQLResult.getString("firstname");
       lastName = SQLResult.getString("lastname");
            out.println("<tr><td>" + id + "</td><td>" + 
         firstName + "</td><td>" + lastName + "</td></tr>");
    // close connection
    SQLResult.close();
    SQLStatement.close();
    Conn.close();
    %>
    </table>
    </body>
    </html>hi :-)
    i've got that on the net as part of the tutorial on jsp (long long time ago)
    you just have to be resourceful in finding solutions :-)
    try google :-) there are lot's of tutorial available in there ;-)
    goodluck ;-)
    regards,

  • How to correct close database connection after report generation

    Hello
    I have problem a with alive database connection after report creation and report  closing. How to properly to close connection to database?
    Best regards
    Edited by: punkers84 on Jun 17, 2011 10:38 AM

    that's what I am doing... after viewing the report, I call the close method on the window closing event of the container window. but the connection is still open. I had a lot of other issues with my jdbc driver but after downgrading to an older version those issues are resolved.Only this one is still there! Is there any other way to close the connection (like using dbcontroller or etc.)?

  • When to open and close database connection

    im trying to connect to a oracle database using servlets
    when should i open and close the connection
    it works fine when i do both in the doPost() method
    but when i tried to open connection in init() methd .. it doesnt seem to work
    what should i do...
    the connection is initialised in the init() method but is null in the doPost() method

    " im trying to connect to a oracle database using servlets
    when should i open and close the connection
    it works fine when i do both in the doPost() method
    but when i tried to open connection in init() methd .. it doesnt seem to work
    what should i do...
    the connection is initialised in the init() method but is null in the doPost() method"
    1:
    without seeing the code i would say the the connection is null
    because you are storing it as a servlet class variable which is
    not thread safe.
    2:
    The best way to do it using connection pooling
    detailed docs on the tomcat website
    3:
    if you are not using connection pooling, then
    open and close the connection in the do* method
    or
    use init() to place the connection in the servletconfig
    and close in destroy() and use synching to access

  • How to close database connections in Crystal Reports

    I am using the following code to connect to database. I can either pass JNDIName or I can provide values for others by leaving JNDI name empty.
    If i use JNDI name, it will use a connection from the connection pool of App Server (in my case Weblogic), but it is not releasing the connection after use. Connection remains even if I logoff from the application. If i keep my max connections as 15 in weblogic, after clicking the page with crystal report 15 times all will remain active and users will not be able to login to the application.
    If i use connectionString and others without using JNDI Name, it directly connects to database. So it creates a connection in database server directly without using connection pool of weblogic. If i check weblogic, it shows no connection in use as expected, but if i check database, i can see the no. of connections increasing everytime a user clicks a crystal report page.
    When the connection touches the maximum allowed connection in server, every application using the same server goes down
    How can I close the connection which was created for the viewing the report?
    String reportName = "/reports/BankBalance.rpt";
    ReportClientDocument clientDoc = (ReportClientDocument) session.getAttribute(reportName);
    if (clientDoc == null)
             clientDoc = new ReportClientDocument();
             clientDoc.setReportAppServer(ReportClientDocument.inprocConnectionString);
            // Open report
            clientDoc.open(reportName, OpenReportOptions._openAsReadOnly);
           String connectString = ""; // jdbc:sybase:Tds:DBSERVERNAME:9812/DBNAME?ServiceName=DBNAME
           String driverName = "";    // com.sybase.jdbc3.jdbc.SybDriver
           String JNDIName = "DS_APP";
           String userName = "";
           String password = "";
           // Switch all tables on the main report and sub reports
           CRJavaHelper.changeDataSource(clientDoc, userName, password, connectString, driverName, JNDIName);
         // logon to database
          CRJavaHelper.logonDataSource(clientDoc, userName, password);
    // Store the report document in session
    session.setAttribute(reportName, clientDoc);
                   // Create the CrystalReportViewer object
                          CrystalReportViewer crystalReportPageViewer = new CrystalReportViewer();
         String reportSourceSessionKey = reportName+"ReportSource";
         Object reportSource = session.getAttribute(reportSourceSessionKey);
         if (reportSource == null)
              reportSource = clientDoc.getReportSource();
              session.setAttribute(reportSourceSessionKey, reportSource);
         //     set the reportsource property of the viewer
         crystalReportPageViewer.setReportSource(reportSource);
         crystalReportPageViewer.setHasRefreshButton(true);
         crystalReportPageViewer.setToolPanelViewType(CrToolPanelViewTypeEnum.none);
         // Process the report
         crystalReportPageViewer.processHttpRequest(request, response, application, null);

    the sample shows how to clear RAS and Enterprise resources after viewing report.
    1. If you use unmanaged RAS - as I can see you using setReportAppServer, then remove the enterprise related stuff : instantiating and cleaning code.
    The sample code is meant to give you an idea on how you can release the resources after done with viewing report. In your case all you need to do for cleaning is call close() on ReportDocumentObject. The sample will need to be modified for your requirements.

  • Need to close RFC connection

    Hi all,
    Currently we developed a application in NWDS, the same is operational from portal.
    As per the requirment we have to run the RFC many times to extract the data from R/3. After running the RFC many times
    we are getting the following Error "Error connecting using JCO.client: null"
    But if we redeploy the application the problem is solved but after a while the same issue is persisting.
    Please suggest how the problem can be solved ??
    Thanks,
    vijay.

    Hi venkat,
    Thanks for the example suggested by you.
    The following is the RFC iam executing many times.
    Z_Hr_Aprsl_Init_Input input= new Z_Hr_Aprsl_Init_Input();
    input.setI_Usrid("UserId");
    wdContext.nodeZ_Hr_Aprsl_Init_Input_new().bind(input);
    wdContext.nodeZ_Hr_Aprsl_Init_Input().currentZ_Hr_Aprsl_Init_InputElement().modelObject().execute();
    the code iam using to close the connection is
    JCO.Client client = JCO.getClient(" "); // Please specify the parameter to be used to refer the above RFC
    client.disconnect();
    Please suggest the required the parameter to close the RFC connection
    Thanks
    vijay

Maybe you are looking for