Saturday, May 31, 2025

[JAVA] HEX from File

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.commons.codec.binary.Hex;

public class HexFileUtil {

    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt";

        try {
            // Example 1: Read and convert hex string to byte array
            String hexString = Files.readString(Paths.get(filePath)).trim();
            byte[] byteArray = hexStringToByteArray(hexString);
            System.out.println("Byte array from hex string: " + java.util.Arrays.toString(byteArray));

            // Example 2: Read file as bytes and convert to hex string
            byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
            String hexStringFromFile = byteArrayToHexString(fileBytes);
            System.out.println("Hex string from file bytes: " + hexStringFromFile);


             // Example 3: Read file as bytes and convert to hex string using Apache Commons Codec
             byte[] fileBytes2 = Files.readAllBytes(Paths.get(filePath));
             String hexStringFromBytes = Hex.encodeHexString(fileBytes2);
             System.out.println("Hex string from file bytes using Apache Commons Codec: " + hexStringFromBytes);


            // Example 4: Read file and print it in hex representation using FileInputStream

            printHexStream(new FileInputStream(filePath), 16);

        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }


    public static void printHexStream(final FileInputStream inputStream, final int numberOfColumns) throws IOException{
         long streamPtr=0;
         while (inputStream.available() > 0) {
             final long col = streamPtr++ % numberOfColumns;
             System.out.printf("%02x ",inputStream.read());
             if (col == (numberOfColumns-1)) {
                 System.out.printf("\n");
             }
         }
    }

    public static byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                                 + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

    public static String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}

[JAVA] PRINT DATA

import java.awt.*;
import java.awt.print.*;

public class PrintExample implements Printable {
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        if (pageIndex > 0) {
            return NO_SUCH_PAGE;
        }
        Graphics2D g2d = (Graphics2D) graphics;
        g2d.drawString("Hello, Printer!", 100, 100);
        return PAGE_EXISTS;
    }

    public static void main(String[] args) {
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        PrintService[] services = PrinterJob.lookupPrintServices();
        if (services.length > 0) {
            try {
                printerJob.setPrintService(services[0]);
                printerJob.setPrintable(new PrintExample());
                if (printerJob.printDialog()) {
                    printerJob.print();
                }
            } catch (PrinterException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("No printers found.");
        }
    }
}

[JAVA] SPEEDTEST NETWORK

long download1 = net.getBytesRecv();
long timestamp1 = net.getTimeStamp();
Thread.sleep(2000); //Sleep for a bit longer, 2s should cover almost every possible problem
net.updateNetworkStats(); //Updating network stats
long download2 = net.getBytesRecv();
long timestamp2 = net.getTimeStamp();
System.out.println("prova " + (download2 - download1)/(timestamp2 - timestamp1));
//Do the correct calculations

[JAVA] SERVER CLIENT NETWORK

// Server.java
import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(12345);
        Socket clientSocket = serverSocket.accept();
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println("Received: " + inputLine);
            out.println("Server received: " + inputLine);
        }
    }
}

// Client.java
import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 12345);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out.println("Hello from client");
        System.out.println("Server response: " + in.readLine());
    }
}

[JAVA] FILL COLOUR from MOUSE

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

public class ColorFromMouse extends JPanel {

    private Color selectedColor = Color.BLACK;
    private int regionWidth = 50; // Example region width

    public ColorFromMouse() {
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int x = e.getX();
                int region = x / regionWidth;

                // Example mapping of regions to colors
                switch (region) {
                    case 0: selectedColor = Color.RED; break;
                    case 1: selectedColor = Color.GREEN; break;
                    case 2: selectedColor = Color.BLUE; break;
                    default: selectedColor = Color.BLACK;
                }
                repaint(); // Trigger redraw with the new color
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(selectedColor);
        g.fillRect(50, 50, 100, 100); // Example filled rectangle
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Color From Mouse");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ColorFromMouse());
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}

[JAVA] DOWNLOAD DATA FROM PROCESS

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class Progressbar {

    public static void main(String[] args) {

        final JProgressBar jProgressBar = new JProgressBar();
        jProgressBar.setMaximum(100000);
        JFrame frame = new JFrame();
        frame.setContentPane(jProgressBar);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(300, 70);
        frame.setVisible(true);

        Runnable updatethread = new Runnable() {
            public void run() {
                try {

                    URL url = new URL("http://downloads.sourceforge.net/project/bitcoin/Bitcoin/blockchain/bitcoin_blockchain_170000.zip");
                    HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
                    long completeFileSize = httpConnection.getContentLength();

                    java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
                    java.io.FileOutputStream fos = new java.io.FileOutputStream(
                            "package.zip");
                    java.io.BufferedOutputStream bout = new BufferedOutputStream(
                            fos, 1024);
                    byte[] data = new byte[1024];
                    long downloadedFileSize = 0;
                    int x = 0;
                    while ((x = in.read(data, 0, 1024)) >= 0) {
                        downloadedFileSize += x;

                        // calculate progress
                        final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100000d);

                        // update progress bar
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                jProgressBar.setValue(currentProgress);
                            }
                        });

                        bout.write(data, 0, x);
                    }
                    bout.close();
                    in.close();
                } catch (FileNotFoundException e) {
                } catch (IOException e) {
                }
            }
        };
        new Thread(updatethread).

        start();
    }

}

[JAVA] PROCESS BAR

public class ProgressBar {
    public static void main(String[] args) throws InterruptedException {
        int total = 100;
        for (int i = 0; i <= total; i++) {
            String bar = generateProgressBar(i, total);
            System.out.print("\r" + bar + " " + i + "%");
            Thread.sleep(50);
        }
        System.out.println();
    }

    private static String generateProgressBar(int current, int total) {
        int progressBarLength = 30;
        int filledLength = (int) (progressBarLength * ((double) current / total));
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < progressBarLength; i++) {
            if (i < filledLength) {
                sb.append("=");
            } else {
                sb.append(" ");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}