diff --git a/src/client/BackgroundAnimation.java b/src/client/BackgroundAnimation.java deleted file mode 100644 index ba30b10..0000000 --- a/src/client/BackgroundAnimation.java +++ /dev/null @@ -1,417 +0,0 @@ -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 deleted file mode 100644 index a3f9902..0000000 --- a/src/client/BroadcastClient.java +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index 64b5ae0..0000000 --- a/src/client/ChatClient.java +++ /dev/null @@ -1,55 +0,0 @@ -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 deleted file mode 100644 index caf66e0..0000000 --- a/src/client/Client.java +++ /dev/null @@ -1,269 +0,0 @@ -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 deleted file mode 100644 index 4fd92fc..0000000 --- a/src/client/Companies.java +++ /dev/null @@ -1,48 +0,0 @@ -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 deleted file mode 100644 index 981ff2c..0000000 --- a/src/client/RankingClient.java +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 7f3f42c..0000000 --- a/src/client/RankingWindow.java +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index a9a75e0..0000000 --- a/src/client/RegisterAction.java +++ /dev/null @@ -1,111 +0,0 @@ -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 deleted file mode 100644 index 79e9519..0000000 --- a/src/client/RibbonPane.java +++ /dev/null @@ -1,65 +0,0 @@ -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
deleted file mode 100644
index 3572653..0000000
--- a/src/client/ShareValuesChangeListener.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package client;
-
-interface ShareValuesChangeListener
-{
-    public void valuesChanged();
-}
\ No newline at end of file
diff --git a/src/client/test.java b/src/client/test.java
deleted file mode 100644
index 4d169f2..0000000
--- a/src/client/test.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package client;
-class test
-{
-    public void run()
-    {
-    }
-}
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/client/BackgroundAnimation.java b/src/com/ayushmaanbhav/jstockmart/client/BackgroundAnimation.java
new file mode 100644
index 0000000..32c8be3
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/client/BackgroundAnimation.java
@@ -0,0 +1,381 @@
+package com.ayushmaanbhav.jstockmart.client;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.GradientPaint;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.HeadlessException;
+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.ComponentEvent;
+import java.awt.event.ComponentListener;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.swing.JPanel;
+import javax.swing.SwingUtilities;
+import javax.swing.Timer;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
+
+@SuppressWarnings("serial")
+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);
+	}
+
+	Timer timer;
+	public void startAnimation() {
+		timer = new Timer(50, new ActionListener() {
+			public void actionPerformed(ActionEvent e) {
+				curves.animate();
+				curves.repaint();
+			}
+		});
+		timer.start();
+	}
+
+	public void stopAnimation() {
+		timer.stop();
+	}
+
+	private void buildContentPane() {
+		// JPanel pane = new JPanel();
+		setDoubleBuffered(true);
+		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);
+			}
+		});
+	}
+}
+
+@SuppressWarnings("serial")
+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);
+	}
+}
+
+@SuppressWarnings("serial")
+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/com/ayushmaanbhav/jstockmart/client/BroadcastClient.java b/src/com/ayushmaanbhav/jstockmart/client/BroadcastClient.java
new file mode 100644
index 0000000..24b63b0
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/client/BroadcastClient.java
@@ -0,0 +1,94 @@
+package com.ayushmaanbhav.jstockmart.client;
+
+import java.util.*;
+import javax.swing.*;
+import java.text.*;
+public class BroadcastClient extends Thread {
+	StringBuffer sb;
+	DecimalFormat twoDForm;
+	int hj = 0;
+	ShareValuesChangeListener svcl;
+	int id;
+	
+	public BroadcastClient(StringBuffer s) {
+		id = 0;
+		sb = s;
+		svcl = null;
+		Companies.comp = new ArrayList();
+		twoDForm = new DecimalFormat("#.##");
+	}
+	
+	public void run(String poo) {
+		try {
+			StringBuffer fin = new StringBuffer();
+			final String rec[] = poo.split("=");
+			final String ids[] = rec[0].split("#");
+			int recid = Integer.parseInt(ids[0]);
+			if(recid <= id) {
+				return;
+			} else {
+				id = recid;
+			}
+			final String mtr[] = ids[1].split(";");
+			final String str[] = rec[1].split(";");
+			for (int i = 0; i < str.length; i++) {
+				String str2[] = str[i].split(":");
+				
+				int company_id = Integer.parseInt(new String(str2[0]));
+				String company_name = new String(str2[1]);
+				double mktvalue = Double.parseDouble(str2[2]);
+				double initial_value = Double.parseDouble(str2[3]);
+				double highest_value = Double.parseDouble(str2[4]);
+				double lowest_value = Double.parseDouble(str2[5]);
+				double price_precision = Double.parseDouble(str2[6]);
+				
+				Companies.updateValues(company_id, company_name, mktvalue, initial_value, highest_value, lowest_value, price_precision);
+				
+				fin.append(str2[1]);
+				fin.append(" : ");
+				fin.append(twoDForm.format(mktvalue));
+				if (mktvalue > initial_value)
+					fin.append("\u25b2"); // This
+											// is some text!
+				else if (mktvalue < initial_value)
+					fin.append("\u25bc");
+				double c = mktvalue - initial_value;
+				if (c > 0.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 { + if (hj == 0) { + GraphPanel.mainPanel.setScores(); + Main.jtp.setEnabledAt(3, true); + HistogramPanel.mainPanel.updateComboBox(Companies.comp); + Main.jtp.setEnabledAt(4, true); + hj = 1; + } else { + GraphPanel.mainPanel.repaint(); + } + } catch (Exception e) { + } + try { + svcl.valuesChanged(); + } catch (Exception e) { + } + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/com/ayushmaanbhav/jstockmart/client/Cashier.java b/src/com/ayushmaanbhav/jstockmart/client/Cashier.java new file mode 100644 index 0000000..2dc8829 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/Cashier.java @@ -0,0 +1,446 @@ +package com.ayushmaanbhav.jstockmart.client; + +import javax.swing.*; +import java.awt.*; +import javax.swing.border.*; +import java.awt.event.*; +import java.text.*; + +import com.ayushmaanbhav.jstockmart.user.*; +import com.sun.awt.AWTUtilities; + +@SuppressWarnings("restriction") +class Cashier { + JDialog jd; + float ii = 0; + DecimalFormat twoDForm = new DecimalFormat("#.##"); + Timer alphaChanger = new Timer(50, new ActionListener() { + private float incrementer = .10f; + @Override + public void actionPerformed(ActionEvent e) { + ii = ii + incrementer; + if (ii > ((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; + SpinnerNumberModel spinnermodel; + JSpinner.NumberEditor jspne; + JSpinner jsp; + Shares pp; + String cmp; + JRadioButton b2, b1; + JRadioButton b3, b4; + 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)); + + if (!b4.isSelected()) { + spinnermodel = new SpinnerNumberModel((double) comp.mktvalue, 1.0, comp.mktvalue * 100, (double) comp.price_precision); + jsp.setModel(spinnermodel); + jsp.setEditor(jspne); + } + + try { + int ent = Integer.parseInt(jtf.getText()); + double price = Double.parseDouble(twoDForm.format(Double.parseDouble(jsp.getValue().toString()))); + if (b3.isSelected()) { + 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)); + if (ent > pp.qty) + tot.setForeground(Color.red); + else + tot.setForeground(Color.black); + } + } else if (b4.isSelected()) { + if (b1.isSelected()) { + total = Double.valueOf(twoDForm.format(ent * price * 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 * price)); + if (ent > pp.qty) + tot.setForeground(Color.red); + else + tot.setForeground(Color.black); + } + } + } catch (Exception v) { + v.printStackTrace(); + total = 0; + tot.setForeground(Color.red); + } + tot.setText("Expected Cash Req./Rec.*: " + twoDForm.format(total)); + } + }); + + public Cashier(Client c, User u) { + client = c; + user = u; + } + + @SuppressWarnings("serial") + 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("Expected 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 cost = new JLabel("Limit Price : "); + if (b1.isSelected()) { + cost.setText("Upper Price Limit : "); + } else { + cost.setText("Lower Price Limit : "); + } + + spinnermodel = new SpinnerNumberModel((double) comp.mktvalue, 1.0, comp.mktvalue * 100, (double) comp.price_precision); + jsp = new JSpinner(spinnermodel); + jspne = new JSpinner.NumberEditor(jsp, "#.##"); + jspne.getTextField().setEditable(false); + jsp.setEditor(jspne); + jsp.setEnabled(false); + + ActionListener grplis = new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (b1.isSelected()) { + cost.setText("Upper Price Limit : "); + } else { + cost.setText("Lower Price Limit : "); + } + } + }; + b1.addActionListener(grplis); + b2.addActionListener(grplis); + + b3 = new JRadioButton("Market Order"); + b4 = new JRadioButton("Limit Order"); + b3.setSelected(true); + ButtonGroup grp2 = new ButtonGroup(); + grp2.add(b3); + grp2.add(b4); + ActionListener grp2lis = new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (b3.isSelected()) { + jsp.setEnabled(false); + } else { + jsp.setEnabled(true); + } + } + }; + b3.addActionListener(grp2lis); + b4.addActionListener(grp2lis); + + 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; + // System.out.println(jsp.getValue().toString()); + final double price = Double.parseDouble(twoDForm.format(Double.parseDouble(jsp.getValue().toString()))); + 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); + b3.setEnabled(false); + b4.setEnabled(false); + jsp.setEnabled(false); + final int kk = noofs; + new Thread() { + public void run() { + String cmd; + if (b1.isSelected()) + cmd = Commands.BUY; + else + cmd = Commands.SELL; + if (b3.isSelected()) + cmd += Commands.MARKET_ORDER; + else + cmd += Commands.LIMIT_ORDER; + + try { + client.placeOrder(user, cmd, comp, price, kk, shr.id); + } catch (Exception ff) { + client.placeOrder(user, cmd, comp, price, kk, -1); + } + timer.stop(); + alphaChanger.start(); + } + }.start(); + } + }); + JLabel cc1 = new JLabel("-> *Transaction charges : 2% of the total cash transactioned."); + JLabel cc2 = new JLabel("-> Red Text indicates warning that your order might fail."); + JLabel cc3 = new JLabel("-> Order can be placed either as a market order or limit order."); + 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 = 1; + 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(b3, gbc); + gbc.gridx = 2; + 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(b4, gbc); + gbc.gridx = 0; + gbc.gridy = 3; + 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 = 3; + 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 = 4; + 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(cost, gbc); + gbc.gridx = 1; + gbc.gridy = 4; + 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(jsp, gbc); + gbc.gridx = 0; + gbc.gridy = 5; + 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 = 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(cash, gbc); + gbc.gridx = 0; + gbc.gridy = 7; + 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 = 7; + 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 = 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(cc1, gbc); + gbc.gridx = 0; + gbc.gridy = 9; + 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 = 10; + 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/com/ayushmaanbhav/jstockmart/client/ChatClient.java b/src/com/ayushmaanbhav/jstockmart/client/ChatClient.java new file mode 100644 index 0000000..d3adbe7 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/ChatClient.java @@ -0,0 +1,42 @@ +package com.ayushmaanbhav.jstockmart.client; + +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 < ff.length; i++) { + jj += ff[i] + " "; + } + NewsPane.temp.delete(0, NewsPane.temp.length()); + NewsPane.temp.append(jj); + while (NewsPane.temp.length() <= 200) { + NewsPane.temp.append(" "); + } + } else { + NewsPane.temp.delete(0, NewsPane.temp.length()); + } + } + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/com/ayushmaanbhav/jstockmart/client/ChatWindow.java b/src/com/ayushmaanbhav/jstockmart/client/ChatWindow.java new file mode 100644 index 0000000..0ce5c90 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/ChatWindow.java @@ -0,0 +1,79 @@ +package com.ayushmaanbhav.jstockmart.client; +import javax.swing.*; + +import com.ayushmaanbhav.jstockmart.user.*; + +import java.awt.*; +import java.awt.event.*; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +@SuppressWarnings("serial") +class ChatWindow extends JPanel { + JTextField jtf; + JTextArea jta; + JLabel jlab; + Client cc; + User user; + String remain; + BlockingQueue queue; + + public ChatWindow(final User u, Client client) { + user = u; + cc = client; + setLayout(new BorderLayout()); + jlab = new JLabel("<> (" + u.getChat() + " characters remainimg)"); + jtf = new JTextField(); + jta = new JTextArea(); + jta.setFont(new Font("Calibri", Font.PLAIN, 13)); + jta.setLineWrap(true); + jta.setEditable(false); + jta.setForeground(Color.green.darker()); + // jtf.setEnabled(false); + jtf.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String s = jtf.getText().trim(); + if (!s.equals("")) { + jtf.setText(""); + queue.offer(s); + } + } + }); + queue = new LinkedBlockingQueue(); + new Thread() { + public void run() { + while (true) { + try { + String message = queue.take(); + remain = sendString(message); + u.setChat(Integer.parseInt(remain)); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + jlab.setText("<> (" + u.getChat() + " characters remainimg)"); + } + }); + } catch (Exception mm) { + mm.printStackTrace(); + } + 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; + } + + synchronized String sendString(String s) { + return cc.sendChat(s, user.getName(), user.getPassword()); + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/client/Client.java b/src/com/ayushmaanbhav/jstockmart/client/Client.java new file mode 100644 index 0000000..eda4c29 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/Client.java @@ -0,0 +1,244 @@ +package com.ayushmaanbhav.jstockmart.client; +import java.io.*; +import java.net.*; + +import com.ayushmaanbhav.jstockmart.user.*; +import com.ayushmaanbhav.jstockmart.utils.TrippleArrayList; + +public class Client { + boolean connected = false; + Socket socket = null; + PrintWriter out = null; + // BufferedReader in = null; + ObjectInputStream in; + String domain; + static boolean testing = true; + volatile int commID = 0; + Client ccl; + int usrD; + Main m; + TestMain maain; + BroadcastClient bc = null; + RankingClient rc = null; + ChatClient cc = null; + Receiver rec; + + public Client(Main mm, TestMain maaii) { + ccl = this; + m = mm; + maain = maaii; + commID = 0; + } + + public void connect(String user, String pass) { + if (!connected) { + try { + socket = new Socket(domain, 4446); + out = new PrintWriter(socket.getOutputStream(), true); + 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(ccl); + rec.start(); + } + } + + String login(String domain, String user, String pass) { + int cmdID = commID++; + this.domain = domain; + connect(user, pass); + try { + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.LOG_IN + ":" + user + ":" + pass); + out.println(cmdID + ";" + Commands.LOG_IN + ":" + user + ":" + pass); + out.flush(); + String rep = (String) receiveReply(cmdID); + 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 { + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.REGISTER + ":" + regno + ":" + user + ":" + pass); + out.println(cmdID + ";" + Commands.REGISTER + ":" + regno + ":" + user + ":" + pass); + out.flush(); + String rep = (String) receiveReply(cmdID); + disconnect(); + return rep.split(":")[0]; + } catch (Exception r) { + r.printStackTrace(); + } + return null; + } + + public void disconnect() { + int cmdID = commID++; + this.connected = false; + try { + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.LOG_OUT); + out.println(cmdID + ";" + Commands.LOG_OUT); + 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 { + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.GET_USER_DETAILS); + usrD = 1; + out.println(cmdID + ";" + Commands.GET_USER_DETAILS); + out.flush(); + User vv = (User) receiveReply(cmdID); + 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 { + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.SEND_CHAT_MESSAGE + ":" + s.trim()); + out.println(cmdID + ";" + Commands.SEND_CHAT_MESSAGE + ":" + s.trim()); + out.flush(); + return (String) receiveReply(cmdID); + } catch (Exception r) { + r.printStackTrace(); + } + return null; + } + + String getChatHistory(String user, String pass) { + int cmdID = commID++; + connect(user, pass); + try { + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.GET_CHAT_HISTORY); + out.println(cmdID + ";" + Commands.GET_CHAT_HISTORY); + out.flush(); + return (String) receiveReply(cmdID); + } catch (Exception r) { + r.printStackTrace(); + } + return null; + } + + void placeOrder(final User user, String cmd, Company comp, double cost_limit, int qty_limit, int id) { + int cmdID = commID++; + connect(user.getName(), user.getPassword()); + try { + if (testing) + System.out.println("Command: " + cmdID + ";" + cmd + ":" + comp.name + ":" + Integer.toString(qty_limit) + ":" + Double.toString(cost_limit) + ":" + id); + out.println(cmdID + ";" + cmd + ":" + comp.name + ":" + Integer.toString(qty_limit) + ":" + Double.toString(cost_limit) + ":" + id); + out.flush(); + Shares pen = (Shares) receiveReply(cmdID); + 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 { + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.CANCEL_ORDER + ":" + id + ":" + sellid); + out.println(cmdID + ";" + Commands.CANCEL_ORDER + ":" + id + ":" + sellid); + out.flush(); + return (String) receiveReply(cmdID); + } catch (Exception r) { + r.printStackTrace(); + } + return null; + } + + @SuppressWarnings("unchecked") + java.util.List getHistory(String comp, int count) { + int cmdID = commID++; + // connect(user.getName(),user.getPassword()); + try { + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.GET_COMPANY_HISTORY + ":" + comp + ":" + Integer.toString(count)); + out.println(cmdID + ";" + Commands.GET_COMPANY_HISTORY + ":" + comp + ":" + Integer.toString(count)); + out.flush(); + return (java.util.List) receiveReply(cmdID); + } catch (Exception r) { + r.printStackTrace(); + } + return null; + } + + @SuppressWarnings("unchecked") + TrippleArrayList getCompanyStats(String comp) { + int cmdID = commID++; + // connect(user.getName(),user.getPassword()); + try { + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.GET_COMPANY_STATS + ":" + comp); + out.println(cmdID + ";" + Commands.GET_COMPANY_STATS + ":" + comp); + out.flush(); + return (TrippleArrayList) receiveReply(cmdID); + } catch (Exception r) { + r.printStackTrace(); + } + return null; + } + + String getSendCompanyStatsPeriodically(String comp) { + int cmdID = commID++; + // connect(user.getName(),user.getPassword()); + try { + if (comp == null) + comp = "-1"; + if (testing) + System.out.println("Command: " + cmdID + ";" + Commands.SEND_PERIODIC_STATS + ":" + comp); + out.println(cmdID + ";" + Commands.SEND_PERIODIC_STATS + ":" + comp); + out.flush(); + return (String) receiveReply(cmdID); + } catch (Exception r) { + r.printStackTrace(); + } + return null; + } + + Object receiveReply(int cmdID) { + Object obj = null; + while (obj == null) { + try { + obj = rec.rev.take(cmdID); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + if (testing) + System.out.println("Got: " + cmdID + " : " + obj.toString() + " : " + Thread.currentThread()); + return obj; + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/client/Companies.java b/src/com/ayushmaanbhav/jstockmart/client/Companies.java new file mode 100644 index 0000000..3516620 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/Companies.java @@ -0,0 +1,57 @@ +package com.ayushmaanbhav.jstockmart.client; + +import java.util.*; +class Companies { + static List comp; + static Double sensex; + + static Company getCompanyWithName(String name) { + for (int i = 0; i < comp.size(); i++) { + if (comp.get(i).name.equalsIgnoreCase(name)) + return comp.get(i); + } + return null; + } + + static Company getCompanyWithId(int id) { + for (int i = 0; i < comp.size(); i++) { + if (comp.get(i).id == id) + return comp.get(i); + } + return null; + } + + static void updateValues(int id, String name, double m, double i, double h, double l, double p_precision) { + try { + getCompanyWithId(id).updateData(m, h, l, p_precision); + } catch (Exception e) { + comp.add(new Company(id, name, m, i, h, l, p_precision)); + } + } + + static void updateValues(int id, double m, double p_precision) throws Exception { + try { + getCompanyWithId(id).updateData(m, p_precision); + } catch (Exception e) { + throw new Exception("company does not exist"); + } + } + + static void updateValues(int id, double m) throws Exception { + try { + getCompanyWithId(id).updateData(m); + } catch (Exception e) { + throw new Exception("company does not exist"); + } + } + + static void removeDuplicates() { + for (int i = 0; i < comp.size(); i++) { + for (int j = 0; j < comp.size(); j++) { + if (comp.get(i).id == comp.get(j).id) { + comp.remove(j); + } + } + } + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/client/Company.java b/src/com/ayushmaanbhav/jstockmart/client/Company.java new file mode 100644 index 0000000..b3e16df --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/Company.java @@ -0,0 +1,53 @@ +package com.ayushmaanbhav.jstockmart.client; +import java.util.*; + +class Company { + String name; + int id, yy; + Double inivalue, mktvalue, low, high, price_precision; + List sharevalue; + + public Company(int ii, String n, double m, double i, double hi, double lo, double p_precision) { + name = new String(n); + sharevalue = new ArrayList(); + mktvalue = m; + sharevalue.add(m); + inivalue = i; + low = lo; + high = hi; + id = ii; + price_precision = p_precision; + yy = 0; + } + + public void updateData(double m, double hi, double lo, double p_precision) { + mktvalue = m; + price_precision = p_precision; + try { + // if (m != sharevalue.get(sharevalue.size() - 1)) + sharevalue.add(m); + } catch (Exception ml) { + } + low = lo; + high = hi; + } + + public void updateData(double m, double p_precision) { + mktvalue = m; + price_precision = p_precision; + try { + // if (m != sharevalue.get(sharevalue.size() - 1)) + sharevalue.add(m); + } catch (Exception ml) { + } + } + + public void updateData(double m) { + mktvalue = m; + try { + // if (m != sharevalue.get(sharevalue.size() - 1)) + sharevalue.add(m); + } catch (Exception ml) { + } + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/client/GraphPanel.java b/src/com/ayushmaanbhav/jstockmart/client/GraphPanel.java new file mode 100644 index 0000000..9b80d0a --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/GraphPanel.java @@ -0,0 +1,222 @@ +package com.ayushmaanbhav.jstockmart.client; + +import java.awt.*; +import java.awt.event.*; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.*; + +@SuppressWarnings("serial") +public class GraphPanel extends JPanel { + + // private int width = 800; + // private int heigth = 600; + private int padding = 25; + private int labelPadding = 25; + private Color lineColor = new Color(44, 102, 230, 180); + private Color pointColor = new Color(100, 100, 100, 180); + private Color gridColor = new Color(200, 200, 200, 200); + private static final Stroke GRAPH_STROKE = new BasicStroke(2f); + private int pointWidth = 4; + private int numberYDivisions = 10; + private static List scores; + + public GraphPanel() { + } + + @Override + protected void paintComponent(Graphics g) { + for (int i = 0; i < Companies.comp.size(); i++) { + if (Companies.comp.get(i).name.equals((String) comp.getSelectedItem())) { + scores = Companies.comp.get(i).sharevalue; + break; + } + } + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g; + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() - 1); + double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore()); + + List graphPoints = new ArrayList<>(); + for (int i = 0; i < scores.size(); i++) { + int x1, y1; + x1 = (int) (i * xScale + padding + labelPadding); + y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding); + graphPoints.add(new Point(x1, y1)); + } + + // draw white background + g2.setColor(Color.WHITE); + g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding); + g2.setColor(Color.BLACK); + + // create hatch marks and grid lines for y axis. + for (int i = 0; i < numberYDivisions + 1; i++) { + int x0 = padding + labelPadding; + int x1 = pointWidth + padding + labelPadding; + int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding); + int y1 = y0; + if (scores.size() > 0) { + g2.setColor(gridColor); + g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth() - padding, y1); + g2.setColor(Color.BLACK); + String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + ""; + FontMetrics metrics = g2.getFontMetrics(); + int labelWidth = metrics.stringWidth(yLabel); + g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3); + } + g2.drawLine(x0, y0, x1, y1); + } + + // and for x axis + for (int i = 0; i < scores.size(); i++) { + if (scores.size() > 1) { + int x0, x1, y0, y1; + x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding; + x1 = x0; + y0 = getHeight() - padding - labelPadding; + y1 = y0 - pointWidth; + if ((i % ((int) (((scores.size()) / 20.0)) + 1)) == 0) { + g2.setColor(gridColor); + g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding); + g2.setColor(Color.BLACK); + String xLabel = i / 2 + "m"; + FontMetrics metrics = g2.getFontMetrics(); + int labelWidth = metrics.stringWidth(xLabel); + if (i % 2 == 0) + g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3); + } + g2.drawLine(x0, y0, x1, y1); + } + } + + // create x and y axes + g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding); + g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding); + + Stroke oldStroke = g2.getStroke(); + g2.setColor(lineColor); + g2.setStroke(GRAPH_STROKE); + for (int i = 0; i < graphPoints.size() - 1; i++) { + int x1 = graphPoints.get(i).x; + int y1 = graphPoints.get(i).y; + int x2 = graphPoints.get(i + 1).x; + int y2 = graphPoints.get(i + 1).y; + g2.drawLine(x1, y1, x2, y2); + } + + g2.setStroke(oldStroke); + g2.setColor(pointColor); + for (int i = 0; i < graphPoints.size(); i++) { + if (i >= scores.size()) + g2.setColor(Color.RED); + int x = graphPoints.get(i).x - pointWidth / 2; + int y = graphPoints.get(i).y - pointWidth / 2; + int ovalW = pointWidth; + int ovalH = pointWidth; + g2.fillOval(x, y, ovalW, ovalH); + } + } + + // @Override + // public Dimension getPreferredSize() { + // return new Dimension(width, heigth); + // } + private double getMinScore() { + double minScore = Double.MAX_VALUE; + for (Company score1 : Companies.comp) { + for (Double score2 : score1.sharevalue) { + minScore = Math.min(minScore, score2); + } + } + return 0; + } + + private double getMaxScore() { + double maxScore = Double.MIN_VALUE; + for (Company score1 : Companies.comp) { + for (Double score2 : score1.sharevalue) { + maxScore = Math.max(maxScore, score2); + } + } + return maxScore; + } + + @SuppressWarnings("unchecked") + public void setScores() { + comp.removeAllItems(); + for (int i = 0; i < Companies.comp.size(); i++) + comp.addItem(Companies.comp.get(i).name); + try { + comp.setSelectedIndex(0); + } catch (Exception o) { + } + invalidate(); + this.repaint(); + } + + public List getScores() { + return scores; + } + + @SuppressWarnings("rawtypes") + static JComboBox comp; + static JPanel frame; + static GraphPanel mainPanel; + static Client client; + static Company comm = null; + @SuppressWarnings("rawtypes") + public static JPanel main(Client cl) { + client = cl; + comp = new JComboBox(); + comp.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + comp.setEnabled(false); + for (int i = 0; i < Companies.comp.size(); i++) { + if (Companies.comp.get(i).name.equals((String) comp.getSelectedItem())) { + comm = Companies.comp.get(i); + break; + } + } + if (comm.yy == 0) { + new Thread() { + public void run() { + List ret = client.getHistory(comm.name, comm.sharevalue.size()); + if (ret != null) { + if (ret.size() > 0) + comm.sharevalue = ret; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + mainPanel.repaint(); + comp.setEnabled(true); + comp.requestFocus(); + } + }); + } + } + }.start(); + comm.yy = 1; + } else { + mainPanel.repaint(); + comp.setEnabled(true); + comp.requestFocus(); + } + } + } + }); + comp.setLightWeightPopupEnabled(false); + mainPanel = new GraphPanel(); + mainPanel.setScores(); + // mainPanel.setPreferredSize(new Dimension(800, 500)); + // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame = new JPanel(); + frame.setLayout(new BorderLayout()); + frame.add(comp, BorderLayout.NORTH); + frame.add(mainPanel, BorderLayout.CENTER); + return frame; + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/client/HistogramPanel.java b/src/com/ayushmaanbhav/jstockmart/client/HistogramPanel.java new file mode 100644 index 0000000..c9748a3 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/HistogramPanel.java @@ -0,0 +1,111 @@ +package com.ayushmaanbhav.jstockmart.client; + +import java.awt.BorderLayout; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.Collections; +import java.util.List; + +import javax.swing.JComboBox; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +import com.ayushmaanbhav.jstockmart.utils.Histogram; +import com.ayushmaanbhav.jstockmart.utils.TrippleArrayList; + +public class HistogramPanel extends JPanel { + private static final long serialVersionUID = 1L; + + private TrippleArrayList scores; + + public HistogramPanel(TrippleArrayList scores) { + this.scores = scores; + } + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g; + Histogram.paintHistogram(g2, getHeight(), getWidth(), scores); + } + + public void setScores(TrippleArrayList arr) { + if (arr != null) { + if (arr.size() > 0) { + Collections.sort(arr); + arr.add(0, 0, 0.0, 0); + arr.add(0, 0.0, 0); + } + } + this.scores = arr; + } + + public TrippleArrayList getScores() { + return scores; + } + + @SuppressWarnings("unchecked") + public void updateComboBox(List score) { + comp.removeItemListener(item); + comp.removeAllItems(); + for (int i = 0; i < score.size(); i++) + comp.addItem(score.get(i).name); + try { + comp.setSelectedIndex(0); + updatePanel(); + } catch (Exception o) { + } + comp.addItemListener(item); + } + + void updatePanel() { + comp.setEnabled(false); + new Thread() { + public void run() { + TrippleArrayList arr = client.getCompanyStats((String) comp.getSelectedItem()); + if (arr != null) { + setScores(arr); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + mainPanel.repaint(); + comp.setEnabled(true); + comp.requestFocus(); + } + }); + } + } + }.start(); + } + + @SuppressWarnings("rawtypes") + static JComboBox comp; + static ItemListener item; + static JPanel frame; + static HistogramPanel mainPanel; + static Client client; + @SuppressWarnings("rawtypes") + public static JPanel main(Client cl) { + client = cl; + comp = new JComboBox(); + item = new ItemListener() { + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + mainPanel.updatePanel(); + } + } + }; + comp.addItemListener(item); + comp.setLightWeightPopupEnabled(false); + mainPanel = new HistogramPanel(new TrippleArrayList()); + // mainPanel.setScores(Companies.comp); + // mainPanel.setPreferredSize(new Dimension(800, 500)); + // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame = new JPanel(); + frame.setLayout(new BorderLayout()); + frame.add(comp, BorderLayout.NORTH); + frame.add(mainPanel, BorderLayout.CENTER); + return frame; + } +} diff --git a/src/com/ayushmaanbhav/jstockmart/client/LoginAction.java b/src/com/ayushmaanbhav/jstockmart/client/LoginAction.java new file mode 100644 index 0000000..b0abd5d --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/LoginAction.java @@ -0,0 +1,96 @@ +package com.ayushmaanbhav.jstockmart.client; +import javax.swing.*; + +import java.awt.event.*; + +import com.ayushmaanbhav.jstockmart.user.*; +import com.ayushmaanbhav.jstockmart.utils.*; + +import java.util.regex.Pattern; + +class LoginAction implements ActionListener { + HintTextField user; + HintPasswordField pass; + String domain; + Client client; + Main main; + public LoginAction(Main mm, HintTextField u, HintPasswordField p, String d, Client c) { + user = u; + pass = p; + domain = d; + client = c; + main = mm; + } + 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(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 us = user.getText(); + String pa = pass.getText(); + String rep = client.login(domain, us, pa); + if (rep == null) + return; + if (rep.equals("0")) { + final User user = (User) client.getUserDetails(us, pa); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + main.proceedLogin(user); + } + }); + } else if (rep.equals("1")) { + client.disconnect(); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + JOptionPane.showMessageDialog(null, "Server Replies: 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; + } else if (rep.equals("2")) { + client.disconnect(); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + JOptionPane.showMessageDialog(null, "Server Replies: 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; + } else if (rep.equals("11")) { + client.disconnect(); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + JOptionPane.showMessageDialog(null, "Server Replies: Sorry you have been banned from playing this game ! Please contact the admmin.", "Error:", JOptionPane.PLAIN_MESSAGE); + user.setText(""); + pass.setText(""); + } + }); + return; + } + } + }.start(); + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/client/Main.java b/src/com/ayushmaanbhav/jstockmart/client/Main.java new file mode 100644 index 0000000..0777d68 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/Main.java @@ -0,0 +1,667 @@ +package com.ayushmaanbhav.jstockmart.client; + +import javax.swing.*; +import javax.swing.table.*; + +import java.awt.*; +import java.awt.event.*; + +import javax.swing.border.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.plaf.basic.BasicInternalFrameUI; + +import com.ayushmaanbhav.jstockmart.user.*; +import com.ayushmaanbhav.jstockmart.utils.ButtonColumn; +import com.ayushmaanbhav.jstockmart.utils.HintPasswordField; +import com.ayushmaanbhav.jstockmart.utils.HintTextField; +import com.ayushmaanbhav.jstockmart.utils.LookAndFeel; + +import java.text.*; + +@SuppressWarnings("serial") +public class Main extends JFrame { + String dir, domain; + Image img, img2; + int maxWidth; + JPanel mpane; + Client client = null; + JInternalFrame internalFrame; + JPanel imgpane; + Graphics gd; + Main main = this; + HintTextField user; + HintPasswordField pass; + JPanel jp1, jp, jp2; + GridBagLayout gbll; + JLabel username; + GridBagConstraints gbc; + @SuppressWarnings("rawtypes") + JComboBox jcb; + ChatWindow chat; + RankingWindow rank; + UserDataChangedListener udcl; + DefaultTableModel dtm[]; + static JLabel mon[]; + ShareValuesChangeListener svcl; + static User ur = null; + final static String location = "com/ayushmaanbhav/jstockmart/data/"; + + public static void main(String args[]) { + Main m = new Main(); + m.init(args); + } + + int getWidth1() { + return getWidth() - 20; + } + + int getHeight1() { + return getHeight() - 20; + } + + protected void loadAppletParameters(String args[]) { + domain = args[0]; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private void createGUI() { + // Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Rectangle screenSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); + setSize(screenSize.width, screenSize.height); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + if (JOptionPane.showConfirmDialog(main, "Are you sure you want to quit?", "Confirm exit.", JOptionPane.OK_OPTION, 0, new ImageIcon("")) != 0) { + return; + } + stop(); + } + }); + LookAndFeel.set(); + gbll = new GridBagLayout(); + mpane = new JPanel(gbll); + mpane.setOpaque(false); + mpane.setBackground(Color.WHITE); + mpane.setBorder(new EtchedBorder()); + setGlassPane(mpane); + + jp = new JPanel(new BorderLayout()) { + @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); + } + }; + jp.setOpaque(false); + user = new HintTextField("Username"); + user.setColumns(18); + pass = new HintPasswordField("Password"); + pass.setColumns(18); + JButton login = new JButton("Login"); + login.setMnemonic(KeyEvent.VK_ENTER); + login.addActionListener(new LoginAction(main, user, pass, domain, client)); + username = new JLabel("Username"); + jcb = new JComboBox(new String[]{"Home", "Rules", "Logout"}); // help + // setting + jcb.setLightWeightPopupEnabled(false); + jcb.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + int sel = jcb.getSelectedIndex(); + if (sel == 1) { + try { + String url = "http://" + domain + "/rules/index.html"; + String os = System.getProperty("os.name").toLowerCase(); + Runtime rt = Runtime.getRuntime(); + + if (os.indexOf("win") >= 0) { + + // this doesn't support showing urls in the form of + // "page.html#nameLink" + rt.exec("rundll32 url.dll,FileProtocolHandler " + url); + + } else if (os.indexOf("mac") >= 0) { + + rt.exec("open " + url); + + } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) { + + // Do a best guess on unix until we get a platform + // independent way + // Build a list of browsers to try, in this order. + String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror", "netscape", "opera", "links", "lynx"}; + + // Build a command string which looks like + // "browser1 "url" || browser2 "url" ||..." + StringBuffer cmd = new StringBuffer(); + for (int i = 0; i < browsers.length; i++) + cmd.append((i == 0 ? "" : " || ") + browsers[i] + " \"" + url + "\" "); + + rt.exec(new String[]{"sh", "-c", cmd.toString()}); + } + // main.getAppletContext().showDocument(new URL(), + // "_blank"); + } catch (Exception ee) { + ee.printStackTrace(); + } + } else if (sel == 2) { + main.stop(); + // main.getAppletContext().showDocument(main.getDocumentBase(), + // "_self"); + } + } + }); + JLabel space = new JLabel(" "); + space.setOpaque(false); + JLabel space2 = new JLabel(" "); + space2.setOpaque(false); + + jp2 = new JPanel(new FlowLayout()); + jp2.setOpaque(false); + jp2.add(username); + jp2.add(jcb); + jp2.add(space2); + + jp1 = new JPanel(new FlowLayout()); + jp1.setOpaque(false); + jp1.add(user); + jp1.add(pass); + jp1.add(login); + jp1.add(space); + + JPanel developer = new JPanel(new GridBagLayout()); + JLabel tit = new JLabel(" StockMart "); + tit.setOpaque(false); + try { + tit.setFont(titleFont); + tit.setForeground(Color.gray.darker().darker().darker()); + } catch (Exception bb) { + bb.printStackTrace(); + } + GridBagConstraints gbc1 = new GridBagConstraints(); + gbc1.gridx = 0; + gbc1.gridy = 0; + gbc1.gridwidth = 1; + gbc1.gridheight = 1; + developer.add(tit, gbc1); + JLabel subtit = new JLabel(" Developed by: Ayush Jain (ayushmaanbhav1008@gmail.com), Contribute here: https://github.com/ayushmaanbhav/stockmart"); + subtit.setOpaque(false); + try { + subtit.setFont(calibri); + subtit.setForeground(Color.black); + } catch (Exception bb) { + bb.printStackTrace(); + } + gbc1.gridx = 0; + gbc1.gridy = 1; + gbc1.gridwidth = 2; + gbc1.gridheight = 1; + developer.add(subtit, gbc1); + developer.setOpaque(false); + jp.add(developer, BorderLayout.WEST); + jp.add(jp1, BorderLayout.EAST); + jp.setBorder(new BevelBorder(BevelBorder.RAISED)); + jp.setPreferredSize(new Dimension(mpane.getWidth(), 45)); + gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 0; + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.gridwidth = 8; + gbc.gridheight = 1; + gbc.ipadx = 0; + gbc.ipady = 0; + gbc.anchor = GridBagConstraints.PAGE_START; + gbc.weightx = 1.0; + gbc.weighty = 1.0; + mpane.add(jp, gbc); + + HintTextField regno = new HintTextField("Registration No."); + regno.setColumns(10); + // textField.setMaximumSize( .getPreferredSize() ); + HintTextField ruser = new HintTextField("Username"); + ruser.setColumns(10); + HintPasswordField rpass = new HintPasswordField("Password"); + rpass.setColumns(10); + JButton register = new JButton("Register"); + register.addActionListener(new RegisterAction(regno, ruser, rpass, domain, client)); + + JPanel regpane = 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); + } + }; + regpane.setOpaque(false); + regpane.setLayout(new BoxLayout(regpane, BoxLayout.PAGE_AXIS)); + regpane.setBorder(new EmptyBorder(10, 20, 10, 20)); // tlbr + regpane.add(Box.createRigidArea(new Dimension(0, 5))); + regpane.add(regno); + regpane.add(Box.createRigidArea(new Dimension(0, 5))); + regpane.add(ruser); + regpane.add(Box.createRigidArea(new Dimension(0, 5))); + regpane.add(rpass); + regpane.add(Box.createRigidArea(new Dimension(0, 5))); + regpane.add(register); + regpane.add(Box.createRigidArea(new Dimension(0, 5))); + + internalFrame = new JInternalFrame("Register:", false, false, false, false); + internalFrame.setContentPane(regpane); + internalFrame.pack(); + + unmovable(internalFrame); + + imgpane = new JPanel(); + imgpane.setOpaque(false); + JLabel imglabel = new JLabel(); + imglabel.setSize((int) (.384 * (double) getWidth1()), (int) (.79 * (double) getHeight1())); + imglabel.setOpaque(false); + imglabel.setIcon(new ImageIcon(img.getScaledInstance(imglabel.getWidth(), imglabel.getHeight(), Image.SCALE_SMOOTH))); + imgpane.add(imglabel); + + gbc.gridx = 6; + gbc.gridy = 3; + gbc.fill = GridBagConstraints.NONE; + gbc.gridwidth = 1; + gbc.gridheight = 3; + gbc.ipadx = 200; + gbc.ipady = 55; + gbc.anchor = GridBagConstraints.CENTER; + gbc.insets = new Insets(0, 0, 100, 0); + mpane.add(internalFrame, gbc); + + gbc.gridx = 1; + gbc.gridy = 2; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridwidth = 2; + gbc.gridheight = 7; + gbc.ipadx = 0; + gbc.ipady = 0; + gbc.insets = new Insets(0, 10, 30, 0); + mpane.add(imgpane, gbc); + + tester = new BackgroundAnimation(); + JPanel anipane = new JPanel(); + anipane.setLayout(new BoxLayout(anipane, BoxLayout.Y_AXIS)); + anipane.add(Box.createRigidArea(new Dimension(0, 45))); + anipane.add(tester); + + rb = new RibbonPane(140, client); + rb.setPreferredSize(new Dimension(mpane.getWidth(), 28)); + anipane.add(rb); + setContentPane(anipane); + mpane.setVisible(true); + internalFrame.setVisible(true); + try { + internalFrame.setSelected(true); + } catch (Exception v) { + }; + rb.startAnimation(); + } + RibbonPane rb; + BackgroundAnimation tester; + + void unmovable(JInternalFrame jif) { + BasicInternalFrameUI ui = (BasicInternalFrameUI) jif.getUI(); + Component north = ui.getNorthPane(); + MouseMotionListener[] actions = (MouseMotionListener[]) north.getListeners(MouseMotionListener.class); + for (int i = 0; i < actions.length; i++) + north.removeMouseMotionListener(actions[i]); + } + + Font titleFont = null; + Font tempus = null; + Font arial = null; + Font calibri = null; + public void init(String args[]) { + loadAppletParameters(args); + try { + calibri = new Font("Calibri", Font.PLAIN, 11); + arial = new Font("Arial", Font.BOLD, 18); + tempus = new Font("Tempus Sans ITC", Font.BOLD, 20); + titleFont = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getClassLoader().getResourceAsStream(location + "burnstown-dam.regular.ttf")).deriveFont(Font.PLAIN, 25); + img = new ImageIcon(this.getClass().getClassLoader().getResource(location + "logo.png")).getImage(); + img2 = new ImageIcon(this.getClass().getClassLoader().getResource(location + "logo2.png")).getImage(); + } catch (Exception m) { + m.printStackTrace(); + } + client = new Client(this, null); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + createGUI(); + main.setVisible(true); + } + }); + } catch (Exception e) { + e.printStackTrace(); + System.err.println("createGUI didn't successfully complete"); + } + } + + static DecimalFormat twoDForm = new DecimalFormat("#.##"); + JTable table[]; + JPanel add; + NewsPane news; + JLabel sensex, spon, time; + JPanel userpane[]; + static JLabel imglabel2 = null; + Cashier cash; + final String[] columnNames1 = {"SrNo.", "Company", "Quantity", "C.M.P.", "Mkt Value", "Gain/Loss", "Abs Return(%)", "Action"}; + final String[] columnNames2 = {"SrNo.", "Company", "C.M.P.", "% Change", "Low", "High", "Action"}; + final String[] columnNames3 = {"SrNo.", "Company", "Type", "Price Limit", "Quantity (Limit)", "Status", "Action"}; + Action delete; + static JTabbedPane jtp; + void proceedLogin(User user) { + tester.stopAnimation(); + ur = user; + username.setFont(tempus); + username.setText(user.getName() + " "); + mpane.remove(internalFrame); + jp.remove(jp1); + mpane.remove(imgpane); + mpane.repaint(); + + news = new NewsPane(); + news.startAnimation(); + JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new RankingWindow(client), new ChatWindow(user, client)); + jsp.setPreferredSize(new Dimension(getWidth1() / 4, getHeight1() - 120)); + gbc.gridx = 6; + gbc.gridy = 1; + gbc.fill = GridBagConstraints.VERTICAL; // VERTICAL + gbc.gridwidth = 2; + gbc.gridheight = 9; + gbc.ipadx = 0; + gbc.ipady = 0; + gbc.insets = new Insets(0, 0, 40, 20); + gbc.anchor = GridBagConstraints.FIRST_LINE_END; + gbc.weightx = 1.0; + gbc.weighty = 1.0; + mpane.add(jsp, gbc); + jp.add(jp2, BorderLayout.EAST); + jsp.setDividerLocation((getHeight1() - 120) / 2); + JPanel add = new JPanel(); + // add.setOpaque(false); + add.setPreferredSize(new Dimension((getWidth1() * 5) / 8, (getHeight1() * 17) / 100)); + add.setMaximumSize(new Dimension((getWidth1() * 5) / 8, (getHeight1() * 17) / 100)); + add.setLayout(new BorderLayout()); + add.add(news, BorderLayout.SOUTH); + add.setBorder(new BevelBorder(BevelBorder.RAISED)); + imglabel2 = new JLabel(); + imglabel2.setSize((int) add.getPreferredSize().getWidth() + 50, (int) add.getPreferredSize().getHeight() - 25); + imglabel2.setOpaque(false); + imglabel2.setIcon(new ImageIcon(img2.getScaledInstance(imglabel2.getWidth(), imglabel2.getHeight(), Image.SCALE_SMOOTH))); + imglabel2.setFont(arial); + imglabel2.setText("
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); + + jtp = new JTabbedPane(); + jtp.setPreferredSize(new Dimension((getWidth1() * 5) / 8, (getHeight1() * 6) / 10)); + userpane = new JPanel[5]; + + 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 == 6) + 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(tempus); + userpane[i].add(mon[i], BorderLayout.SOUTH); + } + + userpane[3] = GraphPanel.main(client); + userpane[4] = HistogramPanel.main(client); + + 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 = "Cancelled"; + 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("Your Holdings", userpane[0]); + jtp.add("Watchlist", userpane[1]); + jtp.add("Your Orders", userpane[2]); + jtp.add("Company Overview", userpane[3]); + + jtp.add("Order Stats", userpane[4]); + jtp.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + String temp = null; + if (jtp.getSelectedIndex() == 4) { + temp = (String) HistogramPanel.comp.getSelectedItem(); + } + final String company = temp; + new Thread() { + public void run() { + client.getSendCompanyStatsPeriodically(company); + } + }.start(); + } + }); + + jtp.setEnabledAt(3, false); + jtp.setEnabledAt(4, false); + 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()) + " Rank: " + RankingClient.rank); + 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.size(); i++) { + data[i] = new Object[]{Integer.toString(i + 1), ss.get(i).company, ss.get(i).qty, twoDForm.format(Companies.getCompanyWithName(ss.get(i).company).mktvalue), twoDForm.format(ss.get(i).qty * Companies.getCompanyWithName(ss.get(i).company).mktvalue), twoDForm.format(ss.get(i).qty * Companies.getCompanyWithName(ss.get(i).company).mktvalue - ss.get(i).qty * ss.get(i).cost), twoDForm.format(((Companies.getCompanyWithName(ss.get(i).company).mktvalue - ss.get(i).cost) * 100) / ss.get(i).cost), "Sell"}; + } + dtm[0].setDataVector(data, columnNames1); + new ButtonColumn(table[0], delete, 7); + } catch (Exception mm) { + mm.printStackTrace(); + } + try { + Object data[][] = new Object[Companies.comp.size()][7]; + for (int i = 0; i < Companies.comp.size(); i++) { + data[i] = new Object[]{Integer.toString(i + 1), Companies.comp.get(i).name, twoDForm.format(Companies.comp.get(i).mktvalue), twoDForm.format((Companies.comp.get(i).mktvalue - Companies.comp.get(i).inivalue) * 100 / Companies.comp.get(i).inivalue), twoDForm.format(Companies.comp.get(i).low), twoDForm.format(Companies.comp.get(i).high), "Buy"}; + } + dtm[1].setDataVector(data, columnNames2); + new ButtonColumn(table[1], delete, 6); + table[1].getColumnModel().getColumn(3).setCellRenderer(dtr); + table[1].repaint(); + } catch (Exception mm) { + mm.printStackTrace(); + } + try { + java.util.List ss = ur.getPendingShares(); + Object data[][] = new Object[ss.size()][7]; + for (int i = 0; i < ss.size(); i++) { + String type = "", costLimit = "Not Applicable"; + switch (ss.get(i).type) { + case 0 : + type = "Market Buy Order"; + break; + case 1 : + type = "Market Sell Order"; + break; + case 2 : + type = "Limit Buy Order"; + costLimit = String.valueOf(ss.get(i).cost_limit); + break; + case 3 : + type = "Limit Sell Order"; + costLimit = String.valueOf(ss.get(i).cost_limit); + break; + } + data[i] = new Object[]{Integer.toString(i + 1), ss.get(i).company, type, costLimit, ss.get(i).qty_limit, ss.get(i).status, "Cancel"}; + } + dtm[2].setDataVector(data, columnNames3); + new ButtonColumn(table[2], delete, 6); + } catch (Exception mm) { + mm.printStackTrace(); + } + } + public void stop() { + try { + if (client != null) + client.disconnect(); + } finally { + System.exit(0); + } + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/client/NewsPane.java b/src/com/ayushmaanbhav/jstockmart/client/NewsPane.java new file mode 100644 index 0000000..649cc41 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/NewsPane.java @@ -0,0 +1,56 @@ +package com.ayushmaanbhav.jstockmart.client; +import javax.swing.*; + +import java.awt.event.*; +import java.awt.*; +@SuppressWarnings("serial") +class NewsPane extends JPanel implements ActionListener { + static StringBuffer temp; + StringBuffer sb; + Timer t; + int loop; + JLabel l; + public NewsPane() { + sb = new StringBuffer(""); + temp = new StringBuffer(""); + t = new Timer(140, this); + setOpaque(false); + setLayout(new BorderLayout()); + l = new JLabel("
News : 
"); + l.setFont(new Font("Calibri", 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/com/ayushmaanbhav/jstockmart/client/RankingClient.java b/src/com/ayushmaanbhav/jstockmart/client/RankingClient.java new file mode 100644 index 0000000..a593a98 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/RankingClient.java @@ -0,0 +1,54 @@ +package com.ayushmaanbhav.jstockmart.client; + +import javax.swing.*; + +public class RankingClient extends Thread { + JTextPane jta; + JScrollPane jspp; + static String rank = ""; + public RankingClient(JTextPane ja, JScrollPane o) { + jta = ja; + jspp = o; + rank = ""; + } + public void run(String hh) { + try { + // StringBuffer fin=new StringBuffer(" "); + String str[] = hh.trim().split(":"); + String f = ""; + int uu = 0; + for (int i = 0; i < str.length; i++) { + int iii = str[i].indexOf('-'); + f += (i + 1) + ") " + str[i].substring(0, iii) + " -> " + str[i].substring(iii+1) + "\n"; + if (uu == 0 && str[i].indexOf(Main.ur.getName()) != -1) { + uu = 1; + rank = (i + 1) + " Score: " + str[i].substring(iii + 1); + } + } + final String h = f; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + try { + jta.setText(h); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + jspp.getVerticalScrollBar().setValue(0); + } + }); + try { + for (int i = 0; i < 3; i++) { + Main.mon[i].setText("Avail. Cash : " + Main.twoDForm.format(Main.ur.getCurrentMoney()) + " Rank: " + rank); + Main.mon[i].repaint(); + } + } catch (Exception mm) { + mm.printStackTrace(); + } + } catch (Exception e) { + } + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/com/ayushmaanbhav/jstockmart/client/RankingWindow.java b/src/com/ayushmaanbhav/jstockmart/client/RankingWindow.java new file mode 100644 index 0000000..1876438 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/RankingWindow.java @@ -0,0 +1,29 @@ +package com.ayushmaanbhav.jstockmart.client; +import javax.swing.*; + +import java.awt.*; + +import javax.swing.text.*; + +@SuppressWarnings("serial") +class RankingWindow extends JPanel { + JTextPane jta; + JScrollPane jsp; + 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_LEFT); + doc.setParagraphAttributes(0, doc.getLength(), center, false); + jta.setFont(new Font("Calibri", Font.PLAIN, 13)); + jta.setEditable(false); + jta.setForeground(Color.red.darker()); + 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, jsp); + cc.rc = cser; + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/client/Receiver.java b/src/com/ayushmaanbhav/jstockmart/client/Receiver.java new file mode 100644 index 0000000..4779a42 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/Receiver.java @@ -0,0 +1,139 @@ +package com.ayushmaanbhav.jstockmart.client; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +import org.thavam.util.concurrent.BlockingHashMap; +import org.thavam.util.concurrent.BlockingMap; + +import com.ayushmaanbhav.jstockmart.user.Commands; +import com.ayushmaanbhav.jstockmart.user.User; +import com.ayushmaanbhav.jstockmart.utils.TrippleArrayList; + +public class Receiver extends Thread { + @SuppressWarnings("rawtypes") + BlockingMap rev; + Client client; + + @SuppressWarnings("rawtypes") + public Receiver(Client client) { + this.client = client; + rev = new BlockingHashMap(); + setPriority(MAX_PRIORITY); + } + + @SuppressWarnings("unchecked") + public void run() { + while (client.connected) { + try { + Object obj = client.in.readObject(); + if (Client.testing) + System.out.println("Got Obj: " + obj.toString()); + if (obj instanceof String) { + String recString = (String) obj; + if (recString.equals(Commands.UNKNOWN_COMMAND)) { + client.connected = false; + client.in.close(); + client.out.close(); + client.socket.close(); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + Cashier.closee = true; + JOptionPane.showMessageDialog(null, "Disconnected from server. Please Restart", "Error:", JOptionPane.PLAIN_MESSAGE); + try { + client.m.stop(); + } catch (Exception w) { + } + } + }); + } else if (recString.equals(Commands.SERVER_NOT_RUNNING)) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + Cashier.closee = true; + JOptionPane.showMessageDialog(null, "Server Not Running.", "Error:", JOptionPane.PLAIN_MESSAGE); + } + }); + } else { + String command[] = recString.split("::"); + if (command[0].equals(Commands.BROADCAST)) { + if (client.bc != null) + client.bc.run(command[1]); + } else if (command[0].equals(Commands.CHAT_AND_NEWS)) { + if (client.cc != null) + client.cc.run(command[1]); + } else if (command[0].equals(Commands.FINAL_RANKINGS)) { + String hhh = command[1]; + final JDialog jd = new JDialog(); + jd.setUndecorated(false); + JPanel pan = new JPanel(new BorderLayout()); + JLabel ppp = new JLabel(); + ppp.setFont(new Font("Calibri", Font.BOLD, 20)); + ppp.setText("
Thanks for playing !!!
1st: " + hhh.split(":")[0] + "
2nd: " + hhh.split(":")[1] + "
3rd: " + hhh.split(":")[2] + "
"); + pan.add(ppp, BorderLayout.CENTER); + JButton ok = new JButton("Ok"); + ok.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + jd.setVisible(false); + try { + client.m.stop(); + } catch (Exception w) { + } + } + }); + pan.add(ok, BorderLayout.SOUTH); + jd.setContentPane(pan); + jd.setModalityType(JDialog.ModalityType.APPLICATION_MODAL); + jd.pack(); + jd.setLocationRelativeTo(null); + jd.setVisible(true); + } else if (command[0].equals(Commands.RANKS)) { + if (client.rc != null) + client.rc.run(command[1]); + } else { + try { + int cmdID = Integer.parseInt(recString); + obj = client.in.readObject(); + rev.offer(cmdID, obj); + } catch (Exception ppp) { + ppp.printStackTrace(); + if (Client.testing) + System.out.println("Shit: " + recString + " : " + Thread.currentThread()); + } + } + } + } else if (obj instanceof User) { + try { + Main.ur.changeData((User) obj); + } catch (Exception w) { + try { + client.maain.ur.changeData((User) obj); + } catch (Exception ppp) { + ppp.printStackTrace(); + } + } + } else if (obj instanceof TrippleArrayList) { + HistogramPanel.mainPanel.setScores((TrippleArrayList) obj); + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + HistogramPanel.mainPanel.repaint(); + } + }); + } + } catch (Exception m) { + m.printStackTrace(); + client.disconnect(); + break; + } + } + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/client/RegisterAction.java b/src/com/ayushmaanbhav/jstockmart/client/RegisterAction.java new file mode 100644 index 0000000..d07885a --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/RegisterAction.java @@ -0,0 +1,96 @@ +package com.ayushmaanbhav.jstockmart.client; +import javax.swing.*; + +import com.ayushmaanbhav.jstockmart.utils.HintPasswordField; +import com.ayushmaanbhav.jstockmart.utils.HintTextField; + +import java.awt.event.*; +import java.util.regex.Pattern; + +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/com/ayushmaanbhav/jstockmart/client/RibbonPane.java b/src/com/ayushmaanbhav/jstockmart/client/RibbonPane.java new file mode 100644 index 0000000..99396d1 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/client/RibbonPane.java @@ -0,0 +1,63 @@ +package com.ayushmaanbhav.jstockmart.client; +import javax.swing.*; + +import java.awt.event.*; +import java.awt.*; +@SuppressWarnings("serial") +class RibbonPane extends JPanel implements ActionListener { + StringBuffer sb, temp; + BroadcastClient bc; + Timer t; + int loop; + JLabel l; + final String wel = " StockMart - Disable proxy in java in control panel and in your browser too.... Register with your AnweshaID or you will be disqualified..... "; + 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); + setDoubleBuffered(true); + } + 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;
+			}
+		} else {
+			while (sb.length() <= 260)
+				sb.append(' ');
+		}
+	}
+	void addShareValuesChangeListener(ShareValuesChangeListener svcl) {
+		bc.svcl = svcl;
+	}
+}
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/client/ShareValuesChangeListener.java b/src/com/ayushmaanbhav/jstockmart/client/ShareValuesChangeListener.java
new file mode 100644
index 0000000..322964e
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/client/ShareValuesChangeListener.java
@@ -0,0 +1,5 @@
+package com.ayushmaanbhav.jstockmart.client;
+
+interface ShareValuesChangeListener {
+	public void valuesChanged();
+}
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/client/Test.java b/src/com/ayushmaanbhav/jstockmart/client/Test.java
new file mode 100644
index 0000000..457ea58
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/client/Test.java
@@ -0,0 +1,117 @@
+package com.ayushmaanbhav.jstockmart.client;
+import java.io.*;
+
+import com.ayushmaanbhav.jstockmart.user.*;
+class Test {
+	int i;
+	BufferedWriter bw;
+	public void main(final String d, final int n) throws IOException {
+		// bw = new BufferedWriter(new FileWriter("test_client_log.txt"));
+		for (i = 0; i < n; i++) {
+			new TestMain() {
+				String regn, un, pass;
+				public void run() {
+					try {
+						// Main m = new Main();
+						// m.domain = d;
+						Client client = new Client(null, this);
+						regn = "robotregno" + (int) (Math.random() * 10000);
+						un = "robotuser" + (int) (Math.random() * 10000);
+						pass = "robotpass" + (int) (Math.random() * 10000);
+						if (!client.register(d, regn, un, pass).equals("1"))
+							return;
+						if (!client.login(d, un, pass).equals("0"))
+							return;
+						ur = (User) client.getUserDetails(un, pass);
+						/*
+						 * m.udcl=new UserDataChangedListener(){ public void
+						 * userDataChanged(User user) { //updateTables(); } };
+						 * m.svcl=new ShareValuesChangeListener(){ public void
+						 * valuesChanged() { //updateTables(); } };
+						 */
+						// m.cash=new Cashier(client,m.ur);
+						client.bc = new BroadcastClient(new StringBuffer());
+						client.rc = null;
+						client.cc = null;
+						while (true) {
+							try {
+								double r = Math.random();
+								// bw.write(un+" "+r);
+								if (r >= 0.0 && r < 0.4375 && Companies.comp.size() > 0) {
+									// bw.write(un+" buying");
+									int id = (int) (Math.random() * Companies.comp.size());
+									Company c = Companies.getCompanyWithId(id);
+									double money = Math.random() * ur.getCurrentMoney();
+									int noofshares = (int) (money / c.mktvalue);
+									if (noofshares > 0) {
+										client.placeOrder(ur, "buy", c, 100, noofshares, c.id);
+										/*
+										 * bw.write(un+" placing buy order: "+c.name
+										 * +noofshares+"\n"); bw.flush();
+										 */
+									}
+								} else if (r >= 0.4375 && r < 0.875 && ur.getCurrentShares().size() > 0) {
+									// bw.write(un+" selling");
+									int id = (int) (Math.random() * ur.getCurrentShares().size());
+									Company c = Companies.getCompanyWithName(ur.getCurrentShares().get(id).company);
+									int noofshares = (int) (Math.random() * ur.getCurrentShares().get(id).qty);
+									if (noofshares > 0) {
+										client.placeOrder(ur, "sell", c, 100, noofshares, ur.getCurrentShares().get(id).id);
+										/*
+										 * bw.write(un+" placing sell order: "+c.
+										 * name+noofshares+"\n"); bw.flush();
+										 */
+									}
+								} else if (r >= 0.875 && r < 0.9 && ur.getPendingShares().size() > 0) {
+									// bw.write(un+" canceling");
+									int id = (int) (Math.random() * ur.getPendingShares().size());
+									client.cancelShares(un, pass, ur.getPendingShares().get(id).id, ur.getPendingShares().get(id).sellid);
+									/*
+									 * bw.write(un+" corder placed"+"\n");
+									 * bw.flush();
+									 */
+								} else if (r >= 0.9 && r < 0.925) {
+									// bw.write(un+" chatting");
+									client.sendChat("hi " + pp++, un, pass);
+									/*
+									 * bw.write(un+" chatted"+"\n"); bw.flush();
+									 */
+								} else {
+									/*
+									 * bw.write(un+" idle"+"\n"); bw.flush();
+									 */
+								}
+								try {
+									Thread.sleep((long) (Math.random() * 3000));
+								} catch (Exception r2) {
+								}
+							} catch (Exception r1) {
+								r1.printStackTrace();
+							}
+						}
+					} catch (Exception r4) {
+						try {
+							/*
+							 * bw.write(un+" : "+r4.getMessage()+"\n");
+							 * bw.flush();
+							 */
+						} catch (Exception jjj) {
+						}
+					}
+				}
+				int pp = 0;
+			}.start();
+			try {
+				Thread.sleep(100);
+			} catch (Exception r2) {
+			}
+		}
+	}
+	public static void main(String args[]) {
+		try {
+			Test t = new Test();
+			t.main("127.0.0.1", 100);
+		} catch (IOException ff) {
+		}
+	}
+}
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/client/TestMain.java b/src/com/ayushmaanbhav/jstockmart/client/TestMain.java
new file mode 100644
index 0000000..8d0b8c2
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/client/TestMain.java
@@ -0,0 +1,5 @@
+package com.ayushmaanbhav.jstockmart.client;
+import com.ayushmaanbhav.jstockmart.user.*;
+public abstract class TestMain extends Thread {
+	User ur;
+}
diff --git a/src/com/ayushmaanbhav/jstockmart/data/burnstown-dam.regular.ttf b/src/com/ayushmaanbhav/jstockmart/data/burnstown-dam.regular.ttf
new file mode 100644
index 0000000..4bd4086
Binary files /dev/null and b/src/com/ayushmaanbhav/jstockmart/data/burnstown-dam.regular.ttf differ
diff --git a/src/com/ayushmaanbhav/jstockmart/data/companies.txt b/src/com/ayushmaanbhav/jstockmart/data/companies.txt
new file mode 100644
index 0000000..0880383
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/data/companies.txt
@@ -0,0 +1,21 @@
+Reliance:1000:2000:0.00045:0.03
+Microsoft:2000:2000:0.00045:0.3
+Maruti:650:2000:0.00045:0.3
+Hero:1200:2000:0.00045:0.3
+N.I.C.:500:3000:0.00045:0.3
+Honda:890:2000:0.00045:0.3
+BUDCo.:770:2000:0.00045:0.3
+Bank of Baroda:300:3000:0.00045:0.3
+Tata Docomo:560:3000:0.00045:0.3
+Air India:896:2000:0.00045:0.3
+Pepsi:234:3000:0.00045:0.3
+Tata Tea:465:3000:0.00045:0.3
+Samsung:723:2000:0.00045:0.3
+Yamaha:452:3000:0.00045:0.3
+Punjab National Bank:489:3000:0.00045:0.3
+BSNL:654:2000:0.00045:0.3
+Asian Paints:720:2000:0.00045:0.3
+Dell:213:3500:0.00045:0.3
+Sony:754:2000:0.00045:0.3
+LG:328:3500:0.00045:0.3
+Whirlpool:578:2500:0.00045:0.3
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/data/logo.png b/src/com/ayushmaanbhav/jstockmart/data/logo.png
new file mode 100644
index 0000000..bc1f6f6
Binary files /dev/null and b/src/com/ayushmaanbhav/jstockmart/data/logo.png differ
diff --git a/src/com/ayushmaanbhav/jstockmart/data/logo2.png b/src/com/ayushmaanbhav/jstockmart/data/logo2.png
new file mode 100644
index 0000000..f2e0bf5
Binary files /dev/null and b/src/com/ayushmaanbhav/jstockmart/data/logo2.png differ
diff --git a/src/client/logo2.png b/src/com/ayushmaanbhav/jstockmart/data/logo3.png
similarity index 100%
rename from src/client/logo2.png
rename to src/com/ayushmaanbhav/jstockmart/data/logo3.png
diff --git a/src/client/logo.png b/src/com/ayushmaanbhav/jstockmart/data/logo4.png
similarity index 100%
rename from src/client/logo.png
rename to src/com/ayushmaanbhav/jstockmart/data/logo4.png
diff --git a/src/com/ayushmaanbhav/jstockmart/data/manifest.txt b/src/com/ayushmaanbhav/jstockmart/data/manifest.txt
new file mode 100644
index 0000000..6ca4ffc
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/data/manifest.txt
@@ -0,0 +1,2 @@
+Main-Class: server.StockMart
+Created-By: Ayush Jain
diff --git a/src/com/ayushmaanbhav/jstockmart/data/manifest2.txt b/src/com/ayushmaanbhav/jstockmart/data/manifest2.txt
new file mode 100644
index 0000000..aa518b7
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/data/manifest2.txt
@@ -0,0 +1,7 @@
+Application-Name: StockMart
+Main-Class: client.Main
+Permissions: all-permissions
+Codebase: *
+Application-Library-Allowable-Codebase: *
+Caller-Allowable-Codebase: *
+Created-By: Ayush Jain
diff --git a/src/com/ayushmaanbhav/jstockmart/data/money.txt b/src/com/ayushmaanbhav/jstockmart/data/money.txt
new file mode 100644
index 0000000..483fb82
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/data/money.txt
@@ -0,0 +1 @@
+100000
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/data/reg.txt b/src/com/ayushmaanbhav/jstockmart/data/reg.txt
new file mode 100644
index 0000000..2518ef4
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/data/reg.txt
@@ -0,0 +1,75 @@
+1101cs10
+1201ee06
+1301cs23
+1301me24
+1301ee40
+1301ee27
+1301ee41
+1301ee19
+1301cs42
+1301ce10
+1101ee27
+1101ee12
+1301me18
+1301cs11
+1201me08
+1201cs37
+1301me12
+1301cs20
+1201me02
+1301ee17
+1301cs43
+1301ee18
+1301me16
+1301me38
+1301ce12
+1301cs46
+1301ee39
+1301ee37
+1301cs31
+1301ee45
+1301ce17
+1101ee10
+1301me08
+1101cs24
+1301ee22
+1101cs39
+1001cs22
+1001ee34
+1101cs02
+1301cs13
+1301cs19
+1301me06
+1301cs14
+1101cs19
+1001cs15
+1301ee01
+1001cs19
+1301me01
+1301me37
+1001cs07
+1101cs26
+1101me05
+1301cs41
+1301ee20
+1101ee11
+1301ce07
+1301me04
+1301me39
+1101cs18
+1301ce21
+1301ch05
+1101cs29
+1301ch12
+1201me17
+1201me24
+1301ch06
+1201me20
+1201me16
+1101ee09
+1101ee07
+1101ee26
+1101cs38
+1101cs39
+1311ee01
+1101cs05
diff --git a/src/com/ayushmaanbhav/jstockmart/server/BroadcastServer.java b/src/com/ayushmaanbhav/jstockmart/server/BroadcastServer.java
new file mode 100644
index 0000000..625fa19
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/BroadcastServer.java
@@ -0,0 +1,82 @@
+package com.ayushmaanbhav.jstockmart.server;
+import java.io.*;
+import java.util.*;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.text.*;
+
+import com.ayushmaanbhav.jstockmart.user.Commands;
+
+public class BroadcastServer extends Thread {
+	@SuppressWarnings("unused")
+	private long SECONDS = 30000;
+	List com;
+	int close;
+	int id;
+	BlockingQueue queue;
+	Server server;
+	static boolean sendFullDetails;
+
+	public BroadcastServer(String name, List c, Server s) throws IOException {
+		super(name);
+		setPriority(9);
+		com = c;
+		server = s;
+		queue = new LinkedBlockingQueue();
+	}
+
+	static DecimalFormat twoDForm = new DecimalFormat("#.##");
+	public void run() {
+		sendFullDetails = true;
+		close = 0;
+		while (true) {
+			if (close == 1)
+				break;
+			try {
+				id = queue.take();
+				int temp = (int) (StockMart.totTime * 60 - (new Date().getTime() - StockMart.startDate.getTime()) / 1000);
+				int hrs = temp / 3600;
+				int mins = ((temp / 60) % 60);
+				StringBuffer dString = new StringBuffer();
+				dString.append(Commands.BROADCAST);
+				dString.append("::");
+				dString.append(String.valueOf(id++));
+				dString.append("#");
+				dString.append(hrs);
+				dString.append(":");
+				dString.append(mins / 10 == 0 ? "0" : "");
+				dString.append(mins);
+				dString.append(";");
+				dString.append(twoDForm.format(ShareMarket.sensex));
+				dString.append("=");
+				for (int i = 0; i < com.size(); i++) {
+					Company c = com.get(i);
+					// if (!c.bankrupt) {
+					dString.append(String.valueOf(i));
+					dString.append(":");
+					dString.append(c.name);
+					dString.append(":");
+					dString.append(String.valueOf(c.sharevalue.get(c.sharevalue.size() - 1)));
+					dString.append(":");
+					dString.append(String.valueOf(c.sharevalue.get(0)));
+					dString.append(":");
+					dString.append(String.valueOf(c.getHighest()));
+					dString.append(":");
+					dString.append(String.valueOf(c.getLowest()));
+					dString.append(":");
+					dString.append(String.valueOf(c.price_precision));
+					dString.append(";");
+					// }
+				}
+				sendFullDetails = false;
+				server.sendMulti(dString.toString(), 5);
+				server.sendPeriodicStats(5);
+				/*
+				 * try { sleep(SECONDS); } catch (InterruptedException e) { }
+				 */
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		}
+	}
+}
diff --git a/src/com/ayushmaanbhav/jstockmart/server/ChatServer.java b/src/com/ayushmaanbhav/jstockmart/server/ChatServer.java
new file mode 100644
index 0000000..9be2236
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/ChatServer.java
@@ -0,0 +1,53 @@
+package com.ayushmaanbhav.jstockmart.server;
+import java.io.*;
+import java.util.*;
+
+import com.ayushmaanbhav.jstockmart.user.Commands;
+
+public class ChatServer extends Thread {
+	Server server;
+	StringBuffer chaat;
+	BufferedWriter bw;
+	public ChatServer(Server s) throws IOException {
+		setPriority(Thread.MIN_PRIORITY);
+		server = s;
+		chaat = new StringBuffer();
+		try {
+			bw = new BufferedWriter(new FileWriter("appdata/chat.txt"));
+		} catch (Exception mm) {
+		}
+	}
+
+	public void run() {
+		while (true) {
+			try {
+				StringBuffer toSend = new StringBuffer();
+				toSend.append(Commands.CHAT_AND_NEWS);
+				toSend.append("::");
+				if (StockMart.newsfeed.equals(""))
+					toSend.append("-1");
+				else
+					toSend.append(StockMart.newsfeed);
+				toSend.append(";");
+				if (chaat.toString().equals(""))
+					toSend.append("-1");
+				else
+					toSend.append(chaat);
+				chaat.setLength(0);
+				server.sendMulti(toSend.toString(), Thread.MIN_PRIORITY);
+				try {
+					bw.write(new Date().toString() + ":" + toSend + "\n");
+					bw.flush();
+				} catch (Exception mm) {
+					mm.printStackTrace();
+				}
+				try {
+					sleep(30000);
+				} catch (InterruptedException e1) {
+				}
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		}
+	}
+}
diff --git a/src/com/ayushmaanbhav/jstockmart/server/Company.java b/src/com/ayushmaanbhav/jstockmart/server/Company.java
new file mode 100644
index 0000000..4912b39
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/Company.java
@@ -0,0 +1,75 @@
+package com.ayushmaanbhav.jstockmart.server;
+import java.util.*;
+import java.io.*;
+class Company {
+	String name;
+	volatile ArrayList sharevalue, futurevalues;
+	volatile int sharessold, nooflimitbidsmatched, totalshares, tsharessold, sharessoldpast;
+	volatile Date d;
+	volatile double perchange, W, rate, vol, highest, lowest, phighest, plowest, price_precision, pprice_precision;
+	boolean bankrupt;
+	BufferedWriter bw;
+
+	@SuppressWarnings("serial")
+	public Company(String n, List l, int sd, int tot, double rate1, double vol1) {
+		rate = rate1;
+		vol = vol1;
+		name = n;
+		highest = 0;
+		phighest = plowest = -1;
+		lowest = Integer.MAX_VALUE;
+		sharevalue = new ArrayList() {
+			@Override
+			public boolean add(Double value) {
+				if (lowest > value) {
+					plowest = lowest;
+					lowest = value;
+				}
+				if (highest < value) {
+					phighest = highest;
+					highest = value;
+				}
+				return super.add(value);
+			}
+		};
+		sharevalue.add(l.get(0));
+		futurevalues = new ArrayList();
+		sharessold = sd;
+		nooflimitbidsmatched = 0;
+		totalshares = tot;
+		tsharessold = 0;
+		bankrupt = false;
+		W = 0;
+		pprice_precision = 0;
+		price_precision = MatchingEngine.getHighestPrecision(this);
+		try {
+			bw = new BufferedWriter(new FileWriter("appdata/companydata/" + name + ".txt"));
+		} catch (Exception mm) {
+		}
+	}
+	/*
+	 * public Company(String n) { name=n; sharevalue=new ArrayList();
+	 * sharessold=0; }
+	 */
+	public void updateFile() {
+		try {
+			bw.write(d.toString() + ":" + name + ":" + sharevalue.get(sharevalue.size() - 1) + ":" + perchange + ":" + sharessoldpast + ":" + tsharessold + ":" + totalshares + "\n");
+			bw.flush();
+		} catch (Exception mm) {
+			mm.printStackTrace();
+		}
+	}
+
+	public double getHighest() {
+		return highest;
+	}
+
+	public double getLowest() {
+		return lowest;
+	}
+	
+	public void setPricePrecision(double price_precision) {
+		this.pprice_precision = this.price_precision;
+		this.price_precision = price_precision;
+	}
+}
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/server/GraphPanel.java b/src/com/ayushmaanbhav/jstockmart/server/GraphPanel.java
new file mode 100644
index 0000000..2ba91c0
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/GraphPanel.java
@@ -0,0 +1,250 @@
+package com.ayushmaanbhav.jstockmart.server;
+
+import java.awt.*;
+import java.awt.event.*;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.*;
+
+@SuppressWarnings("serial")
+public class GraphPanel extends JPanel {
+
+	// private int width = 800;
+	// private int heigth = 600;
+	private int padding = 25;
+	private int labelPadding = 25;
+	private Color lineColor = new Color(44, 102, 230, 180);
+	private Color pointColor = new Color(100, 100, 100, 180);
+	private Color gridColor = new Color(200, 200, 200, 200);
+	private static final Stroke GRAPH_STROKE = new BasicStroke(2f);
+	private int pointWidth = 4;
+	private int numberYDivisions = 10;
+	private static List score;
+	private static List scores, future;
+
+	public GraphPanel(List scores) {
+		GraphPanel.score = scores;
+	}
+
+	@Override
+	protected void paintComponent(Graphics g) {
+		for (int i = 0; i < score.size(); i++) {
+			if (score.get(i).name.equals((String) comp.getSelectedItem())) {
+				scores = score.get(i).sharevalue;
+				future = score.get(i).futurevalues;
+				frame.setTitle(score.get(i).name);
+				break;
+			}
+		}
+		super.paintComponent(g);
+		Graphics2D g2 = (Graphics2D) g;
+		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+
+		double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() + future.size() - 1);
+		double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore());
+
+		List graphPoints = new ArrayList<>();
+		for (int i = 0; i < scores.size() + future.size(); i++) {
+			int x1, y1;
+			if (i < scores.size()) {
+				x1 = (int) (i * xScale + padding + labelPadding);
+				y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding);
+			} else {
+				x1 = (int) (i * xScale + padding + labelPadding);
+				y1 = (int) ((getMaxScore() - future.get(i - scores.size())) * yScale + padding);
+			}
+			graphPoints.add(new Point(x1, y1));
+		}
+
+		// draw white background
+		g2.setColor(Color.WHITE);
+		g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding);
+		g2.setColor(Color.BLACK);
+
+		// create hatch marks and grid lines for y axis.
+		for (int i = 0; i < numberYDivisions + 1; i++) {
+			int x0 = padding + labelPadding;
+			int x1 = pointWidth + padding + labelPadding;
+			int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding);
+			int y1 = y0;
+			if (scores.size() + future.size() > 0) {
+				g2.setColor(gridColor);
+				g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth() - padding, y1);
+				g2.setColor(Color.BLACK);
+				String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + "";
+				FontMetrics metrics = g2.getFontMetrics();
+				int labelWidth = metrics.stringWidth(yLabel);
+				g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3);
+			}
+			g2.drawLine(x0, y0, x1, y1);
+		}
+
+		// and for x axis
+		for (int i = 0; i < scores.size() + future.size(); i++) {
+			if (scores.size() + future.size() > 1) {
+				int x0, x1, y0, y1;
+				x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() + future.size() - 1) + padding + labelPadding;
+				x1 = x0;
+				y0 = getHeight() - padding - labelPadding;
+				y1 = y0 - pointWidth;
+				if ((i % ((int) (((scores.size() + future.size()) / 20.0)) + 1)) == 0) {
+					g2.setColor(gridColor);
+					g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding);
+					g2.setColor(Color.BLACK);
+					String xLabel = i / 2 + "m";
+					FontMetrics metrics = g2.getFontMetrics();
+					int labelWidth = metrics.stringWidth(xLabel);
+					if (i % 2 == 0)
+						g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3);
+				}
+				g2.drawLine(x0, y0, x1, y1);
+			}
+		}
+
+		// create x and y axes
+		g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding);
+		g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding);
+
+		Stroke oldStroke = g2.getStroke();
+		g2.setColor(lineColor);
+		g2.setStroke(GRAPH_STROKE);
+		for (int i = 0; i < graphPoints.size() - 1; i++) {
+			int x1 = graphPoints.get(i).x;
+			int y1 = graphPoints.get(i).y;
+			int x2 = graphPoints.get(i + 1).x;
+			int y2 = graphPoints.get(i + 1).y;
+			g2.drawLine(x1, y1, x2, y2);
+		}
+
+		g2.setStroke(oldStroke);
+		g2.setColor(pointColor);
+		for (int i = 0; i < graphPoints.size(); i++) {
+			if (i >= scores.size())
+				g2.setColor(Color.RED);
+			int x = graphPoints.get(i).x - pointWidth / 2;
+			int y = graphPoints.get(i).y - pointWidth / 2;
+			int ovalW = pointWidth;
+			int ovalH = pointWidth;
+			g2.fillOval(x, y, ovalW, ovalH);
+		}
+	}
+
+	// @Override
+	// public Dimension getPreferredSize() {
+	// return new Dimension(width, heigth);
+	// }
+	private double getMinScore() {
+		double minScore = Double.MAX_VALUE;
+		for (Company score1 : score) {
+			for (Double score2 : score1.sharevalue) {
+				minScore = Math.min(minScore, score2);
+			}
+			for (Double score2 : score1.futurevalues) {
+				minScore = Math.min(minScore, score2);
+			}
+		}
+		return 0;
+	}
+
+	private double getMaxScore() {
+		double maxScore = Double.MIN_VALUE;
+		for (Company score1 : score) {
+			for (Double score2 : score1.sharevalue) {
+				maxScore = Math.max(maxScore, score2);
+			}
+			for (Double score2 : score1.futurevalues) {
+				maxScore = Math.max(maxScore, score2);
+			}
+		}
+		return maxScore;
+	}
+
+	@SuppressWarnings("unchecked")
+	public void setScores(List score) {
+		GraphPanel.score = score;
+		comp.removeAllItems();
+		for (int i = 0; i < score.size(); i++)
+			comp.addItem(score.get(i).name);
+		try {
+			comp.setSelectedIndex(0);
+			scores = score.get(0).sharevalue;
+		} catch (Exception o) {
+		}
+		invalidate();
+		this.repaint();
+	}
+
+	public List getScores() {
+		return scores;
+	}
+
+	@SuppressWarnings("rawtypes")
+	static JComboBox comp;
+	static JFrame frame;
+	static JTextField comp1, comp2;
+	static GraphPanel mainPanel;
+	public static void main() {
+		SwingUtilities.invokeLater(new Runnable() {
+			@SuppressWarnings("rawtypes")
+			public void run() {
+				comp = new JComboBox();
+				comp1 = new JTextField(40);
+				comp2 = new JTextField(40);
+				comp1.addActionListener(new ActionListener() {
+					public void actionPerformed(ActionEvent e) {
+						for (int i = 0; i < score.size(); i++) {
+							if (score.get(i).name.equals((String) comp.getSelectedItem())) {
+								score.get(i).rate = Double.parseDouble(comp1.getText());
+								break;
+							}
+						}
+					}
+				});
+				comp2.addActionListener(new ActionListener() {
+					public void actionPerformed(ActionEvent e) {
+						for (int i = 0; i < score.size(); i++) {
+							if (score.get(i).name.equals((String) comp.getSelectedItem())) {
+								score.get(i).vol = Double.parseDouble(comp2.getText());
+								break;
+							}
+						}
+					}
+				});
+				comp.addItemListener(new ItemListener() {
+					public void itemStateChanged(ItemEvent e) {
+						if (e.getStateChange() == ItemEvent.SELECTED) {
+							for (int i = 0; i < score.size(); i++) {
+								if (score.get(i).name.equals((String) comp.getSelectedItem())) {
+									comp1.setText("" + score.get(i).rate);
+									comp2.setText("" + score.get(i).vol);
+									break;
+								}
+							}
+							mainPanel.repaint();
+							comp.requestFocus();
+						}
+					}
+				});
+				// Random random = new Random();
+				// int maxDataPoints = 40;
+				// int maxScore = 10;
+				mainPanel = new GraphPanel(null);
+				mainPanel.setScores(ShareMarket.companies);
+				mainPanel.setPreferredSize(new Dimension(800, 500));
+				frame = new JFrame("DrawGraph");
+				// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+				frame.getContentPane().setLayout(new BorderLayout());
+				frame.getContentPane().add(comp, BorderLayout.NORTH);
+				JPanel op = new JPanel(new BorderLayout());
+				op.add(comp1, BorderLayout.WEST);
+				op.add(comp2, BorderLayout.EAST);
+				//frame.getContentPane().add(op, BorderLayout.SOUTH);
+				frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
+				frame.pack();
+				frame.setLocationRelativeTo(null);
+				frame.setVisible(true);
+			}
+		});
+	}
+}
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/server/HistogramPanel.java b/src/com/ayushmaanbhav/jstockmart/server/HistogramPanel.java
new file mode 100644
index 0000000..fad0b23
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/HistogramPanel.java
@@ -0,0 +1,94 @@
+package com.ayushmaanbhav.jstockmart.server;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.util.Collections;
+import javax.swing.JComboBox;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.SwingUtilities;
+
+import com.ayushmaanbhav.jstockmart.utils.Histogram;
+import com.ayushmaanbhav.jstockmart.utils.TrippleArrayList;
+
+public class HistogramPanel extends JPanel {
+	private static final long serialVersionUID = 1L;
+
+	private TrippleArrayList scores;
+
+	public HistogramPanel(TrippleArrayList scores) {
+		this.scores = scores;
+	}
+
+	@Override
+	protected void paintComponent(Graphics g) {
+		super.paintComponent(g);
+		Graphics2D g2 = (Graphics2D) g;
+		Histogram.paintHistogram(g2, getHeight(), getWidth(), scores);
+	}
+
+	public void setScores(TrippleArrayList scores) {
+		this.scores = scores;
+	}
+
+	public TrippleArrayList getScores() {
+		return scores;
+	}
+
+	void updatePanel() {
+		comp.setEnabled(false);
+		new Thread() {
+			public void run() {
+				TrippleArrayList arr = new TrippleArrayList(Orders.getLimitOrderStatsOfCompany((String) comp.getSelectedItem()));
+				if (arr != null) {
+					if (arr.size() > 0) {
+						Collections.sort(arr);
+						arr.add(0, 0, 0.0, 0);
+						arr.add(0, 0.0, 0);
+					}
+					setScores(arr);
+					SwingUtilities.invokeLater(new Runnable() {
+						public void run() {
+							mainPanel.repaint();
+							comp.setEnabled(true);
+							// comp.requestFocus();
+						}
+					});
+				}
+			}
+		}.start();
+	}
+
+	@SuppressWarnings("rawtypes")
+	static JComboBox comp;
+	static JFrame frame;
+	static HistogramPanel mainPanel;
+	@SuppressWarnings({"rawtypes", "unchecked"})
+	public static void main() {
+		comp = new JComboBox();
+		for (int i = 0; i < ShareMarket.companies.size(); i++)
+			comp.addItem(ShareMarket.companies.get(i).name);
+		comp.setSelectedIndex(0);
+		comp.addItemListener(new ItemListener() {
+			public void itemStateChanged(ItemEvent e) {
+				if (e.getStateChange() == ItemEvent.SELECTED) {
+					mainPanel.updatePanel();
+				}
+			}
+		});
+		comp.setLightWeightPopupEnabled(false);
+		mainPanel = new HistogramPanel(new TrippleArrayList());
+		mainPanel.setPreferredSize(new Dimension(800, 500));
+		frame = new JFrame();
+		frame.getContentPane().setLayout(new BorderLayout());
+		frame.getContentPane().add(comp, BorderLayout.NORTH);
+		frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
+		frame.pack();
+		frame.setLocationRelativeTo(null);
+		frame.setVisible(true);
+	}
+}
diff --git a/src/com/ayushmaanbhav/jstockmart/server/MatchingEngine.java b/src/com/ayushmaanbhav/jstockmart/server/MatchingEngine.java
new file mode 100644
index 0000000..b19c176
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/MatchingEngine.java
@@ -0,0 +1,354 @@
+package com.ayushmaanbhav.jstockmart.server;
+
+import java.util.ArrayList;
+import java.util.Date;
+
+import com.ayushmaanbhav.jstockmart.user.Shares;
+import com.ayushmaanbhav.jstockmart.user.User;
+
+public class MatchingEngine {
+
+	private static double LTP;
+
+	/*
+	 * The rule is basically to match market orders first because they have to
+	 * be executed immediately. I first get all the market orders and execute
+	 * them at the LTP (Last Traded Price) which is also the CMP (Current Market
+	 * Price). If any market orders are remaining then we match them with limit
+	 * orders. The concept to understand in the limit order matching is that we
+	 * are always biased towards the buyers. We try to profit them. Why ? This
+	 * is because we consider sellers to be clever. You will see this in real
+	 * markets also. They put the price much higher than the actual price and
+	 * then they lower it on bargaining. They know the psychology of their
+	 * customers. To sum up, most of the time sellers profit on the prices they
+	 * set. So we always trade the limit orders on seller's price even if the
+	 * buyer's limit price is higher. One case is special though in which the
+	 * buyer's limit price is higher than the market price or LTP and the seller
+	 * wishes to sell his shares on the market price so he places a market
+	 * order. Now in this case we trade the orders on the market price or LTP
+	 * for the same reasons explained above.
+	 */
+	static void matchOrders() {
+		double avg = 0;
+		for (int i = 0; i < ShareMarket.companies.size(); i++) {
+			Company com = ShareMarket.companies.get(i);
+			double LTP = com.sharevalue.get(com.sharevalue.size() - 1);
+			MatchingEngine.LTP = LTP;
+
+			// get market orders of this company
+			ArrayList buyOrders = Orders.getOrders(Orders.MARKET_BUY_ORDER, com.name);
+			ArrayList sellOrders = Orders.getOrders(Orders.MARKET_SELL_ORDER, com.name);
+
+			// match market orders first
+			while (buyOrders.size() > 0 && sellOrders.size() > 0) {
+				Shares s1 = buyOrders.get(0);
+				Shares s2 = sellOrders.get(0);
+				Shares s3 = MatchingEngine.matchMarketMarketOrders(s1, s2, com, LTP);
+				if (s3 == null) {
+					Orders.remove(s1);
+					buyOrders.remove(s1);
+					Orders.remove(s2);
+					sellOrders.remove(s2);
+				} else if (s3 == s1) {
+					Orders.remove(s1);
+					buyOrders.remove(s1);
+				} else if (s3 == s2) {
+					Orders.remove(s2);
+					sellOrders.remove(s2);
+				}
+			}
+
+			// if any market orders are remaining then match them with limit
+			// orders
+			if (buyOrders.size() > 0) {
+				sellOrders = Orders.getOrders(Orders.LIMIT_SELL_ORDER, com.name);
+				while (buyOrders.size() > 0 && sellOrders.size() > 0) {
+					Shares s1 = buyOrders.get(0);
+					double min_diff = Double.MAX_VALUE;
+					Shares s2 = null;
+					for (Shares temp : sellOrders) {
+						double diff = Math.abs(temp.cost_limit - LTP);
+						if (diff < min_diff) {
+							min_diff = diff;
+							s2 = temp;
+						}
+					}
+					Shares s3 = MatchingEngine.matchMarketLimitOrders(s1, s2, com);
+					if (s3 == null) {
+						Orders.remove(s1);
+						buyOrders.remove(s1);
+						Orders.remove(s2);
+						sellOrders.remove(s2);
+					} else if (s3 == s1) {
+						Orders.remove(s1);
+						buyOrders.remove(s1);
+					} else if (s3 == s2) {
+						Orders.remove(s2);
+						sellOrders.remove(s2);
+					}
+				}
+				buyOrders = Orders.getOrders(Orders.LIMIT_BUY_ORDER, com.name);
+			} else if (sellOrders.size() > 0) {
+				buyOrders = Orders.getOrders(Orders.LIMIT_BUY_ORDER, com.name);
+				while (buyOrders.size() > 0 && sellOrders.size() > 0) {
+					Shares s2 = sellOrders.get(0);
+					Shares s1 = null;
+					double tradingPrice = LTP;
+					for (int loop = 0; loop < buyOrders.size(); loop++) {
+						if (buyOrders.get(loop).cost_limit >= LTP) {
+							s1 = buyOrders.get(loop);
+							break;
+						}
+					}
+					if (s1 == null) {
+						double min_diff = Double.MAX_VALUE;
+						for (Shares temp : buyOrders) {
+							double diff = Math.abs(temp.cost_limit - LTP);
+							if (diff < min_diff) {
+								min_diff = diff;
+								s1 = temp;
+								tradingPrice = s1.cost_limit;
+							}
+						}
+					}
+					Shares s3 = MatchingEngine.matchLimitMarketOrders(s1, s2, com, tradingPrice);
+					if (s3 == null) {
+						Orders.remove(s1);
+						buyOrders.remove(s1);
+						Orders.remove(s2);
+						sellOrders.remove(s2);
+					} else if (s3 == s1) {
+						Orders.remove(s1);
+						buyOrders.remove(s1);
+					} else if (s3 == s2) {
+						Orders.remove(s2);
+						sellOrders.remove(s2);
+					}
+				}
+				sellOrders = Orders.getOrders(Orders.LIMIT_SELL_ORDER, com.name);
+			} else {
+				buyOrders = Orders.getOrders(Orders.LIMIT_BUY_ORDER, com.name);
+				sellOrders = Orders.getOrders(Orders.LIMIT_SELL_ORDER, com.name);
+			}
+
+			// match limit orders
+			int loop1 = 0, loop2 = 0;
+			while (loop1 < buyOrders.size() && sellOrders.size() > 0) {
+				Shares s1 = buyOrders.get(loop1);
+				Shares s2 = null;
+				for (loop2 = 0; loop2 < sellOrders.size(); loop2++) {
+					if (sellOrders.get(loop2).cost_limit <= s1.cost_limit) {
+						s2 = sellOrders.get(loop2);
+						break;
+					}
+				}
+				if (s2 == null) {
+					loop1++;
+					continue;
+				}
+				Shares s3 = MatchingEngine.matchLimitLimitOrders(s1, s2, com);
+				if (s3 == null) {
+					Orders.remove(s1);
+					loop1++;
+					Orders.remove(s2);
+					sellOrders.remove(s2);
+				} else if (s3 == s1) {
+					Orders.remove(s1);
+					loop1++;
+				} else if (s3 == s2) {
+					Orders.remove(s2);
+					sellOrders.remove(s2);
+				}
+			}
+
+			com.sharevalue.add(MatchingEngine.LTP);
+			com.d = new Date();
+
+			try {
+				com.perchange = Double.valueOf(ShareMarket.twoDForm.format((com.sharevalue.get(com.sharevalue.size() - 1) - com.sharevalue.get(com.sharevalue.size() - 2)) * 100 / com.sharevalue.get(com.sharevalue.size() - 2)));
+			} catch (Exception mm) {
+				com.perchange = 0;
+			}
+			if (com.sharevalue.get(com.sharevalue.size() - 1) <= 0.0) {
+				com.bankrupt = true;
+			}
+			avg += com.sharevalue.get(com.sharevalue.size() - 1);
+			com.tsharessold += com.sharessold;
+			com.sharessoldpast = com.sharessold;
+			com.sharessold = 0;
+			com.setPricePrecision(MatchingEngine.calculatePrecision(com));
+		}
+		ShareMarket.sensex = Double.valueOf(ShareMarket.twoDForm.format(avg / ShareMarket.companies.size()));
+	}
+	private static Shares matchMarketMarketOrders(Shares buyOrder, Shares sellOrder, Company comp, double LTP) {
+		return matchOrders(buyOrder, sellOrder, comp, LTP);
+	}
+
+	private static Shares matchMarketLimitOrders(Shares buyOrder, Shares sellOrder, Company comp) {
+		return matchOrders(buyOrder, sellOrder, comp, sellOrder.cost_limit);
+	}
+
+	private static Shares matchLimitMarketOrders(Shares buyOrder, Shares sellOrder, Company comp, double tradingPrice) {
+		return matchOrders(buyOrder, sellOrder, comp, tradingPrice);
+	}
+
+	private static Shares matchLimitLimitOrders(Shares buyOrder, Shares sellOrder, Company comp) {
+		return matchOrders(buyOrder, sellOrder, comp, sellOrder.cost_limit);
+	}
+
+	private static Shares matchOrders(Shares buyOrder, Shares sellOrder, Company comp, double tradingPrice) {
+		User buyer = buyOrder.user;
+		User seller = sellOrder.user;
+		synchronized (buyer) {
+			synchronized (seller) {
+				if (!buyOrder.notCanceled || buyer.isBanned() || !buyer.getPendingShares().contains(buyOrder)) {
+					buyOrder.status = "Canceled";
+					return buyOrder;
+				}
+
+				if (!sellOrder.notCanceled || seller.isBanned() || !seller.getPendingShares().contains(sellOrder)) {
+					sellOrder.status = "Canceled";
+					return sellOrder;
+				}
+
+				try {
+					assert tradingPrice > 0.0;
+				} catch (AssertionError e) {
+					e.printStackTrace();
+					return new Shares();
+				}
+
+				double tot_price = Double.parseDouble(StockMart.twoDForm.format(tradingPrice * 1.02));
+
+				int min_shares = Math.min(buyOrder.qty_limit, sellOrder.qty_limit);
+
+				int buyersAukaad = (int) (buyer.getCurrentMoney() / tot_price);
+				min_shares = Math.min(min_shares, buyersAukaad);
+				if (min_shares == 0) {
+					buyOrder.status = "Failed (Not Enough Money)";
+					return buyOrder;
+				}
+
+				Shares sellersCurrentShares = null;
+				for (int z = 0; z < seller.getCurrentShares().size(); z++) {
+					if (seller.getCurrentShares().get(z).company.equalsIgnoreCase(comp.name)) {
+						sellersCurrentShares = seller.getCurrentShares().get(z);
+						break;
+					}
+				}
+
+				if (sellersCurrentShares == null || sellersCurrentShares.qty <= 0) {
+					sellOrder.status = "Failed (Not Enough Shares)";
+					return sellOrder;
+				}
+
+				min_shares = Math.min(min_shares, sellersCurrentShares.qty);
+
+				boolean remove_buyer = false, remove_seller = false;
+
+				// buyer gets shares
+				buyer.setCurrentMoney(buyer.getCurrentMoney() - Double.parseDouble(StockMart.twoDForm.format(tot_price * min_shares)));
+				comp.sharessold += min_shares;
+				if (min_shares == buyOrder.qty_limit) {
+					buyOrder.status = "Completed";
+					remove_buyer = true;
+				} else if (min_shares == buyersAukaad) {
+					buyOrder.status = "Completed Partially (Not Enough Money)";
+					remove_buyer = true;
+				} else {
+					buyOrder.status = "Completed Partially, Rest Pending";
+					buyOrder.qty_limit -= min_shares;
+				}
+				int y = 0;
+				for (int z = 0; z < buyer.getCurrentShares().size(); z++) {
+					if (buyer.getCurrentShares().get(z).company.equalsIgnoreCase(comp.name)) {
+						buyer.getCurrentShares().get(z).cost = Double.parseDouble(StockMart.twoDForm.format((buyer.getCurrentShares().get(z).cost * buyer.getCurrentShares().get(z).qty + tradingPrice * min_shares) / (min_shares + buyer.getCurrentShares().get(z).qty)));
+						buyer.getCurrentShares().get(z).qty += min_shares;
+						buyer.getCurrentShares().get(z).buyed = new Date();
+						y++;
+						break;
+					}
+				}
+				if (y == 0) {
+					Shares sh = new Shares(buyOrder);
+					sh.buyed = new Date();
+					sh.cost = tradingPrice;
+					sh.qty = min_shares;
+					buyer.getCurrentShares().add(sh);
+				}
+
+				// seller gets money
+				seller.setCurrentMoney(seller.getCurrentMoney() + Double.parseDouble(StockMart.twoDForm.format(tradingPrice * min_shares)));
+				if (min_shares == sellOrder.qty_limit) {
+					sellOrder.status = "Completed";
+					remove_seller = true;
+				} else if (sellersCurrentShares.qty == min_shares) {
+					sellOrder.status = "Completed Partially (Not Enough Shares)";
+					remove_seller = true;
+				} else {
+					sellOrder.status = "Completed Partially, Rest Pending";
+					sellOrder.qty_limit -= min_shares;
+				}
+				if (sellersCurrentShares.qty - min_shares > 0) {
+					sellersCurrentShares.cost = Double.parseDouble(StockMart.twoDForm.format((sellersCurrentShares.cost * sellersCurrentShares.qty - tradingPrice * min_shares) / (sellersCurrentShares.qty - min_shares)));
+					sellersCurrentShares.qty -= min_shares;
+				} else {
+					seller.getCurrentShares().remove(sellersCurrentShares);
+				}
+
+				MatchingEngine.LTP = tradingPrice;
+
+				if (buyOrder.type == Orders.LIMIT_BUY_ORDER && sellOrder.type == Orders.LIMIT_SELL_ORDER) {
+					comp.nooflimitbidsmatched++;
+				}
+
+				try {
+					ShareMarket.server.sendMessage(buyer, 5);
+					ShareMarket.server.sendMessage(seller, 5);
+				} catch (Exception hh) {
+					hh.printStackTrace();
+				}
+
+				if (remove_buyer && remove_seller) {
+					return null;
+				} else if (remove_buyer) {
+					return buyOrder;
+				} else if (remove_seller) {
+					return sellOrder;
+				} else {
+					System.out.println("Warning: neither buyer nor seller removed.");
+					return new Shares();
+				}
+			}
+		}
+	}
+
+	static double calculatePrecision(Company com) {
+		double mktvalue = com.sharevalue.get(com.sharevalue.size() - 1);
+		int noofdigits = noOfDigits((int) mktvalue);
+		int nooflimitorders = Orders.getNoOfLimitOrders(com.name);
+		if (com.nooflimitbidsmatched > 10 && nooflimitorders < 10) {
+			return Double.parseDouble(ShareMarket.twoDForm.format(Math.pow(10, noofdigits - 2) / 8));
+		} else if (com.nooflimitbidsmatched > 5 && nooflimitorders < 10) {
+			return Double.parseDouble(ShareMarket.twoDForm.format(Math.pow(10, noofdigits - 2) / 4));
+		} else if (com.nooflimitbidsmatched > 0 && nooflimitorders < 50) {
+			return Double.parseDouble(ShareMarket.twoDForm.format(Math.pow(10, noofdigits - 2) / 2));
+		} else {
+			return Double.parseDouble(ShareMarket.twoDForm.format(Math.pow(10, noofdigits - 2)));
+		}
+	}
+
+	static double getHighestPrecision(Company com) {
+		double mktvalue = com.sharevalue.get(com.sharevalue.size() - 1);
+		int noofdigits = noOfDigits((int) mktvalue);
+		return Double.parseDouble(ShareMarket.twoDForm.format(Math.pow(10, noofdigits - 2) / 8));
+	}
+
+	static int noOfDigits(int n) {
+		int i = 0;
+		while ((n = n / 10) > 0) {
+			i++;
+		}
+		return i;
+	}
+}
diff --git a/src/com/ayushmaanbhav/jstockmart/server/Orders.java b/src/com/ayushmaanbhav/jstockmart/server/Orders.java
new file mode 100644
index 0000000..6be1480
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/Orders.java
@@ -0,0 +1,157 @@
+package com.ayushmaanbhav.jstockmart.server;
+
+import java.util.*;
+
+import com.ayushmaanbhav.jstockmart.user.Shares;
+import com.ayushmaanbhav.jstockmart.utils.TrippleArrayList;
+
+class Orders {
+	public final static int MARKET_BUY_ORDER = 0;
+	public final static int MARKET_SELL_ORDER = 1;
+	public final static int LIMIT_BUY_ORDER = 2;
+	public final static int LIMIT_SELL_ORDER = 3;
+
+	public static ArrayList limitBuyOrders, limitSellOrders;
+	public static ArrayList marketBuyOrders, marketSellOrders;
+	public static HashMap> stats;
+
+	public Orders() {
+		limitBuyOrders = new ArrayList();
+		limitSellOrders = new ArrayList();
+		marketBuyOrders = new ArrayList();
+		marketSellOrders = new ArrayList();
+		stats = new HashMap>(ShareMarket.companies.size());
+		for (Company comp : ShareMarket.companies) {
+			stats.put(comp.name, new TrippleArrayList());
+		}
+	}
+
+	public static boolean remove(Shares s) {
+		return limitBuyOrders.remove(s) || limitSellOrders.remove(s) || marketBuyOrders.remove(s) || marketSellOrders.remove(s);
+	}
+
+	public static Shares remove(Integer id, Integer sellid, String status) {
+		for (Shares share : marketBuyOrders) {
+			if (share.id == id && share.sellid == sellid) {
+				marketBuyOrders.remove(share);
+				share.status = status;
+				return share;
+			}
+		}
+		for (Shares share : marketSellOrders) {
+			if (share.id == id && share.sellid == sellid) {
+				marketSellOrders.remove(share);
+				share.status = status;
+				return share;
+			}
+		}
+		for (Shares share : limitBuyOrders) {
+			if (share.id == id && share.sellid == sellid) {
+				limitBuyOrders.remove(share);
+				share.status = status;
+				return share;
+			}
+		}
+		for (Shares share : limitSellOrders) {
+			if (share.id == id && share.sellid == sellid) {
+				limitSellOrders.remove(share);
+				share.status = status;
+				return share;
+			}
+		}
+		return null;
+	}
+
+	public static boolean contain(Shares s) {
+		return limitBuyOrders.contains(s) || limitSellOrders.contains(s) || marketBuyOrders.contains(s) || marketSellOrders.contains(s);
+	}
+
+	public static ArrayList getOrders(int type, String comName) {
+		ArrayList list = new ArrayList();
+		if (type == MARKET_BUY_ORDER) {
+			for (Shares share : marketBuyOrders) {
+				if (share.company.equals(comName))
+					list.add(share);
+			}
+		} else if (type == MARKET_SELL_ORDER) {
+			for (Shares share : marketSellOrders) {
+				if (share.company.equals(comName))
+					list.add(share);
+			}
+		} else if (type == LIMIT_BUY_ORDER) {
+			for (Shares share : limitBuyOrders) {
+				if (share.company.equals(comName))
+					list.add(share);
+			}
+		} else if (type == LIMIT_SELL_ORDER) {
+			for (Shares share : limitSellOrders) {
+				if (share.company.equals(comName))
+					list.add(share);
+			}
+		}
+		return list;
+	}
+
+	public static void calculateLimitOrderStats() {
+		for (Company com : ShareMarket.companies) {
+			TrippleArrayList arr = stats.get(com.name);
+			arr.clear();
+			for (Shares share : limitBuyOrders) {
+				if (share.company.equals(com.name)) {
+					int index = arr.containsSecondElement(share.cost_limit);
+					if (index != -1)
+						arr.setFirstElement(index, arr.getFirstElement(index) + share.qty_limit);
+					else
+						arr.add(share.qty_limit, share.cost_limit, 0);
+				}
+			}
+			for (Shares share : limitSellOrders) {
+				if (share.company.equals(com.name)) {
+					int index = arr.containsSecondElement(share.cost_limit);
+					if (index != -1)
+						arr.setThirdElement(index, arr.getThirdElement(index) + share.qty_limit);
+					else
+						arr.add(0, share.cost_limit, share.qty_limit);
+				}
+			}
+		}
+	}
+
+	public static TrippleArrayList getLimitOrderStatsOfCompany(String comName) {
+		for (String key : stats.keySet()) {
+			if (key.equalsIgnoreCase(comName))
+				return stats.get(key);
+		}
+		return new TrippleArrayList();
+	}
+
+	public static int getNoOfLimitOrders(String comName) {
+		int n = 0;
+		for (Shares share : limitBuyOrders) {
+			if (share.company.equals(comName))
+				n++;
+		}
+		for (Shares share : limitSellOrders) {
+			if (share.company.equals(comName))
+				n++;
+		}
+		return n;
+	}
+
+	public static void printQueues() {
+		System.out.println("\nStatus of all the queues:");
+		System.out.print("Limit Buy Orders: ");
+		System.out.println(limitBuyOrders.toString());
+		System.out.print("Limit Sell Orders: ");
+		System.out.println(limitSellOrders.toString());
+		System.out.print("Market Buy Orders: ");
+		System.out.println(marketBuyOrders.toString());
+		System.out.print("Market Sell Orders: ");
+		System.out.println(marketSellOrders.toString());
+		System.out.println("Stats:");
+		for (Company c : ShareMarket.companies) {
+			System.out.print(c.name + ": ");
+			System.out.println(getLimitOrderStatsOfCompany(c.name).toString());
+		}
+	}
+}
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/server/OrdersPanel.java b/src/com/ayushmaanbhav/jstockmart/server/OrdersPanel.java
new file mode 100644
index 0000000..6be2d88
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/OrdersPanel.java
@@ -0,0 +1,169 @@
+package com.ayushmaanbhav.jstockmart.server;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.util.ArrayList;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTable;
+import javax.swing.SwingUtilities;
+import javax.swing.table.DefaultTableModel;
+
+import com.ayushmaanbhav.jstockmart.user.Shares;
+import com.ayushmaanbhav.jstockmart.utils.ButtonColumn;
+
+public class OrdersPanel {
+	static JFrame frame;
+	static DefaultTableModel dtm;
+	static Action delete;
+	static JTable orders;
+	static String[] colNames = {"ID", "Sell ID", "User", "Curr Money", "No. of shares", "Ordered", "Type", "Limit Price", "Qty Limit", "Status", "Cancel"};
+	static JScrollPane jspt;
+	static JComboBox combo;
+	static JButton refresh;
+	static JPanel panel;
+
+	@SuppressWarnings("serial")
+	public static void main() {
+		dtm = new DefaultTableModel(colNames, 0);
+		orders = new JTable(dtm) {
+			public boolean isCellEditable(int row, int col) {
+				if (col == 10)
+					return true;
+				return false;
+			}
+			public boolean isCellSelected(int row, int col) {
+				return false;
+			}
+		};
+		orders.setDragEnabled(false);
+		orders.setRowSelectionAllowed(false);
+		orders.setColumnSelectionAllowed(false);
+		// table.setShowHorizontalLines(true);
+		// table.setShowVerticalLines(true);
+		orders.setRowHeight(30);
+		orders.getTableHeader().setReorderingAllowed(false);
+		orders.setFillsViewportHeight(true);
+		jspt = new JScrollPane(orders);
+		delete = new AbstractAction() {
+			public void actionPerformed(ActionEvent e) {
+				final int row = Integer.valueOf(e.getActionCommand());
+				int res = JOptionPane.showConfirmDialog(null, "Are you sure ?", "Confirm:", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
+				if (res == JOptionPane.YES_OPTION) {
+					Shares ss = Orders.remove((Integer) orders.getValueAt(row, 0), (Integer) orders.getValueAt(row, 1), "Canceled by Admin");
+					if (ss != null)
+						ShareMarket.server.sendMessage(ss.user, 5);
+				}
+			}
+		};
+		combo = new JComboBox();
+		for (int i = 0; i < ShareMarket.companies.size(); i++)
+			combo.addItem(ShareMarket.companies.get(i).name);
+		combo.addItemListener(new ItemListener() {
+			public void itemStateChanged(ItemEvent e) {
+				if (e.getStateChange() == ItemEvent.SELECTED) {
+					update((String) combo.getSelectedItem());
+				}
+			}
+		});
+		refresh = new JButton("Refresh");
+		refresh.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent arg0) {
+				update((String) combo.getSelectedItem());
+			}
+		});
+		frame = new JFrame("Orders");
+		panel = (JPanel) frame.getContentPane();
+		panel.setLayout(new BorderLayout());
+		panel.setPreferredSize(new Dimension(800, 500));
+		panel.add(combo, BorderLayout.NORTH);
+		panel.add(jspt, BorderLayout.CENTER);
+		panel.add(refresh, BorderLayout.SOUTH);
+		frame.pack();
+		frame.setVisible(true);
+		SwingUtilities.invokeLater(new Runnable() {
+			@Override
+			public void run() {
+				combo.setSelectedIndex(0);
+				combo.requestFocus();
+			}
+		});
+	}
+
+	public static void update(final String company) {
+		new Thread() {
+			public void run() {
+				Company comp = null;
+				for (Company temp : ShareMarket.companies) {
+					if (temp.name.equals(company)) {
+						comp = temp;
+						break;
+					}
+				}
+				ArrayList arr = new ArrayList();
+				arr.add(new Object[]{"LIMIT_BUY_ORDERS:", null, null, null, null, null, null, null, null, null, null});
+				ArrayList shares = Orders.getOrders(Orders.LIMIT_BUY_ORDER, comp.name);
+				for (Shares ss : shares) {
+					int noofshares = 0;
+					for (Shares pp : ss.user.getCurrentShares())
+						if (pp.company.equals(comp.name))
+							noofshares += pp.qty;
+					arr.add(new Object[]{ss.id, ss.sellid, ss.user.getName(), ss.user.getCurrentMoney(), noofshares, String.valueOf((ss.ordered.getTime() - StockMart.startDate.getTime()) / 60000) + " mins", "LIMIT_BUY_ORDER", ss.cost_limit, ss.qty_limit, ss.status, "Cancel"});
+				}
+				arr.add(new Object[]{"LIMIT_SELL_ORDERS:", null, null, null, null, null, null, null, null, null, null});
+				shares = Orders.getOrders(Orders.LIMIT_SELL_ORDER, comp.name);
+				for (Shares ss : shares) {
+					int noofshares = 0;
+					for (Shares pp : ss.user.getCurrentShares())
+						if (pp.company.equals(comp.name))
+							noofshares += pp.qty;
+					arr.add(new Object[]{ss.id, ss.sellid, ss.user.getName(), ss.user.getCurrentMoney(), noofshares, String.valueOf((ss.ordered.getTime() - StockMart.startDate.getTime()) / 60000) + " mins", "LIMIT_SELL_ORDER", ss.cost_limit, ss.qty_limit, ss.status, "Cancel"});
+				}
+				arr.add(new Object[]{"MARKET_BUY_ORDERS:", null, null, null, null, null, null, null, null, null, null});
+				shares = Orders.getOrders(Orders.MARKET_BUY_ORDER, comp.name);
+				for (Shares ss : shares) {
+					int noofshares = 0;
+					for (Shares pp : ss.user.getCurrentShares())
+						if (pp.company.equals(comp.name))
+							noofshares += pp.qty;
+					arr.add(new Object[]{ss.id, ss.sellid, ss.user.getName(), ss.user.getCurrentMoney(), noofshares, String.valueOf((ss.ordered.getTime() - StockMart.startDate.getTime()) / 60000) + " mins", "MARKET_BUY_ORDER", "N.A.", ss.qty_limit, ss.status, "Cancel"});
+				}
+				arr.add(new Object[]{"MARKET_SELL_ORDERS:", null, null, null, null, null, null, null, null, null, null});
+				shares = Orders.getOrders(Orders.MARKET_SELL_ORDER, comp.name);
+				for (Shares ss : shares) {
+					int noofshares = 0;
+					for (Shares pp : ss.user.getCurrentShares())
+						if (pp.company.equals(comp.name))
+							noofshares += pp.qty;
+					arr.add(new Object[]{ss.id, ss.sellid, ss.user.getName(), ss.user.getCurrentMoney(), noofshares, String.valueOf((ss.ordered.getTime() - StockMart.startDate.getTime()) / 60000) + " mins", "MARKET_SELL_ORDER", "N.A.", ss.qty_limit, ss.status, "Cancel"});
+				}
+				final Object obj[][] = new Object[arr.size()][];
+				for (int i = 0; i < arr.size(); i++) {
+					obj[i] = arr.get(i);
+				}
+				arr.clear();
+				arr = null;
+				SwingUtilities.invokeLater(new Runnable() {
+					@Override
+					public void run() {
+						dtm.setDataVector(obj, colNames);
+						new ButtonColumn(orders, delete, 10);
+						combo.requestFocus();
+					}
+				});
+			}
+		}.start();
+	}
+}
diff --git a/src/com/ayushmaanbhav/jstockmart/server/RankingServer.java b/src/com/ayushmaanbhav/jstockmart/server/RankingServer.java
new file mode 100644
index 0000000..d44e245
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/RankingServer.java
@@ -0,0 +1,147 @@
+package com.ayushmaanbhav.jstockmart.server;
+import java.io.*;
+import java.util.*;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.text.*;
+
+import javax.swing.*;
+
+import com.ayushmaanbhav.jstockmart.user.*;
+
+public class RankingServer extends Thread {
+	private long SECONDS = 30000;
+	List com;
+	Server server;
+	int close;
+	BufferedWriter bw;
+	BlockingQueue queue;
+	static boolean startWaiting = false;
+
+	public RankingServer(String name, List c, Server s) throws IOException {
+		super(name);
+		setPriority(8);
+		com = c;
+		startWaiting = false;
+		server = s;
+		queue = new LinkedBlockingQueue();
+		try {
+			bw = new BufferedWriter(new FileWriter("appdata/rank.txt"));
+		} catch (Exception mm) {
+		}
+	}
+
+	DecimalFormat twoDForm = new DecimalFormat("#.##");
+	public void run() {
+		close = 0;
+		while (true) {
+			if (close == 1)
+				break;
+			try {
+				StringBuffer dString = new StringBuffer();
+				dString.append(Commands.RANKS);
+				dString.append("::");
+				rankUsers();
+				for (int i = UserDatabase.userList.size() - 1; i >= 0; i--) {
+					User user = UserDatabase.userList.get(i);
+					if (!user.isBanned()) {
+						dString.append(user.getName());
+						dString.append("-");
+						dString.append(twoDForm.format(user.getScore()));
+						dString.append(":");
+					}
+				}
+				// final String sss=dString;
+				SwingUtilities.invokeLater(new Runnable() {
+					public void run() {
+						StringBuffer jj = new StringBuffer();
+						for (int i = UserDatabase.userList.size() - 1; i >= 0; i--) {
+							User user = UserDatabase.userList.get(i);
+							jj.append(UserDatabase.userList.size() - i);
+							jj.append(" )  ");
+							jj.append(user.getName());
+							jj.append("->");
+							jj.append(twoDForm.format(user.getScore()));
+							jj.append("\n");
+						}
+						StockMart.ranks.setText(jj.toString());
+						SwingUtilities.invokeLater(new Runnable() {
+							public void run() {
+								StockMart.jkps.getVerticalScrollBar().setValue(0);
+							}
+						});
+					}
+				});
+				server.sendMulti(dString.toString(), Thread.MIN_PRIORITY);
+				try {
+					bw.write(new Date().toString() + ":" + dString + "\n");
+					bw.flush();
+				} catch (Exception mm) {
+					mm.printStackTrace();
+				}
+				if (startWaiting) {
+					queue.take();
+				} else {
+					try {
+						sleep(SECONDS);
+					} catch (InterruptedException e) {
+					}
+				}
+			} catch (Exception e) {
+				e.printStackTrace();
+				return;
+			}
+		}
+	}
+
+	synchronized void rankUsers() {
+		calculateScores();
+		sortUsers();
+	}
+
+	synchronized private void calculateScores() {
+		synchronized (UserDatabase.userList) {
+			synchronized (com) {
+				for (int i = 0; i < UserDatabase.userList.size(); i++) {
+					User key = UserDatabase.userList.get(i);
+					key.setScore(calculateUserScore(key));
+				}
+			}
+		}
+	}
+
+	synchronized private void sortUsers() {
+		synchronized (UserDatabase.userList) {
+			for (int i = 0; i < UserDatabase.userList.size(); i++) {
+				User key = UserDatabase.userList.get(i);
+				int j;
+				for (j = i - 1; j >= 0; j--) {
+					if ((UserDatabase.userList.get(j).getScore() > key.getScore() && !UserDatabase.userList.get(j).isBanned()) || key.isBanned())
+						UserDatabase.userList.set(j + 1, UserDatabase.userList.get(j));
+					else
+						break;
+				}
+				UserDatabase.userList.set(j + 1, key);
+			}
+
+		}
+	}
+
+	synchronized private double calculateUserScore(User u) {
+		synchronized (u) {
+			double mon = Double.valueOf(twoDForm.format(u.getCurrentMoney()));
+			double score = mon;
+			List list = u.getCurrentShares();
+			for (int i = 0; i < list.size(); i++) {
+				String name = list.get(i).company;
+				for (int j = 0; j < com.size(); j++) {
+					if (com.get(j).name.equalsIgnoreCase(name)) {
+						score = score + Double.valueOf(twoDForm.format(com.get(j).sharevalue.get(com.get(j).sharevalue.size() - 1) * list.get(i).qty));
+						break;
+					}
+				}
+			}
+			return Double.valueOf(twoDForm.format(score));
+		}
+	}
+}
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/server/Server.java b/src/com/ayushmaanbhav/jstockmart/server/Server.java
new file mode 100644
index 0000000..7e13531
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/Server.java
@@ -0,0 +1,693 @@
+package com.ayushmaanbhav.jstockmart.server;
+
+import java.io.*;
+
+import javax.swing.*;
+
+import com.ayushmaanbhav.jstockmart.user.*;
+import com.ayushmaanbhav.jstockmart.utils.TrippleArrayList;
+
+import java.net.*;
+import java.util.*;
+import java.util.concurrent.*;
+
+public class Server {
+
+	private ServerSocket serverSocket;
+	private boolean started;
+	private Thread serverThread;
+	volatile int clientCount;
+	ChatServer chat;
+	static StringBuffer chatHist;
+	List companies;
+	List clientList;
+	volatile static int id = 0;
+
+	abstract class Thread1 extends Thread {
+		volatile protected User user;
+		abstract public void sendMessage(Object mess, int priority);
+	}
+
+	public Server(List comp) throws IOException {
+		companies = comp;
+		serverSocket = new ServerSocket(4446, 20000);
+		serverSocket.setReuseAddress(true);
+		chat = new ChatServer(this);
+		clientList = new ArrayList();
+		clientCount = 0;
+		chatHist = new StringBuffer();
+	}
+
+	// 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(50);
+							} catch (Exception n) {
+							}
+						} catch (SocketException e) {
+							System.err.println("Server closed.");
+						} catch (IOException e) {
+							System.err.println("Accept failed.");
+						}
+					}
+				}
+			};
+			serverThread.setPriority(7);
+			serverThread.start();
+			chat.start();
+		}
+	}
+
+	@SuppressWarnings("deprecation")
+	public void stopServer() {
+		this.started = false;
+		serverThread.interrupt();
+		try {
+			serverSocket.close();
+		} catch (IOException ex) {
+			System.err.println("Server stop failed.");
+		}
+		chat.stop();
+	}
+
+	synchronized public void sendMulti(String mess, int priority) {
+		String copy = new String(mess);
+		for (int i = 0; i < clientList.size(); i++) {
+			if (clientList.get(i).isAlive())
+				clientList.get(i).sendMessage(copy, priority);
+			else
+				clientList.remove(i--);
+		}
+	}
+
+	synchronized public void sendPeriodicStats(int priority) {
+		for (Company comp : ShareMarket.companies) {
+			Object message = new TrippleArrayList(Orders.getLimitOrderStatsOfCompany(comp.name));
+			for (int i = 0; i < clientList.size(); i++) {
+				if (clientList.get(i).isAlive() && clientList.get(i).user != null && clientList.get(i).user.sendStats != null && clientList.get(i).user.sendStats.equalsIgnoreCase(comp.name))
+					clientList.get(i).sendMessage(message, priority);
+			}
+		}
+	}
+
+	synchronized public void sendMessage(User user, int priority) {
+		for (int i = 0; i < clientList.size(); i++) {
+			if (clientList.get(i).user.checkName(user.getName())) {
+				if (clientList.get(i).isAlive())
+					clientList.get(i).sendMessage(new User(user), priority);
+				else
+					clientList.remove(i--);
+				break;
+			}
+		}
+	}
+
+	public void openClient(final Socket socket) {
+		clientCount++;
+		Thread1 g = new Thread1() {
+			BufferedWriter bw;
+			BufferedReader in;
+			ObjectOutputStream objout;
+			volatile protected boolean loggedIn = false;
+			Object obj = new Object();
+
+			public void run() {
+				user = null;
+				try {
+					in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+					objout = new ObjectOutputStream(socket.getOutputStream());
+					String inputLine = null;
+					do {
+						try {
+							inputLine = (String) in.readLine();
+						} catch (IOException e) {
+							break;
+						}
+						processCommand(inputLine);
+					} while (in != null && inputLine != null);
+					objout.close();
+					in.close();
+					socket.close();
+				} catch (Exception ex) {
+					ex.printStackTrace();
+				}
+			}
+
+			void processCommand(final String command1) {
+				final String cmdid = command1.split(";")[0];
+				String command = command1.toLowerCase().split(";")[1];
+				String cmmd[] = command.split(":");
+				for (int i = 0; i < cmmd.length; i++)
+					cmmd[i] = cmmd[i].trim();
+
+				if (cmmd[0].equals(Commands.REGISTER)) {
+					int res = UserDatabase.registerUser(cmmd[1], cmmd[2], cmmd[3]);
+					if (res == 1) {
+						synchronized (obj) {
+							try {
+								objout.writeObject(new String(cmdid));
+								objout.writeObject(new String("1:rs"));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+					} else {
+						synchronized (obj) {
+							try {
+								objout.writeObject(new String(cmdid));
+								objout.writeObject(new String(res + ":wrn"));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+					}
+					try {
+						in.close();
+						objout.close();
+						socket.close();
+						return;
+					} catch (Exception e) {
+						in = null;
+						objout = null;
+						return;
+					}
+				} else if (cmmd[0].equals(Commands.LOG_IN)) {
+					int res = UserDatabase.validate(cmmd[1], cmmd[2]);
+					if (res == 0 && !UserDatabase.getUser(cmmd[1], cmmd[2]).isBanned()) {
+						user = UserDatabase.getUser(cmmd[1], cmmd[2]);
+						loggedIn = true;
+						try {
+							bw = new BufferedWriter(new FileWriter("appdata/userdata/" + user.getName() + ".txt", true));
+						} catch (Exception mm) {
+						}
+						synchronized (obj) {
+							try {
+								objout.writeObject(new String(cmdid));
+								objout.writeObject(new String("0:s"));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+						try {
+							bw.write(new Date().toString() + ":loggedin\n");
+							bw.flush();
+						} catch (Exception mm) {
+							mm.printStackTrace();
+						}
+						BroadcastServer.sendFullDetails = true;
+					} else {
+						if (user != null) {
+							loggedIn = false;
+						}
+						synchronized (obj) {
+							try {
+								objout.writeObject(new String(cmdid));
+								objout.writeObject(new String(res + ":f"));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+						try {
+							in.close();
+							objout.close();
+							socket.close();
+							return;
+						} catch (Exception e) {
+							in = null;
+							objout = null;
+							return;
+						}
+					}
+				} else if (cmmd[0].equals(Commands.LOG_OUT)) {
+					if (user != null) {
+						loggedIn = false;
+					}
+					clientCount--;
+					clientList.remove(this);
+					synchronized (obj) {
+						try {
+							objout.writeObject(new String(cmdid));
+							objout.writeObject(new String("1"));
+							objout.flush();
+
+						} catch (Exception e) {
+						}
+					}
+					try {
+						bw.write(new Date().toString() + ":loggedout\n");
+						bw.flush();
+						bw.close();
+						bw = null;
+					} catch (Exception mm) {
+						mm.printStackTrace();
+					}
+					try {
+						in.close();
+						objout.close();
+						socket.close();
+						return;
+					} catch (Exception e) {
+						in = null;
+						objout = null;
+						return;
+					}
+				} else if (user != null && loggedIn && !user.isBanned()) {
+					if (cmmd[0].equals(Commands.GET_USER_DETAILS)) {
+						try {
+							synchronized (obj) {
+								try {
+									objout.writeObject(new String(cmdid));
+									objout.writeObject(new User(user));
+									objout.flush();
+
+									clientList.add(this);
+								} catch (Exception e) {
+									e.printStackTrace();
+								}
+							}
+						} catch (Exception e) {
+							e.printStackTrace();
+						}
+					} else if (cmmd[0].equals(Commands.SEND_CHAT_MESSAGE)) {
+						// System.out.println("got chat");
+						if (user.chatEnabled && user.getChat() >= 0) {
+							if (user.getChat() - command1.substring(command1.indexOf(":") + 1).length() >= 0) {
+								user.setChat(user.getChat() - command1.substring(command1.indexOf(":") + 1).length());
+								chatHist.append("<");
+								chatHist.append(user.getName());
+								chatHist.append("> : ");
+								chatHist.append(command1.substring(command1.indexOf(":") + 1));
+								chatHist.append("\n");
+								chat.chaat.append("<");
+								chat.chaat.append(user.getName());
+								chat.chaat.append("> : ");
+								chat.chaat.append(command1.substring(command1.indexOf(":") + 1));
+								chat.chaat.append("\n");;
+								new Thread() {
+									public void run() {
+										chat.interrupt();
+									}
+								}.start();
+								SwingUtilities.invokeLater(new Runnable() {
+									public void run() {
+										StockMart.chat.setText(chatHist.toString());
+									}
+								});
+							}
+						}
+						synchronized (obj) {
+							try {
+								objout.writeObject(new String(cmdid));
+								objout.writeObject(Integer.toString(user.getChat()));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+					} else if (cmmd[0].equals(Commands.GET_CHAT_HISTORY)) {
+						synchronized (obj) {
+							try {
+								objout.writeObject(new String(cmdid));
+								objout.writeObject(new String(chatHist.toString()));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+					} else if (cmmd[0].equals(Commands.SEND_FULL_BROADCAST)) {
+						synchronized (obj) {
+							try {
+								BroadcastServer.sendFullDetails = true;
+								objout.writeObject(new String(cmdid));
+								objout.writeObject(new String("1"));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+					} else if (cmmd[0].equals(Commands.SEND_PERIODIC_STATS)) {
+						try {
+							user.sendStats = cmmd[1].trim();
+							if (cmmd[1].trim().equals("-1"))
+								user.sendStats = null;
+						} catch (Exception e) {
+							e.printStackTrace();
+						}
+						synchronized (obj) {
+							try {
+								objout.writeObject(new String(cmdid));
+								objout.writeObject(new String("1"));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+					} else if (cmmd[0].equals(Commands.GET_COMPANY_STATS)) {
+						try {
+							TrippleArrayList arr = Orders.getLimitOrderStatsOfCompany(cmmd[1].trim());
+							if (user.sendStats != null)
+								user.sendStats = cmmd[1].trim();
+							synchronized (obj) {
+								try {
+									objout.writeObject(new String(cmdid));
+									objout.writeObject(new TrippleArrayList(arr));
+									objout.flush();
+								} catch (Exception e) {
+									e.printStackTrace();
+								}
+							}
+						} catch (Exception e) {
+							e.printStackTrace();
+						}
+					} else if (cmmd[0].equals(Commands.GET_COMPANY_HISTORY)) {
+						try {
+							Company comp = null;
+							for (int k = 0; k < companies.size(); k++) {
+								if (companies.get(k).name.equalsIgnoreCase(cmmd[1].trim())) {
+									comp = companies.get(k);
+									break;
+								}
+							}
+							if (comp != null && Integer.parseInt(cmmd[2].trim()) != comp.sharevalue.size()) {
+								synchronized (obj) {
+									try {
+										objout.flush();
+										objout.reset();
+										objout.writeObject(new String(cmdid));
+										ArrayList al = new ArrayList(comp.sharevalue);
+										objout.writeObject(al);
+										objout.flush();
+									} catch (Exception e) {
+										e.printStackTrace();
+									}
+								}
+							} else {
+								synchronized (obj) {
+									try {
+										objout.writeObject(new String(cmdid));
+										objout.writeObject(new ArrayList());
+										objout.flush();
+									} catch (Exception e) {
+										e.printStackTrace();
+									}
+								}
+							}
+						} catch (Exception e) {
+							e.printStackTrace();
+						}
+					} else if (StockMart.started) {
+						if (cmmd[0].equals(Commands.LIMIT_BUY_ORDER)) {
+							final Shares share = new Shares();
+							share.type = Orders.LIMIT_BUY_ORDER;
+							share.company = command1.split(":")[1].trim();
+							share.qty_limit = Integer.parseInt(cmmd[2]);
+							share.cost_limit = Double.parseDouble(cmmd[3]);
+							share.id = id++;
+							share.cost = -1.0;
+							share.sellid = -1;
+							share.buyed = null;
+							share.ordered = new Date();
+							share.status = "Shares Pending";
+							share.notCanceled = true;
+							share.user = user;
+
+							Orders.limitBuyOrders.add(share);
+
+							try {
+								user.getPendingShares().add(share);
+								synchronized (obj) {
+									try {
+										objout.writeObject(new String(cmdid));
+										objout.writeObject(share);
+										objout.flush();
+									} catch (Exception e) {
+										e.printStackTrace();
+									}
+								}
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+							try {
+								bw.write(new Date().toString() + ":buyl:" + share.id + ":" + share.company + ":" + share.qty_limit + ":" + share.cost_limit + ":" + share.status + "\n");
+								bw.flush();
+							} catch (Exception mm) {
+								mm.printStackTrace();
+							}
+						} else if (cmmd[0].equals(Commands.MARKET_BUY_ORDER)) {
+							final Shares share = new Shares();
+							share.type = Orders.MARKET_BUY_ORDER;
+							share.company = command1.split(":")[1].trim();
+							share.qty_limit = Integer.parseInt(cmmd[2]);
+							share.id = id++;
+							share.cost = -1.0;
+							share.sellid = -1;
+							share.buyed = null;
+							share.ordered = new Date();
+							share.status = "Shares Pending";
+							share.notCanceled = true;
+							share.user = user;
+
+							// System.out.println("made share");
+							Orders.marketBuyOrders.add(share);
+
+							try {
+								user.getPendingShares().add(share);
+								synchronized (obj) {
+									try {
+										objout.writeObject(new String(cmdid));
+										objout.writeObject(share);
+										objout.flush();
+										// System.out.println("sent share");
+									} catch (Exception e) {
+										e.printStackTrace();
+									}
+								}
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+							try {
+								bw.write(new Date().toString() + ":buym:" + share.id + ":" + share.company + ":" + share.qty_limit + ":" + share.cost_limit + ":" + share.status + "\n");
+								bw.flush();
+							} catch (Exception mm) {
+								mm.printStackTrace();
+							}
+						} else if (cmmd[0].equals(Commands.LIMIT_SELL_ORDER)) {
+							final Shares share = new Shares();
+							share.type = Orders.LIMIT_SELL_ORDER;
+							share.company = command1.split(":")[1].trim();
+							share.qty_limit = Integer.parseInt(cmmd[2]);
+							share.cost_limit = Double.parseDouble(cmmd[3]);
+							share.id = Integer.parseInt(cmmd[4]);
+							share.sellid = id++;
+							share.cost = -1.0;
+							share.ordered = new Date();
+							share.status = "Payment Pending";
+							share.notCanceled = true;
+							share.user = user;
+
+							Orders.limitSellOrders.add(share);
+
+							try {
+								user.getPendingShares().add(share);
+								synchronized (obj) {
+									try {
+										objout.writeObject(new String(cmdid));
+										objout.writeObject(share);
+										objout.flush();
+									} catch (Exception e) {
+										e.printStackTrace();
+									}
+								}
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+							try {
+								bw.write(new Date().toString() + ":selll:" + share.id + ":" + share.sellid + ":" + share.company + ":" + share.qty_limit + ":" + share.cost_limit + ":" + share.status + "\n");
+								bw.flush();
+							} catch (Exception mm) {
+								mm.printStackTrace();
+							}
+						} else if (cmmd[0].equals(Commands.MARKET_SELL_ORDER)) {
+							final Shares share = new Shares();
+							share.type = Orders.MARKET_SELL_ORDER;
+							share.company = command1.split(":")[1].trim();
+							share.qty_limit = Integer.parseInt(cmmd[2]);
+							share.id = Integer.parseInt(cmmd[4]);
+							share.sellid = id++;
+							share.cost = -1.0;
+							share.ordered = new Date();
+							share.status = "Payment Pending";
+							share.notCanceled = true;
+							share.user = user;
+
+							Orders.marketSellOrders.add(share);
+
+							try {
+								user.getPendingShares().add(share);
+								synchronized (obj) {
+									try {
+										objout.writeObject(new String(cmdid));
+										objout.writeObject(share);
+										objout.flush();
+									} catch (Exception e) {
+										e.printStackTrace();
+									}
+								}
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+							try {
+								bw.write(new Date().toString() + ":sellm:" + share.id + ":" + share.sellid + ":" + share.company + ":" + share.qty_limit + ":" + share.cost_limit + ":" + share.status + "\n");
+								bw.flush();
+							} catch (Exception mm) {
+								mm.printStackTrace();
+							}
+						} else if (cmmd[0].equals(Commands.CANCEL_ORDER)) {
+							try {
+								int id = Integer.parseInt(cmmd[1]);
+								int sellid = Integer.parseInt(cmmd[2]);
+								Shares sh = null;
+								for (int i = 0; i < user.getPendingShares().size(); i++) {
+									if (user.getPendingShares().get(i).id == id && user.getPendingShares().get(i).sellid == sellid) {
+										sh = user.getPendingShares().get(i);
+										break;
+									}
+								}
+
+								if (sh != null && Orders.contain(sh)) {
+									sh.notCanceled = false;
+									sh.status = "Cancelled";
+									Orders.remove(sh);
+
+									synchronized (obj) {
+										try {
+											objout.writeObject(new String(cmdid));
+											objout.writeObject(new String("1"));
+											objout.flush();
+
+										} catch (Exception e) {
+											e.printStackTrace();
+										}
+									}
+								} else {
+									synchronized (obj) {
+										try {
+											objout.writeObject(new String(cmdid));
+											objout.writeObject(new String("0"));
+											objout.flush();
+
+										} catch (Exception e) {
+											e.printStackTrace();
+										}
+									}
+								}
+
+								try {
+									bw.write(new Date().toString() + ":cancel:" + sh.id + ":" + sh.sellid + ":" + sh.company + ":" + sh.qty_limit + ":" + sh.cost_limit + ":" + sh.status + "\n");
+									bw.flush();
+								} catch (Exception mm) {
+									mm.printStackTrace();
+								}
+							} catch (Exception ef) {
+								ef.printStackTrace();
+							}
+						}
+					} else {
+						synchronized (obj) {
+							try {
+								objout.writeObject(new String(cmdid));
+								objout.writeObject(new String(Commands.SERVER_NOT_RUNNING));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+					}
+				} else {
+					clientCount--;
+					clientList.remove(this);
+					try {
+						loggedIn = false;
+						synchronized (obj) {
+							try {
+								System.out.println(command1);
+								objout.writeObject(new String(Commands.UNKNOWN_COMMAND));
+								objout.flush();
+							} catch (Exception e) {
+								e.printStackTrace();
+							}
+						}
+						in.close();
+						objout.close();
+						socket.close();
+						user = null;
+						return;
+					} catch (Exception e) {
+						in = null;
+						objout = null;
+						return;
+					}
+				}
+			}
+			boolean firsttime = true;
+			BlockingQueue toSend = new LinkedBlockingQueue();
+			Thread sender;
+			public void sendMessage(Object mess, int priority) {
+				try {
+					sender.setPriority(priority);
+				} catch (Exception m) {
+				}
+				toSend.offer(mess);
+				// System.out.println("offered: " + mess.toString());
+				if (firsttime && loggedIn) {
+					sender = new Thread() {
+						public void run() {
+							while (loggedIn) {
+								Object object = null;
+								try {
+									object = toSend.take();
+								} catch (Exception e) {
+									e.printStackTrace();
+								}
+								if (object != null) {
+									synchronized (obj) {
+										try {
+											objout.writeObject(object);
+											objout.flush();
+										} catch (Exception e) {
+											e.printStackTrace();
+										}
+									}
+								}
+								try {
+									Thread.sleep(100);
+								} catch (Exception e) {
+									e.printStackTrace();
+								}
+							}
+						}
+					};
+					sender.setPriority(Thread.NORM_PRIORITY);
+					sender.start();
+					firsttime = false;
+				}
+			}
+		};
+		g.setPriority(Thread.NORM_PRIORITY);
+		g.start();
+	}
+}
\ No newline at end of file
diff --git a/src/com/ayushmaanbhav/jstockmart/server/ShareMarket.java b/src/com/ayushmaanbhav/jstockmart/server/ShareMarket.java
new file mode 100644
index 0000000..9ab7675
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/ShareMarket.java
@@ -0,0 +1,172 @@
+package com.ayushmaanbhav.jstockmart.server;
+
+import java.util.*;
+import java.io.*;
+import java.text.*;
+
+import javax.swing.*;
+
+class ShareMarket {
+	volatile static List companies;
+	static Server server;
+	BroadcastServer bserver;
+	RankingServer rserver;
+	volatile static double sensex;
+	boolean testing = false;
+	Orders orderbook;
+	Thread calculations;
+	final int SLEEP = 30000;
+	volatile int loopp = 1;
+	static DecimalFormat twoDForm = new DecimalFormat("#.##");
+	BufferedWriter bw;
+	double T, N;
+
+	void initialise() {
+		companies = new ArrayList();
+		loadCompanies();
+		UserDatabase.loadList();
+		try {
+			bw = new BufferedWriter(new FileWriter("appdata/sharemarket.txt"));
+		} catch (Exception mm) {
+		}
+	}
+
+	void startApp() {
+		orderbook = new Orders();
+		try {
+			bw.write(new Date().toString() + ":app started\n");
+			bw.flush();
+		} catch (Exception mm) {
+			mm.printStackTrace();
+		}
+		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() {
+		try {
+			bw.write(new Date().toString() + ":market started\n");
+			bw.flush();
+		} catch (Exception mm) {
+			mm.printStackTrace();
+		}
+		loopp = 0;
+		bserver.start();
+		bserver.queue.clear();
+		bserver.queue.offer(loopp);
+		RankingServer.startWaiting = true;
+		calculations = new Thread() {
+			public void run() {
+				T = StockMart.totTime;
+				N = (int) (T * 2);
+				SwingUtilities.invokeLater(new Runnable() {
+					public void run() {
+						try {
+							StockMart.updateCompanyTable();
+							/*
+							 * if(GraphPanel.frame.isVisible())
+							 * GraphPanel.mainPanel.repaint();
+							 */
+						} catch (Exception r) {
+							r.printStackTrace();
+						}
+					}
+				});
+				while (StockMart.started) {
+					try {
+						Thread.sleep(SLEEP);
+					} catch (Exception mm) {
+					}
+					Orders.calculateLimitOrderStats();
+					if (testing)
+						Orders.printQueues();
+					synchronized (companies) {
+						MatchingEngine.matchOrders();
+					}
+					bserver.queue.offer(++loopp);
+					rserver.queue.offer(loopp);
+					SwingUtilities.invokeLater(new Runnable() {
+						public void run() {
+							try {
+								StockMart.updateCompanyTable();
+								if (GraphPanel.frame.isVisible())
+									GraphPanel.mainPanel.repaint();
+								if (HistogramPanel.frame.isVisible())
+									HistogramPanel.mainPanel.updatePanel();
+							} catch (Exception r) {
+								r.printStackTrace();
+							}
+						}
+					});
+					for (int i = 0; i < companies.size(); i++) {
+						companies.get(i).updateFile();
+					}
+				}
+			}
+		};
+		calculations.setPriority(Thread.MAX_PRIORITY);
+		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]),Double.parseDouble(s[3]),Double.parseDouble(s[4])));
+				companies.add(new Company(s[0], l, 0, 0, 0.0005, 0.03162277660168379331998893544433));
+			}
+			br.close();
+		} catch (Exception m) {
+			m.printStackTrace();
+		}
+	}
+
+	@SuppressWarnings("deprecation")
+	void stop() {
+		try {
+			bw.write(new Date().toString() + ":market stopped\n");
+			bw.flush();
+		} catch (Exception mm) {
+			mm.printStackTrace();
+		}
+		try {
+			server.stopServer();
+		} catch (Exception m) {
+		}
+		try {
+			bserver.close = 1;
+			bserver.queue.offer(loopp);
+		} catch (Exception m) {
+		}
+		try {
+			RankingServer.startWaiting = false;
+			rserver.close = 1;
+			rserver.queue.offer(1);
+		} catch (Exception m) {
+		}
+		try {
+			calculations.stop();
+		} catch (Exception m) {
+		}
+	}
+}
diff --git a/src/com/ayushmaanbhav/jstockmart/server/StockMart.java b/src/com/ayushmaanbhav/jstockmart/server/StockMart.java
new file mode 100644
index 0000000..cac3504
--- /dev/null
+++ b/src/com/ayushmaanbhav/jstockmart/server/StockMart.java
@@ -0,0 +1,513 @@
+package com.ayushmaanbhav.jstockmart.server;
+
+import javax.swing.*;
+import javax.swing.table.*;
+
+import com.ayushmaanbhav.jstockmart.user.*;
+import com.ayushmaanbhav.jstockmart.utils.LookAndFeel;
+
+import java.awt.*;
+import java.awt.event.*;
+import java.text.*;
+import java.util.Date;
+
+class StockMart {
+	static JPanel puser, mpanel;
+	static JLabel userd, sensex;
+	static JTextArea chat, ranks, news;
+	static JScrollPane jkps;
+	static JTable usertable, comptable;
+	static DefaultTableModel dtmu, dtmc;
+	static JTextField cht, ucht, addmoney, tt;
+	static JCheckBox chatEnabled;
+	@SuppressWarnings("rawtypes")
+	static JComboBox users;
+	static JFrame jf;
+	static String newsfeed = "";
+	static ShareMarket shr;
+	static JButton server, post, changep, banu, checkRN;
+	static String colusr[] = new String[]{"SrNo.", "Company", "Price (Limit)", "Quantity (Limit)", "Ordered/Buyed", "Mkt Value/Type", "Status", "Gain/Loss"};
+	static String[] columnNames2 = {"Srno.", "Company", "C.M.P.", "%Change", "Low", "High", "Stock Traded", "Total Stock Traded", "Total Stock"};
+	static DecimalFormat twoDForm = new DecimalFormat("#.##");
+	static boolean started = false, checkRegNo = true;
+	static int totTime;
+	static User uuu;
+	static Date startDate;
+	@SuppressWarnings("serial")
+	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 (hrs <= 0 && mins <= 0) {
+					started = false;
+					server.setText("Start");
+					// shr.stop();
+					timer2.stop();
+					finalize1();
+				}
+			} catch (Exception bb) {
+			}
+		}
+	});
+	static Timer timer = new Timer(10000, new ActionListener() {
+		public void actionPerformed(ActionEvent e) {
+			try {
+				uuu = UserDatabase.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 User"); + else + banu.setText("Unban User"); + refreshUserTable(uuu); + } catch (Exception n) { + users.removeItem((String) users.getSelectedItem()); + } + } + }); + + public static void refreshUserTable(User u) { + Object obj[][] = new Object[u.getCurrentShares().size() + u.getPendingShares().size() + 1][8]; + java.util.List ss = u.getCurrentShares(); + for (int i = 0; i < u.getCurrentShares().size(); i++) { + Company comp = null; + for (int j = 0; j < ShareMarket.companies.size(); j++) { + if (ShareMarket.companies.get(j).name.equals(ss.get(i).company)) { + comp = ShareMarket.companies.get(j); + break; + } + } + obj[i] = new Object[]{Integer.toString(i + 1), ss.get(i).company, twoDForm.format(ss.get(i).cost), ss.get(i).qty, String.valueOf((ss.get(i).buyed.getTime() - startDate.getTime()) / 60000) + " mins", twoDForm.format(ss.get(i).qty * comp.sharevalue.get(comp.sharevalue.size() - 1)), ss.get(i).status, twoDForm.format(ss.get(i).qty * comp.sharevalue.get(comp.sharevalue.size() - 1) - ss.get(i).qty * ss.get(i).cost)}; + } + obj[u.getCurrentShares().size()] = new Object[]{null, null, null, null, null, null, null, null}; + ss = u.getPendingShares(); + for (int i = 0; i < u.getPendingShares().size(); i++) { + String type = "", costLimit = "Not Applicable"; + switch (ss.get(i).type) { + case Orders.MARKET_BUY_ORDER : + type = "Market Buy Order"; + break; + case Orders.MARKET_SELL_ORDER : + type = "Market Sell Order"; + break; + case Orders.LIMIT_BUY_ORDER : + type = "Limit Buy Order"; + costLimit = String.valueOf(ss.get(i).cost_limit); + break; + case Orders.LIMIT_SELL_ORDER : + type = "Limit Sell Order"; + costLimit = String.valueOf(ss.get(i).cost_limit); + break; + } + obj[i + u.getCurrentShares().size() + 1] = new Object[]{Integer.toString(i + 1), ss.get(i).company, costLimit, ss.get(i).qty_limit, String.valueOf((ss.get(i).ordered.getTime() - startDate.getTime()) / 60000) + " mins", type, ss.get(i).status, null}; + } + dtmu.setDataVector(obj, colusr); + } + + public static void updateCompanyTable() { + try { + Object data[][] = new Object[ShareMarket.companies.size()][9]; + for (int i = 0; i < ShareMarket.companies.size(); i++) { + data[i] = new Object[]{Integer.toString(i + 1), ShareMarket.companies.get(i).name, twoDForm.format(ShareMarket.companies.get(i).sharevalue.get(ShareMarket.companies.get(i).sharevalue.size() - 1)), twoDForm.format(ShareMarket.companies.get(i).perchange), twoDForm.format(ShareMarket.companies.get(i).getLowest()), twoDForm.format(ShareMarket.companies.get(i).getHighest()), ShareMarket.companies.get(i).sharessoldpast, ShareMarket.companies.get(i).tsharessold, ShareMarket.companies.get(i).totalshares}; + } + dtmc.setDataVector(data, columnNames2); + comptable.getColumnModel().getColumn(3).setCellRenderer(dtr); + comptable.repaint(); + } catch (Exception mm) { + mm.printStackTrace(); + } + } + + public static void main(String args[]) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + initialise(); + shr = new ShareMarket(); + shr.initialise(); + shr.startApp(); + timer.start(); + server.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (!started) { + started = true; + startDate = new Date(); + totTime = Integer.parseInt(tt.getText()); + server.setText("Stop"); + shr.start(); + timer2.start(); + GraphPanel.main(); + HistogramPanel.main(); + OrdersPanel.main(); + } else { + started = false; + server.setText("Start"); + // shr.stop(); + timer2.stop(); + finalize1(); + // GraphPanel.frame.setVisible(false); + } + } + }); + } + }); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static void finalize1() { + new Thread() { + public void run() { + shr.rserver.rankUsers(); + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + final JDialog jd = new JDialog(); + jd.setTitle("Confirm Final Rankings"); + jd.setUndecorated(false); + final JComboBox j1 = new JComboBox(), j2 = new JComboBox(), j3 = new JComboBox(); + for (int i = UserDatabase.userList.size() - 1; i >= 0; i--) { + j1.addItem(UserDatabase.userList.get(i).getName()); + j2.addItem(UserDatabase.userList.get(i).getName()); + j3.addItem(UserDatabase.userList.get(i).getName()); + } + try { + j1.setSelectedIndex(0); + j2.setSelectedIndex(1); + j3.setSelectedIndex(2); + } catch (Exception n) { + } + JPanel pan2 = new JPanel(new BorderLayout()); + pan2.add(j1, BorderLayout.NORTH); + pan2.add(j2, BorderLayout.CENTER); + pan2.add(j3, BorderLayout.SOUTH); + JLabel label = new JLabel("Confirm final rankings to send to users:"); + JPanel pan = new JPanel(new BorderLayout()); + pan.add(label, BorderLayout.NORTH); + pan.add(pan2, BorderLayout.CENTER); + JButton ok = new JButton("Ok"), can = new JButton("Cancel"); + ok.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + ShareMarket.server.sendMulti(Commands.FINAL_RANKINGS + "::" + j1.getSelectedItem() + ":" + j2.getSelectedItem() + ":" + j3.getSelectedItem(), Thread.MIN_PRIORITY); + jd.setVisible(false); + } + }); + can.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + jd.setVisible(false); + } + }); + JPanel pan3 = new JPanel(new BorderLayout()); + pan3.add(can, BorderLayout.EAST); + pan3.add(ok, BorderLayout.WEST); + pan.add(pan3, BorderLayout.SOUTH); + jd.setContentPane(pan); + jd.setModalityType(JDialog.ModalityType.APPLICATION_MODAL); + jd.pack(); + jd.setLocationRelativeTo(null); + jd.setVisible(true); + } + }); + } + }.start(); + } + + @SuppressWarnings({"rawtypes", "serial"}) + public static void initialise() { + LookAndFeel.set(); + jf = new JFrame("StockMart"); + jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + mpanel = (JPanel) jf.getContentPane(); + mpanel.setLayout(new BorderLayout()); + post = new JButton("Post"); + post.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + newsfeed = news.getText().trim().replace("\n", ":"); + ShareMarket.server.chat.interrupt(); + } catch (Exception ppp) { + } + } + }); + server = new JButton("Start"); + userd = new JLabel("User-> 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("Calibri", Font.PLAIN, 14)); + 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("Calibri", Font.PLAIN, 14)); + ranks.setLineWrap(true); + cht = new JTextField(30); + ucht = new JTextField(10); + addmoney = new JTextField(10); + 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) { new Thread() { + * public void run() { try { if (JOptionPane.showConfirmDialog(jf, + * "Are you sure ?", "Confirm Value Change", JOptionPane.YES_NO_OPTION) + * == JOptionPane.YES_OPTION) + * ShareMarket.companies.get(row).futurevalues.add(0, + * Double.parseDouble( + * twoDForm.format(Double.valueOf(dtmc.getValueAt(row, + * 2).toString())))); } catch (Exception m) { m.printStackTrace(); } } + * }.start(); } } 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.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + 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)); + jkps = new JScrollPane(ranks, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + rr.add(jkps, 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 User"); + JButton deleteu = new JButton("Delete User"); + + JPanel jpaa = new JPanel(); + jpaa.setLayout(new FlowLayout(FlowLayout.LEFT)); + jpaa.add(changep); + jpaa.add(banu); + jpaa.add(deleteu); + jpaa.add(ucht); + jpaa.add(addmoney); + + JPanel jp = new JPanel(); + jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS)); // + // jp.setAlignmentX( Component.LEFT_ALIGNMENT ); + userd.setAlignmentX(Component.LEFT_ALIGNMENT); + users.setAlignmentX(Component.LEFT_ALIGNMENT); + jpaa.setAlignmentX(Component.LEFT_ALIGNMENT); + chatEnabled.setAlignmentX(Component.LEFT_ALIGNMENT); + jspu.setAlignmentX(Component.LEFT_ALIGNMENT); + 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); + + checkRN = new JButton("UNCHKRegNo"); + checkRN.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + checkRegNo = !checkRegNo; + if (checkRegNo) + checkRN.setText("UNCHKRegNo"); + else + checkRN.setText("CHKRegNo"); + } catch (Exception jj) { + } + } + }); + JButton openGraphPanel = new JButton("Graph Panel"); + openGraphPanel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + if (started) + GraphPanel.frame.setVisible(true); + } catch (Exception jj) { + } + } + }); + JButton openHistogramPanel = new JButton("Histogram"); + openHistogramPanel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + if (started) + HistogramPanel.frame.setVisible(true); + } catch (Exception jj) { + } + } + }); + JButton openOrders = new JButton("Orders"); + openOrders.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + if (started) + OrdersPanel.frame.setVisible(true); + } catch (Exception jj) { + } + } + }); + + JPanel uu3 = new JPanel(new FlowLayout()); + uu3.add(openGraphPanel); + uu3.add(openHistogramPanel); + uu3.add(openOrders); + uu3.add(checkRN); + uu3.add(server); + + JPanel uu = new JPanel(new BorderLayout()); + uu.add(tt, BorderLayout.WEST); + uu.add(sensex, BorderLayout.CENTER); + uu.add(uu3, 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) { + } + } + }); + addmoney.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + new Thread() { + public void run() { + try { + int response = JOptionPane.showConfirmDialog(jf, "For only this user: " + uuu.getName() + "(YES) or to all users(NO) or cancel(CANCEL) ?", "Confirm Value Change", JOptionPane.YES_NO_CANCEL_OPTION); + if (response == JOptionPane.YES_OPTION) + uuu.setCurrentMoney(uuu.getCurrentMoney() + Integer.parseInt(addmoney.getText().trim())); + else if (response == JOptionPane.NO_OPTION) { + int mm = Integer.parseInt(addmoney.getText().trim()); + for (int l = 0; l < UserDatabase.userList.size(); l++) + UserDatabase.userList.get(l).setCurrentMoney(UserDatabase.userList.get(l).getCurrentMoney() + mm); + } + } catch (Exception m) { + m.printStackTrace(); + } + } + }.start(); + try { + uuu.setCurrentMoney(uuu.getCurrentMoney() + 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) { + } + } + }); + deleteu.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + UserDatabase.deleteUser(uuu); + } 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 { + Server.chatHist.append(" : "); + Server.chatHist.append(cht.getText()); + Server.chatHist.append("\n"); + ShareMarket.server.chat.chaat.append(" : "); + ShareMarket.server.chat.chaat.append(cht.getText()); + ShareMarket.server.chat.chaat.append("\n"); + chat.setText(Server.chatHist.toString()); + cht.setText(""); + new Thread() { + public void run() { + ShareMarket.server.chat.interrupt(); + } + }.start(); + } catch (Exception jj) { + } + } + }); + jf.pack(); + jf.setVisible(true); + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/server/UserDatabase.java b/src/com/ayushmaanbhav/jstockmart/server/UserDatabase.java new file mode 100644 index 0000000..e42176e --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/server/UserDatabase.java @@ -0,0 +1,159 @@ +package com.ayushmaanbhav.jstockmart.server; +import java.util.*; +import java.io.*; + +import javax.swing.*; + +import com.ayushmaanbhav.jstockmart.user.*; +class UserDatabase { + volatile static protected List userList; + static protected List regno; + private static double money; + + 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); + } + br.close(); + } catch (Exception m) { + m.printStackTrace(); + } + + try { + BufferedReader br = new BufferedReader(new FileReader("money.txt")); + money = Double.parseDouble(ShareMarket.twoDForm.format(Double.parseDouble(br.readLine()))); + br.close(); + } catch (Exception e) { + } + } + + static void deleteUser(final User ur) { + for (int i = 0; i < userList.size(); i++) { + if (userList.get(i).checkName(ur.getName())) { + userList.remove(i); + break; + } + } + } + + static int registerUser(final String regno, final String name, String pass) { + boolean b = true; + synchronized (userList) { + if (StockMart.checkRegNo) { + b = false; + if (containsRegNo(regno)) + b = true; + } + if (b) { + for (int i = 0; i < userList.size(); i++) { + if (userList.get(i).checkName(name)) + if (userList.get(i).checkRegNo(regno)) + return 4; + else + return 3; + } + User temp = new User(regno, name, pass, 1000, money); + UserSharesManager.allotInitialShares(temp); + userList.add(temp); + temp = null; + SwingUtilities.invokeLater(new Runnable() { + @SuppressWarnings("unchecked") + public void run() { + StockMart.users.addItem(name); + } + }); + return 1; + } + return 2; + } + } + + static boolean containsRegNo(String reg) { + for (int i = 0; i < regno.size(); i++) { + if (regno.get(i).equals(reg)) + return true; + } + return false; + } + + static User getUserWithRegNo(String r) { + synchronized (userList) { + for (int i = 0; i < userList.size(); i++) { + if (userList.get(i).checkRegNo(r)) { + return userList.get(i); + } + } + } + return null; + } + + static User getUserWithName(String n) { + synchronized (userList) { + for (int i = 0; i < userList.size(); i++) { + if (userList.get(i).checkName(n)) { + return userList.get(i); + } + } + } + return null; + } + + static int validate(String n, String p) { + synchronized (userList) { + User user; + int value = 1; + try { + for (int i = 0; i < userList.size(); i++) { + user = userList.get(i); + if (user.isBanned()) + return 11; + if (user.checkName(n)) { + value = 2; + if (user.checkPassword(p)) { + return 0; + } + } + } + } catch (Exception e) { + } + return value; + } + } + + static User getUser(String n, String p) { + synchronized (userList) { + User user; + try { + for (int i = 0; i < userList.size(); i++) { + user = userList.get(i); + if (user.checkName(n)) { + if (user.checkPassword(p)) { + return user; + } + } + } + } catch (Exception e) { + } + } + return null; + } + + static User deleteUserWithName(String n) { + synchronized (userList) { + for (int i = 0; i < userList.size(); i++) { + if (userList.get(i).checkName(n)) { + User uu = userList.get(i); + userList.remove(i); + return uu; + } + } + } + return null; + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/server/UserSharesManager.java b/src/com/ayushmaanbhav/jstockmart/server/UserSharesManager.java new file mode 100644 index 0000000..e46f2a7 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/server/UserSharesManager.java @@ -0,0 +1,38 @@ +package com.ayushmaanbhav.jstockmart.server; + +import java.util.Date; + +import com.ayushmaanbhav.jstockmart.user.Shares; +import com.ayushmaanbhav.jstockmart.user.User; +import com.ayushmaanbhav.jstockmart.utils.RandomGenerator; + +public class UserSharesManager { + static void allotInitialShares(User user) { + int size = ShareMarket.companies.size(); + if (size > 1) { + double limit = user.getCurrentMoney(); + RandomGenerator rg = new RandomGenerator(size); + double limitpercomp = (limit * 2) / size; + for (int i = 0; i < size / 2; i++) { + int index = rg.generateRandom(); + Company comp = ShareMarket.companies.get(index); + double mktvalue = comp.sharevalue.get(comp.sharevalue.size() - 1); + int noofshares = (int) (limitpercomp / mktvalue); + Shares share = new Shares(); + share.buyed = new Date(); + share.id = Server.id++; + share.type = Orders.MARKET_BUY_ORDER; + share.company = comp.name; + share.cost = mktvalue; + share.qty = noofshares; + share.status = "Initial Shares"; + user.getCurrentShares().add(share); + limit -= share.cost * share.qty; + comp.totalshares += share.qty; + } + user.setCurrentMoney(user.getCurrentMoney() + limit); + } else { + System.err.println("Companies not loaded !!"); + } + } +} diff --git a/src/com/ayushmaanbhav/jstockmart/user/Commands.java b/src/com/ayushmaanbhav/jstockmart/user/Commands.java new file mode 100644 index 0000000..51bfe73 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/user/Commands.java @@ -0,0 +1,32 @@ +package com.ayushmaanbhav.jstockmart.user; + +public class Commands { + // client commands + public static final String LOG_IN = "login"; + public static final String REGISTER = "reg"; + public static final String LOG_OUT = "logout"; + public static final String GET_USER_DETAILS = "gud"; + public static final String SEND_CHAT_MESSAGE = "chat"; + public static final String GET_CHAT_HISTORY = "chath"; + public static final String BUY = "buy"; + public static final String SELL = "sell"; + public static final String LIMIT_ORDER = "limit"; + public static final String MARKET_ORDER = "market"; + public static final String MARKET_BUY_ORDER = BUY + MARKET_ORDER; + public static final String MARKET_SELL_ORDER = SELL + MARKET_ORDER; + public static final String LIMIT_BUY_ORDER = BUY + LIMIT_ORDER; + public static final String LIMIT_SELL_ORDER = SELL + LIMIT_ORDER; + public static final String CANCEL_ORDER = "cancel"; + public static final String GET_COMPANY_HISTORY = "getch"; + public static final String GET_COMPANY_STATS = "getcs"; + public static final String SEND_PERIODIC_STATS = "sendps"; + public static final String SEND_FULL_BROADCAST = "sendfb"; + + // server commands + public static final String BROADCAST = "broadcast"; + public static final String CHAT_AND_NEWS = "chat"; + public static final String FINAL_RANKINGS = "rankings"; + public static final String RANKS = "rank"; + public static final String UNKNOWN_COMMAND = "-101"; + public static final String SERVER_NOT_RUNNING = "-102"; +} diff --git a/src/com/ayushmaanbhav/jstockmart/user/Shares.java b/src/com/ayushmaanbhav/jstockmart/user/Shares.java new file mode 100644 index 0000000..31334be --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/user/Shares.java @@ -0,0 +1,66 @@ +package com.ayushmaanbhav.jstockmart.user; + +import java.io.*; +import java.util.*; + +public class Shares implements Serializable { + private static final long serialVersionUID = 1L; + volatile public String company, status; + volatile public int type, qty_limit; + volatile public double cost_limit; + volatile public int qty, id, buyid, sellid; + volatile public double cost; + public Date ordered, buyed; + public User user; + volatile public boolean notCanceled; + + public Shares() { + company = null; + status = null; + qty = 0; + type = -1; + cost_limit = 0; + qty_limit = 0; + id = -1; + user = null; + sellid = -1; + buyid = -1; + cost = 0.0; + ordered = null; + buyed = null; + notCanceled = true; + } + + public Shares(Shares s) { + try { + company = new String(s.company); + } catch (Exception k) { + company = null; + } + try { + status = new String(s.status); + } catch (Exception k) { + status = null; + } + qty = s.qty; + user = s.user; + id = s.id; + cost_limit = s.cost_limit; + type = s.type; + qty_limit = s.qty_limit; + buyid = s.buyid; + sellid = s.sellid; + cost = s.cost; + try { + ordered = (Date) s.ordered.clone(); + } catch (Exception k) { + ordered = null; + } + try { + buyed = (Date) s.buyed.clone(); + } catch (Exception k) { + buyed = null; + } + notCanceled = s.notCanceled; + } +} diff --git a/src/com/ayushmaanbhav/jstockmart/user/User.java b/src/com/ayushmaanbhav/jstockmart/user/User.java new file mode 100644 index 0000000..ccd0e2e --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/user/User.java @@ -0,0 +1,206 @@ +package com.ayushmaanbhav.jstockmart.user; + +import java.io.*; +import java.util.*; +import javax.swing.*; + +public class User implements Serializable { + private static final long serialVersionUID = 1L; + 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; + volatile public String sendStats; + volatile public double score; + + public User(String r, String n, String p, int c, double money) { + chat = c; + name = n; + regno = r; + score = 0; + chatEnabled = true; + banned = false; + sendStats = null; + password = p; + udcl = null; + shares = new ArrayList(); + pendingshares = new ArrayList(); + // history=new ArrayList(); + this.money = money; + u = this; + } + + public User(User user) { + name = new String(user.getName()); + regno = new String(user.getRegNo()); + password = new String(user.getPassword()); + loggedin = user.isLoggedIn(); + money = user.getCurrentMoney(); + shares = new ArrayList(); + pendingshares = new ArrayList(); + for (int i = 0; i < user.getCurrentShares().size(); i++) + shares.add(new Shares(user.getCurrentShares().get(i))); + for (int i = 0; i < user.getPendingShares().size(); i++) + pendingshares.add(new Shares(user.getPendingShares().get(i))); + udcl = null; + sendStats = user.sendStats; + score = user.score; + chat = user.getChat(); + chatEnabled = user.chatEnabled; + banned = user.banned; + u = this; + } + + public void setChat(int c) { + chat = c; + } + + public void setBanned(boolean c) { + banned = c; + } + + public boolean isBanned() { + return banned; + } + + public double getScore() { + return score; + } + + 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; + banned = user.banned; + sendStats = user.sendStats; + score = user.score; + 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 void setScore(double sc) { + score = sc; + } + + 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/com/ayushmaanbhav/jstockmart/user/UserDataChangedListener.java similarity index 67% rename from src/user/UserDataChangedListener.java rename to src/com/ayushmaanbhav/jstockmart/user/UserDataChangedListener.java index b368307..7a57b60 100644 --- a/src/user/UserDataChangedListener.java +++ b/src/com/ayushmaanbhav/jstockmart/user/UserDataChangedListener.java @@ -1,4 +1,4 @@ -package user; +package com.ayushmaanbhav.jstockmart.user; public interface UserDataChangedListener { diff --git a/src/com/ayushmaanbhav/jstockmart/utils/ButtonColumn.java b/src/com/ayushmaanbhav/jstockmart/utils/ButtonColumn.java new file mode 100644 index 0000000..0801bf1 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/utils/ButtonColumn.java @@ -0,0 +1,198 @@ +package com.ayushmaanbhav.jstockmart.utils; + +import java.awt.*; +import java.awt.event.*; + +import javax.swing.*; +import javax.swing.border.*; +import javax.swing.table.*; + +/** + * The ButtonColumn class provides a renderer and an editor that looks like a + * JButton. The renderer and editor will then be used for a specified column in + * the table. The TableModel will contain the String to be displayed on the + * button. + * + * The button can be invoked by a mouse click or by pressing the space bar when + * the cell has focus. Optionally a mnemonic can be set to invoke the button. + * When the button is invoked the provided Action is invoked. The source of the + * Action will be the table. The action command will contain the model row + * number of the button that was clicked. + * + */ +@SuppressWarnings("serial") +public class ButtonColumn extends AbstractCellEditor implements TableCellRenderer, TableCellEditor, ActionListener, MouseListener { + private JTable table; + private Action action; + private int mnemonic; + private Border originalBorder; + private Border focusBorder; + + private JButton renderButton; + private JButton editButton; + private Object editorValue; + private boolean isButtonColumnEditor; + + /** + * Create the ButtonColumn to be used as a renderer and editor. The renderer + * and editor will automatically be installed on the TableColumn of the + * specified column. + * + * @param table + * the table containing the button renderer/editor + * @param action + * the Action to be invoked when the button is invoked + * @param column + * the column to which the button renderer/editor is added + */ + public ButtonColumn(JTable table, Action action, int column) { + this.table = table; + this.action = action; + + renderButton = new JButton(); + editButton = new JButton(); + editButton.setFocusPainted(false); + editButton.addActionListener(this); + originalBorder = editButton.getBorder(); + setFocusBorder(new LineBorder(Color.GRAY)); + + TableColumnModel columnModel = table.getColumnModel(); + columnModel.getColumn(column).setCellRenderer(this); + columnModel.getColumn(column).setCellEditor(this); + table.addMouseListener(this); + } + + /** + * Get foreground color of the button when the cell has focus + * + * @return the foreground color + */ + public Border getFocusBorder() { + return focusBorder; + } + + /** + * The foreground color of the button when the cell has focus + * + * @param focusBorder + * the foreground color + */ + public void setFocusBorder(Border focusBorder) { + this.focusBorder = focusBorder; + editButton.setBorder(focusBorder); + } + + public int getMnemonic() { + return mnemonic; + } + + /** + * The mnemonic to activate the button when the cell has focus + * + * @param mnemonic + * the mnemonic + */ + public void setMnemonic(int mnemonic) { + this.mnemonic = mnemonic; + renderButton.setMnemonic(mnemonic); + editButton.setMnemonic(mnemonic); + } + + @Override + public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { + if (value == null) { + editButton.setText(""); + editButton.setIcon(null); + } else if (value instanceof Icon) { + editButton.setText(""); + editButton.setIcon((Icon) value); + } else { + editButton.setText(value.toString()); + editButton.setIcon(null); + } + + this.editorValue = value; + return editButton; + } + + @Override + public Object getCellEditorValue() { + return editorValue; + } + + // + // Implement TableCellRenderer interface + // + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + if (isSelected) { + renderButton.setForeground(table.getSelectionForeground()); + renderButton.setBackground(table.getSelectionBackground()); + } else { + renderButton.setForeground(table.getForeground()); + renderButton.setBackground(UIManager.getColor("Button.background")); + } + + if (hasFocus) { + renderButton.setBorder(focusBorder); + } else { + renderButton.setBorder(originalBorder); + } + + // renderButton.setText( (value == null) ? "" : value.toString() ); + if (value == null) { + renderButton.setText(""); + renderButton.setIcon(null); + } else if (value instanceof Icon) { + renderButton.setText(""); + renderButton.setIcon((Icon) value); + } else { + renderButton.setText(value.toString()); + renderButton.setIcon(null); + } + + return renderButton; + } + + // + // Implement ActionListener interface + // + /* + * The button has been pressed. Stop editing and invoke the custom Action + */ + public void actionPerformed(ActionEvent e) { + int row = table.convertRowIndexToModel(table.getEditingRow()); + fireEditingStopped(); + + // Invoke the Action + + ActionEvent event = new ActionEvent(table, ActionEvent.ACTION_PERFORMED, "" + row); + action.actionPerformed(event); + } + + // + // Implement MouseListener interface + // + /* + * When the mouse is pressed the editor is invoked. If you then then drag + * the mouse to another cell before releasing it, the editor is still + * active. Make sure editing is stopped when the mouse is released. + */ + public void mousePressed(MouseEvent e) { + if (table.isEditing() && table.getCellEditor() == this) + isButtonColumnEditor = true; + } + + public void mouseReleased(MouseEvent e) { + if (isButtonColumnEditor && table.isEditing()) + table.getCellEditor().stopCellEditing(); + + isButtonColumnEditor = false; + } + + public void mouseClicked(MouseEvent e) { + } + public void mouseEntered(MouseEvent e) { + } + public void mouseExited(MouseEvent e) { + } +} diff --git a/src/com/ayushmaanbhav/jstockmart/utils/HintPasswordField.java b/src/com/ayushmaanbhav/jstockmart/utils/HintPasswordField.java new file mode 100644 index 0000000..c84a15d --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/utils/HintPasswordField.java @@ -0,0 +1,38 @@ +package com.ayushmaanbhav.jstockmart.utils; + +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; + +import javax.swing.*; + +@SuppressWarnings("serial") +public class HintPasswordField extends JPasswordField implements FocusListener { + + private final String hint; + + public HintPasswordField(final String hint) { + super(hint); + this.hint = hint; + super.addFocusListener(this); + } + + @Override + public void focusGained(FocusEvent e) { + if (this.getText().isEmpty()) { + super.setText(""); + } + } + @Override + public void focusLost(FocusEvent e) { + if (this.getText().isEmpty()) { + super.setText(hint); + } + } + + @Override + public String getText() { + @SuppressWarnings("deprecation") + String typed = super.getText(); + return typed.equals(hint) ? "" : typed; + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/utils/HintTextField.java b/src/com/ayushmaanbhav/jstockmart/utils/HintTextField.java new file mode 100644 index 0000000..84b8e59 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/utils/HintTextField.java @@ -0,0 +1,37 @@ +package com.ayushmaanbhav.jstockmart.utils; + +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; + +import javax.swing.*; + +@SuppressWarnings("serial") +public class HintTextField extends JTextField implements FocusListener { + + private final String hint; + + public HintTextField(final String hint) { + super(hint); + this.hint = hint; + super.addFocusListener(this); + } + + @Override + public void focusGained(FocusEvent e) { + if (this.getText().isEmpty()) { + super.setText(""); + } + } + @Override + public void focusLost(FocusEvent e) { + if (this.getText().isEmpty()) { + super.setText(hint); + } + } + + @Override + public String getText() { + String typed = super.getText(); + return typed.equals(hint) ? "" : typed; + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/utils/Histogram.java b/src/com/ayushmaanbhav/jstockmart/utils/Histogram.java new file mode 100644 index 0000000..2677366 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/utils/Histogram.java @@ -0,0 +1,148 @@ +package com.ayushmaanbhav.jstockmart.utils; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.RenderingHints; +import java.awt.Stroke; +import java.util.ArrayList; +import java.util.List; + +public class Histogram { + private static int padding = 25; + private static int labelPadding = 25; + private static Color rectColor1 = new Color(255, 0, 0, 100); + private static Color rectColor2 = new Color(0, 255, 0, 100); + private static Color gridColor = new Color(200, 200, 200, 200); + private static final Stroke GRAPH_STROKE = new BasicStroke(2f); + private static int pointWidth = 4; + private static int numberYDivisions = 10; + + public static void paintHistogram(Graphics2D g2, int height, int width, TrippleArrayList scores) { + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + double xScale = ((double) width - (2 * padding) - labelPadding) / (scores.size() - 1); + double yScale = ((double) height - 2 * padding - labelPadding) / (getMaxScore(scores) - getMinScore(scores)); + + List graphPoints1 = new ArrayList<>(); + for (int i = 1; i < scores.size() - 1; i++) { + int x1 = (int) (i * xScale + padding + labelPadding); + int y1 = (int) ((getMaxScore(scores) - scores.getFirstElement(i)) * yScale + padding); + graphPoints1.add(new Point(x1, y1)); + } + + List graphPoints2 = new ArrayList<>(); + for (int i = 1; i < scores.size() - 1; i++) { + int x1 = (int) (i * xScale + padding + labelPadding); + int y1 = (int) ((getMaxScore(scores) - scores.getThirdElement(i)) * yScale + padding); + graphPoints2.add(new Point(x1, y1)); + } + + // draw white background + g2.setColor(Color.WHITE); + g2.fillRect(padding + labelPadding, padding, width - (2 * padding) - labelPadding, height - 2 * padding - labelPadding); + g2.setColor(Color.BLACK); + + // create hatch marks and grid lines for y axis. + for (int i = 0; i < numberYDivisions + 1; i++) { + int x0 = padding + labelPadding; + int x1 = pointWidth + padding + labelPadding; + int y0 = height - ((i * (height - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding); + int y1 = y0; + if (scores.size() > 0) { + g2.setColor(gridColor); + g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, width - padding, y1); + g2.setColor(Color.BLACK); + String yLabel = ((int) ((getMinScore(scores) + (getMaxScore(scores) - getMinScore(scores)) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + ""; + FontMetrics metrics = g2.getFontMetrics(); + int labelWidth = metrics.stringWidth(yLabel); + g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3); + } + g2.drawLine(x0, y0, x1, y1); + } + + // and for x axis + for (int i = 0; i < scores.size(); i++) { + if (scores.size() > 1) { + int x0 = i * (width - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding; + int x1 = x0; + int y0 = height - padding - labelPadding; + int y1 = y0 - pointWidth; + if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) { + g2.setColor(gridColor); + g2.drawLine(x0, height - padding - labelPadding - 1 - pointWidth, x1, padding); + g2.setColor(Color.BLACK); + String xLabel = Double.toString(scores.getSecondElement(i)); + FontMetrics metrics = g2.getFontMetrics(); + int labelWidth = metrics.stringWidth(xLabel); + g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3); + } + g2.drawLine(x0, y0, x1, y1); + } + } + + String legend1 = "Red Bars : Buy Orders "; + String legend2 = "Green Bars: Sell Orders"; + FontMetrics metrics = g2.getFontMetrics(); + int labelWidth = metrics.stringWidth(legend1); + g2.drawString(legend1, width - padding - labelWidth - 1, padding + metrics.getHeight() + 1); + labelWidth = metrics.stringWidth(legend2); + g2.drawString(legend2, width - padding - labelWidth - 1, padding + (metrics.getHeight() + 1) * 2); + + String legend4 = "Bid/Ask Price"; + String legend3 = "No. of orders"; + labelWidth = metrics.stringWidth(legend3); + g2.drawString(legend3, padding - labelWidth / 4, padding - metrics.getHeight() / 2); + labelWidth = metrics.stringWidth(legend4); + g2.drawString(legend4, width / 2 - labelWidth, height - padding + metrics.getHeight() - 1); + + // create x and y axes + g2.drawLine(padding + labelPadding, height - padding - labelPadding, padding + labelPadding, padding); + g2.drawLine(padding + labelPadding, height - padding - labelPadding, width - padding, height - padding - labelPadding); + + Stroke oldStroke = g2.getStroke(); + g2.setColor(rectColor1); + g2.setStroke(GRAPH_STROKE); + int rec_width = (width - padding * 2 - labelPadding) / (2 * (scores.size() - 1)) - 1; + for (int i = 0; i < graphPoints1.size(); i++) { + int x1 = graphPoints1.get(i).x; + int y1 = graphPoints1.get(i).y; + int rec_height = height - padding - labelPadding - y1; + // int x2 = graphPoints.get(i + 1).x; + // int y2 = graphPoints.get(i + 1).y; + g2.fillRect(x1 - rec_width / 2, y1, rec_width, rec_height); + // g2.drawLine(x1, y1, x2, y2); + } + g2.setColor(rectColor2); + for (int i = 0; i < graphPoints2.size(); i++) { + int x1 = graphPoints2.get(i).x; + int y1 = graphPoints2.get(i).y; + int rec_height = height - padding - labelPadding - y1; + // int x2 = graphPoints.get(i + 1).x; + // int y2 = graphPoints.get(i + 1).y; + g2.fillRect(x1 - rec_width / 2, y1, rec_width, rec_height); + // g2.drawLine(x1, y1, x2, y2); + } + g2.setStroke(oldStroke); + } + + private static double getMinScore(TrippleArrayList scores) { + int minScore = Integer.MAX_VALUE; + for (int i = 1; i < scores.size() - 1; i++) { + minScore = Math.min(minScore, scores.getThirdElement(i)); + minScore = Math.min(minScore, scores.getFirstElement(i)); + } + return minScore; + } + + private static double getMaxScore(TrippleArrayList scores) { + int maxScore = Integer.MIN_VALUE; + for (int i = 1; i < scores.size() - 1; i++) { + maxScore = Math.max(maxScore, scores.getThirdElement(i)); + maxScore = Math.max(maxScore, scores.getFirstElement(i)); + } + return maxScore + 2; + } +} diff --git a/src/com/ayushmaanbhav/jstockmart/utils/LookAndFeel.java b/src/com/ayushmaanbhav/jstockmart/utils/LookAndFeel.java new file mode 100644 index 0000000..004e6a8 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/utils/LookAndFeel.java @@ -0,0 +1,18 @@ +package com.ayushmaanbhav.jstockmart.utils; +import javax.swing.UIManager.LookAndFeelInfo; +import javax.swing.UIManager; +public 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/com/ayushmaanbhav/jstockmart/utils/RandomGenerator.java b/src/com/ayushmaanbhav/jstockmart/utils/RandomGenerator.java new file mode 100644 index 0000000..834c14a --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/utils/RandomGenerator.java @@ -0,0 +1,18 @@ +package com.ayushmaanbhav.jstockmart.utils; + +import java.util.ArrayList; + +public class RandomGenerator { + ArrayList arr; + + public RandomGenerator(int max) { + arr = new ArrayList(max); + for (int i = 0; i < max; i++) { + arr.add(i); + } + } + + public int generateRandom() { + return arr.remove((int) (Math.random() * arr.size())); + } +} \ No newline at end of file diff --git a/src/com/ayushmaanbhav/jstockmart/utils/TrippleArrayList.java b/src/com/ayushmaanbhav/jstockmart/utils/TrippleArrayList.java new file mode 100644 index 0000000..d0feaa8 --- /dev/null +++ b/src/com/ayushmaanbhav/jstockmart/utils/TrippleArrayList.java @@ -0,0 +1,115 @@ +package com.ayushmaanbhav.jstockmart.utils; + +import java.io.Serializable; +import java.util.ArrayList; + +public class TrippleArrayList, B extends Comparable, C extends Comparable> extends ArrayList.Tupple> implements Serializable { + private static final long serialVersionUID = 1L; + + public TrippleArrayList() { + } + + public TrippleArrayList(TrippleArrayList list) { + for (Tupple t : list) { + add(new Tupple(t)); + } + } + + public class Tupple implements Comparable, Serializable { + private static final long serialVersionUID = 1L; + A a; + B b; + C c; + + public Tupple(Tupple t) { + this.a = t.a; + this.b = t.b; + this.c = t.c; + } + + public Tupple(A a, B b, C c) { + this.a = a; + this.b = b; + this.c = c; + } + + public A getA() { + return a; + } + + public B getB() { + return b; + } + + public C getC() { + return c; + } + + @Override + public int compareTo(Tupple t) { + return b.compareTo(t.b); + } + } + + public boolean add(A a, B b, C c) { + return add(new Tupple(a, b, c)); + } + + public void add(int index, A a, B b, C c) { + add(index, new Tupple(a, b, c)); + } + + public int containsFirstElement(A a) { + for (int i = 0; i < size(); i++) { + if (get(i).a.compareTo(a) == 0) { + return i; + } + } + return -1; + } + + public int containsSecondElement(B b) { + for (int i = 0; i < size(); i++) { + if (get(i).b.compareTo(b) == 0) { + return i; + } + } + return -1; + } + + public int containsThirdElement(C c) { + for (int i = 0; i < size(); i++) { + if (get(i).c.compareTo(c) == 0) { + return i; + } + } + return -1; + } + + public A getFirstElement(int index) { + Tupple t = get(index); + return t.getA(); + } + + public B getSecondElement(int index) { + Tupple t = get(index); + return t.getB(); + } + + public C getThirdElement(int index) { + Tupple t = get(index); + return t.getC(); + } + + public void setFirstElement(int index, A a) { + get(index).a = a; + } + + public void setSecondElement(int index, B b) { + get(index).b = b; + } + + public void setThirdElement(int index, C c) { + get(index).c = c; + } +} diff --git a/src/server/BroadcastServer.java b/src/server/BroadcastServer.java deleted file mode 100644 index e04db5e..0000000 --- a/src/server/BroadcastServer.java +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index ad7d27b..0000000 --- a/src/server/LookAndFeel.java +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index 744dd57..0000000 --- a/src/server/PseudoRealTimeData.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * $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 deleted file mode 100644 index b679c3d..0000000 --- a/src/server/RankingServer.java +++ /dev/null @@ -1,110 +0,0 @@ -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 deleted file mode 100644 index 7273e85..0000000 --- a/src/server/StockMart.java +++ /dev/null @@ -1,351 +0,0 @@ -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 deleted file mode 100644 index 09021aa..0000000 --- a/src/server/companies.txt +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index e37d32a..0000000 --- a/src/server/money.txt +++ /dev/null @@ -1 +0,0 @@ -1000 \ No newline at end of file diff --git a/src/server/reg.txt b/src/server/reg.txt deleted file mode 100644 index 041c7a2..0000000 --- a/src/server/reg.txt +++ /dev/null @@ -1 +0,0 @@ -1101cs09 \ No newline at end of file diff --git a/src/user/Shares.java b/src/user/Shares.java deleted file mode 100644 index fc0b6ad..0000000 --- a/src/user/Shares.java +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 3b65ee1..0000000 --- a/src/user/User.java +++ /dev/null @@ -1,173 +0,0 @@ -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