    /**
     * Schedules a {@link SelectionChangeEvent} to fire at the
     * end of the current event loop.
     */
    protected void scheduleSelectionChangeEvent() {
      setEventCancelled(false);
      if (!isEventScheduled()) {
        setEventScheduled(true);
        Scheduler.get().scheduleFinally(() -> {
          setEventScheduled(false);
          if (isEventCancelled()) {
            setEventCancelled(false);
            return;
          }
          fireSelectionChangeEvent();
        });
      }
    }

    /**
     * Schedules a {@link SelectionChangeEvent} to fire at the
     * end of the current event loop.
     */
    protected void scheduleSelectionChangeEvent() {
      setEventCancelled(false);
      if (!isEventScheduled()) {
        setEventScheduled(true);
        Scheduler.get().scheduleFinally(new ScheduledCommand() {
          public void execute() {
            setEventScheduled(false);
            if (isEventCancelled()) {
              setEventCancelled(false);
              return;
            }
            fireSelectionChangeEvent();
          }
        });
      }
    }

Replace Anonymous With Lambda org.gwtproject.view.client.SelectionModel.AbstractSelectionModel.scheduleSelectionChangeEvent.scheduleFinally.new ScheduledCommand with () -> {setEventScheduled(false); in method protected scheduleSelectionChangeEvent() : void from class org.gwtproject.view.client.SelectionModel.AbstractSelectionModel


  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    LOG.info("channel read start");

    CompletableFuture.supplyAsync(() -> handleRequest((Request) msg))
        .thenApply(
            resp ->
                ctx.writeAndFlush(resp)
                    .addListener(
                        new ChannelFutureListener() {
                          @Override
                          public void operationComplete(ChannelFuture channelFuture)
                              throws Exception {
                            LOG.info("finished write to client");
                          }
                        }));
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    LOG.info(String.format("thread id: %d channel read start", Thread.currentThread().getId()));
    var resp = handleRequest((Request) msg);

    // this call to write will call all the ChannelOutboundHandlerAdapter(s)
    ctx.writeAndFlush(resp)
        .addListener(
            new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture channelFuture) throws Exception {
                LOG.info("finished write to client");
              }
            });
  }

Replace Anonymous With Lambda org.example.netty.server.handler.inbound.BusinessLogicHandler.channelRead.addListener.new ChannelFutureListener with resp -> ctx.writeAndFlush(resp).addListener(new ChannelFutureListener(){ in method public channelRead(ctx ChannelHandlerContext, msg Object) : void from class org.example.netty.server.handler.inbound.BusinessLogicHandler


    private void next(String projectName) {
        NucleiConfig.projectName = projectName;

        // 创建后台任务，启动主程序
        SwingWorker<String, Object> task = new SwingWorker<>() {
            @Override
            protected String doInBackground() {
                // 程序加载进度条
                showDisabledStatus();

                NucleiApp.createGUI();
                return "OK";
            }

            @Override
            protected void done() {
                // 此方法将在后台任务完成后在事件调度线程中被回调
                // 取消启动窗口
                StartupFrame.this.dispose();
            }
        };

        // 启动任务
        task.execute();
    }

    private void next(String projectName) {
        NucleiConfig.projectName = projectName;

        // 启动主程序
//        SwingUtilities.invokeLater(NucleiApp::createGUI);
        // 创建后台任务
        SwingWorker<String, Object> task = new SwingWorker<String, Object>() {
            @Override
            protected String doInBackground() {
                // 程序加载进度条
                showDisabledStatus();

                NucleiApp.createGUI();
                return "OK";
            }
            @Override
            protected void done() {
                // 此方法将在后台任务完成后在事件调度线程中被回调
                // 取消启动窗口
                StartupFrame.this.dispose();
            }
        };

        // 启动任务
        task.execute();
    }

Replace Generic With Diamond SwingWorker<String,Object> with SwingWorker<> in method private next(projectName String) : void from class com.g3g4x5x6.StartupFrame


    public ArrayList<Float> calc(ArrayList<Float> input, ArrayList<Float> bias) {
        ArrayList<Float> ans = new ArrayList<>();
        if (height != input.size()) {
            System.out.println("Height of the matrix=" + height + " differs from the with of the vector=" + input.size());
            System.exit(0);
        } else {
            for (int i = 0; i < width; i++) {
                float aux = bias.get(i);
                for (int j = 0; j < height; j++)
                    aux += w[j][i] * input.get(j);
                ans.add(aux);
            }
        }
        return ans;
    }

    public ArrayList<Float> calc(ArrayList<Float> input, ArrayList<Float> bias) {
        ArrayList<Float> ans = new ArrayList<Float>();
        if (height != input.size()) {
            System.out.println("Height of the matrix=" + height + " differs from the with of the vector=" + input.size());
            System.exit(0);
        } else {
            for (int i = 0; i < width; i++) {
                float aux = bias.get(i);
                for (int j = 0; j < height; j++)
                    aux += w[j][i] * input.get(j);
                ans.add(aux);
            }
        }
        return ans;
    }

Replace Generic With Diamond ArrayList<Float> with ArrayList<> in method public calc(input ArrayList<Float>, bias ArrayList<Float>) : ArrayList<Float> from class com.example.Matrix


    private ArrayList<Float> sigmoid(ArrayList<Float> v) {
        ArrayList<Float> ans = new ArrayList<>();
        for (Float x : v) ans.add(1 / (1 + exp(-x)));
        return ans;
    }

    private ArrayList<Float> sigmoid(ArrayList<Float> v) {
        ArrayList<Float> ans = new ArrayList<Float>();
        for (Float x : v) ans.add(1 / (1 + exp(-x)));
        return ans;
    }

Replace Generic With Diamond ArrayList<Float> with ArrayList<> in method private sigmoid(v ArrayList<Float>) : ArrayList<Float> from class com.example.NeuralNetwork


    NeuralNetwork(int[] v) {
        bias = (ArrayList<Float>[]) new ArrayList[v.length];
        weights = new Matrix[v.length - 1];
        for (int i = 0; i < v.length; i++) {
            if (i != v.length - 1)//last layer
                weights[i] = new Matrix(v[i], v[i + 1], minWeight, maxWeight);
            bias[i] = new ArrayList<>();
            initialize(bias[i], v[i]);
        }
    }

    NeuralNetwork(int[] v) {
        bias = (ArrayList<Float>[]) new ArrayList[v.length];
        weights = new Matrix[v.length - 1];
        for (int i = 0; i < v.length; i++) {
            if (i != v.length - 1)//last layer
                weights[i] = new Matrix(v[i], v[i + 1], minWeight, maxWeight);
            bias[i] = new ArrayList<Float>();
            initialize(bias[i], v[i]);
        }
    }

Replace Generic With Diamond ArrayList<Float> with ArrayList<> in method package NeuralNetwork(v int[]) from class com.example.NeuralNetwork


    public DatabaseJsonDao(String filename) {
        this.filename = filename;
        this.citations = new ArrayList<>();
    }

	public DatabaseJsonDao(String filename) {
		this.filename = filename;
		this.citations = new ArrayList<Citation>();
	}

Replace Generic With Diamond ArrayList<Citation> with ArrayList<> in method public DatabaseJsonDao(filename String) from class com.ohtukki.citations.data.DatabaseJsonDao


    public List<Citation> allByPredicate(Predicate<Citation> predicate) {
        Iterable<Citation> c = Iterables.filter(citations,	predicate);
        List<Citation> targetCollection = new ArrayList<>();
        for (Iterator iterator = c.iterator(); iterator.hasNext();) {
            Citation citation = (Citation) iterator.next();
            targetCollection.add(citation);
        }

        return targetCollection;
    }

	public List<Citation> allByPredicate(Predicate<Citation> predicate) {
		Iterable<Citation> c = Iterables.filter(citations,	predicate);
		List<Citation> targetCollection = new ArrayList<Citation>();
		for (Iterator iterator = c.iterator(); iterator.hasNext();) {
			Citation citation = (Citation) iterator.next();
			targetCollection.add(citation);
		}

		return targetCollection;
	}

Replace Generic With Diamond ArrayList<Citation> with ArrayList<> in method public allByPredicate(predicate Predicate<Citation>) : List<Citation> from class com.ohtukki.citations.data.DatabaseJsonDao


                            @Override
                            protected void startServerSocket() {
                                try ( ServerSocket serverSocket = new ServerSocket(0)){

                                    System.out.println(
                                            "Server started on port "
                                                    + serverSocket.getLocalPort());
                                } catch (IOException e) {
                                    System.out.println("Error starting server: " + e.getMessage());
                                }
                            }

                            @Override
                            protected void startServerSocket() {
                                try {
                                    ServerSocket serverSocket = new ServerSocket(0); // Use any available port
                                    System.out.println(
                                            "Server started on port "
                                                    + serverSocket.getLocalPort());
                                } catch (IOException e) {
                                    System.out.println("Error starting server: " + e.getMessage());
                                }
                            }

Try With Resources try(ServerSocket serverSocket=new ServerSocket(0)) in method protected startServerSocket() : void from class dk.dtu.core.onlineTests.GameServerTest.setUp.spy.new GameServer


    public List<String> discover() {
        List<String> servers = new ArrayList<>();
        try (DatagramSocket socket = new DatagramSocket();) {

            socket.setSoTimeout(5000);

            byte[] sendData = M_SEARCH_MESSAGE.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName(SSDP_IP), SSDP_PORT);
            socket.send(sendPacket);

            executorService.execute(() -> {
                byte[] receiveData = new byte[1024];
                while (true) {
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    try {
                        socket.receive(receivePacket);
                        String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
                        if (response.contains("LOCATION")) {
                            String serverIp = extractIp(response);
                            if (serverIp != null && !servers.contains(serverIp)) {
                                servers.add(serverIp);
                            }
                        }
                    } catch (IOException e) {
                        break; // Timeout reached, stop listening
                    }
                }
            });

            Thread.sleep(6000); // Wait for responses

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return servers;
    }

    public List<String> discover() {
        List<String> servers = new ArrayList<>();
        try {
            DatagramSocket socket = new DatagramSocket();
            socket.setSoTimeout(5000);

            byte[] sendData = M_SEARCH_MESSAGE.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName(SSDP_IP), SSDP_PORT);
            socket.send(sendPacket);

            executorService.execute(() -> {
                byte[] receiveData = new byte[1024];
                while (true) {
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    try {
                        socket.receive(receivePacket);
                        String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
                        if (response.contains("LOCATION")) {
                            String serverIp = extractIp(response);
                            if (serverIp != null && !servers.contains(serverIp)) {
                                servers.add(serverIp);
                            }
                        }
                    } catch (IOException e) {
                        break; // Timeout reached, stop listening
                    }
                }
            });

            Thread.sleep(6000); // Wait for responses

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return servers;
    }

Try With Resources try(DatagramSocket socket=new DatagramSocket()) in method public discover() : List<String> from class dk.dtu.engine.utility.SSDPClient


        @Override
        public void run() {
            try (BufferedReader in =
                    new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
                String message;
                while ((message = in.readLine()) != null) {
                    processMessage(message); // Process each message from the client
                }
            } catch (IOException e) {
                logger.error("Error handling client message: {}", e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                    synchronized (lock) {
                        clientWriters.remove(clientSocket); // Remove the client from the map
                    }
                } catch (IOException e) {
                    logger.error("Error stopping client socket: {}", e.getMessage());
                }
            }
        }

        @Override
        public void run() {
            try {
                BufferedReader in =
                        new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String message;
                while ((message = in.readLine()) != null) {
                    processMessage(message); // Process each message from the client
                }
            } catch (IOException e) {
                logger.error("Error handling client message: {}", e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                    synchronized (lock) {
                        clientWriters.remove(clientSocket); // Remove the client from the map
                    }
                } catch (IOException e) {
                    logger.error("Error stopping client socket: {}", e.getMessage());
                }
            }
        }

Try With Resources try(BufferedReader in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) in method public run() : void from class dk.dtu.engine.utility.GameServer.ClientHandler


    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket(PORT)) {
            byte[] buffer = new byte[256];
            System.out.println("Server listening on port " + PORT);

            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);

                String received = new String(packet.getData(), 0, packet.getLength());
                if ("DISCOVER_SERVER_REQUEST".equals(received)) {
                    String response = "DISCOVER_SERVER_RESPONSE";
                    byte[] responseData = response.getBytes();

                    DatagramPacket responsePacket = new DatagramPacket(
                            responseData, responseData.length, packet.getAddress(), packet.getPort()
                    );
                    socket.send(responsePacket);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String multicastAddress = "239.255.255.250";
        int port = 1900;

        try {
            InetAddress group = InetAddress.getByName(multicastAddress);
            MulticastSocket socket = new MulticastSocket(port);
            socket.joinGroup(group);

            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

            System.out.println("Waiting for multicast message...");
            socket.receive(packet);
            String message = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Received multicast message: " + message);

            socket.leaveGroup(group);
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(DatagramSocket socket=new DatagramSocket(PORT)) in method public main(args String[]) : void from class dk.dtu.engine.utility.Server


            @Override
            public void run() {
                try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) {
                    String message;
                    while ((message = in.readLine()) != null) {
                        processMessage(message);
                    }
                } catch (IOException e) {
                    logger.error("Error handling client message: {}", e.getMessage());
                } finally {
                    try {
                        clientSocket.close();
                        synchronized (lock) {
                            clientWriters.remove(clientSocket);
                        }
                    } catch (IOException e) {
                        closingSocketErr(e);
                    }
                }
            }

            @Override
            public void run() {
                try {
                    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    String message;
                    while ((message = in.readLine()) != null) {
                        processMessage(message);
                    }
                } catch (IOException e) {
                    logger.error("Error handling client message: {}", e.getMessage());
                } finally {
                    try {
                        clientSocket.close();
                        synchronized (lock) {
                            clientWriters.remove(clientSocket);
                        }
                    } catch (IOException e) {
                        logger.error("Error closing client socket: {}", e.getMessage());
                    }
                }
            }


    public void removeHeart() {
        try {
            if (emptyHeartImage == null) {
                emptyHeartImage =
                        ImageIO.read(
                                Objects.requireNonNull(
                                        getClass().getResource("/pixel-frame-0.png")));
                Image scaledEmptyHeartImage =
                        emptyHeartImage.getScaledInstance(40, 40, Image.SCALE_SMOOTH);
                emptyHeartIcon = new ImageIcon(scaledEmptyHeartImage);
            }
        } catch (IOException | NullPointerException e) {
            System.out.println("Image not found, check the path.");
        }

        // Find the last "full" heart label and update its icon directly
        int lastIndex = -1;
        for (int i = 0; i < heartStates.length; i++) {
            if (heartStates[i]) { // Check if the heart is marked as full
                lastIndex = i;
            }
        }

        if (lastIndex != -1) {
            Component comp = heartsPanel.getComponent(lastIndex);
            if (comp instanceof JLabel label) {
                label.setIcon(emptyHeartIcon);
                heartStates[lastIndex] = false; // Update state to empty
                System.out.println("Heart emptied at index: " + lastIndex);
            }
        } else {
            System.out.println("No full heart found to replace");
        }

        heartsPanel.revalidate();
        heartsPanel.repaint();
    }

    public void removeHeart() {
        try {
            if (emptyHeartImage == null) {
                emptyHeartImage =
                        ImageIO.read(
                                Objects.requireNonNull(
                                        getClass().getResource("/pixil-frame-0.png")));
                Image scaledEmptyHeartImage =
                        emptyHeartImage.getScaledInstance(40, 40, Image.SCALE_SMOOTH);
                emptyHeartIcon = new ImageIcon(scaledEmptyHeartImage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            System.out.println("Image not found, check the path."); // Debug message
        }

        // Find the last "full" heart label and update its icon directly
        int lastIndex = -1;
        for (int i = 0; i < heartStates.length; i++) {
            if (heartStates[i]) { // Check if the heart is marked as full
                lastIndex = i;
            }
        }

        if (lastIndex != -1) {
            Component comp = heartsPanel.getComponent(lastIndex);
            if (comp instanceof JLabel label) {
                label.setIcon(emptyHeartIcon);
                heartStates[lastIndex] = false; // Update state to empty
                System.out.println("Heart emptied at index: " + lastIndex);
            }
        } else {
            System.out.println("No full heart found to replace");
        }

        heartsPanel.revalidate();
        heartsPanel.repaint();
    }

Merge Catch [catch(NullPointerException e), catch(IOException e)] to catch(IOException|NullPointerException e) in method public removeHeart() : void from class dk.dtu.engine.core.WindowManager


    public void setHeart() {
        try {
            if (heartImage == null) {
                heartImage =
                        ImageIO.read(
                                Objects.requireNonNull(getClass().getResource("/redHeart.png")));
                Image scaledHeartImage = heartImage.getScaledInstance(40, 40, Image.SCALE_SMOOTH);
                heartIcon = new ImageIcon(scaledHeartImage);
            }

        } catch (IOException | NullPointerException e) {
            System.out.println("Image not found, check the path.");
        }

        for (int i = 0; i < heartsPanel.getComponentCount(); i++) {
            Component comp = heartsPanel.getComponent(i);
            if (comp instanceof JLabel label) {
                label.setIcon(heartIcon); // Set each heart to full
                heartStates[i] = true; // Mark the heart as full
            }
        }
        heartsPanel.revalidate();
        heartsPanel.repaint();
    }

    public void setHeart() {
        try {
            if (heartImage == null) {
                heartImage =
                        ImageIO.read(
                                Objects.requireNonNull(getClass().getResource("/redHeart.png")));
                Image scaledHeartImage = heartImage.getScaledInstance(40, 40, Image.SCALE_SMOOTH);
                heartIcon = new ImageIcon(scaledHeartImage);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            System.out.println("Image not found, check the path."); // Debug message
        }

        for (int i = 0; i < heartsPanel.getComponentCount(); i++) {
            Component comp = heartsPanel.getComponent(i);
            if (comp instanceof JLabel label) {
                label.setIcon(heartIcon); // Set each heart to full
                heartStates[i] = true; // Mark the heart as full
            }
        }
        heartsPanel.revalidate();
        heartsPanel.repaint();
    }

Merge Catch [catch(NullPointerException e), catch(IOException e)] to catch(IOException|NullPointerException e) in method public setHeart() : void from class dk.dtu.engine.core.WindowManager


    private Callable<Boolean> timerHasReachedOneSecond() {
        return () -> {
            String time = timer.getTimeString();
            return time.compareTo("00:00:01") >= 0;
        };
    }

    private Callable<Boolean> timerHasReachedOneSecond() {
        return new Callable<Boolean>() {
            public Boolean call() {
                String time = timer.getTimeString();
                return time.compareTo("00:00:01") >= 0;
            }
        };
    }

Replace Anonymous With Lambda dk.dtu.core.TimerTest.timerHasReachedOneSecond.new Callable<Boolean> with () -> {String time=timer.getTimeString(); in method private timerHasReachedOneSecond() : Callable<Boolean> from class dk.dtu.core.TimerTest


    @Override
    public Stream<? extends Arguments> provideArguments(ExtensionContext context) {

        try (MongoClient mongoClient = mongoClient()) {
            MongoCollection<Document> filingHistoryCollection = getFilingHistoryCollection(mongoClient);
            RestClient queueApiClient = getQueueApiRestClient();

            filingHistoryCollection.deleteMany(new Document());

            Queue<Arguments> queue = new ConcurrentLinkedQueue<>();
            findAllDeltas().forEach(deltas -> {

                try {
                    if (deltas.javaDelta() != null && deltas.perlDelta() != null) {
                        DocumentContext delta = JsonPath.parse(deltas.javaDelta());
                        String entityId = delta.read("$.filing_history[0].entity_id");
                        String formType = delta.read("$.filing_history[0].form_type");

                        if (!EXCLUSIONS.contains(entityId)) {

                            postDelta(deltas.perlDelta(), queueApiClient);

                            Document perlDocument = findPerlDocument(filingHistoryCollection, formType, entityId);
                            String expectedRequestBody = transformToPutRequest(perlDocument, delta);

                            queue.add(Arguments.of(getCategory(perlDocument), formType, entityId, deltas.javaDelta(),
                                    expectedRequestBody));
                        }

                    } else {
                        logger.warn("No delta JSON found for transaction {}", deltas.entity_id());
                    }
                } catch (RuntimeException e) {
                    logger.error("Processing failed for delta: transaction_id {}, Java {}, Perl {}",
                            deltas.entity_id(), deltas.javaDelta(), deltas.perlDelta());
                }
            });
            logger.info("Done");
            return queue.stream();
        } catch (Exception e) {
            logger.error("Failed accessing the CHIPS database", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Stream<? extends Arguments> provideArguments(ExtensionContext context) {

        try {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(chipsSource());
            MongoClient mongoClient = mongoClient();
            MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, COMPANY_FILING_HISTORY);
            MongoCollection<Document> filingHistoryCollection = mongoTemplate.getCollection(COMPANY_FILING_HISTORY);
            RestClient queueApiClient = RestClient.builder()
                    .baseUrl(QUEUE_API_URL)
                    .defaultHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_VALUE)
                    .build();

            filingHistoryCollection.deleteMany(new Document());

            Queue<Arguments> queue = new ConcurrentLinkedQueue<>();
            jdbcTemplate.query(FIND_ALL_DELTAS, (rs, rowNum) -> new Deltas(
                            rs.getString("entity_id"),
                            rs.getString("api_delta"),
                            rs.getString("queue_delta")))
                    .forEach(deltas -> {

                        try {
                            if (deltas.javaDelta() != null && deltas.perlDelta() != null) {

                                postDeltaToQueueApi(deltas.perlDelta(), queueApiClient);

                                DocumentContext delta = JsonPath.parse(deltas.javaDelta());
                                String entityId = delta.read("$.filing_history[0].entity_id");
                                String formType = delta.read("$.filing_history[0].form_type");

                                Document perlDocument = findPerlDocument(filingHistoryCollection, formType, entityId);
                                String expectedRequestBody = transformToPutRequest(perlDocument, delta);

                                queue.add(
                                        Arguments.of(getCategory(perlDocument), formType, entityId, deltas.javaDelta(),
                                        expectedRequestBody));

                            } else {
                                logger.warn("No delta JSON found for transaction {}", deltas.entity_id());
                            }
                        } catch (RuntimeException e) {
                            logger.error("Processing failed for delta: transaction_id {}, Java {}, Perl {}",
                                    deltas.entity_id(), deltas.javaDelta(), deltas.perlDelta());
                        }
                    });
            logger.info("Done");
            return queue.stream();
        } catch (SQLException e) {
            logger.error("Failed accessing the CHIPS database", e);
            throw new RuntimeException(e);
        }
    }

Try With Resources try(MongoClient mongoClient=mongoClient()) in method public provideArguments(context ExtensionContext) : Stream<? extends Arguments> from class uk.gov.companieshouse.filinghistory.consumer.kafka.IntegrationDataGenerator


    public static void main(String[] args) {
        System.out.println("Starting server");
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

        try (ServerSocket listener = new ServerSocket(PORT, BACKLOG)) {
            System.out.println("Waiting for clients on port " + PORT);
            System.out.println();

            while (true) {
                Socket socket = listener.accept();
                executor.submit(() -> handleClient(socket));
            }
        } catch (IOException e) {
            System.err.println("Server exception: " + e);
        } finally {
            executor.shutdown();
        }
    }

    public static void main(String[] args) {
        System.out.println("start server...");
        try {
            ServerSocket listener = new ServerSocket(10001, 5);
            System.out.println("Waiting for clients...");
            System.out.println();
            while (true) {
                Socket socket = listener.accept();
                //System.out.println("** New client arrived: **");
                Thread thread = new Thread(() -> {
                    // Try reader and writer
                    try ( BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
                        // Request data
                        RequestContext request;
                        // Unwrap
                        Unwrapper wrapper = new Unwrapper(reader);
                        request = wrapper.unwarp();
                        // Print Request
                        if (request != null){

                            System.out.println("** Client - Start **");
                            System.out.println("** Header: **");
                            System.out.println("    " + request.getHttp_verb() + " " + request.getRequested() + " " + request.getHttp_version());
                            for (Map.Entry<String, String> entry : request.getHeader_values().entrySet()) {
                                System.out.println("    " + entry.getKey() + " " + entry.getValue());
                            }
                            System.out.println("** Body: **");
                            System.out.println(request.getPayload());
                            System.out.println("-------------------------------------------");
                        }
                        // Handle response
                        ResponseHandler responder = new ResponseHandler(writer);
                        responder.response(request);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //System.out.println("** Client gone. **");
                    //System.out.println("");
                });
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(ServerSocket listener=new ServerSocket(PORT,BACKLOG)) in method public main(args String[]) : void from class server.Server


    private String queryAndConvertToJson(String query, String... params) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {
            for (int i = 0; i < params.length; i++) {
                ps.setString(i + 1, params[i]);
            }
            return result2Json(ps.executeQuery());
        } catch (SQLException | JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String showUserCards (User user){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("SELECT cardID, name, damage FROM cards WHERE owner = ?;");
            ps.setString(1,user.getUsername());
            String json = result2Json(ps.executeQuery());
            ps.close();
            conn.close();
            return json;
        } catch (SQLException | JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement(query)) in method private queryAndConvertToJson(query String, params String...) : String from class MonsterCardGame.mtcg.managers.CardManager


    public String showUserDeck (User user){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("SELECT cardID, name, damage FROM cards WHERE owner = ? AND collection = 'deck';");
            ps.setString(1,user.getUsername());
            String json = result2Json(ps.executeQuery());
            ps.close();
            conn.close();
            return json;
        } catch (SQLException | JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }


    public boolean acquirePackage2User(User user) {
        try (Connection conn = getConnection()) {
            // Check Existing Package
            PreparedStatement ps = conn.prepareStatement("SELECT * FROM packages;");
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) {
                    return false;
                }

                int packageID = rs.getInt(1);
                // Decrease Coins User
                if (!user.buyPackage()) {
                    return false;
                }
                // Update Cards Owner and Collection
                updateCardsOwnerAndCollection(conn, user.getUsername(), rs);
                // Delete Package
                deletePackage(conn, packageID);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean acquirePackage2User(User user){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            // Check Existing Package
            PreparedStatement ps = conn.prepareStatement("SELECT * FROM packages;");
            ResultSet rs = ps.executeQuery();
            ps.close();
            if (!rs.next()) {
                rs.close();
                conn.close();
                return false;
            }
            int packageID = rs.getInt(1);
            // Decrease Coins User
            if (!user.buyPackage()){
                return false;
            }
            // Update Cards Owner and Collection
            PreparedStatement ps_Card = conn.prepareStatement("UPDATE cards SET owner = ?, collection = 'stack' WHERE cardID = ?;");
            for (int i = 2; i < 7; i++){
                ps_Card.setString(1,user.getUsername());
                ps_Card.setString(2,rs.getString(i));
                ps_Card.executeUpdate();
            }
            rs.close();
            ps_Card.close();
            // Delete Package
            PreparedStatement ps_Package = conn.prepareStatement("DELETE FROM packages WHERE packageID = ?;");
            ps_Package.setInt(1,packageID);
            ps_Package.executeUpdate();
            ps_Package.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

Try With Resources try(ResultSet rs=ps.executeQuery()) in method public acquirePackage2User(user User) : boolean from class MonsterCardGame.mtcg.managers.CardManager


    public Deck getDeckUser(User user) {
        Deck deck = null;
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT cardID, name, damage FROM cards WHERE owner = ? AND collection = 'deck';")) {
            ps.setString(1, user.getUsername());
            try (ResultSet rs = ps.executeQuery()) {
                List<Card> cards = new ArrayList<>();
                while (rs.next()) {
                    String name = rs.getString(2);
                    cards.add(new Card(rs.getString(1), name, rs.getFloat(3), createCardType(name), createElementType(name)));
                }
                deck = new Deck(cards);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return deck;
    }

    public Deck getDeckUser (User user){
        Deck deck = null;
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("SELECT cardID, name, damage FROM cards WHERE owner = ? AND collection = 'deck';");
            ps.setString(1, user.getUsername());
            ResultSet rs = ps.executeQuery();
            ps.close();
            List<Card> cards = new ArrayList<>();
            while (rs.next()) {
                String name = rs.getString(2);
                cards.add(new Card(rs.getString(1), name, rs.getFloat(3),createCardType(name),createElementType(name)));
            }
            deck = new Deck(cards);
            rs.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return deck;
    }

Try With Resources try(ResultSet rs=ps.executeQuery()) in method public getDeckUser(user User) : Deck from class MonsterCardGame.mtcg.managers.CardManager


    public boolean registerCard(String id, String name, float damage) {
        if (!id.isEmpty() && !name.isEmpty()) {
            ElementType element = createElementType(name);
            CardType cardType = createCardType(name);
            if (element != null && cardType != null) {
                try (Connection conn = getConnection();
                     PreparedStatement ps = conn.prepareStatement("INSERT INTO cards(cardid, name, damage) VALUES(?,?,?);")) {
                    ps.setString(1, id);
                    ps.setString(2, name);
                    ps.setFloat(3, damage);
                    int affectedRows = ps.executeUpdate();
                    if (affectedRows == 0) {
                        return false;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        }
        return false;
    }

    public boolean registerCard(String id, String name, float damage) {
        if (!id.isEmpty() && !name.isEmpty()) {
            ElementType element = createElementType(name);
            CardType cardType = createCardType(name);
            if ( element != null && cardType != null){
                try {
                    Connection conn = DatabaseService.getInstance().getConnection();
                    PreparedStatement ps = conn.prepareStatement("INSERT INTO cards(cardid, name, damage) VALUES(?,?,?);");
                    ps.setString(1, id);
                    ps.setString(2, name);
                    ps.setFloat(3, damage);
                    int affectedRows = ps.executeUpdate();
                    ps.close();
                    conn.close();
                    if (affectedRows == 0) {
                        return false;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        }
        return false;
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("INSERT INTO cards(cardid, name, damage) VALUES(?,?,?);")) in method public registerCard(id String, name String, damage float) : boolean from class MonsterCardGame.mtcg.managers.CardManager


    public void deleteCard(String id) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("DELETE FROM cards WHERE cardid = ? AND collection IS NULL")) {
            ps.setString(1, id);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void deleteCard(String id) {
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("DELETE FROM cards WHERE cardid = ? AND collection IS NULL");
            ps.setString(1, id);
            ps.executeUpdate();
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("DELETE FROM cards WHERE cardid = ? AND collection IS NULL")) in method public deleteCard(id String) : void from class MonsterCardGame.mtcg.managers.CardManager


    public boolean createDeck(User user, List<String> id) {
        if (id.size() != 4) {
            return false;
        }

        try (Connection conn = getConnection()) {
            List<String> checkTwice = new LinkedList<>();
            for (String cardID : id) {
                if (checkTwice.contains(cardID)) {
                    return false;
                }
                checkTwice.add(cardID);
                if (TradeManager.getInstance().marketplaceContains(cardID)) {
                    return false;
                }
                if (!validateCardForUser(conn, user.getUsername(), cardID)) {
                    return false;
                }
            }

            updateCardsToStack(conn, user.getUsername());
            updateCardsToDeck(conn, user.getUsername(), id);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public boolean createDeck(User user, List<String> id){
        if (id.size() != 4){
            return false;
        }
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            // Check if user owns Cards
            List<String> checkTwice = new LinkedList<>();
            for (String cardID: id){
                if (checkTwice.contains(cardID)){
                    conn.close();
                    return false;
                }
                checkTwice.add(cardID);
                if (TradeManager.getInstance().marketplaceContains(cardID)){
                    return false;
                }
                PreparedStatement ps = conn.prepareStatement("SELECT COUNT(cardid) FROM cards WHERE cardid = ? AND owner = ?;");
                ps.setString(1,cardID);
                ps.setString(2,user.getUsername());
                ResultSet rs = ps.executeQuery();
                if (!rs.next() || rs.getInt(1) != 1) {
                    ps.close();
                    rs.close();
                    conn.close();
                    return false;
                }
            }
            // Set all Cards to Stack
            PreparedStatement ps = conn.prepareStatement("UPDATE cards SET collection = 'stack' WHERE owner = ?;");
            ps.setString(1,user.getUsername());
            ps.executeUpdate();
            // Change Cards to Deck
            for (String cardID: id){
                ps = conn.prepareStatement("UPDATE cards SET collection = 'deck' WHERE owner = ? AND cardID = ?;");
                ps.setString(1,user.getUsername());
                ps.setString(2,cardID);
                ps.executeUpdate();
            }
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

Try With Resources try(Connection conn=getConnection()) in method public createDeck(user User, id List<String>) : boolean from class MonsterCardGame.mtcg.managers.CardManager


    public String showMarketplace() {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT tradeID, cards.cardID, name, damage, owner, mindamage, type FROM marketplace JOIN cards ON cards.cardID = marketplace.cardID;")) {
            ResultSet rs = ps.executeQuery();
            ObjectMapper mapper = new ObjectMapper();
            ArrayNode arrayNode = mapper.createArrayNode();
            while (rs.next()) {
                ObjectNode deal = mapper.createObjectNode();
                deal.put("TradeID", rs.getString(1));
                deal.put("CardID", rs.getString(2));
                deal.put("Name", rs.getString(3));
                deal.put("Damage", rs.getString(4));
                deal.put("Owner", rs.getString(5));
                deal.put("MinimumDamage", rs.getString(6));
                deal.put("Type", rs.getString(7));
                arrayNode.add(deal);
            }
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode);
        } catch (SQLException | JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String showMarketplace(){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("SELECT tradeID, cards.cardID, name, damage, owner, mindamage, type FROM marketplace JOIN cards ON cards.cardID = marketplace.cardID;");
            ResultSet rs = ps.executeQuery();
            ps.close();
            ObjectMapper mapper = new ObjectMapper();
            ArrayNode arrayNode = mapper.createArrayNode();
            while (rs.next()){
                ObjectNode deal = mapper.createObjectNode();
                deal.put("TradeID",rs.getString(1));
                deal.put("CardID",rs.getString(2));
                deal.put("Name",rs.getString(3));
                deal.put("Damage",rs.getString(4));
                deal.put("Owner",rs.getString(5));
                deal.put("MinimumDamage",rs.getString(6));
                deal.put("Type",rs.getString(7));
                arrayNode.add(deal);
            }
            rs.close();
            conn.close();
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode);
        } catch (SQLException | JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("SELECT tradeID, cards.cardID, name, damage, owner, mindamage, type FROM marketplace JOIN cards ON cards.cardID = marketplace.cardID;")) in method public showMarketplace() : String from class MonsterCardGame.mtcg.managers.TradeManager


    public boolean removeTrade(User user, String id) {
        try (Connection conn = getConnection()) {
            PreparedStatement ps = conn.prepareStatement("SELECT cards.owner FROM cards JOIN marketplace ON cards.cardID = marketplace.cardID WHERE marketplace.tradeID = ?;");
            ps.setString(1, id);
            ResultSet rs = ps.executeQuery();
            if (!rs.next() || !rs.getString(1).equals(user.getUsername())) {
                rs.close();
                return false;
            }
            rs.close();
            ps = conn.prepareStatement("DELETE FROM marketplace WHERE tradeID = ?;");
            ps.setString(1, id);
            int affectedRows = ps.executeUpdate();
            if (affectedRows != 1) {
                return false;
            }
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean removeTrade(User user, String id){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("SELECT cards.owner FROM cards JOIN marketplace ON cards.cardID = marketplace.cardID WHERE marketplace.tradeID = ?;");
            ps.setString(1, id);
            ResultSet rs = ps.executeQuery();
            ps.close();
            if (!rs.next() || !rs.getString(1).equals(user.getUsername())) {
                rs.close();
                conn.close();
                return false;
            }
            rs.close();
            ps = conn.prepareStatement("DELETE FROM marketplace WHERE tradeID = ?;");
            ps.setString(1, id);
            int affectedRows = ps.executeUpdate();
            ps.close();
            if (affectedRows != 1) {
                conn.close();
                return false;
            }
            conn.close();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

Try With Resources try(Connection conn=getConnection()) in method public removeTrade(user User, id String) : boolean from class MonsterCardGame.mtcg.managers.TradeManager


    public boolean card2market(User user, String tradeID, String cardID, float minimumDamage, String type) {
        try (Connection conn = getConnection()) {
            if (marketplaceContains(cardID)) {
                return false;
            }
            PreparedStatement ps = conn.prepareStatement("SELECT COUNT(cardid) FROM cards WHERE owner = ? AND cardid = ? AND collection LIKE 'stack';");
            ps.setString(1, user.getUsername());
            ps.setString(2, cardID);
            ResultSet rs = ps.executeQuery();
            if (!rs.next() || rs.getInt(1) != 1) {
                rs.close();
                return false;
            }
            rs.close();
            ps = conn.prepareStatement("INSERT INTO marketplace(tradeid, cardid, mindamage, type) VALUES(?,?,?,?);");
            ps.setString(1, tradeID);
            ps.setString(2, cardID);
            ps.setFloat(3, minimumDamage);
            ps.setString(4, type);
            int affectedRows = ps.executeUpdate();
            if (affectedRows != 1) {
                return false;
            }
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean card2market(User user, String tradeID, String cardID, float minimumDamage, String type){
        try {
            // Check if user owns card
            Connection conn = DatabaseService.getInstance().getConnection();
            if (marketplaceContains(cardID)){
                return false;
            }
            PreparedStatement ps = conn.prepareStatement("SELECT COUNT(cardid) FROM cards WHERE owner = ? AND cardid = ? AND collection LIKE 'stack';");
            ps.setString(1, user.getUsername());
            ps.setString(2, cardID);
            ResultSet rs = ps.executeQuery();
            ps.close();
            if (!rs.next() || rs.getInt(1) != 1) {
                rs.close();
                conn.close();
                return false;
            }
            rs.close();
            // Insert Marketplace
            ps = conn.prepareStatement("INSERT INTO marketplace(tradeid, cardid, mindamage, type) VALUES(?,?,?,?);");
            ps.setString(1, tradeID);
            ps.setString(2, cardID);
            ps.setFloat(3, minimumDamage);
            ps.setString(4, type);
            int affectedRows = ps.executeUpdate();
            ps.close();
            if (affectedRows != 1) {
                return false;
            }
            conn.close();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

Try With Resources try(Connection conn=getConnection()) in method public card2market(user User, tradeID String, cardID String, minimumDamage float, type String) : boolean from class MonsterCardGame.mtcg.managers.TradeManager


    public boolean tradeCards(User user, String tradeID, String cardID) {
        if (user == null) {
            return false;
        }
        try (Connection conn = getConnection()) {
            String cardName;
            float cardDamage;
            String offeredCardID;
            String offeredCardOwner;
            float minDamage;
            String type;
            if (marketplaceContains(cardID)) {
                return false;
            }
            PreparedStatement ps = conn.prepareStatement("SELECT name, damage FROM cards WHERE owner = ? AND cardid = ? AND collection LIKE 'stack';");
            ps.setString(1, user.getUsername());
            ps.setString(2, cardID);
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                rs.close();
                return false;
            }
            cardName = rs.getString(1);
            cardDamage = rs.getFloat(2);
            rs.close();
            ps = conn.prepareStatement("SELECT marketplace.cardID, owner, minDamage, type FROM marketplace JOIN cards ON marketplace.cardID = cards.cardID WHERE tradeID = ?;");
            ps.setString(1, tradeID);
            rs = ps.executeQuery();
            if (!rs.next()) {
                rs.close();
                return false;
            }
            offeredCardID = rs.getString(1);
            offeredCardOwner = rs.getString(2);
            minDamage = rs.getFloat(3);
            type = rs.getString(4);
            rs.close();
            CardManager manager = CardManager.getInstance();
            if (type.equalsIgnoreCase("monster")) {
                if (manager.createCardType(cardName) == CardType.Spell) {
                    return false;
                }
            } else if (manager.createCardType(cardName) != manager.createCardType(type)) {
                return false;
            }
            if (cardDamage < minDamage) {
                return false;
            }
            if (offeredCardOwner.equalsIgnoreCase(user.getUsername())) {
                return false;
            }
            ps = conn.prepareStatement("UPDATE cards SET owner = ? WHERE cardID = ?");
            ps.setString(1, offeredCardOwner);
            ps.setString(2, cardID);
            ps.executeUpdate();
            ps = conn.prepareStatement("UPDATE cards SET owner = ? WHERE cardID = ?");
            ps.setString(1, user.getUsername());
            ps.setString(2, offeredCardID);
            ps.executeUpdate();
            ps = conn.prepareStatement("DELETE FROM marketplace WHERE tradeID = ?;");
            ps.setString(1, tradeID);
            ps.executeUpdate();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean tradeCards(User user, String tradeID, String cardID){
        if (user == null){
            return false;
        }
        try {
            // Exchanging
            String cardName;
            float cardDamage;
            // Marketplace
            String offeredCardID;
            String offeredCardOwner;
            float minDamage;
            String type;
            // Check if exchanging card in not on Marktplace
            Connection conn = DatabaseService.getInstance().getConnection();
            if (marketplaceContains(cardID)){
                return false;
            }
            // Get exchanging Card with ID
            PreparedStatement ps = conn.prepareStatement("SELECT name, damage FROM cards WHERE owner = ? AND cardid = ? AND collection LIKE 'stack';");
            ps.setString(1, user.getUsername());
            ps.setString(2, cardID);
            ResultSet rs = ps.executeQuery();
            ps.close();
            if (!rs.next()) {
                rs.close();
                conn.close();
                return false;
            }
            cardName = rs.getString(1);
            cardDamage = rs.getFloat(2);
            rs.close();
            // Get Trade from SQL
            ps = conn.prepareStatement("SELECT marketplace.cardID, owner, minDamage, type FROM marketplace JOIN cards ON marketplace.cardID = cards.cardID WHERE tradeID = ?;");
            ps.setString(1, tradeID);
            rs = ps.executeQuery();
            ps.close();
            if (!rs.next()) {
                rs.close();
                conn.close();
                return false;
            }
            offeredCardID = rs.getString(1);
            offeredCardOwner = rs.getString(2);
            minDamage = rs.getFloat(3);
            type = rs.getString(4);
            rs.close();
            // Check CardType and Damage and Owner
            CardManager manager = CardManager.getInstance();
            if (type.equalsIgnoreCase("monster")){
                if (manager.createCardType(cardName) == CardType.Spell){
                    return false;
                }
            } else if (manager.createCardType(cardName) != manager.createCardType(type)){
                return false;
            }
            if (cardDamage < minDamage){
                return false;
            }
            if (offeredCardOwner.equalsIgnoreCase(user.getUsername())){
                return false;
            }
            // Change cards owners
            ps = conn.prepareStatement("UPDATE cards SET owner = ? WHERE cardID = ?");
            ps.setString(1, offeredCardOwner);
            ps.setString(2, cardID);
            ps.executeUpdate();
            ps.close();
            ps = conn.prepareStatement("UPDATE cards SET owner = ? WHERE cardID = ?");
            ps.setString(1, user.getUsername());
            ps.setString(2, offeredCardID);
            ps.executeUpdate();
            ps.close();
            // Delete marketplace entry
            ps = conn.prepareStatement("DELETE FROM marketplace WHERE tradeID = ?;");
            ps.setString(1, tradeID);
            ps.executeUpdate();
            conn.close();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

Try With Resources try(Connection conn=getConnection()) in method public tradeCards(user User, tradeID String, cardID String) : boolean from class MonsterCardGame.mtcg.managers.TradeManager


    public boolean marketplaceContains(String cardID) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT COUNT(cardid) FROM marketplace WHERE cardid = ?;")) {
            ps.setString(1, cardID);
            ResultSet rs = ps.executeQuery();
            if (rs.next() && rs.getInt(1) == 1) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean marketplaceContains(String cardID){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("SELECT COUNT(cardid) FROM marketplace WHERE cardid = ?;");
            ps.setString(1, cardID);
            ResultSet rs = ps.executeQuery();
            ps.close();
            if (rs.next() && rs.getInt(1) == 1) {
                rs.close();
                conn.close();
                return true;
            }
            rs.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("SELECT COUNT(cardid) FROM marketplace WHERE cardid = ?;")) in method public marketplaceContains(cardID String) : boolean from class MonsterCardGame.mtcg.managers.TradeManager


    public User authorizeUser(String token) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT username, name, bio, image, coins, games, wins, elo FROM users WHERE token = ? AND logged = TRUE;")) {
            ps.setString(1, token);
            ResultSet rs = ps.executeQuery();

            if (!rs.next()) {
                return null;
            }

            return new User(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5), rs.getInt(6), rs.getInt(7), rs.getInt(8));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public User authorizeUser(String token){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("SELECT username, name, bio, image, coins, games, wins, elo FROM users WHERE token = ? AND logged = TRUE;");
            ps.setString(1, token);
            ResultSet rs = ps.executeQuery();
            ps.close();
            if (!rs.next()) {
                rs.close();
                conn.close();
                return null;
            }
            User user = new User(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getInt(5),rs.getInt(6),rs.getInt(7),rs.getInt(8));
            rs.close();
            conn.close();
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("SELECT username, name, bio, image, coins, games, wins, elo FROM users WHERE token = ? AND logged = TRUE;")) in method public authorizeUser(token String) : User from class MonsterCardGame.mtcg.managers.UserManager


    public boolean isAdmin(String token) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT COUNT(username) FROM users WHERE token = ? AND admin = TRUE AND logged = TRUE;")) {
            ps.setString(1, token);
            ResultSet rs = ps.executeQuery();
            if (!rs.next() || rs.getInt(1) != 1) {
                return false;
            }
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean isAdmin(String token){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("SELECT COUNT(username) FROM users WHERE token = ? AND admin = TRUE AND logged = TRUE;");
            ps.setString(1, token);
            ResultSet rs = ps.executeQuery();
            ps.close();
            if (!rs.next() || rs.getInt(1) != 1) {
                rs.close();
                conn.close();
                return false;
            }
            conn.close();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("SELECT COUNT(username) FROM users WHERE token = ? AND admin = TRUE AND logged = TRUE;")) in method public isAdmin(token String) : boolean from class MonsterCardGame.mtcg.managers.UserManager


    public boolean registerUser(String username, String pwd) {
        String token = "Basic " + username + "-mtcgToken";
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT COUNT(username) FROM users WHERE username = ?;")) {
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();

            if (!rs.next() || rs.getInt(1) > 0) {
                return false;
            }

            String insertSql = username.equals("admin") ?
                    "INSERT INTO users(username, pwd, token, admin) VALUES(?,?,?,TRUE);" :
                    "INSERT INTO users(username, pwd, token) VALUES(?,?,?);";

            try (PreparedStatement insertPs = conn.prepareStatement(insertSql)) {
                insertPs.setString(1, username);
                insertPs.setString(2, pwd);
                insertPs.setString(3, token);
                int affectedRows = insertPs.executeUpdate();
                return affectedRows != 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean registerUser(String username, String pwd) {
        String token = "Basic " + username + "-mtcgToken";
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps;
            ps = conn.prepareStatement("SELECT COUNT(username) FROM users WHERE username = ?;");
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            ps.close();
            if (!rs.next() || rs.getInt(1) > 0){
                return false;
            }
            if (username.equals("admin")){
                ps = conn.prepareStatement("INSERT INTO users(username, pwd, token, admin) VALUES(?,?,?,TRUE);");
            } else {
                ps = conn.prepareStatement("INSERT INTO users(username, pwd, token) VALUES(?,?,?);");
            }
            ps.setString(1, username);
            ps.setString(2, pwd);
            ps.setString(3, token);
            int affectedRows = ps.executeUpdate();
            ps.close();
            conn.close();
            return affectedRows != 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("SELECT COUNT(username) FROM users WHERE username = ?;")) in method public registerUser(username String, pwd String) : boolean from class MonsterCardGame.mtcg.managers.UserManager


    public boolean loginUser(String username, String pwd) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("UPDATE users SET logged = TRUE WHERE username = ? AND pwd = ?;")) {
            ps.setString(1, username);
            ps.setString(2, pwd);
            int affectedRows = ps.executeUpdate();
            return affectedRows == 1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean loginUser(String username, String pwd){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("UPDATE users SET logged = TRUE WHERE username = ? AND pwd = ?;");
            ps.setString(1, username);
            ps.setString(2, pwd);
            int affectedRows = ps.executeUpdate();
            ps.close();
            conn.close();
            if (affectedRows == 1) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("UPDATE users SET logged = TRUE WHERE username = ? AND pwd = ?;")) in method public loginUser(username String, pwd String) : boolean from class MonsterCardGame.mtcg.managers.UserManager


    public boolean logoutUser(String username, String pwd) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("UPDATE users SET logged = FALSE WHERE username = ? AND pwd = ?;")) {
            ps.setString(1, username);
            ps.setString(2, pwd);
            int affectedRows = ps.executeUpdate();
            return affectedRows == 1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean logoutUser(String username, String pwd){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("UPDATE users SET logged = FALSE WHERE username = ? AND pwd = ?;");
            ps.setString(1, username);
            ps.setString(2, pwd);
            int affectedRows = ps.executeUpdate();
            ps.close();
            conn.close();
            if (affectedRows == 1) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("UPDATE users SET logged = FALSE WHERE username = ? AND pwd = ?;")) in method public logoutUser(username String, pwd String) : boolean from class MonsterCardGame.mtcg.managers.UserManager


    public static void main(String[] args) {
        System.out.println("Start server...");
        try (ServerSocket listener = new ServerSocket(10001, 5)) {
            System.out.println("Waiting for clients...");
            System.out.println();
            while (true) {
                Socket socket = listener.accept();
                Thread thread = new Thread(() -> handleClient(socket));
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println("start server...");
        try {
            ServerSocket listener = new ServerSocket(10001, 5);
            System.out.println("Waiting for clients...");
            System.out.println();
            while (true) {
                Socket socket = listener.accept();
                //System.out.println("** New client arrived: **");
                Thread thread = new Thread(() -> {
                    // Try reader and writer
                    try ( BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
                        // Request data
                        RequestContext request;
                        // Unwrap
                        Unwrapper wrapper = new Unwrapper(reader);
                        request = wrapper.unwarp();
                        // Print Request
                        if (request != null){

                            System.out.println("** Client - Start **");
                            System.out.println("** Header: **");
                            System.out.println("    " + request.getHttp_verb() + " " + request.getRequested() + " " + request.getHttp_version());
                            for (Map.Entry<String, String> entry : request.getHeader_values().entrySet()) {
                                System.out.println("    " + entry.getKey() + " " + entry.getValue());
                            }
                            System.out.println("** Body: **");
                            System.out.println(request.getPayload());
                            System.out.println("-------------------------------------------");
                        }
                        // Handle response
                        ResponseHandler responder = new ResponseHandler(writer);
                        responder.response(request);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //System.out.println("** Client gone. **");
                    //System.out.println("");
                });
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(ServerSocket listener=new ServerSocket(10001,5)) in method public main(args String[]) : void from class MonsterCardGame.server.TcpListener


    public String getScoreboard() {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT name, wins, games, elo FROM users WHERE name IS NOT NULL ORDER BY elo DESC;")) {
            ResultSet rs = ps.executeQuery();
            ObjectMapper mapper = new ObjectMapper();
            ArrayNode arrayNode = mapper.createArrayNode();
            while (rs.next()) {
                ObjectNode entry = mapper.createObjectNode();
                entry.put("Name", rs.getString(1));
                entry.put("Wins", rs.getString(2));
                entry.put("Games", rs.getString(3));
                entry.put("Elo", rs.getString(4));
                arrayNode.add(entry);
            }
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode);
        } catch (SQLException | JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getScoreboard(){
        try {
            Connection conn = DatabaseService.getInstance().getConnection();
            PreparedStatement ps = conn.prepareStatement("SELECT name, wins, games, elo FROM users WHERE name IS NOT NULL ORDER BY elo DESC;");
            ResultSet rs = ps.executeQuery();
            ps.close();
            ObjectMapper mapper = new ObjectMapper();
            ArrayNode arrayNode = mapper.createArrayNode();
            while (rs.next()){
                ObjectNode entry = mapper.createObjectNode();
                entry.put("Name",rs.getString(1));
                entry.put("Wins",rs.getString(2));
                entry.put("Games",rs.getString(3));
                entry.put("Elo",rs.getString(4));
                arrayNode.add(entry);
            }
            rs.close();
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode);
        } catch (SQLException | JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

Try With Resources try(Connection conn=getConnection(); PreparedStatement ps=conn.prepareStatement("SELECT name, wins, games, elo FROM users WHERE name IS NOT NULL ORDER BY elo DESC;")) in method public getScoreboard() : String from class MonsterCardGame.mtcg.managers.BattleManager


    @Override
    public boolean borrar() {
        if (eliminarDetallePedidos()) {
            String sql = "DELETE FROM pedido WHERE idpedido = ?";
            try (Connection con = getCon();
                 PreparedStatement stm = con.prepareStatement(sql)) {
                stm.setInt(1, this.idpedido);
                stm.executeUpdate();
                return true;
            } catch (SQLException e) {
                Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, e);
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean borrar() {
        String sql = "DELETE from pedido where idpedido = ?";
        try {
            Connection con = getCon();
            PreparedStatement stm = con.prepareStatement(sql);
            stm.setInt(1, this.idpedido);
            stm.executeUpdate();
            return true;
        } catch (SQLException e) {
            Logger.getLogger(Pedido.class.getName()).log(Level.SEVERE, null, e);
            return false;
        }
    }

Try With Resources try(Connection con=getCon(); PreparedStatement stm=con.prepareStatement(sql)) in method public borrar() : boolean from class com.mycompany.oscarssoftware.modelos.Pedido


    @Override
    public void calculateAndSetChecksum(BufferedImage e) {
        String[] fileNameArr = super.getFile().getName().split("\\.");
        String extension = fileNameArr[fileNameArr.length-1];

        try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
            ImageIO.write(e, extension, byteStream);
            Record.algorithm.update(byteStream.toByteArray());
        } catch (IOException ex) {
            // skip the file and set checksum = 0
            System.out.println(ex.getMessage());
            setChecksum(0L);
            return;
        }

        super.setChecksum(Record.algorithm.getValue());
        Record.algorithm.reset();
    }

    @Override
    public void calculateAndSetChecksum(BufferedImage e) {
        String[] fileNameArr = super.getFile().getName().split("\\.");
        String extension = fileNameArr[fileNameArr.length-1];

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

        try {
            ImageIO.write(e, extension, byteStream);
            Record.algorithm.update(byteStream.toByteArray());
            byteStream.close();
        } catch (IOException ex) {
            // skip the file and set checksum = 0
            System.out.println(ex.getMessage());
            setChecksum(0L);
            return;
        }

        super.setChecksum(Record.algorithm.getValue());
        Record.algorithm.reset();
    }

Try With Resources try(ByteArrayOutputStream byteStream=new ByteArrayOutputStream()) in method public calculateAndSetChecksum(e BufferedImage) : void from class pl.magzik.Structures.ImageRecord


    /**
     * Read from a selected file.
     *
     * @param file the file
     */
    public static void read(File file) throws IOException {
        String line;
        final String seperator = ";";
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String[] tempArray;
            while ((line = br.readLine()) != null) {
                tempArray = line.split(seperator);
                Patient patient = new Patient(tempArray[0], tempArray[1], tempArray[3], tempArray[2], "");
                App.patientRegister.getPatientArrayList().add(patient);
            }
        } catch (IOException e) {
            e.getCause();
        } catch (ArrayIndexOutOfBoundsException e) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Incorrect file formatting!");
            alert.setHeaderText("Incorrect formatting of .csv file");
            alert.setContentText("To import a .csv file you will need it on the format: " +
                    "firstname;lastname;generalPractitioner;socialSecurityNumber;diagnosis");
            alert.showAndWait();
        }
    }

    /**
     * Read.
     *
     * @param file the file
     * @throws FileNotFoundException the file not found exception
     */
    public static void read(File file) throws FileNotFoundException {
        String line;
        final String SEPARATOR = ";";
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String[] tempArray;
            while ((line = br.readLine()) != null) {
                tempArray = line.split(SEPARATOR);
                Patient patient = new Patient(tempArray[0], tempArray[1], tempArray[3], tempArray[2], "");
                App.patientRegister.getPatientArrayList().add(patient);
            }
        } catch (IOException e) {
            e.getCause();
        } catch (ArrayIndexOutOfBoundsException e) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Incorrect file formatting!");
            alert.setHeaderText("Incorrect formatting of .csv file");
            alert.setContentText("To import a .csv file you will need it on the format: " +
                    "firstname;lastname;generalPractitioner;socialSecurityNumber;diagnosis");
            alert.showAndWait();
        }
    }

Try With Resources try(BufferedReader br=new BufferedReader(new FileReader(file))) in method public read(file File) : void from class no.ntnu.idatg2001.file.ReadFromCSV


    public Plateau(List<String> plateau){
        for (int y = 0; y < plateau.size(); y++) {
            this.plateau.add(new ArrayList<>());
            char[] ligne= plateau.get(y).toCharArray();
            for (int x = 0; x < ligne.length; x++) {
                this.plateau.get(y).add(new Cellule(ligne[x],x,y));
            }
        }
    }

    public Plateau(List<String> plateau){
        for (int y = 0; y < plateau.size(); y++) {
            this.plateau.add(new ArrayList<Cellule>());
            char[] ligne= plateau.get(y).toCharArray();
            for (int x = 0; x < ligne.length; x++) {
                this.plateau.get(y).add(new Cellule(ligne[x],x,y));
            }
        }
    }

Replace Generic With Diamond ArrayList<Cellule> with ArrayList<> in method public Plateau(plateau List<String>) from class fr.diginamic.tpJ2.jeuDeLaVieConway.classe.Plateau


    public Plateau(int largeur, int hauteur) {
        for (int y = 0; y < hauteur-1; y++) {
            this.plateau.add(new ArrayList<>());
            for (int x = 0; x < largeur-1; x++) {
                this.plateau.get(y).add(new Cellule(false,x,y));
            }
        }

    }

    public Plateau(int largeur, int hauteur) {
        for (int y = 0; y < hauteur-1; y++) {
            this.plateau.add(new ArrayList<Cellule>());
            for (int x = 0; x < largeur-1; x++) {
                this.plateau.get(y).add(new Cellule(false,x,y));
            }
        }

    }

Replace Generic With Diamond ArrayList<Cellule> with ArrayList<> in method public Plateau(largeur int, hauteur int) from class fr.diginamic.tpJ2.jeuDeLaVieConway.classe.Plateau


    /**
     * makes ActionListeners for passengers
     *
     * @return list of passengers ActionListeners
     */
    public static List<ActionListener> getALsForPassengers() {
        ActionListener plus = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog dial = new AddEditPassengerDialog(MainWindow.getFrame(), "Přidat cestujícího");
            }
        };

        ActionListener sort = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog dial = new SortPassengersDialog(MainWindow.getFrame(), "Řazení");
            }
        };

        ActionListener filter = actionListener -> {
            JDialog dial = new FilterPassengersDialog(MainWindow.getFrame(), "Filtr");
        };

        ActionListener select = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ShareCarRiderTable table = Shortcut.getTable(TableCategory.PASSENGERS);
                table.enableMultilineSelection(!table.isMultilineSelectionEnabled());
            }
        };

        ActionListener delete = e -> new DeleteDialog(MainWindow.getFrame(), "Smazat cestující/ho",
                TableCategory.PASSENGERS, Shortcut.getTable(TableCategory.PASSENGERS).getSelectedRows());
        List<ActionListener> passengers = new ArrayList<>();
        passengers.add(plus);
        passengers.add(sort);
        passengers.add(filter);
        passengers.add(select);
        passengers.add(delete);
        return passengers;
    }

    /**
     * makes ActionListeners for passengers
     *
     * @return list of passengers ActionListeners
     */
    public static List<ActionListener> getALsForPassengers() {
        ActionListener plus = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog dial = new AddEditPassengerDialog(MainWindow.getFrame(), "Přidat cestujícího");
            }
        };

        ActionListener sort = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog dial = new SortPassengersDialog(MainWindow.getFrame(), "Řazení");
            }
        };

        ActionListener filter = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog dial = new FilterPassengersDialog(MainWindow.getFrame(), "Filtr");
            }
        };

        ActionListener select = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ShareCarRiderTable table = Shortcut.getTable(TableCategory.PASSENGERS);
                table.enableMultilineSelection(!table.isMultilineSelectionEnabled());
            }
        };

        ActionListener delete = e -> new DeleteDialog(MainWindow.getFrame(), "Smazat cestující/ho",
                TableCategory.PASSENGERS, Shortcut.getTable(TableCategory.PASSENGERS).getSelectedRows());
        List<ActionListener> passengers = new ArrayList<>();
        passengers.add(plus);
        passengers.add(sort);
        passengers.add(filter);
        passengers.add(select);
        passengers.add(delete);
        return passengers;
    }

Replace Anonymous With Lambda cz.muni.fi.pv168.seminar01.beta.ui.utils.ActionListenerProvider.getALsForPassengers.filter.new ActionListener with actionListener -> {JDialog dial=new FilterPassengersDialog(MainWindow.getFrame(),"Filtr"); in method public getALsForPassengers() : List<ActionListener> from class cz.muni.fi.pv168.seminar01.beta.ui.utils.ActionListenerProvider


    @Override
    public void onEditButton(JButton edit) {
        edit.addActionListener(actionListener -> {
            dispose();
            new AddEditRideDialog(MainWindow.getFrame(), "Upravit jízdu", ride);
        });
    }

    @Override
    public void onEditButton(JButton edit) {
        edit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
                new AddEditRideDialog(MainWindow.getFrame(), "Upravit jízdu", ride);
            }
        });
    }

Replace Anonymous With Lambda cz.muni.fi.pv168.seminar01.beta.ui.dialogs.RideDetailDialog.onEditButton.addActionListener.new ActionListener with actionListener -> {dispose(); in method public onEditButton(edit JButton) : void from class cz.muni.fi.pv168.seminar01.beta.ui.dialogs.RideDetailDialog


    private void onSaveEditButton(JButton save) {
        save.addActionListener(actionListener -> {
            trimAllTextComponents();
            if (!validateRideInput()) {
                return;
            }

            String[] departureParsedTime = (departure.getText().split("[:.]"));
            String[] arrivalParsedTime = arrival.getText().split("[:.]");
            LocalTime departureTime = LocalTime.of(Integer.parseInt(departureParsedTime[0]), Integer.parseInt(departureParsedTime[1]));
            LocalTime arrivalTime = LocalTime.of(Integer.parseInt(arrivalParsedTime[0]), Integer.parseInt(arrivalParsedTime[1]));
            int parsedDistance = Integer.parseInt(distance.getText());
            RideTableModel tableModel = (RideTableModel) Shortcut.getTableModel(TableCategory.RIDES);
            ride.setDate(JDatePickerDateGetter.getLocalDate(date));
            ride.setDeparture(departureTime);
            ride.setFrom(startDestination.getText());
            ride.setTo(endDestination.getText());
            ride.setDistance(parsedDistance);
            ride.setPassengers(passengersList.getSelectedValuesList());
            ride.setVehicle((Vehicle) vehicle.getSelectedItem());
            ride.setRepetition((Repetition) repetition.getSelectedItem());
            ride.setArrival(arrivalTime);

            tableModel.updateRow(ride);
            dispose();
            new RideDetailDialog(MainWindow.getFrame(), "Detail jízdy", ride);
        });

    }

    private void onSaveEditButton(JButton save) {
        save.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String[] departureParsedTime = (departure.getText().split("[:.]"));
                String[] arrivalParsedTime = arrival.getText().split("[:.]");
                LocalTime departureTime = LocalTime.of(Integer.parseInt(departureParsedTime[0]), Integer.parseInt(departureParsedTime[1]));
                LocalTime arrivalTime = LocalTime.of(Integer.parseInt(arrivalParsedTime[0]), Integer.parseInt(arrivalParsedTime[1]));
                int parsedDistance = Integer.parseInt(distance.getText());
                RideTableModel tableModel = (RideTableModel) Shortcut.getTableModel(TableCategory.RIDES);
                ride.setDate(JDatePickerDateGetter.getLocalDate(date));
                ride.setDeparture(departureTime);
                ride.setFrom(startDestination.getText());
                ride.setTo(endDestination.getText());
                ride.setDistance(parsedDistance);
                ride.setPassengers(passengersList.getSelectedValuesList());
                ride.setVehicle((Vehicle) vehicle.getSelectedItem());
                ride.setRepetition((Repetition) repetition.getSelectedItem());
                ride.setArrival(arrivalTime);

                tableModel.updateRow(ride);
                dispose();
                new RideDetailDialog(MainWindow.getFrame(), "Detail jízdy", ride);
            }
        });

    }

Replace Anonymous With Lambda cz.muni.fi.pv168.seminar01.beta.ui.dialogs.AddEditRideDialog.onSaveEditButton.addActionListener.new ActionListener with actionListener -> {trimAllTextComponents(); in method private onSaveEditButton(save JButton) : void from class cz.muni.fi.pv168.seminar01.beta.ui.dialogs.AddEditRideDialog


    public static void importRide(String[] split) {
        if (split.length == RIDE_PARAMETERS) {
            long id = tryToLong(split[0]);
            LocalDate date = LocalDate.parse(split[1]);
            LocalTime time = LocalTime.parse(split[2]);
            String from = split[3];
            String where = split[4];
            int distance = tryToInt(split[5]);

            // CATEGORIES
//            Set<PassengerCategory> categorySet = new HashSet<>();
//            String cat = split[6];
//            if (cat.length() > 2) {
//                for (String category: listParser(cat)) {
//                    categorySet.add(RideCategory.fromString(category));
//                }
//            }

            String pass = split[7];
            Set<Passenger> passengerSet = new HashSet<>();
            if (pass.length() > 2) {
                for (String passenger : listParser(pass)) {
                    Passenger passengerObject = (Passenger) Shortcut.getTableModel(TableCategory.PASSENGERS).getObjectById(tryToLong(passenger));
                    if (passengerObject == null) {
                        System.err.println("Import not successful - > Person with id " + pass + " is missing in list");
                    }
                    passengerSet.add(passengerObject);
                }
            }

            long vehicleID = tryToLong(split[8]);
            Vehicle vehicleObject = (Vehicle) Shortcut.getTableModel(TableCategory.VEHICLES).getObjectById(vehicleID);
            if (vehicleObject == null) {
                System.err.println("Import not successful - > Vehicle with id " + vehicleID + " is missing in list");
            }
            Vehicle vehicle = vehicleObject;

            String rep = split[9];
            Repetition repetition = Enum.valueOf(Repetition.class, rep);

            ((RideTableModel) Shortcut.getTableModel(TableCategory.RIDES)).addRow(
                    new Ride(id, date, time, null, from, where, distance, new HashSet<>(), passengerSet, vehicle, repetition, "description"));
        }
    }

    public static void importRide(String[] split) {
        if (split.length == RIDE_PARAMETERS) {
            long id = tryToLong(split[0]);
            LocalDate date = LocalDate.parse(split[1]);
            LocalTime time = LocalTime.parse(split[2]);
            String from = split[3];
            String where = split[4];
            int distance = tryToInt(split[5]);

            // CATEGORIES
//            Set<PassengerCategory> categorySet = new HashSet<>();
//            String cat = split[6];
//            if (cat.length() > 2) {
//                for (String category: listParser(cat)) {
//                    categorySet.add(RideCategory.fromString(category));
//                }
//            }

            String pass = split[7];
            Set<Passenger> passengerSet = new HashSet<>();
            if (pass.length() > 2) {
                for (String passenger : listParser(pass)) {
                    Passenger passengerObject = (Passenger) Shortcut.getTableModel(TableCategory.PASSENGERS).getObjectById(tryToLong(passenger));
                    if (passengerObject == null) {
                        System.err.println("Import not successful - > Person with id " + pass + " is missing in list");
                    }
                    passengerSet.add(passengerObject);
                }
            }

            long vehicleID = tryToLong(split[8]);
            Vehicle vehicleObject = (Vehicle) Shortcut.getTableModel(TableCategory.VEHICLES).getObjectById(vehicleID);
            if (vehicleObject == null) {
                System.err.println("Import not successful - > Vehicle with id " + vehicleID + " is missing in list");
            }
            Vehicle vehicle = vehicleObject;

            String rep = split[9];
            Repetition repetition = Enum.valueOf(Repetition.class, rep);

            ((RideTableModel) Shortcut.getTableModel(TableCategory.RIDES)).addRow(
                    new Ride(id, date, time, null, from, where, distance, new HashSet<RideCategory>(), passengerSet, vehicle, repetition, "description"));
        }
    }

Replace Generic With Diamond Ride with Ride in method public importRide(split String[]) : void from class cz.muni.fi.pv168.seminar01.beta.data.manipulation.ImporterBase


    private void onSaveEditButton(JButton save) {
        validateVehicleInput();
        save.addActionListener(actionListener -> {
            VehicleTableModel tableModel = (VehicleTableModel) Shortcut.getTableModel(TableCategory.VEHICLES);
            vehicle.setLicensePlate(licensePlate.getText());
            vehicle.setBrand(brand.getText());
            vehicle.setType(type.getText());
            vehicle.setCapacity(Integer.parseInt(capacity.getText().trim()));
            vehicle.setConsumption(Float.parseFloat(consumption.getText().trim()));
            vehicle.setFuelType((FuelType) fuelType.getSelectedItem());
            tableModel.updateRow(vehicle);
            dispose();
        });
    }

    private void onSaveEditButton(JButton save) {
        save.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                VehicleTableModel tableModel = (VehicleTableModel) Shortcut.getTableModel(TableCategory.VEHICLES);
                vehicle.setLicensePlate(licensePlate.getText());
                vehicle.setBrand(brand.getText());
                vehicle.setType(type.getText());
                vehicle.setCapacity(Integer.parseInt(capacity.getText().trim()));
                vehicle.setConsumption(Float.parseFloat(consumption.getText()));
                vehicle.setFuelType((FuelType) fuelType.getSelectedItem());
                tableModel.updateRow(vehicle);
                dispose();
            }
        });
    }

Replace Anonymous With Lambda cz.muni.fi.pv168.seminar01.beta.ui.dialogs.AddEditVehicleDialog.onSaveEditButton.addActionListener.new ActionListener with actionListener -> {VehicleTableModel tableModel=(VehicleTableModel)Shortcut.getTableModel(TableCategory.VEHICLES); in method private onSaveEditButton(save JButton) : void from class cz.muni.fi.pv168.seminar01.beta.ui.dialogs.AddEditVehicleDialog