Saturday, May 31, 2025

[JAVA] CREATE WEB DOMAIN SERVER

URL link in Java, you can utilize the java.net.URL class, which represents a Uniform Resource Locator. Here's how you can work with URLs in Java:
1. Creating a URL Object:
  • You can create a URL object by providing a string representation of the URL.
  • Example:
Java
     try {         URL url = new URL("http://www.example.com");     } catch (MalformedURLException e) {         // Handle the exception if the URL is invalid         e.printStackTrace();     }
  • It's recommended to use java.net.URI to parse or construct a URL instead of the deprecated URL constructors.
2. Connecting to the URL:
  • To establish a connection, use the openConnection() method of the URL object, which returns a URLConnection object.
  • Example:
Java
     try {         URL url = new URL("http://www.example.com");         URLConnection connection = url.openConnection();         connection.connect(); // Initiates the connection     } catch (MalformedURLException | IOException e) {         e.printStackTrace();     }
3. Reading Data from the URL:
  • You can read data from the URL using the getInputStream() method of the URLConnection object, which returns an InputStream.
  • Example:
Java
     try {         URL url = new URL("http://www.example.com");         URL page2URL = new URL(url, "page2.html");
URLConnection connection = url.openConnection();         InputStream inputStream = connection.getInputStream();         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));         String line;         while ((line = reader.readLine()) != null) {             System.out.println(line);         }         reader.close();         inputStream.close();     } catch (MalformedURLException | IOException e) {         e.printStackTrace();     }
4. Sending HTTP Requests:
  • For more advanced interactions like sending HTTP GET or POST requests, use HttpURLConnection.
  • Example:
Java
     try {         URL url = new URL("http://www.example.com/api");         HttpURLConnection connection = (HttpURLConnection) url.openConnection();         connection.setRequestMethod("GET"); // Or "POST"         int responseCode = connection.getResponseCode();         if (responseCode == HttpURLConnection.HTTP_OK) {             // Read response         }         connection.disconnect();     } catch (MalformedURLException | IOException e) {         e.printStackTrace();     }
  • Set request properties using setRequestProperty() and handle the response accordingly.
5. Other URL Operations:
  • You can obtain different parts of the URL such as the protocol, host, port, and file using methods like getProtocol()getHost()getPort(), and getFile().
  • You can also extract the reference part (fragment) of the URL using getRef().
6. Working with Local Files:
  • To use a local file as a URL, you can create a URL object using the file path.
  • Example:
Java
     try {         URL fileUrl = new URL("file:///path/to/your/file.txt");     } catch (MalformedURLException e) {         e.printStackTrace();     }
  • Be mindful of path separators and character escaping when dealing with local files.
Important Considerations:
  • Remember to handle MalformedURLException when creating URL objects, and IOException when connecting to or reading from URLs.
  • Consider using libraries like Apache HttpClient for more robust HTTP interactions.
  • When working with server-side applications, web servers like Apache Tomcat can be used to handle requests.

[JAVA] EMAIL SEND

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class EmailSender {
    public static void main(String[] args) {
        String to = "recipient@example.com";
        String from = "sender@example.com";
        String host = "smtp.example.com";
        String username = "your_username";
        String password = "your_password";

        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", "587"); // or 465 for SSL
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true"); // for TLS

        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("Test Email");
            message.setText("This is a test email.");

            Transport.send(message);
            System.out.println("Email sent successfully!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

[JAVA] INHERITANCE

class Animal {
    String name;
    public void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("Dog is barking");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.name = "Buddy";
        dog.eat(); // Inherited from Animal
        dog.bark(); // Specific to Dog
    }
}

[JAVA] PAINT EXAMPLE SIMPLE

import java.util.Arrays;

public class SortString {
    public static void main(String[] args) {
        String inputString = "javaexample";
        char[] charArray = inputString.toCharArray();

        Arrays.sort(charArray);

        String sortedString = new String(charArray);
        System.out.println("Original String: " + inputString);
        System.out.println("Sorted String: " + sortedString);
    }
}

[JAVA] PAUSE AUDIO

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

public class AudioPlayer {

    private Clip clip;
    private long clipTime;

    public void loadAudio(String filePath) throws LineUnavailableException, IOException, UnsupportedAudioFileException {
        File audioFile = new File(filePath);
        AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
        clip = AudioSystem.getClip();
        clip.open(audioStream);
    }

    public void play() {
        clip.start();
    }

    public void pause() {
        clipTime = clip.getMicrosecondPosition();
        clip.stop();
    }

    public void resume() {
        clip.setMicrosecondPosition(clipTime);
        clip.start();
    }

    public void stop() {
        clip.stop();
        clip.close();
    }

    public static void main(String[] args) {
        AudioPlayer player = new AudioPlayer();
        try {
            player.loadAudio("path/to/your/audio.wav"); // Replace with your audio file path
            player.play();

            // Simulate pausing after 2 seconds
            Thread.sleep(2000);
            player.pause();
            System.out.println("Audio paused");

            // Simulate resuming after 2 seconds
            Thread.sleep(2000);
            player.resume();
            System.out.println("Audio resumed");

            // Let the audio play for 5 seconds
            Thread.sleep(5000);
            player.stop();
            System.out.println("Audio stopped");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

[JAVA] SORT by A to Z from String

import java.util.Arrays;

public class SortString {
    public static void main(String[] args) {
        String inputString = "javaexample";
        char[] charArray = inputString.toCharArray();

        Arrays.sort(charArray);

        String sortedString = new String(charArray);
        System.out.println("Original String: " + inputString);
        System.out.println("Sorted String: " + sortedString);
    }
}

[JAVA] JAVA AUTO DRAWING IMAGE FROM IMAGE

import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class AutoDrawImage {

    public static void main(String[] args) {
        try {
            // Load the source image
            BufferedImage sourceImage = ImageIO.read(new File("path/to/your/source/image.jpg"));

            // Create a destination image
            BufferedImage destinationImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_ARGB);

            // Get the graphics context
            Graphics2D g2d = destinationImage.createGraphics();

            // Draw the source image onto the destination
            g2d.drawImage(sourceImage, 0, 0, null);
            g2d.dispose();

            // Save the result
            ImageIO.write(destinationImage, "png", new File("path/to/your/output/image.png"));
            System.out.println("Image drawn and saved successfully!");

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