InetAddress Exception

I've got a load of Windows 98 PCs running the 1.4.1 SE JRE and the first thing my application does is to get the local host address:
try
InetAddress ia = InetAddress.getLocalHost();
String localIpAddress = ia.getHostAddress();
catch (Throwable e)
//log exception here
There's nothing clever or special about this code but on a couple of those PCs this results in the following exception:
at java.net.InetAddress.cacheAddress(InetAddress.java:648)
at java.net.InetAddress.cacheAddress(InetAddress.java:633)
at java.net.InetAddress.getAddressFromNameService(InetAddress.java:1016)
at java.net.InetAddress.getLocalHost(InetAddress.java:1125)
I've looked at the source for InetAddress and can't see why this PC is failing on this call.
Anyone got a clue what's wrong with these PCs?

Anyone got a clue what's wrong with these PCs?Have those PCs been configured for DNS resolution?

Similar Messages

  • InetAddress  exception  errors

    Hi all
    When compiling my program
    Following errors getted:-
    1.unreported exception java.net.UnknownHostException; must be caught or declared to be thrown
              InetAddress inet = InetAddress.getByName("www.davidreilly.com");
    2.exception java.net.MalformedURLException is never thrown in body of corresponding try statement
              catch (MalformedURLException e){}
    This is the part of my code in which errors occur
    try {
                InetAddress inet = InetAddress.getByName("www.davidreilly.com");
                 System.out.println ("IP  : " + inet.getHostAddress());
                catch (MalformedURLException e){}Please help me to correct and why unreported exception java.net.UnknownHostException; must be caught or declared to be thrown if I dont use try and catch statements
    Thanks in advance.

    why unreported exception java.net.UnknownHostException must be caught or declared to be thrownBecause it's a rule of Java.
    if I dont use try and catch statementsBut you do 'use try and catch statements'. There's one of each in your code.
    You're just catching the wrong exception. Nothing in your code throws MalformedURLException yet you have a catch block for it, and InetAddress.getByName() throws UnknownHostException and you don't have a catch block for it.
    You also have an empty catch block, which is very poor practice. At least print something out in the catch block ...

  • Exception when querying java.lang.InetAddress

    Hi,
    When attempting to query an object based on its ipaddress, I ran into the following problem:
    [java] Exception in thread "main" <4|false|4.0.1> kodo.persistence.ArgumentException: The specified parameter of type "class java.net.Inet4Address" is not a valid query parameter.
    [java] at kodo.jdbc.sql.DBDictionary.setUnknown(DBDictionary.java:1347)
    [java] at kodo.jdbc.sql.SQLBuffer.setParameters(SQLBuffer.java:638)
    [java] at kodo.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:539)
    [java] at kodo.jdbc.sql.SQLBuffer.prepareStatement(SQLBuffer.java:512)
    [java] at kodo.jdbc.sql.SelectImpl.execute(SelectImpl.java:332)
    [java] at kodo.jdbc.sql.SelectImpl.execute(SelectImpl.java:301)
    [java] at kodo.jdbc.sql.Union$UnionSelect.execute(Union.java:642)
    [java] at kodo.jdbc.sql.Union.execute(Union.java:326)
    [java] at kodo.jdbc.sql.Union.execute(Union.java:313)
    [java] at kodo.jdbc.kernel.SelectResultObjectProvider.open(SelectResultObjectProvider.java:98)
    [java] at com.solarmetric.rop.EagerResultList.<init>(EagerResultList.java:22)
    [java] at kodo.kernel.QueryImpl.toResult(QueryImpl.java:1445)
    [java] at kodo.kernel.QueryImpl.execute(QueryImpl.java:1167)
    [java] at kodo.kernel.QueryImpl.execute(QueryImpl.java:953)
    [java] at kodo.kernel.QueryImpl.execute(QueryImpl.java:871)
    [java] at kodo.kernel.DelegatingQuery.execute(DelegatingQuery.java:774)
    [java] at kodo.persistence.QueryImpl.execute(QueryImpl.java:241)
    [java] at kodo.persistence.QueryImpl.getResultList(QueryImpl.java:290)
    [java] at test.MainLine.main(MainLine.java:196)
    My query:
    ("select i from Interface i where i.testAddress = addr").setParameter("addr", InetAddress.getLocalHost())
    I have tried this using Inet4Address in the hope that Kodo was having some issues with polymorphism but the same problem occurs.
    The mapping is defined as follows:
    @Basic
    public InetAddress getTestAddress ()
    return _test;
    public void setTestAddress (InetAddress test)
    _test = test;
    I have tried using @Lob but this made no difference. Is it possible to create queries based on a LOB?

    java.sql.SQLException: Invalid state, the Connection object is closed
    It answers your question to an extent. Check if your connection or recordset object is closed
    cheers,
    Siddhs

  • InetAddress posting Unknown Host Exception

    Hello,
    I am relatively new to java and I am running into an Unknown Host Exception when attempting to return the IP's for valid host names. The strange part is that the first host name returns an address however every entry after the first returns the Unkown Host Exception. Here is the snippet of code that the problem is occuring in.
    Inet address as declared earlier in the code:
         private InetAddress Address = null;Code reporting errors:
              StringBuffer sb0 = new StringBuffer();
              int chr;
              // Read until the end of the stream     
              while ((chr = inputStream0.read()) != -1)
                      sb0.append((char) chr);
              String display = sb0.toString();
              String temp = display.replace("Giant ", "g0");
              String[] words = temp.split("\\|");
              StringBuffer db = new StringBuffer();
              for (int i=0; i < words.length; i++)
                      String many = (words[i] +"wu1");
                      try
                              Address = InetAddress.getByName(many);
                   db.append(words[i] + "wu1|" + Address);
                      catch(NullPointerException e)
                              db.append(words[i] + "wu1 - Null Pointer - ");
                      catch(UnknownHostException e)
                              db.append(words[i] + "wu1 - Unknown Host - ");
              String yay = db.toString();
              log.append(yay);
                                    catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
                                    catch (IOException e)
              // TODO Auto-generated catch block
              e.printStackTrace();
              }I have attempted setting Address back to null after the address was appended but it didn't make any difference.
    Edited by: mudbuggle on Aug 4, 2008 7:19 PM

    I made the adjustments however I am still experiencing the same problem.
    www.yahoo.com returns an ip address but the rest return Unknown Host Exceptions.
    www.yahoo.comjava.net.UnknownHostException:
    forums.sun.com
         at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method)
         at java.net.InetAddress$1.lookupAllHostAddr(Unknown Source)
         at java.net.InetAddress.getAddressFromNameService(Unknown Source)
         at java.net.InetAddress.getAllByName0(Unknown Source)
         at java.net.InetAddress.getAllByName(Unknown Source)
    forums.sun.com     at java.net.InetAddress.getAllByName(Unknown Source)
         at java.net.InetAddress.getByName(Unknown Source)
         at IP$1.actionPerformed(IP.java:83)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.AbstractButton.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    java.net.UnknownHostException:
    www.google.com
         at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method)
         at java.net.InetAddress$1.lookupAllHostAddr(Unknown Source)
         at java.net.InetAddress.getAddressFromNameService(Unknown Source)
         at java.net.InetAddress.getAllByName0(Unknown Source)
         at java.net.InetAddress.getAllByName(Unknown Source)
         at java.net.InetAddress.getAllByName(Unknown Source)
         at java.net.InetAddress.getByName(Unknown Source)
         at IP$1.actionPerformed(IP.java:83)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.AbstractButton.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • Exception report when using tomcat 5 with JDBC

    i followed this guide to setup the JDBC with my TOMCAT 5
    http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html#Database%20Connection%20Pool%20(DBCP)%20Configurations
    but i seem to get this error
    exception
    javax.servlet.ServletException: Unable to get connection, DataSource invalid: "org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'"
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:846)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:779)
         org.apache.jsp.SID.test_jsp._jspService(test_jsp.java:81)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'"
         org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:276)
         org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:159)
         org.apache.jsp.SID.test_jsp._jspx_meth_sql_query_0(test_jsp.java:100)
         org.apache.jsp.SID.test_jsp._jspService(test_jsp.java:58)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    i can compile *.java and run them when they need the jdbc drivers to interact with mysql 5 database.
    This is my server.xml
    <!-- Example Server Configuration File -->
    <!-- Note that component elements are nested corresponding to their
    parent-child relationships with each other -->
    <!-- A "Server" is a singleton element that represents the entire JVM,
    which may contain one or more "Service" instances. The Server
    listens for a shutdown command on the indicated port.
    Note: A "Server" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <Server port="8005" shutdown="SHUTDOWN" debug="0">
    <!-- Comment these entries out to disable JMX MBeans support -->
    <!-- You may also configure custom components (e.g. Valves/Realms) by
    including your own mbean-descriptor file(s), and setting the
    "descriptors" attribute to point to a ';' seperated list of paths
    (in the ClassLoader sense) of files to add to the default list.
    e.g. descriptors="/com/myfirm/mypackage/mbean-descriptor.xml"
    -->
    <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"
    debug="0"/>
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
    debug="0"/>
    <!-- Global JNDI resources -->
    <GlobalNamingResources>
    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
    <!-- Editable user database that can also be used by
    UserDatabaseRealm to authenticate users -->
    <Resource name="UserDatabase" auth="Container"
    type="org.apache.catalina.UserDatabase"
    description="User database that can be updated and saved">
    </Resource>
    <ResourceParams name="UserDatabase">
    <parameter>
    <name>factory</name>
    <value>org.apache.catalina.users.MemoryUserDatabaseFactory</value>
    </parameter>
    <parameter>
    <name>pathname</name>
    <value>conf/tomcat-users.xml</value>
    </parameter>
    </ResourceParams>
    </GlobalNamingResources>
    <!-- A "Service" is a collection of one or more "Connectors" that share
    a single "Container" (and therefore the web applications visible
    within that Container). Normally, that Container is an "Engine",
    but this is not required.
    Note: A "Service" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <!-- Define the Tomcat Stand-Alone Service -->
    <Service name="Catalina">
    <!-- A "Connector" represents an endpoint by which requests are received
    and responses are returned. Each Connector passes requests on to the
    associated "Container" (normally an Engine) for processing.
    By default, a non-SSL HTTP/1.1 Connector is established on port 8080.
    You can also enable an SSL HTTP/1.1 Connector on port 8443 by
    following the instructions below and uncommenting the second Connector
    entry. SSL support requires the following steps (see the SSL Config
    HOWTO in the Tomcat 5 documentation bundle for more detailed
    instructions):
    * If your JDK version 1.3 or prior, download and install JSSE 1.0.2 or
    later, and put the JAR files into "$JAVA_HOME/jre/lib/ext".
    * Execute:
    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA (Windows)
    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA (Unix)
    with a password value of "changeit" for both the certificate and
    the keystore itself.
    By default, DNS lookups are enabled when a web application calls
    request.getRemoteHost(). This can have an adverse impact on
    performance, so you can disable it by setting the
    "enableLookups" attribute to "false". When DNS lookups are disabled,
    request.getRemoteHost() will return the String version of the
    IP address of the remote client.
    -->
    <!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
    <Connector port="8080"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" redirectPort="8443" acceptCount="100"
    debug="0" connectionTimeout="20000"
    disableUploadTimeout="true" />
    <!-- Note : To disable connection timeouts, set connectionTimeout value
    to 0 -->
         <!-- Note : To use gzip compression you could set the following properties :
                   compression="on"
                   compressionMinSize="2048"
                   noCompressionUserAgents="gozilla, traviata"
                   compressableMimeType="text/html,text/xml"
         -->
    <!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
    <!--
    <Connector port="8443"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" disableUploadTimeout="true"
    acceptCount="100" debug="0" scheme="https" secure="true"
    clientAuth="false" sslProtocol="TLS" />
    -->
    <!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->
    <Connector port="8009"
    enableLookups="false" redirectPort="8443" debug="0"
    protocol="AJP/1.3" />
    <!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
    <!-- See proxy documentation for more information about using this. -->
    <!--
    <Connector port="8082"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false"
    acceptCount="100" debug="0" connectionTimeout="20000"
    proxyPort="80" disableUploadTimeout="true" />
    -->
    <!-- An Engine represents the entry point (within Catalina) that processes
    every request. The Engine implementation for Tomcat stand alone
    analyzes the HTTP headers included with the request, and passes them
    on to the appropriate Host (virtual host). -->
    <!-- You should set jvmRoute to support load-balancing via JK/JK2 ie :
    <Engine name="Standalone" defaultHost="localhost" debug="0" jvmRoute="jvm1">
    -->
    <!-- Define the top level container in our container hierarchy -->
    <Engine name="Catalina" defaultHost="localhost" debug="0">
    <!-- The request dumper valve dumps useful debugging information about
    the request headers and cookies that were received, and the response
    headers and cookies that were sent, for all requests received by
    this instance of Tomcat. If you care only about requests to a
    particular virtual host, or a particular application, nest this
    element inside the corresponding <Host> or <Context> entry instead.
    For a similar mechanism that is portable to all Servlet 2.4
    containers, check out the "RequestDumperFilter" Filter in the
    example application (the source for this filter may be found in
    "$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
    Request dumping is disabled by default. Uncomment the following
    element to enable it. -->
    <!--
    <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
    -->
    <!-- Global logger unless overridden at lower levels -->
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="catalina_log." suffix=".txt"
    timestamp="true"/>
    <!-- Because this Realm is here, an instance will be shared globally -->
    <!-- This Realm uses the UserDatabase configured in the global JNDI
    resources under the key "UserDatabase". Any edits
    that are performed against this UserDatabase are immediately
    available for use by the Realm. -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
    debug="0" resourceName="UserDatabase"/>
    <!-- Comment out the old realm but leave here for now in case we
    need to go back quickly -->
    <!--
    <Realm className="org.apache.catalina.realm.MemoryRealm" />
    -->
    <!-- Replace the above Realm with one of the following to get a Realm
    stored in a database and accessed via JDBC -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="org.gjt.mm.mysql.Driver"
    connectionURL="jdbc:mysql://localhost/authority"
    connectionName="test" connectionPassword="test"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="oracle.jdbc.driver.OracleDriver"
    connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
    connectionName="scott" connectionPassword="tiger"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="sun.jdbc.odbc.JdbcOdbcDriver"
    connectionURL="jdbc:odbc:CATALINA"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!-- Define the default virtual host
    Note: XML Schema validation will not work with Xerces 2.2.
    -->
    <Host name="localhost" debug="0" appBase="webapps"
    unpackWARs="true" autoDeploy="true"
    xmlValidation="false" xmlNamespaceAware="false">
    <!-- Defines a cluster for this node,
    By defining this element, means that every manager will be changed.
    So when running a cluster, only make sure that you have webapps in there
    that need to be clustered and remove the other ones.
    A cluster has the following parameters:
    className = the fully qualified name of the cluster class
    name = a descriptive name for your cluster, can be anything
    debug = the debug level, higher means more output
    mcastAddr = the multicast address, has to be the same for all the nodes
    mcastPort = the multicast port, has to be the same for all the nodes
    mcastBindAddr = bind the multicast socket to a specific address
    mcastTTL = the multicast TTL if you want to limit your broadcast
    mcastSoTimeout = the multicast readtimeout
    mcastFrequency = the number of milliseconds in between sending a "I'm alive" heartbeat
    mcastDropTime = the number a milliseconds before a node is considered "dead" if no heartbeat is received
    tcpThreadCount = the number of threads to handle incoming replication requests, optimal would be the same amount of threads as nodes
    tcpListenAddress = the listen address (bind address) for TCP cluster request on this host,
    in case of multiple ethernet cards.
    auto means that address becomes
    InetAddress.getLocalHost().getHostAddress()
    tcpListenPort = the tcp listen port
    tcpSelectorTimeout = the timeout (ms) for the Selector.select() method in case the OS
    has a wakup bug in java.nio. Set to 0 for no timeout
    printToScreen = true means that managers will also print to std.out
    expireSessionsOnShutdown = true means that
    useDirtyFlag = true means that we only replicate a session after setAttribute,removeAttribute has been called.
    false means to replicate the session after each request.
    false means that replication would work for the following piece of code:
    <%
    HashMap map = (HashMap)session.getAttribute("map");
    map.put("key","value");
    %>
    replicationMode = can be either 'pooled', 'synchronous' or 'asynchronous'.
    * Pooled means that the replication happens using several sockets in a synchronous way. Ie, the data gets replicated, then the request return. This is the same as the 'synchronous' setting except it uses a pool of sockets, hence it is multithreaded. This is the fastest and safest configuration. To use this, also increase the nr of tcp threads that you have dealing with replication.
    * Synchronous means that the thread that executes the request, is also the
    thread the replicates the data to the other nodes, and will not return until all
    nodes have received the information.
    * Asynchronous means that there is a specific 'sender' thread for each cluster node,
    so the request thread will queue the replication request into a "smart" queue,
    and then return to the client.
    The "smart" queue is a queue where when a session is added to the queue, and the same session
    already exists in the queue from a previous request, that session will be replaced
    in the queue instead of replicating two requests. This almost never happens, unless there is a
    large network delay.
    -->
    <!--
    When configuring for clustering, you also add in a valve to catch all the requests
    coming in, at the end of the request, the session may or may not be replicated.
    A session is replicated if and only if all the conditions are met:
    1. useDirtyFlag is true or setAttribute or removeAttribute has been called AND
    2. a session exists (has been created)
    3. the request is not trapped by the "filter" attribute
    The filter attribute is to filter out requests that could not modify the session,
    hence we don't replicate the session after the end of this request.
    The filter is negative, ie, anything you put in the filter, you mean to filter out,
    ie, no replication will be done on requests that match one of the filters.
    The filter attribute is delimited by ;, so you can't escape out ; even if you wanted to.
    filter=".*\.gif;.*\.js;" means that we will not replicate the session after requests with the URI
    ending with .gif and .js are intercepted.
    The deployer element can be used to deploy apps cluster wide.
    Currently the deployment only deploys/undeploys to working members in the cluster
    so no WARs are copied upons startup of a broken node.
    The deployer watches a directory (watchDir) for WAR files when watchEnabled="true"
    When a new war file is added the war gets deployed to the local instance,
    and then deployed to the other instances in the cluster.
    When a war file is deleted from the watchDir the war is undeployed locally
    and cluster wide
    -->
    <!--
    <Cluster className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
    managerClassName="org.apache.catalina.cluster.session.DeltaManager"
    expireSessionsOnShutdown="false"
    useDirtyFlag="true">
    <Membership
    className="org.apache.catalina.cluster.mcast.McastService"
    mcastAddr="228.0.0.4"
    mcastPort="45564"
    mcastFrequency="500"
    mcastDropTime="3000"/>
    <Receiver
    className="org.apache.catalina.cluster.tcp.ReplicationListener"
    tcpListenAddress="auto"
    tcpListenPort="4001"
    tcpSelectorTimeout="100"
    tcpThreadCount="6"/>
    <Sender
    className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
    replicationMode="pooled"/>
    <Valve className="org.apache.catalina.cluster.tcp.ReplicationValve"
    filter=".*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"/>
    <Deployer className="org.apache.catalina.cluster.deploy.FarmWarDeployer"
    tempDir="/tmp/war-temp/"
    deployDir="/tmp/war-deploy/"
    watchDir="/tmp/war-listen/"
    watchEnabled="false"/>
    </Cluster>
    -->
    <!-- Normally, users must authenticate themselves to each web app
    individually. Uncomment the following entry if you would like
    a user to be authenticated the first time they encounter a
    resource protected by a security constraint, and then have that
    user identity maintained across all web applications contained
    in this virtual host. -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn"
    debug="0"/>
    -->
    <!-- Access log processes all requests for this virtual host. By
    default, log files are created in the "logs" directory relative to
    $CATALINA_HOME. If you wish, you can specify a different
    directory with the "directory" attribute. Specify either a relative
    (to $CATALINA_HOME) or absolute path to the desired directory.
    -->
    <!--
    <Valve className="org.apache.catalina.valves.AccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>
    -->
    <!-- Logger shared by all Contexts related to this virtual host. By
    default (when using FileLogger), log files are created in the "logs"
    directory relative to $CATALINA_HOME. If you wish, you can specify
    a different directory with the "directory" attribute. Specify either a
    relative (to $CATALINA_HOME) or absolute path to the desired
    directory.-->
    <Logger className="org.apache.catalina.logger.FileLogger"
    directory="logs" prefix="localhost_log." suffix=".txt"
    timestamp="true"/>
              <Context path="/testdb" docBase="APACHE_DIR/htdocs/testdb"
    debug="5" reloadable="true" crossContext="true">
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="localhost_DBTest_log." suffix=".txt"
    timestamp="true"/>
    <Resource name="jdbc/TestDB"
    auth="Container"
    type="javax.sql.DataSource"/>
    <ResourceParams name="jdbc/TestDB">
    <parameter>
    <name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>
    <!-- Maximum number of dB connections in pool. Make sure you
    configure your mysqld max_connections large enough to handle
    all of your db connections. Set to 0 for no limit.
    -->
    <parameter>
    <name>maxActive</name>
    <value>10</value>
    </parameter>
    <!-- Maximum number of idle dB connections to retain in pool.
    Set to 0 for no limit.
    -->
    <parameter>
    <name>maxIdle</name>
    <value>5</value>
    </parameter>
    <!-- Maximum time to wait for a dB connection to become available
    in ms, in this example 10 seconds. An Exception is thrown if
    this timeout is exceeded. Set to -1 to wait indefinitely.
    -->
    <parameter>
    <name>maxWait</name>
    <value>10000</value>
    </parameter>
    <!-- MySQL dB username and password for dB connections -->
    <parameter>
    <name>username</name>
    <value>test</value>
    </parameter>
    <parameter>
    <name>password</name>
    <value>testpwd</value>
    </parameter>
    <!-- Class name for mm.mysql JDBC driver -->
    <parameter>
    <name>driverClassName</name>
    <value>com.mysql.jdbc.Driver</value>
    </parameter>
    <!-- The JDBC connection url for connecting to your MySQL dB.
    The autoReconnect=true argument to the url makes sure that the
    mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
    connection. mysqld by default closes idle connections after 8 hours.
    -->
    <parameter>
    <name>url</name>
    <value>jdbc:mysql://localhost/testdb?autoReconnect=true</value>
    </parameter>
    </ResourceParams>
         </Context>
    </Host>
    </Engine>
    </Service>
    </Server>

    You haven't added a resource reference for your web application that gives the application a local name for the global resource "UserDatabase".

  • Exception in thread "RTPC Report" java.lang.NullPointerException

    Hi.. I am having the above problem when ruuning my transmission program..
    I run my code and it seems to be ok... There is message showing the web cam stream is being transmitted...
    However, it dawn on me when i could not even receive any stream via JMStudio with the specified address. e.g. 220.10.10.20 at port 2020.
    Can any one please help?
    Thanks.
    CArter
    Following is my code...
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.net.InetAddress;
    import javax.media.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.format.*;
    import javax.media.control.TrackControl;
    import javax.media.control.QualityControl;
    import javax.media.rtp.*;
    import javax.media.rtp.rtcp.*;
    import javax.media.rtp.*;
    import java.io.InputStream;
    import javax.media.rtp.RTPManager;
    public class MyTransmitter extends Thread
         private MediaLocator videoLocator;
         private String ipAddress;
         private int basePort;
         private Integer stateLock=new Integer(0);
         private boolean failure;
         private Processor processor;
         private DataSource videoDataInput,videoDataOutput;
         private RTPManager rtpMgrs[];
         private VideoFormat JPEG_VIDEO=new VideoFormat(VideoFormat.JPEG_RTP);
         private SendStream sendStream;
         private SourceDescription descriptionList[];
         public MyTransmitter(String ips,String ports){
              ipAddress=ips;
              Integer bPort=Integer.valueOf(ports);
              if(bPort!=null)
                   basePort=bPort.intValue();
         public void run()
              initializeVideo();
              if(videoLocator!=null){
                   createMyProcessor();
                   createMyManager();
              // May be should put inside the if..else statements
              //createMyTransmitter();
         // Initailize the video
         public void initializeVideo()
              // Stre the devices in a vector
              VideoFormat format=new VideoFormat(VideoFormat.RGB);
              Vector deviceList=CaptureDeviceManager.getDeviceList(format);
              CaptureDeviceInfo deviceInfo=null;
              // If there is more than one device detected
              if(deviceList.size()>0){
                   // Set the first device to device Info
                   // GEt the media locator of the devie
                   deviceInfo=(CaptureDeviceInfo)deviceList.elementAt(0);
                   videoLocator=deviceInfo.getLocator();
              }else{
                   System.out.println(" --X No device found...");
         public void createMyProcessor()
              boolean result=false;
              DataSource ds=null;
              // Check if the media locator is null
              if(videoLocator==null){
                   System.out.println(" --X No video locator..");
              System.out.println(" - Trying to create a Processor..");
              // Attempt to create DataSource from media locator
              try{
                   ds=Manager.createDataSource(videoLocator);
              }catch(Exception ex){
                   System.out.println(" --X Unable to create dataSource : "+ex.getMessage());
              System.out.println(" - Video data source is created..");
              // Try to create Processor from DataSource
              try{
                   processor=Manager.createProcessor(ds);
              }catch(NoProcessorException npe){
                   System.out.println(" --X Unable to create Processor: "+npe.getMessage());
              catch(IOException ioe){
                   System.out.println(" --X IOException creating Processor..");
              // Wait for the processor to be configured
              result=waitForState(processor,Processor.Configured);
              if(result==false)
                   System.out.println(" --X Could not configure processor..");
              // Set the track controls for processor
              TrackControl []tracks=processor.getTrackControls();
              if(tracks==null || tracks.length<1){
                   System.err.println(" --X No track is found..");
              // Set the content description of processor to RAW_RTP format
              // This will limit the supported formats to reported from
              // Track.getSupportedFormats() to valid RTP format
              ContentDescriptor cdes=new ContentDescriptor(ContentDescriptor.RAW_RTP);
              processor.setContentDescriptor(cdes);
              Format []supported;
              Format chosen=null;
              boolean atLeastOneTrack=false;
              for(int i=0;i<tracks.length;i++){
                   Format format=tracks.getFormat();
                   if(tracks[i].isEnabled()){
                        supported=tracks[i].getSupportedFormats();
                        // WE've set the output content to RAW_RTP.
                        // So, all the supporte formats should work with RAW_RTP.
                        // We will pick the first one.
                        if(supported.length>0){
                             if(supported[0] instanceof VideoFormat){                              
                                  chosen=checkVideoSize(tracks[i].getFormat(),supported[0]);
                             }else
                                  chosen=supported[0];
                             tracks[i].setFormat(chosen);
                             System.out.println(" Track "+i+" is transmitted in "+chosen+" format.. ");
                             atLeastOneTrack=true;
                        }else{
                             // If no format is suitable, track is disabled
                             tracks[i].setEnabled(false);
                   }else
                        tracks[i].setEnabled(false);          
              if(!atLeastOneTrack)
                   System.out.println("atLeastOneTrack: "+atLeastOneTrack);
                   System.out.println(" --X Could Not find track to RTP format..");
              result=waitForState(processor,Controller.Realized);
              if(result==false){
                   System.out.println(" --X Could NOT realize processor...");
              // Set the JPEG Quality to value 0.5
              setJPEGQuality(processor,0.5f);
              // Set the output Data Source
              videoDataOutput=processor.getDataOutput();
              //Start the processor
              processor.start();          
         public void setJPEGQuality(Processor p,float values)
              Control []cs=p.getControls();
              QualityControl qc=null;
              VideoFormat JPEGFmt=new VideoFormat(VideoFormat.JPEG);
              // Loop through the ocntrols to find the Quality control for the JPEG encoder
              for(int i=0;i<cs.length;i++){
                   if(cs[i] instanceof QualityControl && cs[i] instanceof Owned){
                        Object owner=((Owned)cs[i]).getOwner();
                        // Check if the owner is the Codec
                        // Check the format of output as well
                        if(owner instanceof Codec){
                             Format fmts[]=((Codec)owner).getSupportedOutputFormats(null);
                             // Loop through the supported format and set the quality to 0.5
                             for(int j=0;j<fmts.length;j++){
                                  qc=(QualityControl)cs[i];
                                  qc.setQuality(values);
                                  System.out.println(" - Quality is set to "+values+" on "+qc);
                                  break;
                   if(qc!=null)
                        break;
         public Format checkVideoSize(Format originalFormat,Format supported)
              int width,height;
              Dimension size=((VideoFormat)originalFormat).getSize();     
              Format jpegFormat=new Format(VideoFormat.JPEG_RTP);
              Format h263fmt=new Format(VideoFormat.H263_RTP);
              if(supported.matches(jpegFormat)){
                   width=(size.width%8 == 0 ? size.width:(int)(size.width%8)*8);
                   height=(size.height%8 == 0 ? size.height:(int)(size.height%8)*8);
              }else if(supported.matches(h263fmt)){
                   if(size.width<128){
                        width=128;
                        height=96;
                   }else if(size.width<176){
                        width=176;
                        height=144;
                   }else{
                        width=352;
                        height=288;
              }else{
                   // Unknown format, just return it.
                   return supported;
              return (new VideoFormat(null,new Dimension(width,height),Format.NOT_SPECIFIED,null,Format.NOT_SPECIFIED)).intersects(supported);
         public boolean waitForState(Processor p,Integer status)
              p.addControllerListener(new StateListener());
              failure=false;
              if(status==Processor.Configured){
                   p.configure();               
              }else if(status==Processor.Realized){
                   p.realize();
              //Wait until an event that confirms the success of the method, or failure of an event
              while(p.getState()<status && !failure){
                   synchronized(getStateLock()){
                        try{
                             // Wait
                             getStateLock().wait();
                        }catch(InterruptedException ie){
                             return false;
              if(failure)
                   return false;
              else
                   return true;
         public Integer getStateLock(){
              return stateLock;
         public void setFailure(){
              failure=true;
         public void createMyManager()
              SessionAddress destAddress;
              InetAddress ipAddr;
              int port;
              SourceDescription srcDesList[];
              PushBufferDataSource pbds=(PushBufferDataSource)videoDataOutput;
              PushBufferStream pbss[]=pbds.getStreams();          
              rtpMgrs=new RTPManager[pbss.length];          
              for(int a=0;a<pbss.length;a++){
              try{
                   // RTP Managers or RTP Manager?????
                   rtpMgrs[a]=RTPManager.newInstance();
                   port=basePort;
                   ipAddr=InetAddress.getByName(ipAddress);
                   SessionAddress localAddr=new SessionAddress(InetAddress.getLocalHost(),port+20);
                   destAddress=new SessionAddress(ipAddr,port,1);
                   Integer myipprefix=Integer.valueOf(ipAddress.substring(0,3));
                   if((myipprefix.intValue()>223) && (myipprefix.intValue()<240)){
                        rtpMgrs[a].initialize(destAddress);
                   }else{
                        rtpMgrs[a].initialize(localAddr);
                   rtpMgrs[a].addTarget(destAddress);
                   System.out.println(" Created RTP session: "+ipAddress+" "+port+" to "+destAddress);
                   if(videoDataOutput!=null){
                        sendStream=rtpMgrs[a].createSendStream(videoDataOutput,0);
                        sendStream.start();
              }catch(UnsupportedFormatException ex){
                   System.out.println(" --X Unsupported Format : "+ex);
              catch(IOException ioe){
                   System.out.println(" --X IOException : "+ioe.getMessage());
              catch(Exception ex){
                   System.out.println(" --X Unable to create RTP Manager...");
                   System.out.println(ex.getMessage());
         /*public void createMyTransmitter()
         try{
              if(videoDataOutput!=null){
                   sendStream=rtpMgrs[i].createSendStream(videoDataOutput,0);
                   sendStream.start();
         }catch(UnsupportedFormatException ex){
                   System.out.println(" --X Unsupported Format : "+ex);
         catch(IOException ioe){
                   System.out.println(" --X IOException : "+ioe.getMessage());
         public void stopTransmitter(){
              if(processor!=null){
                   processor.stop();
                   processor.close();
                   processor=null;
                   // Loop through RTP Managers and close all managers..
                   // Dispose them for garbage collection
                   for(int i=0;i<rtpMgrs.length;i++){
                        rtpMgrs[i].removeTargets("Session ended..");
                        rtpMgrs[i].dispose();
                   //rtpMgrs.removeTargets("Session ended..");
                   //rtpMgrs.dispose();
         * StateListener class to handle Controller events
         class StateListener implements ControllerListener{
              public void controllerUpdate(ControllerEvent ce){
                   if(ce instanceof ControllerClosedEvent){
                        processor.close();
                   /* Handle all controller events and notify all
                   waiting thread in waitForState method */
                   if(ce instanceof ControllerEvent){
                        synchronized(getStateLock()){
                             getStateLock().notifyAll();

    Ok I reviewed your code and there were a couple things which I am confused about. Firstly, it looks like you have a section of code which checks to see if the ip address preffix is within the 240-223 range, which tells me that you are trying to implement multicast addresses. However, your example ip is out of the multicast range. Also the InetAddress has an isMulticastAddress() method which can check that for you.
    Those are just the first things that struck me and I'll keep going through the code.

  • Sql exception access denied

    well as the topic says I get an access denied exception. This is when I try to connect to the database
    java.sql.SQLException: Access denied for user 'Java'@'localhost' (using password: YES)
    I get the same problem when I try to connect with the root user.
    this is the code I'm using, ignore the threads as they do not matter
    devil_server.java
    import java.io.*;
    import java.net.MalformedURLException;
    import java.net.*;
    import java.sql.*;
    import java.util.*;
    public class devil_server
    //variable types concerning userthreads
    static public int uid;
    static public int nou;
    static public ServerSocket skanal;
    public static Vector users = new Vector();
    public static Vector usernames = new Vector();
    public static String user;
    public static String pass;
         public static void main(String arg[])
         try {
              System.out.println("write the user used to access the mysql database with Devil Chat");
              user = Keyboard.readString(); //read mysql username from keyboard
              System.out.println("write the password used to access the mysql database with Devil Chat");
              String pass = Keyboard.readString(); //read password for user from keyboard
              uid = 0;
              nou = 0; //Number Of Users
              skanal = new ServerSocket(5555);
              new Thread(new devil_server_user(uid)).start();
              while(true)
                   if(uid>nou)
                        String buffer = "buffer";
                        String userl = "user";
                        users.add(buffer);
                        usernames.add(userl);
                        new Thread(new devil_server_user(uid)).start();
                        nou++;
            }//end while
              }/*end try*/ catch (Exception ex) {
               ex.printStackTrace();
              }//end catch
              //con.close
         } //end main
    }//end classdevil_server_user.java
    import java.io.*;
    import java.net.MalformedURLException;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    public class devil_server_user implements Runnable
    public devil_server_user (int uid){this.uid=uid;};
    public int uid;
    public Socket kanal;
    public InetAddress ip;
    public InputStream streamin;
    public OutputStream streamout;
    public BufferedReader bufferind;
    public PrintWriter printout;
    public String lastuserin;
    public String userinput;
    public String sip;
    public int isadmin;
    //variable types concerning mysql database connectivity
    public Statement stmt;
    //public Statement rstmt;
    public ResultSet rs;
    public Connection conn;
         public void run()
              try {
         System.out.println("Listening on port 5555");
         System.out.println("Waiting for clients");
         kanal = devil_server.skanal.accept();
         devil_server.uid++;
         ip = kanal.getInetAddress();
         sip = ip.toString();
         sip = sip.replace("/","");
         isadmin = 0;
         if(sip.equals("127.0.0.1"))
         isadmin = 1;
         } catch (Exception ex) {
         ex.printStackTrace();
         try {
         System.out.println("Incomming request: "+ ip);
         streamin = kanal.getInputStream();
         System.out.println("Input ready");
         streamout = kanal.getOutputStream();
         System.out.println("Output ready");
         devil_server.users.set(this.uid, printout = new PrintWriter(streamout));
         printout = (PrintWriter)devil_server.users.get(this.uid);
         bufferind = new BufferedReader(new InputStreamReader(streamin));
         catch (IOException e){
         e.printStackTrace();
        try { 
         Class.forName("com.mysql.jdbc.Driver").newInstance();
         conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/Java?user="+devil_server.user+"&password=s"+devil_server.pass);
         stmt = conn.createStatement();
         stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
         } catch (Exception e) {
         e.printStackTrace();
         //String request = bufferind.readLine();
         //System.out.println("message from "+ip+" : "+request);
         //printout.flush();
    //forbindelse
    try {
         userinput = (String)bufferind.readLine();
         } catch(Exception e) {
         e.printStackTrace();
         while(!userinput.startsWith("/name"))
         try {
              userinput = (String)bufferind.readLine();
                   } catch(Exception e) {
         e.printStackTrace();
         try
         stmt = conn.createStatement();
         stmt.executeUpdate("INSERT INTO devilchat_users (ip, username, isadmin) VALUES('"+sip+"',' "+userinput.substring(6)+"','"+isadmin+"')");
         new Thread(new devil_server_broadcast("/say "+userinput.substring(6)+" has joined devilchat")).start();
         devil_server.usernames.set(this.uid, userinput.substring(6));
         printout.println("/knock"); //knocks to the client
         printout.flush();
         userinput = (String)bufferind.readLine();
              } catch(Exception e) {
         e.printStackTrace();
         while(!userinput.startsWith("/knock"))
         try {
         userinput = (String)bufferind.readLine(); //waiting for client to knock back
              } catch(Exception e) {
         e.printStackTrace();
         printout.println("/ready"); //tells client it's ready to read userinput
         printout.flush();
         int spoken = 0;
         System.out.println(devil_server.usernames.get(this.uid)+": has connected");
         new Thread(new devil_server_usercheck()).start();
    //starter l�kke som checker for nye input fra useren
         while(true)
         try{
              userinput = (String)bufferind.readLine();
              if(!userinput.equals(lastuserin))
              if(userinput.startsWith("/name"))
              stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
              rs = stmt.executeQuery("SELECT * FROM devilchat_users WHERE uid='"+this.uid+"'");
              rs.absolute(this.uid);
              String oldname = rs.getString("username"); // get old name from database and save it in a string before applying the new name
              stmt = conn.createStatement();
              stmt.executeUpdate("UPDATE devilchat_users set username='"+userinput.substring(6)+"' WHERE uid ='"+this.uid+"'");
              //start a broadcast to tell the name has changed
              new Thread(new devil_server_broadcast("/namechange *** "+oldname+" has changed their name to "+userinput.substring(6)+" ***")).start();
              //change the username in the vector containing usernames
              devil_server.usernames.set(this.uid, userinput.substring(6));
              //start a new listcheck so the list can be updated
              new Thread(new devil_server_usercheck()).start();
              else if(userinput.startsWith("/say"))
              stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
              rs = stmt.executeQuery("SELECT * FROM devilchat_users WHERE uid='"+this.uid+"'");
              rs.absolute(this.uid);
              String sname = rs.getString("username");
              String say1 = userinput.substring(6);
              userinput = "/say "+sname+": "+say1;
              spoken++;
              stmt = conn.createStatement();
              stmt.executeUpdate("UPDATE devilchat_users set spoken='"+spoken+"' WHERE uid ='"+this.uid+"'");
              new Thread(new devil_server_broadcast(userinput)).start();
              else if(userinput.startsWith("/quit"))
              stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
              rs = stmt.executeQuery("SELECT * FROM devilchat_users WHERE uid='"+this.uid+"'");
              rs.absolute(this.uid);
              String name = rs.getString("username");
              printout.println("/quit "+name+" has left devilchat"); //tells client it's ready to read userinput
              printout.flush();
              devil_server.usernames.set(this.uid, "user");
              devil_server.users.set(this.uid, "buffer");
              new Thread(new devil_server_broadcast("/quit "+name+" has left devilchat")).start();
              conn.close();
              kanal.close();
              break;
              lastuserin = userinput;
         catch(Exception e) {
         e.printStackTrace();
    }this is the full exception handling
    java.sql.SQLException: Access denied for user 'Java'@'localhost' (using password
    : YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
    at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3808)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1256)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
    rce)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java
    :283)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at devil_server_user.run(devil_server_user.java:71)
    at java.lang.Thread.run(Unknown Source)
    java.lang.NullPointerException
    at devil_server_user.run(devil_server_user.java:97)
    at java.lang.Thread.run(Unknown Source)
    I have tried the org driver too and I have tried (url, user, pass) and (url?user=user&password=pass)
    Edited by: Angelwinged_Devil on Mar 13, 2008 6:04 AM

    well it's pretty weird, because I'm trying to make some kind of pattern with the install file I made, although... the install file works and looks like this
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    public class install
        public static void main(String[] args) {
            try {
                // The newInstance() call is a work around for some
                   //older java implementations
                   //org.gjt.mm.mysql.Driver or com.mysql.jdbc.driver
                Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            } catch (Exception ex) {
                ex.printStackTrace();
              try {
              System.out.println("write the user used to access the mysql database with Devil Chat");
              String user = Keyboard.readString(); //read mysql username from keyboard
              System.out.println("write the password used to access the mysql database with Devil Chat");
              String pass = Keyboard.readString(); //read password for user from keyboard
              Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql", user, pass);
              Statement stmt = conn.createStatement();
              stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS Java");
              System.out.println("Database has been created");
              Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/Java", user, pass);
              Statement nstmt = con.createStatement();
              nstmt.executeUpdate("CREATE TABLE IF NOT EXISTS devilchat_users ("+
              "uid int NOT NULL AUTO_INCREMENT, PRIMARY KEY(uid), "
              +"username varchar(25), isadmin bool, spoken int, ip varchar(15))");
              System.out.println("Table has been created");
              con.close();
              conn.close();
                   } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode() + "\n");
    }

  • Exception while starting Weblogic Application Server (ver 7.0)

    While starting WEBLOGIC server (ver 7.0), we are getting the following exception.
    Can anybody help us to correct this problem.
    Following is the Exception we are getting. We couldn't able to trace the reason
    for this error:
    <May 10, 2004 9:22:36 AM IST> <Debug> <TLS> <000000> <SSLManager(server=udaykr,
    realm=myrealm)>
    <May 10, 2004 9:22:36 AM IST> <Notice> <Security> <090082> <Security initializing
    using realm myrealm.>
    <May 10, 2004 9:22:37 AM IST> <Notice> <WebLogicServer> <000327> <Starting WebLogic
    Admin Server "udaykr" for domain "uday">
    <May 10, 2004 9:22:52 AM IST> <Error> <HTTP> <101065> <[HTTP udaykr] Failed to
    obtain localhost name
    java.net.UnknownHostException: -Z
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getLocalHost(Unknown Source)
    at weblogic.servlet.internal.HttpServer.initServerNameAndPort(HttpServer.java:579)
    at weblogic.servlet.internal.HttpServer.start(HttpServer.java:196)
    at weblogic.servlet.internal.WebService.startWebServers(WebService.java:134)
    at weblogic.servlet.internal.WebService.resume(WebService.java:105)
    at weblogic.t3.srvr.ServerLifeCycleList.resume(ServerLifeCycleList.java:61)
    at weblogic.t3.srvr.T3Srvr.resume(T3Srvr.java:812)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:294)
    at weblogic.Server.main(Server.java:31)
    >
    setSessionContext(SessionContext) called from class com.hp.wes.ejb.CaseBean_18uvk_Impl

    While starting WEBLOGIC server (ver 7.0), we are getting the following exception.
    Can anybody help us to correct this problem.
    Following is the Exception we are getting. We couldn't able to trace the reason
    for this error:
    <May 10, 2004 9:22:36 AM IST> <Debug> <TLS> <000000> <SSLManager(server=udaykr,
    realm=myrealm)>
    <May 10, 2004 9:22:36 AM IST> <Notice> <Security> <090082> <Security initializing
    using realm myrealm.>
    <May 10, 2004 9:22:37 AM IST> <Notice> <WebLogicServer> <000327> <Starting WebLogic
    Admin Server "udaykr" for domain "uday">
    <May 10, 2004 9:22:52 AM IST> <Error> <HTTP> <101065> <[HTTP udaykr] Failed to
    obtain localhost name
    java.net.UnknownHostException: -Z
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getLocalHost(Unknown Source)
    at weblogic.servlet.internal.HttpServer.initServerNameAndPort(HttpServer.java:579)
    at weblogic.servlet.internal.HttpServer.start(HttpServer.java:196)
    at weblogic.servlet.internal.WebService.startWebServers(WebService.java:134)
    at weblogic.servlet.internal.WebService.resume(WebService.java:105)
    at weblogic.t3.srvr.ServerLifeCycleList.resume(ServerLifeCycleList.java:61)
    at weblogic.t3.srvr.T3Srvr.resume(T3Srvr.java:812)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:294)
    at weblogic.Server.main(Server.java:31)
    >
    setSessionContext(SessionContext) called from class com.hp.wes.ejb.CaseBean_18uvk_Impl

  • Stocks RMI example not working - Security Exception

    Hi,
    I was trying to run the "Stocks" RMI example that comes with
    Weblogic server(see
    http://www.weblogic.com/docs45/classdocs/API_rmi.html#clientside)
    I compiled and configured the appropriate files, and tried to
    load the sample applet (StockApplet.java) loaded on the
    StockApplet.html page (using Microsoft IE browser).
    However, the applet generated the following exception :
    java.lang.ExceptionInInitializerError: com/ms/security/SecurityExceptionEx
         at weblogic/common/internal/TengahClassLoaders.registerURL (TengahClassLoaders.java:51)
         at weblogic/rjvm/RJVMImpl.loadFromCluster (RJVMImpl.java:1106)
         at weblogic/jndi/WLInitialContextFactoryDelegate.newContext (WLInitialContextFactoryDelegate.java:247)
         at weblogic/jndi/WLInitialContextFactoryDelegate.getInitialContext (WLInitialContextFactoryDelegate.java:205)
         at weblogic/jndi/Environment.getContext (Environment.java:122)
         at weblogic/jndi/Environment.getInitialContext (Environment.java:105)
         at weblogic/rmi/Naming.getContext (Naming.java:225)
         at weblogic/rmi/Naming.lookup (Naming.java:67)
         at examples/rmi/stock/StockApplet.init (StockApplet.java:127)
         at com/ms/applet/AppletPanel.securedCall0 (AppletPanel.java)
         at com/ms/applet/AppletPanel.securedCall (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.run (AppletPanel.java)
         at java/lang/Thread.run (Thread.java)
    As you can see this looks like some sort of security exception. (StockApplet.java:127)
    in the above exception is the line where StockApplet calls Naming.lookup(). So
    I'm guessing it has something to do with it getting the Weblogic's RMI support
    classes to the local VM and deserializing and installing them, which generates
    a security exception.
    What needs to be done to make the example work properly?
    Thanks,
    Leonid Portnoy
    (In addition, two more types of exceptions are generated, which might be related
    to the cause of the above exception. These exceptions are :
    com.ms.security.SecurityExceptionEx[weblogic/rjvm/JVMID.setLocalID]: cannot connect
    to "testserver"
         at com/ms/security/permissions/NetIOPermission.check (NetIOPermission.java)
         at com/ms/security/PolicyEngine.deepCheck (PolicyEngine.java)
         at com/ms/security/PolicyEngine.checkPermission (PolicyEngine.java)
         at com/ms/security/StandardSecurityManager.chk (StandardSecurityManager.java)
         at com/ms/security/StandardSecurityManager.chkex (StandardSecurityManager.java)
         at com/ms/security/StandardSecurityManager.checkConnect (StandardSecurityManager.java)
         at java/net/InetAddress.getLocalHost (InetAddress.java)
         at weblogic/rjvm/JVMID.setLocalID (JVMID.java:59)
         at weblogic/rjvm/JVMID.localID (JVMID.java:43)
         at weblogic/rjvm/LocalRJVM.getID (LocalRJVM.java:143)
         at weblogic/rmi/extensions/BasicServerObjectReference.<init> (BasicServerObjectReference.java:44)
         at weblogic/rmi/extensions/BasicServerObjectAdapter.<init> (BasicServerObjectAdapter.java:43)
         at weblogic/rmi/extensions/BasicRequestHandler.<init> (BasicRequestHandler.java:30)
         at weblogic/rmi/extensions/BasicRequestDispatcher.<init> (BasicRequestDispatcher.java:42)
         at weblogic/rmi/internal/OIDManager.initializeDGCServer (OIDManager.java:267)
         at weblogic/rmi/internal/OIDManager.getReplacement (OIDManager.java:176)
         at weblogic/rmi/internal/OIDManager.replaceObject (OIDManager.java:84)
         at weblogic/rmi/server/UnicastRemoteObject.exportObject (UnicastRemoteObject.java:25)
         at examples/rmi/stock/StockApplet.init (StockApplet.java:110)
         at com/ms/applet/AppletPanel.securedCall0 (AppletPanel.java)
         at com/ms/applet/AppletPanel.securedCall (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.run (AppletPanel.java)
         at java/lang/Thread.run (Thread.java)
    and
    com.ms.security.SecurityExceptionEx[weblogic/jndi/Environment.getProperty]: Unable
    to access system property: weblogic.jndi.provider.rjvm
         at com/ms/security/permissions/PropertyPermission.check (PropertyPermission.java)
         at com/ms/security/PolicyEngine.shallowCheck (PolicyEngine.java)
         at com/ms/security/PolicyEngine.checkCallersPermission (PolicyEngine.java)
         at com/ms/security/StandardSecurityManager.chk (StandardSecurityManager.java)
         at com/ms/security/StandardSecurityManager.checkPropertyAccess (StandardSecurityManager.java)
         at java/lang/System.getProperty (System.java)
         at weblogic/jndi/Environment.getProperty (Environment.java:598)
         at weblogic/jndi/Environment.getProviderRJVM (Environment.java:691)
         at weblogic/jndi/WLInitialContextFactoryDelegate.getInitialContext (WLInitialContextFactoryDelegate.java:166)
         at weblogic/jndi/Environment.getContext (Environment.java:122)
         at weblogic/jndi/Environment.getInitialContext (Environment.java:105)
         at weblogic/rmi/Naming.getContext (Naming.java:225)
         at weblogic/rmi/Naming.lookup (Naming.java:67)
         at examples/rmi/stock/StockApplet.init (StockApplet.java:127)
         at com/ms/applet/AppletPanel.securedCall0 (AppletPanel.java)
         at com/ms/applet/AppletPanel.securedCall (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.run (AppletPanel.java)
         at java/lang/Thread.run (Thread.java)

    Can you post the Stock Applet and other source files...
    Jamal
    ([email protected])

  • StringIndexOutofBounds Exception while doing FTP operation

    Hello, I got this exception at run time when I am doing my FTP operations
    java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:455)
    at FTPConnection.getFullServerReply(FTPConnection.java:312)
    at FTPConnection.getServerReply(FTPConnection.java:296)
    at FTPConnection.executeCommand(FTPConnection.java:329)
    at FTPConnection.login(FTPConnection.java:107)
    at JEditor$FTPUpload.checkTF(JEditor.java:2755)
    at JEditor$FTPUpload.actionPerformed(JEditor.java:2783)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    67)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1820)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:258)
    at java.awt.Component.processMouseEvent(Component.java:5021)
    at java.awt.Component.processEvent(Component.java:4818)
    at java.awt.Container.processEvent(Container.java:1380)
    at java.awt.Component.dispatchEventImpl(Component.java:3526)
    at java.awt.Container.dispatchEventImpl(Container.java:1437)
    at java.awt.Component.dispatchEvent(Component.java:3367)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3214
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2929)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2859)
    at java.awt.Container.dispatchEventImpl(Container.java:1423)
    at java.awt.Window.dispatchEventImpl(Window.java:1566)
    at java.awt.Component.dispatchEvent(Component.java:3367)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:190)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    The file that I used for my FTP is
    * File: FTPConnection.java
    * Author: Bret Taylor <[email protected]>
    * $Id$
    * Parts of this code were adopted from a variety of other FTP classes the
    * author has encountered that he was not completely satisfied with. If you
    * think more thanks are due to any particular author than is given, please
    * let him know. With that caveat, this class can be freely distributed and
    * modified as long as Bret Taylor is given credit in the source code comments.
    import java.io.*;
    import java.net.*;
    import java.util.*;
    * <p>A wrapper for the network and command protocols needed for the most common
    * FTP commands. Standard usage looks something like this:</p>
    * <pre> FTPConnection connection = new FTPConnection();
    * try {
    * if (connection.connect(host)) {
    * if (connection.login(username, password)) {
    * connection.downloadFile(serverFileName);
    * connection.uploadFile(localFileName);
    * connection.disconnect();
    * } catch (UnknownHostException e) {
    * // handle unknown host
    * } catch (IOException e) {
    * // handle I/O exception
    * }</pre>
    * <p>Most FTP commands are wrapped by easy-to-use methods, but in case clients
    * need more flexibility, you can execute commands directly using the methods
    * executeCommand and
    * executeDataCommand,
    * the latter of which is used for commands that require an open data port.</p>
    * @author Bret Taylor
    * @version 1.0
    public class FTPConnection extends Object {
         * If this flag is on, we print out debugging information to stdout during
         * execution. Useful for debugging the FTP class and seeing the server's
         * responses directly.
         private static boolean PRINT_DEBUG_INFO = false;
         * Connects to the given FTP host on port 21, the default FTP port.
         public boolean connect(String host)
              throws UnknownHostException, IOException
              return connect(host, 21);
         * Connects to the given FTP host on the given port.
         public boolean connect(String host, int port)
              throws UnknownHostException, IOException
              connectionSocket = new Socket(host, port);
              outputStream = new PrintStream(connectionSocket.getOutputStream());
              inputStream = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
              if (!isPositiveCompleteResponse(getServerReply())){
                   disconnect();
                   return false;
              return true;
         * Disconnects from the host to which we are currently connected.
         public void disconnect()
              if (outputStream != null) {
                   try {
                        outputStream.close();
                        inputStream.close();
                        connectionSocket.close();
                   } catch (IOException e) {}
                   outputStream = null;
                   inputStream = null;
                   connectionSocket = null;
         * Wrapper for the commands <code>user [username]</code> and <code>pass
         * [password]</code>.
         public boolean login(String username, String password)
              throws IOException
              int response = executeCommand("user " + username);
              if (!isPositiveIntermediateResponse(response)) return false;
              response = executeCommand("pass " + password);
              return isPositiveCompleteResponse(response);
         * Wrapper for the command <code>cwd [directory]</code>.
         public boolean changeDirectory(String directory)
              throws IOException
              int response = executeCommand("cwd " + directory);
              return isPositiveCompleteResponse(response);
         * Wrapper for the commands <code>rnfr [oldName]</code> and <code>rnto
         * [newName]</code>.
         public boolean renameFile(String oldName, String newName)
              throws IOException
              int response = executeCommand("rnfr " + oldName);
              if (!isPositiveIntermediateResponse(response)) return false;
              response = executeCommand("rnto " + newName);
              return isPositiveCompleteResponse(response);
         * Wrapper for the command <code>mkd [directory]</code>.
         public boolean makeDirectory(String directory)
              throws IOException
              int response = executeCommand("mkd " + directory);
              return isPositiveCompleteResponse(response);
         * Wrapper for the command <code>rmd [directory]</code>.
         public boolean removeDirectory(String directory)
              throws IOException
              int response = executeCommand("rmd " + directory);
              return isPositiveCompleteResponse(response);
         * Wrapper for the command <code>cdup</code>.
         public boolean parentDirectory()
              throws IOException
              int response = executeCommand("cdup");
              return isPositiveCompleteResponse(response);
         * Wrapper for the command <code>dele [fileName]</code>.
         public boolean deleteFile(String fileName)
              throws IOException
              int response = executeCommand("dele " + fileName);
              return isPositiveCompleteResponse(response);
         * Wrapper for the command <code>pwd</code>.
         public String getCurrentDirectory()
              throws IOException
              String response = getExecutionResponse("pwd");
              StringTokenizer strtok = new StringTokenizer(response);
              // Get rid of the first token, which is the return code
              if (strtok.countTokens() < 2) return null;
              strtok.nextToken();
              String directoryName = strtok.nextToken();
              // Most servers surround the directory name with quotation marks
              int strlen = directoryName.length();
              if (strlen == 0) return null;
              if (directoryName.charAt(0) == '\"') {
                   directoryName = directoryName.substring(1);
                   strlen--;
              if (directoryName.charAt(strlen - 1) == '\"')
                   return directoryName.substring(0, strlen - 1);
              return directoryName;
         * Wrapper for the command <code>syst</code>.
         public String getSystemType()
              throws IOException
              return excludeCode(getExecutionResponse("syst"));
         * Wrapper for the command <code>mdtm [fileName]</code>. If the file does
         * not exist, we return -1;
         public long getModificationTime(String fileName)
              throws IOException
              String response = excludeCode(getExecutionResponse("mdtm " + fileName));
              try {
                   return Long.parseLong(response);
              } catch (Exception e) {
                   return -1L;
         * Wrapper for the command <code>size [fileName]</code>. If the file does
         * not exist, we return -1;
         public long getFileSize(String fileName)
              throws IOException
              String response = excludeCode(getExecutionResponse("size " + fileName));
              try {
                   return Long.parseLong(response);
              } catch (Exception e) {
                   return -1L;
         * Wrapper for the command <code>retr [fileName]</code>.
         public boolean downloadFile(String fileName)
              throws IOException
              return readDataToFile("retr " + fileName, fileName);
         * Wrapper for the command <code>retr [serverPath]</code>. The local file
         * path to which we will write is given by <code>localPath</code>.
         public boolean downloadFile(String serverPath, String localPath)
              throws IOException
              return readDataToFile("retr " + serverPath, localPath);
         * Wrapper for the command <code>stor [fileName]</code>.
         public boolean uploadFile(String fileName)
              throws IOException
              return writeDataFromFile("stor " + fileName, fileName);
         * Wrapper for the command <code>stor [localPath]</code>. The server file
         * path to which we will write is given by <code>serverPath</code>.
         public boolean uploadFile(String serverPath, String localPath)
              throws IOException
              return writeDataFromFile("stor " + serverPath, localPath);
         * Set the restart point for the next download or upload operation. This
         * lets clients resume interrupted uploads or downloads.
         public void setRestartPoint(int point)
              restartPoint = point;
              debugPrint("Restart noted");
         * Gets server reply code from the control port after an ftp command has
         * been executed. It knows the last line of the response because it begins
         * with a 3 digit number and a space, (a dash instead of a space would be a
         * continuation).
         private int getServerReply()
              throws IOException
              return Integer.parseInt(getFullServerReply().substring(0, 3));
         * Gets server reply string from the control port after an ftp command has
         * been executed. This consists only of the last line of the response,
         * and only the part after the response code.
         private String getFullServerReply()
              throws IOException
              String reply;
              do {
                   reply = inputStream.readLine();
                   debugPrint(reply);
              } while(!(Character.isDigit(reply.charAt(0)) &&
                        Character.isDigit(reply.charAt(1)) &&
              Character.isDigit(reply.charAt(2)) &&
                        reply.charAt(3) == ' '));
              return reply;
         * Executes the given FTP command on our current connection, returning the
         * three digit response code from the server. This method only works for
         * commands that do not require an additional data port.
         public int executeCommand(String command)
              throws IOException
              outputStream.println(command);
              return getServerReply();
         * Executes the given FTP command on our current connection, returning the
         * last line of the server's response. Useful for commands that return
         * one line of information.
         public String getExecutionResponse(String command)
              throws IOException
              outputStream.println(command);
              return getFullServerReply();
         * Executes the given ftpd command on the server and writes the results
         * returned on the data port to the file with the given name, returning true
         * if the server indicates that the operation was successful.
         public boolean readDataToFile(String command, String fileName)
              throws IOException
              // Open the local file
              RandomAccessFile outfile = new RandomAccessFile(fileName, "rw");
              // Do restart if desired
              if (restartPoint != 0) {
                   debugPrint("Seeking to " + restartPoint);
                   outfile.seek(restartPoint);
              // Convert the RandomAccessFile to an OutputStream
              FileOutputStream fileStream = new FileOutputStream(outfile.getFD());
              boolean success = executeDataCommand(command, fileStream);
              outfile.close();
              return success;
         * Executes the given ftpd command on the server and writes the contents
         * of the given file to the server on an opened data port, returning true
         * if the server indicates that the operation was successful.
         public boolean writeDataFromFile(String command, String fileName)
              throws IOException
              // Open the local file
              RandomAccessFile infile = new RandomAccessFile(fileName, "r");
              // Do restart if desired
              if (restartPoint != 0) {
                   debugPrint("Seeking to " + restartPoint);
                   infile.seek(restartPoint);
              // Convert the RandomAccessFile to an InputStream
              FileInputStream fileStream = new FileInputStream(infile.getFD());
              boolean success = executeDataCommand(command, fileStream);
              infile.close();
              return success;
         * Executes the given ftpd command on the server and writes the results
         * returned on the data port to the given OutputStream, returning true
         * if the server indicates that the operation was successful.
         public boolean executeDataCommand(String command, OutputStream out)
              throws IOException
              // Open a data socket on this computer
              ServerSocket serverSocket = new ServerSocket(0);
              if (!setupDataPort(command, serverSocket)) return false;
              Socket clientSocket = serverSocket.accept();
              // Transfer the data
              InputStream in = clientSocket.getInputStream();
              transferData(in, out);
              // Clean up the data structures
              in.close();
              clientSocket.close();
              serverSocket.close();
              return isPositiveCompleteResponse(getServerReply());     
         * Executes the given ftpd command on the server and writes the contents
         * of the given InputStream to the server on an opened data port, returning
         * true if the server indicates that the operation was successful.
         public boolean executeDataCommand(String command, InputStream in)
              throws IOException
              // Open a data socket on this computer
              ServerSocket serverSocket = new ServerSocket(0);
              if (!setupDataPort(command, serverSocket)) return false;
              Socket clientSocket = serverSocket.accept();
              // Transfer the data
              OutputStream out = clientSocket.getOutputStream();
              transferData(in, out);
              // Clean up the data structures
              out.close();
              clientSocket.close();
              serverSocket.close();
              return isPositiveCompleteResponse(getServerReply());     
         * Transfers the data from the given input stream to the given output
         * stream until we reach the end of the stream.
         private void transferData(InputStream in, OutputStream out)
              throws IOException
              byte b[] = new byte[1024]; // 1K blocks I guess
              int amount;
              // Read the data into the file
              while ((amount = in.read(b)) > 0) {
                   out.write(b, 0, amount);
         * Executes the given ftpd command on the server and writes the results
         * returned on the data port to the given FilterOutputStream, returning true
         * if the server indicates that the operation was successful.
         private boolean setupDataPort(String command, ServerSocket serverSocket)
              throws IOException
              // Send our local data port to the server
              if (!openPort(serverSocket)) return false;
              // Set binary type transfer
              outputStream.println("type i");
              if (!isPositiveCompleteResponse(getServerReply())) {
                   debugPrint("Could not set transfer type");
                   return false;
              // If we have a restart point, send that information
              if (restartPoint != 0) {
                   outputStream.println("rest " + restartPoint);
                   restartPoint = 0;
                   // TODO: Interpret server response here
                   getServerReply();
              // Send the command
              outputStream.println(command);
              return isPositivePreliminaryResponse(getServerReply());
         * Get IP address and port number from serverSocket and send them via the
         * <code>port</code> command to the ftp server, returning true if we get a
         * valid response from the server, returning true if the server indicates
         * that the operation was successful.
         private boolean openPort(ServerSocket serverSocket)
              throws IOException
              int localport = serverSocket.getLocalPort();
              // get local ip address
              InetAddress inetaddress = serverSocket.getInetAddress();
              InetAddress localip;
              try {
                   localip = inetaddress.getLocalHost();
              } catch(UnknownHostException e) {
                   debugPrint("Can't get local host");
                   return false;
              // get ip address in high byte order
              byte[] addrbytes = localip.getAddress();
              // tell server what port we are listening on
              short addrshorts[] = new short[4];
              // problem: bytes greater than 127 are printed as negative numbers
              for(int i = 0; i <= 3; i++) {
                   addrshorts[i] = addrbytes;
                   if (addrshorts[i] < 0)
                        addrshorts[i] += 256;
              outputStream.println("port " + addrshorts[0] + "," + addrshorts[1] +
              "," + addrshorts[2] + "," + addrshorts[3] + "," +
              ((localport & 0xff00) >> 8) + "," +
              (localport & 0x00ff));
              return isPositiveCompleteResponse(getServerReply());
         * True if the given response code is in the 100-199 range.
         private boolean isPositivePreliminaryResponse(int response)
              return (response >= 100 && response < 200);
         * True if the given response code is in the 300-399 range.
         private boolean isPositiveIntermediateResponse(int response)
              return (response >= 300 && response < 400);
         * True if the given response code is in the 200-299 range.
         private boolean isPositiveCompleteResponse(int response)
              return (response >= 200 && response < 300);
         * True if the given response code is in the 400-499 range.
         private boolean isTransientNegativeResponse(int response)
              return (response >= 400 && response < 500);
         * True if the given response code is in the 500-599 range.
         private boolean isPermanentNegativeResponse(int response)
              return (response >= 500 && response < 600);
         * Eliminates the response code at the beginning of the response string.
         private String excludeCode(String response)
              if (response.length() < 5) return response;
              return response.substring(4);
         * Prints debugging information to stdout if the private flag
         * <code>PRINT_DEBUG_INFO</code> is turned on.
         private void debugPrint(String message) {
              if (PRINT_DEBUG_INFO) System.err.println(message);
         * The socket through which we are connected to the FTP server.
         private Socket connectionSocket = null;
         * The socket output stream.
         private PrintStream outputStream = null;
         * The socket input stream.
         private BufferedReader inputStream = null;
         * The offset at which we resume a file transfer.
         private long restartPoint = 0L;
    Please help me where am I wrong?
    Thanks

    I would guess the error happens at this line:
    } while(!(Character.isDigit(reply.charAt(0)) && ...
    because apparently reply.length() is 0 at the point of failure, so charAt(0) is beyond the end of the string. You need to check the length first.

  • How to turn off this exception?

    Hi all,
    I am seeing the following java exceptions from the weblogic server.
    java.net.UnknownHostException: unknown
    at java.net.InetAddress.getAllByName0(InetAddress.java:571)
    at java.net.InetAddress.getAllByName0(InetAddress.java:540)
    at java.net.InetAddress.getByName(InetAddress.java:449)
    at
    weblogic.servlet.internal.ServletRequestImpl.getRemoteAddr(ServletRequestImpl.java:840)
    <<<<<<<<<<< failed here
    at weblogic.servlet.logging.CLFLogger.log(CLFLogger.java:54)
    at
    weblogic.servlet.logging.LogManagerHttp.log(LogManagerHttp.java:293)
    at weblogic.servlet.internal.HttpServer.log(HttpServer.java:670)
    <<<<<<<<<<< start to log remote address
    at
    weblogic.servlet.internal.ServletResponseImpl.send(ServletResponseImpl.java:851)
    at
    weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:1636)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    2 questions:
    1) What cause this exception?
    2) Is there anyway to turn off (ignore) this exception? I have looked
    at
    the log file settings but to no avail? Any help or pointers are most
    appreciated.
    Thank you in advance
    drit

    It is "ReverseDNSAllowed" in the ServerConfig : Returns whether or not the kernel
    is allowed to perform reverse DNS lookups.
    freelance_code_inspector <[email protected]> wrote:
    Hi all,
    I am seeing the following java exceptions from the weblogic server.
    java.net.UnknownHostException: unknown
    at java.net.InetAddress.getAllByName0(InetAddress.java:571)
    at java.net.InetAddress.getAllByName0(InetAddress.java:540)
    at java.net.InetAddress.getByName(InetAddress.java:449)
    at
    weblogic.servlet.internal.ServletRequestImpl.getRemoteAddr(ServletRequestImpl.java:840)
    <<<<<<<<<<< failed here
    at weblogic.servlet.logging.CLFLogger.log(CLFLogger.java:54)
    at
    weblogic.servlet.logging.LogManagerHttp.log(LogManagerHttp.java:293)
    at weblogic.servlet.internal.HttpServer.log(HttpServer.java:670)
    <<<<<<<<<<< start to log remote address
    at
    weblogic.servlet.internal.ServletResponseImpl.send(ServletResponseImpl.java:851)
    at
    weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:1636)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    2 questions:
    1) What cause this exception?
    2) Is there anyway to turn off (ignore) this exception? I have looked
    at
    the log file settings but to no avail? Any help or pointers are most
    appreciated.
    Thank you in advance
    drit--
    Dimitri

  • Problem with InetAddress.getByName ("......" ).getHostName(); Help !

    basic problem is that IP does not get resolved under Jdk 1.4 SuSE 7.3
    the following code resolves IP under jdk 1.3 on the same machine, BUT doesn't resolve under Jdk 1.4 on the same machine.
    public class MyTest
         public static void main( String []argv )
              try{
              InetAddress addr = InetAddress.getByName ("64.68.82.30" );               
              String hostName = addr.getHostName();
              System.out.println( hostName );
              }catch( Exception e ){
                   e.printStackTrace();
    hovewer we found that it's not a problem of JDK 1.4 as we have ANOTHER machine with 1.3 and 1.4 running on it where ip gets resolved with the above code.
    maybe some configuration problem ... if so - where and what to configure ...

    more info:
    does not resolve under jdk 1.4 means: it returns the same IP which was passed as a parameter to InetAddress.getByName(). NO exception is thrown.
    reminding: same code on same machine resolves that IP under jdk 1.3

  • InetAddress Question

    I have a small applet that I want to return
    the local computer's hostname.
    It works, but when I leave the page and return
    I get the local loop back as my IP and an exception is throw.
    Why is my computer's port being locked by my first call to InetAddress.getLocalHost(). Is there a way to free my broswer or applet ?

    Its in the start() method.
    I have two <object> tags in my html, that both call the same class file, one of them has a name attribute.
    I do an OnLoad in Javascript using the 'name' of the second <object> to call a method (getvalue())to return the value of the IP to the broswer.
    The Javacode is
    public class GetClientIP extends Applet {
    static public String mystring;
    public String getvalue() {
    return mystring;
    public void start {
    try { InetAddress getIP = InetAddress.getLocalHost();
    mystring += InetAddress.getLocalHost();
    catch (Exception e) {
    e.printStacktace(); }
    }

  • Exception yet no exception?

    Ello,
    I've been trying to make a little program which uses multicasting to send various things over the network using the way as described in the tutorial. However, whenever I try to write my own implementation with multicasting, it always complains about unhandled exceptions. So after I add some exception handling, it all works... Except there is no sign of any exception actually being thrown at all, for example:
            try
                Address_DST = InetAddress.getByName( "230.0.0.1" );
            catch( UnknownHostException e )
                System.out.println("Caught Exception: " + e.getMessage());
            }The code snippet above prints out absolutely nothing, as if nothing had been caught at all. Yet if I remove both the try and catch blocks, it freaks out about an unhandles UnknownHostException. I suppose it would make sense, sine InetAddress.getByName() does check the IP and I don't think 230.0.0.1 doesn't resolve to anything, because it's in the multicast range... Then again, I don't know how clever the whole method itself is...
    Anyways, I got it to work but I don't understand WHY it works... Which is quite annoying... Can anyone help me with this one?

    The unhandled exception message comes from the
    compiler. Your program's not running yet, but
    the compiler knows that getByName can throw
    UnknownHostExceptionAnd Java has rules that you have to account for every checked exception that could come your way--either by catching it or by declaring that you throw it.
    Here's a quick overview of exceptions:
    The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
    RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
    If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
    Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled.

  • Problems in Starting the Sun default server, Exceptions caught

    Hi!
    I m using windows 2003 server,having iis working.
    I hav been installed netbeans1_4_3 sdk , n when i m starting the deployment of Application server or starting default server. Several exceptions are caught listed as(and the entry is done in log in domain1 directory by default):
    [#|2006-02-18T14:25:52.858+0530|SEVERE|sun-appserver-pe8.2|javax.enterprise.system.util|_ThreadID=10;|property_reader.unknownHost
    java.net.UnknownHostException: ajit-d18r738g60: ajit-d18r738g60
         at java.net.InetAddress.getLocalHost(InetAddress.java:1308)
         at com.sun.enterprise.util.net.NetUtils.getCanonicalHostName(NetUtils.java:66)
         at com.sun.enterprise.util.ASenvPropertyReader.setSystemProperties(ASenvPropertyReader.java:161)
         at com.sun.enterprise.tools.launcher.ProcessLauncher.buildInternalCommand(ProcessLauncher.java:468)
         at com.sun.enterprise.tools.launcher.ProcessLauncher.buildCommand(ProcessLauncher.java:404)
         at com.sun.enterprise.tools.launcher.ProcessLauncher.process(ProcessLauncher.java:204)
         at com.sun.enterprise.tools.launcher.ProcessLauncher.main(ProcessLauncher.java:128)
    |#]
    [#|2006-02-18T14:25:53.108+0530|WARNING|sun-appserver-pe8.2|javax.enterprise.tools.launcher|_ThreadID=10;|LAUNCHER005:Spaces in your PATH have been detected. The PATH must be consistently formated (e.g. C:\Program Files\Java\jdk1.5.0\bin; ) or the Appserver may not be able to start and/or stop.  Mixed quoted spaces in your PATH can cause problems, so the launcher will remove all double quotes before invoking the process. The most reliable solution would be to remove all spaces from your path before starting the Appservers components.  |#]
    [#|2006-02-18T14:25:53.118+0530|INFO|sun-appserver-pe8.2|javax.enterprise.tools.launcher|_ThreadID=10;|
    C:/Sun/AppServer/jdk\bin\java
    -client
    -Xmx512m
    -XX:NewRatio=2
    -Dcom.sun.aas.defaultLogFile=C:/Sun/AppServer/domains/domain1/logs/server.log
    -Djava.endorsed.dirs=C:/Sun/AppServer/lib/endorsed
    -Djava.security.policy=C:/Sun/AppServer/domains/domain1/config/server.policy
    -Djava.security.auth.login.config=C:/Sun/AppServer/domains/domain1/config/login.conf
    -Dsun.rmi.dgc.server.gcInterval=3600000
    -Dsun.rmi.dgc.client.gcInterval=3600000
    -Djavax.net.ssl.keyStore=C:/Sun/AppServer/domains/domain1/config/keystore.jks
    -Djavax.net.ssl.trustStore=C:/Sun/AppServer/domains/domain1/config/cacerts.jks
    -Djava.ext.dirs=C:/Sun/AppServer/jdk/jre/lib/ext;C:/Sun/AppServer/domains/domain1/lib/ext;C:/Sun/AppServer/derby/lib
    -Djdbc.drivers=org.apache.derby.jdbc.ClientDriver
    -Djavax.management.builder.initial=com.sun.enterprise.admin.server.core.jmx.AppServerMBeanServerBuilder
    -Dcom.sun.enterprise.config.config_environment_factory_class=com.sun.enterprise.config.serverbeans.AppserverConfigEnvironmentFactory
    -Dcom.sun.enterprise.taglibs=appserv-jstl.jar,jsf-impl.jar
    -Dcom.sun.enterprise.taglisteners=jsf-impl.jar
    -Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
    -Dcom.sun.aas.configName=server-config
    -Dorg.xml.sax.parser=org.xml.sax.helpers.XMLReaderAdapter
    -Ddomain.name=domain1
    -Djmx.invoke.getters=true
    -Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
    -Dcom.sun.aas.promptForIdentity=true
    -Dorg.xml.sax.driver=com.sun.org.apache.xerces.internal.parsers.SAXParser
    -Dcom.sun.aas.instanceRoot=C:/Sun/AppServer/domains/domain1
    -Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
    -Dcom.sun.aas.domainName=domain1
    -Djava.util.logging.manager=com.sun.enterprise.server.logging.ServerLogManager
    -Dproduct.name=Sun-Java-System/Application-Server
    -Dcom.sun.enterprise.overrideablejavaxpackages=javax.faces,javax.servlet.jsp.jstl,javax.xml.bind,javax.help
    -Dcom.sun.aas.configRoot=C:/Sun/AppServer/config
    -Djava.library.path=C:\Sun\AppServer\jdk\jre\bin\client;C:\Sun\AppServer\lib;C:\Sun\AppServer\lib;C:\Sun\AppServer\jdk\bin;.;C:\WINDOWS\system32;C:\WINDOWS;C:\Sun\AppServer\lib;C:\Sun\AppServer\bin;C:\Sun\AppServer\lib;C:\Sun\AppServer\bin;C:\Sun\AppServer\bin;C:\Sun\AppServer\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;;C:\program files\java\jdk1.5.0\bin;
    -Dcom.sun.aas.instanceName=server
    -Dcom.sun.aas.processLauncher=SE
    -cp
    C:/Sun/AppServer/jdk/lib/tools.jar;C:/Sun/AppServer/lib/appserv-rt.jar;C:/Sun/AppServer/lib\activation.jar;C:/Sun/AppServer/lib\admin-cli.jar;C:/Sun/AppServer/lib\appserv-admin.jar;C:/Sun/AppServer/lib\appserv-cmp.jar;C:/Sun/AppServer/lib\appserv-ext.jar;C:/Sun/AppServer/lib\appserv-jstl.jar;C:/Sun/AppServer/lib\appserv-upgrade.jar;C:/Sun/AppServer/lib\commons-launcher.jar;C:/Sun/AppServer/lib\commons-logging.jar;C:/Sun/AppServer/lib\dom.jar;C:/Sun/AppServer/lib\j2ee-svc.jar;C:/Sun/AppServer/lib\j2ee.jar;C:/Sun/AppServer/lib\jax-qname.jar;C:/Sun/AppServer/lib\jaxr-api.jar;C:/Sun/AppServer/lib\jaxr-impl.jar;C:/Sun/AppServer/lib\jaxrpc-api.jar;C:/Sun/AppServer/lib\jaxrpc-impl.jar;C:/Sun/AppServer/lib\jmxremote.jar;C:/Sun/AppServer/lib\jmxremote_optional.jar;C:/Sun/AppServer/lib\jsf-api.jar;C:/Sun/AppServer/lib\jsf-impl.jar;C:/Sun/AppServer/lib\mail.jar;C:/Sun/AppServer/lib\relaxngDatatype.jar;C:/Sun/AppServer/lib\rmissl.jar;C:/Sun/AppServer/lib\saaj-api.jar;C:/Sun/AppServer/lib\saaj-impl.jar;C:/Sun/AppServer/lib\xalan.jar;C:/Sun/AppServer/lib\xercesImpl.jar;C:/Sun/AppServer/lib\xsdlib.jar;C:/Sun/AppServer/lib/install/applications/jmsra/imqjmsra.jar;C:/Sun/AppServer/imq/lib/jaxm-api.jar;C:/Sun/AppServer/imq/lib/fscontext.jar;C:/Sun/AppServer/lib/ant/lib/ant.jar
    com.sun.enterprise.server.PEMain
    start
    display
    native|#]
    [#|2006-02-18T14:25:55.461+0530|SEVERE|sun-appserver-pe8.2|javax.enterprise.system.util|_ThreadID=10;|property_reader.unknownHost
    java.net.UnknownHostException: ajit-d18r738g60: ajit-d18r738g60
         at java.net.InetAddress.getLocalHost(InetAddress.java:1308)
         at com.sun.enterprise.util.net.NetUtils.getCanonicalHostName(NetUtils.java:66)
         at com.sun.enterprise.util.ASenvPropertyReader.setSystemProperties(ASenvPropertyReader.java:161)
         at com.sun.enterprise.server.PEMain.main(PEMain.java:185)
    |#]
    [#|2006-02-18T14:27:04.170
    All the above information is entred in log file after started 2 or 3 time the default server procedure,but not started. So how to come up from this problem

    HI Snjezana!
    You had shown me the right direction, i found the solution : i must hav to connect my system(which is right now stand alone) to internet. And after connecting to internet it works fine.......... but still wld u can tell me ny way through which i can do work without connecting to internet , becoz my frnd is using it in win xp without connecting to intenet, n also J2ME applications r also work when i connect to internet, so ......... plz....
    tell me if u know wht network setting i hav to change ........
    or say me m i right on the thinking as: As my computer is stand alone so tat i doesn;t contain ip address n at that moment the InetAddress class doesn;t find ny ip address n it is throwing the exceptionss. so to solve this problem i hav to assign the ip address .........?? Am i right.............
    plz notify me........

Maybe you are looking for