Skip to content

gaurav-manchandaa/java-weather

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java Weather Application

A comprehensive weather application built in Java that replicates JavaScript weather app features. This application fetches live weather data from the OpenWeatherMap API and provides both console and GUI interfaces.

Features

  • Live Weather Data: Fetches real-time weather information from OpenWeatherMap API
  • Multiple Data Points: Displays temperature, humidity, and wind speed
  • User Input: Allows users to enter any city name
  • JSON Parsing: Uses org.json library for parsing API responses
  • Error Handling: Comprehensive error handling for invalid cities and network issues
  • HTTP Communication: Uses HttpURLConnection for API calls
  • Clean Architecture: Modular code with separate methods for API requests, JSON parsing, and display
  • Two Interfaces: Both console and Java Swing GUI versions
  • Best Practices: Clear variable names and follows Java coding standards

Project Structure

java-weather-app/
├── pom.xml                                    # Maven configuration with org.json dependency
├── README.md                                  # This file
└── src/main/java/com/weather/
    ├── WeatherAppConsole.java                 # Console version of the application
    ├── WeatherAppGUI.java                     # Swing GUI version of the application
    ├── exception/
    │   └── WeatherException.java              # Custom exception for weather-related errors
    ├── model/
    │   └── WeatherData.java                   # Data model for weather information
    └── service/
        └── WeatherService.java                # Service class handling API communication

Prerequisites

  • Java 11 or higher
  • Maven 3.6 or higher
  • Internet connection for API calls
  • OpenWeatherMap API key (free registration required)

Setup Instructions

1. Get OpenWeatherMap API Key

  1. Visit https://openweathermap.org/api
  2. Sign up for a free account
  3. Navigate to the API keys section
  4. Copy your API key

2. Configure API Key

  1. Open src/main/java/com/weather/service/WeatherService.java
  2. Replace YOUR_API_KEY_HERE with your actual API key:
    private static final String API_KEY = "your_actual_api_key_here";

3. Build the Project

Option A: Using the Build Script (Recommended)

cd java-weather-app
./build.sh

Option B: Using Maven (if available)

cd java-weather-app
mvn clean compile

Running the Applications

Console Version

# Using build script
./run-console.sh

# Or using Maven (if available)
mvn exec:java -Dexec.mainClass="com.weather.WeatherAppConsole"

GUI Version

# Using build script
./run-gui.sh

# Or using Maven (if available)
mvn exec:java -Dexec.mainClass="com.weather.WeatherAppGUI"

Usage

Console Application

  1. Run the console application
  2. Enter a city name when prompted
  3. View the weather information displayed
  4. Type 'quit' or 'exit' to close the application

Example output:

==================================================
        JAVA WEATHER APPLICATION
==================================================
Get real-time weather information for any city!
Type 'quit' or 'exit' to close the application.
--------------------------------------------------
Enter city name: London
Fetching weather data for London...

========================================
  Weather in London, GB
========================================
🌡️  Temperature: 15.3°C
💧 Humidity: 72%
💨 Wind Speed: 3.6 m/s
☁️  Conditions: Few Clouds
📊 Weather: Clouds
========================================

GUI Application

  1. Run the GUI application
  2. Enter a city name in the text field
  3. Click "Get Weather" or press Enter
  4. View the weather information in the formatted panel
  5. The application shows a progress bar during API calls
  6. Error messages are displayed both in the status bar and popup dialogs

Dependencies

The project uses Maven for dependency management. The main dependency is:

  • org.json (version 20231013): For parsing JSON responses from the OpenWeatherMap API

Maven will automatically download all dependencies when you build the project.

API Information

This application uses the OpenWeatherMap Current Weather Data API:

  • Base URL: http://api.openweathermap.org/data/2.5/weather
  • Response Format: JSON
  • Units: Metric (Celsius for temperature, m/s for wind speed)
  • Rate Limits: Free accounts get 1,000 API calls per day

Error Handling

The application handles various error scenarios:

  • Invalid City: Shows user-friendly message with suggestions
  • Network Issues: Displays connection error information
  • API Key Issues: Provides setup instructions
  • JSON Parsing Errors: Handles malformed API responses
  • API Rate Limits: Handles HTTP response codes appropriately

Code Architecture

WeatherService Class

  • Handles all HTTP communication with the OpenWeatherMap API
  • Manages connection timeouts and error responses
  • Parses JSON responses into WeatherData objects
  • Implements proper resource cleanup

WeatherData Model

  • Data transfer object containing weather information
  • Includes city name, country, temperature, humidity, wind speed, and weather conditions
  • Provides toString() method for easy console display

Console Application

  • Simple command-line interface
  • Input validation and error handling
  • Formatted output with emojis for better visual appeal
  • Graceful shutdown on user command

GUI Application

  • Modern Swing-based interface
  • Asynchronous API calls using SwingWorker
  • Progress indication during API calls
  • Comprehensive error dialogs
  • Responsive design that adapts to content

Customization

You can easily customize the application:

  1. Change Temperature Units: Modify the API URL in WeatherService to use units=imperial for Fahrenheit
  2. Add More Weather Data: Extend WeatherData model and parsing logic to include additional fields
  3. Styling: Customize colors, fonts, and layout in the GUI version
  4. Additional Features: Add weather forecasts, weather history, or favorite cities

Troubleshooting

Common Issues

  1. "API Key Required" Error

    • Make sure you've replaced YOUR_API_KEY_HERE with your actual API key
    • Verify your API key is active (new keys may take a few hours to activate)
  2. "City Not Found" Error

    • Check city name spelling
    • Try adding country code (e.g., "London,UK")
    • Use English city names
  3. Network Connection Issues

    • Check your internet connection
    • Verify firewall settings allow HTTP requests
    • Some corporate networks may block API calls
  4. Compilation Issues

    • Ensure Java 11 or higher is installed
    • Verify Maven is properly configured
    • Check that all source files are present

License

This project is created for educational purposes. Please respect OpenWeatherMap's terms of service when using their API.

About

A comprehensive Java weather application with console and GUI interfaces that fetches live weather data from OpenWeatherMap API

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors