diff --git a/src/client/BackgroundAnimation.java b/src/client/BackgroundAnimation.java new file mode 100644 index 0000000..ba30b10 --- /dev/null +++ b/src/client/BackgroundAnimation.java @@ -0,0 +1,417 @@ +package client; + +import java.awt.AlphaComposite; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Composite; +import java.awt.Container; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GridBagLayout; +import java.awt.HeadlessException; +import java.awt.Image; +import java.awt.Insets; +import java.awt.LayoutManager; +import java.awt.LayoutManager2; +import java.awt.Paint; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionAdapter; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import java.awt.font.FontRenderContext; +import java.awt.font.TextLayout; +import java.awt.geom.AffineTransform; +import java.awt.geom.Area; +import java.awt.geom.Ellipse2D; +import java.awt.geom.GeneralPath; +import java.awt.geom.Rectangle2D; +import java.awt.geom.RoundRectangle2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.imageio.ImageIO; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSeparator; +import javax.swing.JSlider; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +public class BackgroundAnimation extends JPanel { + + private CurvesPanel curves; + + public BackgroundAnimation() throws HeadlessException { + //super("Stack Layout"); + + buildContentPane(); + // buildDebugControls(); + + startAnimation(); + + //setSize(640, 400); + //setLocationRelativeTo(null); + + //setDefaultCloseOperation(EXIT_ON_CLOSE); + } + + private void startAnimation() { + Timer timer = new Timer(50, new ActionListener() { + public void actionPerformed(ActionEvent e) { + curves.animate(); + curves.repaint(); + } + }); + timer.start(); + } + + private void buildContentPane() { + //JPanel pane = new JPanel(); + setOpaque(false); + setLayout(new StackLayout()); + + GradientPanel gradient = new GradientPanel(); + //chooser = new AvatarChooser(); + curves = new CurvesPanel(); + + add(gradient, StackLayout.TOP); + //add(chooser, StackLayout.TOP); + add(curves, StackLayout.TOP); + + } + + public static void main(String[] args) { + try { + UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); + } catch (ClassNotFoundException ex) { + ex.printStackTrace(); + } catch (IllegalAccessException ex) { + ex.printStackTrace(); + } catch (InstantiationException ex) { + ex.printStackTrace(); + } catch (UnsupportedLookAndFeelException ex) { + ex.printStackTrace(); + } + + SwingUtilities.invokeLater(new Runnable() { + public void run() { + BackgroundAnimation tester = new BackgroundAnimation(); + tester.setVisible(true); + } + }); + } +} + +class CurvesPanel extends JPanel { + protected RenderingHints hints; + + protected int counter = 0; + + protected Color start = new Color(255, 255, 255, 200); + + protected Color end = new Color(255, 255, 255, 0); + + public CurvesPanel() { + this(new BorderLayout()); + } + + public CurvesPanel(LayoutManager manager) { + super(manager); + hints = createRenderingHints(); + } + + protected RenderingHints createRenderingHints() { + RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); + hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + return hints; + } + + public void animate() { + counter++; + } + + @Override + public boolean isOpaque() { + return false; + } + + @Override + protected void paintComponent(Graphics g) { + Graphics2D g2 = (Graphics2D) g; + + RenderingHints oldHints = g2.getRenderingHints(); + g2.setRenderingHints(hints); + + float width = getWidth(); + float height = getHeight(); + + g2.translate(0, -30); + + drawCurve(g2, 20.0f, -10.0f, 20.0f, -10.0f, width / 2.0f - 40.0f, 10.0f, 0.0f, -5.0f, + width / 2.0f + 40, 1.0f, 0.0f, 5.0f, 50.0f, 5.0f, false); + + g2.translate(0, 30); + g2.translate(0, height - 60); + + drawCurve(g2, 30.0f, -15.0f, 50.0f, 15.0f, width / 2.0f - 40.0f, 1.0f, 15.0f, -25.0f, + width / 2.0f, 1.0f / 2.0f, 0.0f, 25.0f, 15.0f, 9.0f, false); + + g2.translate(0, -height + 60); + + drawCurve(g2, height - 35.0f, -5.0f, height - 50.0f, 10.0f, width / 2.0f - 40.0f, 1.0f, + height - 35.0f, -25.0f, width / 2.0f, 1.0f / 2.0f, height - 20.0f, 25.0f, 25.0f, 7.0f, true); + + g2.setRenderingHints(oldHints); + } + + protected void drawCurve(Graphics2D g2, float y1, float y1_offset, float y2, float y2_offset, + float cx1, float cx1_offset, float cy1, float cy1_offset, float cx2, float cx2_offset, + float cy2, float cy2_offset, float thickness, float speed, boolean invert) { + float width = getWidth(); + + float offset = (float) Math.sin(counter / (speed * Math.PI)); + + float start_x = 0.0f; + float start_y = offset * y1_offset + y1; + float end_x = width; + float end_y = offset * y2_offset + y2; + + float ctrl1_x = offset * cx1_offset + cx1; + float ctrl1_y = offset * cy1_offset + cy1; + float ctrl2_x = offset * cx2_offset + cx2; + float ctrl2_y = offset * cy2_offset + cy2; + + GeneralPath thickCurve = new GeneralPath(); + thickCurve.moveTo(start_x, start_y); + thickCurve.curveTo(ctrl1_x, ctrl1_y, ctrl2_x, ctrl2_y, end_x, end_y); + thickCurve.lineTo(end_x, end_y + thickness); + thickCurve.curveTo(ctrl2_x, ctrl2_y + thickness, ctrl1_x, ctrl1_y + thickness, start_x, start_y + + thickness); + thickCurve.lineTo(start_x, start_y); + + Rectangle bounds = thickCurve.getBounds(); + if (!bounds.intersects(g2.getClipBounds())) { + return; + } + + GradientPaint painter = new GradientPaint(0, bounds.y, invert ? end : start, 0, bounds.y + + bounds.height, invert ? start : end); + + Paint oldPainter = g2.getPaint(); + g2.setPaint(painter); + g2.fill(thickCurve); + + g2.setPaint(oldPainter); + } +} + +class GradientPanel extends JPanel { + protected BufferedImage gradientImage; + + protected Color gradientStart = Color.GRAY.brighter();//new Color(204, 249, 124); + + protected Color gradientEnd = Color.GRAY;//new Color(174, 222, 94); + + public GradientPanel() { + this(new BorderLayout()); + } + + public GradientPanel(LayoutManager layout) { + super(layout); + addComponentListener(new GradientCacheManager()); + } + + @Override + protected void paintComponent(Graphics g) { + createImageCache(); + + if (gradientImage != null) { + g.drawImage(gradientImage, 0, 0, getWidth(), getHeight(), null); + } + } + + protected void createImageCache() { + int width = 2; + int height = getHeight(); + + if (width == 0 || height == 0) { + return; + } + + if (gradientImage == null || width != gradientImage.getWidth() + || height != gradientImage.getHeight()) { + + gradientImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + + Graphics2D g2 = gradientImage.createGraphics(); + GradientPaint painter = new GradientPaint(0, 0, gradientEnd, 0, height / 2, gradientStart); + g2.setPaint(painter); + + Rectangle2D rect = new Rectangle2D.Double(0, 0, width, height / 2.0); + g2.fill(rect); + + painter = new GradientPaint(0, height / 2, gradientStart, 0, height, gradientEnd); + g2.setPaint(painter); + + rect = new Rectangle2D.Double(0, (height / 2.0) - 1.0, width, height); + g2.fill(rect); + + g2.dispose(); + } + } + + private void disposeImageCache() { + synchronized (gradientImage) { + gradientImage.flush(); + gradientImage = null; + } + } + + private class GradientCacheManager implements ComponentListener { + public void componentResized(ComponentEvent e) { + } + + public void componentMoved(ComponentEvent e) { + } + + public void componentShown(ComponentEvent e) { + } + + public void componentHidden(ComponentEvent e) { + disposeImageCache(); + } + } +} + +class StackLayout implements LayoutManager2 { + public static final String BOTTOM = "bottom"; + + public static final String TOP = "top"; + + private List components = new LinkedList(); + + public void addLayoutComponent(Component comp, Object constraints) { + synchronized (comp.getTreeLock()) { + if (BOTTOM.equals(constraints)) { + components.add(0, comp); + } else if (TOP.equals(constraints)) { + components.add(comp); + } else { + components.add(comp); + } + } + } + + public void addLayoutComponent(String name, Component comp) { + addLayoutComponent(comp, TOP); + } + + public void removeLayoutComponent(Component comp) { + synchronized (comp.getTreeLock()) { + components.remove(comp); + } + } + + public float getLayoutAlignmentX(Container target) { + return 0.5f; + } + + public float getLayoutAlignmentY(Container target) { + return 0.5f; + } + + public void invalidateLayout(Container target) { + } + + public Dimension preferredLayoutSize(Container parent) { + synchronized (parent.getTreeLock()) { + int width = 0; + int height = 0; + + for (Component comp : components) { + Dimension size = comp.getPreferredSize(); + width = Math.max(size.width, width); + height = Math.max(size.height, height); + } + + Insets insets = parent.getInsets(); + width += insets.left + insets.right; + height += insets.top + insets.bottom; + + return new Dimension(width, height); + } + } + + public Dimension minimumLayoutSize(Container parent) { + synchronized (parent.getTreeLock()) { + int width = 0; + int height = 0; + + for (Component comp : components) { + Dimension size = comp.getMinimumSize(); + width = Math.max(size.width, width); + height = Math.max(size.height, height); + } + + Insets insets = parent.getInsets(); + width += insets.left + insets.right; + height += insets.top + insets.bottom; + + return new Dimension(width, height); + } + } + + public Dimension maximumLayoutSize(Container target) { + return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); + } + + public void layoutContainer(Container parent) { + synchronized (parent.getTreeLock()) { + int width = parent.getWidth(); + int height = parent.getHeight(); + + Rectangle bounds = new Rectangle(0, 0, width, height); + + int componentsCount = components.size(); + + for (int i = 0; i < componentsCount; i++) { + Component comp = components.get(i); + comp.setBounds(bounds); + parent.setComponentZOrder(comp, componentsCount - i - 1); + } + } + } +} \ No newline at end of file diff --git a/src/client/BroadcastClient.java b/src/client/BroadcastClient.java new file mode 100644 index 0000000..a3f9902 --- /dev/null +++ b/src/client/BroadcastClient.java @@ -0,0 +1,74 @@ +package client; +import java.io.*; +import java.net.*; +import java.util.*; +import javax.swing.*; +import java.text.*; +public class BroadcastClient extends Thread +{ + StringBuffer sb; + DecimalFormat twoDForm; + ShareValuesChangeListener svcl; + public BroadcastClient(StringBuffer s) + { + sb=s; + svcl=null; + Companies.comp=new ArrayList(); + twoDForm = new DecimalFormat("#.##"); + } + public void run(String poo) + { + try{ + StringBuffer fin=new StringBuffer(); + try{ + final String rec[]=poo.split("="); + final String mtr[]=rec[0].split(";"); + final String str[]=rec[1].split(";"); + final List clist=new ArrayList(); + for(int i=0;ib) + fin.append("\u25b2"); //This is some text! + else if(a0.0) + fin.append(twoDForm.format(c)); + else if(c<0.0) + fin.append(twoDForm.format(-c)); + fin.append(" "); + } + sb.delete(0,sb.length()); + sb.append(fin.toString()); + SwingUtilities.invokeLater(new Runnable(){ + public void run() + { + try{ + if(Main.imglabel2!=null) + Main.imglabel2.setText("
Sensex: "+mtr[1]+"
Time Left: "+mtr[0]+"
"); + }catch(Exception bb){bb.printStackTrace();} + try{ + svcl.valuesChanged(); + for(int i=0;i((float)0.9)) + { + alphaChanger.stop(); + jd.setVisible(false); + ii=0; + } + try{ + AWTUtilities.setWindowOpacity(jd,Float.valueOf((float)(1-ii))); + }catch(Exception m){} + } + }); + Client client; + User user; + JLabel cash,jlab,tot; + double total=0; + Company comp; + JTextField jtf; + Shares pp; + String cmp; + JRadioButton b2,b1; + static boolean closee=false; + Timer timer = new Timer(250,new ActionListener() { + public void actionPerformed(ActionEvent e) + { + if(closee) + { + timer.stop(); + jd.setVisible(false); + closee=false; + } + comp=Companies.getCompanyWithName(cmp); + cash.setText("Cash Avail : "+twoDForm.format(user.getCurrentMoney())); + jlab.setText("Company : "+cmp+" , C.M.P. : "+twoDForm.format(comp.mktvalue)); + try + { + int ent=Integer.parseInt(jtf.getText()); + if(b1.isSelected()) + { + total=Double.valueOf(twoDForm.format(ent*comp.mktvalue*1.02)); + if(total>user.getCurrentMoney()) + tot.setForeground(Color.red); + else + tot.setForeground(Color.black); + } + else + if(b2.isSelected()) + { + total=Double.valueOf(twoDForm.format(ent*comp.mktvalue*0.98)); + if(ent>pp.qty) + tot.setForeground(Color.red); + else + tot.setForeground(Color.black); + } + }catch(Exception v) + { + total=0; + tot.setForeground(Color.red); + } + tot.setText("Total Cash Req./Rec.*: "+twoDForm.format(total)); + } + }); + public Cashier(Client c,User u) + { + client=c; + user=u; + } + void showDialog(String c,final int bs,final Shares shr) + { + cmp=c; + pp=shr; + jd=new JDialog(); + jd.setUndecorated(true); + comp=Companies.getCompanyWithName(cmp); + JPanel pan=new JPanel(){ + @Override + protected void paintComponent(Graphics grphcs) { + Graphics2D g2d = (Graphics2D) grphcs; + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); + GradientPaint gp = new GradientPaint(0, 0,getBackground().brighter(), 0, getHeight(),getBackground().darker()); + g2d.setPaint(gp); + g2d.fillRect(0, 0, getWidth(), getHeight()); + super.paintComponent(grphcs); + } + }; + pan.setLayout(new GridBagLayout()); + jlab=new JLabel("Company : "+cmp+" , C.M.P. : "+twoDForm.format(comp.mktvalue)); + JLabel op=new JLabel("Operation : "); + tot=new JLabel("Total Cash Req./Rec.:"+twoDForm.format(total)); + b1=new JRadioButton("Buy"); + b2=new JRadioButton("Sell"); + if(bs==0) + b1.setSelected(true); + else + b2.setSelected(true); + ButtonGroup grp=new ButtonGroup(); + grp.add(b1);grp.add(b2); + final JLabel qty=new JLabel("Quantity : "); + jtf=new JTextField(10); + jtf.setText("0"); + cash=new JLabel("Cash Avail : "+twoDForm.format(user.getCurrentMoney())); + final JButton jb1=new JButton("Place Order"); + final JButton jb2=new JButton("Cancel"); + jb2.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) + { + timer.stop(); + jd.setVisible(false); + } + }); + jb1.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) + { + int noofs=0; + try{ + noofs=Integer.parseInt(jtf.getText()); + }catch(Exception ee){ + jtf.setForeground(Color.red); + qty.setForeground(Color.red); + return; + } + if(noofs<=0) + { + jtf.setForeground(Color.red); + qty.setForeground(Color.red); + return; + } + if(b2.isSelected() && noofs>shr.qty) + { + jtf.setForeground(Color.red); + qty.setForeground(Color.red); + return; + } + if(b1.isSelected() && noofs*comp.mktvalue>user.getCurrentMoney()) + { + jtf.setForeground(Color.red); + qty.setForeground(Color.red); + return; + } + jtf.setForeground(Color.black); + qty.setForeground(Color.black); + tot.setForeground(Color.black); + jtf.setEnabled(false); + jb1.setEnabled(false); + jb2.setEnabled(false); + b1.setEnabled(false); + b2.setEnabled(false); + final int kk=noofs; + new Thread(){ + public void run(){ + String cmd; + if(b1.isSelected()) + cmd="buy"; + else + cmd="sell"; + User usr; + try{ + client.placeOrder(user,cmd,comp,kk,shr.id); + }catch(Exception ff) + { + client.placeOrder(user,cmd,comp,kk,-1); + } + //user.changeData(usr); + timer.stop(); + alphaChanger.start(); + } + }.start(); + } + }); + JLabel cc1=new JLabel("-> *Transaction charges : 2% of the total cash transactioned."); + JLabel cc2=new JLabel("-> Order will be executed 30-40 secs after it is placed."); + JLabel cc3=new JLabel("-> Order can be canceled within 10 secs after it is placed."); + GridBagConstraints gbc=new GridBagConstraints(); + gbc.gridx=0; + gbc.gridy=0; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=3; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(jlab,gbc); + gbc.gridx=0; + gbc.gridy=1; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=1; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(op,gbc); + gbc.gridx=1; + gbc.gridy=1; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=1; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(b1,gbc); + gbc.gridx=2; + gbc.gridy=1; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=1; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(b2,gbc); + gbc.gridx=0; + gbc.gridy=2; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=1; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(qty,gbc); + gbc.gridx=1; + gbc.gridy=2; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=2; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(jtf,gbc); + gbc.gridx=0; + gbc.gridy=3; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=3; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(tot,gbc); + gbc.gridx=0; + gbc.gridy=4; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=3; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(cash,gbc); + gbc.gridx=0; + gbc.gridy=5; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=1; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(jb1,gbc); + gbc.gridx=1; + gbc.gridy=5; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=1; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(jb2,gbc); + gbc.gridx=0; + gbc.gridy=6; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=3; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(cc1,gbc); + gbc.gridx=0; + gbc.gridy=7; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=3; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(cc2,gbc); + gbc.gridx=0; + gbc.gridy=8; + gbc.fill=GridBagConstraints.NONE; + gbc.gridwidth=3; + gbc.gridheight=1; + gbc.ipadx=0; + gbc.ipady=0; + gbc.anchor=GridBagConstraints.LINE_START; + //gbc.insets=new Insets(0,0,100,0); + pan.add(cc3,gbc); + pan.setOpaque(false); + pan.setBorder(new CompoundBorder(BorderFactory.createLineBorder(Color.black, 1),BorderFactory.createEmptyBorder(5,5,5,5))); + jd.setContentPane(pan); + timer.start(); + jd.setModalityType(JDialog.ModalityType.APPLICATION_MODAL); + jd.pack(); + jd.setLocationRelativeTo(null); + jd.setVisible(true); + } +} \ No newline at end of file diff --git a/src/client/ChatClient.java b/src/client/ChatClient.java new file mode 100644 index 0000000..64b5ae0 --- /dev/null +++ b/src/client/ChatClient.java @@ -0,0 +1,55 @@ +package client; +import java.io.*; +import java.net.*; +import java.util.*; +import javax.swing.*; +public class ChatClient extends Thread +{ + JTextArea jta; + public ChatClient(JTextArea ja) + { + jta=ja; + } + public void run(String hh) + { + try{ + StringBuffer fin=new StringBuffer(" "); + final String str=hh.trim(); + SwingUtilities.invokeLater(new Runnable(){ + public void run() + { + String s[]=str.split(";"); + if(s.length<2) + return; + else + { + if(!s[1].equals("-1")) + jta.setText(jta.getText()+"\n"+s[1]); + if(!s[0].equals("-1")) + { + String ff[]=s[0].split(":"); + String jj=""; + for(int i=0;i> ("+u.getChat()+" characters remainimg)"); + jtf=new JTextField(); + jta=new JTextArea(); + jta.setFont(new Font("Lucida Sans Unicode",Font.PLAIN,12)); + jta.setLineWrap(true); + jta.setEditable(false); + jta.setForeground(Color.green.darker()); + //jtf.setEnabled(false); + jtf.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + final String s = jtf.getText(); + if (!s.equals("")) + { + jtf.setText(""); + new Thread(){ + public void run(){ + try + { + remain=sendString(s); + u.setChat(Integer.parseInt(remain)); + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + jlab.setText("<> ("+u.getChat()+" characters remainimg)"); + } + }); + }catch(Exception mm){} + if(u.getChat()<=0) + JOptionPane.showMessageDialog(null,"Sorry, You have finished your chat limit.","Error:",JOptionPane.PLAIN_MESSAGE); + } + }.start(); + } + } + }); + JScrollPane jsp=new JScrollPane(jta,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + add(jlab,BorderLayout.NORTH); + add(jsp,BorderLayout.CENTER); + add(jtf,BorderLayout.SOUTH); + try{ + jta.setText(cc.getChatHistory(user.getName(),user.getPassword())); + }catch(Exception mmm){} + ChatClient cser=new ChatClient(jta); + //cser.start(); + client.cc=cser; + } + String sendString(String s) + { + return cc.sendChat(s,user.getName(),user.getPassword()); + } +} \ No newline at end of file diff --git a/src/client/Client.java b/src/client/Client.java new file mode 100644 index 0000000..caf66e0 --- /dev/null +++ b/src/client/Client.java @@ -0,0 +1,269 @@ +package client; +import java.io.*; +import java.net.*; +import java.util.*; +import javax.swing.*; +import user.*; + +public class Client { + private boolean connected = false; + Socket socket = null; + PrintWriter out = null; + //BufferedReader in = null; + ObjectInputStream in; + String domain; + Object reply; + volatile int commID=0; + Client ccl; + int usrD; + Main m; + BroadcastClient bc=null; + RankingClient rc=null; + ChatClient cc=null; + Receiver rec; + + public Client(Main mm) + { + ccl=this; + reply=null; + m=mm; + } + + class Receiver extends Thread + { + ObjectInputStream in; + List rev; + public Receiver(ObjectInputStream i) + { + in=i; + rev=new ArrayList(); + } + public void run() + { + while(connected) + { + try{ + Object obj = in.readObject(); + if(obj.toString().equals("101")) + { + connected=false; + in.close(); + out.close(); + socket.close(); + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + Cashier.closee=true; + JOptionPane.showMessageDialog(null,"Disconnected from server.","Error:",JOptionPane.PLAIN_MESSAGE); + m.getAppletContext().showDocument(m.getDocumentBase(), "_self"); + } + }); + } + else if(obj.toString().equals("102")) + { + reply=obj; + ccl.interrupt(); + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + Cashier.closee=true; + JOptionPane.showMessageDialog(null,"Server Not Running.","Error:",JOptionPane.PLAIN_MESSAGE); + } + }); + } + else if(obj.toString().split("::")[0].equals("broadcast")) + { + bc.run(obj.toString().substring(obj.toString().indexOf("::")+2)); + } + else if(obj.toString().split("::")[0].equals("chat")) + { + cc.run(obj.toString().substring(obj.toString().indexOf("::")+2)); + } + else if(obj.toString().split("::")[0].equals("rank")) + { + rc.run(obj.toString().substring(obj.toString().indexOf("::")+2)); + } + else + { + User hhh=null; + try + { + hhh=(User)obj; + if(usrD==1) + { + reply=obj; + ccl.interrupt(); + } + else + { + m.ur.changeData((User)obj); + } + }catch(Exception p) + { + reply=obj; + ccl.interrupt(); + } + } + try{ + Thread.sleep(500); + }catch(Exception n){} + }catch(Exception m){} + } + } + } + + public void connect(String user,String pass) { + if (!connected) + { + try { + socket = new Socket(domain,4446); + out = new PrintWriter(socket.getOutputStream(), true); + //in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + in=new ObjectInputStream(socket.getInputStream()); + } catch (java.net.UnknownHostException e) { + System.err.println("Don't know about host"); + return; + } catch (IOException e) { + System.err.println("Couldn't get I/O for the connection to"); + return; + } + this.connected = true; + rec=new Receiver(in); + rec.start(); + commID=0; + } + } + + String login(String domain,String user,String pass) + { + int cmdID=commID++; + this.domain=domain; + connect(user,pass); + try{ + out.println(cmdID+";login:"+user+":"+pass); + out.flush(); + String rep=(String)receiveReply(0); + return rep.split(":")[0]; + }catch(Exception r){ + r.printStackTrace();} + return null; + } + + String register(String domain,String regno,String user,String pass) + { + int cmdID=commID++; + this.domain=domain; + connect(user,pass); + try{ + out.println(cmdID+";reg:"+regno+":"+user+":"+pass); + out.flush(); + String rep=(String)receiveReply(0); + disconnect(); + return rep.split(":")[0]; + }catch(Exception r){r.printStackTrace();} + return null; + } + + public void disconnect() + { + int cmdID=commID++; + this.connected = false; + try { + out.println(cmdID+";logout"); + out.flush(); + in.close(); + out.close(); + socket.close(); + } catch (IOException ex) { + System.err.println("Server stop failed."); + } + } + + User getUserDetails(String user,String pass) + { + int cmdID=commID++; + connect(user,pass); + try{ + usrD=1; + out.println(cmdID+";gud"); + out.flush(); + User vv=(User)receiveReply(0); + usrD=0; + return vv; + }catch(Exception r){ + r.printStackTrace();} + return null; + } + + String sendChat(String s,String user,String pass) + { + int cmdID=commID++; + connect(user,pass); + try{ + out.println(cmdID+";chat:"+s.trim()); + out.flush(); + return (String)receiveReply(0); + }catch(Exception r){ + r.printStackTrace();} + return null; + } + + String getChatHistory(String user,String pass) + { + int cmdID=commID++; + connect(user,pass); + try{ + out.println(cmdID+";chath"); + out.flush(); + return (String)receiveReply(0); + }catch(Exception r){ + r.printStackTrace();} + return null; + } + + void placeOrder(final User user,String cmd,Company comp,int qty,int id) + { + int cmdID=commID++; + connect(user.getName(),user.getPassword()); + try{ + out.println(cmdID+";"+cmd+":"+comp.name+":"+Integer.toString(qty)+":"+id); + out.flush(); + Shares pen=(Shares)receiveReply(0); + user.getPendingShares().add(pen); + user.dataChanged(); + }catch(Exception r){ + r.printStackTrace();} + } + + String cancelShares(String user,String pass,int id,int sellid) + { + int cmdID=commID++; + connect(user,pass); + try{ + out.println(cmdID+";cancel:"+id+":"+sellid); + out.flush(); + return (String)receiveReply(0); + }catch(Exception r){ + r.printStackTrace();} + return null; + } + + boolean loop; + Object receiveReply(int cmdID) + { + loop=true; + int i=0; + while(loop && i<=300) + { + try + { + Thread.sleep(100); + i++; + }catch(Exception m){} + } + return reply; + } + + void interrupt() + { + loop=false; + } +} \ No newline at end of file diff --git a/src/client/Companies.java b/src/client/Companies.java new file mode 100644 index 0000000..4fd92fc --- /dev/null +++ b/src/client/Companies.java @@ -0,0 +1,48 @@ +package client; + +import java.util.*; +class Companies +{ + static List comp; + static Double sensex; + static Company getCompanyWithName(String name) + { + for(int i=0;i
Sensex: 
Time Left:
"); + imglabel2.setHorizontalTextPosition(JLabel.LEFT); + imglabel2.setVerticalTextPosition(JLabel.BOTTOM); + add.add(imglabel2,BorderLayout.CENTER); + gbc.gridx=0; + gbc.gridy=1; + gbc.fill=GridBagConstraints.HORIZONTAL; + gbc.gridwidth=5; + gbc.gridheight=2; + gbc.ipadx=0; + gbc.ipady=0; + gbc.insets=new Insets(20,40,0,0); + gbc.anchor=GridBagConstraints.PAGE_START; + gbc.weightx=1.0; + gbc.weighty=1.0; + mpane.add(add,gbc); + + JTabbedPane jtp=new JTabbedPane(); + jtp.setPreferredSize(new Dimension((getWidth()*5)/8,(getHeight()*6)/10)); + userpane=new JPanel[3]; + + dtm=new DefaultTableModel[3]; + dtm[0]=new DefaultTableModel(columnNames1,0); + dtm[1]=new DefaultTableModel(columnNames2,0); + dtm[2]=new DefaultTableModel(columnNames3,0); + + + table=new JTable[3]; + JScrollPane jspt[]=new JScrollPane[3]; + mon=new JLabel[3]; + + cash=new Cashier(client,ur); + table[0]=new JTable(dtm[0]) + { + public boolean isCellEditable(int row, int col) + { + if(col==7) + return true; + return false; + } + public boolean isCellSelected(int row, int col) + { + return false; + } + }; + table[1]=new JTable(dtm[1]) + { + public boolean isCellEditable(int row, int col) + { + if(col==6) + return true; + return false; + } + public boolean isCellSelected(int row, int col) + { + return false; + } + }; + table[2]=new JTable(dtm[2]) + { + public boolean isCellEditable(int row, int col) + { + if(col==4) + return true; + return false; + } + public boolean isCellSelected(int row, int col) + { + return false; + } + }; + + for(int i=0;i<3;i++) + { + table[i].setDragEnabled(false); + table[i].setRowSelectionAllowed(false); + table[i].setColumnSelectionAllowed(false); + //table.setShowHorizontalLines(true); + //table.setShowVerticalLines(true); + table[i].setRowHeight(30); + table[i].getTableHeader().setReorderingAllowed(false); + table[i].setFillsViewportHeight(true); + jspt[i]=new JScrollPane(table[i]); + userpane[i]=new JPanel(new BorderLayout()); + userpane[i].add(jspt[i],BorderLayout.CENTER); + mon[i]=new JLabel("Avail. Cash : "+twoDForm.format(user.getCurrentMoney())); + mon[i].setFont(new Font("Tempus Sans ITC",Font.BOLD,20)); + userpane[i].add(mon[i],BorderLayout.SOUTH); + } + + delete = new AbstractAction() + { + public void actionPerformed(ActionEvent e) + { + JTable table = (JTable)e.getSource(); + final int row = Integer.valueOf(e.getActionCommand()); + if(table==main.table[0]) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + cash.showDialog((String)main.table[0].getValueAt(row,1),1,ur.getCurrentShares().get(row)); + } + }); + } + else + if(table==main.table[1]) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + cash.showDialog((String)main.table[1].getValueAt(row,1),0,null); + } + }); + } + else + if(table==main.table[2]) + { + int res=JOptionPane.showConfirmDialog(null,"Are you sure ?","Confirm:",JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE); + if(res==JOptionPane.YES_OPTION) + { + new Thread(){ + public void run(){ + final String res=client.cancelShares(ur.getName(),ur.getPassword(),ur.getPendingShares().get(row).id,ur.getPendingShares().get(row).sellid); + if(res.equals("0")) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + JOptionPane.showMessageDialog(null,"Sorry your cancellation period is over.","Error:",JOptionPane.PLAIN_MESSAGE); + } + }); + } + else if(res.equals("1")) + { + ur.getPendingShares().get(row).status="Cancelling"; + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + updateTables(); + } + }); + } + } + }.start(); + } + } + } + }; + /*ButtonColumn b=new ButtonColumn(table[0], delete, 7); + ButtonColumn b2=new ButtonColumn(table[1], delete, 6); + ButtonColumn b3=new ButtonColumn(table[2], delete, 4);*/ + jtp.add("Holdings",userpane[0]); + jtp.add("Watchlist",userpane[1]); + jtp.add("Transactions",userpane[2]); + gbc.gridx=0; + gbc.gridy=3; + gbc.fill=GridBagConstraints.HORIZONTAL; + gbc.gridwidth=5; + gbc.gridheight=5; + gbc.ipadx=0; + gbc.ipady=0; + gbc.insets=new Insets(0,40,60,0); + gbc.anchor=GridBagConstraints.PAGE_END; + gbc.weightx=1.0; + gbc.weighty=1.0; + mpane.add(jtp,gbc); + jtp.repaint(); + udcl=new UserDataChangedListener(){ + public void userDataChanged(User user) + { + updateTables(); + } + }; + user.addUserDataChangeListener(udcl); + svcl=new ShareValuesChangeListener(){ + public void valuesChanged() + { + updateTables(); + } + }; + rb.addShareValuesChangeListener(svcl); + } + DefaultTableCellRenderer dtr=new DefaultTableCellRenderer(){ + public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) { + if(value.toString().indexOf("-")!=-1) + { + value=value.toString()+" \u25bc"; + } + else + { + value=value.toString()+" \u25b2"; + } + Component c = super.getTableCellRendererComponent(table, value,isSelected, hasFocus,row, column); + if(value.toString().indexOf("-")!=-1) + { + c.setForeground(Color.red); + } + else + { + c.setForeground(Color.green); + } + return c; + } + }; + void updateTables() + { + try{ + for(int i=0;i<3;i++) + { + mon[i].setText("Avail. Cash : "+twoDForm.format(ur.getCurrentMoney())); + mon[i].repaint(); + } + }catch(Exception mm){mm.printStackTrace();} + try{ + java.util.List ss=ur.getCurrentShares(); + Object data[][]=new Object[ss.size()][8]; + for(int i=0;i ss=ur.getPendingShares(); + Object data[][]=new Object[ss.size()][5]; + for(int i=0;i
News : 
"); + l.setFont(new Font("Arial",Font.BOLD,13)); + l.setOpaque(false); + setSize(getWidth(),30); + add(l,BorderLayout.CENTER); + } + protected void paintComponent(Graphics grphcs) { + Graphics2D g2d = (Graphics2D) grphcs; + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); + GradientPaint gp = new GradientPaint(0, 0,getBackground().brighter(), 0, getHeight(),getBackground().darker()); + g2d.setPaint(gp); + g2d.fillRect(0, 0, getWidth(), getHeight()); + super.paintComponent(grphcs); + } + void startAnimation() + { + loop=0; + t.start(); + } + void stopAnimation() + { + loop=0; + t.stop(); + } + public void actionPerformed(ActionEvent e) + { + if(sb.length()>200) + { + l.setText("
News : "+sb.substring(0,200)+"
"); + sb.append(sb.charAt(0)); + sb.delete(0,1); + loop++; + if(loop>sb.length()) + { + sb=new StringBuffer(temp); + loop=0; + } + } + else + { + sb=new StringBuffer(temp); + loop=0; + } + } +} \ No newline at end of file diff --git a/src/client/RankingClient.java b/src/client/RankingClient.java new file mode 100644 index 0000000..981ff2c --- /dev/null +++ b/src/client/RankingClient.java @@ -0,0 +1,35 @@ +package client; +import java.io.*; +import java.net.*; +import java.util.*; +import javax.swing.*; +public class RankingClient extends Thread +{ + JTextPane jta; + public RankingClient(JTextPane ja) + { + jta=ja; + } + public void run(String hh) + { + try{ + StringBuffer fin=new StringBuffer(" "); + String str[]=hh.trim().split(":"); + String f=""; + for(int i=0;i\n"; + } + final String h=f; + SwingUtilities.invokeLater(new Runnable(){ + public void run() + { + jta.setText(h); + } + }); + }catch(Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/src/client/RankingWindow.java b/src/client/RankingWindow.java new file mode 100644 index 0000000..7f3f42c --- /dev/null +++ b/src/client/RankingWindow.java @@ -0,0 +1,29 @@ +package client; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.text.*; +import user.*; + +class RankingWindow extends JPanel +{ + JTextPane jta; + public RankingWindow(Client cc) + { + setLayout(new BorderLayout()); + JLabel jlab=new JLabel("<>"); + jta=new JTextPane(); + StyledDocument doc = jta.getStyledDocument(); + SimpleAttributeSet center = new SimpleAttributeSet(); + StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER); + doc.setParagraphAttributes(0, doc.getLength(), center, false); + jta.setFont(new Font("Lucida Sans Unicode",Font.BOLD,14)); + jta.setEditable(false); + jta.setForeground(Color.red.darker()); + JScrollPane jsp=new JScrollPane(jta,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + add(jlab,BorderLayout.NORTH); + add(jsp,BorderLayout.CENTER); + RankingClient cser=new RankingClient(jta); + cc.rc=cser; + } +} \ No newline at end of file diff --git a/src/client/RegisterAction.java b/src/client/RegisterAction.java new file mode 100644 index 0000000..a9a75e0 --- /dev/null +++ b/src/client/RegisterAction.java @@ -0,0 +1,111 @@ +package client; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.io.BufferedInputStream; +import javax.swing.border.*; +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +class RegisterAction implements ActionListener +{ + HintTextField reg,user; + HintPasswordField pass; + String domain; + Client client; + public RegisterAction(HintTextField r,HintTextField u,HintPasswordField p,String d,Client c) + { + reg=r; + user=u; + pass=p; + domain=d; + client =c; + } + public void actionPerformed(ActionEvent e) + { + Pattern p1=Pattern.compile("[a-z0-9_]{3,16}"); + Pattern p2=Pattern.compile("[a-z0-9_]{6,18}"); + if(!p1.matcher(reg.getText()).matches()) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + JOptionPane.showMessageDialog(null,"Incorect registration no.\nThe registration no. should be of length {3-16} and can contain\nletters(a-z), numbers and underscores.","Error:",JOptionPane.PLAIN_MESSAGE); + user.setText(""); + } + }); + return; + } + if(!p1.matcher(user.getText()).matches()) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + JOptionPane.showMessageDialog(null,"Incorrect username.\nA username should be of length {3-16} and can contain\nletters(a-z), numbers and underscores.","Error:",JOptionPane.PLAIN_MESSAGE); + user.setText(""); + } + }); + return; + } + if(!p2.matcher(pass.getText()).matches()) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + JOptionPane.showMessageDialog(null,"Incorrect password.\nA password should be of length {6-18} and can contain\nletters(a-z), numbers and underscores","Error:",JOptionPane.PLAIN_MESSAGE); + pass.setText(""); + } + }); + return; + } + if(domain.equals("domain")) + { + domain=JOptionPane.showInputDialog("Enter domain."); + } + if(domain==null || domain.equals("")) + return; + new Thread(){ + public void run() + { + String rep=client.register(domain,reg.getText(),user.getText(),pass.getText()); + if(rep==null) + return; + if(rep.equals("1")) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + JOptionPane.showMessageDialog(null,"Server Replies: Reg Successful","Registration",JOptionPane.PLAIN_MESSAGE); + } + }); + // regestered + } + else if(rep.equals("3")) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + JOptionPane.showMessageDialog(null,"Server Replies: Username already exists.\nA username should be of length {3-16} and can contain\nletters(a-z), numbers and underscores.","Error:",JOptionPane.PLAIN_MESSAGE); + user.setText(""); + } + }); + return; + } + else if(rep.equals("2")) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + JOptionPane.showMessageDialog(null,"Server Replies: Incorect registration no.\nThe registration no. should be of length {3-16} and can contain\nletters(a-z), numbers and underscores.","Error:",JOptionPane.PLAIN_MESSAGE); + reg.setText(""); + } + }); + return; + } + else if(rep.equals("4")) + { + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + JOptionPane.showMessageDialog(null,"Server Replies: Already registered.","Error:",JOptionPane.PLAIN_MESSAGE); + } + }); + return; + } + } + }.start(); + } +} \ No newline at end of file diff --git a/src/client/RibbonPane.java b/src/client/RibbonPane.java new file mode 100644 index 0000000..79e9519 --- /dev/null +++ b/src/client/RibbonPane.java @@ -0,0 +1,65 @@ +package client; +import javax.swing.*; +import java.awt.event.*; +import java.awt.*; +class RibbonPane extends JPanel implements ActionListener +{ + StringBuffer sb,temp; + BroadcastClient bc; + Timer t; + int loop; + JLabel l; + final String wel=" StockMart Anwesha'13 "; + public RibbonPane(int tm,Client cc) + { + sb=new StringBuffer(wel); + temp=new StringBuffer(wel); + bc=new BroadcastClient(temp); + cc.bc=bc; + t=new Timer(tm,this); + setOpaque(false); + l=new JLabel(wel); + l.setFont(new Font("Arial",Font.BOLD,13)); + l.setOpaque(false); + add(l); + } + protected void paintComponent(Graphics grphcs) { + Graphics2D g2d = (Graphics2D) grphcs; + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); + GradientPaint gp = new GradientPaint(0, 0,getBackground().brighter(), 0, getHeight(),getBackground().darker()); + g2d.setPaint(gp); + g2d.fillRect(0, 0, getWidth(), getHeight()); + super.paintComponent(grphcs); + } + void startAnimation() + { + loop=0; + t.start(); + //bc.start(); + } + void stopAnimation() + { + loop=0; + t.stop(); + //bc.interrupt(); + } + public void actionPerformed(ActionEvent e) + { + if(sb.length()>260) + { + l.setText("
"+sb.substring(0,260).replace("\u25b2","\u25b2").replace("\u25bc","\u25bc")+"
");
+            sb.append(sb.charAt(0));
+            sb.delete(0,1);
+            loop++;
+            if(loop>sb.length())
+            {
+                sb=new StringBuffer(temp);
+                loop=0;
+            }
+        }
+    }
+    void addShareValuesChangeListener(ShareValuesChangeListener svcl)
+    {
+        bc.svcl=svcl;
+    }
+}
\ No newline at end of file
diff --git a/src/client/ShareValuesChangeListener.java b/src/client/ShareValuesChangeListener.java
new file mode 100644
index 0000000..3572653
--- /dev/null
+++ b/src/client/ShareValuesChangeListener.java
@@ -0,0 +1,6 @@
+package client;
+
+interface ShareValuesChangeListener
+{
+    public void valuesChanged();
+}
\ No newline at end of file
diff --git a/src/client/logo.png b/src/client/logo.png
new file mode 100644
index 0000000..b3e9910
Binary files /dev/null and b/src/client/logo.png differ
diff --git a/src/client/logo2.png b/src/client/logo2.png
new file mode 100644
index 0000000..dd17fa4
Binary files /dev/null and b/src/client/logo2.png differ
diff --git a/src/client/test.java b/src/client/test.java
new file mode 100644
index 0000000..4d169f2
--- /dev/null
+++ b/src/client/test.java
@@ -0,0 +1,7 @@
+package client;
+class test
+{
+    public void run()
+    {
+    }
+}
\ No newline at end of file
diff --git a/src/server/BroadcastServer.java b/src/server/BroadcastServer.java
new file mode 100644
index 0000000..e04db5e
--- /dev/null
+++ b/src/server/BroadcastServer.java
@@ -0,0 +1,49 @@
+package server;
+import java.io.*;
+import java.net.*;
+import java.util.*;
+import java.text.*;
+
+public class BroadcastServer extends Thread
+{    
+    private long SECONDS = 15000;   
+    List com;
+    int close;
+    Server server;
+    
+    public BroadcastServer(String name,List c,Server s) throws IOException 
+    {
+        super(name);
+        com=c;
+        server=s;
+    }
+
+    static DecimalFormat twoDForm = new DecimalFormat("#.##");
+    public void run() {
+        close=0;
+        while (!interrupted() && com.size()>0)
+        {
+            if(close==1)
+                break;
+            try 
+            {
+                int hrs=((int)(StockMart.totTime*60-(new Date().getTime()-StockMart.startDate.getTime())/1000))/3600;
+                int mins=((((int)(StockMart.totTime*60-(new Date().getTime()-StockMart.startDate.getTime())/1000))/60)%60);
+                String dString="broadcast::"+hrs+":"+mins+";"+twoDForm.format(ShareMarket.sensex)+"=";
+                for(int i=0;i sharevalue;
+    volatile int sharessold,totalshares,tsharessold;
+    volatile double perchange;
+    public Company(String n, List l, int sd, int tot)
+    {
+        name=n;
+        sharevalue=l;
+        sharessold=sd;
+        totalshares=tot;
+        tsharessold=0;
+    }
+    /*public Company(String n)
+    {
+        name=n;
+        sharevalue=new ArrayList();
+        sharessold=0;
+    }*/
+    public double getHighest()
+    {
+        double h=sharevalue.get(0);
+        for(int i=1;ih)
+                h=sharevalue.get(i);
+        }
+        return h;
+    }
+    public double getLowest()
+    {
+        double l=sharevalue.get(0);
+        for(int i=1;iPropertyChangeEvents
+ * in the datamodel.  JRealTimeDemo constructs the plot
+ * from basic sgt objects. 
+ *
+ * @author Donald Denbo
+ * @version $Revision: 1.7 $, $Date: 2001/02/06 00:14:35 $
+ * @since 2.0
+ */
+
+public class JRealTimeDemo extends JApplet implements PropertyChangeListener {
+  PseudoRealTimeData rtData_;
+  JPane pane_;
+  Layer layer_;
+  TimeAxis xbot_;
+  PlainAxis yleft_;
+  LinearTransform xt_, yt_;
+  boolean isStandalone = false;
+  BorderLayout borderLayout1 = new BorderLayout();
+  JPanel buttonPanel = new JPanel();
+  JButton startButton = new JButton();
+  JButton stopButton = new JButton();
+  JButton resetButton = new JButton();
+
+  /**Construct the applet*/
+  public JRealTimeDemo() {
+  }
+  /**Initialize the applet*/
+  public void init() {
+    /*
+     * Create the data source
+     */
+    rtData_ = new PseudoRealTimeData("rtDataSource", "Sea Level");
+    try {
+      jbInit();
+    }
+    catch(Exception e) {
+      e.printStackTrace();
+    }
+    /*
+     * add listener for data source.  JRealTimeDemo is listening
+     * for rangeModified events
+     */
+    rtData_.addPropertyChangeListener(this);
+  }
+  /**Component initialization*/
+  private void jbInit() throws Exception {
+    this.setSize(new Dimension(800, 440));
+    this.getContentPane().setLayout(borderLayout1);
+    startButton.setText("start");
+    startButton.addActionListener(new JRealTimeDemo_startButton_actionAdapter(this));
+    stopButton.setText("stop");
+    stopButton.addActionListener(new JRealTimeDemo_stopButton_actionAdapter(this));
+    resetButton.setText("reset");
+    resetButton.addActionListener(new JRealTimeDemo_resetButton_actionAdapter(this));
+    buttonPanel.setBorder(BorderFactory.createEtchedBorder());
+    this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
+    buttonPanel.add(startButton, null);
+    buttonPanel.add(stopButton, null);
+    buttonPanel.add(resetButton, null);
+    //
+    // construct JPane
+    //
+    pane_ = new JPane("Real Time Data Demo", new Dimension(800, 400));
+    pane_.setBatch(true);
+    pane_.setLayout(new StackedLayout());
+    pane_.setBackground(Color.white);
+    /*
+     * xsize, ysize are the width and height in physical units
+     * of the Layer graphics region.
+     *
+     * xstart, xend are the start and end points for the X axis
+     * ystart, yend are the start and end points for the Y axis
+     */
+    double xsize = 6.0;
+    double xstart = 0.6;
+    double xend = 5.5;
+    double ysize = 3.0;
+    double ystart = 0.6;
+    double yend = 2.75;
+    /*
+     * Create the layer and add it to the Pane.
+     */
+    CartesianGraph graph;
+    /*
+     * Get x and y ranges from data source.
+     */
+    SoTRange.GeoDate xrange = (SoTRange.GeoDate)rtData_.getXRange();
+    SoTRange.Double yrange = (SoTRange.Double)rtData_.getYRange();
+
+    xt_ = new LinearTransform(xstart, xend, xrange.start, xrange.end);
+    yt_ = new LinearTransform(ystart, yend, yrange.start, yrange.end);
+
+    layer_ = new Layer("Layer 1", new Dimension2D(xsize, ysize));
+    pane_.add(layer_);
+
+    SGLabel title = new SGLabel("title",
+				"Real Time Demo",
+				new Point2D.Double((xstart+xend)/2.0,
+						   ysize-0.05));
+    title.setAlign(SGLabel.TOP, SGLabel.CENTER);
+    title.setFont(new Font("Serif", Font.PLAIN, 14));
+    title.setHeightP(0.25);
+    title.setColor(Color.blue.darker());
+    layer_.addChild(title);
+    /*
+     * Create a CartesianGraph and set transforms.
+     */
+    graph = new CartesianGraph("Time Graph");
+    layer_.setGraph(graph);
+    graph.setXTransform(xt_);
+    graph.setYTransform(yt_);
+    /*
+     * Create the bottom axis, set its range in user units
+     * and its origin. Add the axis to the graph.
+     */
+    SoTPoint origin = new SoTPoint(xrange.start, yrange.start);
+    xbot_ = new TimeAxis("Botton Axis", TimeAxis.AUTO);
+    xbot_.setRangeU(xrange);
+    xbot_.setLocationU(origin);
+    Font xbfont = new Font("Helvetica", Font.PLAIN, 14);
+    xbot_.setLabelFont(xbfont);
+    graph.addXAxis(xbot_);
+    /*
+     * Create the left axis, set its range in user units
+     * and its origin. Add the axis to the graph.
+     */
+    String yLabel = "Latitude";
+
+    yleft_ = new PlainAxis("Left Axis");
+    yleft_.setRangeU(yrange);
+    yleft_.setLocationU(origin);
+    yleft_.setLabelFont(xbfont);
+    SGLabel ytitle = new SGLabel("yaxis title", yLabel,
+                                 new Point2D.Double(0.0, 0.0));
+    Font ytfont = new Font("Helvetica", Font.PLAIN, 14);
+    ytitle.setFont(ytfont);
+    ytitle.setHeightP(0.2);
+    yleft_.setTitle(ytitle);
+    graph.addYAxis(yleft_);
+
+    LineAttribute attr = new LineAttribute();
+    graph.setData(rtData_, attr);
+
+    this.getContentPane().add(pane_, BorderLayout.CENTER);
+    if(!isStandalone) pane_.setBatch(false);
+  }
+  /**Start the applet*/
+  public void start() {
+  }
+  /**Stop the applet*/
+  public void stop() {
+    rtData_.stopData();
+  }
+  /**Destroy the applet*/
+  public void destroy() {
+    rtData_.stopData();
+  }
+  /**Get Applet information*/
+  public String getAppletInfo() {
+    return "Applet Information";
+  }
+  /**Main method*/
+  public static void main(String[] args) {
+    JRealTimeDemo applet = new JRealTimeDemo();
+    applet.isStandalone = true;
+    JFrame frame = new JFrame();
+    //EXIT_ON_CLOSE == 3
+    frame.setDefaultCloseOperation(3);
+    frame.setTitle("Real Time Data Demo");
+    frame.getContentPane().add(applet, BorderLayout.CENTER);
+    applet.init();
+    applet.start();
+    frame.setSize(800,440);
+    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
+    frame.setLocation((d.width - frame.getSize().width) / 2, 
+		      (d.height - frame.getSize().height) / 2);
+    frame.setVisible(true);
+    applet.pane_.setBatch(false);
+  }
+
+  //static initializer for setting look & feel
+  static {
+    try {
+      //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
+      //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
+    }
+    catch(Exception e) {
+    }
+  }
+
+  void startButton_actionPerformed(ActionEvent e) {
+    rtData_.startData();
+  }
+
+  void stopButton_actionPerformed(ActionEvent e) {
+    rtData_.stopData();
+  }
+
+  void resetButton_actionPerformed(ActionEvent e) {
+    rtData_.stopData();
+    rtData_.resetData();
+    resetRange();
+  }
+  private void resetRange() {
+    /*
+     * A change in the range has occured. Get new range
+     * and set transforms, axes, and origin appropriately.
+     */
+    pane_.setBatch(true);
+    SoTRange.GeoDate xrange = (SoTRange.GeoDate)rtData_.getXRange();
+    SoTRange.Double yrange = (SoTRange.Double)rtData_.getYRange();
+    SoTPoint origin = new SoTPoint(xrange.start, yrange.start);
+    xt_.setRangeU(xrange);
+    yt_.setRangeU(yrange);
+    xbot_.setRangeU(xrange);
+    xbot_.setLocationU(origin);
+    yleft_.setRangeU(yrange);
+    yleft_.setLocationU(origin);
+    pane_.setBatch(false);
+  }
+  public void propertyChange(PropertyChangeEvent evt) {
+    /**
+     * dataModified property is handled by CartesianGraph
+     * only need to look for rangeModified here to make sure
+     * range is properly updated
+     */
+    if("rangeModified".equals(evt.getPropertyName())) {
+      resetRange();
+    }
+  }
+}
+/*
+ * wrappers for button events created by JBuilder
+ */
+class JRealTimeDemo_startButton_actionAdapter implements ActionListener {
+  JRealTimeDemo adaptee;
+
+  JRealTimeDemo_startButton_actionAdapter(JRealTimeDemo adaptee) {
+    this.adaptee = adaptee;
+  }
+  public void actionPerformed(ActionEvent e) {
+    adaptee.startButton_actionPerformed(e);
+  }
+}
+
+class JRealTimeDemo_stopButton_actionAdapter implements ActionListener {
+  JRealTimeDemo adaptee;
+
+  JRealTimeDemo_stopButton_actionAdapter(JRealTimeDemo adaptee) {
+    this.adaptee = adaptee;
+  }
+  public void actionPerformed(ActionEvent e) {
+    adaptee.stopButton_actionPerformed(e);
+  }
+}
+
+class JRealTimeDemo_resetButton_actionAdapter implements ActionListener {
+  JRealTimeDemo adaptee;
+
+  JRealTimeDemo_resetButton_actionAdapter(JRealTimeDemo adaptee) {
+    this.adaptee = adaptee;
+  }
+  public void actionPerformed(ActionEvent e) {
+    adaptee.resetButton_actionPerformed(e);
+  }
+}
diff --git a/src/server/LookAndFeel.java b/src/server/LookAndFeel.java
new file mode 100644
index 0000000..ad7d27b
--- /dev/null
+++ b/src/server/LookAndFeel.java
@@ -0,0 +1,20 @@
+package server;
+import javax.swing.UIManager.LookAndFeelInfo;
+import javax.swing.UIManager;  
+import javax.swing.UnsupportedLookAndFeelException;        
+class LookAndFeel
+{
+    public static void set() 
+    {
+        try {
+            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
+                if ("Nimbus".equals(info.getName())) {
+                    UIManager.setLookAndFeel(info.getClassName()); //com.sun.java.swing.plaf.windows.WindowsLookAndFeel
+                    break;
+                }
+            }
+        } catch (Exception e) {
+            // If Nimbus is not available, you can set the GUI to another look and feel.
+        } 
+    }
+}
\ No newline at end of file
diff --git a/src/server/PseudoRealTimeData.java b/src/server/PseudoRealTimeData.java
new file mode 100644
index 0000000..744dd57
--- /dev/null
+++ b/src/server/PseudoRealTimeData.java
@@ -0,0 +1,233 @@
+/*
+ * $Id: PseudoRealTimeData.java,v 1.6 2001/12/13 19:07:05 dwd Exp $
+ *
+ * This software is provided by NOAA for full, free and open release.  It is
+ * understood by the recipient/user that NOAA assumes no liability for any
+ * errors contained in the code.  Although this software is released without
+ * conditions or restrictions in its use, it is expected that appropriate
+ * credit be given to its author and to the National Oceanic and Atmospheric
+ * Administration should the software be included by the recipient as an
+ * element in other product development.
+ */
+package server;
+
+import gov.noaa.pmel.sgt.SGLabel;
+import gov.noaa.pmel.util.GeoDate;
+import gov.noaa.pmel.sgt.dm.SGTLine;
+import gov.noaa.pmel.sgt.dm.SGTData;
+import gov.noaa.pmel.sgt.dm.SGTMetaData;
+import gov.noaa.pmel.util.SoTRange;
+import gov.noaa.pmel.util.IllegalTimeValue;
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.Date;
+
+import javax.swing.Timer;
+
+/**
+ * Generates a real-time data stream using SGTLine and
+ * javax.swing.Timer. PseudoRealTimeData
+ * generates PropertyCchangeEvents
+ * whenever data is added "dataModified" or the data range changes
+ * "rangeModified". The "dataModified" event is directly handled by
+ * sgt and the "rangeModified" event needs to be handled
+ * by the graphics application.
+ *
+ * 

PseudoRealTimeData demonstrates how a class that + * implements the SGTLine interface can use the + * getXRange() and getYRange() methods to + * produce "nice" plots. This class updates the data each time step, + * but updates the range only after a day has passed. + * + * @author Donald Denbo + * @version $Revision: 1.6 $, $Date: 2001/12/13 19:07:05 $ + * @since 2.0 + */ + +public class PseudoRealTimeData implements SGTLine, ActionListener { + private SGTMetaData xMeta_; + private SGTMetaData yMeta_; + private SoTRange.GeoDate xRange_; + private SoTRange.Double yRange_; + private GeoDate[] xData_; + private double[] yData_; + private GeoDate tend_; + private int count_; + private String title_; + private SGLabel keyTitle_ = null; + private String id_; + private Timer timer_; + private PropertyChangeSupport changes_ = new PropertyChangeSupport(this); + private GeoDate ref_ = null; + // bufsize should be integral multiple of majorIncrement plus 1 + private int bufsize_ = 241; + private int offset_; + // offsetIncrement should be same as majorIncrement + private int offsetIncrement_ = 24; + + private double minorIncrement_ = 1.0; + private double majorIncrement_ = 24.0; + private int units_ = GeoDate.HOURS; + + private double A0_ = 1.0; + private double A1_ = 0.375; + private double A2_ = 0.2; + private double omega0_ = 0.251327412; + private double omega1_ = 0.3; + /** + * Constructor. + */ + public PseudoRealTimeData(String id, String title) { + xMeta_ = new SGTMetaData("Time", ""); + yMeta_ = new SGTMetaData("PseudoData", "Ps/day"); + title_ = title; + id_ = id; + timer_ = new Timer(200, this); + resetData(); + } + /** + * Get x data array. Always returns null. + */ + public double[] getXArray() { + return null; + } + /** + * Get y data values. Creates a copy of the buffer array. + */ + public double[] getYArray() { + if(count_ > 0) { + double[] temp = new double[count_+offset_]; + for(int i=0; i < count_+offset_; i++) { + temp[i] = yData_[i]; + } + return temp; + } else { + return null; + } + } + public GeoDate[] getTimeArray() { + if(count_ > 0) { + GeoDate[] temp = new GeoDate[count_+offset_]; + for(int i=0; i < count_+offset_; i++) { + temp[i] = xData_[i]; + } + return temp; + } else { + return null; + } + } + public SGTLine getAssociatedData() { + return null; + } + public boolean hasAssociatedData() { + return false; + } + public String getTitle() { + return title_; + } + public SGLabel getKeyTitle() { + return keyTitle_; + } + public String getId() { + return id_; + } + public SGTData copy() { + return null; + } + public boolean isXTime() { + return true; + } + public boolean isYTime() { + return false; + } + public SGTMetaData getXMetaData() { + return xMeta_; + } + public SGTMetaData getYMetaData() { + return yMeta_; + } + public SoTRange getXRange() { + return xRange_.copy(); + } + public SoTRange getYRange() { + return yRange_.copy(); + } + public void addPropertyChangeListener(PropertyChangeListener l) { + changes_.addPropertyChangeListener(l); + } + public void removePropertyChangeListener(PropertyChangeListener l) { + changes_.removePropertyChangeListener(l); + } + /** + * Start the timer and begin/continue generating property change events. + */ + public void startData() { + timer_.start(); + } + /** + * Stop the timer. + */ + public void stopData() { + timer_.stop(); + } + /** + * Reset the demonstration to the begining. + */ + public void resetData() { + xData_ = new GeoDate[bufsize_]; + yData_ = new double[bufsize_]; + try { + ref_ = new GeoDate("1999-01-01 00:00", "yyyy-MM-dd HH:mm"); + } catch (IllegalTimeValue e) { + e.printStackTrace(); + } + tend_ = new GeoDate(ref_); + // Add a little fudge to get last tic on the axis + tend_.increment(10.0, GeoDate.SECONDS); + yRange_ = new SoTRange.Double(-1.5, 1.5); + xRange_ = new SoTRange.GeoDate(new GeoDate(ref_), + tend_.increment(majorIncrement_, units_)); + xData_[0] = new GeoDate(ref_); + yData_[0] = 0.0; + count_ = 1; + offset_ = 0; + } + + /** + * Handle timer ActionEvents + *
Property Change: rangeModified and + * DataModified + */ + public void actionPerformed(ActionEvent e) { + if((count_+offset_) >= bufsize_) { + offset_ = offset_ - offsetIncrement_; + for(int i=0; i < bufsize_-offsetIncrement_; i++) { + xData_[i] = xData_[i+offsetIncrement_]; + yData_[i] = yData_[i+offsetIncrement_]; + } + xRange_.start = xData_[0]; + } + xData_[count_+offset_] = new GeoDate(ref_.increment(minorIncrement_, units_)); + yData_[count_+offset_] = tSeries(count_); + if(xData_[count_+offset_].after(tend_)) { + SoTRange.GeoDate oldRange = (SoTRange.GeoDate)xRange_.copy(); + /** + * compute new range + */ + tend_.increment(majorIncrement_, units_); + xRange_.end = tend_; + changes_.firePropertyChange("rangeModified", oldRange, xRange_); + } else { + changes_.firePropertyChange("dataModified", + new Integer(count_), + new Integer(count_+1)); + } + count_++; + } + + private double tSeries(int val) { + return A0_*Math.sin(omega0_*val)+A1_*Math.sin(omega1_*val)+A2_*Math.random(); + } +} diff --git a/src/server/RankingServer.java b/src/server/RankingServer.java new file mode 100644 index 0000000..b679c3d --- /dev/null +++ b/src/server/RankingServer.java @@ -0,0 +1,110 @@ +package server; +import java.io.*; +import java.net.*; +import java.util.*; +import user.*; +import java.text.*; +import javax.swing.*; + +public class RankingServer extends Thread +{ + private long SECONDS = 30000; + List com; + Server server; + int close; + + public RankingServer(String name,List c,Server s) throws IOException + { + super(name); + com=c; + server=s; + } + + DecimalFormat twoDForm = new DecimalFormat("#.##"); + public void run() { + close=0; + while (!interrupted()) + { + if(close==1) + break; + try + { + String dString="rank::"; + sortUsers(); + for(int i=RegList.userList.size()-1;i>=0;i--) + { + User user=RegList.userList.get(i); + if(!user.isBanned()) + dString+=user.getName()+"->"+twoDForm.format(getScore(user))+":"; + } + //final String sss=dString; + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + String jj=""; + for(int i=RegList.userList.size()-1;i>=0;i--) + { + User user=RegList.userList.get(i); + jj+=(RegList.userList.size()-i)+" ) "+user.getName()+"->"+twoDForm.format(getScore(user))+"\n"; + } + StockMart.ranks.setText(jj); + } + }); + server.sendMulti(dString); + try + { + sleep(SECONDS); + }catch(InterruptedException e){} + }catch(Exception e) + { + e.printStackTrace(); + return; + } + } + } + + void sortUsers() + { + synchronized(RegList.userList) + { + synchronized(com) + { + for(int i=0;i=0;j--) + { + if((getScore(RegList.userList.get(j))>getScore(key) && !RegList.userList.get(j).isBanned()) || key.isBanned()) + RegList.userList.set(j+1,RegList.userList.get(j)); + else + break; + } + RegList.userList.set(j+1,key); + } + } + } + } + + double getScore(User u) + { + synchronized(u) + { + double mon=Double.valueOf(twoDForm.format(u.getCurrentMoney())); + double score=mon; + List list=u.getCurrentShares(); + for(int i=0;i userList; + static protected List regno; + static void loadList() + { + userList=new ArrayList(); + regno=new ArrayList(); + try + { + BufferedReader br=new BufferedReader(new FileReader("reg.txt")); + String str; + while((str=br.readLine())!=null) + { + str=str.trim().toLowerCase(); + regno.add(str); + } + }catch(Exception m){ + m.printStackTrace();} + } + static int registerUser(final String regno,final String name,String pass) + { + synchronized(userList) + { + //if(containsRegNo(regno)) + { + for(int i=0;i companies; + List clientList; + + abstract class Thread1 extends Thread + { + abstract public void sendMessage(String mess); + } + + public Server(List comp) throws IOException { + companies=comp; + serverSocket = new ServerSocket(4446,20000); + serverSocket.setReuseAddress(true); + chat=new ChatServer(this); + clientList=new ArrayList(); + } + + // This server starts on a seperate thread so you can still do other things on the server program + public void startServer() { + if (!started) { + started = true; + serverThread = new Thread() { + public void run() { + while (Server.this.started) { + Socket clientSocket = null; + try { + clientSocket = serverSocket.accept(); + openClient(clientSocket); + try{ + Thread.sleep(10); + }catch(Exception n){} + } catch (SocketException e) { + System.err.println("Server closed."); + } catch (IOException e) { + System.err.println("Accept failed."); + } + } + } + }; + serverThread.start(); + chat.start(); + } + } + + public void stopServer() { + this.started = false; + serverThread.interrupt(); + try { + serverSocket.close(); + } catch (IOException ex) { + System.err.println("Server stop failed."); + } + } + + public void sendMulti(String mess) { + for(int i=0;i=0) + { + if(user.getChat()-command1.substring(command1.indexOf(":")+1).length()>=0) + { + //synchronized(chatHist) + //{ + user.setChat(user.getChat()-command1.substring(command1.indexOf(":")+1).length()); + str=user.getName()+":"+command1.substring(command1.indexOf(":")+1); + chatHist += "<"+user.getName()+"> : "+command1.substring(command1.indexOf(":")+1)+"\n"; + chat.chaat+="<"+user.getName()+"> : "+command1.substring(command1.indexOf(":")+1)+"\n"; + //} + final String ptr=str; + new Thread(){ + public void run() + { + chat.interrupt(); + } + }.start(); + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + StockMart.chat.setText(chatHist); + } + }); + } + } + try{ + objout.writeObject(Integer.toString(user.getChat())); + objout.flush(); + }catch(Exception e) + { + e.printStackTrace(); + } + } + else if(cmmd[0].equals("chath")) + { + try{ + objout.writeObject(chatHist); + objout.flush(); + }catch(Exception e) + { + e.printStackTrace(); + } + } + else if(StockMart.started) + { + if(cmmd[0].equals("buy")) + { + final Shares share=new Shares(); + share.company=command1.split(":")[1].trim(); + share.qty=Integer.parseInt(cmmd[2]); + share.id=id++; + share.cost=-1.0; + share.sellid=-1; + share.buyed=new Date(); + share.ordered=new Date(); + share.status="Shares Pending"; + share.notCanceled=true; + + Company comp=null; + for(int k=0;k0 && shar.qty>0 && sh.qty<=shar.qty && sh.cost!=-1.0) + { + shar.qty-=sh.qty; + comp.sharessold-=sh.qty; + sh.buyed=(Date)shar.buyed.clone(); + user.setCurrentMoney(user.getCurrentMoney()+Double.parseDouble(StockMart.twoDForm.format(sh.qty*sh.cost*0.98))); + sh.status="Payment Received"; + if(shar.qty<=0) + user.getCurrentShares().remove(shar); + } + else + { + sh.status="Failed (Nothing to sell)"; + } + }catch(Exception nn) + { + sh.status="Failed (Nothing to sell)"; + } + } + else + { + //comp.sharessold+=sh.qty; + sh.status="Canceled"; + } + } + } + try{ + objout.reset(); + objout.writeObject(user); + objout.flush(); + }catch(Exception e) + { + e.printStackTrace(); + } + } + }.start(); + + try{ + user.getPendingShares().add(share); + objout.writeObject(share); + objout.flush(); + }catch(Exception e) + { + e.printStackTrace(); + } + } + else if(cmmd[0].equals("cancel")) + { + try{ + int id=Integer.parseInt(cmmd[1]); + int sellid=Integer.parseInt(cmmd[2]); + Shares sh=null; + for(int i=0;i companies; + Server server; + BroadcastServer bserver; + RankingServer rserver; + static double sensex; + Thread calculations; + int SLEEP=30000; + DecimalFormat twoDForm = new DecimalFormat("#.##"); + + void initialise() + { + companies=new ArrayList(); + RegList.loadList(); + loadCompanies(); + } + void startApp() + { + try{ + server=new Server(companies); + }catch(Exception m) + { + m.printStackTrace(); + } + server.startServer(); + try{ + bserver=new BroadcastServer("Share Market Broadcast",companies,server); + }catch(Exception mm) + { + mm.printStackTrace(); + } + try{ + rserver=new RankingServer("Share Market Ranks Broadcast",companies,server); + }catch(Exception mm) + { + mm.printStackTrace(); + } + rserver.start(); + } + void start() + { + bserver.start(); + calculations=new Thread(){ + public void run() + { + while(!interrupted()) + { + synchronized(companies) + { + double d=0.0; + double e=0.0; + double f=0.0; + for(int j=0;j0.0) + com.sharevalue.add(newvalue); + else + { + //bankrupt + } + com.tsharessold+=com.sharessold; + com.sharessold=0; + } + sensex = Double.valueOf(twoDForm.format(e/f*100)); + } + SwingUtilities.invokeLater(new Runnable(){ + public void run(){ + StockMart.updateCompanyTable(); + } + }); + try{ + Thread.sleep(SLEEP); + }catch(Exception mm){} + } + } + }; + calculations.start(); + } + void loadCompanies() + { + try + { + BufferedReader br=new BufferedReader(new FileReader("companies.txt")); + String str; + while((str=br.readLine())!=null) + { + String s[]=str.trim().split(":"); + List l=new ArrayList(); + l.add(Double.parseDouble(s[1])); + companies.add(new Company(s[0],l,0,Integer.parseInt(s[2]))); + } + }catch(Exception m){ + m.printStackTrace();} + } + void stop() + { + try + { + server.stopServer(); + }catch(Exception m){} + try + { + bserver.close=1; + }catch(Exception m){} + try + { + rserver.close=1; + }catch(Exception m){} + try + { + calculations.stop(); + }catch(Exception m){} + } +} diff --git a/src/server/StockMart.java b/src/server/StockMart.java new file mode 100644 index 0000000..7273e85 --- /dev/null +++ b/src/server/StockMart.java @@ -0,0 +1,351 @@ +package server; +import javax.swing.*; +import javax.swing.table.*; +import javax.swing.event.*; +import java.awt.*; +import java.awt.event.*; +import java.text.*; +import java.util.Date; +import user.*; +import java.io.*; +class StockMart +{ + static JPanel puser,mpanel; + static JLabel userd,sensex; + static JTextArea chat,ranks,news; + static JTable usertable,comptable; + static DefaultTableModel dtmu,dtmc; + static JTextField cht,ucht,tt; + static JCheckBox chatEnabled; + static JComboBox users; + static String newsfeed=""; + static ShareMarket shr; + static JButton server,post,changep,banu; + static String colusr[]=new String[]{"SrNo.","Company","Quantity","C.M.P.","Mkt Value","Gain/Loss","Status"}; + static String[] columnNames2 = {"SrNo.","Company","C.M.P.","% Change","Low","High"}; + static DecimalFormat twoDForm = new DecimalFormat("#.##"); + static boolean started=false; + static int totTime; + static User uuu; + static Date startDate; + static DefaultTableCellRenderer dtr=new DefaultTableCellRenderer(){ + public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) { + if(value.toString().indexOf("-")!=-1) + { + value=value.toString()+" \u25bc"; + } + else + { + value=value.toString()+" \u25b2"; + } + Component c = super.getTableCellRendererComponent(table, value,isSelected, hasFocus,row, column); + if(value.toString().indexOf("-")!=-1) + { + c.setForeground(Color.red); + } + else + { + c.setForeground(Color.green); + } + return c; + } + }; + static Timer timer2=new Timer(1000,new ActionListener(){ + public void actionPerformed(ActionEvent e) + { + try{ + int secs = (int)(totTime*60-(new Date().getTime()-startDate.getTime())/1000); + int hrs = secs/3600; + int mins = (secs/60)-hrs*60; + sensex.setText("Sensex: "+ShareMarket.sensex+" Time Left: "+hrs+":"+mins); + if(secs<=0) + { + started=false; + server.setText("Start"); + //shr.stop(); + timer2.stop(); + } + }catch(Exception bb){} + } + }); + static Timer timer=new Timer(1000,new ActionListener(){ + public void actionPerformed(ActionEvent e) + { + try{ + uuu=RegList.getUserWithName((String)users.getSelectedItem()); + userd.setText("

User-> RegNo: "+uuu.getRegNo()+"      Name: "+uuu.getName()+"      Password: "+uuu.getPassword()+"
Money: "+twoDForm.format(uuu.getCurrentMoney())+" Chat: "+uuu.getChat()+"
"); + //ucht.setText(uuu.getChat()+""); + chatEnabled.setSelected(uuu.chatEnabled); + if(!uuu.isBanned()) + banu.setText("Ban this User"); + else + banu.setText("Unban this User"); + refreshUserTable(uuu); + }catch(Exception n) + { + } + } + }); + + public static void refreshUserTable(User u) + { + Object obj[][]=new Object[u.getCurrentShares().size()+u.getPendingShares().size()+1][7]; + java.util.List ss=u.getCurrentShares(); + for(int i=0;i RegNo: Name: Password: Money: Chat: "); + userd.setPreferredSize(new Dimension(300,25)); + sensex=new JLabel("Sensex: Time Left: "); + tt=new JTextField(5); + tt.setText("120"); + news=new JTextArea(5,30); + chat=new JTextArea(5,30); + chat.setFont(new Font("Lucida Sans Unicode",Font.PLAIN,15)); + chat.setForeground(Color.green.darker()); + chat.setEditable(false); + chat.setLineWrap(true); + ranks=new JTextArea(5,50); + ranks.setEditable(false); + ranks.setForeground(Color.red.darker()); + ranks.setFont(new Font("Lucida Sans Unicode",Font.BOLD,15)); + ranks.setLineWrap(true); + cht=new JTextField(30); + ucht=new JTextField(5); + users=new JComboBox(); + chatEnabled=new JCheckBox("ChatEnabled",true); + dtmu=new DefaultTableModel(); + dtmc=new DefaultTableModel(); + usertable=new JTable(dtmu){ + public boolean isCellEditable(int r,int c) + { + return false; + } + }; + comptable=new JTable(dtmc){ + public boolean isCellEditable(int r,int c) + { + if(c==2) + return true; + return false; + } + }; + dtmc.addTableModelListener(new TableModelListener(){ + public void tableChanged(TableModelEvent tme) + { + final int row=tme.getFirstRow(); + try{ + if(tme.getColumn()==2) + shr.companies.get(row).sharevalue.add(Double.parseDouble(twoDForm.format(Double.valueOf(dtmc.getValueAt(row,2).toString())))); + }catch(Exception m) + { + m.printStackTrace(); + } + } + }); + usertable.setRowHeight(30); + usertable.getTableHeader().setReorderingAllowed(false); + usertable.setFillsViewportHeight(true); + comptable.setRowHeight(30); + comptable.getTableHeader().setReorderingAllowed(false); + comptable.setFillsViewportHeight(true); + JScrollPane jspu=new JScrollPane(usertable); + JScrollPane jspc=new JScrollPane(comptable); + + JPanel chatp=new JPanel(new BorderLayout()); + chatp.setPreferredSize(new Dimension(300,300)); + chatp.add(new JScrollPane(chat,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),BorderLayout.CENTER); + chatp.add(cht,BorderLayout.SOUTH); + JPanel rr=new JPanel(new BorderLayout()); + rr.setPreferredSize(new Dimension(300,250)); + rr.add(new JScrollPane(ranks,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),BorderLayout.CENTER); + JPanel rank=new JPanel(new BorderLayout()); + rank.setPreferredSize(new Dimension(600,250)); + rank.add(chatp,BorderLayout.WEST); + rank.add(rr,BorderLayout.EAST); + + changep=new JButton("Change Password"); + banu=new JButton("Ban this User"); + + JPanel jpaa=new JPanel(); + jpaa.setLayout(new BorderLayout()); + jpaa.add(changep,BorderLayout.EAST); + jpaa.add(banu,BorderLayout.WEST); + jpaa.add(ucht,BorderLayout.CENTER); + + JPanel jp=new JPanel(); + jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS)); + jp.add(users); + jp.add(userd); + jp.add(jpaa); + //jp.add(changep); + //jp.add(ucht); + jp.add(chatEnabled); + jp.add(jspu); + + JPanel newspanel=new JPanel(new BorderLayout()); + newspanel.add(new JScrollPane(news,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),BorderLayout.CENTER); + newspanel.add(post,BorderLayout.EAST); + + puser=new JPanel(new BorderLayout()); + puser.add(rank,BorderLayout.NORTH); + puser.add(jp,BorderLayout.CENTER); + + JPanel uu=new JPanel(new BorderLayout()); + uu.add(tt,BorderLayout.WEST); + uu.add(sensex,BorderLayout.CENTER); + uu.add(server,BorderLayout.EAST); + + JPanel qq=new JPanel(new BorderLayout()); + qq.add(jspc,BorderLayout.CENTER); + qq.add(newspanel,BorderLayout.SOUTH); + qq.add(uu,BorderLayout.NORTH); + + mpanel.add(qq,BorderLayout.CENTER); + mpanel.add(puser,BorderLayout.EAST); + + ucht.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e){ + try{ + uuu.setChat(Integer.parseInt(ucht.getText().trim())); + }catch(Exception jj){} + } + }); + banu.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e){ + try{ + if(!uuu.isBanned()) + uuu.setBanned(true); + else + uuu.setBanned(false); + }catch(Exception jj){} + } + }); + chatEnabled.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e){ + try{ + uuu.chatEnabled=chatEnabled.isSelected(); + }catch(Exception jj){} + } + }); + changep.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e){ + try{ + String str=JOptionPane.showInputDialog("Enter new Password."); + if(str!=null && !str.equals("")) + uuu.setPassword(str); + }catch(Exception jj){} + } + }); + cht.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e){ + try{ + final String msg="ADMIN:"+cht.getText(); + shr.server.chatHist+=" : "+cht.getText()+"\n"; + shr.server.chat.chaat+=" : "+cht.getText()+"\n"; + chat.setText(shr.server.chatHist); + cht.setText(""); + new Thread(){ + public void run() + { + shr.server.chat.interrupt(); + } + }.start(); + }catch(Exception jj){} + } + }); + jf.pack(); + jf.setVisible(true); + } +} \ No newline at end of file diff --git a/src/server/companies.txt b/src/server/companies.txt new file mode 100644 index 0000000..09021aa --- /dev/null +++ b/src/server/companies.txt @@ -0,0 +1,21 @@ +Reliance:1000 +Microsoft:2000 +Maruti:650 +Hero:1200 +Leopard:500 +Honda:890 +Gagandeep Steels:770 +Bank of Baroda:300 +Tata Docomo:560 +Air India:896 +Pepsi:234 +Tata Tea:465 +Samsung:723 +Yamaha:452 +Punjab National Bank:489 +BSNL:654 +Asian Paints:720 +Dell:213 +Sony:754 +LG:328 +Whirlpool:578 \ No newline at end of file diff --git a/src/server/money.txt b/src/server/money.txt new file mode 100644 index 0000000..e37d32a --- /dev/null +++ b/src/server/money.txt @@ -0,0 +1 @@ +1000 \ No newline at end of file diff --git a/src/server/reg.txt b/src/server/reg.txt new file mode 100644 index 0000000..041c7a2 --- /dev/null +++ b/src/server/reg.txt @@ -0,0 +1 @@ +1101cs09 \ No newline at end of file diff --git a/src/user/Shares.java b/src/user/Shares.java new file mode 100644 index 0000000..fc0b6ad --- /dev/null +++ b/src/user/Shares.java @@ -0,0 +1,27 @@ +package user; +import java.io.*; +import java.util.*; + +public class Shares implements Serializable +{ + volatile public String company,status; + volatile public int qty,id,sellid; + volatile public double cost; + public Date ordered,buyed; + volatile public boolean notCanceled; + public Shares() + { + } + public Shares(Shares s) + { + company=new String(s.company); + status=new String(s.status); + qty=s.qty; + id=s.id; + sellid=s.sellid; + cost=s.cost; + ordered=(Date)s.ordered.clone(); + buyed=(Date)s.buyed.clone(); + notCanceled=s.notCanceled; + } +} diff --git a/src/user/User.java b/src/user/User.java new file mode 100644 index 0000000..3b65ee1 --- /dev/null +++ b/src/user/User.java @@ -0,0 +1,173 @@ +package user; +import java.io.*; +import java.util.*; +import javax.swing.*; +public class User implements Serializable +{ + volatile protected String name; + volatile protected String regno; + volatile protected String password; + volatile protected boolean loggedin=false; + volatile protected double money; + volatile protected List shares; + volatile protected List pendingshares; + //protected List history; + volatile protected UserDataChangedListener udcl; + protected User u; + volatile protected int chat; + volatile public boolean chatEnabled,banned; + public User(String r,String n,String p,int c) + { + chat=c; + name=n; + regno=r; + chatEnabled=true; + banned=false; + password=p; + udcl=null; + shares=new ArrayList(); + pendingshares=new ArrayList(); + //history=new ArrayList(); + try{ + BufferedReader br=new BufferedReader(new FileReader("money.txt")); + money=Integer.parseInt(br.readLine()); + }catch(Exception e){} + u=this; + } + public void setChat(int c) + { + chat=c; + } + public void setBanned(boolean c) + { + banned=c; + } + public boolean isBanned() + { + return banned; + } + public int getChat() + { + return chat; + } + public void addUserDataChangeListener(UserDataChangedListener u) + { + udcl=u; + } + public UserDataChangedListener removeUserDataChangeListener() + { + UserDataChangedListener u=udcl; + udcl=null; + return u; + } + public void invokeListener() + { + dataChanged(); + } + public void changeData(User user) + { + name=user.getName(); + regno=user.getRegNo(); + password=user.getPassword(); + loggedin=user.isLoggedIn(); + money=user.getCurrentMoney(); + shares=user.getCurrentShares(); + pendingshares=user.getPendingShares(); + chat=user.getChat(); + chatEnabled=user.chatEnabled; + u=this; + dataChanged(); + } + public boolean checkName(String n) + { + if(name.equals(n)) + return true; + return false; + } + public boolean checkPassword(String p) + { + if(password.equals(p)) + return true; + return false; + } + public boolean checkRegNo(String r) + { + if(regno.equals(r)) + return true; + return false; + } + public void setLoggedIn(boolean set) + { + loggedin=set; + } + public boolean isLoggedIn() + { + return loggedin; + } + public String getRegNo() + { + return regno; + } + public void setRegNo(String r) + { + regno=r; + dataChanged(); + } + public String getName() + { + return name; + } + public void setName(String n) + { + name=n; + dataChanged(); + } + public String getPassword() + { + return password; + } + public void setPassword(String p) + { + password=p; + dataChanged(); + } + public double getCurrentMoney() + { + return money; + } + public void setCurrentMoney(double m) + { + money=m; + dataChanged(); + } + public List getCurrentShares() + { + return shares; + } + /*public List getHistory() + { + return history; + }*/ + public List getPendingShares() + { + return pendingshares; + } + public void setCurrentShares(List c) + { + shares=c; + } + public void setPendingShares(List c) + { + pendingshares=c; + } + public void dataChanged() + { + if(udcl!=null) + SwingUtilities.invokeLater(new Runnable(){ + public void run() + { + udcl.userDataChanged(u); + } + }); + } +} \ No newline at end of file diff --git a/src/user/UserDataChangedListener.java b/src/user/UserDataChangedListener.java new file mode 100644 index 0000000..b368307 --- /dev/null +++ b/src/user/UserDataChangedListener.java @@ -0,0 +1,6 @@ +package user; + +public interface UserDataChangedListener +{ + public void userDataChanged(User user); +} \ No newline at end of file