Is this decent code, hacks, or somewhere in between? :)

Recommended Answers

All 3 Replies

I suggest you use the CODE /CODE with [] it'll be easier for us to read then what you have now.

package javachat;

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class Main extends JFrame {

    private static JTextArea textIn;
    private JTextArea textOut;
    private enum Mode {
        ADDRESS,
        PORT,
        READY,
        CONNECTED;
    }
    private Mode mode;
    private String address;
    private int port;

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

    public static void setText(String text) {
        textIn.setText(textIn.getText() + text);
    }

    private Main() {
        this.setSize(400, 350);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.add(makePanel());
        this.setVisible(true);

        mode = Mode.ADDRESS;
        textIn.setText("Enter remote address:\n");
        while (mode == Mode.ADDRESS);

        textIn.setText("Enter remote port:\n");
        while (mode == Mode.PORT);
        
        new Connection(address, port);
        mode = Mode.CONNECTED;
    }

    private JPanel makePanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        textIn = new JTextArea();
        textIn.setEditable(false);
        textOut = new JTextArea("localhost");
        textOut.addKeyListener(new sendListener());
        panel.add(textIn, BorderLayout.CENTER);
        panel.add(textOut, BorderLayout.SOUTH);
        return panel;
    }

    private void sendLine() {
        if (mode == Mode.CONNECTED) {
            Connection.sendLine(textOut.getText());
            textIn.setText(textIn.getText()+textOut.getText());
        }
        else if (mode == Mode.ADDRESS) {
            address = textOut.getText().trim();
            mode = Mode.PORT;
        }
        else if (mode == Mode.PORT) {
            port = Integer.parseInt(textOut.getText().trim());
            mode = Mode.READY;
        }
        textOut.setText("");
    }

    private class sendListener implements KeyListener {

        public void keyTyped(KeyEvent e) {
            if (e.getKeyChar() == '\n') sendLine();
        }
        public void keyPressed(KeyEvent e) { }
        public void keyReleased(KeyEvent e) { }
    }

}
package javachat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

class Connection {

    private Socket s = null;
    private static PrintWriter os;
    
    public static void sendLine(String line) {
        os.print(line);
        os.flush();
    }

    Connection(String address, int port) {
        try {
            s = new Socket(address, port);
            os = new PrintWriter(s.getOutputStream());
            Main.setText("Connected in client mode.\n");
        }
        catch (Exception ex) {
            try {
                Main.setText("No Server found.\n");
                ServerSocket ss = new ServerSocket(port);
                Main.setText("In server mode.\n");
                s = ss.accept();
                os = new PrintWriter(s.getOutputStream());
                Main.setText("Now connected.\n");
            }
            catch (IOException ex1) {
                Main.setText("Connection failed.\n");
            }
        }

        new Thread(new Receive(s)).start();
    }

    public boolean isConnected() {
        if (s != null) return true;
        else return false;
    }

    class Receive implements Runnable {
        Socket socket;

        Receive(Socket s) {
            socket = s;
        }

        public void run() {
            BufferedReader is;
            char cbuf[];
            int len;

            try {
                is = new BufferedReader(
                        new InputStreamReader(s.getInputStream())
                        );
                cbuf = new char[512];
                while (true) {
                    len = is.read(cbuf);
                    if (len != -1) 
                        Main.setText(new String(cbuf, 0, len));
                    else {
                        s = null;
                        Main.setText("The connection was lost.\n");
                        return;
                    }
                }
            } catch (IOException ex) {
                System.exit(1);
            }
        }
    }

}
package webserver;

import java.io.IOException;
import java.net.ServerSocket;

public class WebServer {

    public static String version = "Java Web Server 0.0";

    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(80);
            System.out.println(version);
            while (ss.isBound()) new Thread(new Client(ss.accept())).start();
        } 
        catch (IOException e) { System.exit(2); }
    }

}
package webserver;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;

class Client implements Runnable {

    private static final String userdir = System.getProperty("user.dir");
    static final byte[] EOL = {(byte) '\r', (byte) '\n'};
    private Socket accept;
    private InputStream is;
    private PrintStream os;

    private enum Method {

        GET,
        HEAD,
        UNSUPPORTED;
    }

    public Client(Socket accept) {
        this.accept = accept;
    }

    public void run() {
        try {

            // variables
            is = new BufferedInputStream(accept.getInputStream());
            os = new PrintStream(accept.getOutputStream());
            int character;
            String req = "";
            String[] request;
            Method method;
            File file;

            // store first line of request header
            character = is.read();
            while (character != '\n' && character != '\r') {
                req += (char) character;
                character = is.read();
            }
            System.out.println(req);
            request = req.split(" ");

            // store method
            if (request[0].matches("GET")) {
                method = Method.GET;
            } else if (request[0].matches("HEAD")) {
                method = Method.HEAD;
            } else {
                method = Method.UNSUPPORTED;
            }

            // logic!
            request[1] = request[1].replace("/", File.separator);
            file = new File(userdir + File.separator + request[1]);
            if (file.exists() && !file.isHidden()) {
                if (method == Method.GET || method == Method.HEAD) {
                    writeHeader(file, 200);
                    if (method == Method.GET) {
                        if (file.isFile()) {
                            sendFile(file);
                        } else if (file.isDirectory()) {
                            listDir(request[1], file);
                        }
                    }
                } else {
                    writeHeader(file, 501);
                }
            } else {
                writeHeader(file, 404);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                accept.close();
            } catch (IOException ex) {
                System.exit(1);
            }
        }
    }

    private void sendFile(File file) throws FileNotFoundException, IOException {
        int bufferlen = (int) file.length();
        byte buffer[] = new byte[bufferlen];
        InputStream fs = new FileInputStream(file);
        int len = fs.read(buffer);
        while (len < bufferlen) {
            len += fs.read(buffer, len, bufferlen - len);
        }
        os.write(buffer);
        os.flush();
    }

    private void listDir(String currentDir, File dir) {
        currentDir = currentDir.replace(File.separator, "/");
        String listing[] = dir.list();
        if (!currentDir.endsWith("/")) {
            currentDir += "/";
        }
        os.println(WebServer.version + "<br>");
        for (String item : listing) {
            os.println("<a href=\"" + currentDir + item + "\">" + item + "</a><br>");
        }
        os.flush();
    }

    private void writeHeader(File f, int code) throws IOException {
        String fname = f.getName();
        String buffer = "HTTP/1.0 ";

        switch (code) {
            case 200:
                buffer = buffer + "200 OK";
                break;
            case 400:
                buffer = buffer + "400 Bad Request";
                break;
            case 403:
                buffer = buffer + "403 Forbidden";
                break;
            case 404:
                buffer = buffer + "404 Not Found";
                break;
            case 500:
                buffer = buffer + "500 Internal Server Error";
                break;
            case 501:
                buffer = buffer + "501 Not Implemented";
                break;
        }
        os.print(buffer);
        os.write(EOL);
        buffer = "";

        if (code == 200) {
            buffer += "Content-Type: ";
            if (fname.endsWith("html") || fname.endsWith("htm")) {
                buffer += "text/html";
            } else if (fname.endsWith("java")) {
                buffer += "text/plain";
            } else if (fname.endsWith("jpeg") || fname.endsWith("jpg")) {
                buffer += "image/gif";
            } else {
                buffer += "text/html";
            }
            os.print(buffer);
            os.write(EOL);
        }

        os.write(EOL);
        os.flush();
    }
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaedit;

import java.awt.Color;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
 *
 * @author sean
 */
public class Server implements Runnable {
    // this is the server by which sends and receives are hosted
    // both send and receive

    private String content;
    private int port;

    public Server(String content, int port) {
        this.content = content;
        this.port = port;
    }

    public void run() {

        try {
            ServerSocket ss = new ServerSocket(port);
            ss.setSoTimeout(100);
            while (true) {
                nowServe(ss);
                if (Thread.interrupted()) {
                    ss.close();
                    return;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void nowServe(ServerSocket ss) {
        Socket s = null;
        try {
            try {
                s = ss.accept();
            } catch (SocketTimeoutException e) {
                // not an error
                //e.printStackTrace();
                return;
            }
            InputStream is = new BufferedInputStream(s.getInputStream());
            BufferedOutputStream os =
                    new BufferedOutputStream(s.getOutputStream());
            int mode = is.read();
            if (mode == -1) {
                return;
            }
            if (mode == 0) {
                //send at client
                try {
                    byte[] buffer = new byte[1024];
                    int len = is.read(buffer);
                    String temp = "";
                    while (len >= 0) {
                        for (int i = 0; i < len; i++) {
                            temp += (char) buffer[i];
                        }
                        len = is.read(buffer);
                    }
                    new JavaEdit(temp, Color.WHITE);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (mode == 1) {
                //download at client
                char[] textchars = content.toCharArray();
                for (int i = 0; i < content.length(); i++) {
                    os.write((byte) textchars[i]);
                }
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally  {
            try {
                s.close();
            } catch (Exception e) {
                //e.printStackTrace();
                return;
            }
        }
    }
}
package javaedit;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.StyledDocument;

class Window {
    // keep track of windows for closeWindow()
    // todo: change to typed linked list
    static Integer windowCount = 0;
}

public class JavaEdit extends JFrame implements Runnable {

    public static void main(String[] args) {
        new JavaEdit();
    }
    private String initialContent;
    private Color initialColor;
    private JTextPane editText;
    private StyledDocument doc;
    private JTextField address;
    private JCheckBoxMenuItem serverCheckBox;
    private JMenuItem connectOption;
    private Thread serverThread = null;
    private int port = 9101;
    private JTextField portField;
    private JFrame clientFrame;

    // Default constructor
    private JavaEdit() {
        new JavaEdit("", Color.BLACK);
    }

    // Actual constructor
    public JavaEdit(String StrinitContent, Color fontColor) {
        initialContent = StrinitContent;
        initialColor = fontColor;
        synchronized (Window.windowCount) {
            Window.windowCount += 1;
            new Thread(this, "Window #"+Window.windowCount).start();
        }
    }

    // every main window has one
    public void run() {

        this.setSize(800, 600);
        this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

        JMenuBar menuBar = new JMenuBar();
        JMenu connections = new JMenu("Connections");

        serverCheckBox = new JCheckBoxMenuItem("Serve Current Content");
        serverCheckBox.addActionListener(
                new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        invokeServer();
                    }
                });
        connectOption = new JMenuItem("Connect To...");
        connectOption.addActionListener(
                new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        connectDialog();
                    }
                });
        ///
        connections.add(serverCheckBox);
        connections.add(connectOption);
        menuBar.add(connections);

        JMenu app = new JMenu("Application");
        JMenuItem newOption = new JMenuItem("New Window");
        newOption.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                new JavaEdit();
            }
        });
        app.add(newOption);
        JMenuItem closeOption = new JMenuItem("Close This Window");
        closeOption.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                closeWindow();
            }
        });
        app.add(closeOption);
        JMenuItem closeall = new JMenuItem("Close All Windows");
        closeall.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });
        app.add(closeall);
        menuBar.add(app);

        this.setJMenuBar(menuBar);

        editText = new JTextPane();
        editText.setEditable(true);
        editText.setForeground(initialColor);
        editText.setFont(Font.getFont("Monospaced"));
        editText.setText(initialContent);
        editText.addKeyListener(new Highlights());
        editText.addCaretListener(new Highlights());

        doc = (StyledDocument) editText.getDocument();

        JScrollPane scroll = new JScrollPane(editText);
        this.setLayout(new BorderLayout());
        this.add(scroll, BorderLayout.CENTER);

        this.setVisible(true);
    }

    private void closeWindow() {
        synchronized (Window.windowCount) {
            if (Window.windowCount == 1) {
                System.exit(0);
            }
            if (serverThread != null) {
                serverCheckBox.setState(false);
                serverThread.interrupt();
                serverCheckBox = null;
            }
            this.dispose();
            Window.windowCount -= 1;
        }
    }

    // This Dialog sets up, and selects the client connection type
    private void connectDialog() {
        // todo: move this method when if gets bloated
        clientFrame = new JFrame();
        clientFrame.setAlwaysOnTop(true);
        clientFrame.setSize(300, 300);
        clientFrame.setLayout(new FlowLayout());
        address = new JTextField("localhost", 20);
        clientFrame.add(address);
        portField = new JTextField("9101", 20);
        clientFrame.add(portField);
        JButton download = new JButton("Download");
        clientFrame.add(download);
        download.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    clientConnection(1);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
        JButton send = new JButton("Send");
        clientFrame.add(send);
        send.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    clientConnection(0);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
        clientFrame.setVisible(true);
    }

    private void clientConnection(int mode) throws Exception {

        // this is the client by which a server is accessed
        // both send and receive
        clientFrame.dispose();
        // todo: replace ArrayList with typed linked list
        port = Integer.parseInt(portField.getText());
        String data = "";
        Socket s = new Socket(address.getText(), port);
        OutputStream os = new BufferedOutputStream(s.getOutputStream());
        InputStream is = new BufferedInputStream(s.getInputStream());
        os.write((byte) mode);
        os.flush();
        if (mode == 0) {
            //send
            synchronized (doc) {
                data = doc.getText(0, doc.getLength());
            }
            char datachar[] = data.toCharArray();
            for (char character : datachar) {
                os.write((byte) character);
            }
            os.flush();
        } else if (mode == 1) {
            //download
            byte buffer[] = new byte[1024];
            int len = is.read(buffer);
            while (len >= 0) {
                data += new String(buffer, 0, len);
                len = is.read(buffer);
            }
            new JavaEdit(data, Color.RED);
        }
        s.close();
    }

    private void invokeServer() {
        try {
            if (serverThread != null) {
                serverThread.interrupt();
                serverThread = null;
                serverCheckBox.setState(false);
                Thread.sleep(300);
                return;
            }
            String SPort = JOptionPane.showInputDialog(this, 
                    "Enter port number", "9101");
            if (SPort == null) return;
            JOptionPane.
                    showMessageDialog(this,
                    "Modifications will not be reflected on server until " +
                    "server is reset.");
            port = Integer.parseInt(SPort); //todo: error checking
            Server i = new Server(doc.getText(0, doc.getLength()), port);
            serverThread = new Thread(i, "A server at port "+port);
            serverThread.start();
            serverCheckBox.setState(true);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }

    class Highlights implements KeyListener, CaretListener {
        // highlight all matches for string next to caret

        private Highlighter ohl = null;
        private ArrayList<Object> highlights = new ArrayList();
        private int ipos;
        private int istart, stop;
        private char cmatch;
        private String word;
        private String Strcurrent;
        private Highlighter.HighlightPainter paint = 
                new Painter(Color.LIGHT_GRAY);

        public void keyTyped(KeyEvent e) {
            doUpdate();
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
        }

        public void caretUpdate(CaretEvent e) {
            doUpdate();
        }

        private void doUpdate() {
            try {
                // remove old highlights
                ohl = editText.getHighlighter();
                for (int i = highlights.size()-1; i >= 0; i--) {
                    ohl.removeHighlight(highlights.get(i));
                    highlights.remove(highlights.get(i));
                }
                // get caret ipos
                ipos = editText.getCaret().getDot();
                if (doc.getText(ipos, 1).contains(" ") ||
                        ipos == doc.getLength()) {
                    ipos--;
                }
                // no work for empty document
                if (doc.getLength() == 0) {
                    return;
                }
                //get string to match with: word
                istart = stop = ipos;
                cmatch = doc.getText(istart, 1).toCharArray()[0];
                while (!isMatch(cmatch) && istart > 0) {
                    istart--;
                    cmatch = doc.getText(istart, 1).toCharArray()[0];
                }
                cmatch = doc.getText(stop, 1).toCharArray()[0];
                while (!isMatch(cmatch) && stop < doc.getLength()) {
                    stop++;
                    cmatch = doc.getText(stop, 1).toCharArray()[0];
                }
                word = doc.getText(istart, stop - istart).trim();
                // no work for empty word
                if (word.length() == 0) {
                    return;
                }
                // highlight all matches
                for (int i = 0; i < doc.getLength() - word.length() + 1; i++) {
                    Strcurrent = doc.getText(i, word.length());
                    if (word.contains(Strcurrent)) {
                        Object hl = ohl.addHighlight(i, i + word.length(), paint);
                        highlights.add(hl);
                    }
                }
            } catch (BadLocationException ex) {
                ex.printStackTrace();
            }
        }

        boolean isMatch(char c) {
            // module contains test pattern for highlighter
            if (c == ' '
                    || c == '.'
                    || c == '('
                    || c == ')'
                    || c == ','
                    || c == '='
                    || c == '\n'
                    || c == ';') {
                return true;
            } else {
                return false;
            }
        }

        class Painter extends DefaultHighlighter.DefaultHighlightPainter {
            // replace highlight default
            Painter(Color color) {
                super(color);
            }
        }
    }
}

Your style of coding is different from mine. I can't tell if you have hack openings or not (it's a lot of code to go through) Usually, in my style of coding, I make A Class, Default Constructor, copy constructor etc.. and never return a pointer to my private fields, Which seems to be what you're doing when i see your first class. Although i see a lot of unnecessary this. like this.setSize.. I'm not sure why you did that. You're probably further in programing than me but I never use this. if I don't need to (Even tho it won't hurt to do it at all) but as long as you never pass or return a pointer to a private field accessible to the user, you're fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.