Creating a Gnutella downloading application in Java

Hi I am trying to create an application in Java that is able to simplly download a file from a remote host using the Gnutella (peer-2-peer) protocol. The application accepts 3 arguments:
1 host (IP address or hostname)
2 port (the remote gnutella application is listening on)
3 ss1hash (unique code for the desired file)
Gnutella file transfers work by sending HTTP get request headers to the remote host, which includes the information from the arguments.
This is the application i have created so far...:
import java.io.*;
import java.net.*;
public class GnuttDownloader{
        public static void main(String[] args) throws IOException{
                String host;
                int port;
                host = args[0];
                port = Integer.parseInt(args[1]);
                String sha1Hash;
                sha1Hash = args[2];
                Socket socket=null;
                System.out.println("Starting Downloader...");
                try {
                      socket = new Socket(host, port);
                  // Send request to get root
                  // Be sure to end string with two sets of carriage
                  // return - newline characters.
                  OutputStream outputStream =
                      socket.getOutputStream();
                  PrintWriter out = new PrintWriter(outputStream);
                 out.print ("GET /uri-res/N2R?" + sha1Hash + " HTTP/1.1\r\n"
                            + "User-Agent: Limewire/3.3.5\r\n"
                            + "Host: " + host + ":" + port + "\r\n"
                            + "Connection: Keep-Alive\r\n"
                            + "Range: bytes=0-\r\n\r\n");
                  out.flush();
                  // Fetch response
           InputStream inputStream =
             socket.getInputStream();
           InputStreamReader inputStreamReader =
             new InputStreamReader(inputStream);
           BufferedReader in =
             new BufferedReader(inputStreamReader);
           String response;
           while ((response = in.readLine()) != null) {
             System.out.println(response);
           System.out.print("ARGUMENTS:\nHost: " + host + "\n"
   + "port: " +port + "\nFile's sha1 code: "  + sha1Hash);
           // Close everything
           out.close();
           in.close();
           socket.close();
         } catch (IOException e) {
           System.err.println("Problems talking to " + host + " on port:" + port);
           e.printStackTrace();
     }I have not implemented the file reading/saving part yet, but the application should at least give me a response such as:
HTTP/1.1 200 OK
Server: Gnutella
Content-type: application/binary
Content-length: 4356789
this should verify that it accepts my request, and i should expect a file to be delivered about 4MB long. However this does not happen.
The application manages to connect to a remote host i.e. if I specify a host on my LAN (192.168.0.3) running LimeWire 3.3.5, but instead of receiving the above response, I receive the follwing:
HTTP/1.1 400 Malformed Request
Server: LimeWire/3.3.5
Content-Type: text/plain
Content-Length: 17
Connection: close
Malformed Request
Therefore, i know it is connecting and sending the header, but it seems that it is not understanding the actual header that I send. I can't see anything wrong with it, is there anything that I am doing wrong? Has anyone done anyting like this?Can anyone help me here?
Thanks in advance.

If anyone can help here please????????????????????????????????

Similar Messages

  • How to create a trial version application in java

    hai,
    i'm developing an application in java. i have to made this application as a 30 days trial version... if the customer copy the application and paste it in another system it should not work.. how to perform this task.. i'm new to this task.
    any one help me

    if the customer copy the application and paste it in another system it should not work..That is an extremely hard requirement. You would need to write self modifying code to stop the installer from functioning after its first successful run. Other than that, Java has good cryptography support, and you can make your app writes out the birthday of the time bomb alone with a signature to avoid tempering.

  • Creating a WCF MTOM application with Java Client

    Well I am treading into new ground here.  I need to create a WCF that will pull files from a database in an image column and either send them to a Java service that will accept binary data.  We send an XML file to the Server which is running Java. 
    During the processing of the XML the message may indicate that there are files that need to be included (like attachments in email).  So the Java Service (I suppose) would send a request to a .NET WCF service requesting the files.  The service would
    then retrieve the files from the SQL Server (in the image column) and send them to the calling Java application.  I have been looking around the web some and run across MTOM and I suppose this is the best way to send this, but I have a couple of questions:
    1. Do I need to grab the files from the database and stream them to a temp file first, then use MTOM to send the files?
    2. Can I just send the files from the database to the Java client?  The files are read into a byte array and then saved as a binary data type in SQL Server. (Code to create the file below).
    3.  I am coming into this new so examples would be nice, I mean real basic stuff so I can understand how to make this WCF the correct way.  I have no control over the Java Client, I will let them deal with how to configure the data they get.
    Any help is appreciated.
    Code I use to store any file into SQL:
    Dim fs As New FileStream(filePath, FileMode.Open, FileAccess.Read)
    Dim ilen As Integer = CInt(fs.Length)
    Dim bFile(ilen - 1) As Byte
    fs.Read(bFile, 0, ilen)
    fs.Close()

    Hi,
    Welcome to MSDN.
    I would suggest you consider posting this issue in the forum Mr. Monkeyboy suggested.
    In addition, issues about java are not supported in these forums.
    Thanks for your understanding.
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Need help creating a voice chat application with java

    Hi, all:
    I'm currently using MSN messenger to talk to my friends online. However, the quality gets pretty low sometimes since MSN is a centralized service. So I was wondering if I know a friend well, and he gives me his IP, would it be better for me to just write a simple java app that captures audio from a microphone and send it over through a socket. Once the byte stream gets there, his side of the app can play it back. Of course, the packets I'm sending and receiving will just be normal TCP/IP packets, but we wouldn't have to go through a MSN messenger server, so would the audio quality be better in this case?

    Maybe, but there is probibly other software you can use for direct connections. I would try these first.

  • Download Error in java webstart

    Hi
    I am getting a error while downloading application from java webstart
    I am using Apache 2.2 http server running on port 80
    In that in htdocs folder I have placed my jnlp file and my jar file
    My jnlp file is like this .
    All file are in the folder htdocs/products/
    <jnlp spec="1.0+" codebase="http://127.0.0.1/" href="/products/note.jnlp">
    <information>
    <title>My Application </title>
    <vendor>ABC Pvt Ltd</vendor>
    <homepage href="http://127.0.0.1/products/"/>
    <description>Sample Test</description>
    <shortcut>
    <desktop/>
    <menu submenu="My Application 2.0 (web)"/>
    </shortcut>
    </information>
    <security><all-permissions/></security>
    <resources>
    <j2se version="1.4+" />
    <jar href="/products/Notepad.jar" main="true" download="eager"/>
    </resources>
    <application-desc main-class="Notepad">
    </application-desc>
    </jnlp>
    The error which i am getting is
    An error occurred while launching/running the application.
    Title: My Application
    Vendor: ABC Pvt Ltd
    Category: Download Error
    Bad MIME type returned from server when accessing resource: http://127.0.0.1/products/note.jnlp - text/plain
    JNLPException[category: Download Error : Exception: null : LaunchDesc: null ]
    at com.sun.javaws.cache.DownloadProtocol.doDownload(U nknown Source)
    at com.sun.javaws.cache.DownloadProtocol.isLaunchFile UpdateAvailable(Unknown Source)
    at com.sun.javaws.LaunchDownload.getUpdatedLaunchDesc (Unknown Source)
    at com.sun.javaws.Launcher.downloadResources(Unknown Source)
    at com.sun.javaws.Launcher.handleApplicationDesc(Unkn own Source)
    at com.sun.javaws.Launcher.handleLaunchFile(Unknown Source)
    at com.sun.javaws.Launcher.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Please help ...
    How to solve this issue .
    But the same file is working in Tomcat Server
    please let me know
    Thank you
    Prakash

    Bad MIME type returned from server..A server should return a content type of..
    application/x-java-jnlp-file for JNLP
    files.
    Tomcat probably does that by default, but
    other servers might need to be told about it.
    See your server help, for how to set a
    content-type.

  • I want to create a Ajax based Chating application using java .

    hi . I want to create an chating Application , and ajax based chatting application using java as my server side language ..i have some idea about it .. but one thing that i m not understanding is that how i will communicate with other users because each user has its own session so what i will do to send one messge to all the users ???? . i m new to JavaEE and i have chosen this as my semester project .. i need some help regarding this .

    First get it working without AJAX.

  • How to create a .exe file for a java application

    Hi, I want to create a .exe file for a java application I am developing so that I can schedule it to run at a particular time using Windows Scheduler on WinNT. Is there any way to accomplish this? Or is there any other way in which a Java application can be scheduled to run at a particular time on Windows everyday?

    Create a .bat file and run that. Just have, in the .bat file:
    java YourClassName Alternatively, you can use javaw YourClassName (without *.bat, just put it into Windows Scheduler like suggested above).
    using javaw won't pop up any window...

  • How to create a exe file from a Java application

    hi,
    i have developed an application in java,now i want to distribute it to my client, for this i need to build a .exe file out of this application.
    i already have a jar file ,now can i convert a jar file to a exe file.
    im trying this out with JSmooth project but im getting it right, so can anyone help me .
    thanks,
    vishal j

    if u use dos to run your app like
    "java myapp"
    u can create a shortcut link
    in target wright java remove the path
    just leave the file name without the extension,
    like this Target: "java myapp"
    when u click on appy u'll c that java gets its full path, thats fine
    that works 4 me, ofcourse ur client needs to have JRE or JDK.

  • SAP Web Application Server Java 6.40 download is not working

    SAP Web Application Server Java 6.40 is not working. There seems to be an issue with the server hosting the binaries.
    Antoine Voiry

    try this site
    The SAP WAS 6.40 SP9 is in for of a zip file "WebAS640SP9.zip" it is about 1 GB
    https://www.sdn.sap.com/sdn/downloads.sdn?page=webas640_sp9_maxdb_download.htm
    Also you can go to the site
    https://www.sdn.sap.com/sdn/downloadarea.sdn
    and select "SAP NetWeaver Enterprise Portal on MaxDB, Developer Edition Sneak Preview"
    to download it
    Cheers
    Sai

  • Error in creating upload/download application

    Hi,
    I am trying to create the Howto:Upload/download application and got this error when I browse the file and select submit. Can you please help me to find out why I got this error?
    Thanks,
    Mon, 12 Apr 2004 18:15:58 GMT
    ORA-00942: table or view does not exist
    DAD name: demo
    PROCEDURE : wwv_flow.accept
    URL : http://testserver:80/pls/demo/wwv_flow.accept
    PARAMETERS :
    ===========
    ENVIRONMENT:
    ============
    PLSQL_GATEWAY=WebDb
    GATEWAY_IVERSION=2
    SERVER_SOFTWARE=Apache/1.3.12 (Win32) ApacheJServ/1.1 mod_ssl/2.6.4 OpenSSL/0.9.5a mod_perl/1.22
    GATEWAY_INTERFACE=CGI/1.1
    SERVER_PORT=80
    SERVER_NAME=testserver
    REQUEST_METHOD=POST
    QUERY_STRING=
    PATH_INFO=/pls/demo/wwv_flow.accept
    SCRIPT_NAME=/pls
    REMOTE_HOST=
    REMOTE_ADDR=10.10.2.217
    SERVER_PROTOCOL=HTTP/1.1
    REQUEST_PROTOCOL=HTTP
    REMOTE_USER=
    HTTP_CONTENT_LENGTH=24043
    HTTP_CONTENT_TYPE=multipart/form-data; boundary=---------------------------7d45b3a4013c
    HTTP_USER_AGENT=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)
    HTTP_HOST=testserver
    HTTP_ACCEPT=image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, */*
    HTTP_ACCEPT_ENCODING=gzip, deflate
    HTTP_ACCEPT_LANGUAGE=en-us
    HTTP_ACCEPT_CHARSET=
    HTTP_COOKIE=LOGIN_USERNAME_COOKIE=james; ORACLE_PLATFORM_REMEMBER_UN=janes:james; WWV_FLOW_USER2=4D86B80558A076CE; WWV_CUSTOM-F_604016577451304_100=-1; WWV_CUSTOM-F_604016577451304_104=4D86B80558A076CE
    Authorization=
    HTTP_IF_MODIFIED_SINCE=

    it sounds as if your DAD is referencing a table for its DocumentTablename that doesn't exist. the correct doc table for a supported installation of htmldb is "wwv_flow_file_objects$". my default install of htmldb created a dad like this...
    <Location /pls/htmldb>
    SetHandler pls_handler
    Order deny,allow
    Allow from all
    AllowOverride None
    PlsqlDatabaseUsername HTMLDB_PUBLIC_USER
    PlsqlDatabasePassword %html_db_public_user_pwd%
    PlsqlDatabaseConnectString ap6002wgs.us.oracle.com:1521:apwgs ServiceNameFormat
    PlsqlDefaultPage htmldb
    PlsqlDocumentTablename wwv_flow_file_objects$
    PlsqlDocumentPath docs
    PlsqlDocumentProcedure wwv_flow_file_manager.process_download
    PlsqlAuthenticationMode Basic
    PlsqlNLSLanguage AMERICAN_AMERICA.AL32UTF8
    </Location>
    ...and, again, it sounds as if your "demo" DAD is pointing to something other than wwv_flow_file_objects$. can you check your DAD, please, and let us know if correcting that doesn't fix things for you? also, so you know, that how-to doc assumes that you're using a supported configuration of htmldb. aside from what installs from the 10g companion CD, the only other two supported configurations are mapped out at...
    http://otn.oracle.com/products/database/htmldb/howtos/howto_useoas10g.html
    ...and...
    http://otn.oracle.com/products/database/htmldb/howtos/howto_use9ir2ohs.html
    ...so your "demo" dad should match what's in there.
    thanks,
    raj

  • HT204053 I have an Apple ID created in India. I am unable to download application in another country, during my recent visit. What to do? I have plans to relocate to that country soon

    I have an Apple ID created in India. I am unable to download application in another country, during my recent visit. What to do? I have plans to relocate to that country soon

    When you move to the other country you will need to update your address on your account to be your address in that country, and if using a credit card that will need to be updated to be a credit card that is issued by a bank in your new country and be registered to your address there (you won't be able to use a card issued by an Indian bank except when you are in India).
    You should be able to do by logging into your account on your computer's iTunes via the Store > View Account menu option.

  • I created an Apple ID but i can't able to use it for downloading applications from iTunes store on my 4s iPhone

    I have created an apple id on my 4S iPhone. But i can not able to use it for downloading applications from iTunes store on my phone

    can your computer?
    can your browser ?
    what error does it give you?

  • Not getting application in Java Web Start

    Hello Sir,
    I wanted to run an application using Java Web Start. So, I created a jnlp file and i have mentioned the necessary jar files and the main class file. when I clicked on the jnlp file, the application is running in the Server using Java Web Start and its shortcuts are creates on the desktop and in the startmenu. I am able to run the application by clicking on the shortcut in the server. But I am unable to Download the application in the Java Web Start. It is not showing any Error Messages and the application is not running in the cleint machines.
    The contents of the jnlp file is as follows.
    <?xml version="1.0" encoding="utf-8"?>
    <!-- JNLP File for SimpleClass Demo Application -->
    <jnlp
    spec="1.0+"
    codebase="http://dev01/Dummy/New"
    href="SimpleClass.jnlp">
    <information>
    <title>SimpleClass Demo Application</title>
    <vendor>xxx</vendor>
    <!-- <homepage href="docs/help.html"/> -->
    <description>SimpleClass Demo </description>
    <description kind="short">A demo of Class A and Class B Dependencies in java Web Start.</description>
    <!-- <icon href="images/swingset2.jpg"/> -->
    <!-- <icon kind="splash" href="images/splash.gif"/> -->
    <offline-allowed/>
    </information>
    <security>
    <all-permissions/>
    </security>
    <resources>
    <j2se version="1.4.0"/>
    <jar href="ClassLib.jar"/>
    </resources>
    <application-desc main-class="A"/>
    </jnlp>
    So, please Tell me how to solve this problem.
    Thanking you
    R.Venkatesh
    MakeLogic
    www.makelogic.com
    [email protected]

    Here is an example of my JNLP file that works.
    <?xml version="1.0" encoding="utf-8"?>
    <!-- JNLP File for the Passport Application -->
    <jnlp spec="1.0+" codebase="http://application:8080/application/" href="passport.jnlp">
      <information>
        <title>Passport</title>
        <vendor>WIM Consulting</vendor>
        <homepage href="http://www.wim.ca"/>
        <description>application Passport.</description>
        <description kind="short">Passport</description>
        <icon href="WIMicon.gif" width="32" height="32"/>
        <icon href="WIMsplash.jpg" kind="splash"/>
        <offline-allowed/>
      </information>
      <security>
        <all-permissions/>
      </security>
      <resources>
        <j2se version="1.4+"/>
        <jar href="passport.jar"/>
        <jar href="jars/kunststoff.jar"/>
        <jar href="jars/ldapsec.jar"/>
        <jar href="jars/localedata.jar"/>
        <jar href="jars/mysql-connector-java-3.0.6-stable-bin.jar"/>
      </resources>
      <application-desc main-class="ca.wim.passport.startup"/>
    </jnlp>I am not sure what the problem is.
    "I am unable to Download the application in the Java Web Start"
    If webstart in not actually downloading the jar - is the jar in the correct location?
    Is the server named dev01 and the directory structure actually /Dummy/New?
    Note: you do need to set up the mine type JNLP on your server,
    In my case the location of the JNLP file and main jar file passport is in the following directory.
    c:\Inetpub\WIMRoot\application
    The additional jars are in
    c:\Inetpub\WIMRoot\application
    I hope this may give you some clue
    rykk

  • Create a new web application, how shall I update the file server.xml

    Hi,
    I will create a new web application, i.e named newApp. Then I create a file structure as follows:
    - <server-root>/newApp
    - <server-root>/newApp/WEB-INF
    - <server-root>/newApp/WEB-INF/classes
    Then I must tell the server that I have created a new web application. Then I must update my file server.xml, How shall I do this and where in the file shall I type in the new information?
    I use windows XP Pro, and Tomcat 4.1.27.
    My server.xml file looks like below:
    <!-- 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="Tomcat-Standalone">
    <!-- 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 4.0 documentation bundle for more detailed
    instructions):
    * 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 className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8080" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="100" debug="0" connectionTimeout="20000"
    useURIValidationHack="false" disableUploadTimeout="true" />
    <!-- Note : To disable connection timeouts, set connectionTimeout value
    to -1 -->
    <!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
    <!--
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8443" minProcessors="5" maxProcessors="75"
    enableLookups="true"
    acceptCount="100" debug="0" scheme="https" secure="true"
    useURIValidationHack="false" disableUploadTimeout="true">
    <Factory className="org.apache.coyote.tomcat4.CoyoteServerSocketFactory"
    clientAuth="false" protocol="TLS" />
    </Connector>
    -->
    <!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8009" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" connectionTimeout="0"
    useURIValidationHack="false"
    protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler"/>
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
    port="8009" minProcessors="5" maxProcessors="75"
    acceptCount="10" debug="0"/>
    -->
    <!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
    <!-- See proxy documentation for more information about using this. -->
    <!--
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8082" minProcessors="5" maxProcessors="75"
    enableLookups="true"
    acceptCount="100" debug="0" connectionTimeout="20000"
    proxyPort="80" useURIValidationHack="false"
    disableUploadTimeout="true" />
    -->
    <!-- Define a non-SSL legacy HTTP/1.1 Test Connector on port 8083 -->
    <!--
    <Connector className="org.apache.catalina.connector.http.HttpConnector"
    port="8083" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" />
    -->
    <!-- Define a non-SSL HTTP/1.0 Test Connector on port 8084 -->
    <!--
    <Connector className="org.apache.catalina.connector.http10.HttpConnector"
    port="8084" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" />
    -->
    <!-- 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" jmvRoute="jvm1">
    -->
    <!-- Define the top level container in our container hierarchy -->
    <Engine name="Standalone" 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.3
    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 -->
    <Host name="localhost" debug="0" appBase="webapps"
    unpackWARs="true" autoDeploy="true">
    <!-- 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"/>
    <!-- Define properties for each web application. This is only needed
    if you want to set non-default properties, or have web application
    document roots in places other than the virtual host's appBase
    directory. -->
         <DefaultContext reloadable="true"/>
    <!-- Tomcat Root Context -->
    <Context path="" docBase="ROOT" debug="0"/>
    <!-- Tomcat Examples Context -->
    <Context path="/examples" docBase="examples" debug="0"
    reloadable="true" crossContext="true">
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="localhost_examples_log." suffix=".txt"
    timestamp="true"/>
    <Ejb name="ejb/EmplRecord" type="Entity"
    home="com.wombat.empl.EmployeeRecordHome"
    remote="com.wombat.empl.EmployeeRecord"/>
    <!-- If you wanted the examples app to be able to edit the
    user database, you would uncomment the following entry.
    Of course, you would want to enable security on the
    application as well, so this is not done by default!
    The database object could be accessed like this:
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    UserDatabase database =
    (UserDatabase) envCtx.lookup("userDatabase");
    -->
    <!--
    <ResourceLink name="userDatabase" global="UserDatabase"
    type="org.apache.catalina.UserDatabase"/>
    -->
    <!-- PersistentManager: Uncomment the section below to test Persistent
    Sessions.
    saveOnRestart: If true, all active sessions will be saved
    to the Store when Catalina is shutdown, regardless of
    other settings. All Sessions found in the Store will be
    loaded on startup. Sessions past their expiration are
    ignored in both cases.
    maxActiveSessions: If 0 or greater, having too many active
    sessions will result in some being swapped out. minIdleSwap
    limits this. -1 or 0 means unlimited sessions are allowed.
    If it is not possible to swap sessions new sessions will
    be rejected.
    This avoids thrashing when the site is highly active.
    minIdleSwap: Sessions must be idle for at least this long
    (in seconds) before they will be swapped out due to
    activity.
    0 means sessions will almost always be swapped out after
    use - this will be noticeably slow for your users.
    maxIdleSwap: Sessions will be swapped out if idle for this
    long (in seconds). If minIdleSwap is higher, then it will
    override this. This isn't exact: it is checked periodically.
    -1 means sessions won't be swapped out for this reason,
    although they may be swapped out for maxActiveSessions.
    If set to >= 0, guarantees that all sessions found in the
    Store will be loaded on startup.
    maxIdleBackup: Sessions will be backed up (saved to the Store,
    but left in active memory) if idle for this long (in seconds),
    and all sessions found in the Store will be loaded on startup.
    If set to -1 sessions will not be backed up, 0 means they
    should be backed up shortly after being used.
    To clear sessions from the Store, set maxActiveSessions, maxIdleSwap,
    and minIdleBackup all to -1, saveOnRestart to false, then restart
    Catalina.
    -->
    <!--
    <Manager className="org.apache.catalina.session.PersistentManager"
    debug="0"
    saveOnRestart="true"
    maxActiveSessions="-1"
    minIdleSwap="-1"
    maxIdleSwap="-1"
    maxIdleBackup="-1">
    <Store className="org.apache.catalina.session.FileStore"/>
    </Manager>
    -->
    <Environment name="maxExemptions" type="java.lang.Integer"
    value="15"/>
    <Parameter name="context.param.name" value="context.param.value"
    override="false"/>
    <Resource name="jdbc/EmployeeAppDb" auth="SERVLET"
    type="javax.sql.DataSource"/>
    <ResourceParams name="jdbc/EmployeeAppDb">
    <parameter><name>username</name><value>sa</value></parameter>
    <parameter><name>password</name><value></value></parameter>
    <parameter><name>driverClassName</name>
    <value>org.hsql.jdbcDriver</value></parameter>
    <parameter><name>url</name>
    <value>jdbc:HypersonicSQL:database</value></parameter>
    </ResourceParams>
    <Resource name="mail/Session" auth="Container"
    type="javax.mail.Session"/>
    <ResourceParams name="mail/Session">
    <parameter>
    <name>mail.smtp.host</name>
    <value>localhost</value>
    </parameter>
    </ResourceParams>
    <ResourceLink name="linkToGlobalResource"
    global="simpleValue"
    type="java.lang.Integer"/>
    </Context>
    </Host>
    </Engine>
    </Service>
    </Server>

    To use servlets u have indeed to update your web.xml...Well I'm not sure this is relevant to your case anyway.
    You have to add a <servlet> element to this file.
    Something like this:
    <servlet>
    <servlet-name>blabla</servlet-name>
    <servlet-class>blablapackage.Blablaclass</servlet-class>
    <init-param>...</init-param>
    </servlet>
    Now this may not solve your problem. Make sure you refer to your servlets using their full qualified names.btw, just to be sure, what is your definition of "servlet"? (i mean: any java class or only javax.servlet.Servlet)

  • Creating a file download link on jsp

    I have the following on my jsp. The code worked fine until I tried to use it in a new html design page.
    <code>
    //page name is index.jsp
    try //DISPLAY THE CONTENTS OF THE DATA DIRECTORY
    File dirname = new File(PATH); // create an instance of the File class
    if (dirname.exists()&&dirname.isDirectory())//check to see if File class dirname exists and is valid
    String [] allfiles = dirname.list();//create an array of files in the dirname File class
              for (int i=0; i< allfiles.length; i+=2)//loop through allfiles[] and print out file links
    out.println("<br><table border='1' cellspacing='1' width='99%'>");
                   out.println("<tr><td width='50%' class='pageFont'><input type='checkbox' name='cb' value='"+allfiles[i]+"'>"+allfiles[i]+"      ");
    %>
    <a class="a" href="index.jsp?downfile=C:\\data\\<%=allfiles[i+1]%>">DOWNLOAD</a></td>
    <% if(i+1 < allfiles.length)//PRINTS OUT THE SECOND TD SO THAT WE HAVE 2 COLUMNS OF LINKS
    out.println("<td width='50%' class='pageFont'><input type='checkbox' name='cb' value='"+allfiles[i+1]+"'>"+allfiles[i+1]+"      ");
    %>
    <a class="a" href="index.jsp?downfile=C:\\data\\<%=allfiles[i+1]%>">DOWNLOAD</a></td></tr>
    <%
    out.println("</form></font></table>");
    catch (IOException excep)
         out.println("An IO exception has occured.");
    </code>
    Then when clicked this code is run:
    <code>
    try{
    //CHECK TO SEE IF THE FILE HAS BEEN CLICKED TO DOWNLOAD SINGLE FILE
    if (request.getParameter("downfile") != null)
    String filePath = request.getParameter("downfile");
    File f = new File(filePath);//CREATE AN INSTANCE OF THE FILE CLASS AND POINT IT TO THE LOCATION OF THE DIRECTORY CONTAINING THE FILES
    if (f.exists() && f.canRead())
    response.setContentType ("application/octet-stream");
    response.setHeader ("Content-Disposition", "attachment;filename=\""+f.getName()+"\"");
    response.setContentLength((int) f.length());
    BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(f));
    int i;
    out.clearBuffer();
    while ((i = fileInputStream.read()) != -1) out.write(i);
    fileInputStream.close();
    out.flush();
    </code>
    When I click on this link I get the download dialog box. If I open it I get the following open up in notepad(the files I am trying to give download links are .txt files)
    Below is what is displayed in notepad ALL on 1 line:
    <html>
    <head>
    <LINK rel="stylesheet" ty
    That is displayed in all of the links that I click on. It is the first few lines of html code for index.jsp.
    I know this code is probably not a good way of doing what I need but I got it to work fine until the change.
    I am sure there is an easier way to code the download link without resubmitting the page.
    Thanks in advance!!

    Well all was fine with this jsp until I moved it to ApacheJServ. Now the problem has resurfaced(although it is a little different now)
    I had moved the following code to the top of my page:
    //CHECK TO SEE IF EITHER DOWNFILE OR ZIPFILE VARIABLE EXIST, AND IF THEY DO SET CONTENT TYPE BEFORE SENDING ANY HTML CODE TO THE BROWSER
    try{
    //CHECK TO SEE IF THE FILE HAS BEEN CLICKED TO DOWNLOAD SINGLE FILE
        if (request.getParameter("downfile") != null)
                String filePath = request.getParameter("downfile");
                File f = new File(filePath);//CREATE AN INSTANCE OF THE FILE CLASS AND POINT IT TO THE LOCATION OF THE DIRECTORY CONTAINING THE FILES
                    if (f.exists() && f.canRead())
                        response.setContentType ("application/octet-stream");
                        response.setHeader ("Content-Disposition", "attachment;filename=\""+f.getName()+"\"");
                        response.setContentLength((int) f.length());
                        BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(f));
                        int i;
                        out.clearBuffer();
                        while ((i = fileInputStream.read()) != -1) out.write(i);
                            fileInputStream.close();
                            out.flush();
                            response.flushBuffer();
    catch (Exception e){}
    //This is where the java code ends and the javascript/html code begins.Then further into the page I create the file download links like so:
                            <a class="a" href="main.jsp?downfile=C:\\data\\<%=allfiles[i+1]%>">DOWNLOAD</a>I know this isnt a secure way of doing this but I am on a intranet.
    The problem I am having now is that when I click on one of the links and download the file and then open it, I get the contents of the file plus concatenated to the end of it is the first few HTML lines of the actual jsp that I downloaded the file from. Before I was just getting the first few lines of html from the jsp, not the actual contents of the downloaded file.
    This is an example of what I am getting:
    This is the contents of the file that I downloaded.//This is where the file contents ends.
    <html>
    <head>
    <LINK rel="stylesheet" type="text/css" href="default.css">
    <script language="JavaScript1.2">
    //function that allows user to select all checkboxes
    function doIt(v)
    for(var i=0;i<document.form1.cb.length;i++)
       document.form1.cb.checked=eval(v);
    function swap(imageName,image)
    imageName.src = "templateImages/"+image;
    function imageOver(imageSrc, imageName)
         changeImage = new Image();
         changeImage.src = imageSrc;
         document.images[imageName].src = changeImage.src;
    var hide = true;
    function hideShow( ) /
    Any morre ideas?
    TIA!
    BTW, I went to ApacheJServ because they wont let me use tomcat :(

Maybe you are looking for