joi, 7 iunie 2012

Probleme examen

////////////////////////server////////////////////////
package pack1;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class ClientGui extends JFrame {
   
    SimpleClient client;
   
    private JScrollPane scrollPane;
    private JTextArea text;
    private JTextField inputField;
   
    public ClientGui() {
        super("Client");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        init();
        setPreferredSize(new Dimension(500, 400));
        pack();
        setLocationRelativeTo(null);
       
        setVisible(true);
       
        client = new SimpleClient(this);
        client.sendMess("hello");
    }
   
    private void init() {
        text = new JTextArea();
        text.setEditable(false);
       
        scrollPane = new JScrollPane(text);       
        add(scrollPane);
       
        inputField = new JTextField();
        inputField.addKeyListener(new KeyListener() {

            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    client.sendMess(inputField.getText());
                    inputField.setText("");
                }
            }

            public void keyReleased(KeyEvent e) {
            }
            public void keyTyped(KeyEvent e) {
            }
        });
        add(inputField, BorderLayout.SOUTH);
    }
   
    public static void main(String[] args) {
        new ClientGui();
    }
   
    public void addBoardMess(String mess) {
        text.append(mess + "\n");
        text.setCaretPosition(text.getText().length());
    }
}
...................................
package pack1;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

public class MultiServer {
   
    private ServerGui gui;

    public MultiServer(ServerGui g) throws IOException {
        gui = g;

        ServerSocket serverSocket = null;

        try {

            serverSocket = new ServerSocket(9999);

        } catch (IOException e) {

//            System.err.println("Could not listen on port: 9999.");
            gui.writeMess("Could not listen on port: 9999.");

            System.exit(-1);

        }

//        System.out.println("wait for clients");
        gui.writeMess("wait for clients");

        while (true) {

            try {

                Socket clientSocket = serverSocket.accept();
                gui.writeMess("new client connected");
                new ServerClientThread(clientSocket, gui);

            } catch (Exception e) {

                e.printStackTrace();

                break;

            }

        }

        serverSocket.close();

    }

}
.....................
package pack1;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

public class ServerClientThread extends Thread {
   
    private ServerGui gui;

    private Socket socket = null;

    public ServerClientThread(Socket socket, ServerGui g) {
        gui = g;

        this.socket = socket;

        start();

    }

    public void run() {

//        System.out.println("start new client thread");
        gui.writeMess("start new client thread");

        try {

            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            BufferedReader in = new BufferedReader(new InputStreamReader(socket

            .getInputStream()));

            String inputLine;

            while (true) {

                try {

                    inputLine = in.readLine();
                    gui.writeMess("input from client : " + inputLine);                   

                    out.println("[" + inputLine + "]");

                    if (inputLine.compareToIgnoreCase("bye") == 0) {

//                        System.out.println("client went off");
                        gui.writeMess("client went off");

                        break;

                    }

                } catch (Exception e) {

//                    System.out.println("client diconnected");
                    gui.writeMess("client diconnected");

                    break;

                }

            }

            out.close();

            in.close();

            socket.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}
...................................
package pack1;

import java.awt.Dimension;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

@SuppressWarnings("serial")
public class ServerGui extends JFrame {
   
    private JTextArea text;   
    private JScrollPane scrollPane;
   
    public ServerGui() {
        super("Server");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        init();
        setPreferredSize(new Dimension(500, 400));
        pack();
       
        setLocationRelativeTo(null);       
        setVisible(true);
       
        try {
//            new SimpleServer(this);
            new MultiServer(this);
        } catch (IOException e) {
//            e.printStackTrace();
            writeMess("Error : " + e.getMessage());
        }
    }
   
    private void init() {
        text = new JTextArea();
        text.setEditable(false);
       
        scrollPane = new JScrollPane(text);
        add(scrollPane);
    }
   
    public void writeMess(String mess) {
        text.append(mess + "\n");
        text.setCaretPosition(text.getText().length());
    }
   
    public static void main(String[] args) {
        new ServerGui();
    }
}
.....................................
package pack1;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

import java.net.UnknownHostException;

public class SimpleClient extends Thread {

    Socket echoSocket = null;

    PrintWriter out = null;

    BufferedReader in = null;
   
    private ClientGui gui;

    public SimpleClient(ClientGui g) {
        gui = g;
        try {

            echoSocket = new Socket("localhost", 9999);

            out = new PrintWriter(echoSocket.getOutputStream(), true);

            in = new BufferedReader(new InputStreamReader(echoSocket

            .getInputStream()));
           
            start();

        } catch (UnknownHostException e) {

            System.err.println("Could not connect to server");

            System.exit(1);

        } catch (IOException e) {

            System.err.println("Couldn't get I/O for server conection.");

            System.exit(1);

        }
    }

    public static void main(String[] args) throws IOException {

        // while ((userInput = stdIn.readLine()) != null) {
        //
        // try {
        //
        // out.println(userInput);
        //
        // System.out.println(in.readLine());
        //
        // if (userInput.compareToIgnoreCase("bye") == 0) {
        //
        // break;
        //
        // }
        //
        // } catch (Exception e) {
        //
        // System.out.println("connection losed: " + e.getMessage());
        //
        // break;
        //
        // }
        //
        // }

    }

    public void close() {
        try {
            out.close();

            in.close();

            echoSocket.close();
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
    }
   
    public void sendMess(String mess) {
        out.println(mess);
    }

    @Override
    public void run() {
        try {
            while (true) {
                String inline = in.readLine();
                if (inline != null && inline.length() > 0) {
                    //TODO
                    gui.addBoardMess(inline);
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
//                e.printStackTrace();
                }
            }
        } catch (IOException e) {
//            e.printStackTrace();
            gui.addBoardMess("connection closed");
        }
    }

}
/////////////////////////////////PC///////////////////////

public class AMD implements Tehnologie{
     private String nume;
    
     public AMD(String nume)
     {
         this.nume=nume;
     }
     public String getTehnologieName()
     {
         return nume;
     }
   
     public String getTehnologieFeatures()
     {
         return "AMD Features";
     }
}
...........................
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Console {

   
    public static void run(JApplet applet,int lung,int inalt)
    {
        JFrame frame=new JFrame("Abstract Factory");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600,400);
        frame.getContentPane().add(applet);
       
        applet.init();
        applet.start();
       
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
       
       
    }
}
............................

public class Desktop implements Portabilitate{
   
      private String nume;
     
      public Desktop(String nume)
      {
          this.nume=nume;
      }
     
       public String getPortabilitateName()
       {
           return nume;
       }
       public String getPortabilitateFeatures()
       {
           return "Desktop Features";
          
       }
}
..........................

public class INTEL implements Tehnologie{

    private String nume;
   
    public INTEL(String nume)
    {
        this.nume=nume;
    }
   
    public String getTehnologieName()
    {
        return nume;
    }
      
    public String getTehnologieFeatures()
    {
        return "INTEL features";
    }
}
..............................

public class Laptop implements Portabilitate{

  private String nume;
     
      public Laptop(String nume)
      {
          this.nume=nume;
      }
     
       public String getPortabilitateName()
       {
           return nume;
       }
       public String getPortabilitateFeatures()
       {
           return "Laptop Features";
          
       }
   
}
.........................

public class PC1_Factory extends PCFactory{

    public Portabilitate getPortabilitate()
    {

            return new Desktop("Port_Desktop");
   
   
    }
    public Tehnologie getTehnologie()
    {
            return new AMD("Tehn_AMD");
    }
}
...............................

public class PC2_Factory extends PCFactory {

    public Portabilitate getPortabilitate()
    {
      return new Laptop("Port_Laptop");
    }
    public Tehnologie getTehnologie()
    {

        return new INTEL("Tehn_Intel");
    }
   
   
   
}
...............................

public abstract class PCFactory {

    public static final String Desktop_PC = "Desktop";
    public static final String Laptop_PC = "Laptop";
   
    public static final String AMD_tech = "AMD";
    public static final String INTEL_TEC = "INTEL";
    public static int categ=0;
   
    public abstract Portabilitate getPortabilitate();
    public abstract Tehnologie getTehnologie();
   
    public static PCFactory getPCFactory(String type)
   
    {
        System.out.println("\nType="+type);
       
       
        if (type.equals(PCFactory.Desktop_PC))
            return new PC1_Factory();

        if(type.equals(PCFactory.AMD_tech))
                return new PC1_Factory();
           
       
       
       
       
        if (type.equals(PCFactory.Laptop_PC))
            return new PC2_Factory();
       
        if (type.equals(PCFactory.INTEL_TEC))
                return new  PC2_Factory();
   
   
   
        return new PC1_Factory();
        }
   
   
   
   
}
...............................

public interface Portabilitate {

       public String getPortabilitateName();
       public String getPortabilitateFeatures();
}
........................

public interface Tehnologie {

       public String getTehnologieName();
       public String getTehnologieFeatures();
}
.........................
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


//aplicatia care foloseste aceste clase implementeaza un sistem
//de cautare PC dupa anumite criterii :categorie si tip

public class Test extends JApplet{

   
    JPanel panel1,panel2,panel3,panel4;
    JComboBox combo1;
    JComboBox combo2;
    JLabel label1,label2,label3;
    JTextField text;
    JButton search,exit;
    Box box;
   
    String searchResult=null;
   
    public void init()
    {
        panel1=new JPanel(new FlowLayout());
        //panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        panel2=new JPanel(new FlowLayout());
        panel3=new JPanel(new FlowLayout());
        panel4=new JPanel(new FlowLayout());
       
        text=new JTextField(45);
        text.setEditable(false);
        text.setHorizontalAlignment(JTextField.CENTER);
        //text.setBackground(C);
        text.setText("Please click on Search Button");
       
        label1=new JLabel("PC Category ");
        label2=new JLabel("PC Type ");
        label3=new JLabel("Search Result ");
       
        box=Box.createVerticalBox();
       
        Ascultator asc=new Ascultator();
       
       
        combo1=new JComboBox(new String[]{"Desktop","Laptop","AMD","INTEL"});
        combo2=new JComboBox(new String[]{"Portabilitate","Tehnologie"});
       
       
        combo1.addActionListener(asc);
        combo2.addActionListener(asc);
       
       
       
        panel1.add(label1);
        panel1.add(combo1);
        panel2.add(label2);
        panel2.add(combo2);
       
        box.add(panel1);
        box.add(Box.createVerticalStrut(25));
        box.add(panel2);
        box.add(Box.createVerticalStrut(25));
   
        panel3.add(label3);
        panel3.add(text);
       
       
        search=new JButton("Search");
        exit=new JButton("Exit");
       
        search.addActionListener(asc);
        exit.addActionListener(asc);
        panel4.add(search);
        panel4.add(exit);
       
       
       
        getContentPane().add(box,BorderLayout.NORTH);
        getContentPane().add(panel3,BorderLayout.CENTER);
        getContentPane().add(panel4,BorderLayout.SOUTH);
       
       
    }
   
    public class Ascultator implements ActionListener {

        public void actionPerformed(ActionEvent e) {
           
            String s=e.getActionCommand();
            if(s.equals("Exit"))
                 System.exit(0);
            else
                 if(s.endsWith("Search"))
                 {
                     String pcCategory=(String)combo1.getSelectedItem();
                     String pcType=(String)combo2.getSelectedItem();
                   
                     System.out.println("pcCategory: "+pcCategory);
                     System.out.println("pcType: "+pcType);
                   
                     PCFactory factory=PCFactory.getPCFactory(pcCategory);
                   
                     if(pcType.equals("Portabilitate"))
                     {
                        System.out.print("\nAm trecut pe aici\n");
                         searchResult="";
                         Portabilitate p=factory.getPortabilitate();
                       
                         System.out.println("..."+p.getPortabilitateName()+"..");
                         if(p.getPortabilitateName().equals("Port_Desktop")
                                 || p.getPortabilitateName().equals("Port_Laptop"))
                         searchResult="Name: "+p.getPortabilitateName()+" "+p.getPortabilitateFeatures();

                      }
                     else
       
                         if(pcType.equals("Tehnologie"))
                         {
                             searchResult="";
                             Tehnologie tehnologie=factory.getTehnologie();
                           
                             System.out.println("..."+tehnologie.getTehnologieName()+"..");
                             if(tehnologie.getTehnologieName().equals("Tehn_AMD") ||
                                        tehnologie.getTehnologieName().equals("Tehn_Intel"))
                             searchResult="Name: "+tehnologie.getTehnologieName()+""+"  "+tehnologie.getTehnologieFeatures();
   
                           
                         }
                   
                   
                     text.setText(searchResult);
                   
                   
                 }
                   
        }
       

    }
   
   
   
    public static void main(String[] args) {

           Console.run(new Test(),600,400);   
       
       
    }

}
/////////////////////Adresa////////////////

public interface AddressValidator {

    public boolean isValidAddress(String inp_address,String inp_zip,String inp_state);
   
}
.....................

public class CAAddressAdapter extends CAAdress implements AddressValidator  {

    public boolean isValidAddress(String inp_address, String inp_zip,
            String inp_state) {
   
        return isValidCanadianAddr(inp_address,inp_zip,inp_state);
       
    }

}
.........................

public class CAAdress {

    public boolean isValidCanadianAddr(String inp_address, String inp_zip,
            String inp_state) {
       
    if(inp_address.trim().length()<15)
         return false;
    if(inp_zip.trim().length()!=6)
          return false;
    if(inp_state.trim().length()<6)
         return false;
       
        return true;
    }

}
............................
import javax.swing.*;

public class Console {

    public static void run(JApplet applet,int lung,int inalt)
    {
        JFrame frame=new JFrame("Validare date client");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(lung,inalt);
        frame.getContentPane().add(applet);
        applet.init();
        applet.start();
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
       
       
    }
   
   
}
..............................

public class Customer {

    private static final String US="US";
    private static final String CANADA="Canada";
   
    private String address;
    private String name;
    private String zip, state,type;
   
    public boolean isValidAddress(String inp_address,String inp_zip,String inp_state)
    {
        AddressValidator valid=getValidator(type);
       
        return valid.isValidAddress(inp_address,inp_zip,inp_state);
    }
   
   
    private AddressValidator getValidator(String custType)
    {
        AddressValidator validator=null;
        if(custType.equals("US"))
              validator=new USAddress();
        else
             validator=new CAAddressAdapter();
       
       
        return validator;
    }
   
    public Customer(String inp_name,String inp_address,
            String inp_zip,String inp_state,String inp_type)
    {
        this.name=inp_name;
        this.address=inp_address;
        this.zip=inp_zip;
        this.state=inp_state;
        this.type=inp_type;
    }
   
}
..................................
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JApplet{

    JLabel adresa,zip,state;
    JTextField adr,zipe,stat;
    JOptionPane msg;
    Box box;
   
   
    JPanel panel,panel1,panel2,panel3;
    JButton verifica;
   
    public void init()
    {
       
        panel=new JPanel();
        panel1=new JPanel(new FlowLayout());
        panel2=new JPanel(new FlowLayout());
        panel3=new JPanel(new FlowLayout());
       
       
        box=box.createVerticalBox();
       
        adr=new JTextField(25);
        adr.setBackground(Color.WHITE);
        adr.setHorizontalAlignment(JTextField.LEFT);
       
       
       
        zipe=new JTextField(25);
        zipe.setBackground(Color.WHITE);
        zipe.setHorizontalAlignment(JTextField.LEFT);
       
       
        stat=new JTextField(25);
        stat.setBackground(Color.WHITE);
        stat.setHorizontalAlignment(JTextField.LEFT);
        
       
        adresa=new JLabel("Address");
        zip=new JLabel("Zip Code");
        state=new JLabel("   State    ");
       
       
        panel1.add(adresa);
        panel1.add(adr);
       
        panel2.add(zip);
        panel2.add(zipe);
       
        panel3.add(state);
        panel3.add(stat);
       
        box.add(panel1);
        box.add(panel2);
        box.add(panel3);
       
        getContentPane().add(box,BorderLayout.NORTH);
       
       
        Ascultator asc=new Ascultator();
        verifica=new JButton("Verifica");
        verifica.addActionListener(asc);
       
        panel.add(verifica);
        getContentPane().add(panel,BorderLayout.SOUTH);
       
       
    }
    public class Ascultator implements ActionListener {

        public void actionPerformed(ActionEvent e) {
       
            String s=e.getActionCommand();
            if(s.equals("Verifica"))
            {
                String a=adr.getText();
                String z=zipe.getText();
                String st=stat.getText();
                Customer cus=new Customer("Boris",a,z,st,"US");
                System.out.println("a= "+a);
                System.out.println("z= "+z);
                System.out.println("s= "+st);
               
                boolean ok=cus.isValidAddress(a,z,st);
                System.out.println("ok= "+ok);
                if(ok==true)
                JOptionPane.showMessageDialog(null,
                        "Datele introduse sunt valide", "Rezultat",
                        JOptionPane.INFORMATION_MESSAGE);
                else
                    JOptionPane.showMessageDialog(null,
                            "Datele introduse sunt invalide", "Rezultat",
                            JOptionPane.ERROR_MESSAGE);
                   
               
            }

        }

    }
   
    public static void main(String[] args) {
    Console.run(new Test(),600,400);

    }

}
...................................

public class USAddress implements AddressValidator {

    public boolean isValidAddress(String inp_address, String inp_zip,
            String inp_state) {

        if(inp_address.trim().length()<10)
        {
           
        System.out.println("Address false"+inp_address);
            return false;
        }
        if(inp_zip.trim().length()<5)
        {
            System.out.println("zip false"+inp_zip);
            return false;
        }
       
        if(inp_zip.length()>10)
           
            {
            System.out.println("zip false"+inp_zip);
            return false;
           
            }
       
        if(inp_state.trim().length()!=2)
            {
            System.out.println("State false"+inp_state);
            return false;
            }
   
       
        return true;
    }

}
/////////////////////////Student//////////////////
package pack;



import javax.swing.*;
import java.awt.event.*;
import java.util.*;

public class DisplayFrom extends JFrame{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    InputForm inputForm;
    Observable obsInput;
    JTextField display;

    public DisplayFrom() {
       
          addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                      System.exit(0);
                }
          });
          inputForm = new InputForm();
          obsInput = inputForm.getInputInfo();
          obsInput.addObserver(new InputFormObserver());
          display = new JTextField(10);
          add(display);
          setTitle("Observer form");
          setSize(200, 100);
          setLocation(200, 100);
          setVisible(true);
    }

    private class InputFormObserver implements Observer {
          public void update(Observable ob, Object o) {
                doSomeUpdate();
          }
    }

    public void doSomeUpdate() {
          display.setText(inputForm.getText());
          JOptionPane.showMessageDialog(DisplayFrom.this,
                      "This form has been updated");
    }

    public static void main(String args[]) {
          new DisplayFrom();
    }
}
.........................................
package pack;


import java.awt.event.*;
import java.util.Observable;
import javax.swing.*;


public class InputForm extends JFrame{
   
     /**
     *
     */
    private static final long serialVersionUID = 1L;
    public InformDisplay inform = new InformDisplay();
     JTextField input = new JTextField(10);

     public InputForm() {
           JPanel panel = new JPanel();
           input.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                       inform.notifyObservers();
                 }
           });
           panel.add(new JLabel("Enter: "));
           panel.add(input);
           addWindowListener(new WindowAdapter() {
                 public void windowClosing(WindowEvent e) {
                       System.exit(0);
                 }
           });
           getContentPane().add(panel);
           setTitle("Observable form");
           setSize(200, 100);
           setVisible(true);
     }

     public Observable getInputInfo() {
           return inform;
     }

     public String getText() {
           return input.getText();
     }

     private class InformDisplay extends Observable {
           public void notifyObservers() {
                 setChanged();
                 super.notifyObservers();
           }
     }
}

...................................
package pack;



import java.util.Observable;

public class MessageBoard extends Observable {
     private String message;

     public String getMessage() {
           return message;
     }

     public void changeMessage(String message) {
           this.message = message;
           setChanged();
           notifyObservers(message);
     }

     public static void main(String[] args) {
           MessageBoard board = new MessageBoard();
           Student bob = new Student();
           Student joe = new Student();
           board.addObserver(bob);
           board.addObserver(joe);
           board.changeMessage("More Homework!");
     }
}

...................................
package pack;


import java.util.Observable;
import java.util.Observer;

public class Student implements Observer{
   
     public void update(Observable o, Object arg) {
         System.out.println("Message board changed: " + arg);
   }
}

......................................
/////////////////////shopping//////////////////
package pack;


public abstract class Acount {
   
     private float _balance;
     @SuppressWarnings("unused")
    private int _acountNumber;

     public Acount(int acountNumber) {
           _acountNumber = acountNumber;
     }


     public void credit(float amount) {
           setBalance(getBalance() + amount);
     }


     public void debit(float amount) throws Exception {

           float balance = getBalance();
           if (balance < amount) {
                throw new Exception("Total balance not sufficient");
           } else {
                 setBalance(balance - amount);
           }
     }

     public float getBalance() {
           return _balance;
     }

     public void setBalance(float balance) {
           _balance = balance;
     }

     public static void main(String[] args) throws Exception {

           SavingAcount acount = new SavingAcount(12456);
           acount.credit(100);
           acount.debit(50);
     }
}

..................................
package pack;


import java.util.*;

public class Inventory {
     private List _items = new ArrayList();

     public void addItem(Item item) {
           _items.add(item);
     }

     public void removeItem(Item item) {
           _items.remove(item);
     }
}

.........................
package pack;

import java.util.logging.*;

public class Item {
    private static Logger _logger = Logger.getLogger("cart");
    private String _id;
    private float _price;

    public Item(String id, float price) {
          _id = id;
          _price = price;
    }

    public String getID() {
        _logger.logp(Level.INFO, "Item", "getID", "Entering");
        return _id;
    }

    public float getPrice() {
        _logger.logp(Level.INFO, "Item", "getPrice", "Entering");
        return _price;
    }

    public String toString() {
        _logger.logp(Level.INFO, "Item", "toString", "Entering"); 
          return "Item: " + _id;
    }
}
..............................
package pack;


public class RemoteClient {
   
     public static void main(String[] args) throws Exception {
         int retVal = RemoteService.getReply();
         System.out.println("Reply is " + retVal);
   }
}
..............................
package pack;

import java.rmi.*;

public class RemoteService {
   
    public static int getReply() throws RemoteException {

         if (Math.random() > 0.25) {
               throw new RemoteException("Simulated failure occurred");
         }
         System.out.println("Replying");
         return 5;

   }   
}
...............................
package pack;


public class Sample {

   

    public static void sendMessage(String message) {

          System.out.println(message);

    }


    public static void main(String[] args) {
        sendMessage("message to send");

    }

}

..........................
package pack;


public class SavingAcount extends Acount{
   
    public SavingAcount(int acountNumber) {
          super(acountNumber);
    }

}
.............................
package pack;


import java.util.*;

public class ShoppingCart {
      private List _items = new ArrayList();

      public void addItem(Item item) {
            _items.add(item);
      }

      public void removeItem(Item item) {
            _items.remove(item);
      }

      public void empty() {
            _items.clear();
      }

      public float totalValue() {
            // unimplemented... free!
            return 0;
      }   
}
..............................
package pack;


public class ShoppingCartOperator {
   
     public static void addShoppingCartItem(ShoppingCart sc, Inventory inventory, Item item) {
       inventory.removeItem(item);
       sc.addItem(item);
 }

     public static void removeShoppingCartItem(ShoppingCart sc, Inventory inventory, Item item) {
       sc.removeItem(item);
       inventory.addItem(item);
 }
}

................................
package pack;


public class Test{
    public static void main(String[] args) {
       
        Inventory inventory = new Inventory();

        Item item1 = new Item("1", 30);
        Item item2 = new Item("2", 31);
        Item item3 = new Item("3", 32);
        inventory.addItem(item1);
        inventory.addItem(item2);
        inventory.addItem(item3);
        ShoppingCart sc = new ShoppingCart();
        ShoppingCartOperator.addShoppingCartItem(sc, inventory, item1);
        ShoppingCartOperator.addShoppingCartItem(sc, inventory, item2);
  }
}



................................
package pack;


public class TestFactorial {
      public static void main(String[] args) {
          System.out.println("Result: " + factorial(2) + "\n");
         // System.out.println("Result: " + factorial(10) + "\n");
         // System.out.println("Result: " + factorial(15) + "\n");
         // System.out.println("Result: " + factorial(15) + "\n");
    }

    public static long factorial(int n) {
          if (n == 0) {
                return 1;
          } else {
                return n * factorial(n - 1);
          }
    }
}

////////////////////////////Curatatorie////////////////
package lab;

interface Clean
{
    public void makeClean();
}
.....................
package lab;

interface Extra extends Clean
{
    public void takeCare();
}
......................
package lab;

class Facility implements Extra{
    public void makeClean() {
        System.out.println("Clean Facility B-)");
    }
    public void takeCare() {
        System.out.println("Care has been taken :P");
    }
}
.......................
package lab;

class Office implements Clean
{
    public void makeClean()
    {
        System.out.println("Clean Office ;))");
    }
}
......................
package lab;

class Test {
       static void Jobs (Extra job) {
           if (job instanceof Clean)
               ((Clean)job).makeClean();
           if (job instanceof Extra)
               ((Extra)job).takeCare();
       }
       public static void main(String[] args) {
           Extra e = new Facility();
           Jobs(e);
           Clean c1 = new Office();
           Clean c2 = new Workshop();
           c1.makeClean();
           c2.makeClean();
           e.makeClean();
       }
    }

.....................
package lab;

class Workshop implements Clean
{
    public void makeClean()
    {
        System.out.println("Clean Workshop :>");
    }
}
//////////////////////input-output///////
package pack1;

import java.io.IOException;

public class Ex1 {
    public static void main(String args[]) throws IOException {
          byte data[] = new byte[10];
          System.out.println("Introduceti caractere: ");
          System.in.read(data);
          System.out.print("Ati introdus: ");
          for (int i=0; i < data.length; i++) {
             System.out.print((char) data[i]);
          }
       }


}
.........................
package pack1;
import java.io.*;

public class Ex2 {
   
           public static void main(String args[]) throws IOException {
              int i;
              FileInputStream fin;
            //  FileOutputStream fout;
             
              try {
                 fin = new FileInputStream(args[0]);
              } catch (FileNotFoundException ex) {
                 System.out.println("fisierul nu exista");
                 return;
              } catch (ArrayIndexOutOfBoundsException ex) {
                 System.out.println("folosire: CitesteFisier ");
                 return;
              }
              do {
                 i = fin.read();
                 if (i != -1) System.out.print((char) i);
              } while(i != -1);
              fin.close();
           }


}
..................................
package pack1;
import java.io.*;

public class Ex3 {
    public static void main(String args[]) throws IOException {
          DataOutputStream dataOut;
          DataInputStream dataIn;
          int i = 10;
          double d = 123.45;
          Boolean b = true;
          try {
             dataOut = new DataOutputStream(new FileOutputStream("test.txt"));
          } catch (IOException ex) {
             System.out.println("Fisierul nu poate fi accesat");
             return;
          }
          try {
             dataOut.writeInt(i);
             dataOut.writeDouble(d);
             dataOut.writeBoolean(b);
          } catch (IOException ex) {
             System.out.println("Eroare la scriere in fisier");
          }
          dataOut.close();
          try {
             dataIn = new DataInputStream(new FileInputStream("test.txt"));
          } catch(IOException ex) {
             System.out.println("Fisierul nu poate fi accesat");
             return;
          }
          try {
             i = dataIn.readInt();
             d = dataIn.readDouble();
             b = dataIn.readBoolean();
          } catch (IOException ex) {
             System.out.println("Eroare la citire din fisier");
          }
          dataIn.close();
          System.out.println("valorile citite: " + i + " "  + d + " " + b);
       }


}
.................................
package pack1;
import java.io.*;

public class Ex4 {
     public static void main(String args[]) throws IOException {
          FileWriter fw;
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          try {
             fw = new FileWriter("test.txt");
          } catch (IOException ex) {
             System.out.println("fisierul nu este accesibil");
             return;
          }
          System.out.println("Introduceti text: ");
          do {
             String str = br.readLine();
             if (str.compareTo("END") == 0) break;
             fw.write(str);
          } while (true);
          fw.close();
       }


}
.................................
///////////////factory-XML File/////////////
package pack;

//cvs=valori separate prin virgula

public class CSVFile implements Display{
   
     public void load(String textfile) {
       System.out.println("load from a txt file");
 }

 public void formatConsistency() {
       System.out.println("txt file format changed");
 }
}

...............................
package pack;

//format binar

public class DBFile implements Display{
   
    public void load(String dbfile) {
      System.out.println("load from a db file");
}

public void formatConsistency() {
      System.out.println("db file format changed");
}
}

..........................
package pack;

public interface Display {

    // incarca fisier
    public void load(String fileName);


    // parseaza datele din fisier
    public void formatConsistency();

}

...........................
package pack;


import java.io.*;

public class TestFactory {
    public static void main(String[] args) throws IOException {
       
         Display display = null;
        int s;
        /*System.out.print("introduceti optiunea: 1, 2, 3");
         s=System.in.read();
         // alegerea tipului o facem prin argumente in linie de comanda
        
        */
        s=3;
         if (s==1)
               display = new CSVFile();
         else if (s==2)
               display = new XMLFile();
         else if (s==3)
               display = new DBFile();
         else
               System.exit(1);

         // logica comuna de cod
         display.load("salut");
         display.formatConsistency();
   }
}



............................
package pack;

//format XML

public class XMLFile implements Display{

    public void load(String xmlfile) {
        System.out.println("load from an xml file");
    }


    public void formatConsistency() {
        System.out.println("xml file format changed");
    }
}
////////////////////////car//////////////////
package pack;
public interface Car {

    public String getCarFeatures();
    public String getCarName();
}
.............................
package pack;

public class LuxuryCar implements Car{
    private String name;
   
    public LuxuryCar (String cName)
    {
        name=cName;
    }
   
    public String getCarFeatures()
    {
        return "Luxury Car";
    }
   
    public String getCarName()
    {
        return name;
    }
}

...............................
package pack;

public class LuxurySUV implements SUV{

    private String name;
   
    public LuxurySUV(String sName) {
        name=sName;
    }
   
    public String getSUVFeatures(){
        return "Luxury SUV Features";
    }
    public String getSUVName(){
        return name;
    }
}
.................................
package pack;



public class LuxuryVehicleFactory extends VehicleFactory{

    public Car getCar(){
        return new LuxuryCar("L-C");
    }   
   
     public SUV getSUV() {
         return new LuxurySUV("L-S");
   }

}

.........................
package pack;



import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class MyFrame extends JFrame{
    String s1[]={"luxury","non_luxury"};
    String s2[]={"Car","SUV"};
    JComboBox tip=new JComboBox(s1);
    JComboBox model=new JComboBox(s2);
     JLabel rezultat= new  JLabel("Rezultat cautare");
   
    public MyFrame()
    {
        setSize(500,500);
        setVisible(true);
        JPanel p1=new JPanel(new FlowLayout());
        JPanel p2=new JPanel(new FlowLayout());
       
        add(p1,BorderLayout.WEST);
        p1.add(tip);
        p2.add(model);
        add(p2,BorderLayout.CENTER);
        add(rezultat,BorderLayout.NORTH);
        myActionListener A=new myActionListener();
        tip.addActionListener(A);
        model.addActionListener(A);
    }
   
    class myActionListener implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0) {
            rezultat.setText(cauta());
           
        }
       
       
    }
    public String cauta()
    {
        String searchResult =null;
        VehicleFactory vf = VehicleFactory.getVehicleFactory(tip.getSelectedItem().toString());
         if (model.getSelectedItem().toString().equals("Car")) {

               Car c = vf.getCar();
               searchResult = "Name: " + c.getCarName() + "  Features: "

                           + c.getCarFeatures();

         }

         if (model.getSelectedItem().toString().equals("SUV")) {

               SUV s = vf.getSUV();

               searchResult = "Name: " + s.getSUVName() + "  ||||   Features: "

                           + s.getSUVFeatures();

         }
         return searchResult;       
    }
}

......................................
package pack;


public class NonLuxuryCar implements Car{
    private String name;
   
    public NonLuxuryCar(String cName) {
        name=cName;
    }
   
    public String getCarFeatures()
    {
        return "Non Luxury Car";
    }
   
    public String getCarName()
    {
        return name;
    }
}

.....................................
package pack;



public class NonLuxurySUV implements SUV{
    private String name;
   
    public NonLuxurySUV (String sName){
        sName=name;
    }
   
    public String getSUVFeatures()
    {
        return "Non LUXURY SUV";   
    }
   
    public String getSUVName()
    {
        return name;
       
    }

   
}

...................................
package pack;

public class NonLuxuryVehicleFactory extends VehicleFactory{
   
    public Car getCar()
    {
        return new NonLuxuryCar("NL-C");
    }

    public SUV getSUV()
    {
        return new NonLuxurySUV("NL-SUV");
    }
}
..........................
package pack;


public interface SUV {

    public String getSUVFeatures();
    public String getSUVName();
}

.................................
package pack;


public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        new MyFrame();
    }

}
.......................
package pack;


public abstract class VehicleFactory {
   
    public static final String LUXURY_VEHICLE=null;
    public static final String NON_LUXURY_VEHICLE=null;
   
    public abstract Car getCar();
    public abstract SUV getSUV();
    public static VehicleFactory getVehicleFactory (String s)
    {
        if(s.equals("luxury"))
            return new LuxuryVehicleFactory();
            else
            if(s.equals("non_luxury"))
            return new NonLuxuryVehicleFactory();

            return null;
    }

}

////////////////////////Aspecte////////////
///////////////Hotel///////////
package pack;

public aspect CheckInCustomer {

   

    private Customer Room.checkBy = null;

   

    public Customer Room.getCheckBy() {

          return checkBy;

    }

   

    public void Room.setCheckBy(Customer value) {

          checkBy = value;

    }

   

    public void Room.uncheck() {

          setCheckBy(null);

    }

   

    public void StaffHandler.makeCheckIn(Reservation res) {

          res.getRoom().setCheckBy(res.getCustomer());

          //consume reservation

          getReservations().remove(res);

    }

}


............................
package pack;

public aspect CheckOutCustomer {

   

    public void StaffHandler.makeChekcOut(Room room) {

          room.uncheck();

          room.setAvailability(true);

    }

}


..............................
package pack;

public class Customer {

    private int id;

   

    public int getId() {

          return id;       

    }

   

    public Customer(int id) {

          this.id = id;

    }

}

..............................
package pack;

public class Reservation {

   

    private Room room;

    private Customer customer;

   

    public Room getRoom() {

          return room;

    }

   

    public Customer getCustomer() {

          return customer;

    }

   

    public Reservation(Room room, Customer customer) {

          this.room = room;

          this.customer = customer;

    }

}


............................
package pack;

public aspect ReserveRoomAspect {

   

    private boolean Room.available;    



    public void Room.setAvailability(boolean value) {

          available = value;

    }

   

    public boolean Room.isAvailable() {

          return available;

    }

   

    private Room StaffHandler.getAvailableRoom(RoomCategory categ) {

          for(Room room : getRooms()) {

                if (room.isAvailable() && room.getCateg() == categ) {

                      return room;

                }

          }

          return null;

    }

   

    public void StaffHandler.makeReservation(Customer customer, RoomCategory categ) {

          Room foundRoom = getAvailableRoom(categ);

          if (foundRoom != null) {

                Reservation res = new Reservation(foundRoom, customer);

                getReservations().add(res);

                foundRoom.setAvailability(false);

          }

    }

}

.....................................
package pack;

public class Room {

    private int nr;

    private RoomCategory categ;

   

    public int getNr() {

          return nr;

    }

   

    public RoomCategory getCateg() {

          return categ;

    }

   

    public Room(int nr, RoomCategory categ) {

          this.nr = nr;

          this.categ = categ;

    }

}

..............................
package pack;

public enum RoomCategory {

   

    A(10),

    B(20),

    C(30),

    D(40);

   

    private int price;

   

    public int price() {

          return price;

    }

   

    private RoomCategory(int price) {

          this.price = price;

    }

}

.........................
package pack;

import java.util.*;



public class StaffHandler {



      private List rooms = new ArrayList();

      private List reservations = new ArrayList();



      public StaffHandler() {

            testInits();

      }

     

      public List getRooms() {

            return rooms;

      }

     

      public List getReservations() {

            return reservations;

      }



      private void testInits() {

            for (int i = 0; i < 5; i++) {

                  rooms.add(new Room(10 + i, RoomCategory.A));

                  rooms.add(new Room(20 + i, RoomCategory.B));

                  rooms.add(new Room(30 + i, RoomCategory.C));

                  rooms.add(new Room(40 + i, RoomCategory.D));

            }

      }

}


///////////////////shoping/////////////////
package pack;

import java.util.ArrayList;

import java.util.List;



public class Inventory {

      private List _items = new ArrayList();



      public void addItem(Item item) {

            _items.add(item);

      }



      public void removeItem(Item item) {

            _items.remove(item);

      }
}


...............................
package pack;

import java.util.logging.*;



public class Item {

     

            private static Logger _logger = Logger.getLogger("cart");

     

      private String _id;



      private float _price;



      public Item(String id, float price) {

            _id = id;

            _price = price;

      }



      public String getID() {

                        _logger.logp(Level.INFO, "Item", "getID", "Entering");

            return _id;

      }



      public float getPrice() {

                        _logger.logp(Level.INFO, "Item", "getPrice", "Entering");

            return _price;

      }



      public String toString() {

                        _logger.logp(Level.INFO, "Item", "toString", "Entering"); 

            return "Item: " + _id;

      }

}

............................
package pack;

import java.util.*;



public class ShoppingCart {

      private List _items = new ArrayList();



      public void addItem(Item item) {

            _items.add(item);

      }



      public void removeItem(Item item) {

            _items.remove(item);

      }



      public void empty() {

            _items.clear();

      }



      public float totalValue() {

            // unimplemented... free!

            return 0;

      }

}


..................................
package pack;

public class ShoppingCartOperator {

    public static void addShoppingCartItem(ShoppingCart sc,

                Inventory inventory, Item item) {

          inventory.removeItem(item);

          sc.addItem(item);

    }



    public static void removeShoppingCartItem(ShoppingCart sc,

                Inventory inventory, Item item) {

          sc.removeItem(item);

          inventory.addItem(item);

    }

}


.............................
package pack;

public class Test {

   

    public static void main(String[] args) {

          Inventory inventory = new Inventory();

          Item item1 = new Item("1", 30);

          Item item2 = new Item("2", 31);

          Item item3 = new Item("3", 32);

          inventory.addItem(item1);

          inventory.addItem(item2);

          inventory.addItem(item3);

          ShoppingCart sc = new ShoppingCart();

          ShoppingCartOperator.addShoppingCartItem(sc, inventory, item1);

          ShoppingCartOperator.addShoppingCartItem(sc, inventory, item2);

    }

}

.............................
package pack;

import org.aspectj.lang.*;

import java.util.logging.*;



public aspect TraceAspect {

      private Logger _logger = Logger.getLogger("trace");



      pointcut traceMethods()

      : (execution(* *.*(..)) || execution(*.new(..)))

            && !within(TraceAspect);




      before() : traceMethods() && !execution(String *.toString()) {

          Signature sig = thisJoinPointStaticPart.getSignature();

          _logger.logp(Level.INFO, sig.getDeclaringType().getName(), sig

                      .getName(), createParameterMessage(thisJoinPoint));

    }



    private String createParameterMessage(JoinPoint joinPoint) {

          StringBuffer paramBuffer = new StringBuffer("\n\t[This: ");

          paramBuffer.append(joinPoint.getThis());

          Object[] arguments = joinPoint.getArgs();

          paramBuffer.append("]\n\t[Args: (");

          for (int length = arguments.length, i = 0; i < length; ++i) {

                Object argument = arguments[i];

                paramBuffer.append(argument);

                if (i != length - 1) {

                      paramBuffer.append(',');

                }

          }

          paramBuffer.append(")]");

          return paramBuffer.toString();

    }


}
//////////////////////account////////////////////
package pack;

public abstract class Account {

    private float _balance;



    private int _accountNumber;



    public Account(int accountNumber) {

          _accountNumber = accountNumber;

    }



    public void credit(float amount) {

          setBalance(getBalance() + amount);

    }



    public void debit(float amount) throws Exception {

          float balance = getBalance();

          if (balance < amount) {

                throw new Exception("Total balance not sufficient");

          } else {

                setBalance(balance - amount);

          }

    }



    public float getBalance() {

          return _balance;

    }



    public void setBalance(float balance) {

          _balance = balance;

    }



    public static void main(String[] args) throws Exception {

          SavingsAccount account = new SavingsAccount(12456);

          account.credit(100);

          account.debit(50);

    }

}


...............................
package pack;

public aspect JoinPointTraceAspect {

   

    private int _callDepth = -1;



    pointcut tracePoints() : !within(JoinPointTraceAspect);



    before() : tracePoints() {

          _callDepth++;

          print("Before", thisJoinPoint);

    }



    after() : tracePoints() {

          print("After", thisJoinPoint);

          _callDepth--;

    }



    private void print(String prefix, Object message) {

          for (int i = 0, spaces = _callDepth * 2; i < spaces; i++) {

                System.out.print(" ");

          }

          System.out.println(prefix + ": " + message);

    }

}


..........................
package pack;

public class SavingsAccount extends Account {

   

    public SavingsAccount(int accountNumber) {

          super(accountNumber);
    }
}

Niciun comentariu:

Trimiteți un comentariu