SitePoint Sponsor

User Tag List

Results 1 to 24 of 24
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Hard coding data in a servlet

    Hi all, I wonder if someone could show me how to 'hard code' user input in a servlet and send it a server. Put another way, I want to say, request information from a server by providing a username and password but rather than having to prompt the user to enter this details I want to hard code it in the servlet and send it to the server.

    Secondly, if I were to send this details over the network (using udp), is there a way to convert the data objects to bytes? I stumbled upon the getBytes() method but unsure how to use it.

    any responses appreciated!

  2. #2
    SiteP0int Weazle hooknc's Avatar
    Join Date
    Dec 2004
    Location
    Socialist Republic of Boulder
    Posts
    937
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    My guess is you're a tad confessed on how the technology works.

    Could you restate what you just asked, but in a different way?
    baby steps... baby steps...

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Basically, im tryna create a test app which sends data to a server over the network to a server program. Since this data is goin over the network, I'd like to convert it to bytes using us-ascii before sending it. I'm having problems with converting the data (in this case username and password). Below is my attempt:

    Code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.net.*;
    
    public class MyProgram extends HttpServlet 
    {
    
    	  public void doGet(HttpServletRequest request,
    						   HttpServletResponse response)
    			throws ServletException, IOException{
    
    	
    		   
     //values in {} are username and password above but in us-ascii - not sure im doing it write
    		
    		byte [] data = {115,151,153,145,060,061,062,063};
    
    		//create and initialise a socket object
    		
    		DatagramSocket aSocket = null;
    		
    			//handle server response here
    
    	 }
    }
    Thanks for any response!
    Ps. I want to be able to send the hard coded data in bytes using us-ascii.
    [/code]
    Last edited by fresher; Oct 20, 2008 at 13:11.

  4. #4
    SiteP0int Weazle hooknc's Avatar
    Join Date
    Dec 2004
    Location
    Socialist Republic of Boulder
    Posts
    937
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You should be able to use the java.lang.String method getBytes(String charsetName).

    You would then pass in a the Charset Name you want. In your case you'll want to pass in "US-ASCII".

    This should then give you the byte[] array you're looking for.

    Now, my guess is that you'll also need to know how to actually send that information to the server application in a way the server application can understand what you're sending it.

    You will have to ask whom ever wrote the server application what that protocol is.

    I would recommend creating a "Server" / "External Application" class that will represent that external server application that will handle all the communication to it.

    Look up the Proxy design pattern.

    Best of Luck.
    baby steps... baby steps...

  5. #5
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by hooknc View Post
    You should be able to use the java.lang.String method getBytes(String charsetName).

    You would then pass in a the Charset Name you want. In your case you'll want to pass in "US-ASCII".

    This should then give you the byte[] array you're looking for.

    Now, my guess is that you'll also need to know how to actually send that information to the server application in a way the server application can understand what you're sending it.

    You will have to ask whom ever wrote the server application what that protocol is.

    I would recommend creating a "Server" / "External Application" class that will represent that external server application that will handle all the communication to it.

    Look up the Proxy design pattern.

    Best of Luck.
    Thanks for your reply but I stumbled upon the getbytes() method but not quite sure how to use it. This is my try:

    Code:
     //send username: Mike and password: 1234 over the network in  bytes
        String data = "Mike 1234"; //hard code input
        bytes [] = data.getBytes(String US-ASCII); //convert to bytes using us-ascii
    ---
    Not sure im doing it the write way coz it fails to compile...

    Any further help appreciated.

    Ps. Protocol in use is UDP also I consulted this page: http://java.sun.com/j2se/1.4.2/docs/...ng/String.html

    thanks

  6. #6
    SiteP0int Weazle hooknc's Avatar
    Join Date
    Dec 2004
    Location
    Socialist Republic of Boulder
    Posts
    937
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You made several mistakes in your code above.

    Try the following example...
    Code:
    public class USASCIITest {
    	
    	public static void main(String[] args) throws Exception {
    		
    		String data = "Mike 1234";
    		
    		byte[] byteArray = data.getBytes("US-ASCII");
    		
    		for(byte tempByte: byteArray) {
    			
    			System.out.println(tempByte);
    		}
    		
    	}
    }
    The output should be:
    Code:
    77
    105
    107
    101
    32
    49
    50
    51
    52
    Hope that clears up some confusion.
    baby steps... baby steps...

  7. #7
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by hooknc View Post
    You made several mistakes in your code above.

    Try the following example...
    Code:
    public class USASCIITest {
    	
    	public static void main(String[] args) throws Exception {
    		
    		String data = "Mike 1234";
    		
    		byte[] byteArray = data.getBytes("US-ASCII");
    		
    		for(byte tempByte: byteArray) {
    			
    			System.out.println(tempByte);
    		}
    		
    	}
    }
    The output should be:
    Code:
    77
    105
    107
    101
    32
    49
    50
    51
    52
    Hope that clears up some confusion.
    Many thanks. would you mind explaining the line below with say a comment please?

    Code:
    ....
    for(byte tempByte: byteArray) {
    
    ....
    I know it's a 'for' loop with the variable tempByte declared as type byte. What I dont catch is why you have a colon : after the tempByte var. Can this written another way? I try it and post it if I can...

    Thanks again.

  8. #8
    SiteP0int Weazle hooknc's Avatar
    Join Date
    Dec 2004
    Location
    Socialist Republic of Boulder
    Posts
    937
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Same program with two different styles of for loops.

    Code:
    public class USASCIITest {
    	
    	public static void main(String[] args) throws Exception {
    		
    		String data = "Mike 1234";
    		
    		byte[] byteArray = data.getBytes("US-ASCII");
    		
    		for(byte tempByte: byteArray) {
    			
    			System.out.println(tempByte);
    		}
    		
    		System.out.println("");
    		
    		for(int i = 0; i < byteArray.length; i++) {
    			
    			byte tempByte = byteArray[i];
    			System.out.println(tempByte);
    		}
    	}
    }
    baby steps... baby steps...

  9. #9
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks 've got the sending bit going ok but now I'm having problems converting the received bytes back into something reasonable. I keep getting something like this:[Ljava.lang.String;@16b4rd2.

    thanks for any response

  10. #10
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by fresher View Post
    Thanks 've got the sending bit going ok but now I'm having problems converting the received bytes back into something reasonable. I keep getting something like this:[Ljava.lang.String;@16b4rd2.

    thanks for any response
    Rite, I guess I havent received any help because either I didnt make my self clear or i didnt post my attempt. Basically, based on the above code, I can send data converted to bytes to the server but I'm finding it hard to convert the response from the server back into readable format. the response is made up both strings and numbers and I've beeb able to extract the strings from the response but not the numbers. my attempt: (following the above code)

    Code:
    //receive reply from server
    ......
    
    aSocket.receive(reply);
    //convert bytes to strings
    //my problem is that since the reply is made up of both strings and integers, //the output gets jumbled up since I'm converting both strings and int to string
    String msg = new String(reply.getData());
    out.println(msg); //output servlet stuff
    
    //other servlet stuff...
    Ps. I'm thinking what I'm tryna do can be done with an array but unsure how...

    any help appreciated!

  11. #11
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    I'm still confused as to why you want to do this. You do understand that computer communication is done in bits, which are arranged into bytes and those bytes may represent numbers, letters or even data structures, right?

    If you're concerned with prying eyes, you need to pursue an encrypt/decrypt solution, rather than attempting (and failing) to obfuscate clear text.

  12. #12
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by rushiku View Post
    I'm still confused as to why you want to do this. You do understand that computer communication is done in bits, which are arranged into bytes and those bytes may represent numbers, letters or even data structures, right?

    If you're concerned with prying eyes, you need to pursue an encrypt/decrypt solution, rather than attempting (and failing) to obfuscate clear text.
    There's no security concern whatsover in this since all run on my home network. what I'm tryna achieve is this:
    1. I send data to server on localhost using UDP. since data will go over the network i convert it to bytes using getbytes method above.
    2.The response (datagram packet) from the server is made up of different data structures such as integers and strings so I want to convert the bytes received into the various data structures so that I can read the data. As you can see from above I have used String() to convert the reply/response into string but this is not ok since the reply also contains numbers. I have stumbled upon the ByteArrayInputStream class which apparently can be used to extract different data structures from an array of bytes but im unsure how to use it.

    In precis, if i received a datapacket of which 3 bytes are numbers and say 17 bytes are strings how can I extract this data say using the bytearrayinputstream class or any other means pls? Thanks

  13. #13
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There's no way to extract specific datatypes using ByteArrayInputStream. You can only read the bytes, but you have to determine how to reconstruct the data. Since you're converting a String into bytes (at least this is what I think you're doing), you can convert those bytes back into a String, or you can go byte by byte and determine if it's a String or number or neither and handle it accordingly.

  14. #14
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by rozner View Post
    , or you can go byte by byte and determine if it's a String or number or neither and handle it accordingly.
    Absolutely what I'm tryna do but after reading the bytes using ByteArrayInputStream how can I determine if it's a string or number and either convert it (if string) or leave it as is (if number). I'm guessing using a for loop but I havent got a clue. So say I wanted to find out what the first 4bytes was and handle it, next 20 bytes etc...Can you please provide a code snippet or smth?

    Thanks

    Ps. i learnt about the ByteArrayInputStream from here: http://tinyurl.com/m7clg

  15. #15
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    well there may be an easier way, but off the top of my head, something like this might work:

    Code:
    for (int i=0; i<bytes.length; i++) {
      if (bytes[i] >= 65 && bytes[i] <= 90) {
        // this is an uppercase letter
      } else if (bytes[i] >= 97 && bytes[i] <= 122) {
       // this is a lowercase letter
      }
      // do similar for other case like digits
    
    }
    Take a look at http://www.asciitable.com/ to determine the ranges. Like 48-57 are digits...

    This is also of course dependent on the encoding. I'm pretty sure US-ASCII is 1 byte/char but I could be wrong.

  16. #16
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    Have you tried this? http://java.sun.com/docs/books/tutor...ams/index.html There's even an example of how to write a UDP client and server.

  17. #17
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello, could someone tell me if its possible to store both a string and integer in an array.

    What exactly I'm tyna do?

    Following on from the above posts I'm trying to send more than one request (string & int to the server. So if I wanted to send the following overthe network: credit 40, deduct -20 how would I do it?

    My attempt:
    Code:
    //declare variables
    String[] s = {"deduct","credit"};
    int[] c = {"40","-20"};
    
    //convet to bytes and send
    byte[] data = s.getbytes();
    byte[] data2 = c.getbytes();
    //create socket
    My main concern is that I dont want to have to convert the string to bytes then convert the integer because they'll both be sent as a single data in the datagram packet thus is there a better way of achieving this pls?

    Thanks

    Ps. Didnt start a new topic since it's related the same thread.

  18. #18
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    well I don't think this will compile

    int[] c = {"40","-20"};

    but anyway, you can always use an Object array.

    Code:
    Object [] data = {"deduct","credit",20,-40};
    but if you need to access the data it's more complicated.

    to access credit you would have to do: (String) data[1]
    to access the number 20 you'd have to do: (Integer) data[2]

    if you get that wrong you'll get a ClassCastException - which is bad.

    Now if you're just planning on doing data.getBytes and be done with it, it should work fine.

  19. #19
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    You could come up with a format for yourself that describes the key/value pairs and allows you to delimit and, subsequently, parse them out of the buffer.

    eg: "deduct:20,credit:-40"

    Split this string on commas and you get:
    deduct:20
    credit:-40

    split the new strings on colon and you get:

    action: deduct, amount: 20
    etc

    Seems simple enough to write the parser, which will build a Set of Key/Value objects and send the Set on for further processing.

  20. #20
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks guys - got it working by storing both string and int as string, converting them to bytes and then sorting them out into string and int (using parseInt..) over at the server.

    At the moment I'm trying to implement reliability (since UDP is in use)so that the server detects a duplicate packet that was sent. From my knowledge of networking, sequence numbers can be used but im not quite sure how to code this. My thought, however is to do something like:

    > send a packet with a number which the server keeps track of then compares it with whatever it receives...not sure I got it rite but I think I have the idea.

    Can someone point me in the direction of implementing this pls? Say using some kind of loop...

  21. #21
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I haven't actually tried this

    http://java.sun.com/docs/books/tutor...entServer.html
    (posted by Rushiku)

    but I would imagine the Java classes for dealing with UDP have some kind of built in error correction.

    Sounds like you're trying to implement your own error detection/correction which is not the easiest thing to do. The first thing that comes to mind is a CRC32 checksum but I don't think it can be used on a per packet basis, it's been a while since my networking course so I'd have to do a bit of reading to give you some other suggestions on this.

  22. #22
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    Apparently the definition of a datagram packet is: "A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed."

    Maybe, extend DatagramPacket to have a sequential ID field and keep copies of the packets in the client until the server sends an 'all good' message.

    Hmmm, a 'begin trans' message wouldn't hurt either.

    So a transaction might go like this:
    (c=client, s=server)

    C: Hi, I'm starting a transaction, it will have 7 packets
    S: Okay, go ahead.
    C: (sends 7 packets)
    S: (receives 6 packets and times out)
    S: Hey, what happened to packet 3?
    C: You didn't get that? I thought I sent it. I'll send another copy.
    S: Okay, got 'em all, talk to you later.
    C: (I'll go ahead and clear my buffer then)

  23. #23
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the suggestions rushiku & rozner but I dont know how to put for instance the sequencial id field suggested by rushiku into the datagram i'm sending. However, I've given the crc32 checksum a go as you can see below. My problem now is how to use it.

    Code:
    //implementation of crc32 on my client side just for test -- i think it should go //on the server or even both client and server
    doGet() { //as this is a servlet
    
    String s = "credit 32";
    byte[] data = s.getbytes();
    CRC32 crc = new CRC32();
    crc.update(data);
    
    int chksum = (int) crc.getvalue();
    //just printing the value for testing since im not sure how to use it yet
    out.println("CRC:"+chksum);
    
    //other code
    }
    Is there a way to sort of append/include this to the packet and say check it again at the server?

    Any help appreciated.
    thanks

  24. #24
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    Assuming you're using the Java DatagramPacket Object, just extend it and add a private ID field with a corresponding get and set.

    Something like
    Code:
    public class MyDatagramPacket extends DatagramPacket {
      private int ID;
      public void setID( int ID ) {
        this.ID = ID;
      }
      public int getID() {
        return ID;
      }
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •