diff --git a/dat/wala.properties b/dat/wala.properties index f3e0568..5d347b3 100644 --- a/dat/wala.properties +++ b/dat/wala.properties @@ -25,8 +25,7 @@ ## ubuntu (this is for openjdk 7 32-bit; change to the appropriate versionn) ##java_runtime_dir = /usr/lib/jvm/java-6-sun/jre/lib/ ##java_runtime_dir = /usr/lib/jvm/java-7-openjdk-i386/jre/lib/ -java_runtime_dir = /usr/lib/jvm/java-7-oracle/jre/lib - +java_runtime_dir = C:/Program Files (x86)/Java/jre7/lib ################### Mandatory settings with default value ###################### ##### Default output dir diff --git a/example-apps/campus.jar b/example-apps/campus.jar new file mode 100644 index 0000000..ab06c93 Binary files /dev/null and b/example-apps/campus.jar differ diff --git a/example-apps/chat.jar b/example-apps/chat.jar new file mode 100644 index 0000000..3ab2c92 Binary files /dev/null and b/example-apps/chat.jar differ diff --git a/example-apps/ip.jar b/example-apps/ip.jar new file mode 100644 index 0000000..e861ca1 Binary files /dev/null and b/example-apps/ip.jar differ diff --git a/example-apps/logica.jar b/example-apps/logica.jar new file mode 100644 index 0000000..b66d340 Binary files /dev/null and b/example-apps/logica.jar differ diff --git a/example-apps/src/campus/application/Application.java b/example-apps/src/campus/application/Application.java new file mode 100644 index 0000000..70a0dac --- /dev/null +++ b/example-apps/src/campus/application/Application.java @@ -0,0 +1,27 @@ +package application; + +import java.util.ArrayList; + +import create.Question; +import globals.Banks; +import gui.StartingScreen; + +public class Application { + + public static Banks global = new Banks(); + public static ArrayList selectedQuestions = new ArrayList(); + public static ArrayList questionsToSelect = new ArrayList(); + public static int questaoAtual = 1; + public static String arrayAnswer[]; + public static String arrayAnswerCorrect[]; + + + public static void main(String[] args) { + // TODO Auto-generated method stub + + StartingScreen window = new StartingScreen(); + window.frame.setVisible(true); + + } + +} diff --git a/example-apps/src/campus/create/Question.java b/example-apps/src/campus/create/Question.java new file mode 100644 index 0000000..0a4d17c --- /dev/null +++ b/example-apps/src/campus/create/Question.java @@ -0,0 +1,53 @@ +package create; + +public class Question { + + private String answer; + private String userAnswer; + private String title; + private String description; + public int qNumber; + + + public Question(String title , String description, String answer){ + + this.answer = answer; + this.title = title; + this.description = description; + this.qNumber = 0; + } + + + + public String getAnswer() { + return answer; + } + public void setAnswer(String answer) { + this.answer = answer; + } + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + + + public String getUserAnswer() { + return userAnswer; + } + + + + public void setUserAnswer(String userAnswer) { + this.userAnswer = userAnswer; + } + +} diff --git a/example-apps/src/campus/create/Questionnaire.java b/example-apps/src/campus/create/Questionnaire.java new file mode 100644 index 0000000..ae2a710 --- /dev/null +++ b/example-apps/src/campus/create/Questionnaire.java @@ -0,0 +1,77 @@ +package create; + +import globals.Banks; + +public class Questionnaire { + private String title; + private int questionsNumber; + private Question questionTitles[]; + private String questionNames[]; + + public Questionnaire(String title, int questionsNumber, String[] questions, + Banks bank) { + this.title = title; + this.questionsNumber = questionsNumber; + this.questionNames = questions; + questionTitles = new Question[questionsNumber]; + for (int i = 0; i < questions.length; i++) { + Question obj = bank.getQuestion(questions[i]); + if (obj == null) { + System.out.println("Questão " + questions[i] + + " não encontrada no banco"); + this.questionsNumber--; + } else + bank.getQuestion(questions[i]).qNumber++; + } + } + + public int getQuestionsNumber() { + return questionsNumber; + } + + public void setQuestionsNumber(int questionsNumber) { + this.questionsNumber = questionsNumber; + } + + public Question[] getQuestions() { + return questionTitles; + } + + public void setQuestions(Question[] questions) { + this.questionTitles = questions; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Question[] getAllQuestions(String[] questions, Banks bank) { + Question get[] = new Question[questionsNumber]; + int m = 0; + for (int i = 0; i < questions.length; i++) { + Question obj = bank.getQuestion(questions[i]); + if (obj == null) + System.out.println("Questão " + questions[i] + + " não encontrada no banco"); + else { + if (m < questionsNumber) { + get[m] = obj; + m++; + } + } + } + return get; + } + + public String[] getQuestionNames() { + return questionNames; + } + + public void setQuestionNames(String questionNames[]) { + this.questionNames = questionNames; + } +} \ No newline at end of file diff --git a/example-apps/src/campus/globals/Banks.java b/example-apps/src/campus/globals/Banks.java new file mode 100644 index 0000000..859d341 --- /dev/null +++ b/example-apps/src/campus/globals/Banks.java @@ -0,0 +1,140 @@ +package globals; + +import java.util.ArrayList; +import java.util.Iterator; + +import create.Question; +import create.Questionnaire; + +public class Banks { + + public static int numberQuestions = 0; + public static int numberQuestionnaires = 0; + public static ArrayList questionBank = new ArrayList(); + public static ArrayList questionnaireBank = new ArrayList(); + + + public boolean addQuestionGlobal(Question question) { + if (!hasQuestion(question.getTitle())) { + questionBank.add(question); + this.numberQuestions++; + return true; + } + return false; + } + + public boolean removeQuestion(String title) { + Iterator it = questionBank.iterator(); + while (it.hasNext()) { + Question obj = it.next(); + if (obj.getTitle().equalsIgnoreCase(title)) { + if (obj.qNumber > 0) { + System.out + .println("A questão não pode ser removida pois está em um questionário"); + return false; + } + this.numberQuestions--; + it.remove(); + return true; + } + } + return false; + } + + public boolean hasQuestion(String title) { + Iterator it = questionBank.iterator(); + while (it.hasNext()) { + Question obj = it.next(); + if (obj.getTitle().equalsIgnoreCase(title)) { + return true; + } + } + return false; + } + + public boolean removeQuestionnaire(String title) { + Iterator it = questionnaireBank.iterator(); + while (it.hasNext()) { + Questionnaire obj = it.next(); + if (obj.getTitle().equalsIgnoreCase(title)) { + for (int i = 0; i < obj.getQuestionsNumber(); i++) { + this.getQuestion(title).qNumber--; + } + this.numberQuestionnaires--; + it.remove(); + return true; + } + } + return false; + } + + public boolean hasQuestionnaire(String title) { + Iterator it = questionBank.iterator(); + while (it.hasNext()) { + Question obj = it.next(); + if (obj.getTitle().equalsIgnoreCase(title)) { + return true; + } + } + return false; + } + + public boolean addQuestionnaireGlobal(Questionnaire questionnaire) { + if (!hasQuestionnaire(questionnaire.getTitle())) { + questionnaireBank.add(questionnaire); + this.numberQuestionnaires++; + return true; + } + return false; + } + + public String[] listQuestions() { + String list[] = new String[this.numberQuestions]; + Iterator it = questionBank.iterator(); + while (it.hasNext()) { + int i = 0; + Question obj = it.next(); + System.out.println(obj.getTitle() + "\n"); + list[i] = obj.getTitle(); + + } + return list; + } + + public String[] listQuestionnaires() { + String list[] = new String[this.numberQuestionnaires]; + Iterator it = questionnaireBank.iterator(); + while (it.hasNext()) { + int i = 0; + Questionnaire obj = it.next(); + System.out.println(obj.getTitle() + "\n"); + list[i] = obj.getTitle(); + } + return list; + } + + public Question getQuestion(String title) { + Iterator it = questionBank.iterator(); + while (it.hasNext()) { + Question obj = it.next(); + if (obj.getTitle().equals(title)) + return obj; + + } + System.out.println("Questão não encontrada"); + return null; + } + + public Questionnaire getQuestionnaire(String title) { + Iterator it = questionnaireBank.iterator(); + while (it.hasNext()) { + Questionnaire obj = it.next(); + if (obj.getTitle().equals(title)) + return obj; + + } + System.out.println("Questionário não encontrado"); + return null; + } + +} diff --git a/example-apps/src/campus/gui/CreateQuestion.java b/example-apps/src/campus/gui/CreateQuestion.java new file mode 100644 index 0000000..3cae7ca --- /dev/null +++ b/example-apps/src/campus/gui/CreateQuestion.java @@ -0,0 +1,150 @@ +package gui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Toolkit; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.border.EmptyBorder; +import javax.swing.JOptionPane; +import javax.swing.JTextField; +import javax.swing.JLabel; +import javax.swing.JTextArea; +import javax.swing.DropMode; + +import java.awt.TextArea; + +import javax.swing.JScrollPane; + +import application.Application; +import create.Question; + +import java.awt.Button; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + +public class CreateQuestion extends JFrame { + private int count = 0; + private JPanel contentPane; + private JTextField textFieldTituloQuestao; + private JLabel lbEnunciado; + private JLabel lbRespostaCorreta; + private JTextField textFieldRespostaCorreta; + private Button buttonCriar; + + /** + * Launch the application. + */ + public static void main(String[] args) { + EventQueue.invokeLater(new Runnable() { + public void run() { + try { + CreateQuestion frame = new CreateQuestion(); + frame.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + /** + * Create the frame. + */ + public CreateQuestion() { + setResizable(false); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setBounds(100, 100, 666, 311); + contentPane = new JPanel(); + contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + setContentPane(contentPane); + contentPane.setLayout(null); + + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension tamanhoTela = kit.getScreenSize(); + + int width = tamanhoTela.width; + int height = tamanhoTela.height; + + this.setLocation( (width / 2) - (666/2), (height / 2) - (311/2) ); + + + JLabel lbTituloQuestao = new JLabel("T\u00EDtulo da Quest\u00E3o: *"); + lbTituloQuestao.setBounds(27, 16, 147, 14); + contentPane.add(lbTituloQuestao); + + textFieldTituloQuestao = new JTextField(); + + + textFieldTituloQuestao.setBounds(27, 41, 597, 20); + contentPane.add(textFieldTituloQuestao); + textFieldTituloQuestao.setColumns(10); + + lbEnunciado = new JLabel("Enunciado:"); + lbEnunciado.setBounds(27, 75, 77, 14); + contentPane.add(lbEnunciado); + final JTextArea textAreaEnunciado = new JTextArea(""); + + + textAreaEnunciado.setLineWrap(true); + JScrollPane scrollEnunciado = new JScrollPane(textAreaEnunciado, + JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, + JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + + scrollEnunciado.setBounds(27, 100, 597, 63); + scrollEnunciado.setEnabled(true); + scrollEnunciado.setVisible(true); + contentPane.add(scrollEnunciado); + + lbRespostaCorreta = new JLabel("Resposta Correta:"); + lbRespostaCorreta.setBounds(27, 175, 137, 14); + contentPane.add(lbRespostaCorreta); + + textFieldRespostaCorreta = new JTextField(); + + textFieldRespostaCorreta.setBounds(27, 200, 217, 20); + contentPane.add(textFieldRespostaCorreta); + textFieldRespostaCorreta.setColumns(10); + + Button buttonCancelar = new Button("Cancelar"); + buttonCancelar.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + StartingScreen window = new StartingScreen(); + window.frame.setVisible(true); + dispose(); + } + }); + buttonCancelar.setBounds(466, 240, 70, 22); + contentPane.add(buttonCancelar); + + buttonCriar = new Button("Criar"); + buttonCriar.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if(!textFieldTituloQuestao.getText().equals("") && !textAreaEnunciado.getText().equals("") && !textFieldRespostaCorreta.getText().equals("")){ + if (Application.global.addQuestionGlobal(new Question(textFieldTituloQuestao.getText(), textAreaEnunciado.getText(), + textFieldRespostaCorreta.getText()))) { + System.out.println("Questão adicionada"); + StartingScreen window = new StartingScreen(); + window.frame.setVisible(true); + dispose(); + + } else + JOptionPane.showMessageDialog(null,"A questão já existe no banco, por favor, insira outro nome","Não Adicionado",JOptionPane.INFORMATION_MESSAGE); + + + }else{ + JOptionPane.showMessageDialog(null,"Preencha todos os campos","Falta de Informação",JOptionPane.INFORMATION_MESSAGE); + } + } + }); + buttonCriar.setBounds(554, 240, 70, 22); + contentPane.add(buttonCriar); + + } +} diff --git a/example-apps/src/campus/gui/ListQuestions.java b/example-apps/src/campus/gui/ListQuestions.java new file mode 100644 index 0000000..0c265c7 --- /dev/null +++ b/example-apps/src/campus/gui/ListQuestions.java @@ -0,0 +1,169 @@ +package gui; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Toolkit; + +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.border.EmptyBorder; +import javax.swing.event.ListSelectionEvent; +import javax.swing.JList; +import javax.swing.DefaultListCellRenderer; +import javax.swing.SwingUtilities; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import create.Question; +import application.Application; + +import javax.swing.SwingConstants; +import javax.swing.JButton; + +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + +public class ListQuestions extends JFrame { + + Question obj; + private JPanel contentPane; + + /** + * Launch the application. + */ + public static void main(String[] args) { + EventQueue.invokeLater(new Runnable() { + public void run() { + try { + ListQuestions frame = new ListQuestions(); + frame.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + /** + * Create the frame. + */ + public ListQuestions() { + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setBounds(100, 100, 450, 508); + contentPane = new JPanel(); + contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + setContentPane(contentPane); + + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension tamanhoTela = kit.getScreenSize(); + + int width = tamanhoTela.width; + int height = tamanhoTela.height; + + this.setLocation( (width / 2) - (450/2), (height / 2) - (508/2) ); + + + + final JList list = new JList(Application.global.questionBank.toArray()); + + list.setVisibleRowCount(10); + list.setCellRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, + Object value, int index, boolean isSelected, + boolean cellHasFocus) { + Component renderer = super.getListCellRendererComponent(list, + value, index, isSelected, cellHasFocus); + if (renderer instanceof JLabel && value instanceof Question) { + ((JLabel) renderer).setText(((Question) value).getTitle()); + } + return renderer; + } + }); + + final JLabel label = new JLabel("AQUI"); + + JScrollPane pane = new JScrollPane(list); + pane.setBounds(5, 5, 424, 251); + + contentPane.setLayout(null); + + contentPane.add(pane); + + JLabel lblT = new JLabel("T\u00EDtulo: "); + lblT.setBounds(5, 267, 83, 14); + contentPane.add(lblT); + + final JLabel lbtitulo = new JLabel(" -- titulo da questão"); + lbtitulo.setBounds(72, 267, 352, 14); + contentPane.add(lbtitulo); + + JLabel lblResposta = new JLabel("Resposta:"); + lblResposta.setBounds(5, 292, 83, 14); + contentPane.add(lblResposta); + + final JLabel lbresposta = new JLabel(" -- resposta correta"); + lbresposta.setBounds(72, 292, 352, 14); + contentPane.add(lbresposta); + + JLabel lblEnunciado = new JLabel("Enunciado:"); + lblEnunciado.setBounds(5, 317, 83, 14); + contentPane.add(lblEnunciado); + + final JLabel lbenunciado = new JLabel(" -- enunciado"); + lbenunciado.setVerticalAlignment(SwingConstants.TOP); + lbenunciado.setBounds(72, 317, 352, 97); + contentPane.add(lbenunciado); + + final JButton btnNewButton = new JButton("Deletar"); + btnNewButton.setEnabled(false); + btnNewButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + if (Application.global.removeQuestion(obj.getTitle())) { + JOptionPane.showMessageDialog(null, "Questão deletada", + "Sucesso", JOptionPane.INFORMATION_MESSAGE); + ListQuestions frame = new ListQuestions(); + frame.setVisible(true); + dispose(); + } else { + JOptionPane.showMessageDialog(null, + "Questão NÃO deletada, ocorreu algum imprevisto", + "ERRO", JOptionPane.INFORMATION_MESSAGE); + } + } + }); + btnNewButton.setBounds(335, 435, 89, 23); + contentPane.add(btnNewButton); + + list.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent arg0) { + if (!arg0.getValueIsAdjusting()) { + obj = (Question) list.getSelectedValue(); + if (obj != null) { + lbtitulo.setText(obj.getTitle()); + lbresposta.setText(obj.getAnswer()); + lbenunciado.setText(obj.getDescription()); + } + btnNewButton.setEnabled(true); + } + } + }); + + JButton btnVoltar = new JButton("Voltar"); + btnVoltar.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + StartingScreen window = new StartingScreen(); + window.frame.setVisible(true); + dispose(); + } + }); + btnVoltar.setBounds(231, 435, 89, 23); + contentPane.add(btnVoltar); + } +} diff --git a/example-apps/src/campus/gui/QuestionarioUsuario.java b/example-apps/src/campus/gui/QuestionarioUsuario.java new file mode 100644 index 0000000..42db4fb --- /dev/null +++ b/example-apps/src/campus/gui/QuestionarioUsuario.java @@ -0,0 +1,227 @@ +package gui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Toolkit; + +import javax.swing.ImageIcon; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.border.EmptyBorder; +import javax.swing.JLabel; +import javax.swing.JTextField; + +import java.awt.Cursor; + +import javax.swing.SwingConstants; + +import java.awt.Panel; + +import javax.swing.Icon; +import javax.swing.JTextArea; + +import create.Question; +import application.Application; + +import java.awt.Color; +import java.awt.SystemColor; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Iterator; + +import javax.swing.JButton; + +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + +public class QuestionarioUsuario extends JFrame { + + private JPanel contentPane; + private JTextField textField; + + /** + * Launch the application. + */ + public static void main(String[] args) { + EventQueue.invokeLater(new Runnable() { + public void run() { + try { + QuestionarioUsuario frame = new QuestionarioUsuario("", "", + 0); + frame.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + /** + * Create the frame. + */ + public QuestionarioUsuario(String titulo, String enunciado, int numero) { + System.out.println(Application.questaoAtual); + System.out + .println("Arraysize: " + Application.selectedQuestions.size()); + setResizable(false); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setBounds(100, 100, 666, 311); + contentPane = new JPanel(); + contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + setContentPane(contentPane); + contentPane.setLayout(null); + + + JLabel label = new JLabel("" + numero + ")"); + label.setBounds(10, 11, 46, 14); + contentPane.add(label); + + textField = new JTextField(); + textField.setBounds(69, 233, 86, 20); + textField.setText(Application.arrayAnswer[Application.questaoAtual]); + contentPane.add(textField); + textField.setColumns(10); + + JLabel label_1 = new JLabel("R - "); + label_1.setBounds(10, 236, 46, 14); + contentPane.add(label_1); + + Panel panel = new Panel(); + panel.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent arg0) { + int i = 1; + Question[] array = new Question[Application.selectedQuestions + .size() + 1]; + Iterator it = Application.selectedQuestions + .iterator(); + while (it.hasNext()) { + Question obj = it.next(); + array[i] = obj; + i++; + } + if (Application.questaoAtual < Application.selectedQuestions + .size()) { + Application.arrayAnswer[Application.questaoAtual] = textField.getText(); + Application.questaoAtual++; + QuestionarioUsuario f = new QuestionarioUsuario( + array[Application.questaoAtual].getTitle(), + array[Application.questaoAtual] + .getDescription(), + Application.questaoAtual); + + + f.setVisible(true); + dispose(); + } + + } + }); + panel.setBackground(SystemColor.control); + panel.setBounds(625, 233, 25, 25); + ImageIcon pic = new ImageIcon( + "10409969_688739357883672_1590550356_n.jpg"); + panel.add(new JLabel(pic)); + contentPane.add(panel); + + Panel panel_1 = new Panel(); + panel_1.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + int i = 1; + Question[] array = new Question[Application.selectedQuestions + .size() + 1]; + Iterator it = Application.selectedQuestions + .iterator(); + while (it.hasNext()) { + Question obj = it.next(); + array[i] = obj; + i++; + } + if (Application.questaoAtual > 1) { + Application.questaoAtual--; + QuestionarioUsuario f = new QuestionarioUsuario( + array[Application.questaoAtual].getTitle(), + array[Application.questaoAtual] + .getDescription(), + Application.questaoAtual); + + f.setVisible(true); + + dispose(); + } + + } + }); + panel_1.setBackground(SystemColor.control); + panel_1.setBounds(585, 233, 25, 25); + ImageIcon pic_1 = new ImageIcon( + "10568009_688739361217005_488992022_n.jpg"); + panel_1.add(new JLabel(pic_1)); + contentPane.add(panel_1); + + JLabel label_2 = new JLabel((Icon) null); + panel_1.add(label_2); + + JTextArea textArea = new JTextArea(enunciado); + textArea.setLineWrap(true); + textArea.setEditable(false); + textArea.setBackground(SystemColor.control); + textArea.setBounds(66, 11, 584, 190); + contentPane.add(textArea); + + JButton btnNewButton = new JButton("Terminar"); + btnNewButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + Application.arrayAnswer[Application.questaoAtual] = textField.getText(); + int count = 0; + for (int i = 1; i < Application.arrayAnswer.length; i++) { + System.out.println("Resposta: " + i + " " + Application.arrayAnswer[i]); + System.out.println("Resposta Correta: " + i + " " + Application.arrayAnswerCorrect[i]); + if(Application.arrayAnswer[i].equals(Application.arrayAnswerCorrect[i])){ + count++; + } + } + System.out.println(count + " e " + Application.arrayAnswer.length); + double total = ((double) (count) / (double) (Application.arrayAnswer.length-1)); + System.out.println(total); + String results; + if (total > 0) + results = new DecimalFormat("#.##").format(total*100); + else + results = "0.00"; + JOptionPane.showMessageDialog(null,results+" %","Resultado",JOptionPane.INFORMATION_MESSAGE); + StartingScreen window = new StartingScreen(); + Application.questaoAtual = 1; + Application.selectedQuestions = new ArrayList(); + window.frame.setVisible(true); + dispose(); + } + }); + + btnNewButton.setBounds(289, 248, 89, 23); + contentPane.add(btnNewButton); + + if (Application.questaoAtual == Application.selectedQuestions.size()) { + btnNewButton.setVisible(true); + panel.setVisible(false); + panel_1.setVisible(true); + } else { + btnNewButton.setVisible(false); + panel.setVisible(true); + panel_1.setVisible(true); + } + + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension tamanhoTela = kit.getScreenSize(); + + int width = tamanhoTela.width; + int height = tamanhoTela.height; + + this.setLocation((width / 2) - (666 / 2), (height / 2) - (311 / 2)); + } +} diff --git a/example-apps/src/campus/gui/StartingScreen.java b/example-apps/src/campus/gui/StartingScreen.java new file mode 100644 index 0000000..1eb79cf --- /dev/null +++ b/example-apps/src/campus/gui/StartingScreen.java @@ -0,0 +1,147 @@ +package gui; + +import globals.Banks; + +import java.awt.EventQueue; + +import javax.swing.JFrame; +import javax.swing.JLabel; + +import java.awt.Font; + +import javax.swing.JButton; + +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; +import java.awt.Dimension; +import java.awt.Panel; +import java.awt.Color; +import java.awt.Toolkit; +import java.util.ArrayList; +import java.util.Iterator; + +import javax.swing.SwingConstants; + +import application.Application; +import create.Question; +import create.Questionnaire; + +public class StartingScreen { + + public JFrame frame; + + /** + * Launch the application. + */ + public static void main(String[] args) { + EventQueue.invokeLater(new Runnable() { + public void run() { + try { + StartingScreen window = new StartingScreen(); + window.frame.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + /** + * Create the application. + * + * @wbp.parser.entryPoint + */ + public StartingScreen() { + initialize(); + } + + /** + * Initialize the contents of the frame. + */ + private void initialize() { + frame = new JFrame(); + frame.setResizable(false); + frame.setBounds(100, 100, 447, 257); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().setLayout(null); + + JLabel lblBancoDeQuestes = new JLabel("Question\u00E1rio"); + lblBancoDeQuestes.setFont(new Font("Lucida Sans Unicode", Font.PLAIN, + 16)); + lblBancoDeQuestes.setBounds(164, 21, 109, 14); + frame.getContentPane().add(lblBancoDeQuestes); + + JButton btnSair = new JButton("Sair"); + btnSair.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + frame.dispose(); + } + }); + btnSair.setBounds(231, 186, 89, 23); + frame.getContentPane().add(btnSair); + + Panel panel = new Panel(); + panel.setForeground(Color.BLACK); + panel.setBackground(Color.LIGHT_GRAY); + panel.setBounds(88, 72, 255, 72); + frame.getContentPane().add(panel); + + Toolkit kit = Toolkit.getDefaultToolkit(); + Dimension tamanhoTela = kit.getScreenSize(); + + int width = tamanhoTela.width; + int height = tamanhoTela.height; + + frame.setLocation((width / 2) - (447 / 2), (height / 2) - (257 / 2)); + + JButton btnCriarQuestoes = new JButton("Criar Quest\u00E3o"); + btnCriarQuestoes.setBounds(65, 11, 126, 23); + btnCriarQuestoes.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + CreateQuestion window = new CreateQuestion(); + window.setVisible(true); + frame.dispose(); + } + }); + panel.setLayout(null); + panel.add(btnCriarQuestoes); + + JButton btnAcessarBancoQ = new JButton("Acessar Banco de Questões"); + btnAcessarBancoQ.setBounds(27, 39, 200, 23); + + // btnAcessarBancoQ.addActionListener(new ActionListener(){ + // public void actionPerformed() + // }); + panel.add(btnAcessarBancoQ); + + JButton btnCriarQuestionario = new JButton("Criar"); + btnCriarQuestionario.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + Application.questionsToSelect = new ArrayList(); + Application.selectedQuestions = new ArrayList(); + for (int i = 0; i < Banks.questionBank.size(); i++) + Application.questionsToSelect.add(Banks.questionBank.get(i)); + CreateQuestion frame2 = new CreateQuestion(); + frame2.setVisible(true); + frame.dispose(); + } + }); + + if (Banks.numberQuestions > 0) { + btnCriarQuestionario.setEnabled(true); + } else { + btnCriarQuestionario.setEnabled(false); + } + btnCriarQuestionario.setBounds(330, 186, 89, 23); + frame.getContentPane().add(btnCriarQuestionario); + btnAcessarBancoQ.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + + ListQuestions lista = new ListQuestions(); + lista.setVisible(true); + frame.dispose(); + } + }); + + } +} diff --git a/example-apps/src/campus/test.java b/example-apps/src/campus/test.java new file mode 100644 index 0000000..6224f82 --- /dev/null +++ b/example-apps/src/campus/test.java @@ -0,0 +1,165 @@ +import globals.Banks; + +import java.text.DecimalFormat; +import java.util.Scanner; + +import create.Question; +import create.Questionnaire; + +public class test { + + @SuppressWarnings("unused") + public static void main(String[] args) { + Banks global = new Banks(); + while (true) { + System.out.println("----------------Q&A----------------" + + "\n1 - Criar Questões" + "\n2 - Criar Questionario" + + "\n3 - Ver Banco Questões" + + "\n4 - Ver Banco Questionário" + + "\n5 - Responder Questionário" + "\n6 - Sair" + + "\n---------------------MENU--------------------"); + int select = new Scanner(System.in).nextInt(); + switch (select) { + case 1: + System.out.println("Digite o titulo"); + String titulo = new Scanner(System.in).nextLine(); + System.out.println("Digite a Descrição"); + String descricao = new Scanner(System.in).nextLine(); + System.out.println("Digite a Resposta"); + String resposta = new Scanner(System.in).nextLine(); + if (global.addQuestionGlobal(new Question(titulo, descricao, + resposta))) { + System.out.println("Questão adicionada"); + + } else + System.out + .println("A questão já existe no banco, por favor, insira outro nome"); + + break; + case 2: + if (global.numberQuestions == 0) { + System.out + .println("Crie alguma questão para fazer um questionário"); + } else { + System.out.println("Digite um titulo"); + String tituloQuestionnaire = new Scanner(System.in) + .nextLine(); + System.out.println("Digite numero de questões"); + int num = new Scanner(System.in).nextInt(); + System.out.println("Digite o nome das questões:"); + String[] questions = new String[num]; + for (int i = 0; i < num; i++) { + questions[i] = new Scanner(System.in).nextLine(); + System.out + .println("Nome adicionado, caso não existir, não constará no questionário"); + } + global.addQuestionnaireGlobal(new Questionnaire( + tituloQuestionnaire, num, questions, global)); + } + break; + case 3: + if (global.numberQuestions > 0) { + String get[] = new String[global.numberQuestions]; + get = global.listQuestions(); + System.out + .println("Digite a questão que deseja visualizar: "); + String name = new Scanner(System.in).nextLine(); + Question q = global.getQuestion(name); + if (!(q == null) && q.getTitle().equals(name)) { + System.out.println("Título:"); + System.out.println(q.getTitle()); + System.out.println("Enunciado:"); + System.out.println(q.getDescription()); + System.out.println("Resposta:"); + System.out.println(q.getAnswer()); + } else { + System.out.println("A questão não existe"); + } + } else + System.out + .println("Não há questões disponíveis para listar"); + break; + case 4: + if (global.numberQuestionnaires > 0) { + String getQuestionnaire[] = new String[global.numberQuestions]; + getQuestionnaire = global.listQuestionnaires(); + System.out + .println("Digite o questionário que deseja visualizar: "); + String name = new Scanner(System.in).nextLine(); + Questionnaire q = global.getQuestionnaire(name); + if (!(q == null) && q.getTitle().equals(name)) { + System.out.println("Título:"); + System.out.println(q.getTitle()); + System.out.println("questões:"); + Question[] var = q.getAllQuestions( + q.getQuestionNames(), global); + for (int i = 0; i < var.length; i++) { + System.out.println(var[i].getTitle()); + } + + System.out.println("Número de Questões:"); + System.out.println(q.getQuestionsNumber()); + } else { + System.out.println("A questão não existe"); + } + } else { + System.out.println("Não há questionários para listar"); + } + break; + case 5: + int count = 0; + String getQuestionnaireAns[] = global.listQuestionnaires(); + System.out.println("Qual questionário responder?"); + String name = new Scanner(System.in).nextLine(); + Questionnaire q = global.getQuestionnaire(name); + if (!(q == null) && q.getTitle().equals(name)) { + System.out.println("Título:"); + System.out.println(q.getTitle()); + Question[] var = q.getAllQuestions(q.getQuestionNames(), + global); + for (int i = 0; i < var.length; i++) { + System.out.println(var[i].getTitle() + + "\nLeia com atenção e responda:" + "\n" + + var[i].getDescription()); + String answer = new Scanner(System.in).nextLine(); + var[i].setUserAnswer(answer); + } + + System.out.println("Resumo:"); + for (int i = 0; i < var.length; i++) { + + System.out.println("Questão " + (i + 1) + ":"); + if (!(var[i].getAnswer().equals(var[i].getUserAnswer()))) { + System.out.println("Resposta usuário: " + + var[i].getUserAnswer() + " Correta: " + + var[i].getAnswer() + " ERROU"); + } else { + System.out.println("Resposta usuário: " + + var[i].getUserAnswer() + " Correta: " + + var[i].getAnswer() + " ACERTOU"); + count++; + } + + } + String total; + if (count / var.length > 0) + total = new DecimalFormat("#.00").format(count + / var.length); + else + total = "0.00"; + + System.out.println("Total: " + total); + } else { + System.out.println("A questão não existe"); + } + + case 6: + System.exit(0); + break; + default: + System.out.println("Comando não reconhecido"); + } + + } + } +} diff --git a/example-apps/src/chat/chat/client/ChatClient.java b/example-apps/src/chat/chat/client/ChatClient.java new file mode 100644 index 0000000..2b99824 --- /dev/null +++ b/example-apps/src/chat/chat/client/ChatClient.java @@ -0,0 +1,1943 @@ +package chat.client; + +import java.awt.Color; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.MenuShortcut; +import java.awt.TextArea; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.PrintWriter; +import java.net.Socket; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JColorChooser; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JTextField; +import sun.audio.AudioPlayer; +import sun.audio.AudioStream; + + +enum StateOfClient {CONNECTED, DISCONNECTED}; +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author Administrator + */ +public class ChatClient extends JFrame { + private JPanel panel1; + private JPanel panel2; + private JPanel panel3; + private TextArea textArea1; + private TextArea textArea2; + private TextField textField; + private Calendar calendar; + private String chat_entry; + private PrintWriter out; + private BufferedReader in; + private String IP; + private int PORT; + private String SocketEntryMessage; + private String SocketEntryName; + private JButton button_send; + private JFrame connect; + private JTextField name_field; + private JTextField ip_field1; + private JTextField ip_field2; + private JTextField ip_field3; + private JTextField ip_field4; + private JTextField port_field; + private Socket connectionWithServer; + private MenuItem menu_connect; + private MenuItem menu_disconnect; + private Boolean running; + private String name_field_entry; + private String ip_field1_entry; + private String ip_field2_entry; + private String ip_field3_entry; + private String ip_field4_entry; + private String port_field_entry; + private String pw_field_entry; + private JFrame fonts_color_frame; + private JFrame background_color_frame; + private JColorChooser font_color_chooser; + private JColorChooser background_color_chooser; + private Color background_color; + private Color font_color; + private JPasswordField password; + private MenuItem menu_about; + private JFrame about; + private MenuItem menu_fonts_color; + private MenuItem menu_background_color; + private StateOfClient state; + private MenuItem menu_sounds; + private JFrame sounds_frame; + private JComboBox[] choice; + private JButton[] play; + private JCheckBox[] checkbox; + private String[] selected_sounds; + private int[] selected_sounds_index; + private Boolean[] enabled_sounds; + private Settings settings; + private ArrayList last_used; + private int last_used_index; + private String connected_hand_shake; + private String disconnected_hand_shake; + private String whois_hand_shake; + private int i; + public static final int NUM_OF_SOUNDS = 6; + public static final int MAX_SIZE_OF_NAME = 15; + public static final int NUMBER_OF_LAST_USED = 40; + + + public ChatClient() { + super(); + setSize(796, 508); + setTitle("Chat Client BETA"); + setResizable(false); + + loadSettings(); + + background_color = settings.getBackgroundColor(); + getContentPane().setBackground(background_color); + + font_color = settings.getFontColor(); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + + try { + out.close(); + in.close(); + connectionWithServer.close(); + } + catch (Exception ex) {} + + System.exit(0); + + } + }); + + + chat_entry = ""; + SocketEntryMessage = ""; + SocketEntryName = ""; + + running = true; + state = StateOfClient.DISCONNECTED; + + name_field_entry = settings.getNameFieldEntry(); + ip_field1_entry = settings.getIpField1Entry(); + ip_field2_entry = settings.getIpField2Entry(); + ip_field3_entry = settings.getIpField3Entry(); + ip_field4_entry = settings.getIpField4Entry(); + port_field_entry = settings.getPortEntry(); + + selected_sounds = new String[NUM_OF_SOUNDS]; + selected_sounds_index = new int[NUM_OF_SOUNDS]; + enabled_sounds = new Boolean[NUM_OF_SOUNDS]; + + selected_sounds[0] = settings.getSelectedSounds()[0]; + selected_sounds[1] = settings.getSelectedSounds()[1]; + selected_sounds[2] = settings.getSelectedSounds()[2]; + selected_sounds[3] = settings.getSelectedSounds()[3]; + selected_sounds[4] = settings.getSelectedSounds()[4]; + selected_sounds[5] = settings.getSelectedSounds()[5]; + + for(i = 0; i < NUM_OF_SOUNDS; i++) { + selected_sounds_index[i] = settings.getSelectedSoundsIndex()[i]; + enabled_sounds[i] = settings.getEnabledSounds()[i]; + } + + last_used = new ArrayList(NUMBER_OF_LAST_USED); + last_used_index = 0; + + KeyListener keylistener = new KeyListener() { + + public void keyTyped(KeyEvent e) { + + } + + public void keyPressed(KeyEvent e) { + + switch (e.getKeyCode()) { + case KeyEvent.VK_ENTER : + chat_entry = textField.getText(); + if(chat_entry.length() > 0) { + if(state == StateOfClient.DISCONNECTED) { + if(chat_entry.equals("/help")) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Available Commands:\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/quit\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/disconnect\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/whois \"name\"\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + else { + if(chat_entry.equals("/quit")) { + try { + out.close(); + in.close(); + connectionWithServer.close(); + } + catch(Exception ex) {} + System.exit(0); + } + else { + if(chat_entry.equals("/disconnect")) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "You are not connected to any Server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + else { + if(chat_entry.length() > 7 && chat_entry.substring(0, 7).equals("/whois ")) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "You are not connected to any Server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + else { + if(chat_entry.charAt(0) == '/') { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Unknown command.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + else { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "You are not connected to any Server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + } + } + } + } + + if(enabled_sounds[5]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[5] + ".wav"); + } + catch(FileNotFoundException ex) { + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) { + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + + AudioPlayer.player.start(as); + } + } + else { + if(chat_entry.equals("/help")) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Available Commands:\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/quit\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/disconnect\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/whois \"name\"\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + else { + if(chat_entry.equals("/quit")) { + try { + out.close(); + in.close(); + connectionWithServer.close(); + } + catch(Exception ex) {} + System.exit(0); + } + else { + if(chat_entry.equals("/disconnect")) { + disconnect(); + textField.setText(""); + } + else { + if(chat_entry.length() > 7 && chat_entry.substring(0, 7).equals("/whois ")) { + out.println(whois_hand_shake); + out.println(chat_entry.substring(7, chat_entry.length())); + textField.setText(""); + } + else { + if(chat_entry.charAt(0) == '/') { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Unknown command.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + + if(enabled_sounds[5]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[5] + ".wav"); + } + catch(FileNotFoundException ex) { + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) { + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + + AudioPlayer.player.start(as); + } + } + else { + out.println(chat_entry); + textField.setText(""); + } + } + } + } + } + } + textField.requestFocus(); + lastUsedListInsertion(); + } + break; + case KeyEvent.VK_UP : + if(textField.isFocusOwner() && last_used.size() > 0) { + textField.setText(last_used.get(last_used_index)); + textField.setCaretPosition(textField.getCaretPosition() + last_used.get(last_used_index).length()); + if(last_used_index > 0) { + last_used_index--; + } + else { + last_used_index = last_used.size() - 1; + } + } + break; + case KeyEvent.VK_DOWN : + if(textField.isFocusOwner() && last_used.size() > 0) { + if(last_used_index < last_used.size() - 1) { + last_used_index++; + } + else { + last_used_index = 0; + } + textField.setText(last_used.get(last_used_index)); + textField.setCaretPosition(textField.getCaretPosition() + last_used.get(last_used_index).length()); + } + break; + } + } + + public void keyReleased(KeyEvent e) { + + switch (e.getKeyCode()) { + case KeyEvent.VK_UP : + textField.setCaretPosition(textField.getCaretPosition() + 1); + break; + } + + } + + }; + + + + panel1 = new JPanel(); + panel2 = new JPanel(); + panel3 = new JPanel(); + + setLayout(new FlowLayout()); + textArea1 = new TextArea(25, 87); + textArea1.setEditable(false); + textArea1.setBackground(Color.WHITE); + textArea1.setForeground(font_color); + + textArea2 = new TextArea(25, 14); + textArea2.setEditable(false); + textArea2.setFont(new Font("Bold", Font.BOLD, 12)); + textArea2.setBackground(Color.WHITE); + textArea2.setForeground(font_color); + + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Type /help to get the available commands.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + + textField = new TextField(87); + textField.setForeground(font_color); + textField.requestFocus(); + textField.addKeyListener(keylistener); + + + button_send = new JButton("Send"); + + button_send.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + chat_entry = textField.getText(); + if(chat_entry.length() > 0) { + if(state == StateOfClient.DISCONNECTED) { + if(chat_entry.equals("/help")) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Available Commands:\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/quit\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/disconnect\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/whois \"name\"\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + else { + if(chat_entry.equals("/quit")) { + try { + out.close(); + in.close(); + connectionWithServer.close(); + } + catch(Exception ex) {} + System.exit(0); + } + else { + if(chat_entry.equals("/disconnect")) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "You are not connected to any Server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + else { + if(chat_entry.length() > 7 && chat_entry.substring(0, 7).equals("/whois ")) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "You are not connected to any Server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + else { + if(chat_entry.charAt(0) == '/') { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Unknown command.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + else { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "You are not connected to any Server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + } + } + } + } + + if(enabled_sounds[5]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[5] + ".wav"); + } + catch(FileNotFoundException ex) { + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) { + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + + AudioPlayer.player.start(as); + } + } + else { + if(chat_entry.equals("/help")) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Available Commands:\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/quit\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/disconnect\n"); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "/whois \"name\"\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + } + else { + if(chat_entry.equals("/quit")) { + try { + out.close(); + in.close(); + connectionWithServer.close(); + } + catch(Exception ex) {} + System.exit(0); + } + else { + if(chat_entry.equals("/disconnect")) { + disconnect(); + textField.setText(""); + } + else { + if(chat_entry.length() > 7 && chat_entry.substring(0, 7).equals("/whois ")) { + out.println(whois_hand_shake); + out.println(chat_entry.substring(7, chat_entry.length())); + textField.setText(""); + } + else { + if(chat_entry.charAt(0) == '/') { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Unknown command.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textField.setText(""); + + if(enabled_sounds[5]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[5] + ".wav"); + } + catch(FileNotFoundException ex) { + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) { + textField.requestFocus(); + lastUsedListInsertion(); + return; + } + + AudioPlayer.player.start(as); + } + } + else { + out.println(chat_entry); + textField.setText(""); + } + } + } + } + } + } + lastUsedListInsertion(); + } + textField.requestFocus(); + } + }); + + panel1.add(textArea1); + panel2.add(textArea2); + panel3.add(textField); + panel3.add(new JLabel(" ")); + panel3.add(button_send); + panel3.add(new JLabel(" ")); + + + + add(panel1); + add(new JLabel("")); + add(panel2); + add(panel3); + add(new JLabel(" ")); + + MenuBar menubar = new MenuBar(); + + Menu menu1 = new Menu("File"); + Menu menu2 = new Menu("Options"); + Menu menu3 = new Menu("Help"); + + menu_connect = new MenuItem("Connect"); + menu1.add(menu_connect); + menu_disconnect = new MenuItem("Disconnect"); + menu_disconnect.setEnabled(false); + menu1.addSeparator(); + menu1.add(menu_disconnect); + menu1.addSeparator(); + MenuItem menu_quit = new MenuItem("Quit"); + menu1.add(menu_quit); + + menu_fonts_color = new MenuItem("Fonts Color"); + menu_background_color = new MenuItem("Background Color"); + menu_sounds = new MenuItem("Sounds"); + + menu_about = new MenuItem("About"); + + menu_quit.setShortcut(new MenuShortcut(KeyEvent.VK_Q)); + menu_connect.setShortcut(new MenuShortcut(KeyEvent.VK_S)); + menu_disconnect.setShortcut(new MenuShortcut(KeyEvent.VK_D)); + menu_fonts_color.setShortcut(new MenuShortcut(KeyEvent.VK_F)); + menu_background_color.setShortcut(new MenuShortcut(KeyEvent.VK_B)); + menu_sounds.setShortcut(new MenuShortcut(KeyEvent.VK_U)); + menu_about.setShortcut(new MenuShortcut(KeyEvent.VK_A)); + + menu2.add(menu_fonts_color); + menu2.addSeparator(); + menu2.add(menu_background_color); + menu2.addSeparator(); + menu2.add(menu_sounds); + + menu3.add(menu_about); + + menubar.add(menu1); + menubar.add(menu2); + menubar.add(menu3); + + setMenuBar(menubar); + + menu_quit.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + out.close(); + in.close(); + connectionWithServer.close(); + } + catch (Exception ex) {} + System.exit(0); + } + }); + + menu_fonts_color.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + int color_window_width = 440; + int color_window_height = 420; + fonts_color_frame = new JFrame("Fonts Color"); + fonts_color_frame.setLayout(new FlowLayout()); + fonts_color_frame.setSize(color_window_width, color_window_height); + fonts_color_frame.setLocation((int)(getLocation().getX() + getSize().getWidth() / 2) - (color_window_width / 2), (int)(getLocation().getY() + getSize().getHeight() / 2) - (color_window_height / 2)); + fonts_color_frame.getContentPane().setBackground(background_color); + fonts_color_frame.setResizable(false); + menu_fonts_color.setEnabled(false); + font_color_chooser = new JColorChooser(); + fonts_color_frame.add(font_color_chooser); + + + fonts_color_frame.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + textField.requestFocus(); + menu_fonts_color.setEnabled(true); + fonts_color_frame.dispose(); + + } + }); + + JButton confirmButton = new JButton("Confirm"); + confirmButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + font_color = font_color_chooser.getColor(); + textArea1.setForeground(font_color); + textArea2.setForeground(font_color); + textField.setForeground(font_color); + try { + name_field.setForeground(font_color); + ip_field1.setForeground(font_color); + ip_field2.setForeground(font_color); + ip_field3.setForeground(font_color); + ip_field4.setForeground(font_color); + port_field.setForeground(font_color); + password.setForeground(font_color); + } + catch(NullPointerException ex) {} + + settings.setFontColor(font_color); + saveSettings(); + + textField.requestFocus(); + menu_fonts_color.setEnabled(true); + fonts_color_frame.dispose(); + } + }); + + JButton close = new JButton("Cancel"); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + textField.requestFocus(); + menu_fonts_color.setEnabled(true); + fonts_color_frame.dispose(); + } + }); + + fonts_color_frame.add(confirmButton); + fonts_color_frame.add(close); + + fonts_color_frame.setVisible(true); + + } + }); + + menu_background_color.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + int color_window_width = 440; + int color_window_height = 420; + background_color_frame = new JFrame("Background Color"); + background_color_frame.setLayout(new FlowLayout()); + background_color_frame.setSize(color_window_width, color_window_height); + background_color_frame.setLocation((int)(getLocation().getX() + getSize().getWidth() / 2) - (color_window_width / 2), (int)(getLocation().getY() + getSize().getHeight() / 2) - (color_window_height / 2)); + background_color_frame.getContentPane().setBackground(background_color); + background_color_frame.setResizable(false); + menu_background_color.setEnabled(false); + background_color_chooser = new JColorChooser(); + background_color_frame.add(background_color_chooser); + + + background_color_frame.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + textField.requestFocus(); + menu_background_color.setEnabled(true); + background_color_frame.dispose(); + + } + }); + + JButton confirmButton = new JButton("Confirm"); + confirmButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + textField.requestFocus(); + background_color = background_color_chooser.getColor(); + background_color_frame.setBackground(background_color); + getContentPane().setBackground(background_color); + + try { + connect.setBackground(background_color); + } + catch(NullPointerException ex) {} + + try { + sounds_frame.getContentPane().setBackground(background_color); + } + catch(NullPointerException ex) {} + + try { + fonts_color_frame.getContentPane().setBackground(background_color); + } + catch(NullPointerException ex) {} + + try { + about.getContentPane().setBackground(background_color); + } + catch(NullPointerException ex) {} + + settings.setBackgroundColor(background_color); + saveSettings(); + + menu_background_color.setEnabled(true); + background_color_frame.dispose(); + } + }); + + JButton close = new JButton("Cancel"); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + textField.requestFocus(); + menu_background_color.setEnabled(true); + background_color_frame.dispose(); + } + }); + + background_color_frame.add(confirmButton); + background_color_frame.add(close); + + background_color_frame.setVisible(true); + + } + }); + + menu_sounds.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + int sounds_window_width = 440; + int sounds_window_height = 316; + sounds_frame = new JFrame("Sounds"); + sounds_frame.setLayout(new FlowLayout()); + sounds_frame.setSize(sounds_window_width, sounds_window_height); + sounds_frame.setLocation((int)(getLocation().getX() + getSize().getWidth() / 2) - (sounds_window_width / 2), (int)(getLocation().getY() + getSize().getHeight() / 2) - (sounds_window_height / 2)); + sounds_frame.getContentPane().setBackground(background_color); + sounds_frame.setResizable(false); + menu_sounds.setEnabled(false); + + JPanel panel8 = new JPanel(); + JPanel panel9 = new JPanel(); + JPanel panel10 = new JPanel(); + JPanel panel11 = new JPanel(); + JPanel panel12 = new JPanel(); + JPanel panel13 = new JPanel(); + + panel8.setBackground(Color.LIGHT_GRAY); + panel9.setBackground(Color.LIGHT_GRAY); + panel10.setBackground(Color.LIGHT_GRAY); + panel11.setBackground(Color.LIGHT_GRAY); + panel12.setBackground(Color.LIGHT_GRAY); + panel13.setBackground(Color.LIGHT_GRAY); + + choice = new JComboBox[NUM_OF_SOUNDS]; + play = new JButton[NUM_OF_SOUNDS]; + checkbox = new JCheckBox[NUM_OF_SOUNDS]; + + for(i = 0; i < play.length; i++) { + checkbox[i] = new JCheckBox(); + checkbox[i].setSelected(enabled_sounds[i]); + checkbox[i].addActionListener(new ActionListener() { + int temp = i; + + public void actionPerformed(ActionEvent e) { + if(checkbox[temp].isSelected()) { + choice[temp].setEnabled(true); + play[temp].setEnabled(true); + } + else { + choice[temp].setEnabled(false); + play[temp].setEnabled(false); + } + } + }); + } + + + panel8.add(checkbox[0]); + panel8.add(new JLabel(" ")); + panel8.add(new JLabel("Connected")); + panel8.add(new JLabel(" ")); + String[] connected_sounds = {"connect1", "connect2", "connect3"}; + choice[0] = new JComboBox(connected_sounds); + + panel9.add(checkbox[1]); + panel9.add(new JLabel(" ")); + panel9.add(new JLabel("Disconnected")); + panel9.add(new JLabel(" ")); + String[] disconnected_sounds = {"disconnect1", "disconnect2"}; + choice[1] = new JComboBox(disconnected_sounds); + + panel10.add(checkbox[2]); + panel10.add(new JLabel(" ")); + panel10.add(new JLabel("User Connected")); + panel10.add(new JLabel(" ")); + String[] user_connected_sounds = {"userConnect1", "userConnect2", "userConnect3"}; + choice[2] = new JComboBox(user_connected_sounds); + + panel11.add(checkbox[3]); + panel11.add(new JLabel(" ")); + panel11.add(new JLabel("User Disconnected")); + panel11.add(new JLabel(" ")); + String[] user_disconnected_sounds = {"userDisconnect1", "userDisconnect2"}; + choice[3] = new JComboBox(user_disconnected_sounds); + + panel12.add(checkbox[4]); + panel12.add(new JLabel(" ")); + panel12.add(new JLabel("New Message")); + panel12.add(new JLabel(" ")); + String[] message_sounds = {"newMessage1", "newMessage2", "newMessage3", "newMessage4", "newMessage5"}; + choice[4] = new JComboBox(message_sounds); + + panel13.add(checkbox[5]); + panel13.add(new JLabel(" ")); + panel13.add(new JLabel("Warnings")); + panel13.add(new JLabel(" ")); + String[] not_connected_sounds = {"warning1", "warning2", "warning3"}; + choice[5] = new JComboBox(not_connected_sounds); + + + for(i = 0; i < play.length; i++) { + choice[i].setEnabled(enabled_sounds[i]); + choice[i].setSelectedIndex(selected_sounds_index[i]); + play[i] = new JButton("Play"); + play[i].setEnabled(enabled_sounds[i]); + play[i].addActionListener(new ActionListener() { + int temp = i; + + public void actionPerformed(ActionEvent e) { + String selected = (String)choice[temp].getSelectedItem(); + + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected + ".wav"); + } + catch(FileNotFoundException ex) { + return; + } + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) { + return; + } + + AudioPlayer.player.start(as); + } + }); + } + + + panel8.add(choice[0]); + panel8.add(new JLabel(" ")); + panel8.add(play[0]); + + panel9.add(choice[1]); + panel9.add(new JLabel(" ")); + panel9.add(play[1]); + + panel10.add(choice[2]); + panel10.add(new JLabel(" ")); + panel10.add(play[2]); + + panel11.add(choice[3]); + panel11.add(new JLabel(" ")); + panel11.add(play[3]); + + panel12.add(choice[4]); + panel12.add(new JLabel(" ")); + panel12.add(play[4]); + + panel13.add(choice[5]); + panel13.add(new JLabel(" ")); + panel13.add(play[5]); + + + sounds_frame.add(panel8); + sounds_frame.add(panel9); + sounds_frame.add(panel10); + sounds_frame.add(panel11); + sounds_frame.add(panel12); + sounds_frame.add(panel13); + + + + sounds_frame.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + textField.requestFocus(); + menu_sounds.setEnabled(true); + sounds_frame.dispose(); + + } + }); + + JButton confirmButton = new JButton("Confirm"); + confirmButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + for(i = 0; i < NUM_OF_SOUNDS; i++) { + enabled_sounds[i] = checkbox[i].isSelected(); + selected_sounds_index[i] = choice[i].getSelectedIndex(); + selected_sounds[i] = (String)choice[i].getSelectedItem(); + } + + settings.setEnabledSounds(enabled_sounds); + settings.setSelectedSoundsIndex(selected_sounds_index); + settings.setSelectedSounds(selected_sounds); + saveSettings(); + + textField.requestFocus(); + menu_sounds.setEnabled(true); + sounds_frame.dispose(); + } + }); + + JButton close = new JButton("Cancel"); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + textField.requestFocus(); + menu_sounds.setEnabled(true); + sounds_frame.dispose(); + } + }); + + sounds_frame.add(confirmButton); + sounds_frame.add(close); + + sounds_frame.setVisible(true); + + } + }); + + menu_connect.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + int connect_window_width = 240; + int connect_window_height = 210; + + connect = new JFrame("Connection Options"); + connect.setSize(connect_window_width, connect_window_height); + connect.setLocation((int)(getLocation().getX() + getSize().getWidth() / 2) - (connect_window_width / 2), (int)(getLocation().getY() + getSize().getHeight() / 2) - (connect_window_height / 2)); + connect.getContentPane().setBackground(background_color); + connect.setResizable(false); + menu_connect.setEnabled(false); + + connect.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + + if(name_field_entry.length() < 1 || name_field_entry.length() > MAX_SIZE_OF_NAME) { + name_field_entry = ""; + } + + try { + if(Integer.parseInt(ip_field1_entry) < 0 || Integer.parseInt(ip_field1_entry) > 255) { + ip_field1_entry = ""; + } + } + catch(NumberFormatException ex) { + ip_field1_entry = ""; + } + + try { + if(Integer.parseInt(ip_field2_entry) < 0 || Integer.parseInt(ip_field2_entry) > 255) { + ip_field2_entry = ""; + } + } + catch(NumberFormatException ex) { + ip_field2_entry = ""; + } + + try { + if(Integer.parseInt(ip_field3_entry) < 0 || Integer.parseInt(ip_field3_entry) > 255) { + ip_field3_entry = ""; + } + } + catch(NumberFormatException ex) { + ip_field3_entry = ""; + } + + try { + if(Integer.parseInt(ip_field4_entry) < 0 || Integer.parseInt(ip_field4_entry) > 255) { + ip_field4_entry = ""; + } + } + catch(NumberFormatException ex) { + ip_field4_entry = ""; + } + + try { + if(Integer.parseInt(port_field_entry) < 0 || Integer.parseInt(port_field_entry) > 65535) { + port_field_entry = ""; + } + } + catch(NumberFormatException ex) { + port_field_entry = ""; + } + + settings.setNameFieldEntry(name_field_entry); + settings.setIpField1Entry(ip_field1_entry); + settings.setIpField2Entry(ip_field2_entry); + settings.setIpField3Entry(ip_field3_entry); + settings.setIpField4Entry(ip_field4_entry); + settings.setPortEntry(port_field_entry); + saveSettings(); + + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + + } + }); + + connect.setLayout(new FlowLayout()); + + name_field = new JTextField(10); + ip_field1 = new JTextField(2); + ip_field2 = new JTextField(2); + ip_field3 = new JTextField(2); + ip_field4 = new JTextField(2); + port_field = new JTextField(5); + password = new JPasswordField(10); + + name_field.setForeground(font_color); + ip_field1.setForeground(font_color); + ip_field2.setForeground(font_color); + ip_field3.setForeground(font_color); + ip_field4.setForeground(font_color); + port_field.setForeground(font_color); + password.setForeground(font_color); + + name_field.setText(name_field_entry); + ip_field1.setText(ip_field1_entry); + ip_field2.setText(ip_field2_entry); + ip_field3.setText(ip_field3_entry); + ip_field4.setText(ip_field4_entry); + port_field.setText(port_field_entry); + + JButton connectButton = new JButton("Connect"); + connectButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + + int error_found = 0; + + name_field_entry = name_field.getText(); + if(name_field_entry.length() < 1 || name_field_entry.length() > MAX_SIZE_OF_NAME) { + name_field.setBackground(Color.RED); + error_found++; + } + else { + name_field.setBackground(Color.WHITE); + } + + + ip_field1_entry = ip_field1.getText(); + try { + if(Integer.parseInt(ip_field1_entry) < 0 || Integer.parseInt(ip_field1_entry) > 255) { + ip_field1.setBackground(Color.RED); + error_found++; + } + else { + ip_field1.setBackground(Color.WHITE); + } + } + catch(NumberFormatException ex) { + ip_field1.setBackground(Color.RED); + error_found++; + } + + try { + ip_field2_entry = ip_field2.getText(); + if(Integer.parseInt(ip_field2_entry) < 0 || Integer.parseInt(ip_field2_entry) > 255) { + ip_field2.setBackground(Color.RED); + error_found++; + } + else { + ip_field2.setBackground(Color.WHITE); + } + } + catch(NumberFormatException ex) { + ip_field2.setBackground(Color.RED); + error_found++; + } + + try { + ip_field3_entry = ip_field3.getText(); + if(Integer.parseInt(ip_field3_entry) < 0 || Integer.parseInt(ip_field3_entry) > 255) { + ip_field3.setBackground(Color.RED); + error_found++; + } + else { + ip_field3.setBackground(Color.WHITE); + } + } + catch(NumberFormatException ex) { + ip_field3.setBackground(Color.RED); + error_found++; + } + + try { + ip_field4_entry = ip_field4.getText(); + if(Integer.parseInt(ip_field4_entry) < 0 || Integer.parseInt(ip_field4_entry) > 255) { + ip_field4.setBackground(Color.RED); + error_found++; + } + else { + ip_field4.setBackground(Color.WHITE); + } + } + catch(NumberFormatException ex) { + ip_field4.setBackground(Color.RED); + error_found++; + } + + if(error_found == 0) { + IP = ip_field1_entry + "." + ip_field2_entry + "." + ip_field3_entry + "." + ip_field4_entry; + } + + + try { + port_field_entry = port_field.getText(); + + if(Integer.parseInt(port_field_entry) < 0 || Integer.parseInt(port_field_entry) > 65535) { + port_field.setBackground(Color.RED); + error_found++; + } + else { + port_field.setBackground(Color.WHITE); + } + } + catch(NumberFormatException ex) { + port_field.setBackground(Color.RED); + error_found++; + } + + if(error_found == 0) { + PORT = Integer.valueOf(port_field_entry); + } + else { + return; + } + + pw_field_entry = String.copyValueOf(password.getPassword()); + + try { + + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Attempting to connect to " + IP + " .\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + + connectionWithServer = new Socket(IP, PORT); + + out = new PrintWriter(connectionWithServer.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(connectionWithServer.getInputStream())); + out.println(pw_field_entry); + + try { + while((in.readLine()).equals("waitForPasswordVerification")) {} + } + catch(NullPointerException ex) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Connection Failed, the password is incorrect.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + out = null; + in = null; + + if(enabled_sounds[1]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[1] + ".wav"); + } + catch(FileNotFoundException exc) { + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException exc) { + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + AudioPlayer.player.start(as); + } + + settings.setNameFieldEntry(name_field_entry); + settings.setIpField1Entry(ip_field1_entry); + settings.setIpField2Entry(ip_field2_entry); + settings.setIpField3Entry(ip_field3_entry); + settings.setIpField4Entry(ip_field4_entry); + settings.setPortEntry(port_field_entry); + saveSettings(); + + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + out.println(name_field_entry); + + try { + while((in.readLine()).equals("waitForNameChecking")) {} + connected_hand_shake = in.readLine(); + disconnected_hand_shake = in.readLine(); + whois_hand_shake = in.readLine(); + } + catch(NullPointerException ex) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Connection Failed, the name " + name_field_entry + " already exists.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + out = null; + in = null; + + if(enabled_sounds[1]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[1] + ".wav"); + } + catch(FileNotFoundException exc) { + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException exc) { + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + AudioPlayer.player.start(as); + } + + settings.setNameFieldEntry(name_field_entry); + settings.setIpField1Entry(ip_field1_entry); + settings.setIpField2Entry(ip_field2_entry); + settings.setIpField3Entry(ip_field3_entry); + settings.setIpField4Entry(ip_field4_entry); + settings.setPortEntry(port_field_entry); + saveSettings(); + + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + } + catch(UnknownHostException ex) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Connection Failed, could not connect to the requested server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + + if(enabled_sounds[1]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[1] + ".wav"); + } + catch(FileNotFoundException exc) { + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException exc) { + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + AudioPlayer.player.start(as); + } + + settings.setNameFieldEntry(name_field_entry); + settings.setIpField1Entry(ip_field1_entry); + settings.setIpField2Entry(ip_field2_entry); + settings.setIpField3Entry(ip_field3_entry); + settings.setIpField4Entry(ip_field4_entry); + settings.setPortEntry(port_field_entry); + saveSettings(); + + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + catch(IOException ex) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Connection Failed, could not connect to the requested server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + + if(enabled_sounds[1]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[1] + ".wav"); + } + catch(FileNotFoundException exc) { + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException exc) { + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + AudioPlayer.player.start(as); + } + + settings.setNameFieldEntry(name_field_entry); + settings.setIpField1Entry(ip_field1_entry); + settings.setIpField2Entry(ip_field2_entry); + settings.setIpField3Entry(ip_field3_entry); + settings.setIpField4Entry(ip_field4_entry); + settings.setPortEntry(port_field_entry); + saveSettings(); + + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + return; + } + + state = StateOfClient.CONNECTED; + + setTitle("Chat Client BETA" + " [ " + name_field_entry + " ] "); + textField.requestFocus(); + menu_disconnect.setEnabled(true); + + if(enabled_sounds[0]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[0] + ".wav"); + } + catch(FileNotFoundException ex) { + connect.dispose(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) { + connect.dispose(); + return; + } + + AudioPlayer.player.start(as); + } + + settings.setNameFieldEntry(name_field_entry); + settings.setIpField1Entry(ip_field1_entry); + settings.setIpField2Entry(ip_field2_entry); + settings.setIpField3Entry(ip_field3_entry); + settings.setIpField4Entry(ip_field4_entry); + settings.setPortEntry(port_field_entry); + saveSettings(); + + connect.dispose(); + + } + }); + + JButton close = new JButton("Cancel"); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + + if(name_field_entry.length() < 1 || name_field_entry.length() > MAX_SIZE_OF_NAME) { + name_field_entry = ""; + } + + try { + if(Integer.parseInt(ip_field1_entry) < 0 || Integer.parseInt(ip_field1_entry) > 255) { + ip_field1_entry = ""; + } + } + catch(NumberFormatException ex) { + ip_field1_entry = ""; + } + + try { + if(Integer.parseInt(ip_field2_entry) < 0 || Integer.parseInt(ip_field2_entry) > 255) { + ip_field2_entry = ""; + } + } + catch(NumberFormatException ex) { + ip_field2_entry = ""; + } + + try { + if(Integer.parseInt(ip_field3_entry) < 0 || Integer.parseInt(ip_field3_entry) > 255) { + ip_field3_entry = ""; + } + } + catch(NumberFormatException ex) { + ip_field3_entry = ""; + } + + try { + if(Integer.parseInt(ip_field4_entry) < 0 || Integer.parseInt(ip_field4_entry) > 255) { + ip_field4_entry = ""; + } + } + catch(NumberFormatException ex) { + ip_field4_entry = ""; + } + + try { + if(Integer.parseInt(port_field_entry) < 0 || Integer.parseInt(port_field_entry) > 65535) { + port_field_entry = ""; + } + } + catch(NumberFormatException ex) { + port_field_entry = ""; + } + + settings.setNameFieldEntry(name_field_entry); + settings.setIpField1Entry(ip_field1_entry); + settings.setIpField2Entry(ip_field2_entry); + settings.setIpField3Entry(ip_field3_entry); + settings.setIpField4Entry(ip_field4_entry); + settings.setPortEntry(port_field_entry); + saveSettings(); + + textField.requestFocus(); + menu_connect.setEnabled(true); + connect.dispose(); + + } + }); + + JPanel panel4 = new JPanel(); + JPanel panel5 = new JPanel(); + JPanel panel6 = new JPanel(); + JPanel panel7 = new JPanel(); + + panel4.setBackground(Color.LIGHT_GRAY); + panel5.setBackground(Color.LIGHT_GRAY); + panel6.setBackground(Color.LIGHT_GRAY); + panel7.setBackground(Color.LIGHT_GRAY); + panel4.add(new JLabel(" ")); + panel4.add(new JLabel("Name")); + panel4.add(name_field); + panel4.add(new JLabel(" ")); + panel5.add(new JLabel("IP Address")); + panel5.add(ip_field1); + panel5.add(new JLabel(".")); + panel5.add(ip_field2); + panel5.add(new JLabel(".")); + panel5.add(ip_field3); + panel5.add(new JLabel(".")); + panel5.add(ip_field4); + panel6.add(new JLabel(" ")); + panel6.add(new JLabel("Port")); + panel6.add(port_field); + panel6.add(new JLabel(" ")); + panel7.add(new JLabel("")); + panel7.add(new JLabel("Password")); + panel7.add(password); + panel7.add(new JLabel(" ")); + connect.add(panel4); + connect.add(panel5); + connect.add(panel6); + connect.add(panel7); + connect.add(connectButton); + connect.add(close); + connect.setVisible(true); + + } + }); + + menu_disconnect.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + disconnect(); + } + }); + + + + addWindowListener( new WindowAdapter() { + public void windowOpened( WindowEvent e ){ + textField.requestFocus(); + } + }); + + menu_about.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + int about_window_width = 298; + int about_window_height = 226; + + menu_about.setEnabled(false); + about = new JFrame("About"); + about.setSize(about_window_width, about_window_height); + about.setLocation((int)(getLocation().getX() + getSize().getWidth() / 2) - (about_window_width / 2), (int)(getLocation().getY() + getSize().getHeight() / 2) - (about_window_height / 2)); + about.getContentPane().setBackground(background_color); + about.setResizable(false); + + about.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + menu_about.setEnabled(true); + textField.requestFocus(); + about.dispose(); + + } + }); + + about.setLayout(new FlowLayout()); + JPanel panel = new JPanel(); + panel.setLayout(new GridLayout(8, 1)); + panel.add(new JLabel(" ")); + panel.add(new JLabel(" Chat Client, beta version.")); + panel.add(new JLabel()); + panel.add(new JLabel(" Made by Chris Kalonakis using java ")); + panel.add(new JLabel(" on NetBeans IDE 6.8")); + panel.add(new JLabel()); + panel.add(new JLabel(" Contact: hrkalona@inf.uth.gr")); + panel.add(new JLabel(" ")); + + JButton close = new JButton("Close"); + close.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + menu_about.setEnabled(true); + textField.requestFocus(); + about.dispose(); + + } + }); + + about.add(new JLabel(" ")); + about.add(new JLabel(" ")); + about.add(panel); + about.add(new JLabel(" ")); + about.add(close); + about.setVisible(true); + } + }); + + } + + private void disconnect() { + + try { + state = StateOfClient.DISCONNECTED; + out.close(); + in.close(); + in = null; + out = null; + connectionWithServer.close(); + menu_disconnect.setEnabled(false); + menu_connect.setEnabled(true); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Disconnected from the Server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + textArea2.setText(""); + setTitle("Chat Client BETA"); + + if(enabled_sounds[1]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[1] + ".wav"); + } + catch(FileNotFoundException ex) { + textField.requestFocus(); + return; + } + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) { + textField.requestFocus(); + return; + } + + AudioPlayer.player.start(as); + } + } + catch(Exception ex) {} + textField.requestFocus(); + + } + + public void run() { + + while(running) { + + checkIfServerDisconnected(); + waitForConnection(); + refreshAfterConnection(); + waitForMessages(); + + } + + } + + + private void checkIfServerDisconnected() { + + if(state == StateOfClient.CONNECTED) { + try { + in.readLine(); + } + catch(IOException ex) { + disconnect(); + } + } + + } + + private void waitForConnection(){ + + while(state == StateOfClient.DISCONNECTED) { + System.out.println("");//BUG + } + + } + + + private void refreshAfterConnection() { + int count; + + try { + if(state == StateOfClient.CONNECTED) { + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + "Connected to the Server.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + count = Integer.parseInt(in.readLine()); + + for(i = 0; i < count; i++) { + textArea2.setText(textArea2.getText() + in.readLine() + "\n"); + } + } + } + catch(NullPointerException ex) {} + catch(SocketException ex) {} + catch(IOException ex) {} + + + } + + private void waitForMessages() { + String Temp; + int count; + + try { + while(state == StateOfClient.CONNECTED && (SocketEntryMessage = in.readLine()) != null) { + if(SocketEntryMessage.equals(connected_hand_shake)) { + textArea2.setText(""); + SocketEntryName = in.readLine(); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + SocketEntryName + " has connected.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + + count = Integer.parseInt(in.readLine()); + for(i = 0; i < count; i++) { + textArea2.setText(textArea2.getText() + in.readLine() + "\n"); + } + + if(enabled_sounds[2]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[2] + ".wav"); + } + catch(FileNotFoundException ex) {} + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) {} + + AudioPlayer.player.start(as); + } + } + else { + if(SocketEntryMessage.equals(disconnected_hand_shake)) { + textArea2.setText(""); + SocketEntryName = in.readLine(); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + SocketEntryName + " has disconnected.\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + count = Integer.parseInt(in.readLine()); + for(i = 0; i < count; i++) { + textArea2.setText(textArea2.getText() + in.readLine() + "\n"); + } + + if(enabled_sounds[3]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[3] + ".wav"); + } + catch(FileNotFoundException ex) {} + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) {} + + AudioPlayer.player.start(as); + } + + } + else { + if(SocketEntryMessage.equals(whois_hand_shake)) { + SocketEntryMessage = in.readLine(); + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + " " + SocketEntryMessage + "\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + } + else { + SocketEntryName = in.readLine(); + + if(SocketEntryName.length() > 10) { + Temp = ""; + while(SocketEntryMessage.length() > 40) { + Temp += SocketEntryMessage.substring(0, 40) + "\n"; + SocketEntryMessage = SocketEntryMessage.substring(40, SocketEntryMessage.length()); + } + SocketEntryMessage = Temp + SocketEntryMessage; + } + else { + Temp = ""; + while(SocketEntryMessage.length() > 44) { + Temp += SocketEntryMessage.substring(0, 44) + "\n"; + SocketEntryMessage = SocketEntryMessage.substring(44, SocketEntryMessage.length()); + } + SocketEntryMessage = Temp + SocketEntryMessage; + } + + calendar = new GregorianCalendar(); + textArea1.setText(textArea1.getText() + "<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + "> " + SocketEntryName + " : " + SocketEntryMessage + "\n"); + textArea1.setCaretPosition(textArea1.getText().length()); + + if(!SocketEntryName.equals(name_field_entry)) { + if(enabled_sounds[4]) { + InputStream sound_stream_in = null; + try { + sound_stream_in = new FileInputStream("./Sounds/" + selected_sounds[4] + ".wav"); + } + catch(FileNotFoundException ex) {} + + AudioStream as = null; + try { + as = new AudioStream(sound_stream_in); + } + catch(IOException ex) {} + + AudioPlayer.player.start(as); + } + } + } + } + } + + } + } + catch(Exception ex) {} + + + } + + private void saveSettings() { + + ObjectOutputStream file = null; + + try { + file = new ObjectOutputStream(new FileOutputStream("settings.dat")); + file.writeObject(settings); + file.flush(); + } + catch(IOException ex) {} + + try { + file.close(); + } + catch(Exception ex) {} + + } + + private void loadSettings() { + + ObjectInputStream file = null; + try { + file = new ObjectInputStream(new FileInputStream("settings.dat")); + settings = (Settings) file.readObject(); + } + catch(IOException ex) { + settings = new Settings(); + saveSettings(); + } + catch(ClassNotFoundException ex) { + settings = new Settings(); + saveSettings(); + } + + try { + file.close(); + } + catch(Exception ex) {} + + } + + private void lastUsedListInsertion() { + + if(last_used.size() == NUMBER_OF_LAST_USED) { + last_used.remove(0); + last_used.add(new String(chat_entry)); + last_used_index = last_used.size() - 1; + } + else { + last_used.add(new String(chat_entry)); + last_used_index = last_used.size() - 1; + } + + } + + public static void main(String[] args) throws IOException { + + ChatClient client = new ChatClient(); + client.setVisible(true); + client.run(); + + } + +} + + diff --git a/example-apps/src/chat/chat/client/Settings.java b/example-apps/src/chat/chat/client/Settings.java new file mode 100644 index 0000000..e063e05 --- /dev/null +++ b/example-apps/src/chat/chat/client/Settings.java @@ -0,0 +1,189 @@ +package chat.client; + +import java.awt.Color; +import java.io.Serializable; + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author Administrator + */ +public class Settings implements Serializable { + private String name_field_entry; + private String ip_field1_entry; + private String ip_field2_entry; + private String ip_field3_entry; + private String ip_field4_entry; + private String port_field_entry; + private Color background_color; + private Color font_color; + private Boolean[] enabled_sounds; + private int[] selected_sounds_index; + private String[] selected_sounds; + + + public Settings() { + + this.name_field_entry = ""; + this.ip_field1_entry = ""; + this.ip_field2_entry = ""; + this.ip_field3_entry = ""; + this.ip_field4_entry = ""; + this.port_field_entry = ""; + this.background_color = Color.DARK_GRAY; + this.font_color = Color.BLACK; + this.enabled_sounds = new Boolean[ChatClient.NUM_OF_SOUNDS]; + this.selected_sounds_index = new int[ChatClient.NUM_OF_SOUNDS]; + this.selected_sounds = new String[ChatClient.NUM_OF_SOUNDS]; + + for(int i = 0; i < ChatClient.NUM_OF_SOUNDS; i++) { + selected_sounds_index[i] = 0; + enabled_sounds[i] = true; + } + + selected_sounds[0] = "connect1"; + selected_sounds[1] = "disconnect1"; + selected_sounds[2] = "userConnect1"; + selected_sounds[3] = "userDisconnect1"; + selected_sounds[4] = "newMessage1"; + selected_sounds[5] = "warning1"; + + } + + public Color getBackgroundColor() { + + return this.background_color; + + } + + public void setBackgroundColor(Color obj) { + + this.background_color = obj; + + } + + public Color getFontColor() { + + return this.font_color; + + } + + public void setFontColor(Color obj) { + + this.font_color = obj; + + } + + public String getNameFieldEntry() { + + return this.name_field_entry; + + } + + public void setNameFieldEntry(String obj) { + + this.name_field_entry = obj; + + } + + public String getIpField1Entry() { + + return this.ip_field1_entry; + + } + + public void setIpField1Entry(String obj) { + + this.ip_field1_entry = obj; + + } + + public String getIpField2Entry() { + + return this.ip_field2_entry; + + } + + public void setIpField2Entry(String obj) { + + this.ip_field2_entry = obj; + + } + + public String getIpField3Entry() { + + return this.ip_field3_entry; + + } + + public void setIpField3Entry(String obj) { + + this.ip_field3_entry = obj; + + } + + public String getIpField4Entry() { + + return this.ip_field4_entry; + + } + + public void setIpField4Entry(String obj) { + + this.ip_field4_entry = obj; + + } + + public String getPortEntry() { + + return this.port_field_entry; + + } + + public void setPortEntry(String obj) { + + this.port_field_entry = obj; + + } + + public Boolean[] getEnabledSounds() { + + return this.enabled_sounds; + + } + + public void setEnabledSounds(Boolean[] obj) { + + this.enabled_sounds = obj; + + } + + public int[] getSelectedSoundsIndex() { + + return this.selected_sounds_index; + + } + + public void setSelectedSoundsIndex(int[] obj) { + + this.selected_sounds_index = obj; + + } + + public String[] getSelectedSounds() { + + return this.selected_sounds; + + } + + public void setSelectedSounds(String[] obj) { + + this.selected_sounds = obj; + + } + +} diff --git a/example-apps/src/chat/chat/server/MultiChatServer.java b/example-apps/src/chat/chat/server/MultiChatServer.java new file mode 100644 index 0000000..e0ef78e --- /dev/null +++ b/example-apps/src/chat/chat/server/MultiChatServer.java @@ -0,0 +1,118 @@ +package chat.server; + +import java.net.*; +import java.io.*; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.Random; + +public class MultiChatServer { + + public static void main(String[] args) throws IOException { + ServerSocket connectionWithSender = null; + boolean listening = true; + String password; + + Calendar calendar = new GregorianCalendar(); + + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " The Multithreaded Chat Server is now starting."); + + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " Enter the server's password."); + + BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); + password = stdIn.readLine(); + + try { + connectionWithSender = new ServerSocket(5002); + } catch (IOException e) { + calendar = new GregorianCalendar(); + System.err.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " Could not listen on port: 5002."); + System.exit(-1); + } + + + InetAddress thisIp = InetAddress.getLocalHost(); + + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " IP: " + thisIp.getHostAddress() + " PORT: " + connectionWithSender.getLocalPort()); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " PASSWORD: " + password); + + MultiChatServerThread thread; + + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " Awaiting connections."); + + ArrayList info = new ArrayList(10); + + Random generator = new Random(System.currentTimeMillis()); + + String connected_hand_shake = ""; + String disconnected_hand_shake = ""; + String whois_hand_shake = ""; + + for(int i = 0; i < 256; i++) { + connected_hand_shake += generator.nextInt(10); + } + + do { + for(int i = 0; i < 256; i++) { + disconnected_hand_shake += generator.nextInt(10); + } + } while(connected_hand_shake.equals(disconnected_hand_shake)); + + do { + for(int i = 0; i < 256; i++) { + whois_hand_shake += generator.nextInt(10); + } + } while(connected_hand_shake.equals(whois_hand_shake) || disconnected_hand_shake.equals(whois_hand_shake)); + + while (listening) { + + try { + Socket SenderSocket = connectionWithSender.accept(); + PrintWriter out = new PrintWriter(SenderSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(SenderSocket.getInputStream())); + String pw_entry = in.readLine(); + + out.println("waitForPasswordVerification"); + if(!pw_entry.equals(password)) { + SenderSocket.close(); + in.close(); + out.close(); + } + out.println("Check"); + + String name = in.readLine(); + + Boolean name_found = false; + out.println("waitForNameChecking"); + for(int i = 0; i < info.size(); i++) { + if(info.get(i).getName().equalsIgnoreCase(name)) { + SenderSocket.close(); + in.close(); + out.close(); + name_found = true; + } + } + + if(name_found == false) { + out.println("Check"); + out.println(connected_hand_shake); + out.println(disconnected_hand_shake); + out.println(whois_hand_shake); + UserInfo entry = new UserInfo(out, in, ("" + SenderSocket.getInetAddress()).substring(1), SenderSocket.getPort(), name); + info.add(entry); + thread = new MultiChatServerThread(info, entry, SenderSocket, connected_hand_shake, disconnected_hand_shake, whois_hand_shake); + thread.start(); + } + } + catch(Exception ex) {} + + } + + + connectionWithSender.close(); + } +} diff --git a/example-apps/src/chat/chat/server/MultiChatServerThread.java b/example-apps/src/chat/chat/server/MultiChatServerThread.java new file mode 100644 index 0000000..62e1aa6 --- /dev/null +++ b/example-apps/src/chat/chat/server/MultiChatServerThread.java @@ -0,0 +1,149 @@ +package chat.server; + +import java.net.*; +import java.io.*; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; + +public class MultiChatServerThread extends Thread { + private ArrayList info; + private UserInfo entry; + private Socket socket; + private String connected_hand_shake; + private String disconnected_hand_shake; + private String whois_hand_shake; + public static final int MAX_SIZE_OF_NAME = 15; + + public MultiChatServerThread(ArrayList info, UserInfo entry , Socket socket, String connected_hand_shake, String disconnected_hand_shake, String whois_hand_shake) { + + super("MultiChatServerThread"); + this.info = info; + this.entry = entry; + this.socket = socket; + this.connected_hand_shake = connected_hand_shake; + this.disconnected_hand_shake = disconnected_hand_shake; + this.whois_hand_shake = whois_hand_shake; + + } + + + public void run() { + + Calendar calendar = new GregorianCalendar(); + + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " [Thread:" + String.format("%4d", getId()) + "] The Client " + entry.getIP() + " [ " + entry.getName() + " ]" + " has connected to the Server."); + + long connected_time = System.currentTimeMillis(); + + try { + + String inputLine; + + for(int i = 0; i < info.size(); i++) { + if(info.get(i) != entry) { + info.get(i).getOut().println(connected_hand_shake); + info.get(i).getOut().println(entry.getName()); + } + info.get(i).getOut().println(info.size() - 1); + } + + for(int i = 0; i < info.size(); i++) { + for(int j = 0; j < info.size(); j++) { + if(info.get(i) != info.get(j)) { + info.get(i).getOut().println(info.get(j).getName()); + } + } + } + + try { + while ((inputLine = entry.getIn().readLine()) != null) { + if(inputLine.equals(whois_hand_shake)) { + inputLine = entry.getIn().readLine(); + UserInfo ptr = null; + for(int i = 0; i < info.size(); i++) { + if(info.get(i).getName().equalsIgnoreCase(inputLine)) { + ptr = info.get(i); + break; + } + } + if(ptr != null) { + entry.getOut().println(whois_hand_shake); + entry.getOut().println(ptr.getName() + " @ " + ptr.getIP()); + } + else { + entry.getOut().println(whois_hand_shake); + entry.getOut().println(inputLine + " does not exist."); + } + } + else { + for(int i = 0; i < info.size(); i++) { + info.get(i).getOut().println(inputLine); + info.get(i).getOut().println(entry.getName()); + } + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " [Thread:" + String.format("%4d", getId()) + "] " + String.format("%" + MAX_SIZE_OF_NAME + "s", entry.getName()) + " : " + inputLine); + } + } + } + catch(SocketException ex) {} + + for(int i = 0; i < info.size(); i++) { + if(info.get(i) != entry) { + info.get(i).getOut().println(disconnected_hand_shake); + info.get(i).getOut().println(entry.getName()); + } + } + for(int i = 0; i < info.size(); i++) { + if(info.get(i) == entry) { + info.remove(i); + } + } + + for(int i = 0; i < info.size(); i++) { + info.get(i).getOut().println(info.size() - 1); + } + + for(int i = 0; i < info.size(); i++) { + for(int j = 0; j < info.size(); j++) { + if(info.get(i) != info.get(j)) { + info.get(i).getOut().println(info.get(j).getName()); + } + } + } + + connected_time = System.currentTimeMillis() - connected_time; + + if((connected_time / 1000) < 60) { + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " [Thread:" + String.format("%4d", getId()) + "] " + entry.getIP() + " [ " + entry.getName() + " ] was connected to the Server for " + (connected_time / 1000) % 60 + " second(s)."); + } + else { + if((connected_time / 1000 / 60) < 60) { + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " [Thread:" + String.format("%4d", getId()) + "] " + entry.getIP() + " [ " + entry.getName() + " ] was connected to the Server for " + (connected_time / 1000 / 60) % 60 + " minute(s) " + (connected_time / 1000) % 60 + " second(s)."); + } + else { + if((connected_time / 1000 / 60 / 60) < 24) { + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " [Thread:" + String.format("%4d", getId()) + "] " + entry.getIP() + " [ " + entry.getName() + " ] was connected to the Server for " + connected_time / 1000 / 60 / 60 + " hour(s) " + (connected_time / 1000 / 60) % 60 + " minute(s) " + (connected_time / 1000) % 60 + " second(s)."); + } + else { + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " [Thread:" + String.format("%4d", getId()) + "] " + entry.getIP() + " [ " + entry.getName() + " ] was connected to the Server for " + connected_time / 1000 / 60 / 60 / 24 + " day(s) " + (connected_time / 1000 / 60 / 60) % 24 + " hour(s) " + (connected_time / 1000 / 60) % 60 + " minute(s) " + (connected_time / 1000) % 60 + " second(s)."); + } + } + } + + calendar = new GregorianCalendar(); + System.out.println("<" + String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", calendar.get(Calendar.MINUTE)) + ":" + String.format("%02d", calendar.get(Calendar.SECOND)) + ">" + " [Thread:" + String.format("%4d", getId()) + "] This thread is now terminating."); + + entry.getIn().close(); + socket.close(); + + } + catch (IOException e) {} + + } +} diff --git a/example-apps/src/chat/chat/server/UserInfo.java b/example-apps/src/chat/chat/server/UserInfo.java new file mode 100644 index 0000000..ebed6db --- /dev/null +++ b/example-apps/src/chat/chat/server/UserInfo.java @@ -0,0 +1,62 @@ +package chat.server; + +import java.io.BufferedReader; +import java.io.PrintWriter; + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author Administrator + */ +public class UserInfo { + private PrintWriter out; + private BufferedReader in; + private String IP; + private int PORT; + private String Name; + + public UserInfo(PrintWriter out, BufferedReader in, String IP, int PORT, String Name) { + + this.out = out; + this.in = in; + this.IP = IP; + this.PORT = PORT; + this.Name = Name; + + } + + public PrintWriter getOut() { + + return this.out; + + } + + public BufferedReader getIn() { + + return this.in; + + } + + public String getIP() { + + return this.IP; + + } + + public int getPort() { + + return this.PORT; + + } + + public String getName() { + + return this.Name; + + } + +} diff --git a/example-apps/src/ip/administrador/AdmInexistenteException.java b/example-apps/src/ip/administrador/AdmInexistenteException.java new file mode 100644 index 0000000..7ea3fbb --- /dev/null +++ b/example-apps/src/ip/administrador/AdmInexistenteException.java @@ -0,0 +1,10 @@ +package exceptions.administrador; + +public class AdmInexistenteException extends Exception { + + private static final long serialVersionUID = -7061377520446245525L; + + public AdmInexistenteException() { + super("Administrador não existe."); + } +} diff --git a/example-apps/src/ip/administrador/AdmNaoEncontradoException.java b/example-apps/src/ip/administrador/AdmNaoEncontradoException.java new file mode 100644 index 0000000..ee73804 --- /dev/null +++ b/example-apps/src/ip/administrador/AdmNaoEncontradoException.java @@ -0,0 +1,14 @@ +package exceptions.administrador; + +public class AdmNaoEncontradoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 518772763727978768L; + + public AdmNaoEncontradoException() { + super("Administrador não encontrado!"); + } + +} diff --git a/example-apps/src/ip/administrador/BairroInvalidoException.java b/example-apps/src/ip/administrador/BairroInvalidoException.java new file mode 100644 index 0000000..d9cfdc3 --- /dev/null +++ b/example-apps/src/ip/administrador/BairroInvalidoException.java @@ -0,0 +1,11 @@ +package exceptions.administrador; + + +public class BairroInvalidoException extends Exception { + + private static final long serialVersionUID = 8493332690717566026L; + + public BairroInvalidoException(){ + super("Bairro inválido"); + } +} diff --git a/example-apps/src/ip/administrador/CidadeInvalidaException.java b/example-apps/src/ip/administrador/CidadeInvalidaException.java new file mode 100644 index 0000000..f909c24 --- /dev/null +++ b/example-apps/src/ip/administrador/CidadeInvalidaException.java @@ -0,0 +1,12 @@ +package exceptions.administrador; + +public class CidadeInvalidaException extends Exception { + /** + * + */ + private static final long serialVersionUID = 2501972420789733441L; + + public CidadeInvalidaException(){ + super ("Cidade inválida"); + } +} diff --git a/example-apps/src/ip/administrador/CpfInvalidoException.java b/example-apps/src/ip/administrador/CpfInvalidoException.java new file mode 100644 index 0000000..cfe75b6 --- /dev/null +++ b/example-apps/src/ip/administrador/CpfInvalidoException.java @@ -0,0 +1,11 @@ +package exceptions.administrador; + +public class CpfInvalidoException extends Exception { + + private static final long serialVersionUID = 8430532418525952253L; + + public CpfInvalidoException() { + super("CPF inválido!"); + } + +} diff --git a/example-apps/src/ip/administrador/CpfJaExisteException.java b/example-apps/src/ip/administrador/CpfJaExisteException.java new file mode 100644 index 0000000..d99e8ee --- /dev/null +++ b/example-apps/src/ip/administrador/CpfJaExisteException.java @@ -0,0 +1,12 @@ +package exceptions.administrador; + +public class CpfJaExisteException extends Exception { +/** + * + */ + private static final long serialVersionUID = -4048530757554713908L; + +public CpfJaExisteException(){ + super("Esse cpf já foi cadastrado!"); +} +} diff --git a/example-apps/src/ip/administrador/TelefoneInvalidoException.java b/example-apps/src/ip/administrador/TelefoneInvalidoException.java new file mode 100644 index 0000000..5bfdeed --- /dev/null +++ b/example-apps/src/ip/administrador/TelefoneInvalidoException.java @@ -0,0 +1,14 @@ +package exceptions.administrador; + +public class TelefoneInvalidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -763031994437441979L; + + public TelefoneInvalidoException(){ + super("Telefone Inválido!"); + } + +} diff --git a/example-apps/src/ip/administrador/TelefoneJaExisteException.java b/example-apps/src/ip/administrador/TelefoneJaExisteException.java new file mode 100644 index 0000000..c09b94e --- /dev/null +++ b/example-apps/src/ip/administrador/TelefoneJaExisteException.java @@ -0,0 +1,14 @@ +package exceptions.administrador; + +public class TelefoneJaExisteException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -8166024353844041522L; + + public TelefoneJaExisteException(){ + super("Telefone já cadastrado!"); + } + +} diff --git a/example-apps/src/ip/cliente/BairroInvalidoException.java b/example-apps/src/ip/cliente/BairroInvalidoException.java new file mode 100644 index 0000000..026e997 --- /dev/null +++ b/example-apps/src/ip/cliente/BairroInvalidoException.java @@ -0,0 +1,11 @@ +package exceptions.cliente; + + +public class BairroInvalidoException extends Exception { + + private static final long serialVersionUID = 8493332690717566026L; + + public BairroInvalidoException(){ + super("Bairro inválido"); + } +} diff --git a/example-apps/src/ip/cliente/CidadeInvalidaException.java b/example-apps/src/ip/cliente/CidadeInvalidaException.java new file mode 100644 index 0000000..dc1e867 --- /dev/null +++ b/example-apps/src/ip/cliente/CidadeInvalidaException.java @@ -0,0 +1,12 @@ +package exceptions.cliente; + +public class CidadeInvalidaException extends Exception { + /** + * + */ + private static final long serialVersionUID = 2501972420789733441L; + + public CidadeInvalidaException(){ + super ("Cidade inválida"); + } +} diff --git a/example-apps/src/ip/cliente/ClienteInexistenteException.java b/example-apps/src/ip/cliente/ClienteInexistenteException.java new file mode 100644 index 0000000..17a06e8 --- /dev/null +++ b/example-apps/src/ip/cliente/ClienteInexistenteException.java @@ -0,0 +1,10 @@ +package exceptions.cliente; + +public class ClienteInexistenteException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 2420102669137192557L; + +} diff --git a/example-apps/src/ip/cliente/ClienteNaoEncontradoException.java b/example-apps/src/ip/cliente/ClienteNaoEncontradoException.java new file mode 100644 index 0000000..c4f1329 --- /dev/null +++ b/example-apps/src/ip/cliente/ClienteNaoEncontradoException.java @@ -0,0 +1,14 @@ +package exceptions.cliente; + +public class ClienteNaoEncontradoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 518772763727978768L; + + public ClienteNaoEncontradoException() { + super("Cliente não encontrado!"); + } + +} diff --git a/example-apps/src/ip/cliente/CpfInvalidoException.java b/example-apps/src/ip/cliente/CpfInvalidoException.java new file mode 100644 index 0000000..7ca493d --- /dev/null +++ b/example-apps/src/ip/cliente/CpfInvalidoException.java @@ -0,0 +1,11 @@ +package exceptions.cliente; + +public class CpfInvalidoException extends Exception { + + private static final long serialVersionUID = 8430532418525952253L; + + public CpfInvalidoException() { + super("CPF inválido!"); + } + +} diff --git a/example-apps/src/ip/cliente/CpfJaExisteException.java b/example-apps/src/ip/cliente/CpfJaExisteException.java new file mode 100644 index 0000000..537083f --- /dev/null +++ b/example-apps/src/ip/cliente/CpfJaExisteException.java @@ -0,0 +1,12 @@ +package exceptions.cliente; + +public class CpfJaExisteException extends Exception { +/** + * + */ + private static final long serialVersionUID = -4048530757554713908L; + +public CpfJaExisteException(){ + super("Esse cpf já foi cadastrado!"); +} +} diff --git a/example-apps/src/ip/cliente/EstadoInvalidoException.java b/example-apps/src/ip/cliente/EstadoInvalidoException.java new file mode 100644 index 0000000..08e525c --- /dev/null +++ b/example-apps/src/ip/cliente/EstadoInvalidoException.java @@ -0,0 +1,12 @@ +package exceptions.cliente; + +public class EstadoInvalidoException extends Exception { + /** + * + */ + private static final long serialVersionUID = 2501972420789733441L; + + public EstadoInvalidoException(){ + super ("Estado inválido"); + } +} diff --git a/example-apps/src/ip/cliente/TelefoneInvalidoException.java b/example-apps/src/ip/cliente/TelefoneInvalidoException.java new file mode 100644 index 0000000..71157bf --- /dev/null +++ b/example-apps/src/ip/cliente/TelefoneInvalidoException.java @@ -0,0 +1,14 @@ +package exceptions.cliente; + +public class TelefoneInvalidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -763031994437441979L; + + public TelefoneInvalidoException(){ + super("Telefone Inválido!"); + } + +} diff --git a/example-apps/src/ip/cliente/TelefoneJaExisteException.java b/example-apps/src/ip/cliente/TelefoneJaExisteException.java new file mode 100644 index 0000000..a62a8de --- /dev/null +++ b/example-apps/src/ip/cliente/TelefoneJaExisteException.java @@ -0,0 +1,14 @@ +package exceptions.cliente; + +public class TelefoneJaExisteException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -8166024353844041522L; + + public TelefoneJaExisteException(){ + super("Telefone já cadastrado!"); + } + +} diff --git a/example-apps/src/ip/dados/IteratorClasse.java b/example-apps/src/ip/dados/IteratorClasse.java new file mode 100644 index 0000000..5df37a7 --- /dev/null +++ b/example-apps/src/ip/dados/IteratorClasse.java @@ -0,0 +1,55 @@ +package dados; + +import java.util.Iterator; +import java.util.Vector; + +public class IteratorClasse implements Iterator{ + + //O iterator do tipo geretics pode receber qualquer tipo, por isso usamos assim + + private Vector vetor; + private int indice; + + // Construtor Vector // + public IteratorClasse(Vector vetor){ + this.vetor = vetor; + this.indice = 0; + } + + // Construtor Array // + public IteratorClasse(Generics[] array){ + this.vetor = new Vector(); + Vector auxiliar = new Vector(); + for (int i = 0; i { + + /** + * + */ + private static final long serialVersionUID = -3890860726557093419L; + private String codigo; + private Cliente cliente; + private Produto[] produtos; + private int quantidade; + private BigDecimal preco; + private Date data; + private Pedido prox; + + public Pedido(String codigo, Cliente cliente, Produto[] produtos, Date data, int quantidade, BigDecimal preco) { + super(); + this.codigo = codigo; + this.cliente = cliente; + this.produtos = produtos; + this.quantidade = quantidade; + this.preco = preco; + this.data = data; + this.prox = null; + } + + public Pedido(Pedido produto) { + super(); + this.codigo = produto.getCodigo(); + this.cliente = produto.getCliente(); + this.produtos = produto.getProdutos(); + this.quantidade = produto.getQuantidade(); + this.preco = produto.getPreco(); + this.data = produto.getData(); + this.prox = produto.getProx(); + } + + public Pedido() { + + } + + public String getCodigo() { + return codigo; + } + public void setCodigo(String codigo) { + this.codigo = codigo; + } + public Cliente getCliente() { + return cliente; + } + public void setCliente(Cliente cliente) { + this.cliente = cliente; + } + public Produto[] getProdutos() { + return produtos; + } + public void setProdutos(Produto[] produtos) { + this.produtos = produtos; + } + + public int getQuantidade() { + return quantidade; + } + public void setQuantidade(int quantidade) { + this.quantidade = quantidade; + } + public BigDecimal getPreco() { + return preco; + } + public void setPreco(BigDecimal preco) { + this.preco = preco; + } + + //Precisamos do compareTo para quando for ordenar o vector pra gerar o relatório + + public int compareTo(Pedido pedido) { + int resposta = 1; + if(this.data.before(pedido.data)) + resposta = -1; + else if(this.data.equals(pedido.data)) + resposta = 0; + + return resposta; + + } + + public void setData(Date data) { + this.data = data; + } + + public Date getData() { + return data; + } + + public Pedido getProx() { + return prox; + } + + public void setProx(Pedido prox) { + this.prox = prox; + } + +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/entidade/Pessoa.java b/example-apps/src/ip/dados/entidade/Pessoa.java new file mode 100644 index 0000000..cb6ac01 --- /dev/null +++ b/example-apps/src/ip/dados/entidade/Pessoa.java @@ -0,0 +1,64 @@ +package dados.entidade; + +import java.io.Serializable; + + +public abstract class Pessoa implements Serializable { + /** + * + */ + private static final long serialVersionUID = -8228879323512431235L; + protected String nome; + protected String cpf; + protected Contato contato; + protected String senha; + private Pessoa prox; + + public Pessoa(String nome, String cpf, String senha, Contato contato) { + this.nome = nome; + this.cpf = cpf; + this.senha = senha; + this.contato = contato; + this.prox = null; + } + + public Pessoa() { + + } + + public Pessoa(Pessoa pessoa) { + this.nome = pessoa.getNome(); + this.cpf = pessoa.getCpf(); + this.contato = pessoa.getContato(); + this.senha = pessoa.getSenha(); + this.setProx(pessoa.getProx()); + } + + public Pessoa(String cpf, String telefone, String nome, + String logradouro, String numero, String complemento, + String bairro, String cidade, String senha, String uf) { + this.cpf = cpf; + this.nome = nome; + this.senha = senha; + this.contato.setContato(logradouro, numero, complemento, bairro, cidade, uf, telefone); + + // TODO Auto-generated constructor stub + } + + public String getNome() { return nome;} + public void setNome(String nome) { this.nome = nome;} + + public String getCpf() { return cpf;} + public void setCpf(String cpf) { this.cpf = cpf;} + + public Contato getContato() { return contato;} + public void setContato(Contato contato) { this.contato = contato;} + + public String getSenha() { return this.senha;} + public void setSenha(String senha) { this.senha = senha;} + + public Pessoa getProx() { return prox;} + public void setProx(Pessoa prox) { this.prox = prox;} + +} + diff --git a/example-apps/src/ip/dados/entidade/Produto.java b/example-apps/src/ip/dados/entidade/Produto.java new file mode 100644 index 0000000..2fe0083 --- /dev/null +++ b/example-apps/src/ip/dados/entidade/Produto.java @@ -0,0 +1,54 @@ +package dados.entidade; + +import java.io.Serializable; +import java.math.BigDecimal; + +import dados.entidade.interfaces.IProd; + +public class Produto implements IProd, Serializable { + + private static final long serialVersionUID = 2196137339585578884L; + protected String codigo; + protected String nome; + protected String descricao; + protected BigDecimal preco; + protected int quantidade; + Produto prox; + + public Produto(String codigo, String nome, String descricao, BigDecimal preco) { + this.nome = nome; + this.codigo = codigo; + this.descricao = descricao; + this.preco = preco; + this.prox = null; + } + + public Produto(Produto produto) { + this.codigo = produto.getCodigo(); + this.descricao = produto.getDescricao(); + this.nome = produto.getNome(); + this.preco = produto.getPreco(); + this.prox = produto.getProx(); + } + + public Produto() { + + } + + public void setNome(String nome) { this.nome = nome;} + public String getNome() { return nome;} + + public void setCodigo(String codigo) { this.codigo = codigo;} + public String getCodigo() { return codigo;} + + public void setDescricao(String descricao) { this.descricao = descricao;} + public String getDescricao() { return descricao;} + + public void setPreco(BigDecimal preco) { this.preco = preco;} + public BigDecimal getPreco() { return preco;} + + + public Produto getProx() { return prox;} + public void setProx(Produto prox) { this.prox = prox;} + +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/entidade/interfaces/IAdm.java b/example-apps/src/ip/dados/entidade/interfaces/IAdm.java new file mode 100644 index 0000000..3bdd8aa --- /dev/null +++ b/example-apps/src/ip/dados/entidade/interfaces/IAdm.java @@ -0,0 +1,20 @@ +package dados.entidade.interfaces; + +import dados.entidade.Administrador; +import dados.entidade.Contato; +import dados.entidade.Pessoa; + +public interface IAdm { //O int 1 seria para caso um sistema de login identifica-lo como admin + final static int acesso = 1; + + public String getNome(); + public String getCpf(); + public String getSenha(); + public Contato getContato(); + public void setNome(String nome); + public void setCpf(String cpf); + public void setContato(Contato contato); + public void setSenha(String senha); + public void setProx(Pessoa administrador); + public Administrador getProx(); +} diff --git a/example-apps/src/ip/dados/entidade/interfaces/ICliente.java b/example-apps/src/ip/dados/entidade/interfaces/ICliente.java new file mode 100644 index 0000000..cbf2a91 --- /dev/null +++ b/example-apps/src/ip/dados/entidade/interfaces/ICliente.java @@ -0,0 +1,19 @@ +package dados.entidade.interfaces; + +import dados.entidade.Cliente; +import dados.entidade.Contato; + +public interface ICliente { //O int 0 seria para caso um sistema de login identifica-lo como cliente + final static int acesso = 0; + + public String getNome(); + public String getCpf(); + public String getSenha(); + public Contato getContato(); + public void setNome(String nome); + public void setCpf(String cpf); + public void setContato(Contato contato); + public void setSenha(String senha); + public void setProx(Cliente cliente); + public Cliente getProx(); +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/entidade/interfaces/IPedido.java b/example-apps/src/ip/dados/entidade/interfaces/IPedido.java new file mode 100644 index 0000000..f6e33a1 --- /dev/null +++ b/example-apps/src/ip/dados/entidade/interfaces/IPedido.java @@ -0,0 +1,22 @@ +package dados.entidade.interfaces; + +import java.math.BigDecimal; +import java.util.Date; + +import dados.entidade.Cliente; +import dados.entidade.Produto; + +public interface IPedido { + public void setCodigo(String codigo); + public String getCodigo(); + public void setCliente(Cliente cliente); + public Cliente getCliente(); + public void setProdutos(Produto[] produto); + public Produto[] getProdutos(); + public void setData(Date data); + public Date getData(); + public void setQuantidade(int quantidade); + public int getQuantidade(); + public BigDecimal getPreco(); + public void setPreco(BigDecimal preco); +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/entidade/interfaces/IProd.java b/example-apps/src/ip/dados/entidade/interfaces/IProd.java new file mode 100644 index 0000000..abcde7f --- /dev/null +++ b/example-apps/src/ip/dados/entidade/interfaces/IProd.java @@ -0,0 +1,14 @@ +package dados.entidade.interfaces; + +import java.math.BigDecimal; + +public interface IProd { + + public void setNome(String nome); + public void setCodigo(String codigo); + public void setPreco(BigDecimal preco); + public String getNome(); + public String getCodigo(); + public BigDecimal getPreco(); + +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/excel/ExcelCell.java b/example-apps/src/ip/dados/excel/ExcelCell.java new file mode 100644 index 0000000..5c724d4 --- /dev/null +++ b/example-apps/src/ip/dados/excel/ExcelCell.java @@ -0,0 +1,53 @@ +package dados.excel; + +import org.apache.poi.hssf.usermodel.HSSFCell; + +import dados.excel.exception.CellNumberFormatException; +import dados.excel.exception.CellStringFormatException; + +public class ExcelCell { + + + private HSSFCell hssfCell; + + public ExcelCell (HSSFCell hssfCell) { + this.setHSSFCell (hssfCell); + } + + protected void setHSSFCell (HSSFCell hssfCell) { + + if (hssfCell != null) { + this.hssfCell = hssfCell; + } else { + throw new IllegalArgumentException("A celula passada eh nula"); + } + + } + + public double getNumericCellValue () throws CellNumberFormatException { + double ret = 0.0; + + try { + ret = this.hssfCell.getNumericCellValue (); + } catch (Exception e) { + e.printStackTrace(); + throw new CellNumberFormatException(String.format("O conteúdo da célula numérica não pode ser convertida em um numero", this.hssfCell.getColumnIndex())); + } + + return ret; + } + + public String getStringCellValue () throws CellStringFormatException{ + String ret = ""; + + try { + ret = this.hssfCell.getRichStringCellValue().getString(); + } catch (Exception e) { + throw new CellStringFormatException(String.format("O conteúdo da célula numérica não pode ser convertida em String", this.hssfCell.getColumnIndex())); + } + + return ret; + } + +} + diff --git a/example-apps/src/ip/dados/excel/ExcelRow.java b/example-apps/src/ip/dados/excel/ExcelRow.java new file mode 100644 index 0000000..773f7a8 --- /dev/null +++ b/example-apps/src/ip/dados/excel/ExcelRow.java @@ -0,0 +1,41 @@ +package dados.excel; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFRow; + +import dados.excel.exception.NotDefinedCellException; + +public class ExcelRow { + + + private HSSFRow hssfRow; + + public ExcelRow (HSSFRow hssfRow) { + this.setHSSFRow (hssfRow); + } + + protected void setHSSFRow (HSSFRow hssfRow) { + + if (hssfRow != null) { + this.hssfRow = hssfRow; + } else { + throw new IllegalArgumentException("A linha passada eh nula"); + } + + } + + public ExcelCell getCell (int cellnum) throws NotDefinedCellException { + ExcelCell ret = null; + HSSFCell tmp = this.hssfRow.getCell(cellnum); + + if (tmp != null) { + ret = new ExcelCell (tmp); + } else { + throw new NotDefinedCellException(String.format("A celula numero %d nao esta definida", cellnum)); + } + + return ret; + } + +} + diff --git a/example-apps/src/ip/dados/excel/ExcelSheet.java b/example-apps/src/ip/dados/excel/ExcelSheet.java new file mode 100644 index 0000000..24364b9 --- /dev/null +++ b/example-apps/src/ip/dados/excel/ExcelSheet.java @@ -0,0 +1,41 @@ +package dados.excel; + +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; + +import dados.excel.exception.NotDefinedRowException; + +public class ExcelSheet { + + + private HSSFSheet hssfSheet; + + public ExcelSheet (HSSFSheet hssfSheet) { + this.setHSSFSheet (hssfSheet); + } + + protected void setHSSFSheet (HSSFSheet hssfSheet) { + + if (hssfSheet != null) { + this.hssfSheet = hssfSheet; + } else { + throw new IllegalArgumentException("A planilha passada eh nula"); + } + + } + + public ExcelRow getRow (int rownum) throws NotDefinedRowException { + ExcelRow ret = null; + HSSFRow tmp = this.hssfSheet.getRow (rownum); + + if (tmp != null) { + ret = new ExcelRow (tmp); + } else { + throw new NotDefinedRowException(String.format("A linha(numero %d) nao esta definida", rownum)); + } + + return ret; + } + +} + diff --git a/example-apps/src/ip/dados/excel/ExcelWorkbook.java b/example-apps/src/ip/dados/excel/ExcelWorkbook.java new file mode 100644 index 0000000..e54a3f5 --- /dev/null +++ b/example-apps/src/ip/dados/excel/ExcelWorkbook.java @@ -0,0 +1,49 @@ +package dados.excel; + +import java.io.FileInputStream; +import java.io.IOException; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import dados.excel.exception.IOExcelException; +import dados.excel.exception.SheetNotFoundException; + +public class ExcelWorkbook { + + + private HSSFWorkbook hssfWorkbook; + + public ExcelWorkbook ( String nomeDoArquivo ) throws IOExcelException{ + try{ + FileInputStream fis = new FileInputStream(nomeDoArquivo); + HSSFWorkbook tmp = new HSSFWorkbook (fis); + this.setHSSFWorkbook (tmp); + } catch (IOException e) { + throw new IOExcelException(String.format("Erro ao ler um arquivo. verifique se o arquivo(%s) existe", nomeDoArquivo)); + } + } + + protected void setHSSFWorkbook (HSSFWorkbook hssfWorkbook) { + + if (hssfWorkbook != null) { + this.hssfWorkbook = hssfWorkbook; + } else { + throw new IllegalArgumentException("O valor passado eh nulo"); + } + + } + + public ExcelSheet getSheet (String name) throws SheetNotFoundException { + ExcelSheet ret = null; + HSSFSheet tmp = this.hssfWorkbook.getSheet (name); + + if (tmp != null) { + ret = new ExcelSheet (tmp); + } else { + throw new SheetNotFoundException(String.format("A planilha(%s) nao existe", name)); + } + + return ret; + } + +} + diff --git a/example-apps/src/ip/dados/excel/exception/CellNumberFormatException.java b/example-apps/src/ip/dados/excel/exception/CellNumberFormatException.java new file mode 100644 index 0000000..ca1bb26 --- /dev/null +++ b/example-apps/src/ip/dados/excel/exception/CellNumberFormatException.java @@ -0,0 +1,20 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class CellNumberFormatException extends Exception { + + private static final long serialVersionUID = 1548195017411199960L; + + /** + * @param arg0 + */ + public CellNumberFormatException(String arg0) { + super(arg0); + } +} diff --git a/example-apps/src/ip/dados/excel/exception/CellStringFormatException.java b/example-apps/src/ip/dados/excel/exception/CellStringFormatException.java new file mode 100644 index 0000000..4d7b4e4 --- /dev/null +++ b/example-apps/src/ip/dados/excel/exception/CellStringFormatException.java @@ -0,0 +1,20 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class CellStringFormatException extends Exception { + + private static final long serialVersionUID = 1547195057410199260L; + + /** + * @param arg0 + */ + public CellStringFormatException(String arg0) { + super(arg0); + } +} diff --git a/example-apps/src/ip/dados/excel/exception/IOExcelException.java b/example-apps/src/ip/dados/excel/exception/IOExcelException.java new file mode 100644 index 0000000..b49ac92 --- /dev/null +++ b/example-apps/src/ip/dados/excel/exception/IOExcelException.java @@ -0,0 +1,11 @@ +package dados.excel.exception; + +public class IOExcelException extends Exception { + + private static final long serialVersionUID = 3504731970684381191L; + + public IOExcelException(String arg0) { + super(arg0); + } + +} diff --git a/example-apps/src/ip/dados/excel/exception/NotDefinedCellException.java b/example-apps/src/ip/dados/excel/exception/NotDefinedCellException.java new file mode 100644 index 0000000..f72339b --- /dev/null +++ b/example-apps/src/ip/dados/excel/exception/NotDefinedCellException.java @@ -0,0 +1,25 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class NotDefinedCellException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -3064306033181968794L; + + /** + * @param arg0 + */ + public NotDefinedCellException(String arg0) { + super(arg0); + // TODO Auto-generated constructor stub + } + +} diff --git a/example-apps/src/ip/dados/excel/exception/NotDefinedRowException.java b/example-apps/src/ip/dados/excel/exception/NotDefinedRowException.java new file mode 100644 index 0000000..d82aeaf --- /dev/null +++ b/example-apps/src/ip/dados/excel/exception/NotDefinedRowException.java @@ -0,0 +1,24 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class NotDefinedRowException extends Exception { + + + + private static final long serialVersionUID = -8362425327793826851L; + + /** + * @param arg0 + */ + public NotDefinedRowException(String arg0) { + super(arg0); + // TODO Auto-generated constructor stub + } + +} diff --git a/example-apps/src/ip/dados/excel/exception/SheetNotFoundException.java b/example-apps/src/ip/dados/excel/exception/SheetNotFoundException.java new file mode 100644 index 0000000..419c003 --- /dev/null +++ b/example-apps/src/ip/dados/excel/exception/SheetNotFoundException.java @@ -0,0 +1,22 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class SheetNotFoundException extends Exception { + + private static final long serialVersionUID = 4160089517595438877L; + + /** + * @param arg0 + */ + public SheetNotFoundException(String arg0) { + super(arg0); + // TODO Auto-generated constructor stub + } + +} diff --git a/example-apps/src/ip/dados/interfaces/IRepositorioAdm.java b/example-apps/src/ip/dados/interfaces/IRepositorioAdm.java new file mode 100644 index 0000000..8922437 --- /dev/null +++ b/example-apps/src/ip/dados/interfaces/IRepositorioAdm.java @@ -0,0 +1,17 @@ +package dados.interfaces; + +import java.io.FileNotFoundException; +import java.io.IOException; + +import dados.entidade.Administrador; +import dados.IteratorClasse; + +public interface IRepositorioAdm { + + public void adicionar(Administrador administrador); + public void remover(String cpf); + public void atualizar(Administrador administrador); + public Administrador procurar(String cpf) throws FileNotFoundException, ClassNotFoundException, IOException; + + IteratorClasse iterator(); +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/interfaces/IRepositorioCliente.java b/example-apps/src/ip/dados/interfaces/IRepositorioCliente.java new file mode 100644 index 0000000..dab1258 --- /dev/null +++ b/example-apps/src/ip/dados/interfaces/IRepositorioCliente.java @@ -0,0 +1,14 @@ +package dados.interfaces; + +import dados.entidade.Cliente; +import dados.IteratorClasse; + +public interface IRepositorioCliente { + + public void adicionar(Cliente cliente); + public void remover(String cpf); + public void atualizar(Cliente cliente); + public Cliente procurar(String cpf); + + IteratorClasse iterator(); +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/interfaces/IRepositorioPedido.java b/example-apps/src/ip/dados/interfaces/IRepositorioPedido.java new file mode 100644 index 0000000..17195a3 --- /dev/null +++ b/example-apps/src/ip/dados/interfaces/IRepositorioPedido.java @@ -0,0 +1,14 @@ +package dados.interfaces; + +import dados.entidade.Pedido; +import dados.IteratorClasse; + +public interface IRepositorioPedido { + + public void adicionar(Pedido pedido); + public void remover(String codigo); + public void atualizar(Pedido pedido); + public Pedido procurar(String codigo); + + IteratorClasse iterator(); +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/interfaces/IRepositorioProduto.java b/example-apps/src/ip/dados/interfaces/IRepositorioProduto.java new file mode 100644 index 0000000..3f9c3ea --- /dev/null +++ b/example-apps/src/ip/dados/interfaces/IRepositorioProduto.java @@ -0,0 +1,16 @@ +package dados.interfaces; + + +import dados.entidade.Produto; +import dados.IteratorClasse; + +public interface IRepositorioProduto { + + public void adicionar(Produto produto); + public void remover(String codigo); + public void atualizar(Produto produto); + public Produto procurar(String codigo); + + IteratorClasse iterator(); + +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/repositorio/RepAdmArquivo.java b/example-apps/src/ip/dados/repositorio/RepAdmArquivo.java new file mode 100644 index 0000000..89c35d5 --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepAdmArquivo.java @@ -0,0 +1,263 @@ +package dados.repositorio; + +/*import dados.entidade.Contato; +import exceptions.CampoNaoPreenchidoException; +import exceptions.administrador.AdmNaoEncontradoException; +import exceptions.administrador.CpfInvalidoException; +import exceptions.administrador.CpfJaExisteException; +import exceptions.administrador.TelefoneInvalidoException; +import exceptions.administrador.TelefoneJaExisteException; +import negocio.ControladorAdm;*/ + +import dados.interfaces.IRepositorioAdm; +import dados.entidade.Administrador; +import dados.entidade.Contato; +import dados.IteratorClasse; +import exceptions.CampoNaoPreenchidoException; +import exceptions.administrador.CpfInvalidoException; +import exceptions.administrador.CpfJaExisteException; +import exceptions.administrador.TelefoneInvalidoException; +import exceptions.administrador.TelefoneJaExisteException; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Vector; + + + +public class RepAdmArquivo implements IRepositorioAdm { + + private Vector vetorAdministradores; + + + @SuppressWarnings({ "unchecked", "resource" }) + public RepAdmArquivo() throws IOException { + this.vetorAdministradores = new Vector(); + + File arquivo = new File("arquivoAdministrador.txt"); + if (!arquivo.exists()) { + arquivo.createNewFile(); + } + if (arquivo.length() != 0) { + ObjectInputStream reader = null; + try { + FileInputStream fileInput = new FileInputStream("arquivoAdministrador.txt"); + + reader = new ObjectInputStream(fileInput); + this.vetorAdministradores = (Vector) reader.readObject(); + } catch (ClassNotFoundException e) { + } + } + } + + public void adicionar(Administrador admin) { + this.vetorAdministradores.add(admin); + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoAdministrador.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorAdministradores); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + } catch (IOException e) { + } + } + } + + public void remover(String cpf) { + for (int i = 0; i < this.vetorAdministradores.size(); i++) { + if (this.vetorAdministradores.elementAt(i).getContato() == null) { + + } + else if (this.vetorAdministradores.elementAt(i).getCpf().equals(cpf)) { + this.vetorAdministradores.remove(i); + } + } + + ObjectOutputStream gravar = null; + + FileOutputStream writer; + try { + writer = new FileOutputStream("arquivoAdministrador.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorAdministradores); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + } finally { + try { + gravar.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("unchecked") + public Administrador procurar(String cpf) { + + //Cria um objeto FileInputStream + FileInputStream fileStream; + int indiceAchado = 0; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoAdministrador.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + + this.vetorAdministradores = (Vector) os.readObject(); + for (int indice = 0; indice < vetorAdministradores.size(); indice++) { + if (this.vetorAdministradores.elementAt(indice).getCpf().equals(cpf)) { + indiceAchado = indice; + //System.out.print(indiceAchado); + } + + + + } + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + return this.vetorAdministradores.elementAt(indiceAchado); + + } + //O método atualizar é basicamente feito o procurar, porém depois que ele atualiza um elemento + //Ele deve re-serializar tudo + @SuppressWarnings("unchecked") + public void atualizar(Administrador administrador){ + FileInputStream fileStream; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoAdministrador.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + //Deserializa o vector e verifica se o cpf do elemento é igual + //O cpf do objeto, atualiza e re-serializa. + int indiceAchado = 0; + this.vetorAdministradores = (Vector) os.readObject(); + for (int indice = 0; indice < vetorAdministradores.size(); indice++) { + if (this.vetorAdministradores.elementAt(indice).getCpf().equals(administrador.getCpf())) { + indiceAchado = indice; + //System.out.print(indiceAchado); + this.vetorAdministradores.elementAt(indiceAchado).setContato(administrador.getContato()); + this.vetorAdministradores.elementAt(indiceAchado).setNome(administrador.getNome()); + this.vetorAdministradores.elementAt(indiceAchado).setSenha(administrador.getSenha()); + + } + + + } + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoAdministrador.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorAdministradores); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + + } catch (IOException e) { + } + } + + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + + + } + + + + public IteratorClasse iterator() { + Vector listAdministradors = new Vector(); + for (int i = 0; i < this.vetorAdministradores.size(); i++) { + listAdministradors.add(this.vetorAdministradores.elementAt(i)); + } + IteratorClasse iterator = new IteratorClasse(listAdministradors); + return iterator; + } + + public static void main(String[] args) throws IOException, CpfJaExisteException, CpfInvalidoException, TelefoneInvalidoException, CampoNaoPreenchidoException, TelefoneJaExisteException { + + //TESTE REP-ARQUVIO + + RepAdmArquivo teste = new RepAdmArquivo(); + Contato contato = new Contato("Rua teste", " Testnumero", "Test complemento", "Test bairro" , "Test cidade" , "test uf", "test telefone"); + Administrador admin = new Administrador("Fabio", "156.111.111-11", "12345678", contato); + Administrador adminSubstituir = new Administrador("Junior Alterado", "156.111.111-11", "55555", contato); + + //teste.adicionar(admin); + //teste.adicionar(admin2); + System.out.println(teste.procurar("156.111.111-11").getNome()); + + teste.atualizar(adminSubstituir); + + + System.out.println(teste.procurar("156.111.111-11").getNome()); + + + /* + *:::::::::::TesteCONTROLADOR + * try { + + ControladorAdm controladorAdm = new ControladorAdm(new RepAdmArquivo()); + + + //controladorAdm.adicionar("156.111.111-11", "1234-5678", "teste", "teste", "teste", "teste", "teste", "teste", "teste", "teste"); + + //controladorAdm.adicionar("146.111.111-11", "1235-5678", "teste", "teste", "teste", "teste", "teste", "teste", "teste", "teste"); + + //controladorAdm.remover("156.111.111-11"); + + try { + + System.out.print(controladorAdm.buscaCpf("146.111.111-11").getSenha()); + } catch (AdmNaoEncontradoException e) { + e.getMessage(); + } + + } catch (IOException e) { + } + catch (CpfInvalidoException e2) { + e2.getMessage(); + } + } */ + } +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/repositorio/RepAdmArray.java b/example-apps/src/ip/dados/repositorio/RepAdmArray.java new file mode 100644 index 0000000..a9f1c11 --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepAdmArray.java @@ -0,0 +1,134 @@ +package dados.repositorio; + +import java.util.Vector; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioAdm; +import dados.entidade.Administrador; + +@SuppressWarnings("rawtypes") +public class RepAdmArray implements IRepositorioAdm, Iterable { + + private Administrador[] administradores; + private int indice; + + public RepAdmArray() { + this.administradores = new Administrador[1000]; + this.indice = 0; + } + + public boolean isVazia() { + if (indice == 0 && administradores[0].equals(null)) + return true; + return false; + } + + /*O método adicionar adiciona um objeto ao indice fixo que está é atributo do repositório + daí depois o indice é incrementado em 1 para ficar apto a receber um novo objeto + */ + public void adicionar(Administrador administrador) { + + if(this.indice < this.administradores.length) { + administradores[indice] = administrador; + indice++; + } else { + Administrador[] aux = new Administrador[this.administradores.length * 2]; + for(int i = 0; i < this.indice; i++) { + aux[i] = administradores[i]; + } + + this.administradores = aux; + this.adicionar(administrador); + } + } + + //Só mais para fins de teste, imprimir certo atributo de todos + public void imprimir() { + for(int i = 0; i < indice; i++) { + System.out.println(administradores[i].getCpf() + " - " + administradores[i].getNome()); + } + } + + //A partir da string cpf que vai ser única, ele remove o objeto designado + public void remover(String cpf) { + for(int i = 0; i < indice; i++) { + if(administradores[i].getCpf().equals(cpf)) { + administradores[i] = null; + if(i < indice - 1 && administradores[i + 1] != null) { + administradores[i] = administradores[i + 1]; + administradores[i + 1] = null; + } + } + } + + if(administradores[this.indice - 1] == null) + indice--; + } + //Se o cpf for igual ao objeto no índice, retorna aquele objeto + public Administrador procurar(String cpf) { + for(int i = 0; i < indice; i++) { + if(administradores[i].getCpf().equals(cpf)) + return administradores[i]; + } + + return null; + } + //Método para organizar, junto com um comparator ele compara 2 objetos, verificando seus cpfs + //Caso um cpf for "menor" que outro, ele troca de lugar por meio de um auxiliar + public void sort() { + + for (int i = 0; i < indice - 1; ++i) { + for (int j = i + 1; j < indice; ++j) { + if (administradores[i].getCpf().compareTo(administradores[j].getCpf()) > 0) { + Administrador aux = administradores[i]; + administradores[i] = administradores[j]; + administradores[j] = aux; + } + } + } + + } + + public IteratorClasse iterator() { + + Vector listAdm = new Vector(); + for (int i = 0; i < this.indice; i++) { + listAdm.add(this.administradores[i]); + } + + IteratorClasse iterator = new IteratorClasse(listAdm); + return iterator; + } + + public void atualizar(Administrador administrador) { + for (int i = 0; i < indice; i++) { + if(administradores[i].getCpf().equals(administrador.getCpf())) + administradores[i] = administrador; + } + } + + +//Teste + /*public static void main (String[] args) { + + RepAdmArray rep = new RepAdmArray(); + Administrador testep = new Administrador("Teste", "CPF", "Senha", null); + + Administrador teste2 = new Administrador("Teste2", "CPF2", "Senha3", null); + + Administrador teste3 = new Administrador("Teste3", "CPF3", "Senha3", null); + + + + rep.adicionar(teste3); + rep.adicionar(teste2); + rep.adicionar(testep); + + rep.imprimir(); + + System.out.println("Procura: "+ rep.procurar("CPF2") + "Valores ordenados: \n"); + rep.sort(); + rep.imprimir(); + } +*/ +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/repositorio/RepAdmLista.java b/example-apps/src/ip/dados/repositorio/RepAdmLista.java new file mode 100644 index 0000000..e9d831e --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepAdmLista.java @@ -0,0 +1,169 @@ +package dados.repositorio; + + + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioAdm; +import dados.entidade.Administrador; + + +public class RepAdmLista implements IRepositorioAdm { + + + + int numero_elementos; //Só pra saber se a lista esta vazia e tb o num. de el. + Administrador primeiro = new Administrador(); //O primeiro elemento da lista vai ser o do final, o �ltimo adicionado + Administrador ultimo = new Administrador(); //O ultimo da lista sempre vai apontar pra null + + public RepAdmLista() { + this.numero_elementos = 0; + this.primeiro = null; + this.ultimo = null; + + } + //LISTA ENCADEADA + + public boolean isVazia() { + return (primeiro == null && ultimo == null); + } + + public void adicionar(Administrador administrador) { + /*Qnd vc adiciona 1 elemento a lista, cria-se um objeto admin + *e a esse objeto vai ser atribu�do o valor de primeiro, que na verdade + *vai se tornar o elemento depois do primeiro. E o novo primeiro, vai ser + *admin, que � o objeto criado. + */ + Administrador admin = new Administrador(administrador); + if (isVazia()) { + this.primeiro = admin; + this.ultimo = admin; + + } + else { + admin.setProx(this.primeiro); + } + this.primeiro = admin; + numero_elementos++; + } + + public void adicionarNoFinal(Administrador administrador) { + this.numero_elementos++; + Administrador admin = new Administrador(administrador); + if (isVazia()) + primeiro = admin; + else + ultimo.setProx( admin); + this.ultimo = admin; + } + + + public void imprimir() { + if (this.numero_elementos == 0) + System.out.print("[]"); + else { + System.out.print("["); + Administrador aux = this.primeiro; + for(int i=0; i < this.numero_elementos-1;i++) { + System.out.print(aux.getCpf()+' '); + aux = aux.getProx(); + } + System.out.print(aux.getCpf()+"]"); + + + + } + } + + public Administrador procurar(String cpf){ //Sistema de busca retornando um objeto + Administrador aux = new Administrador(this.primeiro); + + if (aux.getCpf().equals(cpf)) { + return primeiro; + } + else { + for(int i=0; i <= numero_elementos - 1;i++) { + if (aux.getProx().getCpf().equals(cpf)) { + return aux.getProx(); + } + else + aux = aux.getProx(); + + + + + } + + } + return null; + } + + + public void remover(String cpf){ //Excluir um objeto da lista + Administrador aux, auxAnterior = new Administrador(); //Auxiliar, vai servir de apontador + aux = this.primeiro; + auxAnterior = null; + + + if (this.primeiro.getCpf().equals(cpf)) { + this.primeiro = primeiro.getProx(); + this.numero_elementos--; + + } + else { + while (aux !=null && aux.getCpf() != cpf) { + auxAnterior = aux; + aux = ((Administrador) aux).getProx(); + } + if(aux != null) { + ((Administrador) auxAnterior).setProx(aux.getProx()); + this.numero_elementos--; + } + if(aux == ultimo) { + ultimo = auxAnterior; + } + + + } + + + } + @Override + public IteratorClasse iterator() { + return null; + } + + public void atualizar(Administrador pessoa) { + + + procurar(pessoa.getCpf()).setContato(pessoa.getContato()); + procurar(pessoa.getCpf()).setNome(pessoa.getNome()); + procurar(pessoa.getCpf()).setSenha(pessoa.getSenha()); + + } +/* + public static void main(String...arguments) { + RepAdmLista lista = new RepAdmLista(); + + Administrador teste = new Administrador("Paulo", "1", "444", null); + Administrador teste2 = new Administrador("Fera", "2", "555", null); + Administrador testeAtualiza = new Administrador("Fabio", "2", "444", null); + + lista.adicionar(teste); + lista.adicionar(teste2); + + lista.imprimir(); + + System.out.print(lista.procurar("2").getNome()); + + lista.atualizar(testeAtualiza); + + System.out.print(lista.procurar("2").getNome()); + + lista.imprimir(); + } + */ + +} + + + diff --git a/example-apps/src/ip/dados/repositorio/RepClienteArquivo.java b/example-apps/src/ip/dados/repositorio/RepClienteArquivo.java new file mode 100644 index 0000000..534ff89 --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepClienteArquivo.java @@ -0,0 +1,201 @@ +package dados.repositorio; + +import dados.interfaces.IRepositorioCliente; +import dados.entidade.Cliente; +import dados.IteratorClasse; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Vector; + + + +public class RepClienteArquivo implements IRepositorioCliente{ + + private Vector vetorClientes; + + + @SuppressWarnings({ "unchecked", "resource" }) + public RepClienteArquivo() throws IOException { + this.vetorClientes = new Vector(); + + File arquivo = new File("arquivoCliente.txt"); + if (!arquivo.exists()) { + arquivo.createNewFile(); + } + if (arquivo.length() != 0) { + ObjectInputStream reader = null; + try { + FileInputStream fileInput = new FileInputStream("arquivoCliente.txt"); + + reader = new ObjectInputStream(fileInput); + this.vetorClientes = (Vector) reader.readObject(); + } catch (ClassNotFoundException e) { + } + } + } + + public void adicionar(Cliente cliente) { + this.vetorClientes.add(cliente); + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoCliente.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorClientes); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + } catch (IOException e) { + } + } + } + + public void remover(String cpf) { + for (int i = 0; i < this.vetorClientes.size(); i++) { + if (this.vetorClientes.elementAt(i).getContato() == null) { + + } + else if (this.vetorClientes.elementAt(i).getCpf().equals(cpf)) { + this.vetorClientes.remove(i); + } + } + + ObjectOutputStream gravar = null; + + FileOutputStream writer; + try { + writer = new FileOutputStream("arquivoCliente.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorClientes); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + } finally { + try { + gravar.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("unchecked") + public Cliente procurar(String cpf) { + + //Cria um objeto FileInputStream + FileInputStream fileStream; + int indiceAchado = 0; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoCliente.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + + this.vetorClientes = (Vector) os.readObject(); + for (int indice = 0; indice < vetorClientes.size(); indice++) { + if (this.vetorClientes.elementAt(indice).getCpf().equals(cpf)) { + indiceAchado = indice; + //System.out.print(indiceAchado); + } + + + + } + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + return this.vetorClientes.elementAt(indiceAchado); + + } + //O método atualizar é basicamente feito o procurar, porém depois que ele atualiza um elemento + //Ele deve re-serializar tudo + @SuppressWarnings("unchecked") + public void atualizar(Cliente cliente){ + FileInputStream fileStream; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoCliente.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + //Deserializa o vector e verifica se o cpf do elemento é igual + //O cpf do objeto, atualiza e re-serializa. + int indiceAchado = 0; + this.vetorClientes = (Vector) os.readObject(); + for (int indice = 0; indice < vetorClientes.size(); indice++) { + if (this.vetorClientes.elementAt(indice).getCpf().equals(cliente.getCpf())) { + indiceAchado = indice; + //System.out.print(indiceAchado); + this.vetorClientes.elementAt(indiceAchado).setContato(cliente.getContato()); + this.vetorClientes.elementAt(indiceAchado).setNome(cliente.getNome()); + this.vetorClientes.elementAt(indiceAchado).setSenha(cliente.getSenha()); + + } + + + } + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoCliente.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorClientes); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + + } catch (IOException e) { + } + } + + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + + + } + + + + public IteratorClasse iterator() { + Vector listClientes = new Vector(); + for (int i = 0; i < this.vetorClientes.size(); i++) { + listClientes.add(this.vetorClientes.elementAt(i)); + } + IteratorClasse iterator = new IteratorClasse(listClientes); + return iterator; + } + +} diff --git a/example-apps/src/ip/dados/repositorio/RepClienteArray.java b/example-apps/src/ip/dados/repositorio/RepClienteArray.java new file mode 100644 index 0000000..028b45b --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepClienteArray.java @@ -0,0 +1,92 @@ +package dados.repositorio; + +import java.util.Vector; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioCliente; +import dados.entidade.Cliente; + +@SuppressWarnings("rawtypes") +public class RepClienteArray implements IRepositorioCliente, Iterable { + + private Cliente[] clientes; + private int indice; + + public RepClienteArray() { + this.clientes = new Cliente[1000]; + this.indice = 0; + } + + public boolean isVazia() { + if (indice == 0 && clientes[0].equals(null)) + return true; + return false; + } + + public void imprimir() { + for(int i = 0; i < indice; i++) { + System.out.println(clientes[i].getCpf() + " - " + clientes[i].getNome()); + } + + } + + public void adicionar(Cliente cliente) { + if (this.indice < this.clientes.length) { + clientes[this.indice] = cliente; + this.indice++; + } else { + Cliente[] auxiliar = new Cliente[this.clientes.length * 2]; + for (int i = 0; i < this.clientes.length; i++) { + auxiliar[i] = this.clientes[i]; + } + this.clientes = auxiliar; + this.adicionar(cliente); + } + } + + public void remover(String cpf) { + for(int i = 0; i < indice; i++) { + if(clientes[i].getCpf().equals(cpf)) { + clientes[i] = clientes[indice - 1]; + indice--; + } + } + } + + public Cliente procurar(String cpf) { + for(int i = 0; i < indice; i++) { + if(clientes[i].getCpf().equals(cpf)) + return clientes[i]; + } + + return null; + } + + public void sort() { + + for (int i = 0; i < indice - 1; ++i) { + for (int j = i + 1; j < indice; ++j) { + if (clientes[i].getCpf().compareTo(clientes[j].getCpf()) > 0) { + Cliente aux = clientes[i]; + clientes[i] = clientes[j]; + clientes[j] = aux; + } + } + } + + } + + public void atualizar(Cliente cliente) { + + } + + public IteratorClasse iterator() { + Vector listCli = new Vector(); + for(int i = 0; i < indice; i++) { + listCli.add(this.clientes[i]); + } + + IteratorClasse iterator = new IteratorClasse(listCli); + return iterator; + } +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/repositorio/RepClienteLista.java b/example-apps/src/ip/dados/repositorio/RepClienteLista.java new file mode 100644 index 0000000..34161c2 --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepClienteLista.java @@ -0,0 +1,147 @@ +package dados.repositorio; + + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioCliente; +import dados.entidade.Cliente; +import dados.entidade.Pessoa; + +public class RepClienteLista implements IRepositorioCliente { + + + + int numero_elementos; //Só pra saber se a lista esta vazia e tb o num. de el. + Pessoa primeiro = new Cliente(); //O primeiro elemento da lista vai ser o do final, o �ltimo adicionado + Pessoa ultimo = new Cliente(); //O ultimo da lista sempre vai apontar pra null + + public RepClienteLista() { + this.numero_elementos = 0; + this.primeiro = null; + this.ultimo = null; + + } + //LISTA ENCADEADA + + public boolean isVazia() { + return (primeiro == null && ultimo == null); + } + + public void adicionar(Cliente pessoa) { + /*Qnd vc adiciona 1 elemento a lista, cria-se um objeto cliente + *e a esse objeto vai ser atribu�do o valor de primeiro, que na verdade + *vai se tornar o elemento depois do primeiro. E o novo primeiro, vai ser + *cliente, que � o objeto criado. + */ + Pessoa cliente = new Cliente((Cliente) pessoa); + if (isVazia()) { + this.primeiro = cliente; + this.ultimo = cliente; + + } + else { + ((Cliente) cliente).setProx((Cliente) this.primeiro); + } + this.primeiro = cliente; + numero_elementos++; + } + + public void adicionarNoFinal(Pessoa pessoa) { + this.numero_elementos++; + Pessoa cliente = new Cliente((Cliente) pessoa); + if (isVazia()) + primeiro = cliente; + else + ((Cliente) ultimo).setProx((Cliente) cliente); + this.ultimo = cliente; + } + + + public void imprimir() { + if (this.numero_elementos == 0) + System.out.print("[]"); + else { + System.out.print("["); + Pessoa aux = this.primeiro; + for(int i=0; i < this.numero_elementos-1;i++) { + System.out.print(aux.getCpf()+' '); + aux = ((Cliente)aux).getProx(); + } + System.out.print(((Cliente)aux).getCpf()+"]"); + + + + } + } + + public Cliente procurar(String cpf){ //Sistema de busca retornando um objeto + Pessoa aux = new Cliente((Cliente) this.primeiro); + + if (((Cliente)aux).getCpf().equals(cpf)) { + return (Cliente) primeiro; + } + else { + for(int i=0; i <= numero_elementos - 1;i++) { + if (((Cliente)aux).getProx().getCpf().equals(cpf)) { + return ((Cliente)aux).getProx(); + } + else + aux = ((Cliente)aux).getProx(); + + + + + } + + } + return null; + } + + + public void remover(String cpf){ //Excluir um objeto da lista + Pessoa aux, auxAnterior = new Cliente(); //Auxiliar, vai servir de apontador + aux = this.primeiro; + auxAnterior = null; + + + if (this.primeiro.getCpf().equals(cpf)) { + this.primeiro = ((Cliente) primeiro).getProx(); + this.numero_elementos--; + + } + else { + while (aux !=null && !aux.getCpf().equals(cpf)) { + auxAnterior = aux; + aux = ((Cliente) aux).getProx(); + } + if(aux != null) { + ((Cliente) auxAnterior).setProx(((Cliente) aux).getProx()); + this.numero_elementos--; + } + if(aux == ultimo) { + ultimo = auxAnterior; + } + + + } + + + } + + public void atualizar(Cliente pessoa) { + + + procurar(pessoa.getCpf()).setContato(pessoa.getContato()); + procurar(pessoa.getCpf()).setNome(pessoa.getNome()); + procurar(pessoa.getCpf()).setSenha(pessoa.getSenha()); + + } + + @Override + public IteratorClasse iterator() { + // TODO Auto-generated method stub + return null; + } + + + +} diff --git a/example-apps/src/ip/dados/repositorio/RepPedidoArquivo.java b/example-apps/src/ip/dados/repositorio/RepPedidoArquivo.java new file mode 100644 index 0000000..660e086 --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepPedidoArquivo.java @@ -0,0 +1,206 @@ +package dados.repositorio; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Vector; + +import dados.IteratorClasse; +import dados.entidade.Pedido; +import dados.interfaces.IRepositorioPedido; + +public class RepPedidoArquivo implements IRepositorioPedido { + + private Vector vetorPedidos; + + @SuppressWarnings({ "unchecked", "resource" }) + public RepPedidoArquivo() throws IOException { + this.vetorPedidos = new Vector(); + + File arquivo = new File("arquivoPedido.txt"); + if (!arquivo.exists()) { + arquivo.createNewFile(); + } + if (arquivo.length() != 0) { + ObjectInputStream reader = null; + try { + FileInputStream fileInput = new FileInputStream("arquivoPedido.txt"); + + reader = new ObjectInputStream(fileInput); + this.vetorPedidos = (Vector) reader.readObject(); + } catch (ClassNotFoundException e) { + } + } + } + + public void adicionar(Pedido pedido) { + this.vetorPedidos.add(pedido); + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoPedido.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorPedidos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + } catch (IOException e) { + } + } + } + + public void remover(String codigo) { + for (int i = 0; i < this.vetorPedidos.size(); i++) { + if (this.vetorPedidos.elementAt(i).getPreco() == null) { + + } + else if (this.vetorPedidos.elementAt(i).getCodigo().equals(codigo)) { + this.vetorPedidos.remove(i); + } + } + + ObjectOutputStream gravar = null; + + FileOutputStream writer; + try { + writer = new FileOutputStream("arquivoPedido.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorPedidos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + } finally { + try { + gravar.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("unchecked") + public Pedido procurar(String codigo) { + + //Cria um objeto FileInputStream + FileInputStream fileStream; + int indiceAchado = 0; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoPedido.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + + this.vetorPedidos = (Vector) os.readObject(); + for (int indice = 0; indice < vetorPedidos.size(); indice++) { + if (this.vetorPedidos.elementAt(indice).getCodigo().equals(codigo)) { + indiceAchado = indice; + //System.out.print(indiceAchado); + } + + + + } + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + return this.vetorPedidos.elementAt(indiceAchado); + + } + //O método atualizar é basicamente feito o procurar, porém depois que ele atualiza um elemento + //Ele deve re-serializar tudo + @SuppressWarnings("unchecked") + public void atualizar(Pedido pedidosubs){ + FileInputStream fileStream; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoPedido.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + //Deserializa o vector e verifica se o cpf do elemento é igual + //O cpf do objeto, atualiza e re-serializa. + int indiceAchado = 0; + this.vetorPedidos = (Vector) os.readObject(); + for (int indice = 0; indice < vetorPedidos.size(); indice++) { + if (this.vetorPedidos.elementAt(indice).getCodigo().equals(pedidosubs.getCodigo())) { + indiceAchado = indice; + //System.out.print(indiceAchado); + this.vetorPedidos.elementAt(indiceAchado).setCliente(pedidosubs.getCliente()); + this.vetorPedidos.elementAt(indiceAchado).setData(pedidosubs.getData()); + this.vetorPedidos.elementAt(indiceAchado).setPreco(pedidosubs.getPreco()); + this.vetorPedidos.elementAt(indiceAchado).setProdutos(pedidosubs.getProdutos()); + this.vetorPedidos.elementAt(indiceAchado).setQuantidade(pedidosubs.getQuantidade()); + } + + + } + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoPedido.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorPedidos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + + } catch (IOException e) { + } + } + + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + + + } + + + // ObjectOutputStream escreve por cima do arquivo antigo (append false) + public Vector getListaPedidos() { + return this.vetorPedidos; + } + + @Override + public IteratorClasse iterator() { + // TODO Auto-generated method stub + Vector listPedidos = new Vector(); + for (int i = 0; i < this.vetorPedidos.size(); i++) { + listPedidos.add(this.vetorPedidos.elementAt(i)); + } + IteratorClasse iterator = new IteratorClasse(listPedidos); + return iterator; + + } +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/repositorio/RepPedidoArray.java b/example-apps/src/ip/dados/repositorio/RepPedidoArray.java new file mode 100644 index 0000000..98f2c28 --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepPedidoArray.java @@ -0,0 +1,110 @@ +package dados.repositorio; + +import java.util.Vector; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioPedido; +import dados.entidade.Pedido; + + +@SuppressWarnings("rawtypes") +public class RepPedidoArray implements IRepositorioPedido, Iterable { + private Pedido[] pedidos; + private int indice; + + public boolean isVazia() { + if (indice == 0 && pedidos[0].equals(null)) + return true; + return false; + } + + public RepPedidoArray() { + pedidos = new Pedido[1000]; + indice = 0; + } + + public void adicionar(Pedido pedido) { + + if(this.indice < this.pedidos.length) { + pedidos[indice] = pedido; + indice++; + } else { + Pedido[] aux = new Pedido[this.pedidos.length * 2]; + for(int i = 0; i < this.indice; i++) { + aux[i] = this.pedidos[i]; + } + + this.pedidos = aux; + this.adicionar(pedido); + } + + } + + public void remover(String codigo) { + for(int i = 0; i < indice; i++) { + if(pedidos[i].getCodigo().equals(codigo)) { + pedidos[i] = null; + if(i < indice - 1 && pedidos[i + 1] != null) { + pedidos[i] = pedidos[i + 1]; + pedidos[i + 1] = null; + } + } + } + + if(pedidos[this.indice - 1] == null) + indice--; + } + + public Pedido procurar(String codigo) { + for(int i = 0; i < indice; i++) { + if(pedidos[i].getCodigo().equals(codigo)) + return pedidos[i]; + } + + return null; + } + + public void imprimir() { + for(int i = 0; i < indice; i++) { + System.out.print(pedidos[i].getCodigo()); + } + + } + + public void atualizar(Pedido pedido) { + for(int i = 0; i < indice; i++) { + if(pedidos[i].getCodigo().equals(pedido.getCodigo())) + pedidos[i] = pedido; + } + } + + public void sort() { + + for (int i = 0; i < indice - 1; ++i) { + for (int j = i + 1; j < indice; ++j) { + if (pedidos[i].getCodigo().compareTo(pedidos[j].getCodigo()) > 0) { + Pedido aux = pedidos[i]; + pedidos[i] = pedidos[j]; + pedidos[j] = aux; + } + } + } + + } + + public IteratorClasse iterator() { + Vector listPedido = new Vector(); + for(int i = 0; i < indice; i++) { + listPedido.add(pedidos[i]); + } + + IteratorClasse iterator = new IteratorClasse(listPedido); + return iterator; + } + + public Pedido[] getLista() { + return this.pedidos; + } + + +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/repositorio/RepPedidoLista.java b/example-apps/src/ip/dados/repositorio/RepPedidoLista.java new file mode 100644 index 0000000..002b1c0 --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepPedidoLista.java @@ -0,0 +1,148 @@ +package dados.repositorio; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioPedido; +import dados.entidade.Pedido; + + +public class RepPedidoLista implements IRepositorioPedido{ + + int numero_elementos; //Só pra saber se a lista esta vazia e tb o num. de el. + Pedido primeiro = new Pedido(); //O primeiro elemento da lista vai ser o do final, o �ltimo adicionado + Pedido ultimo = new Pedido(); //O ultimo da lista sempre vai apontar pra null + + public RepPedidoLista() { + this.numero_elementos = 0; + this.primeiro = null; + this.ultimo = null; + + } + //LISTA ENCADEADA + + public boolean isVazia() { + return (primeiro == null && ultimo == null); + } + + public void adicionar(Pedido produto) { + /*Qnd vc adiciona 1 elemento a lista, cria-se um objeto pedido + *e a esse objeto vai ser atribu�do o valor de primeiro, que na verdade + *vai se tornar o elemento depois do primeiro. E o novo primeiro, vai ser + *pedido, que � o objeto criado. + */ + Pedido pedido = new Pedido(produto); + if (isVazia()) { + this.primeiro = pedido; + this.ultimo = pedido; + + } + else { + ((Pedido) pedido).setProx((Pedido) this.primeiro); + } + this.primeiro = pedido; + numero_elementos++; + } + + public void inserirNoFinal(Pedido produto) { + this.numero_elementos++; + Pedido pedido = new Pedido(produto); + if (isVazia()) + primeiro = pedido; + else + ((Pedido) ultimo).setProx((Pedido) pedido); + this.ultimo = pedido; + } + + + public void imprimir() { + if (this.numero_elementos == 0) + System.out.print("[]"); + else { + System.out.print("["); + Pedido aux = this.primeiro; + for(int i=0; i < this.numero_elementos-1;i++) { + System.out.print(aux.getCodigo()+' '); + aux = ((Pedido)aux).getProx(); + } + System.out.print(((Pedido)aux).getCodigo()+"]"); + + + + } + } + + public Pedido procurar(String codigo){ //Sistema de busca retornando um objeto + Pedido aux = new Pedido(this.primeiro); + + if (((Pedido)aux).getCodigo().equals(codigo)) { + return primeiro; + } + else { + for(int i=0; i <= numero_elementos - 1;i++) { + if (((Pedido)aux).getProx().getCodigo().equals(codigo)) { + return ((Pedido)aux).getProx(); + } + else + aux = ((Pedido)aux).getProx(); + + + + + } + + } + return null; + } + + + public void remover(String codigo){ //Excluir um objeto da lista + Pedido aux, auxAnterior = new Pedido(); //Auxiliar, vai servir de apontador + aux = this.primeiro; + auxAnterior = null; + + + if (this.primeiro.getCodigo().equals(codigo)) { + this.primeiro = ((Pedido) primeiro).getProx(); + this.numero_elementos--; + + } + else { + while (aux !=null && !aux.getCodigo().equals(codigo)) { + auxAnterior = aux; + aux = ((Pedido) aux).getProx(); + } + if(aux != null) { + ((Pedido) auxAnterior).setProx(((Pedido) aux).getProx()); + this.numero_elementos--; + } + if(aux == ultimo) { + ultimo = auxAnterior; + } + + + } + + + } + + + @Override + public IteratorClasse iterator() { + // TODO Auto-generated method stub + return null; + } + + public void atualizar(Pedido produto) { + + + procurar(produto.getCodigo()).setCliente(produto.getCliente()); + procurar(produto.getCodigo()).setData(produto.getData()); + procurar(produto.getCodigo()).setPreco(produto.getPreco()); + procurar(produto.getCodigo()).setQuantidade(produto.getQuantidade()); + procurar(produto.getCodigo()).setProdutos(produto.getProdutos()); + } + + + + + +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/repositorio/RepProdutoArquivo.java b/example-apps/src/ip/dados/repositorio/RepProdutoArquivo.java new file mode 100644 index 0000000..821eff1 --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepProdutoArquivo.java @@ -0,0 +1,200 @@ +package dados.repositorio; + +import dados.interfaces.IRepositorioProduto; +import dados.entidade.Produto; +import dados.IteratorClasse; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Vector; + + + +public class RepProdutoArquivo implements IRepositorioProduto{ + + private Vector vetorProdutos; + + + @SuppressWarnings({ "unchecked", "resource" }) + public RepProdutoArquivo() throws IOException { + this.vetorProdutos = new Vector(); + + File arquivo = new File("arquivoProduto.txt"); + if (!arquivo.exists()) { + arquivo.createNewFile(); + } + if (arquivo.length() != 0) { + ObjectInputStream reader = null; + try { + FileInputStream fileInput = new FileInputStream("arquivoProduto.txt"); + + reader = new ObjectInputStream(fileInput); + this.vetorProdutos = (Vector) reader.readObject(); + } catch (ClassNotFoundException e) { + } + } + } + + public void adicionar(Produto produto) { + this.vetorProdutos.add(produto); + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoProduto.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorProdutos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + } catch (IOException e) { + } + } + } + + public void remover(String cpf) { + for (int i = 0; i < this.vetorProdutos.size(); i++) { + if (this.vetorProdutos.elementAt(i).getPreco() == null) { + + } + else if (this.vetorProdutos.elementAt(i).getCodigo().equals(cpf)) { + this.vetorProdutos.remove(i); + } + } + + ObjectOutputStream gravar = null; + + FileOutputStream writer; + try { + writer = new FileOutputStream("arquivoProduto.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorProdutos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + } finally { + try { + gravar.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("unchecked") + public Produto procurar(String cpf) { + + //Cria um objeto FileInputStream + FileInputStream fileStream; + int indiceAchado = 0; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoProduto.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + + this.vetorProdutos = (Vector) os.readObject(); + for (int indice = 0; indice < vetorProdutos.size(); indice++) { + if (this.vetorProdutos.elementAt(indice).getCodigo().equals(cpf)) { + indiceAchado = indice; + //System.out.print(indiceAchado); + } + + + + } + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + return this.vetorProdutos.elementAt(indiceAchado); + + } + //O método atualizar é basicamente feito o procurar, porém depois que ele atualiza um elemento + //Ele deve re-serializar tudo + @SuppressWarnings("unchecked") + public void atualizar(Produto produtosubs){ + FileInputStream fileStream; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoProduto.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + //Deserializa o vector e verifica se o cpf do elemento é igual + //O cpf do objeto, atualiza e re-serializa. + int indiceAchado = 0; + this.vetorProdutos = (Vector) os.readObject(); + for (int indice = 0; indice < vetorProdutos.size(); indice++) { + if (this.vetorProdutos.elementAt(indice).getCodigo().equals(produtosubs.getCodigo())) { + indiceAchado = indice; + //System.out.print(indiceAchado); + this.vetorProdutos.elementAt(indiceAchado).setDescricao(produtosubs.getDescricao()); + this.vetorProdutos.elementAt(indiceAchado).setNome(produtosubs.getNome()); + this.vetorProdutos.elementAt(indiceAchado).setPreco(produtosubs.getPreco()); + + } + + + } + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoProduto.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorProdutos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + + } catch (IOException e) { + } + } + + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + + + } + + + + public IteratorClasse iterator() { + Vector listProdutos = new Vector(); + for (int i = 0; i < this.vetorProdutos.size(); i++) { + listProdutos.add(this.vetorProdutos.elementAt(i)); + } + IteratorClasse iterator = new IteratorClasse(listProdutos); + return iterator; + } +} \ No newline at end of file diff --git a/example-apps/src/ip/dados/repositorio/RepProdutoArray.java b/example-apps/src/ip/dados/repositorio/RepProdutoArray.java new file mode 100644 index 0000000..b1e9cf0 --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepProdutoArray.java @@ -0,0 +1,107 @@ +package dados.repositorio; + +import java.util.Vector; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioProduto; +import dados.entidade.Produto; + +@SuppressWarnings("rawtypes") +public class RepProdutoArray implements IRepositorioProduto, Iterable { + + + private Produto[] produtos; + private int indice; + + public boolean isVazia() { + if (indice == 0 && produtos[0].equals(null)) + return true; + return false; + } + + public RepProdutoArray() { + produtos = new Produto[2000]; + indice = 0; + } + + public void adicionar(Produto produto) { + if(this.indice < this.produtos.length) { + produtos[indice] = produto; + indice++; + } else { + Produto[] aux = new Produto[this.produtos.length * 2]; + for(int i = 0; i < indice; i++) { + aux[i] = produtos[i]; + } + + this.produtos = aux; + this.adicionar(produto); + + + } + } + + + public void remover(String codigo) { + for(int i = 0; i < indice; i++) { + if(produtos[i].getCodigo().equals(codigo)) { + produtos[i] = null; + if(i < indice - 1 && produtos[i + 1] != null) { + produtos[i] = produtos[i + 1]; + produtos[i + 1] = null; + } + } + } + + if(produtos[this.indice - 1] == null) + indice--; + } + + public Produto procurar(String codigo) { + for(int i = 0; i < indice; i++) { + if(produtos[i].getCodigo().equals(codigo)) + return produtos[i]; + } + + return null; + } + + public void atualizar(Produto produto) { + for(int i = 0; i < indice; i++) { + if(produtos[i].getCodigo().equals(produto.getCodigo())) + produtos[i] = produto; + } + } + + public void imprimir() { + for(int i = 0; i < indice; i++) { + System.out.print(produtos[i].getCodigo()); + } + + } + + public void sort() { + + for (int i = 0; i < indice - 1; ++i) { + for (int j = i + 1; j < indice; ++j) { + if (produtos[i].getCodigo().compareTo(produtos[j].getCodigo()) > 0) { + Produto aux = produtos[i]; + produtos[i] = produtos[j]; + produtos[j] = aux; + } + } + } + + } + public IteratorClasse iterator() { + Vector listProd = new Vector(); + for(int i = 0; i < indice; i++) { + listProd.add(produtos[i]); + } + + IteratorClasse iterator = new IteratorClasse(listProd); + return iterator; + } +} + + \ No newline at end of file diff --git a/example-apps/src/ip/dados/repositorio/RepProdutoLista.java b/example-apps/src/ip/dados/repositorio/RepProdutoLista.java new file mode 100644 index 0000000..2874c1d --- /dev/null +++ b/example-apps/src/ip/dados/repositorio/RepProdutoLista.java @@ -0,0 +1,150 @@ +package dados.repositorio; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioProduto; +import dados.entidade.Livro; +import dados.entidade.Produto; + + + +public class RepProdutoLista implements IRepositorioProduto{ + + int numero_elementos; //Só pra saber se a lista esta vazia e tb o num. de el. + Produto primeiro = new Livro(); //O primeiro elemento da lista vai ser o do final, o �ltimo adicionado + Produto ultimo = new Livro(); //O ultimo da lista sempre vai apontar pra null + + public RepProdutoLista() { + this.numero_elementos = 0; + this.primeiro = null; + this.ultimo = null; + + } + //LISTA ENCADEADA + + public boolean isVazia() { + return (primeiro == null && ultimo == null); + } + + public void adicionar(Produto produto) { + /*Qnd vc adiciona 1 elemento a lista, cria-se um objeto livro + *e a esse objeto vai ser atribu�do o valor de primeiro, que na verdade + *vai se tornar o elemento depois do primeiro. E o novo primeiro, vai ser + *livro, que � o objeto criado. + */ + Produto livro = new Livro(produto); + if (isVazia()) { + this.primeiro = livro; + this.ultimo = livro; + + } + else { + ((Livro) livro).setProx((Livro) this.primeiro); + } + this.primeiro = livro; + numero_elementos++; + } + + public void inserirNoFinal(Produto produto) { + this.numero_elementos++; + Produto livro = new Livro(produto); + if (isVazia()) + primeiro = livro; + else + ((Livro) ultimo).setProx((Livro) livro); + this.ultimo = livro; + } + + + public void imprimir() { + if (this.numero_elementos == 0) + System.out.print("[]"); + else { + System.out.print("["); + Produto aux = this.primeiro; + for(int i=0; i < this.numero_elementos-1;i++) { + System.out.print(aux.getCodigo()+' '); + aux = ((Livro)aux).getProx(); + } + System.out.print(((Livro)aux).getCodigo()+"]"); + + + + } + } + + public Produto procurar(String codigo){ //Sistema de busca retornando um objeto + Produto aux = new Livro(this.primeiro); + + if (((Livro)aux).getCodigo().equals(codigo)) { + return primeiro; + } + else { + for(int i=0; i <= numero_elementos - 1;i++) { + if (((Livro)aux).getProx().getCodigo().equals(codigo)) { + return ((Livro)aux).getProx(); + } + else + aux = ((Livro)aux).getProx(); + + + + + } + + } + return null; + } + + + public void remover(String codigo){ //Excluir um objeto da lista + Produto aux, auxAnterior = new Livro(); //Auxiliar, vai servir de apontador + aux = this.primeiro; + auxAnterior = null; + + + if (this.primeiro.getCodigo().equals(codigo)) { + this.primeiro = ((Livro) primeiro).getProx(); + this.numero_elementos--; + + } + else { + while (aux !=null && !aux.getCodigo().equals(codigo)) { + auxAnterior = aux; + aux = ((Livro) aux).getProx(); + } + if(aux != null) { + ((Livro) auxAnterior).setProx(((Livro) aux).getProx()); + this.numero_elementos--; + } + if(aux == ultimo) { + ultimo = auxAnterior; + } + + + } + + + } + + + @Override + public IteratorClasse iterator() { + // TODO Auto-generated method stub + return null; + } + + public void atualizar(Produto produto) { + + + procurar(produto.getCodigo()).setDescricao(produto.getDescricao()); + procurar(produto.getCodigo()).setNome(produto.getNome()); + procurar(produto.getCodigo()).setPreco(produto.getPreco()); + + + } + + + + + +} \ No newline at end of file diff --git a/example-apps/src/ip/entidade/Administrador.java b/example-apps/src/ip/entidade/Administrador.java new file mode 100644 index 0000000..bfd2ccc --- /dev/null +++ b/example-apps/src/ip/entidade/Administrador.java @@ -0,0 +1,56 @@ +package dados.entidade; + +import java.io.Serializable; + +import dados.entidade.interfaces.IAdm; + + +@SuppressWarnings("rawtypes") +public class Administrador extends Pessoa implements IAdm, Serializable, Comparable { + + private static final long serialVersionUID = 799180543074610211L; + Administrador prox; //Proximo da Lista + Contato contato; + + public Administrador(String nome, String cpf, String senha, Contato contato) { + super(nome, cpf, senha, contato); + this.contato = contato; + this.prox = null; + } + + + + + public Administrador(Administrador administrador) { + this.nome = administrador.getNome(); + this.cpf = administrador.getCpf(); + this.contato = administrador.getContato(); + this.senha = administrador.getSenha(); + this.prox = administrador.getProx(); + + } + + + public Administrador() { + + } + + + + public Administrador getProx() { + return prox; + } + + public void setProx(Administrador prox) { + this.prox = prox; + } + + public int compareTo(Object o) { + // TODO Auto-generated method stub + return 0; + } + + + + +} \ No newline at end of file diff --git a/example-apps/src/ip/entidade/Cliente.java b/example-apps/src/ip/entidade/Cliente.java new file mode 100644 index 0000000..0159c2b --- /dev/null +++ b/example-apps/src/ip/entidade/Cliente.java @@ -0,0 +1,36 @@ +package dados.entidade; + +import java.io.Serializable; + +import dados.entidade.interfaces.ICliente; + + +public class Cliente extends Pessoa implements ICliente, Serializable { + + private static final long serialVersionUID = -181648016681977239L; + Cliente prox; //Proximo da Lista + Contato contato; + + public Cliente(String nome, String cpf, String senha, Contato contato) { + super(nome, cpf, senha, contato); + this.contato = contato; + this.prox = null; + } + + public Cliente(Cliente cliente) { + this.nome = cliente.getNome(); + this.cpf = cliente.getCpf(); + this.contato = cliente.getContato(); + this.senha = cliente.getSenha(); + this.prox = cliente.getProx(); + + } + + public Cliente() { + + } + + public Cliente getProx() { return prox;} + public void setProx(Cliente prox) { this.prox = prox;} + +} \ No newline at end of file diff --git a/example-apps/src/ip/entidade/Contato.java b/example-apps/src/ip/entidade/Contato.java new file mode 100644 index 0000000..a7d2388 --- /dev/null +++ b/example-apps/src/ip/entidade/Contato.java @@ -0,0 +1,58 @@ +package dados.entidade; + +import java.io.Serializable; + +public class Contato implements Serializable{ + + private static final long serialVersionUID = -1548581281174377261L; + private String telefone, numero, rua, bairro, cidade, uf, complemento; + + public Contato(String rua, String numero, String complemento, String bairro, + String cidade, String uf, String telefone) { + this.numero = numero; + this.rua = rua; + this.complemento = complemento; + this.bairro = bairro; + this.cidade = cidade; + this.telefone = telefone; + this.uf = uf; + + } + + public void setContato(String rua, String numero, String complemento, String bairro, + String cidade, String uf, String telefone) { + this.numero = numero; + this.rua = rua; + this.complemento = complemento; + this.bairro = bairro; + this.cidade = cidade; + this.telefone = telefone; + this.uf = uf; + } + + public String getTelefone() { return telefone;} + public void setTelefone(String telefone) { this.telefone = telefone;} + + public String getNumero() { return numero;} + public void setNumero(String numero) { this.numero = numero;} + + public String getRua() { return rua;} + public void setRua(String rua) { this.rua = rua;} + + public String getBairro() { return bairro;} + public void setBairro(String bairro) { this.bairro = bairro;} + + public String getCidade() { return cidade;} + public void setCidade(String cidade) { this.cidade = cidade;} + + public String getComplemento() { return complemento;} + public void setComplemento(String complemento) { this.complemento = complemento;} + + public String getUf() { + return uf; + } + + public void setUf(String uf) { + this.uf = uf; + } +} diff --git a/example-apps/src/ip/entidade/Livro.java b/example-apps/src/ip/entidade/Livro.java new file mode 100644 index 0000000..7e2ecc7 --- /dev/null +++ b/example-apps/src/ip/entidade/Livro.java @@ -0,0 +1,73 @@ +package dados.entidade; + +import java.io.Serializable; +import java.math.BigDecimal; + + +public class Livro extends Produto implements Serializable{ + + private static final long serialVersionUID = 2476645651903968754L; + private String nomeAutor; + private String editora; + private String anoPublicacao; + Livro prox; + + public Livro(String codigo, String nome, String descricao, BigDecimal valor, String nomeAutor, String editora, String anoPublicacao) { + super(codigo, nome, descricao, valor); + this.nomeAutor = nomeAutor; + this.editora = editora; + this.anoPublicacao = anoPublicacao; + this.prox = null; + } + + + + public Livro(Produto produto) { + super(produto); + this.codigo = produto.getCodigo(); + this.descricao = produto.getDescricao(); + this.nome = produto.getNome(); + this.preco = produto.getPreco(); + this.prox = (Livro) produto.getProx(); + } + + + + public Livro() { + + } + + + + public String getNomeAutor() { + return nomeAutor; + } + + public void setNomeAutor(String nomeAutor) { + this.nomeAutor = nomeAutor; + } + + public String getEditora() { + return editora; + } + + public void setEditora(String editora) { + this.editora = editora; + } + + public String getAnoPublicacao() { + return anoPublicacao; + } + + public void setAnoPublicacao(String anoPublicacao) { + this.anoPublicacao = anoPublicacao; + } + + public Produto getProx() { + return prox; + } + + public void setProx(Produto prox) { + this.prox = (Livro) prox; + } +} \ No newline at end of file diff --git a/example-apps/src/ip/entidade/Midia.java b/example-apps/src/ip/entidade/Midia.java new file mode 100644 index 0000000..0383908 --- /dev/null +++ b/example-apps/src/ip/entidade/Midia.java @@ -0,0 +1,45 @@ +package dados.entidade; + + +public class Midia extends Produto { + private String nomeArtista; + private String distribuidor; + private String anoPublicacao; + private String genero; + + public Midia() { + + } + + public String getNomeArtista() { + return nomeArtista; + } + + public void setNomeArtista(String nomeArtista) { + this.nomeArtista = nomeArtista; + } + + public String getDistribuidor() { + return distribuidor; + } + + public void setDistribuidor(String distribuidor) { + this.distribuidor = distribuidor; + } + + public String getAnoPublicacao() { + return anoPublicacao; + } + + public void setAnoPublicacao(String anoPublicacao) { + this.anoPublicacao = anoPublicacao; + } + + public String getGenero() { + return genero; + } + + public void setGenero(String genero) { + this.genero = genero; + } +} \ No newline at end of file diff --git a/example-apps/src/ip/entidade/Pedido.java b/example-apps/src/ip/entidade/Pedido.java new file mode 100644 index 0000000..4203410 --- /dev/null +++ b/example-apps/src/ip/entidade/Pedido.java @@ -0,0 +1,110 @@ +package dados.entidade; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +import dados.entidade.interfaces.IPedido; + +public class Pedido implements Serializable, IPedido, Comparable { + + /** + * + */ + private static final long serialVersionUID = -3890860726557093419L; + private String codigo; + private Cliente cliente; + private Produto[] produtos; + private int quantidade; + private BigDecimal preco; + private Date data; + private Pedido prox; + + public Pedido(String codigo, Cliente cliente, Produto[] produtos, Date data, int quantidade, BigDecimal preco) { + super(); + this.codigo = codigo; + this.cliente = cliente; + this.produtos = produtos; + this.quantidade = quantidade; + this.preco = preco; + this.data = data; + this.prox = null; + } + + public Pedido(Pedido produto) { + super(); + this.codigo = produto.getCodigo(); + this.cliente = produto.getCliente(); + this.produtos = produto.getProdutos(); + this.quantidade = produto.getQuantidade(); + this.preco = produto.getPreco(); + this.data = produto.getData(); + this.prox = produto.getProx(); + } + + public Pedido() { + + } + + public String getCodigo() { + return codigo; + } + public void setCodigo(String codigo) { + this.codigo = codigo; + } + public Cliente getCliente() { + return cliente; + } + public void setCliente(Cliente cliente) { + this.cliente = cliente; + } + public Produto[] getProdutos() { + return produtos; + } + public void setProdutos(Produto[] produtos) { + this.produtos = produtos; + } + + public int getQuantidade() { + return quantidade; + } + public void setQuantidade(int quantidade) { + this.quantidade = quantidade; + } + public BigDecimal getPreco() { + return preco; + } + public void setPreco(BigDecimal preco) { + this.preco = preco; + } + + //Precisamos do compareTo para quando for ordenar o vector pra gerar o relatório + + public int compareTo(Pedido pedido) { + int resposta = 1; + if(this.data.before(pedido.data)) + resposta = -1; + else if(this.data.equals(pedido.data)) + resposta = 0; + + return resposta; + + } + + public void setData(Date data) { + this.data = data; + } + + public Date getData() { + return data; + } + + public Pedido getProx() { + return prox; + } + + public void setProx(Pedido prox) { + this.prox = prox; + } + +} \ No newline at end of file diff --git a/example-apps/src/ip/entidade/Pessoa.java b/example-apps/src/ip/entidade/Pessoa.java new file mode 100644 index 0000000..cb6ac01 --- /dev/null +++ b/example-apps/src/ip/entidade/Pessoa.java @@ -0,0 +1,64 @@ +package dados.entidade; + +import java.io.Serializable; + + +public abstract class Pessoa implements Serializable { + /** + * + */ + private static final long serialVersionUID = -8228879323512431235L; + protected String nome; + protected String cpf; + protected Contato contato; + protected String senha; + private Pessoa prox; + + public Pessoa(String nome, String cpf, String senha, Contato contato) { + this.nome = nome; + this.cpf = cpf; + this.senha = senha; + this.contato = contato; + this.prox = null; + } + + public Pessoa() { + + } + + public Pessoa(Pessoa pessoa) { + this.nome = pessoa.getNome(); + this.cpf = pessoa.getCpf(); + this.contato = pessoa.getContato(); + this.senha = pessoa.getSenha(); + this.setProx(pessoa.getProx()); + } + + public Pessoa(String cpf, String telefone, String nome, + String logradouro, String numero, String complemento, + String bairro, String cidade, String senha, String uf) { + this.cpf = cpf; + this.nome = nome; + this.senha = senha; + this.contato.setContato(logradouro, numero, complemento, bairro, cidade, uf, telefone); + + // TODO Auto-generated constructor stub + } + + public String getNome() { return nome;} + public void setNome(String nome) { this.nome = nome;} + + public String getCpf() { return cpf;} + public void setCpf(String cpf) { this.cpf = cpf;} + + public Contato getContato() { return contato;} + public void setContato(Contato contato) { this.contato = contato;} + + public String getSenha() { return this.senha;} + public void setSenha(String senha) { this.senha = senha;} + + public Pessoa getProx() { return prox;} + public void setProx(Pessoa prox) { this.prox = prox;} + +} + diff --git a/example-apps/src/ip/entidade/Produto.java b/example-apps/src/ip/entidade/Produto.java new file mode 100644 index 0000000..2fe0083 --- /dev/null +++ b/example-apps/src/ip/entidade/Produto.java @@ -0,0 +1,54 @@ +package dados.entidade; + +import java.io.Serializable; +import java.math.BigDecimal; + +import dados.entidade.interfaces.IProd; + +public class Produto implements IProd, Serializable { + + private static final long serialVersionUID = 2196137339585578884L; + protected String codigo; + protected String nome; + protected String descricao; + protected BigDecimal preco; + protected int quantidade; + Produto prox; + + public Produto(String codigo, String nome, String descricao, BigDecimal preco) { + this.nome = nome; + this.codigo = codigo; + this.descricao = descricao; + this.preco = preco; + this.prox = null; + } + + public Produto(Produto produto) { + this.codigo = produto.getCodigo(); + this.descricao = produto.getDescricao(); + this.nome = produto.getNome(); + this.preco = produto.getPreco(); + this.prox = produto.getProx(); + } + + public Produto() { + + } + + public void setNome(String nome) { this.nome = nome;} + public String getNome() { return nome;} + + public void setCodigo(String codigo) { this.codigo = codigo;} + public String getCodigo() { return codigo;} + + public void setDescricao(String descricao) { this.descricao = descricao;} + public String getDescricao() { return descricao;} + + public void setPreco(BigDecimal preco) { this.preco = preco;} + public BigDecimal getPreco() { return preco;} + + + public Produto getProx() { return prox;} + public void setProx(Produto prox) { this.prox = prox;} + +} \ No newline at end of file diff --git a/example-apps/src/ip/entidade/interfaces/IAdm.java b/example-apps/src/ip/entidade/interfaces/IAdm.java new file mode 100644 index 0000000..3bdd8aa --- /dev/null +++ b/example-apps/src/ip/entidade/interfaces/IAdm.java @@ -0,0 +1,20 @@ +package dados.entidade.interfaces; + +import dados.entidade.Administrador; +import dados.entidade.Contato; +import dados.entidade.Pessoa; + +public interface IAdm { //O int 1 seria para caso um sistema de login identifica-lo como admin + final static int acesso = 1; + + public String getNome(); + public String getCpf(); + public String getSenha(); + public Contato getContato(); + public void setNome(String nome); + public void setCpf(String cpf); + public void setContato(Contato contato); + public void setSenha(String senha); + public void setProx(Pessoa administrador); + public Administrador getProx(); +} diff --git a/example-apps/src/ip/entidade/interfaces/ICliente.java b/example-apps/src/ip/entidade/interfaces/ICliente.java new file mode 100644 index 0000000..cbf2a91 --- /dev/null +++ b/example-apps/src/ip/entidade/interfaces/ICliente.java @@ -0,0 +1,19 @@ +package dados.entidade.interfaces; + +import dados.entidade.Cliente; +import dados.entidade.Contato; + +public interface ICliente { //O int 0 seria para caso um sistema de login identifica-lo como cliente + final static int acesso = 0; + + public String getNome(); + public String getCpf(); + public String getSenha(); + public Contato getContato(); + public void setNome(String nome); + public void setCpf(String cpf); + public void setContato(Contato contato); + public void setSenha(String senha); + public void setProx(Cliente cliente); + public Cliente getProx(); +} \ No newline at end of file diff --git a/example-apps/src/ip/entidade/interfaces/IPedido.java b/example-apps/src/ip/entidade/interfaces/IPedido.java new file mode 100644 index 0000000..f6e33a1 --- /dev/null +++ b/example-apps/src/ip/entidade/interfaces/IPedido.java @@ -0,0 +1,22 @@ +package dados.entidade.interfaces; + +import java.math.BigDecimal; +import java.util.Date; + +import dados.entidade.Cliente; +import dados.entidade.Produto; + +public interface IPedido { + public void setCodigo(String codigo); + public String getCodigo(); + public void setCliente(Cliente cliente); + public Cliente getCliente(); + public void setProdutos(Produto[] produto); + public Produto[] getProdutos(); + public void setData(Date data); + public Date getData(); + public void setQuantidade(int quantidade); + public int getQuantidade(); + public BigDecimal getPreco(); + public void setPreco(BigDecimal preco); +} \ No newline at end of file diff --git a/example-apps/src/ip/entidade/interfaces/IProd.java b/example-apps/src/ip/entidade/interfaces/IProd.java new file mode 100644 index 0000000..abcde7f --- /dev/null +++ b/example-apps/src/ip/entidade/interfaces/IProd.java @@ -0,0 +1,14 @@ +package dados.entidade.interfaces; + +import java.math.BigDecimal; + +public interface IProd { + + public void setNome(String nome); + public void setCodigo(String codigo); + public void setPreco(BigDecimal preco); + public String getNome(); + public String getCodigo(); + public BigDecimal getPreco(); + +} \ No newline at end of file diff --git a/example-apps/src/ip/excel/ExcelCell.java b/example-apps/src/ip/excel/ExcelCell.java new file mode 100644 index 0000000..5c724d4 --- /dev/null +++ b/example-apps/src/ip/excel/ExcelCell.java @@ -0,0 +1,53 @@ +package dados.excel; + +import org.apache.poi.hssf.usermodel.HSSFCell; + +import dados.excel.exception.CellNumberFormatException; +import dados.excel.exception.CellStringFormatException; + +public class ExcelCell { + + + private HSSFCell hssfCell; + + public ExcelCell (HSSFCell hssfCell) { + this.setHSSFCell (hssfCell); + } + + protected void setHSSFCell (HSSFCell hssfCell) { + + if (hssfCell != null) { + this.hssfCell = hssfCell; + } else { + throw new IllegalArgumentException("A celula passada eh nula"); + } + + } + + public double getNumericCellValue () throws CellNumberFormatException { + double ret = 0.0; + + try { + ret = this.hssfCell.getNumericCellValue (); + } catch (Exception e) { + e.printStackTrace(); + throw new CellNumberFormatException(String.format("O conteúdo da célula numérica não pode ser convertida em um numero", this.hssfCell.getColumnIndex())); + } + + return ret; + } + + public String getStringCellValue () throws CellStringFormatException{ + String ret = ""; + + try { + ret = this.hssfCell.getRichStringCellValue().getString(); + } catch (Exception e) { + throw new CellStringFormatException(String.format("O conteúdo da célula numérica não pode ser convertida em String", this.hssfCell.getColumnIndex())); + } + + return ret; + } + +} + diff --git a/example-apps/src/ip/excel/ExcelRow.java b/example-apps/src/ip/excel/ExcelRow.java new file mode 100644 index 0000000..773f7a8 --- /dev/null +++ b/example-apps/src/ip/excel/ExcelRow.java @@ -0,0 +1,41 @@ +package dados.excel; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFRow; + +import dados.excel.exception.NotDefinedCellException; + +public class ExcelRow { + + + private HSSFRow hssfRow; + + public ExcelRow (HSSFRow hssfRow) { + this.setHSSFRow (hssfRow); + } + + protected void setHSSFRow (HSSFRow hssfRow) { + + if (hssfRow != null) { + this.hssfRow = hssfRow; + } else { + throw new IllegalArgumentException("A linha passada eh nula"); + } + + } + + public ExcelCell getCell (int cellnum) throws NotDefinedCellException { + ExcelCell ret = null; + HSSFCell tmp = this.hssfRow.getCell(cellnum); + + if (tmp != null) { + ret = new ExcelCell (tmp); + } else { + throw new NotDefinedCellException(String.format("A celula numero %d nao esta definida", cellnum)); + } + + return ret; + } + +} + diff --git a/example-apps/src/ip/excel/ExcelSheet.java b/example-apps/src/ip/excel/ExcelSheet.java new file mode 100644 index 0000000..24364b9 --- /dev/null +++ b/example-apps/src/ip/excel/ExcelSheet.java @@ -0,0 +1,41 @@ +package dados.excel; + +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; + +import dados.excel.exception.NotDefinedRowException; + +public class ExcelSheet { + + + private HSSFSheet hssfSheet; + + public ExcelSheet (HSSFSheet hssfSheet) { + this.setHSSFSheet (hssfSheet); + } + + protected void setHSSFSheet (HSSFSheet hssfSheet) { + + if (hssfSheet != null) { + this.hssfSheet = hssfSheet; + } else { + throw new IllegalArgumentException("A planilha passada eh nula"); + } + + } + + public ExcelRow getRow (int rownum) throws NotDefinedRowException { + ExcelRow ret = null; + HSSFRow tmp = this.hssfSheet.getRow (rownum); + + if (tmp != null) { + ret = new ExcelRow (tmp); + } else { + throw new NotDefinedRowException(String.format("A linha(numero %d) nao esta definida", rownum)); + } + + return ret; + } + +} + diff --git a/example-apps/src/ip/excel/ExcelWorkbook.java b/example-apps/src/ip/excel/ExcelWorkbook.java new file mode 100644 index 0000000..e54a3f5 --- /dev/null +++ b/example-apps/src/ip/excel/ExcelWorkbook.java @@ -0,0 +1,49 @@ +package dados.excel; + +import java.io.FileInputStream; +import java.io.IOException; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import dados.excel.exception.IOExcelException; +import dados.excel.exception.SheetNotFoundException; + +public class ExcelWorkbook { + + + private HSSFWorkbook hssfWorkbook; + + public ExcelWorkbook ( String nomeDoArquivo ) throws IOExcelException{ + try{ + FileInputStream fis = new FileInputStream(nomeDoArquivo); + HSSFWorkbook tmp = new HSSFWorkbook (fis); + this.setHSSFWorkbook (tmp); + } catch (IOException e) { + throw new IOExcelException(String.format("Erro ao ler um arquivo. verifique se o arquivo(%s) existe", nomeDoArquivo)); + } + } + + protected void setHSSFWorkbook (HSSFWorkbook hssfWorkbook) { + + if (hssfWorkbook != null) { + this.hssfWorkbook = hssfWorkbook; + } else { + throw new IllegalArgumentException("O valor passado eh nulo"); + } + + } + + public ExcelSheet getSheet (String name) throws SheetNotFoundException { + ExcelSheet ret = null; + HSSFSheet tmp = this.hssfWorkbook.getSheet (name); + + if (tmp != null) { + ret = new ExcelSheet (tmp); + } else { + throw new SheetNotFoundException(String.format("A planilha(%s) nao existe", name)); + } + + return ret; + } + +} + diff --git a/example-apps/src/ip/excel/exception/CellNumberFormatException.java b/example-apps/src/ip/excel/exception/CellNumberFormatException.java new file mode 100644 index 0000000..ca1bb26 --- /dev/null +++ b/example-apps/src/ip/excel/exception/CellNumberFormatException.java @@ -0,0 +1,20 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class CellNumberFormatException extends Exception { + + private static final long serialVersionUID = 1548195017411199960L; + + /** + * @param arg0 + */ + public CellNumberFormatException(String arg0) { + super(arg0); + } +} diff --git a/example-apps/src/ip/excel/exception/CellStringFormatException.java b/example-apps/src/ip/excel/exception/CellStringFormatException.java new file mode 100644 index 0000000..4d7b4e4 --- /dev/null +++ b/example-apps/src/ip/excel/exception/CellStringFormatException.java @@ -0,0 +1,20 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class CellStringFormatException extends Exception { + + private static final long serialVersionUID = 1547195057410199260L; + + /** + * @param arg0 + */ + public CellStringFormatException(String arg0) { + super(arg0); + } +} diff --git a/example-apps/src/ip/excel/exception/IOExcelException.java b/example-apps/src/ip/excel/exception/IOExcelException.java new file mode 100644 index 0000000..b49ac92 --- /dev/null +++ b/example-apps/src/ip/excel/exception/IOExcelException.java @@ -0,0 +1,11 @@ +package dados.excel.exception; + +public class IOExcelException extends Exception { + + private static final long serialVersionUID = 3504731970684381191L; + + public IOExcelException(String arg0) { + super(arg0); + } + +} diff --git a/example-apps/src/ip/excel/exception/NotDefinedCellException.java b/example-apps/src/ip/excel/exception/NotDefinedCellException.java new file mode 100644 index 0000000..f72339b --- /dev/null +++ b/example-apps/src/ip/excel/exception/NotDefinedCellException.java @@ -0,0 +1,25 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class NotDefinedCellException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -3064306033181968794L; + + /** + * @param arg0 + */ + public NotDefinedCellException(String arg0) { + super(arg0); + // TODO Auto-generated constructor stub + } + +} diff --git a/example-apps/src/ip/excel/exception/NotDefinedRowException.java b/example-apps/src/ip/excel/exception/NotDefinedRowException.java new file mode 100644 index 0000000..d82aeaf --- /dev/null +++ b/example-apps/src/ip/excel/exception/NotDefinedRowException.java @@ -0,0 +1,24 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class NotDefinedRowException extends Exception { + + + + private static final long serialVersionUID = -8362425327793826851L; + + /** + * @param arg0 + */ + public NotDefinedRowException(String arg0) { + super(arg0); + // TODO Auto-generated constructor stub + } + +} diff --git a/example-apps/src/ip/excel/exception/SheetNotFoundException.java b/example-apps/src/ip/excel/exception/SheetNotFoundException.java new file mode 100644 index 0000000..419c003 --- /dev/null +++ b/example-apps/src/ip/excel/exception/SheetNotFoundException.java @@ -0,0 +1,22 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class SheetNotFoundException extends Exception { + + private static final long serialVersionUID = 4160089517595438877L; + + /** + * @param arg0 + */ + public SheetNotFoundException(String arg0) { + super(arg0); + // TODO Auto-generated constructor stub + } + +} diff --git a/example-apps/src/ip/exception/CellNumberFormatException.java b/example-apps/src/ip/exception/CellNumberFormatException.java new file mode 100644 index 0000000..ca1bb26 --- /dev/null +++ b/example-apps/src/ip/exception/CellNumberFormatException.java @@ -0,0 +1,20 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class CellNumberFormatException extends Exception { + + private static final long serialVersionUID = 1548195017411199960L; + + /** + * @param arg0 + */ + public CellNumberFormatException(String arg0) { + super(arg0); + } +} diff --git a/example-apps/src/ip/exception/CellStringFormatException.java b/example-apps/src/ip/exception/CellStringFormatException.java new file mode 100644 index 0000000..4d7b4e4 --- /dev/null +++ b/example-apps/src/ip/exception/CellStringFormatException.java @@ -0,0 +1,20 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class CellStringFormatException extends Exception { + + private static final long serialVersionUID = 1547195057410199260L; + + /** + * @param arg0 + */ + public CellStringFormatException(String arg0) { + super(arg0); + } +} diff --git a/example-apps/src/ip/exception/IOExcelException.java b/example-apps/src/ip/exception/IOExcelException.java new file mode 100644 index 0000000..b49ac92 --- /dev/null +++ b/example-apps/src/ip/exception/IOExcelException.java @@ -0,0 +1,11 @@ +package dados.excel.exception; + +public class IOExcelException extends Exception { + + private static final long serialVersionUID = 3504731970684381191L; + + public IOExcelException(String arg0) { + super(arg0); + } + +} diff --git a/example-apps/src/ip/exception/NotDefinedCellException.java b/example-apps/src/ip/exception/NotDefinedCellException.java new file mode 100644 index 0000000..f72339b --- /dev/null +++ b/example-apps/src/ip/exception/NotDefinedCellException.java @@ -0,0 +1,25 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class NotDefinedCellException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -3064306033181968794L; + + /** + * @param arg0 + */ + public NotDefinedCellException(String arg0) { + super(arg0); + // TODO Auto-generated constructor stub + } + +} diff --git a/example-apps/src/ip/exception/NotDefinedRowException.java b/example-apps/src/ip/exception/NotDefinedRowException.java new file mode 100644 index 0000000..d82aeaf --- /dev/null +++ b/example-apps/src/ip/exception/NotDefinedRowException.java @@ -0,0 +1,24 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class NotDefinedRowException extends Exception { + + + + private static final long serialVersionUID = -8362425327793826851L; + + /** + * @param arg0 + */ + public NotDefinedRowException(String arg0) { + super(arg0); + // TODO Auto-generated constructor stub + } + +} diff --git a/example-apps/src/ip/exception/SheetNotFoundException.java b/example-apps/src/ip/exception/SheetNotFoundException.java new file mode 100644 index 0000000..419c003 --- /dev/null +++ b/example-apps/src/ip/exception/SheetNotFoundException.java @@ -0,0 +1,22 @@ +/** + * + */ +package dados.excel.exception; + +/** + * @author Geral + * + */ +public class SheetNotFoundException extends Exception { + + private static final long serialVersionUID = 4160089517595438877L; + + /** + * @param arg0 + */ + public SheetNotFoundException(String arg0) { + super(arg0); + // TODO Auto-generated constructor stub + } + +} diff --git a/example-apps/src/ip/exceptions/CampoNaoPreenchidoException.java b/example-apps/src/ip/exceptions/CampoNaoPreenchidoException.java new file mode 100644 index 0000000..9932342 --- /dev/null +++ b/example-apps/src/ip/exceptions/CampoNaoPreenchidoException.java @@ -0,0 +1,14 @@ +package exceptions; + +public class CampoNaoPreenchidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 8545544619586522920L; + + public CampoNaoPreenchidoException() { + super("Algum campo obrigatório não foi preenchido!"); + } + +} diff --git a/example-apps/src/ip/exceptions/CodigoInvalidoException.java b/example-apps/src/ip/exceptions/CodigoInvalidoException.java new file mode 100644 index 0000000..eec0185 --- /dev/null +++ b/example-apps/src/ip/exceptions/CodigoInvalidoException.java @@ -0,0 +1,15 @@ +package exceptions; + + +public class CodigoInvalidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 3687586306981069060L; + + public CodigoInvalidoException(){ + super("Código inválido!"); + } + +} diff --git a/example-apps/src/ip/exceptions/NomeInvalidoException.java b/example-apps/src/ip/exceptions/NomeInvalidoException.java new file mode 100644 index 0000000..13890ef --- /dev/null +++ b/example-apps/src/ip/exceptions/NomeInvalidoException.java @@ -0,0 +1,14 @@ +package exceptions; + +public class NomeInvalidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 365306938689757384L; + + public NomeInvalidoException () { + super ("Nome inválido!"); + } + +} diff --git a/example-apps/src/ip/exceptions/TipoRepositorioInvalidoException.java b/example-apps/src/ip/exceptions/TipoRepositorioInvalidoException.java new file mode 100644 index 0000000..10b1ed9 --- /dev/null +++ b/example-apps/src/ip/exceptions/TipoRepositorioInvalidoException.java @@ -0,0 +1,15 @@ +package exceptions; + + +public class TipoRepositorioInvalidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 8387339307091616306L; + + public TipoRepositorioInvalidoException(){ + super("Tipo de repositório inválido!"); + } + +} diff --git a/example-apps/src/ip/exceptions/administrador/AdmInexistenteException.java b/example-apps/src/ip/exceptions/administrador/AdmInexistenteException.java new file mode 100644 index 0000000..7ea3fbb --- /dev/null +++ b/example-apps/src/ip/exceptions/administrador/AdmInexistenteException.java @@ -0,0 +1,10 @@ +package exceptions.administrador; + +public class AdmInexistenteException extends Exception { + + private static final long serialVersionUID = -7061377520446245525L; + + public AdmInexistenteException() { + super("Administrador não existe."); + } +} diff --git a/example-apps/src/ip/exceptions/administrador/AdmNaoEncontradoException.java b/example-apps/src/ip/exceptions/administrador/AdmNaoEncontradoException.java new file mode 100644 index 0000000..ee73804 --- /dev/null +++ b/example-apps/src/ip/exceptions/administrador/AdmNaoEncontradoException.java @@ -0,0 +1,14 @@ +package exceptions.administrador; + +public class AdmNaoEncontradoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 518772763727978768L; + + public AdmNaoEncontradoException() { + super("Administrador não encontrado!"); + } + +} diff --git a/example-apps/src/ip/exceptions/administrador/BairroInvalidoException.java b/example-apps/src/ip/exceptions/administrador/BairroInvalidoException.java new file mode 100644 index 0000000..d9cfdc3 --- /dev/null +++ b/example-apps/src/ip/exceptions/administrador/BairroInvalidoException.java @@ -0,0 +1,11 @@ +package exceptions.administrador; + + +public class BairroInvalidoException extends Exception { + + private static final long serialVersionUID = 8493332690717566026L; + + public BairroInvalidoException(){ + super("Bairro inválido"); + } +} diff --git a/example-apps/src/ip/exceptions/administrador/CidadeInvalidaException.java b/example-apps/src/ip/exceptions/administrador/CidadeInvalidaException.java new file mode 100644 index 0000000..f909c24 --- /dev/null +++ b/example-apps/src/ip/exceptions/administrador/CidadeInvalidaException.java @@ -0,0 +1,12 @@ +package exceptions.administrador; + +public class CidadeInvalidaException extends Exception { + /** + * + */ + private static final long serialVersionUID = 2501972420789733441L; + + public CidadeInvalidaException(){ + super ("Cidade inválida"); + } +} diff --git a/example-apps/src/ip/exceptions/administrador/CpfInvalidoException.java b/example-apps/src/ip/exceptions/administrador/CpfInvalidoException.java new file mode 100644 index 0000000..cfe75b6 --- /dev/null +++ b/example-apps/src/ip/exceptions/administrador/CpfInvalidoException.java @@ -0,0 +1,11 @@ +package exceptions.administrador; + +public class CpfInvalidoException extends Exception { + + private static final long serialVersionUID = 8430532418525952253L; + + public CpfInvalidoException() { + super("CPF inválido!"); + } + +} diff --git a/example-apps/src/ip/exceptions/administrador/CpfJaExisteException.java b/example-apps/src/ip/exceptions/administrador/CpfJaExisteException.java new file mode 100644 index 0000000..d99e8ee --- /dev/null +++ b/example-apps/src/ip/exceptions/administrador/CpfJaExisteException.java @@ -0,0 +1,12 @@ +package exceptions.administrador; + +public class CpfJaExisteException extends Exception { +/** + * + */ + private static final long serialVersionUID = -4048530757554713908L; + +public CpfJaExisteException(){ + super("Esse cpf já foi cadastrado!"); +} +} diff --git a/example-apps/src/ip/exceptions/administrador/TelefoneInvalidoException.java b/example-apps/src/ip/exceptions/administrador/TelefoneInvalidoException.java new file mode 100644 index 0000000..5bfdeed --- /dev/null +++ b/example-apps/src/ip/exceptions/administrador/TelefoneInvalidoException.java @@ -0,0 +1,14 @@ +package exceptions.administrador; + +public class TelefoneInvalidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -763031994437441979L; + + public TelefoneInvalidoException(){ + super("Telefone Inválido!"); + } + +} diff --git a/example-apps/src/ip/exceptions/administrador/TelefoneJaExisteException.java b/example-apps/src/ip/exceptions/administrador/TelefoneJaExisteException.java new file mode 100644 index 0000000..c09b94e --- /dev/null +++ b/example-apps/src/ip/exceptions/administrador/TelefoneJaExisteException.java @@ -0,0 +1,14 @@ +package exceptions.administrador; + +public class TelefoneJaExisteException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -8166024353844041522L; + + public TelefoneJaExisteException(){ + super("Telefone já cadastrado!"); + } + +} diff --git a/example-apps/src/ip/exceptions/cliente/BairroInvalidoException.java b/example-apps/src/ip/exceptions/cliente/BairroInvalidoException.java new file mode 100644 index 0000000..026e997 --- /dev/null +++ b/example-apps/src/ip/exceptions/cliente/BairroInvalidoException.java @@ -0,0 +1,11 @@ +package exceptions.cliente; + + +public class BairroInvalidoException extends Exception { + + private static final long serialVersionUID = 8493332690717566026L; + + public BairroInvalidoException(){ + super("Bairro inválido"); + } +} diff --git a/example-apps/src/ip/exceptions/cliente/CidadeInvalidaException.java b/example-apps/src/ip/exceptions/cliente/CidadeInvalidaException.java new file mode 100644 index 0000000..dc1e867 --- /dev/null +++ b/example-apps/src/ip/exceptions/cliente/CidadeInvalidaException.java @@ -0,0 +1,12 @@ +package exceptions.cliente; + +public class CidadeInvalidaException extends Exception { + /** + * + */ + private static final long serialVersionUID = 2501972420789733441L; + + public CidadeInvalidaException(){ + super ("Cidade inválida"); + } +} diff --git a/example-apps/src/ip/exceptions/cliente/ClienteInexistenteException.java b/example-apps/src/ip/exceptions/cliente/ClienteInexistenteException.java new file mode 100644 index 0000000..17a06e8 --- /dev/null +++ b/example-apps/src/ip/exceptions/cliente/ClienteInexistenteException.java @@ -0,0 +1,10 @@ +package exceptions.cliente; + +public class ClienteInexistenteException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 2420102669137192557L; + +} diff --git a/example-apps/src/ip/exceptions/cliente/ClienteNaoEncontradoException.java b/example-apps/src/ip/exceptions/cliente/ClienteNaoEncontradoException.java new file mode 100644 index 0000000..c4f1329 --- /dev/null +++ b/example-apps/src/ip/exceptions/cliente/ClienteNaoEncontradoException.java @@ -0,0 +1,14 @@ +package exceptions.cliente; + +public class ClienteNaoEncontradoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 518772763727978768L; + + public ClienteNaoEncontradoException() { + super("Cliente não encontrado!"); + } + +} diff --git a/example-apps/src/ip/exceptions/cliente/CpfInvalidoException.java b/example-apps/src/ip/exceptions/cliente/CpfInvalidoException.java new file mode 100644 index 0000000..7ca493d --- /dev/null +++ b/example-apps/src/ip/exceptions/cliente/CpfInvalidoException.java @@ -0,0 +1,11 @@ +package exceptions.cliente; + +public class CpfInvalidoException extends Exception { + + private static final long serialVersionUID = 8430532418525952253L; + + public CpfInvalidoException() { + super("CPF inválido!"); + } + +} diff --git a/example-apps/src/ip/exceptions/cliente/CpfJaExisteException.java b/example-apps/src/ip/exceptions/cliente/CpfJaExisteException.java new file mode 100644 index 0000000..537083f --- /dev/null +++ b/example-apps/src/ip/exceptions/cliente/CpfJaExisteException.java @@ -0,0 +1,12 @@ +package exceptions.cliente; + +public class CpfJaExisteException extends Exception { +/** + * + */ + private static final long serialVersionUID = -4048530757554713908L; + +public CpfJaExisteException(){ + super("Esse cpf já foi cadastrado!"); +} +} diff --git a/example-apps/src/ip/exceptions/cliente/EstadoInvalidoException.java b/example-apps/src/ip/exceptions/cliente/EstadoInvalidoException.java new file mode 100644 index 0000000..08e525c --- /dev/null +++ b/example-apps/src/ip/exceptions/cliente/EstadoInvalidoException.java @@ -0,0 +1,12 @@ +package exceptions.cliente; + +public class EstadoInvalidoException extends Exception { + /** + * + */ + private static final long serialVersionUID = 2501972420789733441L; + + public EstadoInvalidoException(){ + super ("Estado inválido"); + } +} diff --git a/example-apps/src/ip/exceptions/cliente/TelefoneInvalidoException.java b/example-apps/src/ip/exceptions/cliente/TelefoneInvalidoException.java new file mode 100644 index 0000000..71157bf --- /dev/null +++ b/example-apps/src/ip/exceptions/cliente/TelefoneInvalidoException.java @@ -0,0 +1,14 @@ +package exceptions.cliente; + +public class TelefoneInvalidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -763031994437441979L; + + public TelefoneInvalidoException(){ + super("Telefone Inválido!"); + } + +} diff --git a/example-apps/src/ip/exceptions/cliente/TelefoneJaExisteException.java b/example-apps/src/ip/exceptions/cliente/TelefoneJaExisteException.java new file mode 100644 index 0000000..a62a8de --- /dev/null +++ b/example-apps/src/ip/exceptions/cliente/TelefoneJaExisteException.java @@ -0,0 +1,14 @@ +package exceptions.cliente; + +public class TelefoneJaExisteException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -8166024353844041522L; + + public TelefoneJaExisteException(){ + super("Telefone já cadastrado!"); + } + +} diff --git a/example-apps/src/ip/exceptions/pedido/DataInvalidaException.java b/example-apps/src/ip/exceptions/pedido/DataInvalidaException.java new file mode 100644 index 0000000..7448dd6 --- /dev/null +++ b/example-apps/src/ip/exceptions/pedido/DataInvalidaException.java @@ -0,0 +1,15 @@ +package exceptions.pedido; + +public class DataInvalidaException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = -7435975292867826985L; + + public DataInvalidaException () { + super ("Data Inválida!"); + } + +} diff --git a/example-apps/src/ip/exceptions/pedido/DatasInvalidasException.java b/example-apps/src/ip/exceptions/pedido/DatasInvalidasException.java new file mode 100644 index 0000000..c3eb25d --- /dev/null +++ b/example-apps/src/ip/exceptions/pedido/DatasInvalidasException.java @@ -0,0 +1,14 @@ +package exceptions.pedido; + +public class DatasInvalidasException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = 6711158218260873755L; + + public DatasInvalidasException(){ + super("Datas inválidas!"); + } +} diff --git a/example-apps/src/ip/exceptions/pedido/PedidoInvalidoException.java b/example-apps/src/ip/exceptions/pedido/PedidoInvalidoException.java new file mode 100644 index 0000000..d3df6bf --- /dev/null +++ b/example-apps/src/ip/exceptions/pedido/PedidoInvalidoException.java @@ -0,0 +1,15 @@ +package exceptions.pedido; + +public class PedidoInvalidoException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = -7413553396183110229L; + + public PedidoInvalidoException() { + super("Pedido inválido!"); + } + +} diff --git a/example-apps/src/ip/exceptions/pedido/PedidoNaoEncontradoException.java b/example-apps/src/ip/exceptions/pedido/PedidoNaoEncontradoException.java new file mode 100644 index 0000000..ed4de68 --- /dev/null +++ b/example-apps/src/ip/exceptions/pedido/PedidoNaoEncontradoException.java @@ -0,0 +1,14 @@ +package exceptions.pedido; + +public class PedidoNaoEncontradoException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = 6740991126763866832L; + + public PedidoNaoEncontradoException () { + super ("Pedido não encontrado!"); + } +} diff --git a/example-apps/src/ip/exceptions/pedido/QuantidadeProdutosInvalidaException.java b/example-apps/src/ip/exceptions/pedido/QuantidadeProdutosInvalidaException.java new file mode 100644 index 0000000..eb3baa9 --- /dev/null +++ b/example-apps/src/ip/exceptions/pedido/QuantidadeProdutosInvalidaException.java @@ -0,0 +1,14 @@ +package exceptions.pedido; + +public class QuantidadeProdutosInvalidaException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 5512156152622871287L; + + public QuantidadeProdutosInvalidaException(){ + super("Quantidade de produtos inválida!"); + } + +} diff --git a/example-apps/src/ip/exceptions/produto/AnoInvalidoException.java b/example-apps/src/ip/exceptions/produto/AnoInvalidoException.java new file mode 100644 index 0000000..e1a7638 --- /dev/null +++ b/example-apps/src/ip/exceptions/produto/AnoInvalidoException.java @@ -0,0 +1,12 @@ +package exceptions.produto; + +public class AnoInvalidoException extends Exception { + /** + * + */ + private static final long serialVersionUID = -6899488026114280437L; + + public AnoInvalidoException() { + super("Ano inválido"); + } +} \ No newline at end of file diff --git a/example-apps/src/ip/exceptions/produto/ProdutoNaoEncontradoException.java b/example-apps/src/ip/exceptions/produto/ProdutoNaoEncontradoException.java new file mode 100644 index 0000000..2163296 --- /dev/null +++ b/example-apps/src/ip/exceptions/produto/ProdutoNaoEncontradoException.java @@ -0,0 +1,14 @@ +package exceptions.produto; + +public class ProdutoNaoEncontradoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -5502802968119199034L; + + public ProdutoNaoEncontradoException () { + super ("Produto não encontrado!"); + } + +} diff --git a/example-apps/src/ip/exceptions/produto/ValorInvalidoException.java b/example-apps/src/ip/exceptions/produto/ValorInvalidoException.java new file mode 100644 index 0000000..bea44a7 --- /dev/null +++ b/example-apps/src/ip/exceptions/produto/ValorInvalidoException.java @@ -0,0 +1,14 @@ +package exceptions.produto; + +public class ValorInvalidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -5100321524233328233L; + + public ValorInvalidoException(){ + super("Valor inválido!"); + } + +} diff --git a/example-apps/src/ip/fachada/Fachada.java b/example-apps/src/ip/fachada/Fachada.java new file mode 100644 index 0000000..2337162 --- /dev/null +++ b/example-apps/src/ip/fachada/Fachada.java @@ -0,0 +1,766 @@ +package fachada; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.Calendar; +import java.util.Date; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import negocio.ControladorAdm; +import negocio.ControladorCliente; +import negocio.ControladorPedido; +import negocio.ControladorProduto; +import relatorios.RelatorioAdm; +import relatorios.RelatorioCliente; +import relatorios.RelatorioProduto; +import dados.IteratorClasse; +import dados.entidade.Administrador; +import dados.entidade.Cliente; +import dados.entidade.Livro; +import dados.entidade.Pedido; +import dados.entidade.Produto; +import dados.excel.ExcelRow; +import dados.excel.ExcelSheet; +import dados.excel.ExcelWorkbook; +import dados.excel.exception.CellNumberFormatException; +import dados.excel.exception.CellStringFormatException; +import dados.excel.exception.IOExcelException; +import dados.excel.exception.NotDefinedCellException; +import dados.excel.exception.NotDefinedRowException; +import dados.excel.exception.SheetNotFoundException; +import dados.repositorio.RepAdmArquivo; +import dados.repositorio.RepAdmArray; +import dados.repositorio.RepAdmLista; +import dados.repositorio.RepClienteArquivo; +import dados.repositorio.RepClienteArray; +import dados.repositorio.RepClienteLista; +import dados.repositorio.RepPedidoArquivo; +import dados.repositorio.RepPedidoArray; +import dados.repositorio.RepPedidoLista; +import dados.repositorio.RepProdutoArquivo; +import dados.repositorio.RepProdutoArray; +import dados.repositorio.RepProdutoLista; +import exceptions.CampoNaoPreenchidoException; +import exceptions.CodigoInvalidoException; +import exceptions.NomeInvalidoException; +import exceptions.TipoRepositorioInvalidoException; +import exceptions.administrador.AdmNaoEncontradoException; +import exceptions.cliente.BairroInvalidoException; +import exceptions.cliente.CidadeInvalidaException; +import exceptions.cliente.ClienteNaoEncontradoException; +import exceptions.cliente.CpfInvalidoException; +import exceptions.cliente.CpfJaExisteException; +import exceptions.cliente.EstadoInvalidoException; +import exceptions.cliente.TelefoneInvalidoException; +import exceptions.cliente.TelefoneJaExisteException; +import exceptions.pedido.DataInvalidaException; +import exceptions.pedido.DatasInvalidasException; +import exceptions.pedido.PedidoInvalidoException; +import exceptions.pedido.PedidoNaoEncontradoException; +import exceptions.pedido.QuantidadeProdutosInvalidaException; +import exceptions.produto.AnoInvalidoException; +import exceptions.produto.ProdutoNaoEncontradoException; +import exceptions.produto.ValorInvalidoException; + +public class Fachada { + + private ControladorCliente controladorCliente; + private ControladorPedido controladorPedido; + private ControladorProduto controladorProduto; + private ControladorAdm controladorAdm; + private String tipoRepositorio; + + @SuppressWarnings({ "resource" }) + public Fachada() throws IOException, TipoRepositorioInvalidoException, + IOExcelException, SheetNotFoundException, CellStringFormatException, CellNumberFormatException, PedidoNaoEncontradoException, exceptions.administrador.CpfJaExisteException, exceptions.administrador.CpfInvalidoException, exceptions.administrador.TelefoneInvalidoException, exceptions.administrador.TelefoneJaExisteException, DatasInvalidasException, AnoInvalidoException { + File arquivo = new File("config.txt"); + if (arquivo.exists()) { + BufferedReader leitor = new BufferedReader(new FileReader("config.txt")); + this.tipoRepositorio = leitor.readLine(); + if (this.tipoRepositorio != null) { + if (this.tipoRepositorio.equalsIgnoreCase("array")) { + this.controladorCliente = new ControladorCliente(new RepClienteArray()); + this.controladorPedido = new ControladorPedido(new RepPedidoArray()); + this.controladorProduto = new ControladorProduto(new RepProdutoArray()); + this.controladorAdm = new ControladorAdm(new RepAdmArray()); + } else if (this.tipoRepositorio.equalsIgnoreCase("lista")) { + this.controladorCliente = new ControladorCliente(new RepClienteLista()); + this.controladorPedido = new ControladorPedido(new RepPedidoLista()); + this.controladorProduto = new ControladorProduto(new RepProdutoLista()); + this.controladorAdm = new ControladorAdm(new RepAdmLista()); + } else if (this.tipoRepositorio.equalsIgnoreCase("arquivo")) { + this.controladorCliente = new ControladorCliente(new RepClienteArquivo()); + this.controladorPedido = new ControladorPedido(new RepPedidoArquivo()); + this.controladorProduto = new ControladorProduto(new RepProdutoArquivo()); + this.controladorAdm = new ControladorAdm(new RepAdmArquivo()); + } else { + throw new TipoRepositorioInvalidoException(); + } + } else { + throw new TipoRepositorioInvalidoException(); + } + } else { + throw new TipoRepositorioInvalidoException(); + } + + this.lerAdministradores(); + this.lerClientes(); + this.lerProdutos(); + this.lerPedidos(); + } + + + public void lerAdministradores() throws IOExcelException, SheetNotFoundException, + CellStringFormatException, exceptions.administrador.CpfJaExisteException, exceptions.administrador.CpfInvalidoException, exceptions.administrador.TelefoneInvalidoException, exceptions.administrador.TelefoneJaExisteException { + ExcelWorkbook arquivo = new ExcelWorkbook("workbookAdm.xls"); + ExcelSheet planilha = arquivo.getSheet("Administradores"); + boolean continua = true; + + for(int i = 1; continua; i++) { + String numeroStr = ""; + + try { + ExcelRow linha = planilha.getRow(i); + String nome = linha.getCell(0).getStringCellValue(); + String cpf = linha.getCell(1).getStringCellValue(); + String logradouro = linha.getCell(2).getStringCellValue(); + int numero = 0; + try { + numero = (int) linha.getCell(3).getNumericCellValue(); + } catch (CellNumberFormatException e) { + numeroStr = linha.getCell(3).getStringCellValue(); + } + + String complemento = ""; + try { + complemento = linha.getCell(4).getStringCellValue(); + } catch (NotDefinedCellException ex) { + } + + String bairro = linha.getCell(5).getStringCellValue(); + String cidade = linha.getCell(6).getStringCellValue(); + String telefone = linha.getCell(7).getStringCellValue(); + String senha = linha.getCell(8).getStringCellValue(); + String uf = linha.getCell(9).getStringCellValue(); + + if (numero != 0) { + numeroStr = "" + numero; + } else if (numeroStr.equals("")) { + numeroStr = null; + } + + try { + + this.adicionarAdministrador(cpf, telefone, nome, logradouro, numeroStr, complemento, bairro, cidade, senha, uf); + + } catch (BairroInvalidoException e) { + } catch (CidadeInvalidaException e) { + } catch (TelefoneJaExisteException e) { + } catch (CampoNaoPreenchidoException e) { + } catch (CpfInvalidoException e) { + } catch (TelefoneInvalidoException e) { + } catch (CpfJaExisteException e) { + } catch (NomeInvalidoException e) { + } catch (EstadoInvalidoException e) { + } + + } catch (NotDefinedRowException ex) { + continua = false; + } catch (NotDefinedCellException ex) { + continua = false; + } + } + } + + public void lerClientes() throws IOExcelException, SheetNotFoundException, + CellStringFormatException { + + ExcelWorkbook arquivo = new ExcelWorkbook("workbookCli.xls"); + ExcelSheet planilha = arquivo.getSheet("Clientes"); + boolean continua = true; + + for (int i = 1; continua; i++) { + String numeroStr = ""; + + try { + ExcelRow linha = planilha.getRow(i); + String nome = linha.getCell(0).getStringCellValue(); + String cpf = linha.getCell(1).getStringCellValue(); + String logradouro = linha.getCell(2).getStringCellValue(); + int numero = 0; + try { + numero = (int) linha.getCell(3).getNumericCellValue(); + } catch (CellNumberFormatException e) { + numeroStr = linha.getCell(3).getStringCellValue(); + } + + String complemento = ""; + try { + complemento = linha.getCell(4).getStringCellValue(); + } catch (NotDefinedCellException ex) { + } + + String bairro = linha.getCell(5).getStringCellValue(); + String cidade = linha.getCell(6).getStringCellValue(); + String telefone = linha.getCell(7).getStringCellValue(); + String senha = linha.getCell(8).getStringCellValue(); + String uf = linha.getCell(9).getStringCellValue(); + + if (numero != 0) { + numeroStr = "" + numero; + } else if (numeroStr.equals("")) { + numeroStr = null; + } + + try { + + this.adicionarCliente(cpf, telefone, nome, logradouro, numeroStr, complemento, bairro, cidade, senha, uf); + + } catch (BairroInvalidoException e) { + } catch (CidadeInvalidaException e) { + } catch (TelefoneJaExisteException e) { + } catch (CampoNaoPreenchidoException e) { + } catch (CpfInvalidoException e) { + } catch (TelefoneInvalidoException e) { + } catch (CpfJaExisteException e) { + } catch (NomeInvalidoException e) { + } + + } catch (NotDefinedRowException ex) { + continua = false; + } catch (NotDefinedCellException ex) { + continua = false; + } + } + } + + + public void lerProdutos() throws IOExcelException, SheetNotFoundException, + CellStringFormatException, AnoInvalidoException { + ExcelWorkbook arquivo = new ExcelWorkbook("workbookPro.xls"); + ExcelSheet produtos = arquivo.getSheet("Produtos"); + boolean continua = true; + for (int i = 1; continua; i++) { + try { + ExcelRow linha = produtos.getRow(i); + String codigoProduto = ""; + + try { + int codigo = (int) linha.getCell(0).getNumericCellValue(); + codigoProduto = "" + codigo; + } catch (CellNumberFormatException e) { + codigoProduto = linha.getCell(0).getStringCellValue(); + } + + String nomeProduto = linha.getCell(1).getStringCellValue(); + String descricaoProduto = ""; + try { + descricaoProduto = linha.getCell(2).getStringCellValue(); + } catch (NotDefinedCellException e) { + } + + boolean invalido = false; + String valorFormatado = ""; + try { + double valor = (double) linha.getCell(3).getNumericCellValue(); + valorFormatado = "" + valor; + } catch (CellNumberFormatException e) { + + String valor = linha.getCell(3).getStringCellValue(); + + for (int j = 0; j < valor.length(); j++) { + if (valor.charAt(j) == ',') { + String parteUm = valor.substring(0, j); + String parteDois = valor.substring(j + 1); + valor = parteUm + "." + parteDois; + } + if (valor.charAt(j) != ',' && valor.charAt(j) != '.' + && !(("" + valor.charAt(j)).matches("\\d{1}"))) { + invalido = true; + } + } + valorFormatado = valor; + } + + + String nomeAutor = null; + try { + nomeAutor = linha.getCell(4).getStringCellValue(); + } catch (NotDefinedCellException e){ + + } + String editora = null; + try { + editora = linha.getCell(5).getStringCellValue(); + } catch (NotDefinedCellException e) { + + } + String anoPublicacao = null; + try { + anoPublicacao = linha.getCell(6).getStringCellValue(); + } catch (NotDefinedCellException e) { + + } + + if (!invalido) { + try { + this.adicionarProduto(codigoProduto, nomeProduto, descricaoProduto, valorFormatado, nomeAutor, editora, anoPublicacao); + } catch (ValorInvalidoException e) { + } catch (CampoNaoPreenchidoException e) { + } catch (CodigoInvalidoException e) { + } catch (NomeInvalidoException e) { + } + } + } catch (NotDefinedRowException e) { + continua = false; + } catch (NotDefinedCellException e) { + continua = false; + } + } + + +} + + +public void lerPedidos() throws IOExcelException, SheetNotFoundException, +CellStringFormatException, CellNumberFormatException, PedidoNaoEncontradoException, DatasInvalidasException { + ExcelWorkbook arquivo = new ExcelWorkbook("workbookPed.xls"); + ExcelSheet pedidos = arquivo.getSheet("Pedidos"); + boolean continua = true; + for (int i = 1; continua; i++) { + try { + ExcelRow linha = pedidos.getRow(i); + + String codigoPedido = ""; + try { + int codigo = (int) linha.getCell(0).getNumericCellValue(); + codigoPedido = "" + codigo; + } catch (CellNumberFormatException e) { + codigoPedido = linha.getCell(0).getStringCellValue(); + } + + String telefoneCliente = linha.getCell(1).getStringCellValue(); + + boolean campoValido = true; + boolean clienteEncontrado = true; + Cliente cliente = null; + try { + cliente = this.controladorCliente.buscaTelefone(telefoneCliente); + } catch (ClienteNaoEncontradoException e) { + clienteEncontrado = false; + } catch (TelefoneInvalidoException e) { + campoValido = false; + } + + String quantidade; + int quantidadeInt = 0; + try { + quantidadeInt = (int) linha.getCell(2).getNumericCellValue(); + } catch (CellNumberFormatException e) { + } + + if (quantidadeInt == 0) { + quantidade = null; + } else { + quantidade = "" + quantidadeInt; + } + + quantidade = "" + quantidadeInt; + String[] produtos; + try { + String produtosPedido = linha.getCell(3).getStringCellValue(); + produtos = produtosPedido.split("-"); + } catch (CellStringFormatException e) { + produtos = new String[1]; + produtos[0] = "" + (int) linha.getCell(3).getNumericCellValue(); + } + String dataStr = linha.getCell(4).getStringCellValue(); + + dataStr = dataStr.replaceAll("\\(", ""); + dataStr = dataStr.replaceAll("\\)", ""); + + DateFormat df = DateFormat.getDateInstance(); + Date data = null; + + try { + data = df.parse(dataStr); + } catch (ParseException e1) { + campoValido = false; + } + if (!(this.verificaData(dataStr))) { + campoValido = false; + } + IteratorClasse iterator = null; + + iterator = this.controladorPedido.getListaPedidos(null, null); + + while (iterator.hasNext()) { + Pedido auxiliar = iterator.next(); + if (codigoPedido.equals(auxiliar.getCodigo())) { + campoValido = false; + } + } + + if (campoValido && clienteEncontrado) { + String cpf = cliente.getCpf(); + String telefone = cliente.getContato().getTelefone(); + String nome = cliente.getNome(); + String logradouro = cliente.getContato().getRua(); + String numero = cliente.getContato().getNumero(); + String complemento = ""; + if (!(cliente.getContato().getComplemento().equals("") || cliente.getContato().getComplemento() == null)) { + complemento = cliente.getContato().getComplemento(); + } + String bairro = cliente.getContato().getBairro(); + String cidade = cliente.getContato().getCidade(); + + boolean invalido = false; + Produto[] arrayProdutos = new Produto[produtos.length]; + for (int j = 0; j < produtos.length; j++) { + try { + arrayProdutos[j] = this.visualizarCadastroProduto(produtos[j]); + } catch (ProdutoNaoEncontradoException ex) { + invalido = true; + } + } + + if (!invalido) { + try { + this.controladorPedido.adicionar(cpf, telefone, nome, logradouro, numero, complemento, bairro, cidade, codigoPedido, cidade, arrayProdutos, data, quantidade, cidade); + } catch (QuantidadeProdutosInvalidaException e) { + } catch (ProdutoNaoEncontradoException e) { + } + } + } + } catch (NotDefinedRowException e) { + continua = false; + } catch (NotDefinedCellException e) { + continua = false; + } + } + + } + + public void adicionarAdministrador(String cpf, String telefone, String nome, String logradouro, String numero, String complemento, + String bairro, String cidade, String senha, String uf) throws CpfInvalidoException, TelefoneInvalidoException, CampoNaoPreenchidoException, + CpfJaExisteException, TelefoneJaExisteException, NomeInvalidoException, BairroInvalidoException, CidadeInvalidaException, EstadoInvalidoException, exceptions.administrador.CpfJaExisteException, exceptions.administrador.CpfInvalidoException, exceptions.administrador.TelefoneInvalidoException, exceptions.administrador.TelefoneJaExisteException { + + if (!this.apenasLetras(nome)) { + throw new NomeInvalidoException(); + } else if (!this.apenasLetras(bairro)) { + throw new BairroInvalidoException(); + } else if (!this.apenasLetras(cidade)) { + throw new CidadeInvalidaException(); + } + + this.controladorAdm.adicionar(cpf, telefone, nome, logradouro, numero, complemento, bairro, cidade, senha, uf); + + } + + public void adicionarCliente(String cpf, String telefone, String nome, String logradouro, String numero, String complemento, + String bairro, String cidade, String senha, String uf) throws CpfInvalidoException, + TelefoneInvalidoException, CampoNaoPreenchidoException, CpfJaExisteException, + TelefoneJaExisteException, NomeInvalidoException, BairroInvalidoException, + CidadeInvalidaException { + + if (!this.apenasLetras(nome)) { + throw new NomeInvalidoException(); + } else if (!this.apenasLetras(bairro)) { + throw new BairroInvalidoException(); + } else if (!this.apenasLetras(cidade)) { + throw new CidadeInvalidaException(); + } + + this.controladorCliente.adicionar(cpf, telefone, nome, logradouro, numero, complemento, bairro, cidade, senha, uf); + + } + + public void adicionarProduto(String codigo, String nome, String descricao, String valor, String nomeAutor, String editora, String anoPublicacao) throws ValorInvalidoException, CampoNaoPreenchidoException, + CodigoInvalidoException, NomeInvalidoException, AnoInvalidoException { + if (this.apenasLetras(nome)) { + this.controladorProduto.adicionar(codigo, nome, descricao, valor, nomeAutor, editora, anoPublicacao); + } else { + throw new NomeInvalidoException(); + } + } + + public void adicionarPedido(String cpf, String[] codigosProdutos) throws CpfInvalidoException, ClienteNaoEncontradoException, + ProdutoNaoEncontradoException, PedidoInvalidoException, PedidoNaoEncontradoException, DatasInvalidasException { + + boolean produtosCadastrados = true; + + Cliente auxiliar = null; + Produto[] produtos = new Livro[codigosProdutos.length]; + + auxiliar = this.controladorCliente.buscaCpf(cpf); + + for (int i = 0; i < codigosProdutos.length && produtosCadastrados; i++) { + produtos[i] = this.controladorProduto.buscaCodigo(codigosProdutos[i]); + } + + + String telefone = auxiliar.getContato().getTelefone(); + String nome = auxiliar.getNome(); + String logradouro = auxiliar.getContato().getRua(); + String numero = auxiliar.getContato().getNumero(); + String complemento = ""; + if (auxiliar.getContato().getComplemento() != null && !auxiliar.getContato().equals("")) { + complemento = auxiliar.getContato().getComplemento(); + } + String bairro = auxiliar.getContato().getBairro(); + String cidade = auxiliar.getContato().getCidade(); + String senha = auxiliar.getSenha(); + String uf = auxiliar.getContato().getUf(); + Calendar calendario = Calendar.getInstance(); + Date data = calendario.getTime(); + String quantidadeProdutosStr = "" + produtos.length; + + IteratorClasse iterator = null; + + iterator = this.controladorPedido.getListaPedidos(null, null); + + String codigoUltimo = "0"; + while (iterator.hasNext()) { + codigoUltimo = iterator.next().getCodigo(); + } + + String codigo = "" + (Integer.parseInt(codigoUltimo) + 1); + try { + this.controladorPedido.adicionar(cpf, telefone, nome, logradouro, numero, complemento, bairro, cidade, + uf, codigo, produtos, data, quantidadeProdutosStr, senha); + } catch (QuantidadeProdutosInvalidaException ex) { + } + } + + public void removerAdm(String cpf) throws CpfInvalidoException { + try { + this.controladorAdm.remover(cpf); + } catch (exceptions.administrador.CpfInvalidoException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void removerCliente(String cpf) throws CpfInvalidoException { + try { + this.controladorCliente.remover(cpf); + } catch (ClienteNaoEncontradoException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void cancelarPedido(String codigo) throws PedidoNaoEncontradoException { + this.controladorPedido.remover(codigo); + } + + public void removerProduto(String codigo) throws ProdutoNaoEncontradoException { + this.controladorProduto.remover(codigo); + } + + public IteratorClasse visualizarAdministradores(String nome) throws AdmNaoEncontradoException { + IteratorClasse iterator = this.controladorAdm.buscaNome(nome); + return iterator; + } + + public IteratorClasse visualizarClientes(String nome) throws ClienteNaoEncontradoException { + IteratorClasse iterator = this.controladorCliente.buscaNome(nome); + return iterator; + } + + public Administrador visualizarCadastroAdmCpf(String cpf) throws AdmNaoEncontradoException, CpfInvalidoException { + Administrador administrador = null; + try { + administrador = this.controladorAdm.buscaCpf(cpf); + } catch (exceptions.administrador.CpfInvalidoException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return administrador; + } + + public Cliente visualizarCadastroClienteTelefone(String telefone) throws + ClienteNaoEncontradoException, TelefoneInvalidoException { + Cliente cliente = this.controladorCliente.buscaTelefone(telefone); + return cliente; + } + + public Cliente visualizarCadastroClienteCpf(String cpf) throws + ClienteNaoEncontradoException, CpfInvalidoException { + Cliente cliente = this.controladorCliente.buscaCpf(cpf); + return cliente; + } + + public IteratorClasse visualizarProdutos(String nome) throws + ProdutoNaoEncontradoException { + IteratorClasse iterator = this.controladorProduto.buscaNome(nome); + return iterator; + } + + public IteratorClasse buscarProdutoParteCodigo(String codigo) throws + ProdutoNaoEncontradoException { + IteratorClasse iterator = this.controladorProduto.buscaParteCodigo(codigo); + return iterator; + } + + public Produto visualizarCadastroProduto(String codigo) throws ProdutoNaoEncontradoException { + Produto produto = this.controladorProduto.buscaCodigo(codigo); + return produto; + } + + + public IteratorClasse visualizarPedidos(String dataInicialStr, String dataFinalStr) + throws DataInvalidaException, DatasInvalidasException { + Date dataInicial = null; + Date dataFinal = null; + + dataInicial = this.parseData(dataInicialStr); + dataFinal = this.parseData(dataFinalStr); + + IteratorClasse iterator = this.controladorPedido.getListaPedidos(dataInicial, dataFinal); + return iterator; + } + + public IteratorClasse fazerRelatorioAdm(String nomeAdm) { + + RelatorioAdm relatorio = null; + try { + relatorio = new RelatorioAdm(this.controladorPedido.getRepositorio(), nomeAdm); + relatorio.escreveArquivo(); + } catch (IOException e) { + } + + IteratorClasse informacoes = (IteratorClasse) relatorio.iterator(); + return informacoes; + } + + public IteratorClasse fazerRelatorioCliente(String dataInicialStr, + String dataFinalStr, String nomeCliente) throws DataInvalidaException, + DatasInvalidasException { + + Date dataInicial = null; + Date dataFinal = null; + dataInicial = this.parseData(dataInicialStr); + dataFinal = this.parseData(dataFinalStr); + + if (dataInicial != null && dataFinal != null) { + if (!dataInicial.before(dataFinal)) { + throw new DatasInvalidasException(); + } + } + + RelatorioCliente relatorio = null; + try { + relatorio = new RelatorioCliente(this.controladorPedido.getRepositorio(), + dataInicial, dataFinal, nomeCliente); + relatorio.escreveArquivo(); + } catch (IOException e) { + } + + IteratorClasse informacoes = relatorio.iterator(); + return informacoes; + } + + public IteratorClasse fazerRelatorioProduto(String dataInicialStr, + String dataFinalStr, String codigoProduto) throws DataInvalidaException, + CampoNaoPreenchidoException, DatasInvalidasException { + + Date dataInicial = null; + Date dataFinal = null; + dataInicial = this.parseData(dataInicialStr); + dataFinal = this.parseData(dataFinalStr); + + if (dataInicial != null && dataFinal != null) { + if (!dataInicial.before(dataFinal)) { + throw new DatasInvalidasException(); + } + } + + RelatorioProduto relatorio = null; + try { + relatorio = new RelatorioProduto(this.controladorPedido.getRepositorio(), dataInicial, dataFinal, codigoProduto); + relatorio.escreveArquivo(); + } catch (IOException e) { + } + + IteratorClasse informacoes = relatorio.iterator(); + return informacoes; + } + + private Date parseData(String data) throws DataInvalidaException { + Date date = null; + DateFormat formatador = DateFormat.getDateInstance(); + boolean valida = false; + if (!(data == null || data.trim().equals(""))) { + try { + date = formatador.parse(data); + if (this.verificaData(data)) { + valida = true; + } else { + valida = false; + } + } catch (ParseException ex) { + } + } else { + valida = true; + } + + if (!valida) { + throw new DataInvalidaException(); + } + + return date; + } + + private boolean verificaData(String data) { + String[] partes = data.split("/"); + boolean dataValida = false; + int dia = Integer.parseInt(partes[0]); + int mes = Integer.parseInt(partes[1]); + int ano = Integer.parseInt(partes[2]); + if (partes[2].length() != 4) { + dataValida = false; + + } else if (ano > 0) { + if (mes > 0 && mes < 13) { + if (dia > 0 && dia < 32) { + if (mes == 1 || mes == 3 || mes == 5 || mes == 7 + || mes == 8 || mes == 10 || mes == 12) { + dataValida = true; + } else if (mes == 2) { + if ((ano % 4 == 0 && ano % 100 != 0) + || (ano % 400 == 0)) { + if (dia < 30) { + dataValida = true; + } + } else { + + if (dia < 29) { + dataValida = true; + } + } + + } else { + if (dia < 31) { + dataValida = true; + } + } + } + } + } + + return dataValida; +} + +private boolean apenasLetras(String palavra) { + Pattern pattern = Pattern.compile("[a-zA-Z\\sÇçÛûÙùÚúÒòÓóÕõÔôÌìÃíÈèÉéÊêÀàÃáÃã]+"); + Matcher matcher = pattern.matcher(palavra); + return matcher.matches(); + +} +} \ No newline at end of file diff --git a/example-apps/src/ip/gui/TelaAdmListar.java b/example-apps/src/ip/gui/TelaAdmListar.java new file mode 100644 index 0000000..459b98d --- /dev/null +++ b/example-apps/src/ip/gui/TelaAdmListar.java @@ -0,0 +1,5 @@ +package gui; + +public class TelaAdmListar { + +} \ No newline at end of file diff --git a/example-apps/src/ip/gui/TelaCadastro.form b/example-apps/src/ip/gui/TelaCadastro.form new file mode 100644 index 0000000..cee4bf2 --- /dev/null +++ b/example-apps/src/ip/gui/TelaCadastro.form @@ -0,0 +1,422 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example-apps/src/ip/gui/TelaCadastro.java b/example-apps/src/ip/gui/TelaCadastro.java new file mode 100644 index 0000000..b9af61c --- /dev/null +++ b/example-apps/src/ip/gui/TelaCadastro.java @@ -0,0 +1,478 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package gui; + + +import fachada.Fachada; +import gui.TelaInicial; + + + +/** + * + * @author Josana + */ +public class TelaCadastro extends javax.swing.JDialog { + + /** + * Creates new form TelaCadastro + */ + public TelaCadastro(java.awt.Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jLabel2 = new javax.swing.JLabel(); + jLabel3 = new javax.swing.JLabel(); + jLabel4 = new javax.swing.JLabel(); + jLabel5 = new javax.swing.JLabel(); + jLabel6 = new javax.swing.JLabel(); + jLabel7 = new javax.swing.JLabel(); + jLabel8 = new javax.swing.JLabel(); + CampoRua = new javax.swing.JTextField(); + CampoNumero = new javax.swing.JTextField(); + CampoComplemento = new javax.swing.JTextField(); + CampoBairro = new javax.swing.JTextField(); + CampoCidade = new javax.swing.JTextField(); + SelecionarUF = new javax.swing.JComboBox(); + CampoTelefone = new javax.swing.JFormattedTextField(); + jPanel2 = new javax.swing.JPanel(); + jLabel9 = new javax.swing.JLabel(); + jLabel10 = new javax.swing.JLabel(); + jLabel11 = new javax.swing.JLabel(); + jLabel12 = new javax.swing.JLabel(); + CampoNome = new javax.swing.JTextField(); + CampoCPF = new javax.swing.JTextField(); + SelecionarTipo = new javax.swing.JComboBox(); + CampoSenha = new javax.swing.JPasswordField(); + jLabel1 = new javax.swing.JLabel(); + Cadastrar = new javax.swing.JButton(); + LimparDados = new javax.swing.JButton(); + Cancelar = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Endereço")); + + jLabel2.setText("Rua:"); + + jLabel3.setText("Bairro:"); + + jLabel4.setText("UF:"); + + jLabel5.setText("Complemento:"); + + jLabel6.setText("Número:"); + + jLabel7.setText("Telefone:"); + + jLabel8.setText("Cidade:"); + + CampoNumero.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyTyped(java.awt.event.KeyEvent evt) { + CampoNumeroKeyTyped(evt); + } + }); + + CampoCidade.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + CampoCidadeActionPerformed(evt); + } + }); + CampoCidade.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyTyped(java.awt.event.KeyEvent evt) { + CampoCidadeKeyTyped(evt); + } + }); + + SelecionarUF.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "AC", "AL", "AM", "AP", "BA", "CE", "DF", "ES", "GO", "MA", "MG", "MS", "MT", "PA", "PB", "PE", "PI", "PR", "RJ", "RN", "RO", "RR", "RS", "SC", "SE", "SP", "TO" })); + SelecionarUF.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + SelecionarUFActionPerformed(evt); + } + }); + + try { + CampoTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####"))); + } catch (java.text.ParseException ex) { + ex.printStackTrace(); + } + CampoTelefone.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyTyped(java.awt.event.KeyEvent evt) { + CampoTelefoneKeyTyped(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(CampoRua) + .addGap(18, 18, 18) + .addComponent(jLabel6) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(CampoNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel5) + .addGap(18, 18, 18) + .addComponent(CampoComplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(CampoBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel7) + .addGap(10, 10, 10) + .addComponent(CampoTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addGap(30, 30, 30) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(CampoCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(SelecionarUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addGap(0, 208, Short.MAX_VALUE))) + .addContainerGap()) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(18, 18, 18) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel2) + .addComponent(CampoRua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel6) + .addComponent(CampoNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(8, 8, 8) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel5) + .addComponent(CampoComplemento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel4) + .addComponent(CampoBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(SelecionarUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel7) + .addComponent(jLabel8) + .addComponent(CampoCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(CampoTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(21, 21, 21)) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Informações de Login")); + + jLabel9.setText("Nome:"); + + jLabel10.setText("CPF:"); + + jLabel11.setText("Senha:"); + + jLabel12.setText("Tipo de usuário:"); + + CampoNome.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyTyped(java.awt.event.KeyEvent evt) { + CampoNomeKeyTyped(evt); + } + }); + + CampoCPF.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + CampoCPFActionPerformed(evt); + } + }); + CampoCPF.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyTyped(java.awt.event.KeyEvent evt) { + CampoCPFKeyTyped(evt); + } + }); + + SelecionarTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Cliente\t", "Administrador" })); + SelecionarTipo.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + SelecionarTipoActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGap(18, 18, 18) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel9) + .addComponent(jLabel10)) + .addGap(18, 18, 18) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(CampoNome, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE) + .addComponent(CampoCPF)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(jLabel11) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(CampoSenha)) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(jLabel12) + .addGap(18, 18, 18) + .addComponent(SelecionarTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addGap(77, 77, 77)) + ); + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel9) + .addComponent(jLabel11) + .addComponent(CampoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(CampoNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel12) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel10) + .addComponent(SelecionarTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(CampoCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap(43, Short.MAX_VALUE)) + ); + + jLabel1.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N + jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); + jLabel1.setText("Cadastrar Novo Usuário"); + + Cadastrar.setText("Cadastrar"); + Cadastrar.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + CadastrarActionPerformed(evt); + } + }); + + LimparDados.setText("Limpar Dados"); + LimparDados.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + LimparDadosActionPerformed(evt); + } + }); + + Cancelar.setText("Cancelar"); + Cancelar.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + CancelarActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(62, 62, 62) + .addComponent(Cadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(69, 69, 69) + .addComponent(LimparDados, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(54, 54, 54) + .addComponent(Cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(layout.createSequentialGroup() + .addGap(148, 148, 148) + .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addGap(0, 0, Short.MAX_VALUE))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(LimparDados, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE) + .addComponent(Cadastrar, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)) + .addComponent(Cancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + private void CampoCidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CampoCidadeActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_CampoCidadeActionPerformed + + private void SelecionarUFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SelecionarUFActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_SelecionarUFActionPerformed + + private void SelecionarTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SelecionarTipoActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_SelecionarTipoActionPerformed + + private void CampoCPFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CampoCPFActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_CampoCPFActionPerformed + + private void CadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CadastrarActionPerformed + + +//fachada.adicionarCliente(CampoCPF.getText(), CampoTelefone.getText(), CampoNome.getText(), CampoNome.getText(), CampoRua.getText(), CampoNumero.getText(), CampoBairro.getText(), CampoCidade.getText(), CampoSenha.getPassword().toString(), SelecionarUF.getName().toString()); + }//GEN-LAST:event_CadastrarActionPerformed + + private void CampoCPFKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CampoCPFKeyTyped + char k=evt.getKeyChar(); + if (!(k>='0' && k<='9')) + evt.consume(); + }//GEN-LAST:event_CampoCPFKeyTyped + + private void CampoNumeroKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CampoNumeroKeyTyped + char k=evt.getKeyChar(); + if (!(k>='0' && k<='9')) + evt.consume(); + }//GEN-LAST:event_CampoNumeroKeyTyped + + private void CampoCidadeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CampoCidadeKeyTyped + char k=evt.getKeyChar(); + if (k>='0' && k<='9') + evt.consume(); + }//GEN-LAST:event_CampoCidadeKeyTyped + + private void CampoNomeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CampoNomeKeyTyped + char k=evt.getKeyChar(); + if (k>='0' && k<='9') + evt.consume(); + }//GEN-LAST:event_CampoNomeKeyTyped + + private void LimparDadosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LimparDadosActionPerformed + CampoRua.setText(""); + CampoComplemento.setText(""); + CampoNumero.setText(""); + CampoCPF.setText(""); + CampoBairro.setText(""); + CampoCidade.setText(""); + CampoTelefone.setText(""); + CampoNome.setText(""); + CampoSenha.setText(""); + + + }//GEN-LAST:event_LimparDadosActionPerformed + + private void CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelarActionPerformed + this.dispose(); + }//GEN-LAST:event_CancelarActionPerformed + + private void CampoTelefoneKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CampoTelefoneKeyTyped + char k=evt.getKeyChar(); + if (!(k>='0' && k<='9')) + evt.consume(); + }//GEN-LAST:event_CampoTelefoneKeyTyped + + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the dialog */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + TelaCadastro dialog = new TelaCadastro(new javax.swing.JFrame(), true); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(0); + } + }); + dialog.setVisible(true); + } + }); + } + + + /** + * @param args the command line arguments + */ + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton Cadastrar; + private javax.swing.JTextField CampoBairro; + private javax.swing.JTextField CampoCPF; + private javax.swing.JTextField CampoCidade; + private javax.swing.JTextField CampoComplemento; + private javax.swing.JTextField CampoNome; + private javax.swing.JTextField CampoNumero; + private javax.swing.JTextField CampoRua; + private javax.swing.JPasswordField CampoSenha; + private javax.swing.JFormattedTextField CampoTelefone; + private javax.swing.JButton Cancelar; + private javax.swing.JButton LimparDados; + private javax.swing.JComboBox SelecionarTipo; + private javax.swing.JComboBox SelecionarUF; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel10; + private javax.swing.JLabel jLabel11; + private javax.swing.JLabel jLabel12; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JLabel jLabel6; + private javax.swing.JLabel jLabel7; + private javax.swing.JLabel jLabel8; + private javax.swing.JLabel jLabel9; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + // End of variables declaration//GEN-END:variables +} diff --git a/example-apps/src/ip/gui/TelaCarrinho.java b/example-apps/src/ip/gui/TelaCarrinho.java new file mode 100644 index 0000000..01ef724 --- /dev/null +++ b/example-apps/src/ip/gui/TelaCarrinho.java @@ -0,0 +1,5 @@ +package gui; + +public class TelaCarrinho { + +} \ No newline at end of file diff --git a/example-apps/src/ip/gui/TelaClienteListar.java b/example-apps/src/ip/gui/TelaClienteListar.java new file mode 100644 index 0000000..0bee924 --- /dev/null +++ b/example-apps/src/ip/gui/TelaClienteListar.java @@ -0,0 +1,5 @@ +package gui; + +public class TelaClienteListar { + +} \ No newline at end of file diff --git a/example-apps/src/ip/gui/TelaConfVenda.java b/example-apps/src/ip/gui/TelaConfVenda.java new file mode 100644 index 0000000..fc2d7a8 --- /dev/null +++ b/example-apps/src/ip/gui/TelaConfVenda.java @@ -0,0 +1,5 @@ +package gui; + +public class TelaConfVenda { + +} \ No newline at end of file diff --git a/example-apps/src/ip/gui/TelaInicial.form b/example-apps/src/ip/gui/TelaInicial.form new file mode 100644 index 0000000..3567dd2 --- /dev/null +++ b/example-apps/src/ip/gui/TelaInicial.form @@ -0,0 +1,149 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example-apps/src/ip/gui/TelaInicial.java b/example-apps/src/ip/gui/TelaInicial.java new file mode 100644 index 0000000..7b6b4c0 --- /dev/null +++ b/example-apps/src/ip/gui/TelaInicial.java @@ -0,0 +1,193 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package gui; + + +import javax.swing.JDialog; +import javax.swing.JFrame; + + + + +/** + * + * @author Josana + */ +public class TelaInicial extends javax.swing.JFrame { + + /** + * Creates new form TelaInicial + */ + public TelaInicial() { + initComponents(); + this.setTitle("Livraria"); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jLabel1 = new javax.swing.JLabel(); + jPanel1 = new javax.swing.JPanel(); + Cadastrar = new javax.swing.JButton(); + Login = new javax.swing.JButton(); + Sair = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + + jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N + jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); + jLabel1.setText("Livraria"); + jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP); + + jPanel1.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), javax.swing.BorderFactory.createEtchedBorder())); + + Cadastrar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N + Cadastrar.setText("Cadastrar"); + Cadastrar.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + CadastrarActionPerformed(evt); + } + }); + + Login.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N + Login.setText("Login"); + Login.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + LoginActionPerformed(evt); + } + }); + + Sair.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N + Sair.setText("Sair"); + Sair.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + SairActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(149, 149, 149) + .addComponent(Cadastrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(Login, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE) + .addComponent(Sair, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) + .addGap(177, 177, 177)) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(24, 24, 24) + .addComponent(Cadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE) + .addComponent(Login, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(33, 33, 33) + .addComponent(Sair, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(21, 21, 21)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(135, 135, 135) + .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 381, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addGap(28, 28, 28) + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(50, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void SairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SairActionPerformed + System.exit(0); + }//GEN-LAST:event_SairActionPerformed + + private void CadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CadastrarActionPerformed + JDialog telaCadastro = new TelaCadastro(this, true); + telaCadastro.setVisible(true); + }//GEN-LAST:event_CadastrarActionPerformed + + private void LoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginActionPerformed + // TODO add your handling code here: + JDialog telaLogin = new TelaLogin(this, true); + telaLogin.setVisible(true); + }//GEN-LAST:event_LoginActionPerformed + + + + /** + * @param args the command line arguments + */ + + public static void main(String args[]) { + + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(TelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + new TelaInicial().setVisible(true); + + } + }); + } + + + + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton Cadastrar; + private javax.swing.JButton Login; + private javax.swing.JButton Sair; + private javax.swing.JLabel jLabel1; + private javax.swing.JPanel jPanel1; + // End of variables declaration//GEN-END:variables + +} \ No newline at end of file diff --git a/example-apps/src/ip/gui/TelaLogin.form b/example-apps/src/ip/gui/TelaLogin.form new file mode 100644 index 0000000..f09eb79 --- /dev/null +++ b/example-apps/src/ip/gui/TelaLogin.form @@ -0,0 +1,147 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example-apps/src/ip/gui/TelaLogin.java b/example-apps/src/ip/gui/TelaLogin.java new file mode 100644 index 0000000..400a1fe --- /dev/null +++ b/example-apps/src/ip/gui/TelaLogin.java @@ -0,0 +1,180 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package gui; + +/** + * + * @author Josana + */ +public class TelaLogin extends javax.swing.JDialog { + + /** + * Creates new form TelaLogin + */ + public TelaLogin(java.awt.Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jLabel1 = new javax.swing.JLabel(); + jPanel1 = new javax.swing.JPanel(); + jLabel2 = new javax.swing.JLabel(); + jLabel3 = new javax.swing.JLabel(); + jPasswordField1 = new javax.swing.JPasswordField(); + jTextField1 = new javax.swing.JTextField(); + jButton1 = new javax.swing.JButton(); + jButton2 = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + + jLabel1.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N + jLabel1.setText("Faça seu Login"); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados")); + + jLabel2.setText("CPF:"); + + jLabel3.setText("Senha:"); + + jPasswordField1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jPasswordField1ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(67, 67, 67) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel3) + .addComponent(jLabel2)) + .addGap(18, 18, 18) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) + .addComponent(jPasswordField1)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(25, 25, 25) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel2) + .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel3) + .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(42, Short.MAX_VALUE)) + ); + + jButton1.setText("Login"); + + jButton2.setText("Voltar"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jLabel1) + .addGap(145, 145, 145)) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addContainerGap()) + .addGroup(layout.createSequentialGroup() + .addGap(69, 69, 69) + .addComponent(jButton1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 117, Short.MAX_VALUE) + .addComponent(jButton2) + .addGap(96, 96, 96)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addGap(32, 32, 32) + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jButton1) + .addComponent(jButton2)) + .addGap(22, 22, 22)) + ); + + pack(); + }// //GEN-END:initComponents + + private void jPasswordField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordField1ActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_jPasswordField1ActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the dialog */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + TelaLogin dialog = new TelaLogin(new javax.swing.JFrame(), true); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(0); + } + }); + dialog.setVisible(true); + } + }); + } + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButton1; + private javax.swing.JButton jButton2; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JPanel jPanel1; + private javax.swing.JPasswordField jPasswordField1; + private javax.swing.JTextField jTextField1; + // End of variables declaration//GEN-END:variables +} diff --git a/example-apps/src/ip/gui/TelaProduto.java b/example-apps/src/ip/gui/TelaProduto.java new file mode 100644 index 0000000..4b26857 --- /dev/null +++ b/example-apps/src/ip/gui/TelaProduto.java @@ -0,0 +1,5 @@ +package gui; + +public class TelaProduto { + +} \ No newline at end of file diff --git a/example-apps/src/ip/gui/TelaVisitante.java b/example-apps/src/ip/gui/TelaVisitante.java new file mode 100644 index 0000000..d3c1943 --- /dev/null +++ b/example-apps/src/ip/gui/TelaVisitante.java @@ -0,0 +1,5 @@ +package gui; + +public class TelaVisitante { + +} \ No newline at end of file diff --git a/example-apps/src/ip/gui/Teste.java b/example-apps/src/ip/gui/Teste.java new file mode 100644 index 0000000..58e88ac --- /dev/null +++ b/example-apps/src/ip/gui/Teste.java @@ -0,0 +1,60 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package gui; + +/** + * + * @author Josana + */ +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; + +/** + * + * @author Sekkuar + */ +public class Teste { + + public static void main(String[] args) { + new Teste().go(); + } + + public void go(){ + JFrame janela = new JFrame("Minha Janela"); + JButton botao = new JButton("clica aqui!"); + + botao.addActionListener(new Listener());//cria o actionListener para o botão + + + janela.setSize(250, 250); //coloca o tamanho da frame + janela.add(botao); //coloca o botão na janela + janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + //Se essa janela fechar, todas fecham. + janela.setVisible(true); //mostra a janela + } + + + //Classe actionListener do botão + class Listener implements ActionListener{ + + public void actionPerformed(ActionEvent e) { + JFrame nova_janela = new JFrame("Outra Janela!"); + // cria uma nova janela + JLabel label = new JLabel("Você abriu uma janela nova!"); + + nova_janela.setSize(200,200); + nova_janela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + //se esta janela for fechada, o programa continua rodando + + nova_janela.add(label); + nova_janela.setVisible(true); + } + + } +} + diff --git a/example-apps/src/ip/interfaces/IRepositorioAdm.java b/example-apps/src/ip/interfaces/IRepositorioAdm.java new file mode 100644 index 0000000..8922437 --- /dev/null +++ b/example-apps/src/ip/interfaces/IRepositorioAdm.java @@ -0,0 +1,17 @@ +package dados.interfaces; + +import java.io.FileNotFoundException; +import java.io.IOException; + +import dados.entidade.Administrador; +import dados.IteratorClasse; + +public interface IRepositorioAdm { + + public void adicionar(Administrador administrador); + public void remover(String cpf); + public void atualizar(Administrador administrador); + public Administrador procurar(String cpf) throws FileNotFoundException, ClassNotFoundException, IOException; + + IteratorClasse iterator(); +} \ No newline at end of file diff --git a/example-apps/src/ip/interfaces/IRepositorioCliente.java b/example-apps/src/ip/interfaces/IRepositorioCliente.java new file mode 100644 index 0000000..dab1258 --- /dev/null +++ b/example-apps/src/ip/interfaces/IRepositorioCliente.java @@ -0,0 +1,14 @@ +package dados.interfaces; + +import dados.entidade.Cliente; +import dados.IteratorClasse; + +public interface IRepositorioCliente { + + public void adicionar(Cliente cliente); + public void remover(String cpf); + public void atualizar(Cliente cliente); + public Cliente procurar(String cpf); + + IteratorClasse iterator(); +} \ No newline at end of file diff --git a/example-apps/src/ip/interfaces/IRepositorioPedido.java b/example-apps/src/ip/interfaces/IRepositorioPedido.java new file mode 100644 index 0000000..17195a3 --- /dev/null +++ b/example-apps/src/ip/interfaces/IRepositorioPedido.java @@ -0,0 +1,14 @@ +package dados.interfaces; + +import dados.entidade.Pedido; +import dados.IteratorClasse; + +public interface IRepositorioPedido { + + public void adicionar(Pedido pedido); + public void remover(String codigo); + public void atualizar(Pedido pedido); + public Pedido procurar(String codigo); + + IteratorClasse iterator(); +} \ No newline at end of file diff --git a/example-apps/src/ip/interfaces/IRepositorioProduto.java b/example-apps/src/ip/interfaces/IRepositorioProduto.java new file mode 100644 index 0000000..3f9c3ea --- /dev/null +++ b/example-apps/src/ip/interfaces/IRepositorioProduto.java @@ -0,0 +1,16 @@ +package dados.interfaces; + + +import dados.entidade.Produto; +import dados.IteratorClasse; + +public interface IRepositorioProduto { + + public void adicionar(Produto produto); + public void remover(String codigo); + public void atualizar(Produto produto); + public Produto procurar(String codigo); + + IteratorClasse iterator(); + +} \ No newline at end of file diff --git a/example-apps/src/ip/negocio/ControladorAdm.java b/example-apps/src/ip/negocio/ControladorAdm.java new file mode 100644 index 0000000..4c005b2 --- /dev/null +++ b/example-apps/src/ip/negocio/ControladorAdm.java @@ -0,0 +1,223 @@ +package negocio; + +import dados.entidade.Administrador; +import dados.entidade.Contato; +import dados.interfaces.IRepositorioAdm; +import exceptions.administrador.*; +import exceptions.CampoNaoPreenchidoException; +import dados.IteratorClasse; + +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ControladorAdm { + private IRepositorioAdm repositorio; + + public ControladorAdm(IRepositorioAdm repositorio) { + this.repositorio = repositorio; + } + + public void adicionar(String cpf, String telefone, String nome, String logradouro, String numero, String complemento, String bairro, String cidade, String senha, String uf) throws CpfJaExisteException, CpfInvalidoException, TelefoneInvalidoException, CampoNaoPreenchidoException, TelefoneJaExisteException { + boolean cpfValido = this.validaCpf(cpf); + boolean numeroValido = this.validaNumero(telefone); + boolean cpfExiste = false; + if(cpfValido) { + cpfExiste = this.jaExisteCpf(cpf); + } + boolean telefoneExiste = this.jaExisteTelefone(telefone); + boolean campoVazio = this.campoVazio(cpf, telefone, nome, logradouro, numero, bairro, cidade, senha); + + if(cpfExiste) + throw new CpfJaExisteException(); + + if(telefoneExiste) + throw new TelefoneJaExisteException(); + + if(!cpfValido) + throw new CpfInvalidoException(); + + if(!numeroValido) + throw new TelefoneInvalidoException(); + + if (campoVazio) + throw new CampoNaoPreenchidoException(); + + Contato contato = new Contato(logradouro, numero, complemento, bairro, cidade, uf, telefone); + Administrador administrador = new Administrador(nome, cpf, senha, contato); + this.repositorio.adicionar(administrador); + } + + public void remover(String cpf) throws CpfInvalidoException { + Administrador admin = null; + try { + admin = new Administrador(this.buscaCpf(cpf)); + } catch (AdmNaoEncontradoException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + this.repositorio.remover(admin.getCpf()); + } + + public boolean jaExisteCpf(String cpf) { + boolean jaExiste = false; + IteratorClasse iterator = repositorio.iterator(); + while(iterator.hasNext()) { + Administrador auxiliar = iterator.next(); + if(auxiliar.getCpf().equals(cpf)) + jaExiste = true; + } + + return jaExiste; + } + + public boolean jaExisteNumero(String numero) { + boolean jaExiste = false; + IteratorClasse iterator = repositorio.iterator(); + while(iterator.hasNext()) { + Administrador auxiliar = iterator.next(); + if(auxiliar.getContato().getNumero().equals(numero)) + jaExiste = true; + } + + return jaExiste; + } + + public boolean jaExisteTelefone(String telefone) { + boolean jaExiste = false; + IteratorClasse iterator = repositorio.iterator(); + while(iterator.hasNext()) { + Administrador auxiliar = iterator.next(); + if(auxiliar.getContato().getTelefone().equals(telefone)) + jaExiste = true; + } + + return jaExiste; + } + + public boolean validaCpf(String cpf) { + boolean cpfValido = false; + + if(!(cpf == null)) { + if (cpf.matches("\\d{3}\\.\\d{3}\\.\\d{3}-\\d{2}")) { + cpfValido = true; + } + } + + return cpfValido; + } + + public boolean validaNumero(String numero) { + boolean numeroValido = false; + if (numero.matches("\\d{4}\\-\\d{4}")) { + numeroValido = true; + } + + return numeroValido; + } + + public boolean validaNome(String nome) { + boolean nomeValido = false; + if(this.apenasLetras(nome)) { + nomeValido = true; + } + + return nomeValido; + } + + private boolean campoVazio(String cpf, String telefone, String nome, String logradouro, + String numero, String bairro, String cidade, String senha) { + boolean campoVazio = false; + if (nome == null || nome.trim().equals("")) { + campoVazio = true; + } else if (logradouro == null || logradouro.trim().equals("")) { + campoVazio = true; + } else if (bairro == null || bairro.trim().equals("")) { + campoVazio = true; + } else if (cidade == null || cidade.trim().equals("")) { + campoVazio = true; + } else if (numero == null || numero.trim().equals("")) { + campoVazio = true; + } else if (cpf == null || cpf.trim().equals("")) { + campoVazio = true; + } else if (telefone == null || telefone.trim().equals("")) { + campoVazio = true; + } else if (senha == null || senha.trim().equals("")) { + campoVazio = true; + } + + return campoVazio; + } + + public Administrador buscaCpf(String cpf) throws CpfInvalidoException, AdmNaoEncontradoException { + Administrador resposta = null; + boolean achou = false; + IteratorClasse iterator = repositorio.iterator(); + if (this.validaCpf(cpf)) { + while (iterator.hasNext()) { + Administrador auxiliar = iterator.next(); + if (auxiliar.getCpf().equals(cpf)) { + resposta = auxiliar; + achou = true; + } + } + + if (!achou) { + throw new AdmNaoEncontradoException(); + } + + } else { + throw new CpfInvalidoException(); + } + return resposta; + } + + public Administrador buscaTelefone(String telefone) throws AdmNaoEncontradoException, + TelefoneInvalidoException { + Administrador resposta = null; + boolean achou = false; + IteratorClasse iterator = repositorio.iterator(); + if (this.validaNumero(telefone)) { + while (iterator.hasNext()) { + Administrador auxiliar = iterator.next(); + if (auxiliar.getContato().getTelefone().equals(telefone)) { + resposta = auxiliar; + achou = true; + } + } + + if (!achou) { + throw new AdmNaoEncontradoException(); + } + + } else { + throw new TelefoneInvalidoException(); + } + return resposta; + } + + public IteratorClasse buscaNome(String nome) throws AdmNaoEncontradoException { + IteratorClasse iterator = repositorio.iterator(); + Vector resposta = new Vector(); + while (iterator.hasNext()) { + Administrador auxiliar = iterator.next(); + if (auxiliar.getNome().toLowerCase().contains(nome.toLowerCase())) { + resposta.add(auxiliar); + } + } + + if (resposta.isEmpty()) { + throw new AdmNaoEncontradoException(); + } + + IteratorClasse retorno = new IteratorClasse(resposta); + return retorno; + } + + private boolean apenasLetras(String palavra) { + Pattern pattern = Pattern.compile("[a-zA-Z\\sÇçÛûÙùÚúÒòÓóÕõÔôÌìÃíÈèÉéÊêÀàÃáÃã]+"); + Matcher matcher = pattern.matcher(palavra); + return matcher.matches(); + + } +} \ No newline at end of file diff --git a/example-apps/src/ip/negocio/ControladorCliente.java b/example-apps/src/ip/negocio/ControladorCliente.java new file mode 100644 index 0000000..d3107ed --- /dev/null +++ b/example-apps/src/ip/negocio/ControladorCliente.java @@ -0,0 +1,215 @@ +package negocio; + +import dados.entidade.Cliente; +import dados.entidade.Contato; +import dados.interfaces.IRepositorioCliente; +import exceptions.cliente.*; +import exceptions.CampoNaoPreenchidoException; +import dados.IteratorClasse; + +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ControladorCliente { + private IRepositorioCliente repositorio; + + public ControladorCliente(IRepositorioCliente repositorio) { + this.repositorio = repositorio; + } + + public void adicionar(String cpf, String telefone, String nome, String senha, String logradouro, String numero, String complemento, String bairro, String cidade, String uf) throws CpfJaExisteException, CpfInvalidoException, TelefoneInvalidoException, CampoNaoPreenchidoException, TelefoneJaExisteException { + boolean cpfValido = this.validaCpf(cpf); + boolean numeroValido = this.validaNumero(telefone); + boolean cpfExiste = false; + if(cpfValido) { + cpfExiste = this.jaExisteCpf(cpf); + } + boolean telefoneExiste = this.jaExisteTelefone(telefone); + boolean campoVazio = this.campoVazio(cpf, telefone, nome, logradouro, numero, bairro, cidade); + + if(cpfExiste) + throw new CpfJaExisteException(); + + if(telefoneExiste) + throw new TelefoneJaExisteException(); + + if(!cpfValido) + throw new CpfInvalidoException(); + + if(!numeroValido) + throw new TelefoneInvalidoException(); + + if (campoVazio) + throw new CampoNaoPreenchidoException(); + + Contato contato = new Contato(logradouro, numero, complemento, bairro, cidade, uf, telefone); + Cliente cliente = new Cliente(nome, cpf, senha, contato); + this.repositorio.adicionar(cliente); + } + + public void remover(String cpf) throws CpfInvalidoException, ClienteNaoEncontradoException { + this.buscaCpf(cpf); + this.repositorio.remover(cpf); + } + + public boolean jaExisteCpf(String cpf) { + boolean jaExiste = false; + IteratorClasse iterator = repositorio.iterator(); + while(iterator.hasNext()) { + Cliente auxiliar = iterator.next(); + if(auxiliar.getCpf().equals(cpf)) + jaExiste = true; + } + + return jaExiste; + } + + public boolean jaExisteTelefone(String telefone) { + boolean jaExiste = false; + IteratorClasse iterator = repositorio.iterator(); + while(iterator.hasNext()) { + Cliente auxiliar = iterator.next(); + if(auxiliar.getContato().getTelefone().equals(telefone)) + jaExiste = true; + } + + return jaExiste; + } + + public boolean jaExisteNumero(String numero) { + boolean jaExiste = false; + IteratorClasse iterator = repositorio.iterator(); + while(iterator.hasNext()) { + Cliente auxiliar = iterator.next(); + if(auxiliar.getContato().getNumero().equals(numero)) + jaExiste = true; + } + + return jaExiste; + } + + public boolean validaCpf(String cpf) { + boolean cpfValido = false; + + if(!(cpf == null)) { + if (cpf.matches("\\d{3}\\.\\d{3}\\.\\d{3}-\\d{2}")) { + cpfValido = true; + } + } + + return cpfValido; + } + + public boolean validaNumero(String numero) { + boolean numeroValido = false; + if (numero.matches("\\d{4}\\-\\d{4}")) { + numeroValido = true; + } + + return numeroValido; + } + + public boolean validaNome(String nome) { + boolean nomeValido = false; + if(this.apenasLetras(nome)) { + nomeValido = true; + } + + return nomeValido; + } + + private boolean campoVazio(String cpf, String telefone, String nome, String logradouro, + String numero, String bairro, String cidade) { + boolean campoVazio = false; + if (nome == null || nome.trim().equals("")) { + campoVazio = true; + } else if (logradouro == null || logradouro.trim().equals("")) { + campoVazio = true; + } else if (bairro == null || bairro.trim().equals("")) { + campoVazio = true; + } else if (cidade == null || cidade.trim().equals("")) { + campoVazio = true; + } else if (numero == null || numero.trim().equals("")) { + campoVazio = true; + } else if (cpf == null || cpf.trim().equals("")) { + campoVazio = true; + } else if (telefone == null || telefone.trim().equals("")) { + campoVazio = true; + } + + return campoVazio; + } + + public Cliente buscaCpf(String cpf) throws CpfInvalidoException, ClienteNaoEncontradoException { + Cliente resposta = null; + boolean achou = false; + IteratorClasse iterator = repositorio.iterator(); + if (this.validaCpf(cpf)) { + while (iterator.hasNext()) { + Cliente auxiliar = iterator.next(); + if (auxiliar.getCpf().equals(cpf)) { + resposta = auxiliar; + achou = true; + } + } + + if (!achou) { + throw new ClienteNaoEncontradoException(); + } + + } else { + throw new CpfInvalidoException(); + } + return resposta; + } + + public Cliente buscaTelefone(String telefone) throws ClienteNaoEncontradoException, + TelefoneInvalidoException { + Cliente resposta = null; + boolean achou = false; + IteratorClasse iterator = repositorio.iterator(); + if (this.validaNumero(telefone)) { + while (iterator.hasNext()) { + Cliente auxiliar = iterator.next(); + if (auxiliar.getContato().getTelefone().equals(telefone)) { + resposta = auxiliar; + achou = true; + } + } + + if (!achou) { + throw new ClienteNaoEncontradoException(); + } + + } else { + throw new TelefoneInvalidoException(); + } + return resposta; + } + + public IteratorClasse buscaNome(String nome) throws ClienteNaoEncontradoException { + IteratorClasse iterator = repositorio.iterator(); + Vector resposta = new Vector(); + while (iterator.hasNext()) { + Cliente auxiliar = iterator.next(); + if (auxiliar.getNome().toLowerCase().contains(nome.toLowerCase())) { + resposta.add(auxiliar); + } + } + + if (resposta.isEmpty()) { + throw new ClienteNaoEncontradoException(); + } + + IteratorClasse retorno = new IteratorClasse(resposta); + return retorno; + } + + private boolean apenasLetras(String palavra) { + Pattern pattern = Pattern.compile("[a-zA-Z\\sÇçÛûÙùÚúÒòÓóÕõÔôÌìÃíÈèÉéÊêÀàÃáÃã]+"); + Matcher matcher = pattern.matcher(palavra); + return matcher.matches(); + + } +} diff --git a/example-apps/src/ip/negocio/ControladorPedido.java b/example-apps/src/ip/negocio/ControladorPedido.java new file mode 100644 index 0000000..3ae86f3 --- /dev/null +++ b/example-apps/src/ip/negocio/ControladorPedido.java @@ -0,0 +1,164 @@ +package negocio; + +import dados.IteratorClasse; +import java.math.BigDecimal; +import java.util.Date; +import java.util.Vector; + +import dados.entidade.Cliente; +import dados.entidade.Contato; +import dados.entidade.Pedido; +import dados.entidade.Produto; +import dados.interfaces.IRepositorioPedido; +import exceptions.pedido.DatasInvalidasException; +import exceptions.pedido.PedidoNaoEncontradoException; +import exceptions.pedido.QuantidadeProdutosInvalidaException; +import exceptions.produto.ProdutoNaoEncontradoException; + +public class ControladorPedido { + private IRepositorioPedido repositorio; + + public ControladorPedido(IRepositorioPedido repositorio) { + this.repositorio = repositorio; + } + + public void adicionar(String cpf, String telefone, String nome, String logradouro, String numero, String complemento, + String bairro, String cidade, String uf, String codigo, Produto[] produtos, Date data, + String quantidadeProdutosStr, String senha) throws PedidoNaoEncontradoException, QuantidadeProdutosInvalidaException, ProdutoNaoEncontradoException { + int quantidadeProdutos = 0; + try { + quantidadeProdutos = Integer.parseInt(quantidadeProdutosStr); + } catch (NumberFormatException e) { + throw new QuantidadeProdutosInvalidaException(); + } + + if (quantidadeProdutos != produtos.length) { + throw new QuantidadeProdutosInvalidaException(); + } + + if (quantidadeProdutos > 7) { + throw new QuantidadeProdutosInvalidaException(); + } + + Contato contato = new Contato(logradouro, numero, complemento, bairro, cidade, uf, telefone); + Cliente cliente = new Cliente(cpf, nome, senha, contato); + + BigDecimal taxa = this.calculaTaxa(cliente, produtos.length); + BigDecimal valor = new BigDecimal(0.0); + valor = valor.add(taxa); + for (int i = 0; i < produtos.length; i++) { + if (produtos[i] != null) { + valor = valor.add(produtos[i].getPreco()); + } else { + throw new ProdutoNaoEncontradoException(); + } + } + + boolean temDesconto = this.temDesconto(cliente); + if (temDesconto) { + double menorValor = (produtos[0].getPreco()).doubleValue(); + for (int i = 0; i < produtos.length; i++) { + if ((produtos[i].getPreco()).doubleValue() < menorValor) { + menorValor = (produtos[i].getPreco().doubleValue()); + } + } + + valor = valor.subtract(new BigDecimal(menorValor)); + } + + Pedido pedido = new Pedido(codigo, cliente, produtos, data, produtos.length, valor); + this.repositorio.adicionar(pedido); + } + + @SuppressWarnings("null") + private BigDecimal calculaTaxa(Cliente cliente, int tamanhoPedido) { + BigDecimal taxa = null; + double bonus; + String bairro = cliente.getContato().getBairro(); + boolean desconto = false; + + String[] bairrosDesconto = {"Aflitos", "Espinheiro", "Tamarineira", "Jaqueira", + "Torre", "Parnamirim", "Casa Forte", "Jabotatão", "Afogados", "Barro", + "Boa Viagem", "IPSEP"}; + + for (int i = 0; i < bairrosDesconto.length; i++) { + if (bairro.equalsIgnoreCase(bairrosDesconto[i])) { + desconto = true; + } + } + if (desconto) { + taxa = new BigDecimal(3.50); + } else { + taxa = new BigDecimal(7.00); + } + if (tamanhoPedido > 5) { + bonus = (tamanhoPedido - 5) * 0.1; + taxa = taxa.subtract(taxa.multiply(new BigDecimal(bonus))); + } + return taxa; + } + + private boolean temDesconto(Cliente cliente) { + IteratorClasse iterator = repositorio.iterator(); + int contador = 0; + boolean temDesconto = false; + + while (iterator.hasNext()) { + Pedido auxiliar = iterator.next(); + if (auxiliar.getCliente().getCpf().equals(cliente.getCpf())) { + contador++; + } + } + + if (contador % 5 == 0 && contador != 0) { + temDesconto = true; + } + + return temDesconto; + } + + public void remover(String codigo) throws PedidoNaoEncontradoException { + this.buscaCodigo(codigo); + this.repositorio.remover(codigo); + } + private Pedido buscaCodigo(String codigo) throws PedidoNaoEncontradoException { + Pedido resposta = null; + IteratorClasse iterator = this.repositorio.iterator(); + while (iterator.hasNext()) { + Pedido auxiliar = iterator.next(); + if (auxiliar.getCodigo().equals(codigo)) { + resposta = auxiliar; + } + } + if (resposta == null) { + throw new PedidoNaoEncontradoException(); + } + return resposta; + } + + public IteratorClasse getListaPedidos(Date dataInicio, Date dataFim) + throws DatasInvalidasException { + if (!(dataInicio == null || dataFim == null)) { + if (!dataInicio.before(dataFim)) { + throw new DatasInvalidasException(); + } + } + IteratorClasse iterator = this.repositorio.iterator(); + Vector pedidos = new Vector(); + while (iterator.hasNext()) { + Pedido auxiliar = iterator.next(); + if ((dataInicio == null || auxiliar.getData().after(dataInicio)) + && (dataFim == null || auxiliar.getData().before(dataFim))) { + pedidos.add(auxiliar); + } + } + IteratorClasse retorno = new IteratorClasse(pedidos); + return retorno; + } + +public IRepositorioPedido getRepositorio() { + + return this.repositorio; +} + +} \ No newline at end of file diff --git a/example-apps/src/ip/negocio/ControladorProduto.java b/example-apps/src/ip/negocio/ControladorProduto.java new file mode 100644 index 0000000..d4a890b --- /dev/null +++ b/example-apps/src/ip/negocio/ControladorProduto.java @@ -0,0 +1,151 @@ +package negocio; + +import dados.IteratorClasse; +import java.math.BigDecimal; +import java.util.Vector; + +import dados.entidade.Livro; +import dados.entidade.Produto; +import dados.interfaces.IRepositorioProduto; +import exceptions.CampoNaoPreenchidoException; +import exceptions.CodigoInvalidoException; +import exceptions.produto.AnoInvalidoException; +import exceptions.produto.ProdutoNaoEncontradoException; +import exceptions.produto.ValorInvalidoException; + +public class ControladorProduto { + private IRepositorioProduto repositorio; + + public ControladorProduto(IRepositorioProduto repositorio) { + this.repositorio = repositorio; + } + + public void adicionar(String codigo, String nome, String descricao, String valor, String nomeAutor, String editora, String anoPublicacao) throws ValorInvalidoException, + CampoNaoPreenchidoException, CodigoInvalidoException, AnoInvalidoException { + if (valor.trim().length() == 0 || valor == null) { + throw new CampoNaoPreenchidoException(); + } + + boolean valorInvalido = false; + int quantidadePontos = 0; + for (int i = 0; i < valor.length(); i++) { + if (("" + valor.charAt(i)).matches("\\.")) { + quantidadePontos++; + } + if (quantidadePontos > 1) { + valorInvalido = true; + } + if (!(("" + valor.charAt(i)).matches("\\d{1}") || (("" + valor.charAt(i)).matches("\\.")))) { + valorInvalido = true; + } + } + + if (valorInvalido) { + throw new ValorInvalidoException(); + } + + boolean anoInvalido = true; + + if(anoPublicacao.matches("\\d{4}")) + anoInvalido = false; + + if(anoInvalido) + throw new AnoInvalidoException(); + + double valorAux = Double.parseDouble(valor); + + BigDecimal valorBig = new BigDecimal(valorAux); + if (codigo.trim().length() == 0 || codigo == null) { + throw new CampoNaoPreenchidoException(); + } else if (nome.trim().length() == 0 || nome == null) { + throw new CampoNaoPreenchidoException(); + } else { + + this.validaCodigo(codigo); + Produto produto; + + produto = new Livro(codigo, nome, descricao, valorBig, nomeAutor, editora, anoPublicacao); + this.repositorio.adicionar(produto); + + } + + } + + public void remover(String codigo) throws ProdutoNaoEncontradoException { + + this.buscaCodigo(codigo); + this.repositorio.remover(codigo); + + } + + public Produto buscaCodigo(String codigo) throws ProdutoNaoEncontradoException { + + Produto resposta = null; + IteratorClasse iterator = null; + + iterator = this.repositorio.iterator(); + + while (iterator.hasNext()) { + Produto auxiliar = iterator.next(); + if (auxiliar.getCodigo().equals(codigo)) { + resposta = auxiliar; + } + } + + if (resposta == null) { + throw new ProdutoNaoEncontradoException(); + } else { + return resposta; + } + } + + public IteratorClasse buscaParteCodigo(String codigo) throws ProdutoNaoEncontradoException { + IteratorClasse iterator = this.repositorio.iterator(); + Vector resposta = new Vector(); + while (iterator.hasNext()) { + Produto auxiliar = iterator.next(); + if (auxiliar.getCodigo().contains(codigo)) { + resposta.add(auxiliar); + } + } + + if (resposta.isEmpty()) { + throw new ProdutoNaoEncontradoException(); + } + + IteratorClasse retorno = new IteratorClasse(resposta); + return retorno; + } + + public IteratorClasse buscaNome(String nome) throws ProdutoNaoEncontradoException { + IteratorClasse iterator = this.repositorio.iterator(); + Vector resposta = new Vector(); + + while (iterator.hasNext()) { + Produto auxiliar = iterator.next(); + if (auxiliar.getNome().toLowerCase().contains(nome.toLowerCase())) { + resposta.add(auxiliar); + } + } + + if (resposta.isEmpty()) { + throw new ProdutoNaoEncontradoException(); + } + + IteratorClasse retorno = new IteratorClasse(resposta); + return retorno; + } + + private void validaCodigo(String codigo) throws CodigoInvalidoException { + IteratorClasse iterator = null; + + iterator = this.repositorio.iterator(); + + while (iterator.hasNext()) { + Produto auxiliar = iterator.next(); + if (auxiliar.getCodigo().equals(codigo)) { + throw new CodigoInvalidoException(); + } + } + } +} \ No newline at end of file diff --git a/example-apps/src/ip/pedido/DataInvalidaException.java b/example-apps/src/ip/pedido/DataInvalidaException.java new file mode 100644 index 0000000..7448dd6 --- /dev/null +++ b/example-apps/src/ip/pedido/DataInvalidaException.java @@ -0,0 +1,15 @@ +package exceptions.pedido; + +public class DataInvalidaException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = -7435975292867826985L; + + public DataInvalidaException () { + super ("Data Inválida!"); + } + +} diff --git a/example-apps/src/ip/pedido/DatasInvalidasException.java b/example-apps/src/ip/pedido/DatasInvalidasException.java new file mode 100644 index 0000000..c3eb25d --- /dev/null +++ b/example-apps/src/ip/pedido/DatasInvalidasException.java @@ -0,0 +1,14 @@ +package exceptions.pedido; + +public class DatasInvalidasException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = 6711158218260873755L; + + public DatasInvalidasException(){ + super("Datas inválidas!"); + } +} diff --git a/example-apps/src/ip/pedido/PedidoInvalidoException.java b/example-apps/src/ip/pedido/PedidoInvalidoException.java new file mode 100644 index 0000000..d3df6bf --- /dev/null +++ b/example-apps/src/ip/pedido/PedidoInvalidoException.java @@ -0,0 +1,15 @@ +package exceptions.pedido; + +public class PedidoInvalidoException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = -7413553396183110229L; + + public PedidoInvalidoException() { + super("Pedido inválido!"); + } + +} diff --git a/example-apps/src/ip/pedido/PedidoNaoEncontradoException.java b/example-apps/src/ip/pedido/PedidoNaoEncontradoException.java new file mode 100644 index 0000000..ed4de68 --- /dev/null +++ b/example-apps/src/ip/pedido/PedidoNaoEncontradoException.java @@ -0,0 +1,14 @@ +package exceptions.pedido; + +public class PedidoNaoEncontradoException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = 6740991126763866832L; + + public PedidoNaoEncontradoException () { + super ("Pedido não encontrado!"); + } +} diff --git a/example-apps/src/ip/pedido/QuantidadeProdutosInvalidaException.java b/example-apps/src/ip/pedido/QuantidadeProdutosInvalidaException.java new file mode 100644 index 0000000..eb3baa9 --- /dev/null +++ b/example-apps/src/ip/pedido/QuantidadeProdutosInvalidaException.java @@ -0,0 +1,14 @@ +package exceptions.pedido; + +public class QuantidadeProdutosInvalidaException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 5512156152622871287L; + + public QuantidadeProdutosInvalidaException(){ + super("Quantidade de produtos inválida!"); + } + +} diff --git a/example-apps/src/ip/produto/AnoInvalidoException.java b/example-apps/src/ip/produto/AnoInvalidoException.java new file mode 100644 index 0000000..e1a7638 --- /dev/null +++ b/example-apps/src/ip/produto/AnoInvalidoException.java @@ -0,0 +1,12 @@ +package exceptions.produto; + +public class AnoInvalidoException extends Exception { + /** + * + */ + private static final long serialVersionUID = -6899488026114280437L; + + public AnoInvalidoException() { + super("Ano inválido"); + } +} \ No newline at end of file diff --git a/example-apps/src/ip/produto/ProdutoNaoEncontradoException.java b/example-apps/src/ip/produto/ProdutoNaoEncontradoException.java new file mode 100644 index 0000000..2163296 --- /dev/null +++ b/example-apps/src/ip/produto/ProdutoNaoEncontradoException.java @@ -0,0 +1,14 @@ +package exceptions.produto; + +public class ProdutoNaoEncontradoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -5502802968119199034L; + + public ProdutoNaoEncontradoException () { + super ("Produto não encontrado!"); + } + +} diff --git a/example-apps/src/ip/produto/ValorInvalidoException.java b/example-apps/src/ip/produto/ValorInvalidoException.java new file mode 100644 index 0000000..bea44a7 --- /dev/null +++ b/example-apps/src/ip/produto/ValorInvalidoException.java @@ -0,0 +1,14 @@ +package exceptions.produto; + +public class ValorInvalidoException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -5100321524233328233L; + + public ValorInvalidoException(){ + super("Valor inválido!"); + } + +} diff --git a/example-apps/src/ip/relatorios/RelatorioAdm.java b/example-apps/src/ip/relatorios/RelatorioAdm.java new file mode 100644 index 0000000..bacc9df --- /dev/null +++ b/example-apps/src/ip/relatorios/RelatorioAdm.java @@ -0,0 +1,62 @@ +package relatorios; + +import dados.interfaces.IRepositorioPedido; +import dados.IteratorClasse; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Vector; + + +@SuppressWarnings("rawtypes") +public class RelatorioAdm implements Iterable { + + private String nome; + private File arquivo; + private IteratorClasse informacoesRelatorio; + private IteratorClasse retornavel; + private String nomeArquivo; + + + +public RelatorioAdm (IRepositorioPedido repositorio, String nome) throws IOException { + this.nome = nome; + SimpleDateFormat formatador = new SimpleDateFormat("yyyyMMddHHmmss"); + Date dataAtual = new Date(); + String auxiliar = formatador.format(dataAtual); + String nomeArquivo = "Relatorio de Administradores " + auxiliar + ".txt"; + this.arquivo = new File (nomeArquivo); + this.nomeArquivo = nomeArquivo; + this.arquivo.createNewFile(); + this.escreveRelatorio(); + } + +private void escreveRelatorio(){ + + Vector linhas = new Vector(); + String primeiraLinha = "Nome do Administrador: " + this.nome; + + linhas.add(primeiraLinha); + + this.informacoesRelatorio = new IteratorClasse(linhas); + this.retornavel = new IteratorClasse(linhas); + + } + + public void escreveArquivo() throws IOException{ + PrintWriter writer = new PrintWriter (new FileWriter (this.nomeArquivo)); + while (this.informacoesRelatorio.hasNext()){ + String linha = this.informacoesRelatorio.next(); + writer.println(linha); + } + writer.close(); + } + + @Override + public IteratorClasse iterator(){ + return this.retornavel; + } +} diff --git a/example-apps/src/ip/relatorios/RelatorioCliente.java b/example-apps/src/ip/relatorios/RelatorioCliente.java new file mode 100644 index 0000000..0813547 --- /dev/null +++ b/example-apps/src/ip/relatorios/RelatorioCliente.java @@ -0,0 +1,121 @@ +package relatorios; + +import dados.entidade.Pedido; +import dados.interfaces.IRepositorioPedido; +import dados.IteratorClasse; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; +import java.util.Vector; + +@SuppressWarnings("rawtypes") +public class RelatorioCliente implements Iterable { + + private IteratorClasse iteratorPedido; + private Date dataInicial; + private Date dataFinal; + private String nome; + private File arquivo; + private IteratorClasse informacoesRelatorio; + private IteratorClasse retornavel; + private String nomeArquivo; + + public RelatorioCliente (IRepositorioPedido repositorioPedidos, Date dataInicial, + Date dataFinal, String nome) throws IOException { + this.iteratorPedido = repositorioPedidos.iterator(); + this.dataInicial = dataInicial; + this.dataFinal = dataFinal; + this.nome = nome; + SimpleDateFormat formatador = new SimpleDateFormat("yyyyMMddHHmmss"); + Date dataAtual = new Date(); + String auxiliar = formatador.format(dataAtual); + String nomeArquivo = "Relatorio de Clientes " + auxiliar + ".txt"; + this.arquivo = new File (nomeArquivo); + this.nomeArquivo = nomeArquivo; + this.arquivo.createNewFile(); + this.escreveRelatorio(); + + } + + private void escreveRelatorio(){ + + SimpleDateFormat formatador = new SimpleDateFormat("dd/MM/yyyy"); + String dataInicialStr, dataFinalStr = ""; + if (this.dataInicial == null){ + dataInicialStr = "__/__/____"; + } else { + dataInicialStr = formatador.format(this.dataInicial); + } + if (this.dataFinal == null){ + dataFinalStr = "__/__/____"; + } else { + dataFinalStr = formatador.format(this.dataFinal); + } + Vector linhas = new Vector(); + String primeiraLinha = "Nome do Cliente: " + this.nome; + String segundaLinha = "Período de Compras: " + dataInicialStr + " - " + dataFinalStr; + + Vector dados = new Vector(); + while (this.iteratorPedido.hasNext()){ + Pedido auxiliar = this.iteratorPedido.next(); + if (auxiliar.getCliente().getNome().toLowerCase(). + contains(this.nome.toLowerCase())){ + if ((this.dataInicial == null || auxiliar.getData(). + after(this.dataInicial)) && (this.dataFinal == null || + auxiliar.getData().before(this.dataFinal))){ + dados.add(auxiliar); + } + } + } + + + Collections.sort(dados); + + linhas.add(primeiraLinha); + linhas.add(segundaLinha); + + for (int i = 0; i(linhas); + this.retornavel = new IteratorClasse(linhas); + + } + + public void escreveArquivo() throws IOException{ + PrintWriter writer = new PrintWriter (new FileWriter (this.nomeArquivo)); + while (this.informacoesRelatorio.hasNext()){ + String linha = this.informacoesRelatorio.next(); + writer.println(linha); + } + writer.close(); + } + + @Override + public IteratorClasse iterator(){ + return this.retornavel; + } +} \ No newline at end of file diff --git a/example-apps/src/ip/relatorios/RelatorioPedido.java b/example-apps/src/ip/relatorios/RelatorioPedido.java new file mode 100644 index 0000000..45ee000 --- /dev/null +++ b/example-apps/src/ip/relatorios/RelatorioPedido.java @@ -0,0 +1,5 @@ +package relatorios; + +public class RelatorioPedido { + +} diff --git a/example-apps/src/ip/relatorios/RelatorioProduto.java b/example-apps/src/ip/relatorios/RelatorioProduto.java new file mode 100644 index 0000000..c0a4c8c --- /dev/null +++ b/example-apps/src/ip/relatorios/RelatorioProduto.java @@ -0,0 +1,160 @@ +package relatorios; + +import dados.entidade.Pedido; +import dados.interfaces.IRepositorioPedido; +import dados.IteratorClasse; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; +import java.util.Vector; + +@SuppressWarnings("rawtypes") +public class RelatorioProduto implements Iterable { + + + /* + * A implementação de RelatorioProduto é bem similar a RelatorioCliente. + * A estrutura do relatório, em si, é um pouco diferente, mas a lógica + * é basicamente a mesma: inicializamos atributos e geramos o relatório + * através de métodos para popularem 2 iterators e escreverem no arquivo. + */ + + // Atributos // + private IteratorClasse iteratorPedido; + private Date dataInicial; + private Date dataFinal; + private String codigo; + private File arquivo; + private IteratorClasse informacoesRelatorio; + private IteratorClasse retornavel; + private String nomeArquivo; + + // Construtor: inicializa os atributos e chama o método escreveRelatorio(). // + public RelatorioProduto (IRepositorioPedido repositorioPedidos, Date dataInicial, + Date dataFinal, String codigo) throws IOException{ + this.iteratorPedido = repositorioPedidos.iterator(); + this.dataInicial = dataInicial; + this.dataFinal = dataFinal; + this.codigo = codigo; + SimpleDateFormat formatador = new SimpleDateFormat("yyyyMMddHHmmss"); + Date dataAtual = new Date(); + String auxiliar = formatador.format(dataAtual); + String nomeArquivo = "Relatorio de Produtos " + auxiliar + ".txt"; + this.arquivo = new File (nomeArquivo); + this.nomeArquivo = nomeArquivo; + this.arquivo.createNewFile(); + this.escreveRelatorio(); + + } + + // Guarda as informações que constarão no relatório // + private void escreveRelatorio(){ + SimpleDateFormat formatador = new SimpleDateFormat("dd/MM/yyyy"); + String dataInicialStr, dataFinalStr = ""; + if (this.dataInicial == null){ + dataInicialStr = "__/__/____"; + } else { + dataInicialStr = formatador.format(this.dataInicial); + } + if (this.dataFinal == null){ + dataFinalStr = "__/__/____"; + } else { + dataFinalStr = formatador.format(this.dataFinal); + } + + Vector codigosEncontrados = new Vector(); + Vector pedidosEncontrados = new Vector(); + + IteratorClasse iterator = this.iteratorPedido; + while (iterator.hasNext()){ + Pedido auxiliar = iterator.next(); + for (int i = 0; i iterator2 = new IteratorClasse(pedidosEncontrados); + Vector dados = new Vector(); + + while (iterator2.hasNext()){ + Pedido auxiliar = iterator2.next(); + if ((this.dataInicial == null || auxiliar.getData().after(this.dataInicial)) + && (this.dataFinal == null || auxiliar.getData().before(this.dataFinal))){ + dados.add(auxiliar); + } + } + Collections.sort(dados); + + Vector linhas = new Vector(); + + linhas.add(primeiraLinha); + linhas.add(segundaLinha); + linhas.add(terceiraLinha); + + NumberFormat nf = NumberFormat.getCurrencyInstance(); + + for (int i = 0; i(linhas); + this.retornavel = new IteratorClasse(linhas); + } + + // Escreve no arquivo // + public void escreveArquivo() throws IOException{ + PrintWriter writer = new PrintWriter (new FileWriter (this.nomeArquivo)); + while (this.informacoesRelatorio.hasNext()){ + String linha = this.informacoesRelatorio.next(); + writer.println(linha); + } + writer.close(); + } + + // Retorna o iterator a ser utilizado na GUI // + public IteratorClasse iterator(){ + return this.retornavel; + } +} \ No newline at end of file diff --git a/example-apps/src/ip/repositorio/RepAdmArquivo.java b/example-apps/src/ip/repositorio/RepAdmArquivo.java new file mode 100644 index 0000000..89c35d5 --- /dev/null +++ b/example-apps/src/ip/repositorio/RepAdmArquivo.java @@ -0,0 +1,263 @@ +package dados.repositorio; + +/*import dados.entidade.Contato; +import exceptions.CampoNaoPreenchidoException; +import exceptions.administrador.AdmNaoEncontradoException; +import exceptions.administrador.CpfInvalidoException; +import exceptions.administrador.CpfJaExisteException; +import exceptions.administrador.TelefoneInvalidoException; +import exceptions.administrador.TelefoneJaExisteException; +import negocio.ControladorAdm;*/ + +import dados.interfaces.IRepositorioAdm; +import dados.entidade.Administrador; +import dados.entidade.Contato; +import dados.IteratorClasse; +import exceptions.CampoNaoPreenchidoException; +import exceptions.administrador.CpfInvalidoException; +import exceptions.administrador.CpfJaExisteException; +import exceptions.administrador.TelefoneInvalidoException; +import exceptions.administrador.TelefoneJaExisteException; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Vector; + + + +public class RepAdmArquivo implements IRepositorioAdm { + + private Vector vetorAdministradores; + + + @SuppressWarnings({ "unchecked", "resource" }) + public RepAdmArquivo() throws IOException { + this.vetorAdministradores = new Vector(); + + File arquivo = new File("arquivoAdministrador.txt"); + if (!arquivo.exists()) { + arquivo.createNewFile(); + } + if (arquivo.length() != 0) { + ObjectInputStream reader = null; + try { + FileInputStream fileInput = new FileInputStream("arquivoAdministrador.txt"); + + reader = new ObjectInputStream(fileInput); + this.vetorAdministradores = (Vector) reader.readObject(); + } catch (ClassNotFoundException e) { + } + } + } + + public void adicionar(Administrador admin) { + this.vetorAdministradores.add(admin); + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoAdministrador.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorAdministradores); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + } catch (IOException e) { + } + } + } + + public void remover(String cpf) { + for (int i = 0; i < this.vetorAdministradores.size(); i++) { + if (this.vetorAdministradores.elementAt(i).getContato() == null) { + + } + else if (this.vetorAdministradores.elementAt(i).getCpf().equals(cpf)) { + this.vetorAdministradores.remove(i); + } + } + + ObjectOutputStream gravar = null; + + FileOutputStream writer; + try { + writer = new FileOutputStream("arquivoAdministrador.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorAdministradores); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + } finally { + try { + gravar.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("unchecked") + public Administrador procurar(String cpf) { + + //Cria um objeto FileInputStream + FileInputStream fileStream; + int indiceAchado = 0; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoAdministrador.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + + this.vetorAdministradores = (Vector) os.readObject(); + for (int indice = 0; indice < vetorAdministradores.size(); indice++) { + if (this.vetorAdministradores.elementAt(indice).getCpf().equals(cpf)) { + indiceAchado = indice; + //System.out.print(indiceAchado); + } + + + + } + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + return this.vetorAdministradores.elementAt(indiceAchado); + + } + //O método atualizar é basicamente feito o procurar, porém depois que ele atualiza um elemento + //Ele deve re-serializar tudo + @SuppressWarnings("unchecked") + public void atualizar(Administrador administrador){ + FileInputStream fileStream; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoAdministrador.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + //Deserializa o vector e verifica se o cpf do elemento é igual + //O cpf do objeto, atualiza e re-serializa. + int indiceAchado = 0; + this.vetorAdministradores = (Vector) os.readObject(); + for (int indice = 0; indice < vetorAdministradores.size(); indice++) { + if (this.vetorAdministradores.elementAt(indice).getCpf().equals(administrador.getCpf())) { + indiceAchado = indice; + //System.out.print(indiceAchado); + this.vetorAdministradores.elementAt(indiceAchado).setContato(administrador.getContato()); + this.vetorAdministradores.elementAt(indiceAchado).setNome(administrador.getNome()); + this.vetorAdministradores.elementAt(indiceAchado).setSenha(administrador.getSenha()); + + } + + + } + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoAdministrador.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorAdministradores); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + + } catch (IOException e) { + } + } + + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + + + } + + + + public IteratorClasse iterator() { + Vector listAdministradors = new Vector(); + for (int i = 0; i < this.vetorAdministradores.size(); i++) { + listAdministradors.add(this.vetorAdministradores.elementAt(i)); + } + IteratorClasse iterator = new IteratorClasse(listAdministradors); + return iterator; + } + + public static void main(String[] args) throws IOException, CpfJaExisteException, CpfInvalidoException, TelefoneInvalidoException, CampoNaoPreenchidoException, TelefoneJaExisteException { + + //TESTE REP-ARQUVIO + + RepAdmArquivo teste = new RepAdmArquivo(); + Contato contato = new Contato("Rua teste", " Testnumero", "Test complemento", "Test bairro" , "Test cidade" , "test uf", "test telefone"); + Administrador admin = new Administrador("Fabio", "156.111.111-11", "12345678", contato); + Administrador adminSubstituir = new Administrador("Junior Alterado", "156.111.111-11", "55555", contato); + + //teste.adicionar(admin); + //teste.adicionar(admin2); + System.out.println(teste.procurar("156.111.111-11").getNome()); + + teste.atualizar(adminSubstituir); + + + System.out.println(teste.procurar("156.111.111-11").getNome()); + + + /* + *:::::::::::TesteCONTROLADOR + * try { + + ControladorAdm controladorAdm = new ControladorAdm(new RepAdmArquivo()); + + + //controladorAdm.adicionar("156.111.111-11", "1234-5678", "teste", "teste", "teste", "teste", "teste", "teste", "teste", "teste"); + + //controladorAdm.adicionar("146.111.111-11", "1235-5678", "teste", "teste", "teste", "teste", "teste", "teste", "teste", "teste"); + + //controladorAdm.remover("156.111.111-11"); + + try { + + System.out.print(controladorAdm.buscaCpf("146.111.111-11").getSenha()); + } catch (AdmNaoEncontradoException e) { + e.getMessage(); + } + + } catch (IOException e) { + } + catch (CpfInvalidoException e2) { + e2.getMessage(); + } + } */ + } +} \ No newline at end of file diff --git a/example-apps/src/ip/repositorio/RepAdmArray.java b/example-apps/src/ip/repositorio/RepAdmArray.java new file mode 100644 index 0000000..a9f1c11 --- /dev/null +++ b/example-apps/src/ip/repositorio/RepAdmArray.java @@ -0,0 +1,134 @@ +package dados.repositorio; + +import java.util.Vector; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioAdm; +import dados.entidade.Administrador; + +@SuppressWarnings("rawtypes") +public class RepAdmArray implements IRepositorioAdm, Iterable { + + private Administrador[] administradores; + private int indice; + + public RepAdmArray() { + this.administradores = new Administrador[1000]; + this.indice = 0; + } + + public boolean isVazia() { + if (indice == 0 && administradores[0].equals(null)) + return true; + return false; + } + + /*O método adicionar adiciona um objeto ao indice fixo que está é atributo do repositório + daí depois o indice é incrementado em 1 para ficar apto a receber um novo objeto + */ + public void adicionar(Administrador administrador) { + + if(this.indice < this.administradores.length) { + administradores[indice] = administrador; + indice++; + } else { + Administrador[] aux = new Administrador[this.administradores.length * 2]; + for(int i = 0; i < this.indice; i++) { + aux[i] = administradores[i]; + } + + this.administradores = aux; + this.adicionar(administrador); + } + } + + //Só mais para fins de teste, imprimir certo atributo de todos + public void imprimir() { + for(int i = 0; i < indice; i++) { + System.out.println(administradores[i].getCpf() + " - " + administradores[i].getNome()); + } + } + + //A partir da string cpf que vai ser única, ele remove o objeto designado + public void remover(String cpf) { + for(int i = 0; i < indice; i++) { + if(administradores[i].getCpf().equals(cpf)) { + administradores[i] = null; + if(i < indice - 1 && administradores[i + 1] != null) { + administradores[i] = administradores[i + 1]; + administradores[i + 1] = null; + } + } + } + + if(administradores[this.indice - 1] == null) + indice--; + } + //Se o cpf for igual ao objeto no índice, retorna aquele objeto + public Administrador procurar(String cpf) { + for(int i = 0; i < indice; i++) { + if(administradores[i].getCpf().equals(cpf)) + return administradores[i]; + } + + return null; + } + //Método para organizar, junto com um comparator ele compara 2 objetos, verificando seus cpfs + //Caso um cpf for "menor" que outro, ele troca de lugar por meio de um auxiliar + public void sort() { + + for (int i = 0; i < indice - 1; ++i) { + for (int j = i + 1; j < indice; ++j) { + if (administradores[i].getCpf().compareTo(administradores[j].getCpf()) > 0) { + Administrador aux = administradores[i]; + administradores[i] = administradores[j]; + administradores[j] = aux; + } + } + } + + } + + public IteratorClasse iterator() { + + Vector listAdm = new Vector(); + for (int i = 0; i < this.indice; i++) { + listAdm.add(this.administradores[i]); + } + + IteratorClasse iterator = new IteratorClasse(listAdm); + return iterator; + } + + public void atualizar(Administrador administrador) { + for (int i = 0; i < indice; i++) { + if(administradores[i].getCpf().equals(administrador.getCpf())) + administradores[i] = administrador; + } + } + + +//Teste + /*public static void main (String[] args) { + + RepAdmArray rep = new RepAdmArray(); + Administrador testep = new Administrador("Teste", "CPF", "Senha", null); + + Administrador teste2 = new Administrador("Teste2", "CPF2", "Senha3", null); + + Administrador teste3 = new Administrador("Teste3", "CPF3", "Senha3", null); + + + + rep.adicionar(teste3); + rep.adicionar(teste2); + rep.adicionar(testep); + + rep.imprimir(); + + System.out.println("Procura: "+ rep.procurar("CPF2") + "Valores ordenados: \n"); + rep.sort(); + rep.imprimir(); + } +*/ +} \ No newline at end of file diff --git a/example-apps/src/ip/repositorio/RepAdmLista.java b/example-apps/src/ip/repositorio/RepAdmLista.java new file mode 100644 index 0000000..e9d831e --- /dev/null +++ b/example-apps/src/ip/repositorio/RepAdmLista.java @@ -0,0 +1,169 @@ +package dados.repositorio; + + + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioAdm; +import dados.entidade.Administrador; + + +public class RepAdmLista implements IRepositorioAdm { + + + + int numero_elementos; //Só pra saber se a lista esta vazia e tb o num. de el. + Administrador primeiro = new Administrador(); //O primeiro elemento da lista vai ser o do final, o �ltimo adicionado + Administrador ultimo = new Administrador(); //O ultimo da lista sempre vai apontar pra null + + public RepAdmLista() { + this.numero_elementos = 0; + this.primeiro = null; + this.ultimo = null; + + } + //LISTA ENCADEADA + + public boolean isVazia() { + return (primeiro == null && ultimo == null); + } + + public void adicionar(Administrador administrador) { + /*Qnd vc adiciona 1 elemento a lista, cria-se um objeto admin + *e a esse objeto vai ser atribu�do o valor de primeiro, que na verdade + *vai se tornar o elemento depois do primeiro. E o novo primeiro, vai ser + *admin, que � o objeto criado. + */ + Administrador admin = new Administrador(administrador); + if (isVazia()) { + this.primeiro = admin; + this.ultimo = admin; + + } + else { + admin.setProx(this.primeiro); + } + this.primeiro = admin; + numero_elementos++; + } + + public void adicionarNoFinal(Administrador administrador) { + this.numero_elementos++; + Administrador admin = new Administrador(administrador); + if (isVazia()) + primeiro = admin; + else + ultimo.setProx( admin); + this.ultimo = admin; + } + + + public void imprimir() { + if (this.numero_elementos == 0) + System.out.print("[]"); + else { + System.out.print("["); + Administrador aux = this.primeiro; + for(int i=0; i < this.numero_elementos-1;i++) { + System.out.print(aux.getCpf()+' '); + aux = aux.getProx(); + } + System.out.print(aux.getCpf()+"]"); + + + + } + } + + public Administrador procurar(String cpf){ //Sistema de busca retornando um objeto + Administrador aux = new Administrador(this.primeiro); + + if (aux.getCpf().equals(cpf)) { + return primeiro; + } + else { + for(int i=0; i <= numero_elementos - 1;i++) { + if (aux.getProx().getCpf().equals(cpf)) { + return aux.getProx(); + } + else + aux = aux.getProx(); + + + + + } + + } + return null; + } + + + public void remover(String cpf){ //Excluir um objeto da lista + Administrador aux, auxAnterior = new Administrador(); //Auxiliar, vai servir de apontador + aux = this.primeiro; + auxAnterior = null; + + + if (this.primeiro.getCpf().equals(cpf)) { + this.primeiro = primeiro.getProx(); + this.numero_elementos--; + + } + else { + while (aux !=null && aux.getCpf() != cpf) { + auxAnterior = aux; + aux = ((Administrador) aux).getProx(); + } + if(aux != null) { + ((Administrador) auxAnterior).setProx(aux.getProx()); + this.numero_elementos--; + } + if(aux == ultimo) { + ultimo = auxAnterior; + } + + + } + + + } + @Override + public IteratorClasse iterator() { + return null; + } + + public void atualizar(Administrador pessoa) { + + + procurar(pessoa.getCpf()).setContato(pessoa.getContato()); + procurar(pessoa.getCpf()).setNome(pessoa.getNome()); + procurar(pessoa.getCpf()).setSenha(pessoa.getSenha()); + + } +/* + public static void main(String...arguments) { + RepAdmLista lista = new RepAdmLista(); + + Administrador teste = new Administrador("Paulo", "1", "444", null); + Administrador teste2 = new Administrador("Fera", "2", "555", null); + Administrador testeAtualiza = new Administrador("Fabio", "2", "444", null); + + lista.adicionar(teste); + lista.adicionar(teste2); + + lista.imprimir(); + + System.out.print(lista.procurar("2").getNome()); + + lista.atualizar(testeAtualiza); + + System.out.print(lista.procurar("2").getNome()); + + lista.imprimir(); + } + */ + +} + + + diff --git a/example-apps/src/ip/repositorio/RepClienteArquivo.java b/example-apps/src/ip/repositorio/RepClienteArquivo.java new file mode 100644 index 0000000..534ff89 --- /dev/null +++ b/example-apps/src/ip/repositorio/RepClienteArquivo.java @@ -0,0 +1,201 @@ +package dados.repositorio; + +import dados.interfaces.IRepositorioCliente; +import dados.entidade.Cliente; +import dados.IteratorClasse; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Vector; + + + +public class RepClienteArquivo implements IRepositorioCliente{ + + private Vector vetorClientes; + + + @SuppressWarnings({ "unchecked", "resource" }) + public RepClienteArquivo() throws IOException { + this.vetorClientes = new Vector(); + + File arquivo = new File("arquivoCliente.txt"); + if (!arquivo.exists()) { + arquivo.createNewFile(); + } + if (arquivo.length() != 0) { + ObjectInputStream reader = null; + try { + FileInputStream fileInput = new FileInputStream("arquivoCliente.txt"); + + reader = new ObjectInputStream(fileInput); + this.vetorClientes = (Vector) reader.readObject(); + } catch (ClassNotFoundException e) { + } + } + } + + public void adicionar(Cliente cliente) { + this.vetorClientes.add(cliente); + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoCliente.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorClientes); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + } catch (IOException e) { + } + } + } + + public void remover(String cpf) { + for (int i = 0; i < this.vetorClientes.size(); i++) { + if (this.vetorClientes.elementAt(i).getContato() == null) { + + } + else if (this.vetorClientes.elementAt(i).getCpf().equals(cpf)) { + this.vetorClientes.remove(i); + } + } + + ObjectOutputStream gravar = null; + + FileOutputStream writer; + try { + writer = new FileOutputStream("arquivoCliente.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorClientes); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + } finally { + try { + gravar.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("unchecked") + public Cliente procurar(String cpf) { + + //Cria um objeto FileInputStream + FileInputStream fileStream; + int indiceAchado = 0; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoCliente.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + + this.vetorClientes = (Vector) os.readObject(); + for (int indice = 0; indice < vetorClientes.size(); indice++) { + if (this.vetorClientes.elementAt(indice).getCpf().equals(cpf)) { + indiceAchado = indice; + //System.out.print(indiceAchado); + } + + + + } + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + return this.vetorClientes.elementAt(indiceAchado); + + } + //O método atualizar é basicamente feito o procurar, porém depois que ele atualiza um elemento + //Ele deve re-serializar tudo + @SuppressWarnings("unchecked") + public void atualizar(Cliente cliente){ + FileInputStream fileStream; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoCliente.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + //Deserializa o vector e verifica se o cpf do elemento é igual + //O cpf do objeto, atualiza e re-serializa. + int indiceAchado = 0; + this.vetorClientes = (Vector) os.readObject(); + for (int indice = 0; indice < vetorClientes.size(); indice++) { + if (this.vetorClientes.elementAt(indice).getCpf().equals(cliente.getCpf())) { + indiceAchado = indice; + //System.out.print(indiceAchado); + this.vetorClientes.elementAt(indiceAchado).setContato(cliente.getContato()); + this.vetorClientes.elementAt(indiceAchado).setNome(cliente.getNome()); + this.vetorClientes.elementAt(indiceAchado).setSenha(cliente.getSenha()); + + } + + + } + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoCliente.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorClientes); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + + } catch (IOException e) { + } + } + + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + + + } + + + + public IteratorClasse iterator() { + Vector listClientes = new Vector(); + for (int i = 0; i < this.vetorClientes.size(); i++) { + listClientes.add(this.vetorClientes.elementAt(i)); + } + IteratorClasse iterator = new IteratorClasse(listClientes); + return iterator; + } + +} diff --git a/example-apps/src/ip/repositorio/RepClienteArray.java b/example-apps/src/ip/repositorio/RepClienteArray.java new file mode 100644 index 0000000..028b45b --- /dev/null +++ b/example-apps/src/ip/repositorio/RepClienteArray.java @@ -0,0 +1,92 @@ +package dados.repositorio; + +import java.util.Vector; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioCliente; +import dados.entidade.Cliente; + +@SuppressWarnings("rawtypes") +public class RepClienteArray implements IRepositorioCliente, Iterable { + + private Cliente[] clientes; + private int indice; + + public RepClienteArray() { + this.clientes = new Cliente[1000]; + this.indice = 0; + } + + public boolean isVazia() { + if (indice == 0 && clientes[0].equals(null)) + return true; + return false; + } + + public void imprimir() { + for(int i = 0; i < indice; i++) { + System.out.println(clientes[i].getCpf() + " - " + clientes[i].getNome()); + } + + } + + public void adicionar(Cliente cliente) { + if (this.indice < this.clientes.length) { + clientes[this.indice] = cliente; + this.indice++; + } else { + Cliente[] auxiliar = new Cliente[this.clientes.length * 2]; + for (int i = 0; i < this.clientes.length; i++) { + auxiliar[i] = this.clientes[i]; + } + this.clientes = auxiliar; + this.adicionar(cliente); + } + } + + public void remover(String cpf) { + for(int i = 0; i < indice; i++) { + if(clientes[i].getCpf().equals(cpf)) { + clientes[i] = clientes[indice - 1]; + indice--; + } + } + } + + public Cliente procurar(String cpf) { + for(int i = 0; i < indice; i++) { + if(clientes[i].getCpf().equals(cpf)) + return clientes[i]; + } + + return null; + } + + public void sort() { + + for (int i = 0; i < indice - 1; ++i) { + for (int j = i + 1; j < indice; ++j) { + if (clientes[i].getCpf().compareTo(clientes[j].getCpf()) > 0) { + Cliente aux = clientes[i]; + clientes[i] = clientes[j]; + clientes[j] = aux; + } + } + } + + } + + public void atualizar(Cliente cliente) { + + } + + public IteratorClasse iterator() { + Vector listCli = new Vector(); + for(int i = 0; i < indice; i++) { + listCli.add(this.clientes[i]); + } + + IteratorClasse iterator = new IteratorClasse(listCli); + return iterator; + } +} \ No newline at end of file diff --git a/example-apps/src/ip/repositorio/RepClienteLista.java b/example-apps/src/ip/repositorio/RepClienteLista.java new file mode 100644 index 0000000..34161c2 --- /dev/null +++ b/example-apps/src/ip/repositorio/RepClienteLista.java @@ -0,0 +1,147 @@ +package dados.repositorio; + + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioCliente; +import dados.entidade.Cliente; +import dados.entidade.Pessoa; + +public class RepClienteLista implements IRepositorioCliente { + + + + int numero_elementos; //Só pra saber se a lista esta vazia e tb o num. de el. + Pessoa primeiro = new Cliente(); //O primeiro elemento da lista vai ser o do final, o �ltimo adicionado + Pessoa ultimo = new Cliente(); //O ultimo da lista sempre vai apontar pra null + + public RepClienteLista() { + this.numero_elementos = 0; + this.primeiro = null; + this.ultimo = null; + + } + //LISTA ENCADEADA + + public boolean isVazia() { + return (primeiro == null && ultimo == null); + } + + public void adicionar(Cliente pessoa) { + /*Qnd vc adiciona 1 elemento a lista, cria-se um objeto cliente + *e a esse objeto vai ser atribu�do o valor de primeiro, que na verdade + *vai se tornar o elemento depois do primeiro. E o novo primeiro, vai ser + *cliente, que � o objeto criado. + */ + Pessoa cliente = new Cliente((Cliente) pessoa); + if (isVazia()) { + this.primeiro = cliente; + this.ultimo = cliente; + + } + else { + ((Cliente) cliente).setProx((Cliente) this.primeiro); + } + this.primeiro = cliente; + numero_elementos++; + } + + public void adicionarNoFinal(Pessoa pessoa) { + this.numero_elementos++; + Pessoa cliente = new Cliente((Cliente) pessoa); + if (isVazia()) + primeiro = cliente; + else + ((Cliente) ultimo).setProx((Cliente) cliente); + this.ultimo = cliente; + } + + + public void imprimir() { + if (this.numero_elementos == 0) + System.out.print("[]"); + else { + System.out.print("["); + Pessoa aux = this.primeiro; + for(int i=0; i < this.numero_elementos-1;i++) { + System.out.print(aux.getCpf()+' '); + aux = ((Cliente)aux).getProx(); + } + System.out.print(((Cliente)aux).getCpf()+"]"); + + + + } + } + + public Cliente procurar(String cpf){ //Sistema de busca retornando um objeto + Pessoa aux = new Cliente((Cliente) this.primeiro); + + if (((Cliente)aux).getCpf().equals(cpf)) { + return (Cliente) primeiro; + } + else { + for(int i=0; i <= numero_elementos - 1;i++) { + if (((Cliente)aux).getProx().getCpf().equals(cpf)) { + return ((Cliente)aux).getProx(); + } + else + aux = ((Cliente)aux).getProx(); + + + + + } + + } + return null; + } + + + public void remover(String cpf){ //Excluir um objeto da lista + Pessoa aux, auxAnterior = new Cliente(); //Auxiliar, vai servir de apontador + aux = this.primeiro; + auxAnterior = null; + + + if (this.primeiro.getCpf().equals(cpf)) { + this.primeiro = ((Cliente) primeiro).getProx(); + this.numero_elementos--; + + } + else { + while (aux !=null && !aux.getCpf().equals(cpf)) { + auxAnterior = aux; + aux = ((Cliente) aux).getProx(); + } + if(aux != null) { + ((Cliente) auxAnterior).setProx(((Cliente) aux).getProx()); + this.numero_elementos--; + } + if(aux == ultimo) { + ultimo = auxAnterior; + } + + + } + + + } + + public void atualizar(Cliente pessoa) { + + + procurar(pessoa.getCpf()).setContato(pessoa.getContato()); + procurar(pessoa.getCpf()).setNome(pessoa.getNome()); + procurar(pessoa.getCpf()).setSenha(pessoa.getSenha()); + + } + + @Override + public IteratorClasse iterator() { + // TODO Auto-generated method stub + return null; + } + + + +} diff --git a/example-apps/src/ip/repositorio/RepPedidoArquivo.java b/example-apps/src/ip/repositorio/RepPedidoArquivo.java new file mode 100644 index 0000000..660e086 --- /dev/null +++ b/example-apps/src/ip/repositorio/RepPedidoArquivo.java @@ -0,0 +1,206 @@ +package dados.repositorio; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Vector; + +import dados.IteratorClasse; +import dados.entidade.Pedido; +import dados.interfaces.IRepositorioPedido; + +public class RepPedidoArquivo implements IRepositorioPedido { + + private Vector vetorPedidos; + + @SuppressWarnings({ "unchecked", "resource" }) + public RepPedidoArquivo() throws IOException { + this.vetorPedidos = new Vector(); + + File arquivo = new File("arquivoPedido.txt"); + if (!arquivo.exists()) { + arquivo.createNewFile(); + } + if (arquivo.length() != 0) { + ObjectInputStream reader = null; + try { + FileInputStream fileInput = new FileInputStream("arquivoPedido.txt"); + + reader = new ObjectInputStream(fileInput); + this.vetorPedidos = (Vector) reader.readObject(); + } catch (ClassNotFoundException e) { + } + } + } + + public void adicionar(Pedido pedido) { + this.vetorPedidos.add(pedido); + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoPedido.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorPedidos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + } catch (IOException e) { + } + } + } + + public void remover(String codigo) { + for (int i = 0; i < this.vetorPedidos.size(); i++) { + if (this.vetorPedidos.elementAt(i).getPreco() == null) { + + } + else if (this.vetorPedidos.elementAt(i).getCodigo().equals(codigo)) { + this.vetorPedidos.remove(i); + } + } + + ObjectOutputStream gravar = null; + + FileOutputStream writer; + try { + writer = new FileOutputStream("arquivoPedido.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorPedidos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + } finally { + try { + gravar.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("unchecked") + public Pedido procurar(String codigo) { + + //Cria um objeto FileInputStream + FileInputStream fileStream; + int indiceAchado = 0; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoPedido.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + + this.vetorPedidos = (Vector) os.readObject(); + for (int indice = 0; indice < vetorPedidos.size(); indice++) { + if (this.vetorPedidos.elementAt(indice).getCodigo().equals(codigo)) { + indiceAchado = indice; + //System.out.print(indiceAchado); + } + + + + } + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + return this.vetorPedidos.elementAt(indiceAchado); + + } + //O método atualizar é basicamente feito o procurar, porém depois que ele atualiza um elemento + //Ele deve re-serializar tudo + @SuppressWarnings("unchecked") + public void atualizar(Pedido pedidosubs){ + FileInputStream fileStream; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoPedido.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + //Deserializa o vector e verifica se o cpf do elemento é igual + //O cpf do objeto, atualiza e re-serializa. + int indiceAchado = 0; + this.vetorPedidos = (Vector) os.readObject(); + for (int indice = 0; indice < vetorPedidos.size(); indice++) { + if (this.vetorPedidos.elementAt(indice).getCodigo().equals(pedidosubs.getCodigo())) { + indiceAchado = indice; + //System.out.print(indiceAchado); + this.vetorPedidos.elementAt(indiceAchado).setCliente(pedidosubs.getCliente()); + this.vetorPedidos.elementAt(indiceAchado).setData(pedidosubs.getData()); + this.vetorPedidos.elementAt(indiceAchado).setPreco(pedidosubs.getPreco()); + this.vetorPedidos.elementAt(indiceAchado).setProdutos(pedidosubs.getProdutos()); + this.vetorPedidos.elementAt(indiceAchado).setQuantidade(pedidosubs.getQuantidade()); + } + + + } + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoPedido.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorPedidos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + + } catch (IOException e) { + } + } + + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + + + } + + + // ObjectOutputStream escreve por cima do arquivo antigo (append false) + public Vector getListaPedidos() { + return this.vetorPedidos; + } + + @Override + public IteratorClasse iterator() { + // TODO Auto-generated method stub + Vector listPedidos = new Vector(); + for (int i = 0; i < this.vetorPedidos.size(); i++) { + listPedidos.add(this.vetorPedidos.elementAt(i)); + } + IteratorClasse iterator = new IteratorClasse(listPedidos); + return iterator; + + } +} \ No newline at end of file diff --git a/example-apps/src/ip/repositorio/RepPedidoArray.java b/example-apps/src/ip/repositorio/RepPedidoArray.java new file mode 100644 index 0000000..98f2c28 --- /dev/null +++ b/example-apps/src/ip/repositorio/RepPedidoArray.java @@ -0,0 +1,110 @@ +package dados.repositorio; + +import java.util.Vector; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioPedido; +import dados.entidade.Pedido; + + +@SuppressWarnings("rawtypes") +public class RepPedidoArray implements IRepositorioPedido, Iterable { + private Pedido[] pedidos; + private int indice; + + public boolean isVazia() { + if (indice == 0 && pedidos[0].equals(null)) + return true; + return false; + } + + public RepPedidoArray() { + pedidos = new Pedido[1000]; + indice = 0; + } + + public void adicionar(Pedido pedido) { + + if(this.indice < this.pedidos.length) { + pedidos[indice] = pedido; + indice++; + } else { + Pedido[] aux = new Pedido[this.pedidos.length * 2]; + for(int i = 0; i < this.indice; i++) { + aux[i] = this.pedidos[i]; + } + + this.pedidos = aux; + this.adicionar(pedido); + } + + } + + public void remover(String codigo) { + for(int i = 0; i < indice; i++) { + if(pedidos[i].getCodigo().equals(codigo)) { + pedidos[i] = null; + if(i < indice - 1 && pedidos[i + 1] != null) { + pedidos[i] = pedidos[i + 1]; + pedidos[i + 1] = null; + } + } + } + + if(pedidos[this.indice - 1] == null) + indice--; + } + + public Pedido procurar(String codigo) { + for(int i = 0; i < indice; i++) { + if(pedidos[i].getCodigo().equals(codigo)) + return pedidos[i]; + } + + return null; + } + + public void imprimir() { + for(int i = 0; i < indice; i++) { + System.out.print(pedidos[i].getCodigo()); + } + + } + + public void atualizar(Pedido pedido) { + for(int i = 0; i < indice; i++) { + if(pedidos[i].getCodigo().equals(pedido.getCodigo())) + pedidos[i] = pedido; + } + } + + public void sort() { + + for (int i = 0; i < indice - 1; ++i) { + for (int j = i + 1; j < indice; ++j) { + if (pedidos[i].getCodigo().compareTo(pedidos[j].getCodigo()) > 0) { + Pedido aux = pedidos[i]; + pedidos[i] = pedidos[j]; + pedidos[j] = aux; + } + } + } + + } + + public IteratorClasse iterator() { + Vector listPedido = new Vector(); + for(int i = 0; i < indice; i++) { + listPedido.add(pedidos[i]); + } + + IteratorClasse iterator = new IteratorClasse(listPedido); + return iterator; + } + + public Pedido[] getLista() { + return this.pedidos; + } + + +} \ No newline at end of file diff --git a/example-apps/src/ip/repositorio/RepPedidoLista.java b/example-apps/src/ip/repositorio/RepPedidoLista.java new file mode 100644 index 0000000..002b1c0 --- /dev/null +++ b/example-apps/src/ip/repositorio/RepPedidoLista.java @@ -0,0 +1,148 @@ +package dados.repositorio; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioPedido; +import dados.entidade.Pedido; + + +public class RepPedidoLista implements IRepositorioPedido{ + + int numero_elementos; //Só pra saber se a lista esta vazia e tb o num. de el. + Pedido primeiro = new Pedido(); //O primeiro elemento da lista vai ser o do final, o �ltimo adicionado + Pedido ultimo = new Pedido(); //O ultimo da lista sempre vai apontar pra null + + public RepPedidoLista() { + this.numero_elementos = 0; + this.primeiro = null; + this.ultimo = null; + + } + //LISTA ENCADEADA + + public boolean isVazia() { + return (primeiro == null && ultimo == null); + } + + public void adicionar(Pedido produto) { + /*Qnd vc adiciona 1 elemento a lista, cria-se um objeto pedido + *e a esse objeto vai ser atribu�do o valor de primeiro, que na verdade + *vai se tornar o elemento depois do primeiro. E o novo primeiro, vai ser + *pedido, que � o objeto criado. + */ + Pedido pedido = new Pedido(produto); + if (isVazia()) { + this.primeiro = pedido; + this.ultimo = pedido; + + } + else { + ((Pedido) pedido).setProx((Pedido) this.primeiro); + } + this.primeiro = pedido; + numero_elementos++; + } + + public void inserirNoFinal(Pedido produto) { + this.numero_elementos++; + Pedido pedido = new Pedido(produto); + if (isVazia()) + primeiro = pedido; + else + ((Pedido) ultimo).setProx((Pedido) pedido); + this.ultimo = pedido; + } + + + public void imprimir() { + if (this.numero_elementos == 0) + System.out.print("[]"); + else { + System.out.print("["); + Pedido aux = this.primeiro; + for(int i=0; i < this.numero_elementos-1;i++) { + System.out.print(aux.getCodigo()+' '); + aux = ((Pedido)aux).getProx(); + } + System.out.print(((Pedido)aux).getCodigo()+"]"); + + + + } + } + + public Pedido procurar(String codigo){ //Sistema de busca retornando um objeto + Pedido aux = new Pedido(this.primeiro); + + if (((Pedido)aux).getCodigo().equals(codigo)) { + return primeiro; + } + else { + for(int i=0; i <= numero_elementos - 1;i++) { + if (((Pedido)aux).getProx().getCodigo().equals(codigo)) { + return ((Pedido)aux).getProx(); + } + else + aux = ((Pedido)aux).getProx(); + + + + + } + + } + return null; + } + + + public void remover(String codigo){ //Excluir um objeto da lista + Pedido aux, auxAnterior = new Pedido(); //Auxiliar, vai servir de apontador + aux = this.primeiro; + auxAnterior = null; + + + if (this.primeiro.getCodigo().equals(codigo)) { + this.primeiro = ((Pedido) primeiro).getProx(); + this.numero_elementos--; + + } + else { + while (aux !=null && !aux.getCodigo().equals(codigo)) { + auxAnterior = aux; + aux = ((Pedido) aux).getProx(); + } + if(aux != null) { + ((Pedido) auxAnterior).setProx(((Pedido) aux).getProx()); + this.numero_elementos--; + } + if(aux == ultimo) { + ultimo = auxAnterior; + } + + + } + + + } + + + @Override + public IteratorClasse iterator() { + // TODO Auto-generated method stub + return null; + } + + public void atualizar(Pedido produto) { + + + procurar(produto.getCodigo()).setCliente(produto.getCliente()); + procurar(produto.getCodigo()).setData(produto.getData()); + procurar(produto.getCodigo()).setPreco(produto.getPreco()); + procurar(produto.getCodigo()).setQuantidade(produto.getQuantidade()); + procurar(produto.getCodigo()).setProdutos(produto.getProdutos()); + } + + + + + +} \ No newline at end of file diff --git a/example-apps/src/ip/repositorio/RepProdutoArquivo.java b/example-apps/src/ip/repositorio/RepProdutoArquivo.java new file mode 100644 index 0000000..821eff1 --- /dev/null +++ b/example-apps/src/ip/repositorio/RepProdutoArquivo.java @@ -0,0 +1,200 @@ +package dados.repositorio; + +import dados.interfaces.IRepositorioProduto; +import dados.entidade.Produto; +import dados.IteratorClasse; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Vector; + + + +public class RepProdutoArquivo implements IRepositorioProduto{ + + private Vector vetorProdutos; + + + @SuppressWarnings({ "unchecked", "resource" }) + public RepProdutoArquivo() throws IOException { + this.vetorProdutos = new Vector(); + + File arquivo = new File("arquivoProduto.txt"); + if (!arquivo.exists()) { + arquivo.createNewFile(); + } + if (arquivo.length() != 0) { + ObjectInputStream reader = null; + try { + FileInputStream fileInput = new FileInputStream("arquivoProduto.txt"); + + reader = new ObjectInputStream(fileInput); + this.vetorProdutos = (Vector) reader.readObject(); + } catch (ClassNotFoundException e) { + } + } + } + + public void adicionar(Produto produto) { + this.vetorProdutos.add(produto); + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoProduto.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorProdutos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + } catch (IOException e) { + } + } + } + + public void remover(String cpf) { + for (int i = 0; i < this.vetorProdutos.size(); i++) { + if (this.vetorProdutos.elementAt(i).getPreco() == null) { + + } + else if (this.vetorProdutos.elementAt(i).getCodigo().equals(cpf)) { + this.vetorProdutos.remove(i); + } + } + + ObjectOutputStream gravar = null; + + FileOutputStream writer; + try { + writer = new FileOutputStream("arquivoProduto.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorProdutos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + } finally { + try { + gravar.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("unchecked") + public Produto procurar(String cpf) { + + //Cria um objeto FileInputStream + FileInputStream fileStream; + int indiceAchado = 0; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoProduto.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + + this.vetorProdutos = (Vector) os.readObject(); + for (int indice = 0; indice < vetorProdutos.size(); indice++) { + if (this.vetorProdutos.elementAt(indice).getCodigo().equals(cpf)) { + indiceAchado = indice; + //System.out.print(indiceAchado); + } + + + + } + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + return this.vetorProdutos.elementAt(indiceAchado); + + } + //O método atualizar é basicamente feito o procurar, porém depois que ele atualiza um elemento + //Ele deve re-serializar tudo + @SuppressWarnings("unchecked") + public void atualizar(Produto produtosubs){ + FileInputStream fileStream; + ObjectInputStream os = null; + try { + fileStream = new FileInputStream("arquivoProduto.txt"); + //Cria um ObjectInputStream + os = new ObjectInputStream(fileStream); + //Deserializa o vector e verifica se o cpf do elemento é igual + //O cpf do objeto, atualiza e re-serializa. + int indiceAchado = 0; + this.vetorProdutos = (Vector) os.readObject(); + for (int indice = 0; indice < vetorProdutos.size(); indice++) { + if (this.vetorProdutos.elementAt(indice).getCodigo().equals(produtosubs.getCodigo())) { + indiceAchado = indice; + //System.out.print(indiceAchado); + this.vetorProdutos.elementAt(indiceAchado).setDescricao(produtosubs.getDescricao()); + this.vetorProdutos.elementAt(indiceAchado).setNome(produtosubs.getNome()); + this.vetorProdutos.elementAt(indiceAchado).setPreco(produtosubs.getPreco()); + + } + + + } + ObjectOutputStream gravar = null; + + try { + + FileOutputStream writer = new FileOutputStream("arquivoProduto.txt", false); + gravar = new ObjectOutputStream(writer); + gravar.writeObject(this.vetorProdutos); + gravar.flush(); + } catch (FileNotFoundException e) { + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + gravar.close(); + + } catch (IOException e) { + } + } + + } catch (FileNotFoundException e) { + } catch (IOException ex) { + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + finally { + try { + os.close(); + } catch (IOException e) { + } + + } + + + } + + + + public IteratorClasse iterator() { + Vector listProdutos = new Vector(); + for (int i = 0; i < this.vetorProdutos.size(); i++) { + listProdutos.add(this.vetorProdutos.elementAt(i)); + } + IteratorClasse iterator = new IteratorClasse(listProdutos); + return iterator; + } +} \ No newline at end of file diff --git a/example-apps/src/ip/repositorio/RepProdutoArray.java b/example-apps/src/ip/repositorio/RepProdutoArray.java new file mode 100644 index 0000000..b1e9cf0 --- /dev/null +++ b/example-apps/src/ip/repositorio/RepProdutoArray.java @@ -0,0 +1,107 @@ +package dados.repositorio; + +import java.util.Vector; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioProduto; +import dados.entidade.Produto; + +@SuppressWarnings("rawtypes") +public class RepProdutoArray implements IRepositorioProduto, Iterable { + + + private Produto[] produtos; + private int indice; + + public boolean isVazia() { + if (indice == 0 && produtos[0].equals(null)) + return true; + return false; + } + + public RepProdutoArray() { + produtos = new Produto[2000]; + indice = 0; + } + + public void adicionar(Produto produto) { + if(this.indice < this.produtos.length) { + produtos[indice] = produto; + indice++; + } else { + Produto[] aux = new Produto[this.produtos.length * 2]; + for(int i = 0; i < indice; i++) { + aux[i] = produtos[i]; + } + + this.produtos = aux; + this.adicionar(produto); + + + } + } + + + public void remover(String codigo) { + for(int i = 0; i < indice; i++) { + if(produtos[i].getCodigo().equals(codigo)) { + produtos[i] = null; + if(i < indice - 1 && produtos[i + 1] != null) { + produtos[i] = produtos[i + 1]; + produtos[i + 1] = null; + } + } + } + + if(produtos[this.indice - 1] == null) + indice--; + } + + public Produto procurar(String codigo) { + for(int i = 0; i < indice; i++) { + if(produtos[i].getCodigo().equals(codigo)) + return produtos[i]; + } + + return null; + } + + public void atualizar(Produto produto) { + for(int i = 0; i < indice; i++) { + if(produtos[i].getCodigo().equals(produto.getCodigo())) + produtos[i] = produto; + } + } + + public void imprimir() { + for(int i = 0; i < indice; i++) { + System.out.print(produtos[i].getCodigo()); + } + + } + + public void sort() { + + for (int i = 0; i < indice - 1; ++i) { + for (int j = i + 1; j < indice; ++j) { + if (produtos[i].getCodigo().compareTo(produtos[j].getCodigo()) > 0) { + Produto aux = produtos[i]; + produtos[i] = produtos[j]; + produtos[j] = aux; + } + } + } + + } + public IteratorClasse iterator() { + Vector listProd = new Vector(); + for(int i = 0; i < indice; i++) { + listProd.add(produtos[i]); + } + + IteratorClasse iterator = new IteratorClasse(listProd); + return iterator; + } +} + + \ No newline at end of file diff --git a/example-apps/src/ip/repositorio/RepProdutoLista.java b/example-apps/src/ip/repositorio/RepProdutoLista.java new file mode 100644 index 0000000..2874c1d --- /dev/null +++ b/example-apps/src/ip/repositorio/RepProdutoLista.java @@ -0,0 +1,150 @@ +package dados.repositorio; + +import dados.IteratorClasse; +import dados.interfaces.IRepositorioProduto; +import dados.entidade.Livro; +import dados.entidade.Produto; + + + +public class RepProdutoLista implements IRepositorioProduto{ + + int numero_elementos; //Só pra saber se a lista esta vazia e tb o num. de el. + Produto primeiro = new Livro(); //O primeiro elemento da lista vai ser o do final, o �ltimo adicionado + Produto ultimo = new Livro(); //O ultimo da lista sempre vai apontar pra null + + public RepProdutoLista() { + this.numero_elementos = 0; + this.primeiro = null; + this.ultimo = null; + + } + //LISTA ENCADEADA + + public boolean isVazia() { + return (primeiro == null && ultimo == null); + } + + public void adicionar(Produto produto) { + /*Qnd vc adiciona 1 elemento a lista, cria-se um objeto livro + *e a esse objeto vai ser atribu�do o valor de primeiro, que na verdade + *vai se tornar o elemento depois do primeiro. E o novo primeiro, vai ser + *livro, que � o objeto criado. + */ + Produto livro = new Livro(produto); + if (isVazia()) { + this.primeiro = livro; + this.ultimo = livro; + + } + else { + ((Livro) livro).setProx((Livro) this.primeiro); + } + this.primeiro = livro; + numero_elementos++; + } + + public void inserirNoFinal(Produto produto) { + this.numero_elementos++; + Produto livro = new Livro(produto); + if (isVazia()) + primeiro = livro; + else + ((Livro) ultimo).setProx((Livro) livro); + this.ultimo = livro; + } + + + public void imprimir() { + if (this.numero_elementos == 0) + System.out.print("[]"); + else { + System.out.print("["); + Produto aux = this.primeiro; + for(int i=0; i < this.numero_elementos-1;i++) { + System.out.print(aux.getCodigo()+' '); + aux = ((Livro)aux).getProx(); + } + System.out.print(((Livro)aux).getCodigo()+"]"); + + + + } + } + + public Produto procurar(String codigo){ //Sistema de busca retornando um objeto + Produto aux = new Livro(this.primeiro); + + if (((Livro)aux).getCodigo().equals(codigo)) { + return primeiro; + } + else { + for(int i=0; i <= numero_elementos - 1;i++) { + if (((Livro)aux).getProx().getCodigo().equals(codigo)) { + return ((Livro)aux).getProx(); + } + else + aux = ((Livro)aux).getProx(); + + + + + } + + } + return null; + } + + + public void remover(String codigo){ //Excluir um objeto da lista + Produto aux, auxAnterior = new Livro(); //Auxiliar, vai servir de apontador + aux = this.primeiro; + auxAnterior = null; + + + if (this.primeiro.getCodigo().equals(codigo)) { + this.primeiro = ((Livro) primeiro).getProx(); + this.numero_elementos--; + + } + else { + while (aux !=null && !aux.getCodigo().equals(codigo)) { + auxAnterior = aux; + aux = ((Livro) aux).getProx(); + } + if(aux != null) { + ((Livro) auxAnterior).setProx(((Livro) aux).getProx()); + this.numero_elementos--; + } + if(aux == ultimo) { + ultimo = auxAnterior; + } + + + } + + + } + + + @Override + public IteratorClasse iterator() { + // TODO Auto-generated method stub + return null; + } + + public void atualizar(Produto produto) { + + + procurar(produto.getCodigo()).setDescricao(produto.getDescricao()); + procurar(produto.getCodigo()).setNome(produto.getNome()); + procurar(produto.getCodigo()).setPreco(produto.getPreco()); + + + } + + + + + +} \ No newline at end of file diff --git a/example-apps/src/ip/testes/Teste.java b/example-apps/src/ip/testes/Teste.java new file mode 100644 index 0000000..2c6f730 --- /dev/null +++ b/example-apps/src/ip/testes/Teste.java @@ -0,0 +1,103 @@ +package testes; + +import java.io.IOException; +import dados.excel.exception.CellNumberFormatException; +import dados.excel.exception.CellStringFormatException; +import dados.excel.exception.IOExcelException; +import dados.excel.exception.SheetNotFoundException; +import exceptions.CampoNaoPreenchidoException; +import exceptions.CodigoInvalidoException; +import exceptions.NomeInvalidoException; +import exceptions.TipoRepositorioInvalidoException; +import exceptions.administrador.AdmNaoEncontradoException; +import exceptions.administrador.CpfInvalidoException; +import exceptions.administrador.CpfJaExisteException; +import exceptions.administrador.TelefoneInvalidoException; +import exceptions.administrador.TelefoneJaExisteException; +import exceptions.cliente.BairroInvalidoException; +import exceptions.cliente.CidadeInvalidaException; +import exceptions.cliente.ClienteNaoEncontradoException; +import exceptions.cliente.EstadoInvalidoException; +import exceptions.pedido.DataInvalidaException; +import exceptions.pedido.DatasInvalidasException; +import exceptions.pedido.PedidoInvalidoException; +import exceptions.pedido.PedidoNaoEncontradoException; +import exceptions.produto.AnoInvalidoException; +import exceptions.produto.ProdutoNaoEncontradoException; +import exceptions.produto.ValorInvalidoException; +import fachada.Fachada; + +public class Teste { + + public static void main(String[] args) throws IOException, TipoRepositorioInvalidoException, IOExcelException, SheetNotFoundException, CellStringFormatException, CellNumberFormatException, PedidoNaoEncontradoException, CpfJaExisteException, CpfInvalidoException, TelefoneInvalidoException, TelefoneJaExisteException, DatasInvalidasException, AnoInvalidoException, exceptions.cliente.CpfInvalidoException, exceptions.cliente.TelefoneInvalidoException, CampoNaoPreenchidoException, exceptions.cliente.CpfJaExisteException, exceptions.cliente.TelefoneJaExisteException, NomeInvalidoException, BairroInvalidoException, CidadeInvalidaException, EstadoInvalidoException, ClienteNaoEncontradoException, ProdutoNaoEncontradoException, PedidoInvalidoException, ValorInvalidoException, CodigoInvalidoException, AdmNaoEncontradoException, DataInvalidaException { + Fachada fachada = null; + try { + fachada = new Fachada(); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (TipoRepositorioInvalidoException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOExcelException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (SheetNotFoundException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (CellStringFormatException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (CellNumberFormatException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + String cpf = "111.111.111-11"; + String telefone = "1111-1111"; + String nome = "Jose"; + String logradouro = "Rua"; + String numero = "10"; + String complemento = "Casa"; + String bairro = "Barro"; + String cidade = "cidade"; + String senha = "123123"; + String uf = "pe"; + String codigo = "1"; + String[] codigosProdutos = {"1"}; + String descricao = "Issae"; + String nomeLivro = "nomeLivro"; + String nomeAutor = "nomeAutor"; + String editora = "ufpe"; + String anoPublicacao = "2010"; + String preco = "33.10"; + + + fachada.adicionarAdministrador(cpf, telefone, nome, logradouro, numero, complemento, bairro, cidade, senha, uf); + fachada.adicionarCliente(cpf, telefone, nome, logradouro, numero, complemento, bairro, cidade, senha, uf); + fachada.adicionarProduto(codigo, nomeLivro, descricao, preco, nomeAutor, editora, anoPublicacao); + fachada.adicionarPedido(cpf, codigosProdutos); + fachada.buscarProdutoParteCodigo(codigo); + fachada.cancelarPedido(codigo); + String dataInicialStr = "12/04/2010"; + String dataFinalStr = "16/04/2013"; + String nomeAdm = "nomeAdm"; + fachada.fazerRelatorioAdm(nomeAdm); + String nomeCliente = "nomeCliente"; + fachada.fazerRelatorioCliente(dataInicialStr, dataFinalStr, nomeCliente); + String codigoProduto = "431232"; + fachada.fazerRelatorioProduto(dataInicialStr, dataFinalStr, codigoProduto); //fazerRelatorioProduto e Cliente jogam exceção sobre Data Invalida, mas geram os relatorios com um certo delay. + fachada.visualizarAdministradores(nome); + fachada.visualizarClientes(nome); + fachada.visualizarPedidos(dataInicialStr, dataFinalStr); + fachada.visualizarProdutos(nome); + fachada.removerAdm(cpf); + fachada.removerCliente(cpf); + fachada.removerProduto(codigo); + + } + +} diff --git a/example-apps/src/logicaProj/logica/Arquivo.java b/example-apps/src/logicaProj/logica/Arquivo.java new file mode 100644 index 0000000..7612ff3 --- /dev/null +++ b/example-apps/src/logicaProj/logica/Arquivo.java @@ -0,0 +1,450 @@ +package logica; + +/* + * Universidade Federal de Pernambuco + * Centro de Informática + * Disciplina: Algoritmos e Estrutura de Dados + * + */ +import java.io.*; + +/** + * Classe que manipula a entrada e saída de dados de um programa através de + * arquivos.

+ * + * Exemplo de Uso:

+ * + * // Abre os arquivos de entrada e saída
+ * Arquivo io = new Arquivo("L1Q1.in", "L1Q1.out");

+ * + * // Lê dados do arquivo de entrada
+ * String s = io.readString();
+ * char c = io.readChar();
+ * int i = io.readInt();
+ * double d = io.readDouble();

+ * + * // Grava dados no arquivo de saída
+ * io.print("Algoritmos");
+ * io.print(35);
+ * io.println(2.3);

+ * + * // Fecha o arquivo após o uso
+ * io.close();
+ * + * @author Emannuel Macêdo (egm@cin.ufpe.br) + * + */ + +public class Arquivo { + + private BufferedReader in; + private PrintWriter out; + private String[] buffer; + private int nextChar; + private int nextTokenLin, nextTokenCol; + private int primLin, contLin; + + /** + * Construtor da classe Arquivo. Abre o arquivo de entrada no modo leitura, + * e o arquivo de saída no modo gravação. Se o arquivo de saída já existir, + * seu conteúdo é descartado. + * + * @param in nome do arquivo de entrada de dados + * @param out nome do arquivo de saída de dados + * + */ + public Arquivo(String in, String out) { + try { + // abre o arquivo de entrada no modo leitura + this.in = new BufferedReader(new FileReader(in)); + + // abre o arquivo de saída no modo gravação + this.out = new PrintWriter(new FileWriter(out), true); + + this.initBuffer(); + + } catch (IOException e) { + throw new RuntimeException(e.toString()); + } + } + + /** Fecha o arquivo quando o garbage collector é chamado */ + protected void finalize() { + this.close(); + } + + /** Fecha o arquivo, após o seu uso. */ + public void close() { + try { + if (this.in != null) { + this.in.close(); + this.in = null; + } + + if (this.out != null) { + this.out.close(); + this.out = null; + } + } catch (IOException e) { + throw new RuntimeException(e.toString()); + } + } + + /* -------------------------------------------- */ + /* ------------ FUNÇÕES DE LEITURA ------------ */ + /* -------------------------------------------- */ + + /** Indica se foi encontrado o fim do arquivo. */ + public boolean isEndOfFile() { + return (this.nextTokenLin < 0); + } + + /** Indica se foi encontrado o fim da linha. */ + public boolean isEndOfLine() { + return (this.nextTokenLin != this.primLin); + } + + /** + * Lê uma linha do arquivo. Se parte da linha já foi lida, então o restante + * é retornado, mesmo que seja uma linha em branco (String de tamanho zero). + * + * @return a próxima linha lida do arquivo, ou null se o fim + * do arquivo for encontrado + * + */ + private String readLine() { + if (this.contLin <= 0) + return null; + + String line = this.buffer[this.primLin]; + if (this.nextChar > 0) + if (this.nextChar >= line.length()) + line = ""; + else + line = line.substring(this.nextChar, line.length()-1); + + this.buffer[this.primLin] = null; + this.nextChar = 0; + this.primLin++; + this.contLin--; + + if (this.nextTokenLin >= 0 && this.nextTokenLin < this.primLin) + this.findNext(); + + return line; + } + + /** + * Lê o próximo caractere do arquivo, incluindo espaços (' ') e quebras de + * linha ('\n'). Se o fim do arquivo for alcançado, o caractere nulo ('\0') + * é retornado. + * + * @return o caractere lido + */ + private char readChar() { + if (this.contLin <= 0) + return '\0'; + + char newChar; + String line = this.buffer[this.primLin]; + if (this.nextChar >= line.length()) { + newChar = '\n'; + this.readLine(); + } else { + newChar = line.charAt(this.nextChar++); + if (newChar != ' ' && this.nextTokenLin >= 0) + this.findNext(); + } + + return newChar; + } + + /** + * Lê uma string do arquivo. + * + * @return a string lida + * + */ + public String readString() { + String next = null; + + try { + this.checkEOF(); + + String line = this.buffer[this.nextTokenLin]; + for (int i = this.primLin; i < this.contLin; i++) + this.buffer[i] = null; + this.buffer[0] = line; + this.nextTokenLin = this.primLin = 0; + this.contLin = 1; + + int i, size = line.length(); + for (i = this.nextTokenCol; i < size; i++) + if (line.charAt(i) == ' ') + break; + + next = line.substring(this.nextTokenCol, i); + this.nextChar = i; + this.findNext(); + } catch (IOException e) { + throw new RuntimeException(e.toString()); + } + + return next; + } + + /** + * Lê um inteiro do arquivo. + * + * @return o número lido + * + */ + public int readInt() { + return Integer.valueOf(this.readString()).intValue(); + } + + /** + * Lê um double do arquivo. + * + * @return o número lido + * + */ + public double readDouble() { + return Double.valueOf(this.readString()).doubleValue(); + } + + /* -------------------------------------------- */ + /* ------ FUNÇÕES AUXILIARES DE LEITURA ------- */ + /* -------------------------------------------- */ + + /** Prepara o buffer de entrada para ser usado */ + private void initBuffer() throws IOException { + this.buffer = new String[5]; + this.nextChar = 0; + this.nextTokenLin = 0; + this.primLin = this.contLin = 0; + + String line = this.in.readLine(); + if (line == null) { + this.nextTokenLin = -1; + } else { + this.buffer[0] = line; + this.contLin++; + this.findNext(); + } + } + + /** Verifica se o fim do arquivo foi encontrado */ + private void checkEOF() throws EOFException { + if (this.isEndOfFile()) + throw new EOFException(); + } + + /** Acrescenta uma linha lida do arquivo no buffer */ + private int appendLine(String str) { + if (this.contLin == 0) + this.primLin = 0; + + if (this.primLin + this.contLin >= this.buffer.length) { + String[] src = this.buffer; + if (this.contLin >= this.buffer.length) + this.buffer = new String[2 * this.buffer.length]; + + System.arraycopy(src, this.primLin, this.buffer, 0, this.contLin); + this.nextTokenLin -= this.primLin; + this.primLin = 0; + } + + buffer[this.primLin + this.contLin] = str; + this.contLin++; + return (this.primLin + this.contLin - 1); + } + + /** Encontra a posição do próximo token a ser lido */ + private void findNext() { + try { + String line = this.buffer[this.primLin]; + if (line != null) { + int size = line.length(); + for (int i = this.nextChar; i < size; i++) + if (line.charAt(i) != ' ') { + this.nextTokenCol = i; + return; + } + } + + this.nextTokenLin = this.nextTokenCol = -1; + while ((line = this.in.readLine()) != null) { + int size = line.length(); + for (int i = 0; i < size; i++) + if (line.charAt(i) != ' ') { + this.nextTokenCol = i; + this.nextTokenLin = this.appendLine(line); + return; + } + this.appendLine(line); + } + } catch (IOException e) { + throw new RuntimeException(e.toString()); + } + } + + /* -------------------------------------------- */ + /* ------------ FUNÇÕES DE ESCRITA ------------ */ + /* -------------------------------------------- */ + + /** + * Escreve um caractere no arquivo. + * + * @param c caractere que será escrito no arquivo + * + */ + public void print(char c) { + this.out.print(String.valueOf(c)); + } + + /** + * Escreve uma string no arquivo. + * + * @param s string que será escrita no arquivo + * + */ + public void print(String s) { + this.out.print(s); + } + + /** + * Escreve um inteiro no arquivo. + * + * @param i número que será escrito no arquivo + * + */ + public void print(int i) { + this.out.print(i); + } + + /** + * Escreve um double no arquivo. + * + * @param d número que será escrito no arquivo + * @exception IOException em caso de erro de I/O + * + */ + public void print(double d) { + this.out.print(d); + } + + /** + * Escreve um double no arquivo, com um número fixo de casas decimais. Uma + * precisão menor ou igual a zero indica que apenas a parte inteira será + * impressa (com arredondamento). + * + * @param d número que será escrito no arquivo + * @param dec número de casas decimais de precisao + * @exception IOException em caso de erro de I/O + * + */ + public void print(double d, int dec) { + this.out.print(this.formatDouble(d, dec)); + } + + /** + * Começa uma nova linha no arquivo. + * + */ + public void println() { + this.out.println(); + } + + /** + * Escreve um caractere e começa uma nova linha no arquivo. + * + * @param c caractere que será escrito no arquivo + * + */ + public void println(char c) { + this.out.println(String.valueOf(c)); + } + + /** + * Escreve uma string e começa uma nova linha no arquivo. + * + * @param s string que será gravada no arquivo + * + */ + public void println(String s) { + this.out.println(s); + } + + /** + * Escreve um inteiro e começa uma nova linha no arquivo. + * + * @param i número que será gravado no arquivo + * + */ + public void println(int i) { + this.out.println(i); + } + + /** + * Escreve um double e começa uma nova linha no arquivo. + * + * @param d número que será gravado no arquivo + * @exception IOException em caso de erro de I/O + * + */ + public void println(double d) { + this.out.println(d); + } + + /** + * Escreve um double no arquivo, com um número fixo de casas decimais e + * começa uma nova linha no arquivo. Uma precisão menor ou igual a zero + * indica que apenas a parte inteira será impressa (com arredondamento). + * + * @param d número que será escrito no arquivo + * @param dec número de casas decimais de precisao + * @exception IOException em caso de erro de I/O + * + */ + public void println(double d, int dec) { + this.out.println(this.formatDouble(d, dec)); + } + + /** + * Grava os dados do buffer no arquivo. Isto é feito automaticamente a cada + * quebra de linha (println). + */ + public void flush() { + this.out.flush(); + } + + /* -------------------------------------------- */ + /* ------ FUNÇÕES AUXILIARES DE ESCRITA ------- */ + /* -------------------------------------------- */ + + private String formatDouble(double d, int dec) { + if (dec <= 0) { + return String.valueOf(Math.round(d)); + } + StringBuffer res = new StringBuffer(); + long aprox = (int) Math.round(d * Math.pow(10, dec)); + if (d < 0) { + aprox = -aprox; + res.append('-'); + } + String num = String.valueOf(aprox); + int n = num.length() - dec; + if (n <= 0) { + res.append("0."); + for (int i = 0; i < -n; i++) + res.append('0'); + res.append(num); + } else { + char[] array = num.toCharArray(); + res.append(array, 0, n).append('.').append(array, n, dec); + } + return res.toString(); + } + +} \ No newline at end of file diff --git a/example-apps/src/logicaProj/logica/Exp.java b/example-apps/src/logicaProj/logica/Exp.java new file mode 100644 index 0000000..37650b1 --- /dev/null +++ b/example-apps/src/logicaProj/logica/Exp.java @@ -0,0 +1,310 @@ +package logica; + +import java.util.ArrayList; + +public class Exp +{ + private String exp; + private ArrayList exps; + + Exp(String exp) + { + exps = new ArrayList(); + this.exp = exp; + int n = 0, a = 0; + for (int i = 0; i < exp.length(); i++) + { + if (exp.charAt(i) == '(') + { + if (n == 0 && i > 0) + { + if (!vectorContains(exps, substr(exp, a-1, i - 1 - a))) + exps.add(substr(exp, a, i - 1 - a)); + a = i; + } + n++; + + } + else if (exp.charAt(i) == ')') + { + n--; + if (n == 0 && i == exp.length() - 1) + if (!vectorContains(exps, substr(exp, a, i + 1 - a))) + exps.add(substr(exp, a, i + 1 - a)); + } + } + } + + public void printAll() { + for (int i = 0; i < exps.size(); i++) + { + System.out.println(exps.get(i)); + } + } + + + public static String replace(String str, int comeco, int fim, String substituta) { + StringBuffer sb = new StringBuffer(str); + if (fim+comeco+1 <= str.length()) + sb.replace(comeco, fim+comeco+1, substituta); + else + sb.replace(comeco, str.length(), substituta); + return sb.toString(); + + } + + + public static String substr(String str, int comeco, int fim) { + StringBuffer sb = new StringBuffer(str); + if (fim+comeco+1 <= str.length()) { + if (fim+comeco+1 == str.length()) + return sb.substring(comeco+1, str.length()-1); + else + return sb.substring(comeco+1, comeco+fim-1); + } + else + return sb.substring(comeco+1, str.length()-1); + } + + + boolean vectorContains(ArrayList v, String exp) + { + if (exp.length() < 5) + for (int i = 0; i < v.size(); i++) + if (v.get(i) == exp) + return true; + else + { + for (int l = 0; i < v.size(); i++) + { + boolean b = true; + if (exp.length() == v.get(i).length()) + { + for (int j = 0; j < v.get(i).length(); j++) + { + if (v.get(l).charAt(j) == '+' || v.get(l).charAt(j) == '-' || v.get(l).charAt(j) == '(' || v.get(l).charAt(j) == ')') + continue; + + int found; + if (j != 0 && v.get(i).charAt(j - 1) == '-') + { + found = exp.indexOf("-" + v.get(l).charAt(j)); + if (found == -1) + { + b = false; + break; + } + } + else + { + found = exp.indexOf("+" + v.get(l).charAt(j)); + if (found == -1) + { + found = exp.indexOf("(" + v.get(l).charAt(j)); + if (found == -1) + { + b = false; + break; + } + } + } + + } + if (b) + return true; + } + } + } + return false; + } + + String clearExpression(String exp) + { + + for (int i = 0; i < exp.length(); i++) + { + char c = exp.charAt(i); + + if ((i > 0 && exp.charAt(i - 1) != '-') || c == '(' || c == ')' || c == '+' || c == '-') + continue; + + for (int j = exp.length() - 1; j > 0; j--) + { + while (j > exp.length()) + { + continue; + } + + if ((j > 0 && exp.charAt(j - 1) != '-') || i == j || exp.charAt(j) == '(' || exp.charAt(j) == ')' || exp.charAt(j) == '+' || exp.charAt(j) == '-') + continue; + + + if (c == exp.charAt(j) && exp.charAt(i - 1) == '-' && exp.charAt(j - 1) == '-') + { + + if (j > 1 && exp.charAt(j - 2) == '+') + exp = replace(exp, j - 2, 3, ""); + else + exp = replace(exp, j - 1, 3, ""); + + } + + } + } + + return exp; + } + + void clearExpressions() + { + for (int i = 0; i < exps.size(); i++) + { + exps.set(i, clearExpression(exps.get(i))); + } + } + + boolean isSatisfiable(Arquivo arquivo) + { + clearExpressions(); + + for (int i = 0; i < exps.size(); i++) + { + for (int j = 0; j < exps.get(i).length(); j++) + { + char c = exps.get(i).charAt(j); + if (c == '+' || c == '-' || c == '(' || c == ')') + continue; + + if (j > 0 && exps.get(i).charAt(j - 1) != '-') + continue; + + for (int k = exps.size() - 1; k > 0; k--) + { + if (j == k) + continue; + + for (int l = 0; l < exps.get(k).length(); l++) + { + if (exps.get(k).charAt(l) == '-' || exps.get(k).charAt(l) == '+' || exps.get(k).charAt(l) == '(' || exps.get(k).charAt(l) == ')') + continue; + + if (exps.get(i).charAt(j) == exps.get(k).charAt(l) && l > 0 && exps.get(k).charAt(l - 1) != '-') + { + + String str1 = exps.get(i); + + if (j > 1 && exps.get(i).charAt(j - 2) == '+') + str1 = replace(exp, j - 2, 3, ""); + else + if (exps.get(i).charAt(j + 1) != ')') + str1 = replace(str1, j - 1, 3, ""); + else + str1 = replace(str1, j - 1, 2, ""); + + + String str2 = exps.get(k); + + if (l > 0 && exps.get(k).charAt(l - 1) == '+') + str2 = replace(str2 ,l - 1, 2, ""); + else + if (exps.get(k).charAt(l + 1) != ')') + str2 = replace(str2, l, 2, ""); + else + str2 = replace(str2, l, 1, ""); + + + String str = substr(str1, 0, str1.length() - 1); + if (!(str1.charAt(1) == ')' || str2.charAt(1) == ')')) + str = str + '+'; + str = str + substr(str2, 1, str2.length() - 1); + + str = clearExpression(str); + + + //System.out.println("vetor já contém? " + vectorContains(exps, str) + " | " + str); + if (str != "()" && !vectorContains(exps, str)) + { + exps.add(str); + } + } + } + } + } + } + + + for (int i = 0; i < exps.size(); i++) + { + if (exps.get(i).length() != 3) + continue; + + for (int j = 0; j < exps.size(); j++) + { + if (exps.get(j).length() != 4) + continue; + + if (exps.get(i).charAt(1) == exps.get(j).charAt(2)) + return false; + } + } + + return true; + } + + boolean isInFNC(String exp) + { + int a = 0, p = 0; + for (int i = 1; i < exp.length() - 1; i++) + { + if (exp.charAt(i) == '>' || exp.charAt(i) == '.' || exp.charAt(i) == '(') + return false; + } + + return true; + } + + boolean isInFNC() + { + int n = 0, a = 0; + for (int i = 0; i < exp.length(); i++) + if (exp.charAt(i) == '(') + { + if (n == 0 && i > 0) + { + if (exp.charAt(i - 1) == '>' || exp.charAt(i - 1) == '+') + return false; + a = i; + } + n++; + } + else if (exp.charAt(i) == ')') + n--; + + for (int i = 0; i < exps.size(); i++) + { + if (!isInFNC(exps.get(i))) + return false; + } + return true; + } + + boolean areAllHorn() + { + for (int i = 0; i < exps.size(); i++) + { + int n = 0, a = 1, op = 0; + for (int j = 1; j < exps.get(i).length() - 1; j++) + { + if (exps.get(i).charAt(j) == '>' || exps.get(i).charAt(j) == '.' || exps.get(i).charAt(j) == '+') + op++; + if (exps.get(i).charAt(j) == '-') + n++; + } + + if (!(n >= op)) + return false; + } + + return true; + } +} diff --git a/example-apps/src/logicaProj/logica/Resolucao.java b/example-apps/src/logicaProj/logica/Resolucao.java new file mode 100644 index 0000000..525ae71 --- /dev/null +++ b/example-apps/src/logicaProj/logica/Resolucao.java @@ -0,0 +1,40 @@ +package logica; + +import java.util.ArrayList; + + +public class Resolucao { + + public static void main(String[] args) + { + Arquivo arquivo = new Arquivo("Expressoes.in", "Expressoes.out"); + int n; + String formula; + n = arquivo.readInt(); + for (int i = 0; i < n; i++) + { + formula = ""; + formula = arquivo.readString(); + Exp exp = new Exp(formula); + //exp.printAll(); + + arquivo.print("caso #" + (i + 1) + ": "); + if (!exp.isInFNC()) + { + arquivo.println("nao esta na FNC"); + continue; + } + if (!exp.areAllHorn()) + { + arquivo.println("nem todas as clausulas sao de horn"); + continue; + } + if (exp.isSatisfiable(arquivo)) + arquivo.println("satisfativel"); + else + arquivo.println("insatisfativel"); + } + } + + +} diff --git a/results/readme.txt b/results/readme.txt index 3bcaabd..cad0598 100644 --- a/results/readme.txt +++ b/results/readme.txt @@ -1,2 +1,8 @@ This file is needed so that the results folder is included in the repository. -This folder may contain some application outputs. \ No newline at end of file +This folder may contain some application outputs. + + +NullPointerException, quando rodei o debug na linha 444 do MethodDependencyAnalisys.java ( Set reads = rwSets.get(method).readSet;) está dando ai, ele está pegando um rwSet que fica vazio sempre então dá nullpointer mas não sabemos como resolver ainda +O ultimo erro foi resolvido trocando o prefixo do "app" pra o package que esta a classe, e em vez de pontos transformar em barras + +ex: test.unit.Test.java -> test/unit/ seria o package \ No newline at end of file diff --git a/src-tests/rwsets/AllTests.java b/src-tests/rwsets/AllTests.java index 1c49837..24f9e82 100644 --- a/src-tests/rwsets/AllTests.java +++ b/src-tests/rwsets/AllTests.java @@ -5,9 +5,13 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ - // Add test classes here +// Add test classes here rwsets.coffeemaker.TestCoffeeMaker.class, - rwsets.core.Sanity.class + rwsets.core.Sanity.class, + rwsets.campus.TestCampus.class, + rwsets.ip.TestIp.class, + rwsets.chat.TestChat.class, + rwsets.logicaProj.TestLogica.class }) public class AllTests { } \ No newline at end of file diff --git a/src-tests/rwsets/campus/TestCampus.dot b/src-tests/rwsets/campus/TestCampus.dot new file mode 100644 index 0000000..2afaabd --- /dev/null +++ b/src-tests/rwsets/campus/TestCampus.dot @@ -0,0 +1,13 @@ +digraph "DirectedGraph" { + graph [concentrate = true]; + center=true; + fontsize=6; + node [ color=blue,shape="box"fontsize=6,fontcolor=black,fontname=Arial]; + edge [ color=black,fontsize=6,fontcolor=black,fontname=Arial]; +"boolean globals/Banks.addQuestionGlobal(create/Question)"[color="red", fontsize="6", fontname="Arial"]; +"boolean globals/Banks.addQuestionGlobal(create/Question)" -> "boolean globals/Banks.addQuestionGlobal(create/Question)" [label="int globals/Banks.numberQuestions : 20" ] +"boolean globals/Banks.removeQuestion(java/lang/String)" -> "boolean globals/Banks.addQuestionGlobal(create/Question)" [label="int globals/Banks.numberQuestions : 36" ] +"void globals/Banks.()" -> "boolean globals/Banks.addQuestionGlobal(create/Question)" [label="int globals/Banks.numberQuestions : 11" ] +"void globals/Banks.()" -> "boolean globals/Banks.addQuestionGlobal(create/Question)" [label="java/util/ArrayList globals/Banks.questionBank : 13" ] +"void globals/Banks.()" -> "boolean globals/Banks.hasQuestion(java/lang/String)" [label="java/util/ArrayList globals/Banks.questionBank : 13" ] +} diff --git a/src-tests/rwsets/campus/TestCampus.java b/src-tests/rwsets/campus/TestCampus.java new file mode 100644 index 0000000..de9e798 --- /dev/null +++ b/src-tests/rwsets/campus/TestCampus.java @@ -0,0 +1,66 @@ +package rwsets.campus; + +import japa.parser.ParseException; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; + +import javax.swing.JButton; + +import org.junit.Assert; +import org.junit.Test; + +import rwsets.Helper; + +import com.ibm.wala.shrikeCT.InvalidClassFileException; +import com.ibm.wala.util.CancelException; +import com.ibm.wala.util.WalaException; + +import depend.util.graph.SimpleGraph; + +public class TestCampus { + + String USER_DIR = System.getProperty("user.dir"); + String SEP = System.getProperty("file.separator"); + String EXAMPLES = USER_DIR + SEP + "example-apps"; + String TEST_DIR = USER_DIR + SEP + "src-tests"; + String EXAMPLES_SRC = EXAMPLES + SEP + "src"; + String EXAMPLES_JAR = EXAMPLES; + String RESOURCES_DIR = USER_DIR + SEP + "dat"; + String CAMPUS_JAR = EXAMPLES_JAR + SEP + "campus.jar"; + @Test + public void test0() throws IOException, WalaException, CancelException, ParseException, InvalidClassFileException { + + String strCompUnit = EXAMPLES_SRC + SEP + "campus" + SEP + "globals" + SEP + "Banks.java"; + String campusJar = EXAMPLES_JAR + SEP + "campus.jar"; + + Assert.assertTrue((new File(strCompUnit)).exists()); + Assert.assertTrue((new File(campusJar)).exists()); + + String line = "if (!hasQuestion(question.getTitle())) {"; + SimpleGraph sg = depend.Main.analyze(campusJar, "globals", strCompUnit, line); + + // System.out.println(sg.toDotString()); + + String expectedResultFile = TEST_DIR + SEP + "rwsets/campus/TestCampus.dot"; + Assert.assertEquals(Helper.readFile(expectedResultFile), sg.toDotString()); + } + + @Test + public void testPrimitiveTypeDependency() throws IOException, WalaException, CancelException, ParseException, InvalidClassFileException { + + String strCompUnit = EXAMPLES_SRC + SEP + "campus/application/Application.java"; + Assert.assertTrue((new File(strCompUnit)).exists()); + + String line = "public static ArrayList questionsToSelect = new ArrayList();"; + SimpleGraph sg = depend.Main.analyze(CAMPUS_JAR, "application", strCompUnit, line); + System.out.println(sg.toDotString()); + // check + String expectedResultFile = TEST_DIR + "/rwsets/campus/TestCampus2.dot"; + String expected = Helper.readFile(expectedResultFile); + Assert.assertEquals(expected, sg.toDotString()); + } + + +} \ No newline at end of file diff --git a/src-tests/rwsets/campus/TestCampus2.dot b/src-tests/rwsets/campus/TestCampus2.dot new file mode 100644 index 0000000..9b65446 --- /dev/null +++ b/src-tests/rwsets/campus/TestCampus2.dot @@ -0,0 +1,8 @@ +digraph "DirectedGraph" { + graph [concentrate = true]; + center=true; + fontsize=6; + node [ color=blue,shape="box"fontsize=6,fontcolor=black,fontname=Arial]; + edge [ color=black,fontsize=6,fontcolor=black,fontname=Arial]; +"void application/Application.()"[color="red", fontsize="6", fontname="Arial"]; +} \ No newline at end of file diff --git a/src-tests/rwsets/chat/TestChat.java b/src-tests/rwsets/chat/TestChat.java new file mode 100644 index 0000000..87396df --- /dev/null +++ b/src-tests/rwsets/chat/TestChat.java @@ -0,0 +1,63 @@ +package rwsets.chat; + +import japa.parser.ParseException; + +import java.io.File; +import java.io.IOException; +import java.util.Properties; +import java.util.Vector; + + import org.junit.Assert; +import org.junit.Test; + + import rwsets.Helper; + + import com.ibm.wala.classLoader.IClass; +import com.ibm.wala.classLoader.IMethod; +import com.ibm.wala.shrikeCT.InvalidClassFileException; +import com.ibm.wala.util.CancelException; +import com.ibm.wala.util.WalaException; +import com.ibm.wala.util.io.CommandLine; +import com.ibm.wala.util.warnings.Warnings; + + import depend.MethodDependencyAnalysis; +import depend.util.Util; +import depend.util.graph.SimpleGraph; + + public class TestChat { + + String USER_DIR = System.getProperty("user.dir"); + String SEP = System.getProperty("file.separator"); + String EXAMPLES = USER_DIR + SEP + "example-apps"; + String TEST_DIR = USER_DIR + SEP + "src-tests"; + String EXAMPLES_SRC = EXAMPLES + SEP + "src"; + String EXAMPLES_JAR = EXAMPLES; + String RESOURCES_DIR = USER_DIR + SEP + "dat"; + String CHAT_JAR = EXAMPLES_JAR + SEP + "chat.jar"; + + @Test + public void testBasicDoesNotCrash() throws IOException, WalaException, CancelException, ParseException, InvalidClassFileException { + String strCompUnit = EXAMPLES_SRC + SEP + "chat" + SEP + "chat" + SEP + "server" + SEP + "MultiChatServer.java"; + Assert.assertTrue((new File(strCompUnit)).exists()); + String line = "thread = new MultiChatServerThread(info, entry, SenderSocket, connected_hand_shake, disconnected_hand_shake, whois_hand_shake);"; + // check for crashes + depend.Main.analyze(CHAT_JAR, "server", strCompUnit, line); + } + + + @Test + public void test0() throws IOException, WalaException, CancelException, ParseException, InvalidClassFileException { + + String strCompUnit = EXAMPLES_SRC + SEP + "chat" + SEP + "chat" + SEP + "server" + SEP + "MultiChatServer.java"; + String chatJar = EXAMPLES_JAR + SEP + "chat.jar"; + + Assert.assertTrue((new File(strCompUnit)).exists()); + Assert.assertTrue((new File(chatJar)).exists()); + + String line = "UserInfo entry = new UserInfo(out, in, (\"\" + SenderSocket.getInetAddress()).substring(1), SenderSocket.getPort(), name);"; + SimpleGraph sg = depend.Main.analyze(chatJar, "server", strCompUnit, line); + System.out.println(sg.toDotString()); + String expectedResultFile = TEST_DIR + SEP + "rwsets/ip/TestIp.dot"; + Assert.assertEquals(Helper.readFile(expectedResultFile), sg.toDotString()); + } +} diff --git a/src-tests/rwsets/coffeemaker/TestCoffeeMaker.java b/src-tests/rwsets/coffeemaker/TestCoffeeMaker.java index a855c99..255e3e4 100644 --- a/src-tests/rwsets/coffeemaker/TestCoffeeMaker.java +++ b/src-tests/rwsets/coffeemaker/TestCoffeeMaker.java @@ -45,7 +45,7 @@ public void test0() throws IOException, WalaException, CancelException, ParseExc String line = "if(addRecipe(newRecipe)) {"; SimpleGraph sg = depend.Main.analyze(coffeejar, "coffee", strCompUnit, line); - String expectedResultFile = TEST_DIR + SEP + "rwsets/coffeemaker/TestCoffeeMaker.test0.data"; + String expectedResultFile = TEST_DIR + SEP + "rwsets/coffeemaker/TestCoffeeMaker.test0.dot"; Assert.assertEquals(Helper.readFile(expectedResultFile), sg.toDotString()); } @@ -97,7 +97,7 @@ public void testAnalysisWithLineContents() throws Exception { IMethod method = depend.Main.findMethod(clazz); SimpleGraph sg = depend.Main.run(mda, method); - String expectedResultFile = TEST_DIR + SEP + "rwsets/coffeemaker/TestCoffeeMaker.testAnalysisWithLineContents.data"; + String expectedResultFile = TEST_DIR + SEP + "rwsets/coffeemaker/TestCoffeeMaker.testAnalysisWithLineContents.dot"; Assert.assertEquals(Helper.readFile(expectedResultFile), sg.toString()); } } \ No newline at end of file diff --git a/src-tests/rwsets/coffeemaker/TestCoffeeMaker.test0.dot b/src-tests/rwsets/coffeemaker/TestCoffeeMaker.test0.dot new file mode 100644 index 0000000..267c9f6 --- /dev/null +++ b/src-tests/rwsets/coffeemaker/TestCoffeeMaker.test0.dot @@ -0,0 +1,23 @@ +digraph "DirectedGraph" { + graph [concentrate = true]; + center=true; + fontsize=6; + node [ color=blue,shape="box"fontsize=6,fontcolor=black,fontname=Arial]; + edge [ color=black,fontsize=6,fontcolor=black,fontname=Arial]; +"boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)"[color="red", fontsize="6", fontname="Arial"]; +"boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 58" ] +"boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Z coffeemaker/CoffeeMaker.recipeFull : 59" ] +"boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 58" ] +"boolean coffeemaker/CoffeeMaker.deleteRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 79" ] +"boolean coffeemaker/CoffeeMaker.deleteRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 79" ] +"boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 98" ] +"boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 98" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 23" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 26" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Z coffeemaker/CoffeeMaker.recipeFull : 24" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Z coffeemaker/CoffeeMaker.recipeFull : 27" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 23" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 26" ] +"void coffeemaker/Recipe.setName(java/lang/String)" -> "boolean coffeemaker/Recipe.equals(coffeemaker/Recipe)" [label="java/lang/String coffeemaker/Recipe.name : 65" ] +"void coffeemaker/Recipe.setName(java/lang/String)" -> "java/lang/String coffeemaker/Recipe.getName()" [label="java/lang/String coffeemaker/Recipe.name : 65" ] +} \ No newline at end of file diff --git a/src-tests/rwsets/coffeemaker/TestCoffeeMaker.testAnalysisWithLineContents.dot b/src-tests/rwsets/coffeemaker/TestCoffeeMaker.testAnalysisWithLineContents.dot new file mode 100644 index 0000000..c9736c6 --- /dev/null +++ b/src-tests/rwsets/coffeemaker/TestCoffeeMaker.testAnalysisWithLineContents.dot @@ -0,0 +1,15 @@ +"boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 58" ] +"boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Z coffeemaker/CoffeeMaker.recipeFull : 59" ] +"boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 58" ] +"boolean coffeemaker/CoffeeMaker.deleteRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 79" ] +"boolean coffeemaker/CoffeeMaker.deleteRecipe(coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 79" ] +"boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 98" ] +"boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 98" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 23" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 26" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Z coffeemaker/CoffeeMaker.recipeFull : 24" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.addRecipe(coffeemaker/Recipe)" [label="Z coffeemaker/CoffeeMaker.recipeFull : 27" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 23" ] +"void coffeemaker/CoffeeMaker.()" -> "boolean coffeemaker/CoffeeMaker.editRecipe(coffeemaker/Recipe,coffeemaker/Recipe)" [label="Lcoffeemaker/Recipe coffeemaker/CoffeeMaker.recipeArray : 26" ] +"void coffeemaker/Recipe.setName(java/lang/String)" -> "boolean coffeemaker/Recipe.equals(coffeemaker/Recipe)" [label="java/lang/String coffeemaker/Recipe.name : 65" ] +"void coffeemaker/Recipe.setName(java/lang/String)" -> "java/lang/String coffeemaker/Recipe.getName()" [label="java/lang/String coffeemaker/Recipe.name : 65" ] \ No newline at end of file diff --git a/src-tests/rwsets/ip/TestIp.dot b/src-tests/rwsets/ip/TestIp.dot new file mode 100644 index 0000000..b76459e --- /dev/null +++ b/src-tests/rwsets/ip/TestIp.dot @@ -0,0 +1,12 @@ +digraph "DirectedGraph" { + graph [concentrate = true]; + center=true; + fontsize=6; + node [ color=blue,shape="box"fontsize=6,fontcolor=black,fontname=Arial]; + edge [ color=black,fontsize=6,fontcolor=black,fontname=Arial]; +"dados/IteratorClasse dados/repositorio/RepAdmArquivo.iterator()"[color="red", fontsize="6", fontname="Arial"]; +"dados/entidade/Administrador dados/repositorio/RepAdmArquivo.procurar(java/lang/String)" -> "dados/IteratorClasse dados/repositorio/RepAdmArquivo.iterator()" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 120" ] +"void dados/repositorio/RepAdmArquivo.()" -> "dados/IteratorClasse dados/repositorio/RepAdmArquivo.iterator()" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 40" ] +"void dados/repositorio/RepAdmArquivo.()" -> "dados/IteratorClasse dados/repositorio/RepAdmArquivo.iterator()" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 52" ] +"void dados/repositorio/RepAdmArquivo.atualizar(dados/entidade/Administrador)" -> "dados/IteratorClasse dados/repositorio/RepAdmArquivo.iterator()" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 158" ] +} \ No newline at end of file diff --git a/src-tests/rwsets/ip/TestIp.java b/src-tests/rwsets/ip/TestIp.java new file mode 100644 index 0000000..bba6ca1 --- /dev/null +++ b/src-tests/rwsets/ip/TestIp.java @@ -0,0 +1,78 @@ +package rwsets.ip; + + +import japa.parser.ParseException; + + import java.io.File; +import java.io.IOException; +import java.util.Properties; +import java.util.Vector; + + import org.junit.Assert; +import org.junit.Test; + + import rwsets.Helper; + + import com.ibm.wala.classLoader.IClass; +import com.ibm.wala.classLoader.IMethod; +import com.ibm.wala.shrikeCT.InvalidClassFileException; +import com.ibm.wala.util.CancelException; +import com.ibm.wala.util.WalaException; +import com.ibm.wala.util.io.CommandLine; +import com.ibm.wala.util.warnings.Warnings; + + import depend.MethodDependencyAnalysis; +import depend.util.Util; +import depend.util.graph.SimpleGraph; + + public class TestIp { + + String USER_DIR = System.getProperty("user.dir"); + String SEP = System.getProperty("file.separator"); + String EXAMPLES = USER_DIR + SEP + "example-apps"; + String TEST_DIR = USER_DIR + SEP + "src-tests"; + String EXAMPLES_SRC = EXAMPLES + SEP + "src"; + String EXAMPLES_JAR = EXAMPLES; + String RESOURCES_DIR = USER_DIR + SEP + "dat"; + String IP_JAR = EXAMPLES_JAR + SEP + "ip.jar"; + + @Test + public void testBasicDoesNotCrash() throws IOException, WalaException, CancelException, ParseException, InvalidClassFileException { + String strCompUnit = EXAMPLES_SRC + SEP + "ip" + SEP + "dados" + SEP + "repositorio" + SEP + "RepAdmArquivo.java"; + Assert.assertTrue((new File(strCompUnit)).exists()); + String line = "this.vetorAdministradores = new Vector();"; + // check for crashes + depend.Main.analyze(IP_JAR, "dados/repositorio", strCompUnit, line); + } + + @Test + public void testPrimitiveTypeDependency() throws IOException, WalaException, CancelException, ParseException, InvalidClassFileException { + + String strCompUnit = EXAMPLES_SRC + SEP + "ip" + SEP + "dados" + SEP + "repositorio" + SEP + "RepAdmArquivo.java"; + Assert.assertTrue((new File(strCompUnit)).exists()); + + String line = "teste.atualizar(adminSubstituir);"; + SimpleGraph sg = depend.Main.analyze(IP_JAR, "dados/repositorio", strCompUnit, line); + System.out.println(sg.toDotString()); + // check + String expectedResultFile = TEST_DIR + SEP + "rwsets" + SEP + "ip" + SEP + "TestIpDep.dot"; + String expected = Helper.readFile(expectedResultFile); + Assert.assertEquals(expected, sg.toDotString()); + } + + @Test + public void test0() throws IOException, WalaException, CancelException, ParseException, InvalidClassFileException { + + String strCompUnit = EXAMPLES_SRC + SEP + "ip/dados/repositorio/RepAdmArquivo.java"; + String ipJar = EXAMPLES_JAR + SEP + "ip.jar"; + + Assert.assertTrue((new File(strCompUnit)).exists()); + Assert.assertTrue((new File(ipJar)).exists()); + + String line = "Vector listAdministradors = new Vector();"; + SimpleGraph sg = depend.Main.analyze(ipJar, "dados/repositorio", strCompUnit, line); + //System.out.println(sg.toDotString()); + String expectedResultFile = TEST_DIR + SEP + "rwsets/ip/TestIp.dot"; + Assert.assertEquals(Helper.readFile(expectedResultFile), sg.toDotString()); + } +} diff --git a/src-tests/rwsets/ip/TestIpDep.dot b/src-tests/rwsets/ip/TestIpDep.dot new file mode 100644 index 0000000..373680d --- /dev/null +++ b/src-tests/rwsets/ip/TestIpDep.dot @@ -0,0 +1,16 @@ +digraph "DirectedGraph" { + graph [concentrate = true]; + center=true; + fontsize=6; + node [ color=blue,shape="box"fontsize=6,fontcolor=black,fontname=Arial]; + edge [ color=black,fontsize=6,fontcolor=black,fontname=Arial]; +"void dados/repositorio/RepAdmArquivo.main(Ljava/lang/String)"[color="red", fontsize="6", fontname="Arial"]; +"dados/entidade/Administrador dados/repositorio/RepAdmArquivo.procurar(java/lang/String)" -> "dados/entidade/Administrador dados/repositorio/RepAdmArquivo.procurar(java/lang/String)" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 120" ] +"dados/entidade/Administrador dados/repositorio/RepAdmArquivo.procurar(java/lang/String)" -> "void dados/repositorio/RepAdmArquivo.atualizar(dados/entidade/Administrador)" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 120" ] +"void dados/repositorio/RepAdmArquivo.()" -> "dados/entidade/Administrador dados/repositorio/RepAdmArquivo.procurar(java/lang/String)" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 40" ] +"void dados/repositorio/RepAdmArquivo.()" -> "dados/entidade/Administrador dados/repositorio/RepAdmArquivo.procurar(java/lang/String)" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 52" ] +"void dados/repositorio/RepAdmArquivo.()" -> "void dados/repositorio/RepAdmArquivo.atualizar(dados/entidade/Administrador)" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 40" ] +"void dados/repositorio/RepAdmArquivo.()" -> "void dados/repositorio/RepAdmArquivo.atualizar(dados/entidade/Administrador)" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 52" ] +"void dados/repositorio/RepAdmArquivo.atualizar(dados/entidade/Administrador)" -> "dados/entidade/Administrador dados/repositorio/RepAdmArquivo.procurar(java/lang/String)" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 158" ] +"void dados/repositorio/RepAdmArquivo.atualizar(dados/entidade/Administrador)" -> "void dados/repositorio/RepAdmArquivo.atualizar(dados/entidade/Administrador)" [label="java/util/Vector dados/repositorio/RepAdmArquivo.vetorAdministradores : 158" ] +} \ No newline at end of file diff --git a/src-tests/rwsets/logicaProj/TestLogica.dot b/src-tests/rwsets/logicaProj/TestLogica.dot new file mode 100644 index 0000000..e84d5db --- /dev/null +++ b/src-tests/rwsets/logicaProj/TestLogica.dot @@ -0,0 +1,106 @@ +digraph "DirectedGraph" { + graph [concentrate = true]; + center=true; + fontsize=6; + node [ color=blue,shape="box"fontsize=6,fontcolor=black,fontname=Arial]; + edge [ color=black,fontsize=6,fontcolor=black,fontname=Arial]; +"void logica/Resolucao.main(Ljava/lang/String)"[color="red", fontsize="6", fontname="Arial"]; +"char logica/Arquivo.readChar()" -> "void logica/Arquivo.findNext()" [label="int logica/Arquivo.nextChar : 154" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "boolean logica/Arquivo.isEndOfFile()" [label="int logica/Arquivo.nextTokenLin : 254" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="Ljava/lang/String logica/Arquivo.buffer : 251" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="Ljava/lang/String logica/Arquivo.buffer : 258" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.contLin : 259" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.nextTokenLin : 254" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.primLin : 246" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.primLin : 255" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "java/lang/String logica/Arquivo.readString()" [label="Ljava/lang/String logica/Arquivo.buffer : 251" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "java/lang/String logica/Arquivo.readString()" [label="Ljava/lang/String logica/Arquivo.buffer : 258" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.contLin : 259" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.nextTokenLin : 254" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.primLin : 246" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.primLin : 255" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "void logica/Arquivo.findNext()" [label="Ljava/lang/String logica/Arquivo.buffer : 251" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "void logica/Arquivo.findNext()" [label="Ljava/lang/String logica/Arquivo.buffer : 258" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "void logica/Arquivo.findNext()" [label="int logica/Arquivo.primLin : 246" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "void logica/Arquivo.findNext()" [label="int logica/Arquivo.primLin : 255" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "void logica/Arquivo.initBuffer()" [label="Ljava/lang/String logica/Arquivo.buffer : 251" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "void logica/Arquivo.initBuffer()" [label="Ljava/lang/String logica/Arquivo.buffer : 258" ] +"int logica/Arquivo.appendLine(java/lang/String)" -> "void logica/Arquivo.initBuffer()" [label="int logica/Arquivo.contLin : 259" ] +"java/lang/String logica/Arquivo.readLine()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="Ljava/lang/String logica/Arquivo.buffer : 126" ] +"java/lang/String logica/Arquivo.readLine()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.contLin : 129" ] +"java/lang/String logica/Arquivo.readLine()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.primLin : 128" ] +"java/lang/String logica/Arquivo.readLine()" -> "java/lang/String logica/Arquivo.readString()" [label="Ljava/lang/String logica/Arquivo.buffer : 126" ] +"java/lang/String logica/Arquivo.readLine()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.contLin : 129" ] +"java/lang/String logica/Arquivo.readLine()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.primLin : 128" ] +"java/lang/String logica/Arquivo.readLine()" -> "void logica/Arquivo.findNext()" [label="Ljava/lang/String logica/Arquivo.buffer : 126" ] +"java/lang/String logica/Arquivo.readLine()" -> "void logica/Arquivo.findNext()" [label="int logica/Arquivo.nextChar : 127" ] +"java/lang/String logica/Arquivo.readLine()" -> "void logica/Arquivo.findNext()" [label="int logica/Arquivo.primLin : 128" ] +"java/lang/String logica/Arquivo.readLine()" -> "void logica/Arquivo.initBuffer()" [label="Ljava/lang/String logica/Arquivo.buffer : 126" ] +"java/lang/String logica/Arquivo.readLine()" -> "void logica/Arquivo.initBuffer()" [label="int logica/Arquivo.contLin : 129" ] +"java/lang/String logica/Arquivo.readString()" -> "boolean logica/Arquivo.isEndOfFile()" [label="int logica/Arquivo.nextTokenLin : 178" ] +"java/lang/String logica/Arquivo.readString()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="Ljava/lang/String logica/Arquivo.buffer : 176" ] +"java/lang/String logica/Arquivo.readString()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="Ljava/lang/String logica/Arquivo.buffer : 177" ] +"java/lang/String logica/Arquivo.readString()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.contLin : 179" ] +"java/lang/String logica/Arquivo.readString()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.nextTokenLin : 178" ] +"java/lang/String logica/Arquivo.readString()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.primLin : 178" ] +"java/lang/String logica/Arquivo.readString()" -> "java/lang/String logica/Arquivo.readString()" [label="Ljava/lang/String logica/Arquivo.buffer : 176" ] +"java/lang/String logica/Arquivo.readString()" -> "java/lang/String logica/Arquivo.readString()" [label="Ljava/lang/String logica/Arquivo.buffer : 177" ] +"java/lang/String logica/Arquivo.readString()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.contLin : 179" ] +"java/lang/String logica/Arquivo.readString()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.nextTokenLin : 178" ] +"java/lang/String logica/Arquivo.readString()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.primLin : 178" ] +"java/lang/String logica/Arquivo.readString()" -> "void logica/Arquivo.findNext()" [label="Ljava/lang/String logica/Arquivo.buffer : 176" ] +"java/lang/String logica/Arquivo.readString()" -> "void logica/Arquivo.findNext()" [label="Ljava/lang/String logica/Arquivo.buffer : 177" ] +"java/lang/String logica/Arquivo.readString()" -> "void logica/Arquivo.findNext()" [label="int logica/Arquivo.nextChar : 187" ] +"java/lang/String logica/Arquivo.readString()" -> "void logica/Arquivo.findNext()" [label="int logica/Arquivo.primLin : 178" ] +"java/lang/String logica/Arquivo.readString()" -> "void logica/Arquivo.initBuffer()" [label="Ljava/lang/String logica/Arquivo.buffer : 176" ] +"java/lang/String logica/Arquivo.readString()" -> "void logica/Arquivo.initBuffer()" [label="Ljava/lang/String logica/Arquivo.buffer : 177" ] +"java/lang/String logica/Arquivo.readString()" -> "void logica/Arquivo.initBuffer()" [label="int logica/Arquivo.contLin : 179" ] +"void logica/Arquivo.(java/lang/String,java/lang/String)" -> "void logica/Arquivo.findNext()" [label="java/io/BufferedReader logica/Arquivo.in : 59" ] +"void logica/Arquivo.(java/lang/String,java/lang/String)" -> "void logica/Arquivo.initBuffer()" [label="java/io/BufferedReader logica/Arquivo.in : 59" ] +"void logica/Arquivo.(java/lang/String,java/lang/String)" -> "void logica/Arquivo.print(java/lang/String)" [label="java/io/PrintWriter logica/Arquivo.out : 62" ] +"void logica/Arquivo.(java/lang/String,java/lang/String)" -> "void logica/Arquivo.println(java/lang/String)" [label="java/io/PrintWriter logica/Arquivo.out : 62" ] +"void logica/Arquivo.close()" -> "void logica/Arquivo.findNext()" [label="java/io/BufferedReader logica/Arquivo.in : 81" ] +"void logica/Arquivo.close()" -> "void logica/Arquivo.initBuffer()" [label="java/io/BufferedReader logica/Arquivo.in : 81" ] +"void logica/Arquivo.close()" -> "void logica/Arquivo.print(java/lang/String)" [label="java/io/PrintWriter logica/Arquivo.out : 86" ] +"void logica/Arquivo.close()" -> "void logica/Arquivo.println(java/lang/String)" [label="java/io/PrintWriter logica/Arquivo.out : 86" ] +"void logica/Arquivo.findNext()" -> "boolean logica/Arquivo.isEndOfFile()" [label="int logica/Arquivo.nextTokenLin : 276" ] +"void logica/Arquivo.findNext()" -> "boolean logica/Arquivo.isEndOfFile()" [label="int logica/Arquivo.nextTokenLin : 282" ] +"void logica/Arquivo.findNext()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.nextTokenLin : 276" ] +"void logica/Arquivo.findNext()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.nextTokenLin : 282" ] +"void logica/Arquivo.findNext()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.nextTokenCol : 271" ] +"void logica/Arquivo.findNext()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.nextTokenCol : 276" ] +"void logica/Arquivo.findNext()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.nextTokenCol : 281" ] +"void logica/Arquivo.findNext()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.nextTokenLin : 276" ] +"void logica/Arquivo.findNext()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.nextTokenLin : 282" ] +"void logica/Arquivo.initBuffer()" -> "boolean logica/Arquivo.isEndOfFile()" [label="int logica/Arquivo.nextTokenLin : 224" ] +"void logica/Arquivo.initBuffer()" -> "boolean logica/Arquivo.isEndOfFile()" [label="int logica/Arquivo.nextTokenLin : 229" ] +"void logica/Arquivo.initBuffer()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="Ljava/lang/String logica/Arquivo.buffer : 222" ] +"void logica/Arquivo.initBuffer()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="Ljava/lang/String logica/Arquivo.buffer : 231" ] +"void logica/Arquivo.initBuffer()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.contLin : 225" ] +"void logica/Arquivo.initBuffer()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.contLin : 232" ] +"void logica/Arquivo.initBuffer()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.nextTokenLin : 224" ] +"void logica/Arquivo.initBuffer()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.nextTokenLin : 229" ] +"void logica/Arquivo.initBuffer()" -> "int logica/Arquivo.appendLine(java/lang/String)" [label="int logica/Arquivo.primLin : 225" ] +"void logica/Arquivo.initBuffer()" -> "java/lang/String logica/Arquivo.readString()" [label="Ljava/lang/String logica/Arquivo.buffer : 222" ] +"void logica/Arquivo.initBuffer()" -> "java/lang/String logica/Arquivo.readString()" [label="Ljava/lang/String logica/Arquivo.buffer : 231" ] +"void logica/Arquivo.initBuffer()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.contLin : 225" ] +"void logica/Arquivo.initBuffer()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.contLin : 232" ] +"void logica/Arquivo.initBuffer()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.nextTokenLin : 224" ] +"void logica/Arquivo.initBuffer()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.nextTokenLin : 229" ] +"void logica/Arquivo.initBuffer()" -> "java/lang/String logica/Arquivo.readString()" [label="int logica/Arquivo.primLin : 225" ] +"void logica/Arquivo.initBuffer()" -> "void logica/Arquivo.findNext()" [label="Ljava/lang/String logica/Arquivo.buffer : 222" ] +"void logica/Arquivo.initBuffer()" -> "void logica/Arquivo.findNext()" [label="Ljava/lang/String logica/Arquivo.buffer : 231" ] +"void logica/Arquivo.initBuffer()" -> "void logica/Arquivo.findNext()" [label="int logica/Arquivo.nextChar : 223" ] +"void logica/Arquivo.initBuffer()" -> "void logica/Arquivo.findNext()" [label="int logica/Arquivo.primLin : 225" ] +"void logica/Arquivo.initBuffer()" -> "void logica/Arquivo.initBuffer()" [label="Ljava/lang/String logica/Arquivo.buffer : 222" ] +"void logica/Arquivo.initBuffer()" -> "void logica/Arquivo.initBuffer()" [label="Ljava/lang/String logica/Arquivo.buffer : 231" ] +"void logica/Arquivo.initBuffer()" -> "void logica/Arquivo.initBuffer()" [label="int logica/Arquivo.contLin : 225" ] +"void logica/Arquivo.initBuffer()" -> "void logica/Arquivo.initBuffer()" [label="int logica/Arquivo.contLin : 232" ] +"void logica/Exp.(java/lang/String)" -> "boolean logica/Exp.areAllHorn()" [label="java/util/ArrayList logica/Exp.exps : 12" ] +"void logica/Exp.(java/lang/String)" -> "boolean logica/Exp.isInFNC()" [label="java/lang/String logica/Exp.exp : 13" ] +"void logica/Exp.(java/lang/String)" -> "boolean logica/Exp.isInFNC()" [label="java/util/ArrayList logica/Exp.exps : 12" ] +"void logica/Exp.(java/lang/String)" -> "boolean logica/Exp.isSatisfiable(logica/Arquivo)" [label="java/lang/String logica/Exp.exp : 13" ] +"void logica/Exp.(java/lang/String)" -> "boolean logica/Exp.isSatisfiable(logica/Arquivo)" [label="java/util/ArrayList logica/Exp.exps : 12" ] +"void logica/Exp.(java/lang/String)" -> "void logica/Exp.(java/lang/String)" [label="java/util/ArrayList logica/Exp.exps : 12" ] +"void logica/Exp.(java/lang/String)" -> "void logica/Exp.clearExpressions()" [label="java/util/ArrayList logica/Exp.exps : 12" ] +} \ No newline at end of file diff --git a/src-tests/rwsets/logicaProj/TestLogica.java b/src-tests/rwsets/logicaProj/TestLogica.java new file mode 100644 index 0000000..fd5b763 --- /dev/null +++ b/src-tests/rwsets/logicaProj/TestLogica.java @@ -0,0 +1,47 @@ +package rwsets.logicaProj; + +import japa.parser.ParseException; + +import java.io.File; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Test; + +import rwsets.Helper; + +import com.ibm.wala.shrikeCT.InvalidClassFileException; +import com.ibm.wala.util.CancelException; +import com.ibm.wala.util.WalaException; + +import depend.util.graph.SimpleGraph; + +public class TestLogica { + + String USER_DIR = System.getProperty("user.dir"); + String SEP = System.getProperty("file.separator"); + String EXAMPLES = USER_DIR + SEP + "example-apps"; + String TEST_DIR = USER_DIR + SEP + "src-tests"; + String EXAMPLES_SRC = EXAMPLES + SEP + "src"; + String EXAMPLES_JAR = EXAMPLES; + String RESOURCES_DIR = USER_DIR + SEP + "dat"; + + @Test + public void test0() throws IOException, WalaException, CancelException, ParseException, InvalidClassFileException { + + String strCompUnit = EXAMPLES_SRC + SEP + "logicaProj" + SEP + "logica" + SEP + "Resolucao.java"; + String logicaJar = EXAMPLES_JAR + SEP + "logica.jar"; + + Assert.assertTrue((new File(strCompUnit)).exists()); + Assert.assertTrue((new File(logicaJar)).exists()); + + String line = "if (!exp.isInFNC())"; + SimpleGraph sg = depend.Main.analyze(logicaJar, "logica", strCompUnit, line); + //System.out.println(sg.toDotString()); + String expectedResultFile = TEST_DIR + SEP + "rwsets/logicaProj/TestLogica.dot"; + Assert.assertEquals(Helper.readFile(expectedResultFile), sg.toDotString()); + } + + + +} diff --git a/src/depend/Main.java b/src/depend/Main.java index 0c05e93..eb72af5 100755 --- a/src/depend/Main.java +++ b/src/depend/Main.java @@ -166,15 +166,18 @@ public static SimpleGraph analyze( }; MethodDependencyAnalysis mda = createMDA(args); - + // find informed class IClass clazz = mda.getCHA().lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Application, targetClass)); if (clazz == null) { throw new RuntimeException("Could not find class \"" + targetClass + "\""); } // find informed method + System.out.println("oi"); + System.out.println(targetLine); IMethod imethod = findMethod(mda, clazz, targetLine); + // run the analysis return run(mda, imethod); diff --git a/src/depend/MethodDependencyAnalysis.java b/src/depend/MethodDependencyAnalysis.java index 1baf54a..2f520e8 100755 --- a/src/depend/MethodDependencyAnalysis.java +++ b/src/depend/MethodDependencyAnalysis.java @@ -441,6 +441,7 @@ public SimpleGraph getDependenciesGraph(IMethod method, int sourceLine, SimpleGraph dependencyGraph = new SimpleGraph(); if(!forwardDependencies){ + System.out.println(); Set reads = rwSets.get(method).readSet; Set callSites = null; CallGraph cg = this.getCallGraphGenerator().getFullCallGraph(); diff --git a/src/depend/util/parser/Util.java b/src/depend/util/parser/Util.java index 465bcd2..75bb21e 100644 --- a/src/depend/util/parser/Util.java +++ b/src/depend/util/parser/Util.java @@ -29,7 +29,7 @@ public static void main(String[] args) throws ParseException, IOException, Class String strCompUnit = System.getProperty("user.dir") + System.getProperty("file.separator") + - "src/examples/D.java"; + "example-apps\\ip\\dados\\repositorio\\RepAdmArquivo.java"; getLineAndWALAClassName(line, strCompUnit); } @@ -75,6 +75,9 @@ public static String[] getLineAndWALAClassName(String line, String strCompUnit) CompilationUnit cUnit = parserClass(classFile); cUnit.accept(vva, null); + System.out.println("Decl da classe"); + System.out.println(lastClassStr); + if (!vva.found) { throw new RuntimeException(); } @@ -102,7 +105,7 @@ private static String to_WALA_ClassName(PackageDeclaration pd, StringBuffer sb = new StringBuffer(); sb.append("L"); if (pd != null) { - sb.append(pd.getName()); + sb.append(pd.getName().toString().replaceAll("\\.", "/")); sb.append("/"); } for (int i = 0; i < stack.size(); i++) { @@ -159,6 +162,7 @@ public void visit(ClassOrInterfaceDeclaration n, Void arg) { // System.out.println(sb.toString().trim()); // System.out.println(name); if (sb.toString().trim().equals(cname.trim())) { + //if (sb.toString().replace(" ","").equals(cname.replace(" ", ""))) { found = true; } super.visit(n, arg);