Showing posts with label netbeans. Show all posts
Showing posts with label netbeans. Show all posts

Wednesday, June 10, 2026

Java: reading config.conf file

example config.conf


# http and https ports configuration
http_port = 48001
https_port = 48001

# printer port
printer_port=/dev/rfcomm0
# printer size
printer_size=80mm

java code


    // configuration file config.conf
    static final String linux_file_path = "/etc/dddtescpos/config.conf";
    static final String file_path = "./config.conf";

    public static String printer_port = null;
    public static String printer_size = null;
    
    public static int http_port = -1;
    public static int https_port = -1;
    
    public static void readConfig() {
        Path configFile = Paths.get(linux_file_path);
        
        if (Files.notExists(configFile)) {
            configFile = Paths.get(file_path);
        }
        
        // comment in config file will # or !
        Properties props = new Properties();

        try (InputStream input = Files.newInputStream(configFile)) {
            props.load(input);
        
            printer_port = props.getProperty("printer_port");
            printer_size = props.getProperty("printer_size");
            if (printer_size == null || printer_size.isBlank()) {
                printer_size = "80mm";   // default
            } else {
                printer_size = printer_size.trim().toLowerCase();

                if (!printer_size.equals("58mm")
                        && !printer_size.equals("80mm")) {
                    printer_size = "80mm";   // default for invalid value
                }
            }


            String tmpPort = props.getProperty("http_port","48001");
            try {
                int intTmpPort = Integer.parseInt(tmpPort); 
                if (intTmpPort<48000 || intTmpPort>65535)
                    intTmpPort = 48001;
                    http_port = intTmpPort;
            } catch (NumberFormatException ex) {
                http_port = 48001;
            }
            tmpPort = props.getProperty("https_port","48002");
            try {
                int intTmpPort = Integer.parseInt(tmpPort); 
                if (intTmpPort<48000 || intTmpPort>65535)
                    intTmpPort = 48002;
                https_port = intTmpPort;
            } catch (NumberFormatException ex) {
                https_port = 48002;
            }
            // if ports hava equal value, set default
            if (http_port == https_port) {
                http_port = 48001;
                https_port = 48002;
            }
        } catch (IOException ex) {
            System.out.println("No Configuration file found");
            http_port = 48001;
            https_port = 48002;            
        }
        
    }

 

Monday, June 8, 2026

Java: http and https (self sign certificate)

install mkcert


# apt install mkcert

go to root of netbeans project and create self sign certificate


$ mkcert localhost
Created a new local CA 💥
Note: the local CA is not installed in the system trust store.
Note: the local CA is not installed in the Firefox and/or Chrome/Chromium trust store.
Run "mkcert -install" for certificates to be trusted automatically ⚠️

Created a new certificate valid for the following names 📜
 - "localhost"

The certificate is at "./localhost.pem" and the key at "./localhost-key.pem" ✅

It will expire on 8 September 2028 🗓

Convert to PKCS 12


$ openssl pkcs12 -export \
  -in localhost.pem \
  -inkey localhost-key.pem \
  -out localhost.p12 \
  -name localhost
Enter Export Password:
Verifying - Enter Export Password:

main java code


/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 */

package com.dedetok.ddtescpos;

import com.alibaba.fastjson2.JSONObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsExchange;
import com.sun.net.httpserver.HttpsServer;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;


/**
 *
 * @author dedetok
 */
public class DdtEscPos {

    final static String serviceString = "DdtEscPos";
    final static String serviceVersion = "1.0";
    
    public static void main(String[] args) {
        System.out.println("DdtEscPos reading configuration file");
        MyController.readConfig(); // if configuration not available, use hard code config
        
        System.out.println(serviceString+" "+serviceVersion);
        
        // ================= 
        try {
            HttpServer httpServer = createHttpService(MyController.http_port);
            HttpsServer httpsServer = createHttpsService(MyController.https_port);
            
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("Stopping HTTP & HTTPS server...");
                httpServer.stop(5); // stop 5 second
                System.out.println("HTTP server stopped");
                httpsServer.stop(5); // stop 5 second
                System.out.println("HTTPS server stopped");

            }));
            httpServer.start();
            System.out.println("HTTP server running on http://localhost:" + MyController.http_port);
            httpsServer.start();
            System.out.println("HTTPS server running on http://localhost:" + MyController.https_port);

        } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | KeyManagementException ex) {
            System.getLogger(DdtEscPos.class.getName()).log(System.Logger.Level.ERROR, (String) null, ex);
        }
    }

    /*
     * create http service in httpPort
     */
    static HttpsServer createHttpsService(int httpsPort) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {
        // Load PKCS12 keystore
        char[] password = "escpos".toCharArray();
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (FileInputStream fis = new FileInputStream("localhost.p12")) {
            ks.load(fis, password);
        }

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
        
        kmf.init(ks, password);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, null);

        // Create HTTPS server
        HttpsServer httpsServer =
                HttpsServer.create(
                        new InetSocketAddress("localhost", httpsPort),
                        0);        
    
        httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
        
        // Register endpoints
        httpsServer.createContext("/", DdtEscPos::handleHttpRequest);
        httpsServer.createContext("/printjson", DdtEscPos::handlePrintJson);        
        
        return httpsServer;
    }
    
    /*
     * create http service in httpPort
     */
    static HttpServer createHttpService(int httpPort) throws IOException {
        HttpServer httpServer =
                HttpServer.create(new InetSocketAddress("localhost", httpPort), 0);
        
        httpServer.createContext("/", DdtEscPos::handleHttpRequest);
        httpServer.createContext("/printjson", DdtEscPos::handlePrintJson);
        return httpServer;
    }

    /*
     * handling /
     */
    static void handleHttpRequest(HttpExchange exchange) throws IOException {
        // CORS
        exchange.getResponseHeaders().add(
                "Access-Control-Allow-Origin", "*");

        exchange.getResponseHeaders().add(
                "Access-Control-Allow-Headers",
                "Content-Type, Authorization");

        exchange.getResponseHeaders().add(
        "Access-Control-Allow-Methods",
        "GET, POST, OPTIONS");

        if ("OPTIONS".equalsIgnoreCase(exchange.getRequestMethod())) {
            exchange.sendResponseHeaders(204, -1);
            return;
        }
        
        // UTF-8 text response
        exchange.getResponseHeaders().add(
                "Content-Type",
                "text/plain; charset=UTF-8");
        
        String response = infoService(exchange).toString();

        byte[] responseBytes = response.getBytes(StandardCharsets.UTF_8);

        exchange.sendResponseHeaders(200, responseBytes.length);

        
        try (OutputStream os = exchange.getResponseBody()) {
            os.write(responseBytes);
        }
        System.out.println("Servicing client done"); // debug
    }

    /*
     * handling /printjson
     */
    static void handlePrintJson(HttpExchange exchange) throws IOException {
        // CORS
        exchange.getResponseHeaders().add(
                "Access-Control-Allow-Origin", "*");

        exchange.getResponseHeaders().add(
                "Access-Control-Allow-Headers",
                "Content-Type, Authorization");

        exchange.getResponseHeaders().add(
        "Access-Control-Allow-Methods",
        "GET, POST, OPTIONS");

        if ("OPTIONS".equalsIgnoreCase(exchange.getRequestMethod())) {
            exchange.sendResponseHeaders(204, -1);
            return;
        }
        
        // UTF-8 text response
        exchange.getResponseHeaders().add(
                "Content-Type",
                "text/plain; charset=UTF-8");
        // get json from request
        // Read request body
        String requestBody;
        try (InputStream is = exchange.getRequestBody()) {
            requestBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            // Parse JSON
            // Parse JSON and process
            JSONObject json = JSONObject.parseObject(requestBody);

            JSONObject responseJson = infoService(exchange);
            
            try {
                MyController.printJson(json.toString());


                responseJson.put("status", "printing done");
            } catch (IOException ex) {
                responseJson.put("status", "printing fail");
                responseJson.put("error", ex.getMessage());
                
            }
            
            byte[] bytes =
                responseJson.toString().getBytes(StandardCharsets.UTF_8);

            exchange.sendResponseHeaders(200, bytes.length);
            OutputStream os = exchange.getResponseBody();
            os.write(bytes);
            os.flush();

        }
    }
    
    /* 
     * standard info response 
     */
    static JSONObject infoService(HttpExchange exchange) {
        JSONObject jsonObj = new JSONObject();
        
        jsonObj.put("version", serviceVersion);
        jsonObj.put("service", serviceString);
        jsonObj.put("status", "running");
        String host = exchange.getLocalAddress().getHostString();
        int port = exchange.getLocalAddress().getPort();

        String scheme = (exchange instanceof HttpsExchange)
        ? "https://"
        : "http://";
        
        String baseUrl = scheme + host + ":" + port;
        jsonObj.put("endpoint",baseUrl+"/printjson");
        
        return jsonObj;
    }
}

to run service


$ java -jar target/DdtEscPos-1.0.jar 
Hello World!
HTTP server running on http://localhost:50001
HTTPS server running on https://localhost:50002
Serviing client done
Serviing client done

using curl to send json to print http


$ curl -H "Content-Type: application/json" \
     -d @exampleescpos.json \
     http://localhost:50001/printjson

https


$ curl -k \
  -H "Content-Type: application/json" \
  -d @exampleescpos.json \
  https://localhost:50002/printjson

or 


$ curl --insecure \
  -H "Content-Type: application/json" \
  -d @exampleescpos.json \
  https://localhost:50002/printjson

Credit: esc html using https://www.freeformatter.com/html-escape.html 

Saturday, May 30, 2026

Java Netbeans: upgrade binary Netbeans 29 to Netbeans 30

 This step is straight forward:

  1. go to your root directory (e.g your home dir ~/), and rename old folder e.g ~/netbeans29.
  2. extract netbeans 30 binary and put it in root directory to replace old folder (e.g your home dir ~/).
  3. Run your netbeans 30, import previous configuration
  4. if no error found you safe to remove
    1. old netbeans 29 (e.g ~/netbeans29) 
    2. ~/.netbeans/29
    3. ~/.cache/netbeans/29

 

Wednesday, February 18, 2026

Java Netbeans: java with maven vs java with gradle

Comparison

Feature  Java with Maven Java with Gradle
Configuration Uses XML (pom.xml). Uses Groovy or Kotlin DSL (build.gradle).
Philosophy Convention over configuration; strict, linear lifecycle. Flexibility; task-oriented and highly customizable.
Performance Slower; typically lacks advanced incremental build tracking. Faster; uses build caching, daemons, and incremental compilation.
Learning Curve Easy for beginners due to standardized structure. Steeper; requires understanding the DSL and build logic.
IDE Integration Deeply integrated; NetBeans was a pioneer in native Maven support. Fully supported; provides fast project synchronization.
Start with default template Yes No

 

 

When Java with Maven 

  1.     Onboarding & Stability: Because Maven follows strict convention-over-configuration, any Java developer can join a project and immediately know where everything is and how to run it.
  2.     Predictability: Maven’s XML is declarative and "logic-free," making it very reliable for CI/CD pipelines where "zero-surprise" builds are critical.
  3.     Low Maintenance: Maven projects from 10 years ago often still build perfectly today. Gradle’s high-speed evolution means its build scripts can sometimes require updates when you upgrade versions.
  4.     Small Projects: For a single-module project, the speed difference is negligible. In these cases, the extra complexity and learning curve of Gradle may not be worth it. 

When Java with Gradle

  1.     Large, Multi-Module Projects: Gradle is significantly faster (sometimes 100x faster) because it only recompiles what changed and can share build results between different developers via a Build Cache.
  2.     Custom Workflows: If you need to do something non-standard (like custom file manipulations or complex deployment steps), Gradle’s Groovy/Kotlin DSL is much more powerful than writing custom Maven plugins.
  3.     Android Development: Gradle is the official build tool for Android, making it the only real choice for that ecosystem.

This content is created from AI chat. 

Tuesday, November 4, 2025

Java Netbeans: using opencsv from url

Create a new Project Java with Maven project name e.g. TestOpenCSV

At Project Files, open pom.xml and add

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.dedetok</groupId>
    <artifactId>TestOpenCSV</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.release>17</maven.compiler.release>
        <exec.mainClass>com.dedetok.testopencsv.TestOpenCSV</exec.mainClass>
    </properties>
    <dependencies>
    <dependency>
        <groupId>com.opencsv</groupId>
        <artifactId>opencsv</artifactId>
        <version>5.9</version> <!-- or latest -->
    </dependency>
</dependencies>
</project>

You can use beans to map the result, or manually process the csv files. for data size bigger then 1 millions, there is deference about 1 second, it is better to manually process. Here are code to test, before you use it in production. Feel free to change any the code to meet your requirement.

Classs Radio

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.dedetok.testopencsv;

import com.opencsv.bean.CsvBindByName;

/**
 *
 * @author dedetok
 */
public class Radio {
    @CsvBindByName(column = "country")
    private String country;

    @CsvBindByName(column = "city")
    private String city;

    @CsvBindByName(column = "radioname")
    private String radioname;

    @CsvBindByName(column = "url_logo")
    private String url_logo;

    @CsvBindByName(column = "url_stream")
    private String url_stream;

    public String getCountry() { return country; }
    public String getCity() { return city; }
    public String getRadioname() { return radioname; }
    public String getUrl_logo() { return url_logo; }
    public String getUrl_stream() { return url_stream; }
}

Main class

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 */

package com.dedetok.testopencsv;

import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.exceptions.CsvValidationException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import java.util.List;

/**
 *
 * @author dedetok
 */
public class TestOpenCSV {

    static String urlString = "https://raw.githubusercontent.com/dedetok/myradiolist/refs/heads/main/myradio_radiolist.csv";
    
    public static void main(String[] args) throws CsvValidationException {
        System.out.println("Hello World!");
        
        // start function

        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // Check response
            int status = connection.getResponseCode();
            if (status == 200) {
                // Configure parser: semicolon separator, double-quote as quote char
                InputStreamReader reader = new InputStreamReader(connection.getInputStream());
                // Start For parsing manual
                CSVParser parser = new CSVParserBuilder()
                        .withSeparator(';')
                        .withQuoteChar('"')
                        .build();
                //CSVReader csvReader = new CSVReader(reader);
                CSVReader csvReader = new CSVReaderBuilder(reader)
                        .withCSVParser(parser)
                        //.withSkipLines(1) // skip header if needed
                        .build();
                String[] nextLine;
                int i=1;
                while ((nextLine = csvReader.readNext()) != null) {
                    for (String cell : nextLine) {
                        System.out.print(cell + " | ");
                    }
                    i++;
                    System.out.println();
                    if (i==5) {
                        break;
                    }
                }
                // End For parsing manual
                // start convert directly to list<Radio> using opencsv beans
                /*
                CsvToBean<Radio> csvToBean = new CsvToBeanBuilder<Radio>(reader)
                    .withType(Radio.class)
                    .withSeparator(';')
                    .withQuoteChar('"')
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();
                List<Radio> radios = csvToBean.parse();
                System.out.println("Loaded " + radios.size() + " radios!");
                
                // debug
                for (int i = 0; i < Math.min(5, radios.size()); i++) {
                    Radio r = radios.get(i);
                    System.out.println(
                        r.getCountry() + " | " +
                        r.getCity() + " | " +
                        r.getRadioname() + " | " +
                        r.getUrl_logo() + " | " +
                        r.getUrl_stream()
                    );
                }
                */
                // end convert directly to list<Radio> using opencsv beans

            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(TestOpenCSV.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TestOpenCSV.class.getName()).log(Level.SEVERE, null, ex);
        }      
    }
}

 Code is write with collaboration with chatgpt 

 

Tuesday, August 5, 2025

Netbeans: using maven to connect to mariadb

  1. Create project "Java with Maven" -> "Java Application"
  2. Under tab "Project" -> Project Files, edit pom.xml and add mariadb jconnect client
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ...
      <dependencies>
    ...
      <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client</artifactId>
        <version>3.5.3</version>
        </dependency>
      </dependencies>
    ...
    </project>
  3. Test connection using this code
      public static void main(String[] args) throws SQLException, ClassNotFoundException {
        // TODO Auto-generated method stub
        String muser = "my_user";
        String mpass = "my_password";
        String murl = "jdbc:mariadb://localhost:3306/my_database_name";
        Class.forName("org.mariadb.jdbc.Driver");
        Connection connection = DriverManager.getConnection(murl, muser, mpass);
        System.out.println("ok");
      }

Friday, May 9, 2025

Netbeans: Netbeans 25 with JDK 17 add MariaDB Connector/J 3.5 into Java Project Maven

Netbeans 25 can be download from https://www.apache.org/dyn/closer.lua/netbeans/netbeans/25/netbeans-25-bin.zip. Extract it, it will create folder netbeans. 

On debian, to run netbeans:

[home_user]\netbeans/bin/netbeans

On window, to run netbeans (windows 64):

[folder]\netbeans\bin\netbeans64.exe

Note: on windows, if you want to clean install remove/delete folder C:\Users\[username]\AppData\Roaming\NetBeans\[any_previous].

Download mariadb-java-client-3.5.3.jar from https://mariadb.com/downloads/connectors/connectors-data-access/java8-connector/ and choose mariadb-java-client-3.5.3.jar.

Add mariadb-java-client-3.5.3.jar into project

  1. create a New Project -> Java with maven -> Java application
  2. in tab Files under your project, create folder libjar
  3. copy mariadb-java-client-3.5.3.jar
  4. in Project -> your project, right click on Dependencies, Add Dependency:
    Group ID: org.mariadb.jdbc
    Artifact ID: mariadb-java-client
    Version: 3.5.3
  5. Scope: Runtime
  6. done. 

Run your database and test your project by editing your java files:

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        // TODO Auto-generated method stub
        String muser = "
my_user";
        String mpass = "
my_password";
        String murl = "jdbc:mariadb://localhost:3306/
my_database_name";
        Class.forName("org.mariadb.jdbc.Driver");
        Connection connection = DriverManager.getConnection(murl, muser, mpass);
        System.out.println("ok");
    }

Add mariadb to Services:

  1. to add mariadb connector j, go to Services -> Right Click Databases -> New Connection.
  2. Select MariaDB (MySQL-compatible).
  3. select jar file.
  4. next.
  5. fill/adjust username, password and database name.
  6. test connection.
  7. if successfull, next.
  8. leave default connection info and finish.

You can manage your mariadb database from Service.