I would like to create journal for my physical file using java program.
a) How we can get the existing journal name and description by passing schema name.?
Ex: DSPFD FILE(SCHEMA_NAME/TABLE_NAME) command is executing successfully but no output in java console.
b) How we can read actual name of table and display in java console.
Thanks in advance.
/**
* Test program to test the AS/400 Command from Java.
*/
public static void main(String[] args) {
String server = "SERVER1";
String user = "USER_ID";
String pass = "PWD_ABC";
String getjournalcmd = "DSPFD FILE(SCHEMA_NAME/TABLE_NAME) OUTPUT(*PRINT)";
String createjournalcmd = "STRJRNPF FILE(SCHEMA_NAME/TABLE_NAME) JRN(SCH_JRN_LIB_NAME/JRN_NAME)";
AS400 as400 = null;
try {
// Create an AS400 object
as400 = new AS400(server, user, pass);
// Create a Command object
CommandCall command = new CommandCall(as400);
// Run the command.
System.out.println("Executing: " + getjournalcmd);
boolean success = command.run(getjournalcmd);
if (success) {
System.out.println("Command Executed Successfully.");
} else {
System.out.println("Command Failed!");
}
// Get the command results
AS400Message[] messageList1 = command.getMessageList();
System.out.println(messageList1.length);
for (AS400Message message : messageList1) {
System.out.println(message.getText());
}
// Create journal
System.out.println("Executing: " + createjournalcmd);
boolean success1 = command.run(createjournalcmd);
if (success1) {
System.out.println("Command Executed Successfully.");
} else {
System.out.println("Command Failed!");
}
// Get the command results
AS400Message[] messageList = command.getMessageList();
System.out.println(messageList.length);
for (AS400Message message : messageList) {
System.out.println(message.getText());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Make sure to disconnect
as400.disconnectAllServices();
} catch (Exception e) {
}
}
System.exit(0);
}
The IBM Toolbox for Java has a class to retrieve that information. Here is the Javadocs. You are going to have to use the IFS name of the object in question which looks like this /QSYS.LIB/libraryname.LIB/filename.FILE
If I wanted to do this, I would try something like this:
String journal = "";
FileAttributes fa = new FileAttributes(myConnection, ifsPath);
if (fa.isJournalingStatus()) {
journal = fa.getJournal();
}
DSPFD output(*print) produces a report but doesn't return anything back to caller. You can use QDBRTVFD API instead to have the values returned back to the caller Java method. Alternative is to create a program on IBM i (AS400) backend that gets the information you need and has a simplified parameter structure.
I have written a code snippet to cpature ping using JPCAP. the code I have written is given below :
while (true) {
try {
PacketCapture m_pcap;
m_pcap = new PacketCapture();
m_pcap.open("\\Device\\NPF_{007262BD-....-7EE83D72EBEA}",true);//param 1 is actual device ID
m_pcap.setFilter("proto ICMP", true);
pktlistener a = new pktlistener(); //handles the packet
m_pcap.addPacketListener(a);
System.out.println("going to sleep");
Thread.sleep(1 * 1000);// Waiting for 1 second before ending capture
System.out.println("woken up");
m_pcap.removePacketListener(a);
m_pcap.endCapture();
m_pcap.close();
a = null;
m_pcap = null;
} catch (Exception e) {
e.printStackTrace();
}
}
Now the above code starts a new capture after every one second. The problem with the above is that after 10 runs of the loop, it throws the exception :
Exception in thread "Thread-6" java.lang.Error: Too many instances, exceeds 10
at net.sourceforge.jpcap.capture.PacketCapture.<init>(PacketCapture.java:51)
Q1. How do i prevent this. I need to start a new PacketCapture every second.
Q2. Is there any other simpler way to capture ping messages recived on a system through java?
You cannot use the constructor of PacketCapture more than ten times. This behavior is hardcoded as the constructor looks like this:
/**
* Create a new packet capture instance.
*/
public PacketCapture() {
if (nextInstance >= INSTANCE_MAX) {
throw new Error("Too many instances, exceeds " + INSTANCE_MAX);
}
instanceNum = nextInstance++;
}
To capture ping requests, you should try the following code
public class Main {
public static void main(String[] args) throws CaptureDeviceLookupException {
Capture cap = new Capture();
cap.doCapture();
}
}
class PingListener implements PacketListener {
#Override
public void packetArrived(Packet packet) {
try {
// only ICMP packages
if (packet instanceof ICMPPacket) {
ICMPPacket tcpPacket = (ICMPPacket) packet;
int data = tcpPacket.getMessageCode();
// only echo request packages
if (data == ICMPMessages.ECHO) {
// print source and destination.
String srcHost = tcpPacket.getSourceAddress();
String dstHost = tcpPacket.getDestinationAddress();
System.out.println("Ping from: " + srcHost + " to " + dstHost);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Capture {
public void doCapture() {
// create capture instance
PacketCapture capture = new PacketCapture();
// add listener that handles incomming and outgoing packages
PingListener pingListener = new PingListener();
capture.addPacketListener(pingListener);
// m_pcap.setFilter("filter here or in handler", true);
try {
capture.open("\\Device\\NPF_{...}", true); // connect capture to device
while (true) {
capture.capture(1); // capture one package
}
} catch (Exception e) {
e.printStackTrace(); // exception during capture or handling of
// packages
} finally {
// technically never reached as the loop goes on forever.
// if loop terminates after a while then:
// remove listener
capture.removePacketListener(pingListener);
// end capture (only necessary, if PacketCapture still waits for
// other packages)
capture.endCapture();
// close connection to capture device
capture.close();
}
}
}
I think there is a misunderstanding of the class PacketCapture. It does not actually capture one package and is then discarded. It opens a connection to the device you want to capture packages of and then starts listening for as long as you hold that connection. You then start capturing n packages by calling capture.capture(n). For each package arriving while "capture" blocks your program, the listener is called.
Alternatively you can drop the while-loop and use capture.capture(-1). This will block your program forever until you close the capture from another device.
I made a simple program in Processing, and it works great. Im now attempting to bring my beginner Java skills to Eclipse to make the same program over again. The program takes a Rs232 string that comes from the Com port and sends it over Xmpp.
The issue I'm having is that i cant call newChat.sendMessage(message) like i can in processing from any of the Classes/Tabs. Can someone clue me in to what i should look for to fix this issue. I'm guessing Extending, or implementing the Xmpp class is what i need to do. I love how simple processing handles it..
Any help will be greatly appreciated.
Fyi: the Smack library's are in the code folder for processing.
Main Application:
import processing.net.*;
void setup() {
size(400, 200);
noStroke();
background(0);
LoadSerialPort();
OpenChatConnection();
setupFilterThread ();
}
void draw() {
}
String timestampTime() {
Calendar now = Calendar.getInstance();
return String.format("%1$tH:%1$tM:%1$tS", now);
}
String timestampDate() {
Calendar now = Calendar.getInstance();
return String.format("%1$tm/%1$td/%1$tY", now);
}
Filter Class/Tab:
FilterThread thread1;
List FilteredArchAddressList = new ArrayList();
ArrayList CallList = new ArrayList();
void setupFilterThread () {
thread1 = new FilterThread(100, "a");
thread1.start();
}
void checkForNewCalls() {
if (CallList.size() >=1) {
println("New Call In List, Size: "+CallList.size());
FilterComPortString((String) CallList.get(0));
CallList.remove(0);
}
}
void FilterComPortString(String s) {
Message message = new Message("icu1#broadcast.server", Message.Type.normal);
//message.setTo("icu1#broadcast.x-dev");
message.setSubject("MSG_TYPE_NORMAL");
message.setBody(s);
message.setProperty("systemID", "JS1");
message.setProperty("serverTime", trim(timestampTime()));
message.setProperty("serverDate", trim(timestampDate()));
try {
newChat.sendMessage(message);
}
catch (Exception e) {
println(e);
}
}
}
class FilterThread extends Thread {
boolean running; // Is the thread running? Yes or no?
int wait; // How many milliseconds should we wait in between executions?
String id; // Thread name
int count; // counter
// Constructor, create the thread
// It is not running by default
FilterThread (int w, String s) {
wait = w;
running = false ;
id = s;
count = 0;
}
int getCount() {
return count;
}
// Overriding "start()"
void start () {
// Set running equal to true
running = true ;
// Print messages
println ("Starting thread (will execute every " + wait + " milliseconds.)");
// Do whatever start does in Thread, don't forget this!
super .start();
}
// We must implement run, this gets triggered by start()
void run () {
while (running) {
checkForNewCalls();
// Ok, let's wait for however long we should wait
try {
sleep((long )(wait));
}
catch (Exception e) {
}
}
System.out.println (id + " thread is done!"); // The thread is done when we get to the end of run()
}
// Our method that quits the thread
void quit() {
System.out.println ("Quitting.");
running = false ; // Setting running to false ends the loop in run()
// IUn case the thread is waiting. . .
interrupt();
}
}
Rs232 Class/Tab:
import processing.serial.*;
Serial myPort; // Rs232, Serial Port
String inString; // Input string from serial port:
int lf = 10; // ASCII linefeed
String SelectedCom;
void LoadSerialPort() {
println(Serial.list());
println("________________________________________________________");
try {
myPort = new Serial(this, Serial.list()[0], 9600);
myPort.bufferUntil(lf);
SelectedCom = Serial.list()[0];
println("Connected to Serial Port:");
println("________________________________________________________");
}
catch (ArrayIndexOutOfBoundsException e) {
String exception = e.toString();
if (exception.contains("ArrayIndexOutOfBoundsException: 0")) {
println("NO AVAILABLE COM PORT FOUND");
}
else {
println(e);
}
}
}
void serialEvent(Serial p) {
inString = p.readString();
CallList.add(new String(inString));
}
Xmpp Class/Tab:
String FromXmpp = "";
Chat newChat;
ChatManager chatmanager;
XMPPConnection connection;
public void OpenChatConnection() {
// This is the connection to google talk. If you use jabber, put other stuff in here.
ConnectionConfiguration config = new ConnectionConfiguration("192.168.0.103", 5222, "Jabber/XMPP");
config.setSASLAuthenticationEnabled(false);
configure(ProviderManager.getInstance());
connection = new XMPPConnection(config);
println("Connecting");
try {
//connection.DEBUG_ENABLED = true;
connection.connect();
println("Connected to: "+connection.getServiceName() );
}
catch (XMPPException e1) {
println("NOT Connected");
}
if (connection.isConnected()) {
try {
// This is the username and password of the chat client that is to run within Processing.
println("Connecting");
connection.login("System1", "test");
//connection.login("inside_processing_username#gmail.com", "yourpassword");
}
catch (XMPPException e1) {
// would probably be a good idea to put some user friendly action here.
e1.printStackTrace();
}
println("Logged in as: "+connection.getUser() );
}
chatmanager = connection.getChatManager();
// Eventhandler, to catch incoming chat events
newChat = chatmanager.createChat("icu#broadcast.server", new MessageListener() { //icu1#broadcast.x-dev //admin#x-dev
public void processMessage(Chat chat, Message message) {
// Here you do what you do with the message
FromXmpp = message.getBody();
// Process commands
//println(FromXmpp);
}
}
);
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
System.out.println(entry);
}
}
public void configure(ProviderManager pm) {
// Private Data Storage
pm.addIQProvider("query", "jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());
// Time
try {
pm.addIQProvider("query", "jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time"));
}
catch (ClassNotFoundException e) {
println(("TestClient "+" Can't load class for org.jivesoftware.smackx.packet.Time"));
}
// Roster Exchange
pm.addExtensionProvider("x", "jabber:x:roster", new RosterExchangeProvider());
// Message Events
pm.addExtensionProvider("x", "jabber:x:event", new MessageEventProvider());
// Chat State
pm.addExtensionProvider("active", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
pm.addExtensionProvider("composing", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
pm.addExtensionProvider("paused", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
pm.addExtensionProvider("inactive", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
pm.addExtensionProvider("gone", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
// XHTML
pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());
// Group Chat Invitations
pm.addExtensionProvider("x", "jabber:x:conference", new GroupChatInvitation.Provider());
// Service Discovery # Items
pm.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
// Service Discovery # Info
pm.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
// Data Forms
pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());
// MUC User
pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());
// MUC Admin
pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin", new MUCAdminProvider());
// MUC Owner
pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());
// Delayed Delivery
pm.addExtensionProvider("x", "jabber:x:delay", new DelayInformationProvider());
// Version
try {
pm.addIQProvider("query", "jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));
}
catch (ClassNotFoundException e) {
// Not sure what's happening here.
}
// VCard
pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());
// Offline Message Requests
pm.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
// Offline Message Indicator
pm.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
// Last Activity
pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());
// User Search
pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());
// SharedGroupsInfo
pm.addIQProvider("sharedgroup", "http://www.jivesoftware.org/protocol/sharedgroup", new SharedGroupsInfo.Provider());
// JEP-33: Extended Stanza Addressing
pm.addExtensionProvider("addresses", "http://jabber.org/protocol/address", new MultipleAddressesProvider());
// FileTransfer
pm.addIQProvider("si", "http://jabber.org/protocol/si", new StreamInitiationProvider());
pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
// Privacy
pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());
pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider());
pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.MalformedActionError());
pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadLocaleError());
pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadPayloadError());
pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadSessionIDError());
pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.SessionExpiredError());
}
If you know your way around eclipse, first you need to create a new Java project and add Processing's core.jar to the build path and start by creating a sublcass of PApplet. If not, there's a really easy to work with eclipse plugin called Proclipsing and video guide to get started with it.
Bringing your code from Processing to eclipse:
You need to understand that all the code you have in a Processing sketch (including tabs) gets merged into a single .java file and the sketch name is the class name. Any classes you define in tabs in the sketch become nested classes in a main single class. Easiest way to see this is to export an applet and have a look in the generated folder for the SketchName.java file. Remember, a tab is not a class (although it can contain one).
So you've got a few options. Here are two basic approaches:
Create a new PApplet subclass and start pasting your whole code in it (including content of tabs). You will need to de explicit about accessors (e.g. public void setup() instead of just void setup()) and be careful with double/float values (e.g. if eclipse complains about 1.0, be explicit: 1.0f)
The other option is to create multiple classes, as I imagine you intend to do if you're using eclipse. The catch is, in Processing, variables defined in tabs are actually 'global' variables. Your code would work the same way if you declare those in the main tab at the top. Also, using PApplet functions needs to be refactored. Some functions can be called using Java's classes (not PApplet's) to break the dependency: e.g. System.out.println() instead of println(), but of others you might want your classes to have access to a PApplet instance:
e.g.
public class FilterThread extends Thread {
boolean running; // Is the thread running? Yes or no?
int wait; // How many milliseconds should we wait in between executions?
String id; // Thread name
int count; // counter
YourSketchClass parent;
// Constructor, create the thread
// It is not running by default
FilterThread (int w, String s,YourSketchClass p) {
wait = w;
running = false ;
id = s;
count = 0;
parent = p;
}
int getCount() {
return count;
}
// Overriding "start()"
public void start () {
// Set running equal to true
running = true ;
// Print messages
System.out.println ("Starting thread (will execute every " + wait + " milliseconds.)");
// Do whatever start does in Thread, don't forget this!
super .start();
}
// We must implement run, this gets triggered by start()
public void run () {
while (running) {
parent.checkForNewCalls();
// Ok, let's wait for however long we should wait
try {
sleep((long )(wait));
}
catch (Exception e) {
}
}
System.out.println (id + " thread is done!"); // The thread is done when we get to the end of run()
}
// Our method that quits the thread
void quit() {
System.out.println ("Quitting.");
running = false ; // Setting running to false ends the loop in run()
// IUn case the thread is waiting. . .
interrupt();
}
}
Every class which uses the chat-functionality, needs to know the chat-object. You can put all your variables and functions which are not in a separate class in the main source-file.
When you declare a variable in Processing, it can be used from any tab, in java global variables do not exist. You can get a similar functionality like this: Create a new file GlobalVars.java with this content:
public class GlobalVars {
public static Chat myChat;
}
Now everytime you want to access the Chat-functions, you have to write e.g. GlobalVars.myChat.sendMessage("Hi!");
Btw, You have to include the net.jar-file. On Mac this is located here:
Processing.app/Contents/Resources/Java/modes/java/libraries/net/library/net.jar
I'm making a multyplayer game and I'm using java sockets for the server, the server is working very well but I think it needs some tweaks regarding the way I'm parsing/handling the requests.
I would like to know if there is a better way of parse the requests instead of splitting input lines by (,) commas like I'm doing.
Should the data sent between the client and server be encrypted in some way? Just a small encryption to obfuscate the requests on sniffers eyes. What is the best way of doing that?
And regarding the thread safe is it OK with Collections.synchronizedList and synchronized blocks on iterations? Or is there a better/cleaner way?
Finally is there any java sockes library that will do all those things above? If so should I use it or is that an overkill for a small java sokets game server.
Is any thing else that I should improve?
Thanks :)
Bellow is the basic structure of my server.
public class Servidor extends Thread {
private ServerSocket serverSocket;
public static boolean LISTENING = true;
private final List<Client> clients = Collections.synchronizedList(new ArrayList<Client>());
private final List<Game> games = Collections.synchronizedList(new ArrayList<Game>());
public Servidor() {
try {
serverSocket = new ServerSocket(SERVER_PORT);
} catch (IOException e) {
Log.add("error starting server: " + e);
}
}
#Override
public void run() {
// Wait for players to connect
while (LISTENING) {
try {
Client c = new Client(serverSocket.accept());
clients.add(c);
c.start();
} catch (IOException e) {}
}
}
class Client extends Thread {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private boolean loggedin;
private Player player;
private Game game;
public Cliente(Socket sock) {
socket = sock;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
} catch (IOException e) {
Log.add("error connecting to player!");
}
}
/* Send to this player */
public void send(String s) {
out.println(s);
}
/* Send to all players on the server */
public void boardcast(String s) {
synchronized (clients) {
for (Client c : clients) {
c.send(s);
}
}
}
/* Get player by ID */
private Player getPlayerByID(int playerID) {
synchronized (clients) {
for (Client c : clients) {
if (c.player != null) {
if (c.player.getID() == playerID) {
return c.player;
}
}
}
}
return null;
}
/* Split inputLine */
private String[] splitInput(String input, int argsNumber) {
String[] args = null;
try {
args = input.split(",", -1);
if (args.length != argsNumber) {
args = null;
}
} catch (Exception ex) {
Log.add("error splitting input");
} finally {
return args;
}
}
#Override
public void run() {
char cmd;
String inputLine, outputLine;
String[] args;
try {
loop:
while ((inputLine = in.readLine()) != null) {
// check if inputLine have 2 chars (CMD_TYPE:)
if (inputLine.length() < 2) {
kickPlayer();
break loop;
}
// get CMD
cmd = inputLine.charAt(0);
// remove (CMD_TYPE:) from inputLine
inputLine = inputLine.substring(2);
// check e player is logged (L:username,password)
if (!loggedin) {
// check if the input string have 2 arguments
if ((args = splitInput(inputLine, 2)) == null) {
kickPlayer();
break loop;
}else{
// ... TESTE LOGIN ON DATABASE ...
// set player data
player = new Player(query.getInt("player_id"), query.getString("username"), query.getInt("level"))
}
}else{
// Commands
switch (cmd) {
// P:CARD_ID,TARGET_ID eg:(P:5:3)
case CMD_PLAY:
// check if the input string have 2 arguments
if ((args = splitInput(inputLine, 2)) == null) {
kickPlayer();
break loop;
} else {
// ... VALIDATE OTHER PARAMETERS ...
// update game
game.addCard(args[0], args[0]);
// update players
boardcast(CMD_PLAY + ":" + player.getID+ "," + game.LastCard());
}
break;
// ... TEST OTHER COMMANDS ...
default:
Log.add("invalid command";
break loop;
}
}
}
} catch (IOException e) {
Log.add("connection lost";
} finally {
removeClient();
}
}
}
}
I am a programmer for 3 years now but now I am really trying to learn network server programming.
Some tips that might help you:
You should take a look about some design patterns to make you code more organized and extensible. You can specify a class for every message type and wrap it. It can use text delimiters or message size for framing the messages.
Keep the message handling code separated from the Client class you created, this makes easier to add support to new messages.
This would be something like:
class ClientHandler
{
public void run()
{
while(isConnected())
messageRouter.handleMessage(getNextMessage());
}
}
interface MessageHandler
{
public boolean canHandle(Message m);
public void handleMessage(Message m);
}
class MessageRouter
{
private List<MessageHandler> handlers;
public void handleMessage(Message msg)
{
for(MessageHandler m : handlers)
{
if(m.canHandle(msg))
{
m.handle(msg);
return;
}
}
throw UnsupportedMessage();
}
}
Something like that...
BTW: I am Brazilian too
good luck with your project
Adding basic security to communication is fairly simple and can be achieved without a lot of hassle. It took me a day of "googling" to figure out how to use it ... I have forgotten most of the details but if you want I can upload the source of my project for you to have a look at ... I personally would recommend some encryption before actually releasing the game...
A link for java ssl sockets can be found here
A link to create your own keystore can be found here
That should help you get started and message me if you want me to upload my source code.
As far as the lists are concerned most of the time you will only be reading the lists so I would suggest that you make a custom lock so that writers must acquire write lock whereas multiple readers can acquire the lock concurrently.. Will require you to design a new class or perhaps you can find a solution on-line.
As far as parsing the string is concerned, to the best of my knowledge objects can be passed remotely so you can transmit array of string instead of having to parse them. I personally broke my communication into several calls to read and write to input streams (probably the slowest approach :) )
and any ways good luck with your project. Message me if you need the source :)
.
I have LinkedList Queue, and I'm trying to read a file with numbers of people in queue waiting to be helped and the number of agents available to help at the time. I do not know to check if they are busy or how to add the people waiting in the queue in the first place. Can anyone help me? This is the code I have so far.
public class WaitingQueue
{
public int [] windows = 0; // every time we add some one check if location occupied
public int time = 0;
public int waitTime = 0;
public static void main(String args[])
{
Queue newQueue = new Queue();
try{
FileInputStream fn = new FileInputStream(args[0]);
BufferedReader br = new BufferedReader(new InputStreamReader(fn));
String line;
while((line = br.readLine()) != null)
{
time++; // happens every time window i busy
waitTime++ // increment waiTime
if ( time for people to arrive)
{
add people to the queue // have to have a queue for people waiting.
//use enque to add people.
}
if(window is open)
{
// move people from queue to window
// use dequeue
}
if(time = x;)
{
// add some people to list
}
}
//Close the input stream
outFile.close();
fn.close();
}
}catch (Exception e)
{/*Catches exception*/
System.err.println("An error has occured : " + e.getMessage());
}
}
--EDIT--
I see your code has now been tagged in Java; my code is more of a c#/pseudo, so you might need to convert it into Java.
--EDIT--
Though this may not help. But I'd suggest a more entity orient approach; something like:
Agents, Agent List: Shall list the available agents
Customers, Customer Queue: Shall maintain a queue of customers wanting help
CustomerSupport Manager:
Shall see if an agent is available(not busy)
Dequeue the customer
Assign it to one of the available agents
Above the top of my head, see following:
Customer:
public class Customer
{
string _strName;
public Customer(string strName) { _strName = strName; }
}
Agent:
public class Agent
{
string _strName;
bool _bIsBusy = false;//
public bool IsBusy { get { return _bIsBusy; } }
Customer _Customer;
public Agent(string strName)
{
_strName = strName;
}
public void HandleCustomer(Customer theCustomer)
{
_Customer = theCustomer;
_bIsBusy = true;//Busy as long as the window is open.
//You might need something that doesnt block;
Thread.Sleep(5 * 1000); //Wait for time to simulate that agent is talking to customer
RemoveCustomer();//Done with the customer.
}
private void RemoveCustomer()
{
_Customer = null;
_bIsBusy = false;
}
}
Manager:
A class that manages the customers and agents, according to availability
public class CustomerServiceBench
{
Queue<Customer> queCustomers = new Queue<Customer>();
List<Agent> lstAgents = new List<Agent>();
Thread thdService;
public CustomerServiceBench()
{
//Something along these lines.
thdService = new Thread(delegate() { WaitAndAddCustomerIfAgentIsAvailable(); });
}
private void AddCustomer()
{
//Add a dummy customer.
Random r = new Random(1231);
queCustomers.Enqueue(new Customer("Customer" + r.Next().ToString()));
Thread.Sleep(5 * 1000); //SpinWait.Once()...
}
private void WaitAndAddCustomerIfAgentIsAvailable()
{
//Thread1 to manage the
}
}
It's not trivial so I suggest you search a bit for a tutorial with lots of example code and then alter it to suit your needs.
8.3 The Producer/Consumer Pattern - Java Threads, Third Edition
The producer-consumer pattern in Java 5: using blocking queues in preference to wait()/notify()