#StackBounty: #java #eclipse #jframe Is it possible for Eclipse to only open one JFrame?

Bounty: 50

When run the project second time, can the previous JFrame closed before open the new one ?

So I no need to close the JFrame when trying to run the project second time.

enter image description here

Is it possible to open only one JFrame?


Get this bounty!!!

#StackBounty: #java #file #http #logging Scanning through logs (tail -f fashion) parsing and sending to a remote server

Bounty: 100

I have a task at hand to build a utility which

  1. Scans through a log file.

  2. Rolls over if a log file is reset.

  3. Scans through each line of the log file.

  4. Each line is sent to an executor service and checks are performed: which include looking for a particular word in the line, if a match is found I forward this line for further processing which includes splitting up the line and forming JSON.

  5. This JSON is sent across to a server using a CloseableHttpCLient with connection keep alive and ServiceUnavailableRetryStrategy patterns.

EntryPoint FileTailReader:(Started from Main)

   public class FileTailReader implements Runnable {

    private final File file;
    private long filePointer;
    private String url;
    private static volatile boolean keepLooping = true; // TODO move to main class
    private static final Logger logger = LogManager.getLogger(Main.class);
    private ExecutorService executor;
    private List<Future<?>> futures;


    public FileTailReader(File file, String url, ExecutorService executor, List<Future<?>> futures) {
        this.file = file;
        this.url = url;
        this.executor = executor;
        this.futures = futures;

    }

    private HttpPost getPost() {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        return httpPost;
    }

    @Override
    public void run() {
        long updateInterval = 100;
        try {
            ArrayList<String> batchArray = new ArrayList<>();
            HttpPost httpPost = getPost();
            CloseableHttpAsyncClient closeableHttpClient = getCloseableClient();
            Path path = Paths.get(file.toURI());
            BasicFileAttributes basicFileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
            Object fileKey = basicFileAttributes.fileKey();
            String iNode = fileKey.toString();  // iNode is common during file roll
            long startTime = System.nanoTime();
            while (keepLooping) {

                Thread.sleep(updateInterval);
                long len = file.length();

                if (len < filePointer) {

                    // Log must have been rolled
                    // We can spawn a new thread here to read the remaining part of the rolled file.
                    // Compare the iNode of the file in tail with every file in the dir, if a match is found
                    // - we have the rolled file
                    // This scenario will occur only if our reader lags behind the writer - No worry

                    RolledFileReader rolledFileReader = new RolledFileReader(iNode, file, filePointer, executor,
                            closeableHttpClient, httpPost, futures);
                    new Thread(rolledFileReader).start();

                    logger.info("Log file was reset. Restarting logging from start of file.");
                    this.appendMessage("Log file was reset. Restarting logging from start of file.");
                    filePointer = len;
                } else if (len > filePointer) {
                    // File must have had something added to it!
                    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
                    randomAccessFile.seek(filePointer);
                    FileInputStream fileInputStream = new FileInputStream(randomAccessFile.getFD());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
                    String bLine;
                    while ((bLine = bufferedReader.readLine()) != null) {
                        // We will use an array to hold 100 lines, so that we can batch process in a
                        // single thread
                        batchArray.add(bLine);
                        switch (batchArray.size()) {

                            case 1000:
                                appendLine((ArrayList<String>) batchArray.clone(), closeableHttpClient, httpPost);
                                batchArray.clear();
                                break;
                        }
                    }

                    if (batchArray.size() > 0) {
                        appendLine((ArrayList<String>) batchArray.clone(), closeableHttpClient, httpPost);
                    }

                    filePointer = randomAccessFile.getFilePointer();
                    randomAccessFile.close();
                    fileInputStream.close();
                    bufferedReader.close();
                   // logger.info("Total time taken: " + ((System.nanoTime() - startTime) / 1e9));

                }

                //boolean allDone = checkIfAllExecuted();
               // logger.info("isAllDone" + allDone + futures.size());

            }
            executor.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
            this.appendMessage("Fatal error reading log file, log tailing has stopped.");
        }
    }

    private void appendMessage(String line) {
        System.out.println(line.trim());
    }

    private void appendLine(ArrayList<String> batchArray, CloseableHttpAsyncClient client, HttpPost httpPost) {
        Future<?> future = executor.submit(new LocalThreadPoolExecutor(batchArray, client, httpPost));
        futures.add(future);

    }

    private boolean checkIfAllExecuted() {
        boolean allDone = true;
        for (Future<?> future : futures) {
            allDone &= future.isDone(); // check if future is done
        }
        return allDone;
    }

    //Reusable connection
    private RequestConfig getConnConfig() {
        return RequestConfig.custom()
                .setConnectionRequestTimeout(5 * 1000)
                .setConnectTimeout(5 * 1000)
                .setSocketTimeout(5 * 1000).build();
    }

    private PoolingNHttpClientConnectionManager getPoolingConnManager() throws IOReactorException {
        ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
        PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
        cm.setMaxTotal(1000);
        cm.setDefaultMaxPerRoute(1000);

        return cm;
    }

    private CloseableHttpAsyncClient getCloseableClient() throws IOReactorException {
        CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClientBuilder.create()
                .setDefaultRequestConfig(getConnConfig())
                .setConnectionManager(getPoolingConnManager()).build();

        httpAsyncClient.start();

        return httpAsyncClient;


                /*.setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                    @Override
                    public boolean retryRequest(
                            final HttpResponse response, final int executionCount, final HttpContext context) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        return statusCode != HttpURLConnection.HTTP_OK && executionCount < 5;
                    }

                    @Override
                    public long getRetryInterval() {
                        return 0;
                    }
                }).build();*/
    }


}

I am using an implementation of Rabin Karp for string find:

public class RabinKarp {
    private final String pat;      // the pattern  // needed only for Las Vegas
    private long patHash;    // pattern hash value
    private int m;           // pattern length
    private long q;          // a large prime, small enough to avoid long overflow
    private final int R;           // radix
    private long RM;         // R^(M-1) % Q

    /**
     * Preprocesses the pattern string.
     *
     * @param pattern the pattern string
     * @param R       the alphabet size
     */
    public RabinKarp(char[] pattern, int R) {
        this.pat = String.valueOf(pattern);
        this.R = R;
        throw new UnsupportedOperationException("Operation not supported yet");
    }

    /**
     * Preprocesses the pattern string.
     *
     * @param pat the pattern string
     */
    public RabinKarp(String pat) {
        this.pat = pat;      // save pattern (needed only for Las Vegas)
        R = 256;
        m = pat.length();
        q = longRandomPrime();

        // precompute R^(m-1) % q for use in removing leading digit
        RM = 1;
        for (int i = 1; i <= m - 1; i++)
            RM = (R * RM) % q;
        patHash = hash(pat, m);
    }

    // Compute hash for key[0..m-1].
    private long hash(String key, int m) {
        long h = 0;
        for (int j = 0; j < m; j++)
            h = (R * h + key.charAt(j)) % q;
        return h;
    }

    // Las Vegas version: does pat[] match txt[i..i-m+1] ?
    private boolean check(String txt, int i) {
        for (int j = 0; j < m; j++)
            if (pat.charAt(j) != txt.charAt(i + j))
                return false;
        return true;
    }

    // Monte Carlo version: always return true
    // private boolean check(int i) {
    //    return true;
    //}

    /**
     * Returns the index of the first occurrrence of the pattern string
     * in the text string.
     *
     * @param txt the text string
     * @return the index of the first occurrence of the pattern string
     * in the text string; n if no such match
     */
    public int search(String txt) {
        int n = txt.length();
        if (n < m) return n;
        long txtHash = hash(txt, m);

        // check for match at offset 0
        if ((patHash == txtHash) && check(txt, 0))
            return 0;

        // check for hash match; if hash match, check for exact match
        for (int i = m; i < n; i++) {
            // Remove leading digit, add trailing digit, check for match.
            txtHash = (txtHash + q - RM * txt.charAt(i - m) % q) % q;
            txtHash = (txtHash * R + txt.charAt(i)) % q;

            // match
            int offset = i - m + 1;
            if ((patHash == txtHash) && check(txt, offset))
                return offset;
        }

        // no match
        return -1;
    }


    // a random 31-bit prime
    private static long longRandomPrime() {
        BigInteger prime = BigInteger.probablePrime(31, new Random());
        return prime.longValue();
    }
}

Here is my RolledFileReader

public class RolledFileReader implements Runnable {

    private static final Logger logger = LogManager.getLogger(RolledFileReader.class);

    private String iNode;
    private File tailedFile;
    private long filePointer;
    private ExecutorService executor;
    private CloseableHttpAsyncClient client;
    private HttpPost httpPost;
    List<Future<?>> futures;

    public RolledFileReader(String iNode, File tailedFile, long filePointer, ExecutorService executor,
                            CloseableHttpAsyncClient client, HttpPost httpPost, List<Future<?>> futures) {
        this.iNode = iNode;
        this.tailedFile = tailedFile;
        this.filePointer = filePointer;
        this.executor = executor;
        this.client = client;
        this.httpPost = httpPost;
        this.futures = futures;
    }

    @Override
    public void run() {
        try {
            inodeReader();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void inodeReader() throws Exception {
        String fParent = tailedFile.getParentFile().toString();
        File[] files = new File(fParent).listFiles();
        if (files != null) {
            Arrays.sort(files, Collections.reverseOrder()); // Probability of finding the file at top increases
            for (File file : files) {
                if (file.isFile()) {
                    Path path = Paths.get(file.toURI());
                    BasicFileAttributes basicFileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
                    Object fileKey = basicFileAttributes.fileKey();
                    String matchInode = fileKey.toString();
                    if (matchInode.equalsIgnoreCase(iNode) && file.length() > filePointer) {
                        //We found a match - now process the remaining file - we are in a separate thread
                        readRolledFile(file, filePointer);

                    }
                }
            }

        }
    }


    public void readRolledFile(File rolledFile, long filePointer) throws Exception {
        ArrayList<String> batchArray = new ArrayList<>();
        RandomAccessFile randomAccessFile = new RandomAccessFile(rolledFile, "r");
        randomAccessFile.seek(filePointer);
        FileInputStream fileInputStream = new FileInputStream(randomAccessFile.getFD());
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
        String bLine;
        while ((bLine = bufferedReader.readLine()) != null) {

            batchArray.add(bLine);
            switch (batchArray.size()) {
                case 1000:
                    executor.execute(new LocalThreadPoolExecutor((ArrayList<String>) batchArray.clone(), client, httpPost));
            }
        }

        if (batchArray.size() > 0) {
            executor.execute(new LocalThreadPoolExecutor((ArrayList<String>) batchArray.clone(), client, httpPost));
        }
    }


}

And my executor service LocalThreadPoolExecutor:

   public class LocalThreadPoolExecutor implements Runnable {
    private static final Logger logger = LogManager.getLogger(Main.class);

    private final ArrayList<String> payload;
    private final CloseableHttpAsyncClient client;
    private final HttpPost httpPost;
    private HttpContext context;
    private final RabinKarp searcher = new RabinKarp("JioEvents");

    public LocalThreadPoolExecutor(ArrayList<String> payload, CloseableHttpAsyncClient client,
                                   HttpPost httpPost) {
        this.payload = payload;
        this.client = client;
        this.httpPost = httpPost;
    }

    @Override
    public void run() {
        try {
            for (String line : payload) {
                int offset = searcher.search(line);
                switch (offset) {
                    case -1:
                        break;
                    default:
                        String zeroIn = line.substring(offset).toLowerCase();
                        String postPayload = processLogs(zeroIn);
                        if (null != postPayload) {
                            postData(postPayload, client, httpPost);
                        }
                }
            }
       // logger.info("Processed a batch of: "+payload.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String processLogs(String line) {
        String[] jsonElements = line.split("\|");
        switch (jsonElements.length) {
            case 15:
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("customerID", jsonElements[1]);
                jsonObject.put("mobileNumber", jsonElements[2]);
                jsonObject.put("eventID", jsonElements[3]);
                jsonObject.put("eventType", jsonElements[4]);
                jsonObject.put("eventDateTime", jsonElements[5]);
                jsonObject.put("eventResponseCode", jsonElements[6]);
                jsonObject.put("sourceSystem", jsonElements[7]);
                jsonObject.put("clientID", jsonElements[8]);
                jsonObject.put("serverHostName", jsonElements[9]);
                jsonObject.put("serverIPAddress", jsonElements[10]);
                jsonObject.put("serverSessionID", jsonElements[11]);
                jsonObject.put("softwareVersion", jsonElements[12]);
                jsonObject.put("deviceInfo", jsonElements[13]);
                jsonObject.put("userAgent", jsonElements[14]);
                return jsonObject.toString();
        }
        return null;
    }

    private void postData(String data, CloseableHttpAsyncClient client, HttpPost httpPost) throws Exception {

        StringEntity entity = new StringEntity(data);
        httpPost.setEntity(entity);
        Future<HttpResponse> future = client.execute(httpPost, context, null);
     //   HttpResponse response = future.get();
     //   logger.info("Resp is: "+response.getStatusLine().getStatusCode());

    }

}

And finally the Main class:

public class Main {
    private static final Logger logger = LogManager.getLogger(Main.class);
    private static final ExecutorService executor = Executors.newFixedThreadPool(25);
    private static final List<Future<?>> futures = new ArrayList<>();

    private static void usage() {
        System.out.println("Invalid usage");
    }

    public static void main(String[] args) {

        if (args.length < 2) {
            usage();
            System.exit(0);
        }
        String url = args[0];
        String fPath = args[1];

        File log = new File(fPath);
        FileTailReader fileTailReader = new FileTailReader(log, url, executor, futures);

        new Thread(fileTailReader).start(); // Can issue multiple threads with an executor like so, for multiple files


    }

}

The purpose of declaring member variables in Main is that I can later on add ShutdownHooks.

I am interested in knowing how I can make this code faster. Right now I am getting a throughput of 300000 lines per 8876 millis. Which is not going well with my peers.

Edit:

I changed the way RandomAccessFile is reading from the file and I have observed a considerable increase in speed, however I am still looking for fresh pointers to enhance and optimize this utility:

else if (len > filePointer) {
                    // File must have had something added to it!
                    long startTime = System.nanoTime();
                    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
                    randomAccessFile.seek(filePointer);
                    FileInputStream fileInputStream = new FileInputStream(randomAccessFile.getFD());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
                    String bLine;
                    logger.info("Pointer: "+filePointer+" fileLength: "+len);
                    while ((bLine = bufferedReader.readLine()) != null) {
                        this.appendLine(bLine, httpclient, httpPost);
                    }
                    logger.info("Total time taken: " + ((System.nanoTime() - startTime) / 1e9));
                    filePointer = randomAccessFile.getFilePointer();
                    logger.info("FilePointer reset to: "+filePointer);
                    randomAccessFile.close();
                    fileInputStream.close();
                    bufferedReader.close();
                }

I also added a bit of batch processing in the above snippet (Code from FileTailReader is edited to demonstrate the same in particular addition of batchArray which is a list) – I see an improvement of 10 seconds. Now the program executes in 21 point some milli seconds.


Get this bounty!!!

#StackBounty: #java #reflection #dependencies How to determine all runtime (but not static) dependencies of Java source by reading the …

Bounty: 50

Let’s say I wanted to assert that a given Java source folder contained all of the source code required to run any of the programs contained in the source folder. Simply showing that the whole source folder compiles would be insufficient because perhaps some of those programs use reflection to instantiate objects. As such I could search through all the code and look for invocations of newInstance() to learn what classes are expected to be present at runtime. But what about calls to Class.forName(...) that are not involved in calls to newInstance() ? Better check for those as well. But how many such things do I need to check for?

Is there any sort of exhaustive list I could consult to ensure that I am considering each way in Java that such a runtime dependency could be introduced? Restated, does there exist some list of operations such that if I can show none of the source in a source folder use those operations (and that folder compiles) that all (code) dependencies are present?

If no such list exists, could we start one in this thread and make a best effort to cover all operations that we know of?

Edit

I’d like to narrow the question a little. What I’m most interested in showing is that if a codebase compiles, all dependencies are present. It seems to me to do this I would need to first compile the codebase and then check to see if any of the code ever calls certain methods (e.g. newInstance) that could introduce a runtime dependency. If no such methods are found, I’m reasonably sure that all required code is present in source form and running the program will not generate a ClassNotFoundException.


Get this bounty!!!

#StackBounty: #java #design-patterns #mvc Is this a correct implementation of Trygve Reenskaug 's MVC specification?

Bounty: 100

So I was reading the MODELS – VIEWS – CONTROLLERS paper by Trygve Reenskaug from December 1979 and wanted to try an implementation with Java Swing from my understandings..

Notes I have taken are as follows:

A view is attached to its model (or model part) and gets the data
necessary for the presentation from the model by asking questions. It
may also update the model by sending appropriate messages. All these
questions and messages have to be in the terminology of the model, the
view will therefore have to know the semantics of the attributes of
the model it represents.

A view should never know about user input, such as mouse operations
and keystrokes. It should always be possible to write a method in a
controller that sends messages to views which exactly reproduce any
sequence of user commands.

A Controller provides means for user input by presenting the user with
menus or other means of giving commands and data. The controller
receives such user input, translates it into the appropriate messages
and pass these messages onto one or more of the views.

The application I worked on is a very simple Note Taking application. This is what the application itself looks like:

enter image description here
enter image description here
enter image description here

Moving on the code, start with Directory Layout..enter image description here

My Model is very simple and knows nothing about Views or Controllers..

package biz.tugay.swingynotes.model;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNote {

    private final String note;

    public SwingyNote(final String note) {
        this.note = note;
    }

    public String getNote() {
        return note;
    }
}

package biz.tugay.swingynotes.model;

import java.util.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public final class SwingyNoteService {

    private final Set<SwingyNote> swingyNotes = new HashSet<SwingyNote>();

    // Add some sample data..
    {
        final SwingyNote sampleNote = new SwingyNote("Sample Note!");
        addNote(sampleNote);

        final SwingyNote helloWorld = new SwingyNote("Hello World!");
        addNote(helloWorld);
    }

    public void addNote(final SwingyNote swingyNote) {
        swingyNotes.add(swingyNote);
    }

    public Collection<SwingyNote> getAllNotes() {
        return swingyNotes;
    }
}

Moving on to View..

package biz.tugay.swingynotes.view;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNotesMainFrame extends JFrame {

    public SwingyNotesMainFrame(final AllNotesPanel allNotesPanel, final AddNewNotePanel addNewNotePanel) {
        super("Swingy Notes");

        // Set Layout..
        final BorderLayout borderLayout = new BorderLayout();
        final Container contentPane = getContentPane();
        contentPane.setLayout(borderLayout);

        // Add panels..
        contentPane.add(allNotesPanel, BorderLayout.CENTER);
        contentPane.add(addNewNotePanel, BorderLayout.SOUTH);

        // Adjust properties and make the frame visible..
        setSize(600, 200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AllNotesPanel extends JPanel {

    private final SwingyNoteService swingyNoteService;

    public AllNotesPanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        displayAllNotes();
    }

    public void displayAllNotes() {
        removeAll();
        final Collection<SwingyNote> allNotes = swingyNoteService.getAllNotes();
        for (final SwingyNote swingyNote : allNotes) {
            final JLabel swingyNoteLabel = buildLabelForSwingyNote(swingyNote);
            add(swingyNoteLabel);
        }
        validate();
        repaint();
    }

    private JLabel buildLabelForSwingyNote(final SwingyNote swingyNote) {
        final JLabel swingyNoteLabel = new JLabel(swingyNote.getNote());
        swingyNoteLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
        swingyNoteLabel.setFont(new Font("Dialog", Font.BOLD, 27));
        swingyNoteLabel.setOpaque(true);
        swingyNoteLabel.setBackground(Color.YELLOW);
        return swingyNoteLabel;
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNotePanel extends JPanel {

    private final SwingyNoteService swingyNoteService;
    private final JTextField newNoteInputTextField;

    public AddNewNotePanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        this.newNoteInputTextField = new JTextField(20);

        add(newNoteInputTextField);
    }

    public void addNote() {
        final SwingyNote swingyNote = new SwingyNote(newNoteInputTextField.getText());
        swingyNoteService.addNote(swingyNote);
        newNoteInputTextField.setText(null);
    }
}

and here is my Controller

package biz.tugay.swingynotes.controller;

import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.AllNotesPanel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNoteButton extends JButton implements ActionListener {

    private final AddNewNotePanel addNewNotePanel;
    private final AllNotesPanel allNotesPanel;

    public AddNewNoteButton(final AddNewNotePanel addNewNotePanel, final AllNotesPanel allNotesPanel) {
        super("Add New Note!");
        addActionListener(this);

        this.addNewNotePanel = addNewNotePanel;
        this.allNotesPanel = allNotesPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        addNewNotePanel.addNote();
        allNotesPanel.displayAllNotes();
    }
}

and this is how I start my Application:

package biz.tugay.swingynotes;

import biz.tugay.swingynotes.controller.AddNewNoteButton;
import biz.tugay.swingynotes.model.SwingyNoteService;
import biz.tugay.swingynotes.view.AllNotesPanel;
import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.SwingyNotesMainFrame;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class App {

    public static void main(String[] args) {

        // Model..
        final SwingyNoteService swingyNoteService = new SwingyNoteService();

        // View..
        final AllNotesPanel allNotesPanel = new AllNotesPanel(swingyNoteService);
        final AddNewNotePanel addNewNotePanel = new AddNewNotePanel(swingyNoteService);

        // Controller..
        final AddNewNoteButton addNewNoteButton = new AddNewNoteButton(addNewNotePanel, allNotesPanel);
        addNewNotePanel.add(addNewNoteButton);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingyNotesMainFrame(allNotesPanel, addNewNotePanel);
            }
        });
    }
}

Do all components seem to be correct?


Get this bounty!!!

#StackBounty: #java #design-patterns #mvc Is this a correct implementation of Trygve Reenskaug 's MVC specification?

Bounty: 100

So I was reading the MODELS – VIEWS – CONTROLLERS paper by Trygve Reenskaug from December 1979 and wanted to try an implementation with Java Swing from my understandings..

Notes I have taken are as follows:

A view is attached to its model (or model part) and gets the data
necessary for the presentation from the model by asking questions. It
may also update the model by sending appropriate messages. All these
questions and messages have to be in the terminology of the model, the
view will therefore have to know the semantics of the attributes of
the model it represents.

A view should never know about user input, such as mouse operations
and keystrokes. It should always be possible to write a method in a
controller that sends messages to views which exactly reproduce any
sequence of user commands.

A Controller provides means for user input by presenting the user with
menus or other means of giving commands and data. The controller
receives such user input, translates it into the appropriate messages
and pass these messages onto one or more of the views.

The application I worked on is a very simple Note Taking application. This is what the application itself looks like:

enter image description here
enter image description here
enter image description here

Moving on the code, start with Directory Layout..enter image description here

My Model is very simple and knows nothing about Views or Controllers..

package biz.tugay.swingynotes.model;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNote {

    private final String note;

    public SwingyNote(final String note) {
        this.note = note;
    }

    public String getNote() {
        return note;
    }
}

package biz.tugay.swingynotes.model;

import java.util.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public final class SwingyNoteService {

    private final Set<SwingyNote> swingyNotes = new HashSet<SwingyNote>();

    // Add some sample data..
    {
        final SwingyNote sampleNote = new SwingyNote("Sample Note!");
        addNote(sampleNote);

        final SwingyNote helloWorld = new SwingyNote("Hello World!");
        addNote(helloWorld);
    }

    public void addNote(final SwingyNote swingyNote) {
        swingyNotes.add(swingyNote);
    }

    public Collection<SwingyNote> getAllNotes() {
        return swingyNotes;
    }
}

Moving on to View..

package biz.tugay.swingynotes.view;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNotesMainFrame extends JFrame {

    public SwingyNotesMainFrame(final AllNotesPanel allNotesPanel, final AddNewNotePanel addNewNotePanel) {
        super("Swingy Notes");

        // Set Layout..
        final BorderLayout borderLayout = new BorderLayout();
        final Container contentPane = getContentPane();
        contentPane.setLayout(borderLayout);

        // Add panels..
        contentPane.add(allNotesPanel, BorderLayout.CENTER);
        contentPane.add(addNewNotePanel, BorderLayout.SOUTH);

        // Adjust properties and make the frame visible..
        setSize(600, 200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AllNotesPanel extends JPanel {

    private final SwingyNoteService swingyNoteService;

    public AllNotesPanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        displayAllNotes();
    }

    public void displayAllNotes() {
        removeAll();
        final Collection<SwingyNote> allNotes = swingyNoteService.getAllNotes();
        for (final SwingyNote swingyNote : allNotes) {
            final JLabel swingyNoteLabel = buildLabelForSwingyNote(swingyNote);
            add(swingyNoteLabel);
        }
        validate();
        repaint();
    }

    private JLabel buildLabelForSwingyNote(final SwingyNote swingyNote) {
        final JLabel swingyNoteLabel = new JLabel(swingyNote.getNote());
        swingyNoteLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
        swingyNoteLabel.setFont(new Font("Dialog", Font.BOLD, 27));
        swingyNoteLabel.setOpaque(true);
        swingyNoteLabel.setBackground(Color.YELLOW);
        return swingyNoteLabel;
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNotePanel extends JPanel {

    private final SwingyNoteService swingyNoteService;
    private final JTextField newNoteInputTextField;

    public AddNewNotePanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        this.newNoteInputTextField = new JTextField(20);

        add(newNoteInputTextField);
    }

    public void addNote() {
        final SwingyNote swingyNote = new SwingyNote(newNoteInputTextField.getText());
        swingyNoteService.addNote(swingyNote);
        newNoteInputTextField.setText(null);
    }
}

and here is my Controller

package biz.tugay.swingynotes.controller;

import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.AllNotesPanel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNoteButton extends JButton implements ActionListener {

    private final AddNewNotePanel addNewNotePanel;
    private final AllNotesPanel allNotesPanel;

    public AddNewNoteButton(final AddNewNotePanel addNewNotePanel, final AllNotesPanel allNotesPanel) {
        super("Add New Note!");
        addActionListener(this);

        this.addNewNotePanel = addNewNotePanel;
        this.allNotesPanel = allNotesPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        addNewNotePanel.addNote();
        allNotesPanel.displayAllNotes();
    }
}

and this is how I start my Application:

package biz.tugay.swingynotes;

import biz.tugay.swingynotes.controller.AddNewNoteButton;
import biz.tugay.swingynotes.model.SwingyNoteService;
import biz.tugay.swingynotes.view.AllNotesPanel;
import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.SwingyNotesMainFrame;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class App {

    public static void main(String[] args) {

        // Model..
        final SwingyNoteService swingyNoteService = new SwingyNoteService();

        // View..
        final AllNotesPanel allNotesPanel = new AllNotesPanel(swingyNoteService);
        final AddNewNotePanel addNewNotePanel = new AddNewNotePanel(swingyNoteService);

        // Controller..
        final AddNewNoteButton addNewNoteButton = new AddNewNoteButton(addNewNotePanel, allNotesPanel);
        addNewNotePanel.add(addNewNoteButton);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingyNotesMainFrame(allNotesPanel, addNewNotePanel);
            }
        });
    }
}

Do all components seem to be correct?


Get this bounty!!!

#StackBounty: #java #design-patterns #mvc Is this a correct implementation of Trygve Reenskaug 's MVC specification?

Bounty: 100

So I was reading the MODELS – VIEWS – CONTROLLERS paper by Trygve Reenskaug from December 1979 and wanted to try an implementation with Java Swing from my understandings..

Notes I have taken are as follows:

A view is attached to its model (or model part) and gets the data
necessary for the presentation from the model by asking questions. It
may also update the model by sending appropriate messages. All these
questions and messages have to be in the terminology of the model, the
view will therefore have to know the semantics of the attributes of
the model it represents.

A view should never know about user input, such as mouse operations
and keystrokes. It should always be possible to write a method in a
controller that sends messages to views which exactly reproduce any
sequence of user commands.

A Controller provides means for user input by presenting the user with
menus or other means of giving commands and data. The controller
receives such user input, translates it into the appropriate messages
and pass these messages onto one or more of the views.

The application I worked on is a very simple Note Taking application. This is what the application itself looks like:

enter image description here
enter image description here
enter image description here

Moving on the code, start with Directory Layout..enter image description here

My Model is very simple and knows nothing about Views or Controllers..

package biz.tugay.swingynotes.model;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNote {

    private final String note;

    public SwingyNote(final String note) {
        this.note = note;
    }

    public String getNote() {
        return note;
    }
}

package biz.tugay.swingynotes.model;

import java.util.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public final class SwingyNoteService {

    private final Set<SwingyNote> swingyNotes = new HashSet<SwingyNote>();

    // Add some sample data..
    {
        final SwingyNote sampleNote = new SwingyNote("Sample Note!");
        addNote(sampleNote);

        final SwingyNote helloWorld = new SwingyNote("Hello World!");
        addNote(helloWorld);
    }

    public void addNote(final SwingyNote swingyNote) {
        swingyNotes.add(swingyNote);
    }

    public Collection<SwingyNote> getAllNotes() {
        return swingyNotes;
    }
}

Moving on to View..

package biz.tugay.swingynotes.view;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNotesMainFrame extends JFrame {

    public SwingyNotesMainFrame(final AllNotesPanel allNotesPanel, final AddNewNotePanel addNewNotePanel) {
        super("Swingy Notes");

        // Set Layout..
        final BorderLayout borderLayout = new BorderLayout();
        final Container contentPane = getContentPane();
        contentPane.setLayout(borderLayout);

        // Add panels..
        contentPane.add(allNotesPanel, BorderLayout.CENTER);
        contentPane.add(addNewNotePanel, BorderLayout.SOUTH);

        // Adjust properties and make the frame visible..
        setSize(600, 200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AllNotesPanel extends JPanel {

    private final SwingyNoteService swingyNoteService;

    public AllNotesPanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        displayAllNotes();
    }

    public void displayAllNotes() {
        removeAll();
        final Collection<SwingyNote> allNotes = swingyNoteService.getAllNotes();
        for (final SwingyNote swingyNote : allNotes) {
            final JLabel swingyNoteLabel = buildLabelForSwingyNote(swingyNote);
            add(swingyNoteLabel);
        }
        validate();
        repaint();
    }

    private JLabel buildLabelForSwingyNote(final SwingyNote swingyNote) {
        final JLabel swingyNoteLabel = new JLabel(swingyNote.getNote());
        swingyNoteLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
        swingyNoteLabel.setFont(new Font("Dialog", Font.BOLD, 27));
        swingyNoteLabel.setOpaque(true);
        swingyNoteLabel.setBackground(Color.YELLOW);
        return swingyNoteLabel;
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNotePanel extends JPanel {

    private final SwingyNoteService swingyNoteService;
    private final JTextField newNoteInputTextField;

    public AddNewNotePanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        this.newNoteInputTextField = new JTextField(20);

        add(newNoteInputTextField);
    }

    public void addNote() {
        final SwingyNote swingyNote = new SwingyNote(newNoteInputTextField.getText());
        swingyNoteService.addNote(swingyNote);
        newNoteInputTextField.setText(null);
    }
}

and here is my Controller

package biz.tugay.swingynotes.controller;

import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.AllNotesPanel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNoteButton extends JButton implements ActionListener {

    private final AddNewNotePanel addNewNotePanel;
    private final AllNotesPanel allNotesPanel;

    public AddNewNoteButton(final AddNewNotePanel addNewNotePanel, final AllNotesPanel allNotesPanel) {
        super("Add New Note!");
        addActionListener(this);

        this.addNewNotePanel = addNewNotePanel;
        this.allNotesPanel = allNotesPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        addNewNotePanel.addNote();
        allNotesPanel.displayAllNotes();
    }
}

and this is how I start my Application:

package biz.tugay.swingynotes;

import biz.tugay.swingynotes.controller.AddNewNoteButton;
import biz.tugay.swingynotes.model.SwingyNoteService;
import biz.tugay.swingynotes.view.AllNotesPanel;
import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.SwingyNotesMainFrame;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class App {

    public static void main(String[] args) {

        // Model..
        final SwingyNoteService swingyNoteService = new SwingyNoteService();

        // View..
        final AllNotesPanel allNotesPanel = new AllNotesPanel(swingyNoteService);
        final AddNewNotePanel addNewNotePanel = new AddNewNotePanel(swingyNoteService);

        // Controller..
        final AddNewNoteButton addNewNoteButton = new AddNewNoteButton(addNewNotePanel, allNotesPanel);
        addNewNotePanel.add(addNewNoteButton);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingyNotesMainFrame(allNotesPanel, addNewNotePanel);
            }
        });
    }
}

Do all components seem to be correct?


Get this bounty!!!

#StackBounty: #java #design-patterns #mvc Is this a correct implementation of Trygve Reenskaug 's MVC specification?

Bounty: 100

So I was reading the MODELS – VIEWS – CONTROLLERS paper by Trygve Reenskaug from December 1979 and wanted to try an implementation with Java Swing from my understandings..

Notes I have taken are as follows:

A view is attached to its model (or model part) and gets the data
necessary for the presentation from the model by asking questions. It
may also update the model by sending appropriate messages. All these
questions and messages have to be in the terminology of the model, the
view will therefore have to know the semantics of the attributes of
the model it represents.

A view should never know about user input, such as mouse operations
and keystrokes. It should always be possible to write a method in a
controller that sends messages to views which exactly reproduce any
sequence of user commands.

A Controller provides means for user input by presenting the user with
menus or other means of giving commands and data. The controller
receives such user input, translates it into the appropriate messages
and pass these messages onto one or more of the views.

The application I worked on is a very simple Note Taking application. This is what the application itself looks like:

enter image description here
enter image description here
enter image description here

Moving on the code, start with Directory Layout..enter image description here

My Model is very simple and knows nothing about Views or Controllers..

package biz.tugay.swingynotes.model;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNote {

    private final String note;

    public SwingyNote(final String note) {
        this.note = note;
    }

    public String getNote() {
        return note;
    }
}

package biz.tugay.swingynotes.model;

import java.util.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public final class SwingyNoteService {

    private final Set<SwingyNote> swingyNotes = new HashSet<SwingyNote>();

    // Add some sample data..
    {
        final SwingyNote sampleNote = new SwingyNote("Sample Note!");
        addNote(sampleNote);

        final SwingyNote helloWorld = new SwingyNote("Hello World!");
        addNote(helloWorld);
    }

    public void addNote(final SwingyNote swingyNote) {
        swingyNotes.add(swingyNote);
    }

    public Collection<SwingyNote> getAllNotes() {
        return swingyNotes;
    }
}

Moving on to View..

package biz.tugay.swingynotes.view;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNotesMainFrame extends JFrame {

    public SwingyNotesMainFrame(final AllNotesPanel allNotesPanel, final AddNewNotePanel addNewNotePanel) {
        super("Swingy Notes");

        // Set Layout..
        final BorderLayout borderLayout = new BorderLayout();
        final Container contentPane = getContentPane();
        contentPane.setLayout(borderLayout);

        // Add panels..
        contentPane.add(allNotesPanel, BorderLayout.CENTER);
        contentPane.add(addNewNotePanel, BorderLayout.SOUTH);

        // Adjust properties and make the frame visible..
        setSize(600, 200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AllNotesPanel extends JPanel {

    private final SwingyNoteService swingyNoteService;

    public AllNotesPanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        displayAllNotes();
    }

    public void displayAllNotes() {
        removeAll();
        final Collection<SwingyNote> allNotes = swingyNoteService.getAllNotes();
        for (final SwingyNote swingyNote : allNotes) {
            final JLabel swingyNoteLabel = buildLabelForSwingyNote(swingyNote);
            add(swingyNoteLabel);
        }
        validate();
        repaint();
    }

    private JLabel buildLabelForSwingyNote(final SwingyNote swingyNote) {
        final JLabel swingyNoteLabel = new JLabel(swingyNote.getNote());
        swingyNoteLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
        swingyNoteLabel.setFont(new Font("Dialog", Font.BOLD, 27));
        swingyNoteLabel.setOpaque(true);
        swingyNoteLabel.setBackground(Color.YELLOW);
        return swingyNoteLabel;
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNotePanel extends JPanel {

    private final SwingyNoteService swingyNoteService;
    private final JTextField newNoteInputTextField;

    public AddNewNotePanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        this.newNoteInputTextField = new JTextField(20);

        add(newNoteInputTextField);
    }

    public void addNote() {
        final SwingyNote swingyNote = new SwingyNote(newNoteInputTextField.getText());
        swingyNoteService.addNote(swingyNote);
        newNoteInputTextField.setText(null);
    }
}

and here is my Controller

package biz.tugay.swingynotes.controller;

import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.AllNotesPanel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNoteButton extends JButton implements ActionListener {

    private final AddNewNotePanel addNewNotePanel;
    private final AllNotesPanel allNotesPanel;

    public AddNewNoteButton(final AddNewNotePanel addNewNotePanel, final AllNotesPanel allNotesPanel) {
        super("Add New Note!");
        addActionListener(this);

        this.addNewNotePanel = addNewNotePanel;
        this.allNotesPanel = allNotesPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        addNewNotePanel.addNote();
        allNotesPanel.displayAllNotes();
    }
}

and this is how I start my Application:

package biz.tugay.swingynotes;

import biz.tugay.swingynotes.controller.AddNewNoteButton;
import biz.tugay.swingynotes.model.SwingyNoteService;
import biz.tugay.swingynotes.view.AllNotesPanel;
import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.SwingyNotesMainFrame;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class App {

    public static void main(String[] args) {

        // Model..
        final SwingyNoteService swingyNoteService = new SwingyNoteService();

        // View..
        final AllNotesPanel allNotesPanel = new AllNotesPanel(swingyNoteService);
        final AddNewNotePanel addNewNotePanel = new AddNewNotePanel(swingyNoteService);

        // Controller..
        final AddNewNoteButton addNewNoteButton = new AddNewNoteButton(addNewNotePanel, allNotesPanel);
        addNewNotePanel.add(addNewNoteButton);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingyNotesMainFrame(allNotesPanel, addNewNotePanel);
            }
        });
    }
}

Do all components seem to be correct?


Get this bounty!!!

#StackBounty: #java #design-patterns #mvc Is this a correct implementation of Trygve Reenskaug 's MVC specification?

Bounty: 100

So I was reading the MODELS – VIEWS – CONTROLLERS paper by Trygve Reenskaug from December 1979 and wanted to try an implementation with Java Swing from my understandings..

Notes I have taken are as follows:

A view is attached to its model (or model part) and gets the data
necessary for the presentation from the model by asking questions. It
may also update the model by sending appropriate messages. All these
questions and messages have to be in the terminology of the model, the
view will therefore have to know the semantics of the attributes of
the model it represents.

A view should never know about user input, such as mouse operations
and keystrokes. It should always be possible to write a method in a
controller that sends messages to views which exactly reproduce any
sequence of user commands.

A Controller provides means for user input by presenting the user with
menus or other means of giving commands and data. The controller
receives such user input, translates it into the appropriate messages
and pass these messages onto one or more of the views.

The application I worked on is a very simple Note Taking application. This is what the application itself looks like:

enter image description here
enter image description here
enter image description here

Moving on the code, start with Directory Layout..enter image description here

My Model is very simple and knows nothing about Views or Controllers..

package biz.tugay.swingynotes.model;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNote {

    private final String note;

    public SwingyNote(final String note) {
        this.note = note;
    }

    public String getNote() {
        return note;
    }
}

package biz.tugay.swingynotes.model;

import java.util.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public final class SwingyNoteService {

    private final Set<SwingyNote> swingyNotes = new HashSet<SwingyNote>();

    // Add some sample data..
    {
        final SwingyNote sampleNote = new SwingyNote("Sample Note!");
        addNote(sampleNote);

        final SwingyNote helloWorld = new SwingyNote("Hello World!");
        addNote(helloWorld);
    }

    public void addNote(final SwingyNote swingyNote) {
        swingyNotes.add(swingyNote);
    }

    public Collection<SwingyNote> getAllNotes() {
        return swingyNotes;
    }
}

Moving on to View..

package biz.tugay.swingynotes.view;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNotesMainFrame extends JFrame {

    public SwingyNotesMainFrame(final AllNotesPanel allNotesPanel, final AddNewNotePanel addNewNotePanel) {
        super("Swingy Notes");

        // Set Layout..
        final BorderLayout borderLayout = new BorderLayout();
        final Container contentPane = getContentPane();
        contentPane.setLayout(borderLayout);

        // Add panels..
        contentPane.add(allNotesPanel, BorderLayout.CENTER);
        contentPane.add(addNewNotePanel, BorderLayout.SOUTH);

        // Adjust properties and make the frame visible..
        setSize(600, 200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AllNotesPanel extends JPanel {

    private final SwingyNoteService swingyNoteService;

    public AllNotesPanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        displayAllNotes();
    }

    public void displayAllNotes() {
        removeAll();
        final Collection<SwingyNote> allNotes = swingyNoteService.getAllNotes();
        for (final SwingyNote swingyNote : allNotes) {
            final JLabel swingyNoteLabel = buildLabelForSwingyNote(swingyNote);
            add(swingyNoteLabel);
        }
        validate();
        repaint();
    }

    private JLabel buildLabelForSwingyNote(final SwingyNote swingyNote) {
        final JLabel swingyNoteLabel = new JLabel(swingyNote.getNote());
        swingyNoteLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
        swingyNoteLabel.setFont(new Font("Dialog", Font.BOLD, 27));
        swingyNoteLabel.setOpaque(true);
        swingyNoteLabel.setBackground(Color.YELLOW);
        return swingyNoteLabel;
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNotePanel extends JPanel {

    private final SwingyNoteService swingyNoteService;
    private final JTextField newNoteInputTextField;

    public AddNewNotePanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        this.newNoteInputTextField = new JTextField(20);

        add(newNoteInputTextField);
    }

    public void addNote() {
        final SwingyNote swingyNote = new SwingyNote(newNoteInputTextField.getText());
        swingyNoteService.addNote(swingyNote);
        newNoteInputTextField.setText(null);
    }
}

and here is my Controller

package biz.tugay.swingynotes.controller;

import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.AllNotesPanel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNoteButton extends JButton implements ActionListener {

    private final AddNewNotePanel addNewNotePanel;
    private final AllNotesPanel allNotesPanel;

    public AddNewNoteButton(final AddNewNotePanel addNewNotePanel, final AllNotesPanel allNotesPanel) {
        super("Add New Note!");
        addActionListener(this);

        this.addNewNotePanel = addNewNotePanel;
        this.allNotesPanel = allNotesPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        addNewNotePanel.addNote();
        allNotesPanel.displayAllNotes();
    }
}

and this is how I start my Application:

package biz.tugay.swingynotes;

import biz.tugay.swingynotes.controller.AddNewNoteButton;
import biz.tugay.swingynotes.model.SwingyNoteService;
import biz.tugay.swingynotes.view.AllNotesPanel;
import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.SwingyNotesMainFrame;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class App {

    public static void main(String[] args) {

        // Model..
        final SwingyNoteService swingyNoteService = new SwingyNoteService();

        // View..
        final AllNotesPanel allNotesPanel = new AllNotesPanel(swingyNoteService);
        final AddNewNotePanel addNewNotePanel = new AddNewNotePanel(swingyNoteService);

        // Controller..
        final AddNewNoteButton addNewNoteButton = new AddNewNoteButton(addNewNotePanel, allNotesPanel);
        addNewNotePanel.add(addNewNoteButton);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingyNotesMainFrame(allNotesPanel, addNewNotePanel);
            }
        });
    }
}

Do all components seem to be correct?


Get this bounty!!!

#StackBounty: #java #design-patterns #mvc Is this a correct implementation of Trygve Reenskaug 's MVC specification?

Bounty: 100

So I was reading the MODELS – VIEWS – CONTROLLERS paper by Trygve Reenskaug from December 1979 and wanted to try an implementation with Java Swing from my understandings..

Notes I have taken are as follows:

A view is attached to its model (or model part) and gets the data
necessary for the presentation from the model by asking questions. It
may also update the model by sending appropriate messages. All these
questions and messages have to be in the terminology of the model, the
view will therefore have to know the semantics of the attributes of
the model it represents.

A view should never know about user input, such as mouse operations
and keystrokes. It should always be possible to write a method in a
controller that sends messages to views which exactly reproduce any
sequence of user commands.

A Controller provides means for user input by presenting the user with
menus or other means of giving commands and data. The controller
receives such user input, translates it into the appropriate messages
and pass these messages onto one or more of the views.

The application I worked on is a very simple Note Taking application. This is what the application itself looks like:

enter image description here
enter image description here
enter image description here

Moving on the code, start with Directory Layout..enter image description here

My Model is very simple and knows nothing about Views or Controllers..

package biz.tugay.swingynotes.model;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNote {

    private final String note;

    public SwingyNote(final String note) {
        this.note = note;
    }

    public String getNote() {
        return note;
    }
}

package biz.tugay.swingynotes.model;

import java.util.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public final class SwingyNoteService {

    private final Set<SwingyNote> swingyNotes = new HashSet<SwingyNote>();

    // Add some sample data..
    {
        final SwingyNote sampleNote = new SwingyNote("Sample Note!");
        addNote(sampleNote);

        final SwingyNote helloWorld = new SwingyNote("Hello World!");
        addNote(helloWorld);
    }

    public void addNote(final SwingyNote swingyNote) {
        swingyNotes.add(swingyNote);
    }

    public Collection<SwingyNote> getAllNotes() {
        return swingyNotes;
    }
}

Moving on to View..

package biz.tugay.swingynotes.view;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class SwingyNotesMainFrame extends JFrame {

    public SwingyNotesMainFrame(final AllNotesPanel allNotesPanel, final AddNewNotePanel addNewNotePanel) {
        super("Swingy Notes");

        // Set Layout..
        final BorderLayout borderLayout = new BorderLayout();
        final Container contentPane = getContentPane();
        contentPane.setLayout(borderLayout);

        // Add panels..
        contentPane.add(allNotesPanel, BorderLayout.CENTER);
        contentPane.add(addNewNotePanel, BorderLayout.SOUTH);

        // Adjust properties and make the frame visible..
        setSize(600, 200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

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

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AllNotesPanel extends JPanel {

    private final SwingyNoteService swingyNoteService;

    public AllNotesPanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        displayAllNotes();
    }

    public void displayAllNotes() {
        removeAll();
        final Collection<SwingyNote> allNotes = swingyNoteService.getAllNotes();
        for (final SwingyNote swingyNote : allNotes) {
            final JLabel swingyNoteLabel = buildLabelForSwingyNote(swingyNote);
            add(swingyNoteLabel);
        }
        validate();
        repaint();
    }

    private JLabel buildLabelForSwingyNote(final SwingyNote swingyNote) {
        final JLabel swingyNoteLabel = new JLabel(swingyNote.getNote());
        swingyNoteLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
        swingyNoteLabel.setFont(new Font("Dialog", Font.BOLD, 27));
        swingyNoteLabel.setOpaque(true);
        swingyNoteLabel.setBackground(Color.YELLOW);
        return swingyNoteLabel;
    }
}

package biz.tugay.swingynotes.view;

import biz.tugay.swingynotes.model.SwingyNote;
import biz.tugay.swingynotes.model.SwingyNoteService;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNotePanel extends JPanel {

    private final SwingyNoteService swingyNoteService;
    private final JTextField newNoteInputTextField;

    public AddNewNotePanel(final SwingyNoteService swingyNoteService) {
        this.swingyNoteService = swingyNoteService;
        this.newNoteInputTextField = new JTextField(20);

        add(newNoteInputTextField);
    }

    public void addNote() {
        final SwingyNote swingyNote = new SwingyNote(newNoteInputTextField.getText());
        swingyNoteService.addNote(swingyNote);
        newNoteInputTextField.setText(null);
    }
}

and here is my Controller

package biz.tugay.swingynotes.controller;

import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.AllNotesPanel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class AddNewNoteButton extends JButton implements ActionListener {

    private final AddNewNotePanel addNewNotePanel;
    private final AllNotesPanel allNotesPanel;

    public AddNewNoteButton(final AddNewNotePanel addNewNotePanel, final AllNotesPanel allNotesPanel) {
        super("Add New Note!");
        addActionListener(this);

        this.addNewNotePanel = addNewNotePanel;
        this.allNotesPanel = allNotesPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        addNewNotePanel.addNote();
        allNotesPanel.displayAllNotes();
    }
}

and this is how I start my Application:

package biz.tugay.swingynotes;

import biz.tugay.swingynotes.controller.AddNewNoteButton;
import biz.tugay.swingynotes.model.SwingyNoteService;
import biz.tugay.swingynotes.view.AllNotesPanel;
import biz.tugay.swingynotes.view.AddNewNotePanel;
import biz.tugay.swingynotes.view.SwingyNotesMainFrame;

import javax.swing.*;

/* User: koray@tugay.biz Date: 2017/05/12 */
public class App {

    public static void main(String[] args) {

        // Model..
        final SwingyNoteService swingyNoteService = new SwingyNoteService();

        // View..
        final AllNotesPanel allNotesPanel = new AllNotesPanel(swingyNoteService);
        final AddNewNotePanel addNewNotePanel = new AddNewNotePanel(swingyNoteService);

        // Controller..
        final AddNewNoteButton addNewNoteButton = new AddNewNoteButton(addNewNotePanel, allNotesPanel);
        addNewNotePanel.add(addNewNoteButton);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingyNotesMainFrame(allNotesPanel, addNewNotePanel);
            }
        });
    }
}

Do all components seem to be correct?


Get this bounty!!!

#StackBounty: #java #jpa #docker #keycloak Bottleneck when using auth/admin/realms/myrealm/users in my app

Bounty: 350

I am running a script which requests the master token before requesting the list of users for a realm. I perform this request in a tight loop 100 times and output the time it takes to perform the “auth/admin/realms/mine/users?first=0&max=1000” request. When testing with a locally installed keycloak docker, a single request is taking 4.0 seconds. If I run 5 instances of this script at the same time, a single request takes around 10 seconds. And if I run 10 instances, it jumps to 20 seconds before a reply is received. Therefore, I have a serious bottleneck in my webapp on the page where I list all user information and was wondering how I might go about solving this problem. I am running keycloak 2.5.0.Final. My java home is /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.111-2.b15.el7_3.x86_64/jre. authorizationPersister = jpa.

My script:

import requests

keyCloakUrl = "http://foo.bar"

for i in range(100):

    session = requests.Session()
    r = session.post(
        keyCloakUrl +"auth/realms/master/protocol/openid-connect/token", 
        data={
            "grant_type":"password",
            "client_id":"admin-cli",
            "username":"admin",
            "password":"admin"
        }
    )
    master_token = json.loads(r.content)['access_token']

    r = s.get(
        keyCloakUrl + "auth/admin/realms/mine/users?first=0&max=1000",
        headers={'Authorization':'Bearer '+master_token}
    )
    print(r.elapsed.total_seconds())

My dockerfile:

FROM jboss/keycloak-mysql:2.5.0.Final

ARG db2

ADD deps/ /opt/jboss/keycloak/
RUN /opt/jboss/keycloak/import_utbud_realm.sh 

CMD ["-b", "0.0.0.0", "-bmanagement", "0.0.0.0", "-Djboss.socket.binding.port-offset=2"]

UPDATE

I also tried measuring the time for the “auth/realms/master/protocol/openid-connect/token” request. This is 0.1 seconds per request with only one instance of the script running and 0.8 seconds with 10 instances running.


Get this bounty!!!