String Tokenizer/ Multiple Client app.

Hi all,
I am developing a multi user pure Java App.
My situation:
1. client request server for connection. > server accepted
2. client send his details (name*|*group*|*ID)
3. server receive the string, update itself and other client accordingly
My problem:
1. to send client detail (name*|*group*|*ID), String tokenizer is being used? and *|" serve as delimeter ?
2. how do create an statement that count the total user connected to server or leave the server
3. and how to assign an identifier to each connected client, thus server can perform differ operation based on the identifier.
Thanks Ya, if someone can provide me some suggestions
Happy Life

To answer your problems directly
1. Client Info: Yes, read all information from the client using an inputstream. convert that into a String, and use StringTokenizer (str, "|") to parse the information
2. # of clients: After a client has connected to your server, they will be automatically shunted to another port that that user alone communicates on. You should set up a new thread to listen to data being sent on that port. Keep these listeners in an array/vector/arraylist and use getSize()
3. The identifier could just be their port #

Similar Messages

  • Saving string  from multiple clients on a server data structue

    I have a server which receives updates from multiple clients ( in this example, football scores which are updated periodically by the clients.)
    When the server receives the scores it needs to store them and at certain time intervals send the complete list of scores to multiple terminals at various locations.
    I am approaching this task in stages...
    stage 1.
    ..create the clients and server ...test the clients can send the data and the server can receive the data and output to screen..
    this is completed
    stage 2...
    a/ on the server side store the received scores in a data structure (ArrayList<String> is what I'm thinking.)
    b/ periodically output all scores to the screen (maybe every 30 seconds) and empty the ArrayList..am looking at the Timer class for this part..
    stage 3
    create the monitors and output scores to monitors periodically..
    ======================================================
    right now I'm at stage 2a ie trying to store the received scores in a data structure.
    i've created a method saveScore in the StoreScore class which is called by the StoreScore run method...
    The saveScore method creates an ArrayList and adds the score to it...
    Question
    does every thread create a new instance of storedScores and therefore the scores are stored in a multitude of data structures?
    I think the answer is yes and if so then this is not the solution...
    What I'm thinking is , as all scores can be outputted to the server screen via System.out.println, is there not a way of saving all these scores in a single data structure?
    The code below is the server code..
    any advice much appreciated....thank you
    /*=============================================================== */
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.*;
    class ScoresServer1{
    final static int portNum = 1234; // any number > 1024
    final static int numThreads = 10;
    static ExecutorService pool;
    public static void main(String[] args){
    pool = Executors.newFixedThreadPool(numThreads);
    System.out.println("Server running ...");
    try{  
    ServerSocket servesock = new ServerSocket(portNum);
    // for service requests on port
    while (true){ 
    // wait for a service request on port portNum
    Socket socket = servesock.accept();
    // submit request to pool
    pool.submit(new StoreScore(socket));
    }catch(IOException e){}
    class StoreScore implements Runnable {
    BufferedReader reader;
    Socket sock;
    public StoreScore(Socket clientSOcket) {
    try {
    sock = clientSOcket;
    InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
    reader = new BufferedReader(isReader);
    } catch (Exception ex) { ex.printStackTrace(); }
    public void run() {
    String message;
    try {
    while ((message = reader.readLine()) != null) {
    // System.out.println("latest score: " + message);
    saveScore(message);
    } catch (Exception ex) { ex.printStackTrace(); }
    public void saveScore(String message){
         ArrayList<String> storedScores = new ArrayList<String>();
         storedScores.add(message);
         Iterator<String> t = storedScores.iterator();
              while(t.hasNext()){
                   String s = t.next();
                   System.out.println(s);
    }

    does every thread create a new instance of storedScores and therefore the scores are stored in a multitude of data structures?
    I think the answer is yes and if so then this is not the solution...The answer is yes. However, threads can share data, if they were properly synchronized. You should read the threading tutorial before creating a lot of hard to debug mistakes.
    [http://java.sun.com/docs/books/tutorial/essential/concurrency/]

  • Clarification on downloads on multiple client apps

    Dear all
    We are a small agency currently with a CC account and Single Edition DPS. This is fine for the majority of our projects.
    However, a couple of client are now talking about projects which would require DPS Professional. I wonder if you could help with the following:
    We would need to retain our current Single Edition DPS. Would we be able to open a separate DPS Professional account and use our CC InDesign for these projects and our current Single Edition DPS?
    What is the smallest number of folio downloads a Professional DPS user can purchase and how much are they?
    If we purchase 5k downloads, can we specifically assign this to a folio project for a client? We would not want the downloads spread between all current, live apps and would like to assign downloads to a client project. For example, we may have an app where a client wants to purchase 10k downloads, another which requires 5k. Can we purchase and assign to each folio in this way?
    Many thanks in advance.

    I think it would be wise to wait until new rules for Professional Account are announced (March 12, 2014?).
    It is expected that with new rules, only one app (with renditions for all available platforms) will be allowed per one subscription.
    This would answer your question about buying downloads as well...

  • How do I run multiple java apps in one JVM to reduce memory use?

    Hi all,
    I saw an article either on the web or in a magazine not too long ago about how to "detect" if the app is already running, and if so, it hands off the new instance to the already running JVM, which then creates a thread to run the Java app in. As it turns out, my app will be used in an ASP environment, through Citrix. We may have as many as 50 to 100 users running the same app, each with their own unique user ID, but all using the same one server to run it on. Each instance eats up 25MB of memory right now. So the question is if anybody knows of a URL or an app like this that can handle the process of running the same (or even different Java) apps in one JVM as separate threads, instead of requring several instances of the JVM to run? I know this article presented a fully working example, and I believe I know enough to do it but I wanted ot use the article as a reference to make sure it is done right. I know that each app basically would use the same one "launcher" program that would on first launch "listen" to a port, as well as send a message through the port to see if an existing launcher was running. If it does, it hands off the Java app to be run to the existing luancher application and shuts down the 2nd launching app. By using this method, the JVM eats up its normal memory, but each Java app only consumes its necessary memory as well and doesn't use up more JVM instance memory.
    Thanks.

    <pre>
    import java.util.Properties;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.lang.reflect.Method;
    import java.lang.reflect.InvocationTargetException;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    public class RunProg implements Runnable, Cloneable
    private String iProg;
    private String iArgs[];
    public static void main(String args[])
    new RunProg().main();
    // first step is to start main program itself
    private void main()
    Properties properties = System.getProperties();
    try
    properties.load(new FileInputStream("RunProg.properties"));
    catch(IOException e)
    System.setProperties(properties);
    int i = 0;
    System.out.println("enter main, activeCount=" + Thread.activeCount());
    while(true)
    String program = properties.getProperty("Prog" + i);
    if(program == null)
    break;
    StringTokenizer st = new StringTokenizer(program);
    String[] args = new String[st.countTokens() - 1];
    try
    RunProg rp = (RunProg)this.clone();
    rp.iProg = st.nextToken();
    for(int j = 0; st.hasMoreTokens(); j++)
         args[j] = st.nextToken();
    rp.iArgs = args;
    Thread th = new Thread(rp);
    th.setName("prog" + i + "=" + program);
    th.start();
    System.out.println("prog" + i + "=" + program + ", started");
    catch(CloneNotSupportedException e)
    System.out.println("prog" + i + "=" + program + ", can't start");
    i++;
         System.out.println("end of main, activeCount=" + Thread.activeCount());
    // next step is to start all others one by one
    public void run()
    try
    Class c = Class.forName(iProg);
    Class p[] = new Class[1];
    p[0] = String[].class;
    Method m = c.getMethod("main", p);
    Object o[] = new Object[1];
    o[0] = iArgs;
    m.invoke(null, o);
    catch(ClassNotFoundException e)
    System.out.println(iProg + "ClassNotFoundException");
    catch(NoSuchMethodException e)
    System.out.println(iProg + "NoSuchMethodException");
    catch(InvocationTargetException e)
    System.out.println(iProg + "NoSuchMethodException");
    catch(IllegalAccessException e)
    System.out.println(iProg + "NoSuchMethodException");
    System.out.println(Thread.currentThread().getName() + ", ended");
    System.out.println("exit run, activeCount=" + Thread.activeCount());
    // setup SecurityManager to disable method System.exit()
    public RunProg()
         SecurityManager sm = new mySecurityManager();
         System.setSecurityManager(sm);
    // inner-class to disable method System.exit()
    protected class mySecurityManager extends SecurityManager
         public void checkExit(int status)
              super.checkExit(status);
              Thread.currentThread().stop();
              throw new SecurityException();
    * inner-class to analyze StringTokenizer. This class is enhanced to check double Quotation marks
    protected class StringTokenizer implements Enumeration
    private int currentPosition;
    private int maxPosition;
    private String str;
    private String delimiters;
    private boolean retTokens;
    * Constructs a string tokenizer for the specified string. All
    * characters in the <code>delim</code> argument are the delimiters
    * for separating tokens.
    * <p>
    * If the <code>returnTokens</code> flag is <code>true</code>, then
    * the delimiter characters are also returned as tokens. Each
    * delimiter is returned as a string of length one. If the flag is
    * <code>false</code>, the delimiter characters are skipped and only
    * serve as separators between tokens.
    * @param str a string to be parsed.
    * @param delim the delimiters.
    * @param returnTokens flag indicating whether to return the delimiters
    * as tokens.
    public StringTokenizer(String str, String delim, boolean returnTokens)
    currentPosition = 0;
    this.str = str;
    maxPosition = str.length();
    delimiters = delim;
    retTokens = returnTokens;
    * Constructs a string tokenizer for the specified string. The
    * characters in the <code>delim</code> argument are the delimiters
    * for separating tokens. Delimiter characters themselves will not
    * be treated as tokens.
    * @param str a string to be parsed.
    * @param delim the delimiters.
    public StringTokenizer(String str, String delim)
    this(str, delim, false);
    * Constructs a string tokenizer for the specified string. The
    * tokenizer uses the default delimiter set, which is
    * <code>"&#92;t&#92;n&#92;r&#92;f"</code>: the space character, the tab
    * character, the newline character, the carriage-return character,
    * and the form-feed character. Delimiter characters themselves will
    * not be treated as tokens.
    * @param str a string to be parsed.
    public StringTokenizer(String str)
    this(str, " \t\n\r\f", false);
    * Skips delimiters.
    protected void skipDelimiters()
    while(!retTokens &&
    (currentPosition < maxPosition) &&
    (delimiters.indexOf(str.charAt(currentPosition)) >= 0))
    currentPosition++;
    * Tests if there are more tokens available from this tokenizer's string.
    * If this method returns <tt>true</tt>, then a subsequent call to
    * <tt>nextToken</tt> with no argument will successfully return a token.
    * @return <code>true</code> if and only if there is at least one token
    * in the string after the current position; <code>false</code>
    * otherwise.
    public boolean hasMoreTokens()
    skipDelimiters();
    return(currentPosition < maxPosition);
    * Returns the next token from this string tokenizer.
    * @return the next token from this string tokenizer.
    * @exception NoSuchElementException if there are no more tokens in this
    * tokenizer's string.
    public String nextToken()
    skipDelimiters();
    if(currentPosition >= maxPosition)
    throw new NoSuchElementException();
    int start = currentPosition;
    boolean inQuotation = false;
    while((currentPosition < maxPosition) &&
    (delimiters.indexOf(str.charAt(currentPosition)) < 0 || inQuotation))
    if(str.charAt(currentPosition) == '"')
    inQuotation = !inQuotation;
    currentPosition++;
    if(retTokens && (start == currentPosition) &&
    (delimiters.indexOf(str.charAt(currentPosition)) >= 0))
    currentPosition++;
    String s = str.substring(start, currentPosition);
    if(s.charAt(0) == '"')
    s = s.substring(1);
    if(s.charAt(s.length() - 1) == '"')
    s = s.substring(0, s.length() - 1);
    return s;
    * Returns the next token in this string tokenizer's string. First,
    * the set of characters considered to be delimiters by this
    * <tt>StringTokenizer</tt> object is changed to be the characters in
    * the string <tt>delim</tt>. Then the next token in the string
    * after the current position is returned. The current position is
    * advanced beyond the recognized token. The new delimiter set
    * remains the default after this call.
    * @param delim the new delimiters.
    * @return the next token, after switching to the new delimiter set.
    * @exception NoSuchElementException if there are no more tokens in this
    * tokenizer's string.
    public String nextToken(String delim)
    delimiters = delim;
    return nextToken();
    * Returns the same value as the <code>hasMoreTokens</code>
    * method. It exists so that this class can implement the
    * <code>Enumeration</code> interface.
    * @return <code>true</code> if there are more tokens;
    * <code>false</code> otherwise.
    * @see java.util.Enumeration
    * @see java.util.StringTokenizer#hasMoreTokens()
    public boolean hasMoreElements()
    return hasMoreTokens();
    * Returns the same value as the <code>nextToken</code> method,
    * except that its declared return value is <code>Object</code> rather than
    * <code>String</code>. It exists so that this class can implement the
    * <code>Enumeration</code> interface.
    * @return the next token in the string.
    * @exception NoSuchElementException if there are no more tokens in this
    * tokenizer's string.
    * @see java.util.Enumeration
    * @see java.util.StringTokenizer#nextToken()
    public Object nextElement()
    return nextToken();
    * Calculates the number of times that this tokenizer's
    * <code>nextToken</code> method can be called before it generates an
    * exception. The current position is not advanced.
    * @return the number of tokens remaining in the string using the current
    * delimiter set.
    * @see java.util.StringTokenizer#nextToken()
    public int countTokens()
    int count = 0;
    int currpos = currentPosition;
    while(currpos < maxPosition)
    * This is just skipDelimiters(); but it does not affect
    * currentPosition.
    while(!retTokens &&
    (currpos < maxPosition) &&
    (delimiters.indexOf(str.charAt(currpos)) >= 0))
    currpos++;
    if(currpos >= maxPosition)
    break;
    int start = currpos;
    boolean inQuotation = false;
    while((currpos < maxPosition) &&
    (delimiters.indexOf(str.charAt(currpos)) < 0 || inQuotation))
    if(str.charAt(currpos) == '"')
    inQuotation = !inQuotation;
    currpos++;
    if(retTokens && (start == currpos) &&
    (delimiters.indexOf(str.charAt(currpos)) >= 0))
    currpos++;
    count++;
    return count;
    </pre>
    RunProg.properties like this:
    Prog1=GetEnv 47838 837489 892374 839274
    Prog0=GetEnv "djkfds dfkljsd" dsklfj

  • Multiple clients on socket connection

    Hi!
    I understand that it is possible that multiple clients listen to one server (on the same port) and even write to it (then it should be a multi-threaded server).
    But i would like to refuse connectios, if one client is connected. How can I do that?
    In my case I have a (single threaded) server. Now one clients connects. The server waits to receive data from the client and answers, without ever closing the port. that works.
    Now if I connect with a second client, the openicng of the socket in the second client works fine, although the server does not seem to notice the second client. Communication is not possible between the server and the second client, and the server doesn't answer to the first client anymore, although he receives data from it.
    So, since the server does not seem to notice the second client (does not accept the connection) and I don't get an exception at the second client, what can I do?
    Thank you for your help!
    concerned Code (if you want to take a look at it):
    CLIENT:
    socket = new Socket(hostname, echo_port);
    SERVER:
    try
    ServerSocket waitingsocket = new ServerSocket(echo_port);
    try
         socket= waitingsocket.accept();
         System.out.println("Client connected");
         ReaderThread reader = new ReaderThread( this, socket );
         reader.start();          
    catch (Exception e)
    READER:
    public void run()
         while (true)
              try {
                   int bytesRead = inStream.read(inputBuffer,
                   0, inputBuffer.length);
                   readCallback.tcpUpdate(inputBuffer,bytesRead);
              catch (Exception oops)
                   readCallback.tcpUpdate(null,-1);
              

    Just to make sure this is clear: You can NOT have multiple clients on a given socket connection. You CAN have multiple clients connected to a particular port on a given server, but each client will be communicating with the server through a different of socket.
    The usual approach here is to set up a listening ServerSocket on the desired port, call accept() on it, then process the communication from the returned Socket object. This is usually done by spawning a new thread and allowing it to handle the socket communication, while the ServerSocket loops around to another accept() for the next communication.
    Here's an excellent intro to the concepts (the code is really ugly and poorly implemented, but it does a good job of explaining the overall concept). I used this as a starting point, and now (after a whole lot of development) have a pretty sweet extensible web server class that handles template expansion, etc... (I use this as a quick and dirty UI for some of my apps, instead of requiring the user to install a JSP container):
    http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/
    - K

  • [Windows 8.1 Desktop/Surface/Phone] connect client app to synchronization service(s)

    Hello Everybody!
    I have to do some research about:  what is the best way to set up my project, I am new to Azure.
    Situation:
    I need to develop a service(s) and client app(s) that are able to synchronize data with each other: files and database changes. the client app(s) must have the capability  to work online / offline,  offline: when there is no internet connection
    the data has to be stored local on the client device(s) and sync it later when there is active internet connection.
    Client Devices:
    Windows 8.1 (Windows 8.1 PC/Desktop)             
    Windows 8.1 RT (Windows 8.1 Surface tablet)
    Windows Phone 8.1 (Windows 8.1 Smart-phone)
    We prefer to create the clients as a C# Store App Application.
    Service:
    This might become , if technically possible and preferable, a Azure service who main task it is to manage the communication between the server and the clients
    Last days I spend my time doing research about how to get this done right.
    I found several interesting techniques, some of got all the features I needed, and some just a few, but most of them aren't supported on one or more devices.
    Microsoft Synchronization Framework
      Sync Toolkit WinRT / Phone
     Live SDK
    Microsoft Synchronization Framework - got all the features I need but is not supported on Win RT and Phone
    Sync Toolkit WinRT / Phone - Only Database Sync, is got bad documentation and unknown if supported on Desktop
    Live SDK - Libraries to integrate with OneDrive, Only File Sync
    Questions:
    Does Azure support all the devices?
    Is Azure supported in  C# Windows 8.1 Store Apps?
    Is Azure suited to host a service I described?
    Thanks in advanced!

    Hi JelteV,
    Thanks for posting!
    Base on my experience, if you wan to synchronize data with each clients. I suggest you could refer to this solution:
    1.Create a Sql Azure Database or storage account for storing your data 
    2.Create a WCF service (web role or work role ) for communication between Client and Database
    3.Set Up Table Structure (Important). I suggest you could add the deviceID and userID to distinguish the different data source. And add fields such as 'status', 'create time', 'latest update time' and so on.
    For example, you client insert a record into local database and set the 'status' as ‘stay update’ or '1'. When your client connect the database and synchronize the data to server, you could set the 'status' as 'updating' or '2' . After
    synchronization  data, you could change the status as 'updated' or '3'.
    According to this idea, the client CRUD -> change the local state code
    -> Sync data -> change the local state code ->
    synchronization is complete -> change the local state code .If the mobile device need operate the data on the service , it also need to change the server status code to be updated, to be deleted (deleted should
    be treated differently), the next time the client login server automatically checks the "state" as "pending action" and then synchronize the server to the client. So whether it is operating on a local table, or on the side of the direct
    operation of the service, you can ensure that the data is synchronized two tables.
    >>Does Azure support all the devices?
    >>Is Azure supported in  C# Windows 8.1 Store Apps?
    >>Is Azure suited to host a service I described?
    From your question, I think you could create a WCF service host on azure, and call WCF service form different devices. And this method is supported the different device and win8.1 store app.
    Also, please see this thread:
    http://stackoverflow.com/questions/14595738/net-data-synchronization-between-multiple-clients-and-a-central-server
    Hope this helps.
    Regards,
    Will
    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.

  • How to handle multiple clients with DatagramSocket

    I am trying to handle multiple clients with 1 datagramSocket bind to one port (basically I have only one port to use, and I can not use TCP or any other ports). At the server side I have two threads one for receiving packets and buffering them, another for processing the packets in the buffer and sending replies.
    I can have multiple clients sending datagramPackets to me and I will have to process the packets and send them to DIFFERENT clients. Ex. Client 1 sends datagramPacket to Server which sends the processed packet to Client 2. Also Client 2 sends a datagramPacket to Server which again processes the packet and sends it to Client1. May have Client 3 and 4 doing the same thing at the same time... and so on...
    My root class is creating the datagramSocket(somePort) and two threads (receiver and sender). How can I use the socket that I created in these two threads??
    I have done the following and I am getting "java.net.bindexception". When I am sending stuff from Client1 to Client2 everything is fine but when I start sending something from Client2 to Client 1, I get the bindexception... Client 1 is using port 3000, Client 2 is using port 4000.
    I really don't have a lot of experience in socket programming so I am not sure if there is a much simpler way to do this. I appreciate all the tips and help that I can get...
    Thanks...
    class UDP_serv
         static DatagramSocket udpSocket;
         final static int SERVER_PORT     = 2000;
         public static void main(String[] args) throws SocketException
              udpSocket= new DatagramSocket(SERVER_PORT);
              new DataReceiver().start ();
              new DataSender().start ();
         static class DataReceiver extends Thread
              DataReceiver()
                   Thread.currentThread().setName("DataReceiver");
              public void run()
                   while (true)
                        byte pckt[] = new byte [MaxMsgSize];          
                        DatagramPacket dp = new DatagramPacket (pckt, pckt.length);
                        try
                             udpSocket.receive (dp);
                             //PUSH TO RECEIVE BUFFER
                        catch(Exception e)
                             e.printStackTrace();
         static class DataSender extends Thread
              DataSender()
                   Thread.currentThread().setName("DataSender");
              public void run()
                   while (true)
                        processDataMsg();
          static void processDataMsg() 
             DatagramPacket op;
             InetAddress DA = null;
             int DP = 0;
             byte [] outPacket = null;
             // POP FROM RECEIVE BUFFER
             // SOME PROCESSING HERE     
             // Set Destination Address (DA)
             // Set Destination Port (DP)
             // DA and DP are the forwarding IP and Port addresses
             // not the addresses original packet was sent from.
             try
              op = new DatagramPacket (outPacket, outPacket.length,DA, DP);
              udpSocket.send(op);
             catch (IOException e)
              e.printStackTrace();
    }Also for development and testing purposes, I am running the two clients and the server on the same machine (windows xp-32b) so all of the Destination IP Addresses are 127.0.0.1. and as I said Ports that I am using are 2000, 3000, 4000 (Server, Client1, Client2).

    Hmm I have minimized the code and it seems to be working now.
    I think I have an error in the header portion of the data I am sending, where I am storing the source IP/Port and destination IP/Port. I think the server in the middle is messing these values up while sending them to the destination Client. Because the destination client actually receives the stuff and sends the reply back to the server, but the reply packet's headers has 0/0 as the dest IP / Port...
    Server is giving me java.net.BindException: Cannot assign requested address error when it tries to forward the reply it received from the client2 as the address it is trying to send is 0!
    I guess it doesnt just give this error when you try to open two sockets to the same port...
    Paul, Thanks for the direction on how to proceed... took me a while get the minimized code but at least figured out the problem. Well still have to make sure that is THE problem though :)
    As far as the statics goes how can I change those to non static ones? Where do I make an instance of the top level class that creates the threads? and how do I pass the DatagramSocket to the threads/ if I dont need to pass how do I call or use the datagramSocket I created in the top level class? I mean do I still kinda have it like a global variable on the top?? A very simple example would be much appreciated...
    I think these might be really basic questions but I am having a rough time with the hierarchy in java...

  • Tips on localizing rich client apps

    We are currently using a properties resource file with around 1200 lines of localized
    messages/text. There is also an ApplicationResource class which contains string constants corresponding to the keys in the language file.
    -- client_en_US.properties --
    table.column.name=Name
    table.column.address=Address
    ApplicationResources.class
    public static final String TABLE_COLUMN_NAME="table.column.name";
    public static final String TABLE_COLUMN_ADDRESS="table.column.address";
    -- client app --
    ApplicationResources.getResources().getText(ApplicationResources.TABLE_COLUMN_NAME);
    The biggest disadvantage with this solution is that the ApplicationResources class gets very big and consumes quite a lot of memory, you'll end up with a string instance for each text that you want to localize. The advantage is that client devs don't have to look into the properties file for the proper key name instead they can use code completion(eclipse etc) and use the constant defined to get localized text. We also minimize runtime errors when property names are not found.
    We don't have any restrictions on the memory on the client side but I feel that this solution is definetly not very optimal and quite "ugly".
    Any suggestions on how to do this "properly"?

    The biggest disadvantage with this solution is that the ApplicationResources class gets very big
    and consumes quite a lot of memory, you'll end up with a string instance for each text that you
    want to localize.Actually, you don't create any string instances that you wouldn't otherwise create. Further, the class consumes disk space but not necessarily memory, because the static final fields are inlined into the classes which use them, so if they're the only members of the class there's no reason for it to be loaded.
    I feel that this solution is definetly not very optimal and quite "ugly".There aren't any nice ways of doing this, because you have to have some duplication. Your way of doing it is no worse than any other I've seen.
    If you really want to be sure that you don't hit runtime issues, my advice would be to write a model checker to put into your build process which scans the bytecode for calls to getText, asserts that the parameter is a constant string, and scans the properties files to ensure each has an entry with that string as its key.

  • Problem using multiple Client Certificates

    Hi folks, I had (mistakenly) posted an earlier version of this question to the crypto forum.
    My problem is that I have multiple client certs in my keystore, but only one is being used as the selected certificate for client authentication for all connection�s. So, one connection works fine, the rest fail because the server doesn�t like the client cert being presented.
    I have been trying to get the JSSE to select the proper client certificate by making use of the chooseClientAlias method. (init the SSL context with a custom key manager that extends X509ExtendedKeyManager and implements the inherited abstract method X509KeyManager.chooseClientAlias(String[], Principal[], Socket))
    But, still no luck.. the JSSE is not calling in to the my version of chooseClientAlias, and it just keeps presenting the same client certificate.
    No clue why, any thoughts on how to get the JSSE to call my version of chooseClientAlias?
    Thanks!
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(createCustomKeyManagers(Keystore, KeystorePassword),
                createCustomTrustManagers(Keystore, KeystorePassword),null);
    SSLSocketFactory factory = sslContext.getSocketFactory();
    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    urlConn = (HttpsURLConnection) conn;
    urlConn.setSSLSocketFactory(factory);
    BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
         System.out.println(line);  }
    public class CustomKeyManager extends X509ExtendedKeyManager
        private X509ExtendedKeyManager defaultKeyManager;
        private Properties serverMap;
        public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket)
            SocketAddress socketAddress = socket.getRemoteSocketAddress();
            String hostName = ((InetSocketAddress)socketAddress).getHostName().toUpperCase();
            String alias = null;
            if(serverMap.containsKey(hostName)){
                alias = serverMap.getProperty(hostName.toUpperCase());
                if(alias != null && alias.length() ==0){
                    alias = null; }
            else {
                alias = defaultKeyManager.chooseClientAlias(keyType, issuers, socket);
            return alias;
    .

    Topic was correctly answered by ejp in the crypto forum..
    namely: javax.net.ssl.X509KeyManager.chooseClientAlias() is called if there was an incoming CertificateRequest, according to the JSSE source code. If there's an SSLEngine it calls javax.net.ssl.X509ExtendedKeyManager.chooseEngineClientAlias() instead.*
    You can create your own SSLContext with your own X509KeyManager, get its socketFactory, and set that as the socket factory for HttpsURLConnection.*
    Edited by: wick123 on Mar 5, 2008 10:26 AM

  • Publishing server doesn't work - error 'The request URL doesn't contain the query string for the client OS'

    Hi,
    I'm trying to setup an App-V environment in my lab.
    I've used the App-V 5.0 Trial guide to help me configure all necessary components.
    I'm able to install everything without error.
    when come time to publish an app, it simply doesn't show up on my client.
    after looking at events on the client and server, I found that the Publishing server is returning under Admin the following message.
    'The request URL doesn't contain the query string for the client OS'
    My setup is pretty simple.
    App-V Server managament and Publishing on the same box
    App-V database on my SQL server.
    I'm able to see the publishing "webpage" by using http:://localhost:889.
    It only display this :
    -<Publishing Protocol="1.0"
    <Packages />
    </Publishing>
    I've published one app from the management console.
    any idea what could mean this error?
    thanks

    Hi,
    thanks for the link.
    I've validated the suggested debug steps. It seems that the problem is with my Publish server again.
    I've looked in the web.config file. It seems to be missing some parts compare to the example provided.
    Again, I've published an application from the management console. Management and Publishing are running on the same box, while SQL is remote.
    Here's the web.config
    <?xml version="1.0" ?>
    - <configuration>
    - <system.web>
    <compilation debug="false" targetFramework="4.0" />
    <machineKey validationKey="AutoGenerate,IsolateApps" decryptionKey="AutoGenerate,IsolateApps" />
    - <authentication>
    - <!-- We don't support form authentication, but this will supress x-ray security warning
    -->
    <forms requireSSL="true" />
    </authentication>
    </system.web>
    - <system.webServer>
    - <modules runAllManagedModulesForAllRequests="true">
    <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
    - <security>
    - <requestFiltering>
    - <verbs>
    <remove verb="GET" />
    <add verb="GET" allowed="true" />
    </verbs>
    </requestFiltering>
    </security>
    </system.webServer>
    - <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    + <behaviors>
    - <serviceBehaviors>
    - <behavior name="">
    <serviceAuthorization impersonateCallerForAllOperations="true" />
    <serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
    </behavior>
    </serviceBehaviors>
    </behaviors>
    - <bindings>
    - <webHttpBinding>
    - <binding name="SecureBinding">
    - <security mode="Transport">
    <transport clientCredentialType="Windows" />
    </security>
    </binding>
    <binding name="UnsecureBinding" />
    </webHttpBinding>
    </bindings>
    - <protocolMapping>
    <add scheme="http" binding="webHttpBinding" bindingConfiguration="UnsecureBinding" />
    <add scheme="https" binding="webHttpBinding" bindingConfiguration="SecureBinding" />
    </protocolMapping>
    - <standardEndpoints>
    - <webHttpEndpoint>
    - <!--
    Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
    via the attributes on the <standardEndpoint> element below
    -->
    <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
    </webHttpEndpoint>
    </standardEndpoints>
    </system.serviceModel>
    </configuration>

  • TES 6.1.0.x Multiple Client Managers

    Hello:
    I am trying to find out if there is anyone else using multiple client managers on a load balancer and if we could have a discussion regarding such a setup. We have this in our envrionment and it does work, however sometimes I see oddities with in the client - even if I log directly into one of my client managers, by-passing the load balancer completely.
    Looking forward to hearing from anyone with a similar setup.
    Regards,
    Ceceil Rufo

    We haven't done a formal load testing yet.  But we have conducted training with 10 - 15 users and would experience performance sometimes people just getting kicked out.  At the time though we were still finagling with server configuration settings for threads, cache and java heap.  During training too what seemed to impact performance more was the browser and version, and workstation memory.  For a web app, TES 6.1 uses a LOT of memory so there were some suggested tweaks that had to be done on some machines.  We have more consistent performance on IE 9 (than IE 10), and Firefox 18+ was faster.
    I have installed Jconsole and am planning to conduct load testing sometime this month where i could monitor server resource from Jconsole to get an idea where bog down really is. 
    There is a TES 6.1 presentation doc that sort of outlines approx sizing based on concurrent users - we fit in the 10 -20 concurrent users given that our CM has 12GB RAM (allocated 10GB to TES) and 4 core.  So hopefully with two CMs we can have upto 40.  We are open to adding more mem if needed.  So what tools do you use for Load testing?  Also I wonder if it was possible to automate Load Testing like with Jmeter or something.  For now we just plan on getting 20 users together to perform set functions at the same time and measure that with 1 CM up and me looking in Jconsole.
    I also notice the multiple connections, even see myself twice even when I only have 1 browser session.  Not having had a chance to dig to deeply i was chalking it up to maybe that I didn't exit properly last time so that it has to wait 30 minuts to totally clear me (with time to live setting) out but haven't really tested formally.  I will see about adding that to my testing.  I would also think it would impact system in that some folks may cause the number of concurrent connections allowed to be exceeded if you have too many of these lying around but since they are not doing anything perhaps not performance as much?  It will be good to confirm though that a single web session really only takes 1 connection and won't potentially spawn another somehow.
    Our implementation being highly distributed with workgroups having full autonomy over their jobs - means every team needs to have access to Transporter.  We have over 15 teams. Which is scary since that also takes resources from the CM -  and also from a management and training perspective.  We also haven't load tested the Transporter server interms of number of concurrent users that can be running Transporter on it at one time.  Nor have any clear idea yet how we'll manage the mapping files.  But we are also opening up Transporter to be installed by teams on their team server (only that they have to patch themselves) - I really wonder if we should just restrict Transporter access to just the servers our team manage and no one else can install it anywhere else.

  • Multiple Client Logon in JCO

    Dear All,
    We import an RFC as a Model and the names used for the connections are used to create JCO connections in the WEB AS.
    However we have a need where we will know the SAP Client number only on the runtime. This means that the JCO connections can not be pre created in the WEB AS.
    To solve this i tried the following solution:
    I created 2 JCO connections for 2 different client Numbers in WEB AS. After importing the RFC i went to the class file where the connection name is mentioned. I applied a condition by coding to choose one of the JCO Connections which i created programatically. However when i rebuild the project this complete code is overwritten to the connection name specified in the wizard during the RFC model import.
    Can anyone suggest answers for the following ?
    - How can i manipulate the connection name of the JCO in code without being overwritten during rebuild ?
    - Do you know of any other ways other of achieving my objective of connecting to multiple clients and deciding the connection name on the runtime?
    Kind Regards,
    Mukesh

    Hi Mukesh,
       If you already have a JCo connection created based on the LDAP credentials, you can fetch the details like this:
    try {
    IWDJCOClientConnection clientCon =  WDSystemLandscape.getJCOClientConnection("<name of the JCO connection>");
    String clientName      = clientCon.getClientName();
    String lang          = clientCon.getLanguage();
    String passowrd          = clientCon.getPassword();
    String sysID          = clientCon.getSystemIdentifier();
    String user          = clientCon.getUser();
    //etc...
    } catch (WDSystemLandscapeException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    Is this what you are looking for?
    Regards,
    Satyajit.
    Message was edited by: Satyajit Chakraborty

  • One Server Multiple Clients

    Hello,
    This server code accepts only one client connection at a time. However, I have several lines that are specifically for the server to accept more than one client. What do I need to do in addition for the server to recognize that it can accept more than one client at a time?
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    import javax.swing.JFrame;
    public class ServerTest
       public static void main( String args[] )
          Server application = new Server();
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          application.runServer();
    class Server extends JFrame
       private JTextField enterField;
       private JTextArea displayArea;
       private ObjectOutputStream output;
       private ObjectInputStream input;
       private ServerSocket server;
       private Socket connection;
       private int counter = 1;
       private ExecutorService serverExecutor;
       private MultiServer clients[];
       public Server()
          super( "Server" );
          enterField = new JTextField();
          enterField.setEditable( false );
          enterField.addActionListener(
             new ActionListener()
                public void actionPerformed( ActionEvent event )
                   sendData( event.getActionCommand() );
                   enterField.setText( "" );
          add( enterField, BorderLayout.NORTH );
          displayArea = new JTextArea();
          add( new JScrollPane( displayArea ), BorderLayout.CENTER );
          setSize( 300, 150 );
          setVisible( true );
       public void runServer()
          serverExecutor = Executors.newCachedThreadPool();
          try
             server = new ServerSocket( 12345, 100 );
             while ( true )
                try
                   waitForConnection();
                   getStreams();
                   processConnection();
                catch ( EOFException eofException )
                   displayMessage( "\nServer terminated connection" );
                finally
                   closeConnection();
                   counter++;
          catch ( IOException ioException )
             ioException.printStackTrace();
       private void waitForConnection() throws IOException
          displayMessage( "Waiting for connection\n" );
          connection = server.accept(); 
          serverExecutor.execute( new MultiServer(server, connection));     
          displayMessage( "Connection " + counter + " received from: " + connection.getInetAddress().getHostName() );
       private void getStreams() throws IOException
          output = new ObjectOutputStream( connection.getOutputStream() );
          output.flush();
          input = new ObjectInputStream( connection.getInputStream() );
          displayMessage( "\nGot I/O streams\n" );
       private void processConnection() throws IOException
          String message = "Connection successful";
          sendData( message );
          setTextFieldEditable( true );
          serverExecutor.execute(new MultiServer(server, connection));
          do
             try
                message = ( String ) input.readObject();
                displayMessage( "\n" + message );
             catch ( ClassNotFoundException classNotFoundException )
                displayMessage( "\nUnknown object type received" );
          } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
       private void closeConnection()
          displayMessage( "\nTerminating connection\n" );
          setTextFieldEditable( false );
          try
             output.close();
             input.close();
             connection.close();
          catch ( IOException ioException )
             ioException.printStackTrace();
       private void sendData( String message )
          try
             output.writeObject( "SERVER>>> " + message );
             output.flush();
             displayMessage( "\nSERVER>>> " + message );
          catch ( IOException ioException )
             displayArea.append( "\nError writing object" );
       private void displayMessage( final String messageToDisplay )
          SwingUtilities.invokeLater(
             new Runnable()
                public void run()
                   displayArea.append( messageToDisplay );
       private void setTextFieldEditable( final boolean editable )
          SwingUtilities.invokeLater(
             new Runnable()
                public void run()
                   enterField.setEditable( editable );
      class MultiServer extends Thread
      public MultiServer(ServerSocket servers, Socket connection)
          servers = server;
      public void run(){System.out.print("Yes");}
    }

    Check out the "Supporting Multiple Clients" bit here: http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html
    Start a Thread for each client. I'd recommend you create a class:
    class Client
        Socket socket;
        ObjectOutputStream out;
        ObjectInputStream in;
        ...any other client-specific data you need...
        public void sendMessage(String s) { ...send to this client...; }
       ...any other client-specific methods you need...;
    }Create one of those when accept() gets a new connection, then start the thread for that client.
    You may want to keep a LinkedList that contains all the Client objects. E.g. if you want to send a message to all clients you'd loop over the LinkedList and send to each in turn. Synchronize the list appropriately. Removing clients from the list when they close down can be interesting :-) so be careful.

  • Send data to multiple clients from a server

    My problem statement is this:
    A server is created, say X. Multiple clients are created, say A, B & C. If X sends a message to A it should reach only A and should not go to B or C. Similarly if X sends message to B it should not reach A or C. I made a one to one communication with the following code:
    //Server
    import java.io.*;
    import java.net.*;
    class X
    public static void main(String args[])throws Exception
    ServerSocket ss=new ServerSocket(4321);
    try
    Socket s=ss.accept();
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    DataOutputStream out = new DataOutputStream(s.getOutputStream());
    String str=in.readLine();
    out.writeBytes(str+"\n");
    s.close();
    ss.close();
    catch (IOException e){}
    //Client A
    import java.io.*;
    import java.net.*;
    class A
    public static void main(String args[])throws Exception
    try
    Socket s=new Socket("localhost",4321);
    BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
    System.out.println(in.readLine());
    s.close();
    catch(Exception e){}
    }But i dont know how to keep track of each client. Because all the clients sockets are created at the same port, ie. 4321. I think thread will help. But even then i dont know how to identify each client. Somebody please help. Thanks in advance.
    Edited by: sowndar on Dec 5, 2009 1:21 AM

    YoungWinston wrote:
    sowndar wrote:
    Ok. I think i have to attach an unique ID to each client message. So that, with the help of that ID, the server can identify each client. Have i caught ur point?If you don't mind using a port per client, you could do something like a receptionist taking incoming calls (on 4321 only).
    - Hi I'm Client xyz.
    - Hi Client xyz, please call me back on port abcd and I'll put you straight through to our server.
    Since 4321 is an "open line" you might have to have some sort of ID so that Clients know which return messages are meant for them, but messages on the other ports would all be direct Client to Server. Also, the Server is then is charge of port allocation and communication on the "open" port is kept to a minimum.4321 is the socket that the server is listening to. It's not what the actual communication will be carried out over. Run this, then telnet to port 12345 a few times
    public class TestServerSocket {
      public static void main(String[] args) throws Exception {
              ServerSocket server = new ServerSocket(12345);
              while (true) {
                   Socket socket = server.accept();
                   System.err.println(socket.getPort());
    }Notice how each inbound connection is allocated a unique outbound socket.

  • Error: XPath query string returns multiple nodes

    Hi all,
    I am facing issue with the assign activity.
    Error message:
    com.oracle.bpel.client.BPELFault: faultName: {{http://schemas.xmlsoap.org/ws/2003/03/business-process/}selectionFailure} parts: {{ summary=&lt;summary>*XPath query string returns multiple nodes. The assign activity part and query are returning multiple nodes. The assign activity part and query named in the error message returned multiple nodes. It should return single node. According to BPEL4WS specification 1.1 section 14.3, the assign activity part and query named in the error message should not return multiple nodes. Verify the part and xpath query named in the error message at line number 2005 in the BPEL source*.
    BPEL code:
    <copy>
    <from variable="Invoice_Tax_loopCounter"/>
    <to variable="Var_Invoice_Tax_Contacts" part="payload" query="/ns30:Invoice_Tax_Contacts/ns30:Invoice/ns29:Get_InvoiceOutput[bpws:getVariableData'Invoice_Tax_loopCounter')]/ns29:ADDR_ATTRIBUTE2"/>
    </copy>
    We are using SOA 11.1.1.3 version.
    Any pointers on this?
    Thanks in advance

    Hi-
    This is because you are have multiple nodes either in source or target XML.
    My guess is some nodes of your XML might be repeating (means a single element/node has multiple values). Can you please check that or please post your XML here.
    Edited by: 145678 on Mar 7, 2011 6:28 PM

Maybe you are looking for