Last active
October 3, 2023 17:49
-
-
Save luckeyboylooser/2e541999ad45d73d3a3c84911700e530 to your computer and use it in GitHub Desktop.
Java code that retrieves weather data using openweather api and google calendar api to check for events and then lets you know what to wear depending on the weather
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javafx.application.Application; | |
import javafx.scene.Scene; | |
import javafx.scene.control.*; | |
import javafx.scene.layout.*; | |
import javafx.stage.Stage; | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import java.security.GeneralSecurityException; | |
import java.io.IOException; | |
import java.util.Collections; | |
import java.util.List; | |
import org.json.JSONObject; // You need the JSON library | |
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; | |
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; | |
import com.google.api.client.json.JsonFactory; | |
import com.google.api.client.json.JsonParserFactory; | |
import com.google.api.services.calendar.Calendar; | |
import com.google.api.services.calendar.CalendarScopes; | |
import com.google.api.services.calendar.model.*; | |
import org.json.JSONObject; // You need the JSON library | |
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; | |
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; | |
import com.google.api.client.json.JsonFactory; | |
import com.google.api.client.json.JsonParserFactory; | |
import com.google.api.services.calendar.Calendar; | |
import com.google.api.services.calendar.CalendarScopes; | |
import com.google.api.services.calendar.model.*; | |
//------------------------------------------------------------------------------------------------------------------- CALENDER EVENTS DISPLAY CLASS | |
public class CalendarEventsRetrieval { | |
private static final String APPLICATION_NAME = "WeatherAndCalendarApp"; | |
private static final JsonFactory JSON_FACTORY = JsonFactory.getDefaultInstance(); | |
private static final String SERVICE_ACCOUNT_JSON_KEY_FILE = "D:/downloads all/client_secret_895648545337-mvk7lm1icl45lpr0gc3ga99f8qdn2n56.apps.googleusercontent.com.json"; | |
// service acc JSON key file | |
private static final String CALENDAR_ID = "primary"; // Use "primary" for the user's primary calendar | |
public static List<Event> getCalendarEvents() throws IOException { | |
// Initialize the Google Calendar service with credentials | |
Calendar service = initializeCalendarService(); | |
// Define the start and end dates for the events query (e.g., for the next week) | |
DateTime now = new DateTime(System.currentTimeMillis()); | |
DateTime endOfWeek = new DateTime(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000); // 7 days from now | |
// Create a list to store the fetched events | |
List<Event> events = Collections.emptyList(); | |
try { | |
// Fetch events from the user's calendar | |
Events eventsResponse = service.events().list(CALENDAR_ID) | |
.setTimeMin(now) | |
.setTimeMax(endOfWeek) | |
.setOrderBy("startTime") | |
.setSingleEvents(true) | |
.execute(); | |
events = eventsResponse.getItems(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return events; | |
} | |
private static Calendar initializeCalendarService() throws IOException { | |
// Load the service account credentials from the JSON key file | |
GoogleCredential credentials = GoogleCredential.fromStream( | |
CalendarEventsRetrieval.class.getResourceAsStream(SERVICE_ACCOUNT_JSON_KEY_FILE)) | |
.createScoped(Collections.singleton(CalendarScopes.CALENDAR)); | |
// Build and return the Google Calendar service | |
return new Calendar.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, credentials) | |
.setApplicationName(APPLICATION_NAME) | |
.build(); | |
} | |
} | |
//-------------------------------------------------------------------------------------------------------------------- WEATHER RETRIEVAL CLASS | |
public class WeatherDataRetrieval { | |
public static String getWeatherData(String apiKey, String city) throws IOException { | |
String apiUrl = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey; | |
try { | |
// Create a URL for the OpenWeatherMap API | |
URL url = new URL(apiUrl); | |
// Open a connection to the URL | |
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); | |
// Set the request method to GET | |
connection.setRequestMethod("GET"); | |
// Get the response code from the connection | |
int responseCode = connection.getResponseCode(); | |
if (responseCode == HttpURLConnection.HTTP_OK) { | |
// Create a BufferedReader to read the API response | |
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); | |
String inputLine; | |
StringBuilder response = new StringBuilder(); | |
// Read the response line by line | |
while ((inputLine = reader.readLine()) != null) { | |
response.append(inputLine); | |
} | |
// Close the BufferedReader | |
reader.close(); | |
// Return the JSON response as a string | |
return response.toString(); | |
} else { | |
// Handle the case where the API request fails | |
throw new IOException("API request failed with response code: " + responseCode); | |
} | |
} catch (IOException e) { | |
// Handle any exceptions that occur during the API call | |
throw e; | |
} | |
} | |
} | |
//-------------------------------------------------------------------------------------------------------------------- WEATHER AND CAL CLASS | |
public class WeatherAndCalendarApp extends Application { | |
private TextField cityInput; | |
private TextArea weatherOutput; | |
private TextArea calendarEventsOutput; | |
public static void main(String[] args) { | |
launch(args); | |
} | |
@Override | |
public void start(Stage primaryStage) { | |
primaryStage.setTitle("Weather and Calendar App"); | |
Label cityLabel = new Label("Enter City:"); | |
cityInput = new TextField(); | |
Button getWeatherButton = new Button("Get Weather"); | |
getWeatherButton.setOnAction(e -> getWeather()); | |
weatherOutput = new TextArea(); | |
weatherOutput.setEditable(false); | |
weatherOutput.setWrapText(true); | |
calendarEventsOutput = new TextArea(); | |
calendarEventsOutput.setEditable(false); | |
calendarEventsOutput.setWrapText(true); | |
VBox vbox = new VBox(10); | |
vbox.getChildren().addAll(cityLabel, cityInput, getWeatherButton, weatherOutput, new Label("Calendar Events:"), calendarEventsOutput); | |
Scene scene = new Scene(vbox, 600, 400); | |
primaryStage.setScene(scene); | |
primaryStage.show(); | |
} | |
private void getWeather() { | |
String apiKey = "YOUR_OPENWEATHER_API_KEY"; | |
String city = cityInput.getText(); | |
try { | |
String weatherData = getWeatherData(apiKey, city); | |
// Parse the weather data JSON and extract relevant information | |
String recommendations = generateClothingRecommendations(weatherData); | |
weatherOutput.setText("Weather in " + city + ":\n" + weatherData + "\n\n" + recommendations); | |
} catch (IOException e) { | |
weatherOutput.setText("Error: Failed to fetch weather data."); | |
e.printStackTrace(); | |
} | |
try { | |
List<Event> events = getCalendarEvents(); | |
displayCalendarEvents(events); | |
} catch (IOException | GeneralSecurityException e) { | |
calendarEventsOutput.setText("Error: Failed to fetch calendar events."); | |
e.printStackTrace(); | |
} | |
} | |
private String generateClothingRecommendations(String weatherData) { | |
// Parse the weather data JSON and extract relevant information | |
double temperature = extractTemperature(weatherData); | |
String weatherCondition = extractWeatherCondition(weatherData); | |
// Initialize clothing recommendations | |
StringBuilder recommendations = new StringBuilder("Recommended clothing based on weather conditions:\n"); | |
// Analyze temperature and weather conditions | |
if (weatherCondition.contains("rain") || weatherCondition.contains("thunderstorm")) { | |
recommendations.append(" - Umbrella and waterproof jacket for rainy weather.\n"); | |
} else if (weatherCondition.contains("snow")) { | |
recommendations.append(" - Warm clothing, snow boots, and gloves for snowy weather.\n"); | |
} else if (temperature > 25) { | |
recommendations.append(" - Light clothing, sunglasses, and sunscreen for hot weather.\n"); | |
} else if (temperature < 10) { | |
recommendations.append(" - Warm coat, hat, and gloves for cold weather.\n"); | |
} else { | |
recommendations.append(" - Casual clothing for the current weather.\n"); | |
} | |
return recommendations.toString(); | |
} | |
private double extractTemperature(String weatherData) { | |
// Implement logic to extract temperature from weatherData | |
// Parse the JSON and access the temperature field | |
// Example: double temperature = parsedWeatherData.getDouble("main.temp"); | |
return 20.0; // Replace with actual temperature extraction logic | |
} | |
private String extractWeatherCondition(String weatherData) { | |
// Implement logic to extract weather conditions from weatherData | |
// Parse the JSON and access the weather condition field | |
// Example: String condition = parsedWeatherData.getJSONArray("weather").getJSONObject(0).getString("main"); | |
return "clear"; // Replace with actual weather condition extraction logic | |
} | |
//------------------------------------------- json file | |
private double extractTemperature(String weatherData) { | |
try { | |
// Parse the weatherData JSON response | |
JSONObject jsonData = new JSONObject(weatherData); | |
// Extract the temperature from the "main" object | |
JSONObject mainObject = jsonData.getJSONObject("main"); | |
double temperature = mainObject.getDouble("temp"); | |
// The temperature is typically in Kelvin; you may convert it to Celsius or Fahrenheit if needed | |
// Example conversion to Celsius: | |
// temperature -= 273.15; | |
return temperature; | |
} catch (Exception e) { | |
// Handle any exceptions that may occur during parsing | |
e.printStackTrace(); | |
return 0.0; // Return a default value or handle the error as needed | |
} | |
} | |
//---------------------------------------------------------------------------------------------------------------- TO FETCH WEATHER DATA | |
private String getWeatherData(String apiKey, String city) throws IOException { | |
// Use the provided WeatherDataRetrieval class to fetch weather data | |
try { | |
return WeatherDataRetrieval.getWeatherData(apiKey, city); | |
} catch (IOException e) { | |
throw e; | |
} | |
} | |
// Inside the getWeather() method | |
try { | |
String weatherData = getWeatherData(apiKey, city); | |
weatherOutput.setText("Weather in " + city + ":\n" + weatherData); | |
} catch (IOException e) { | |
weatherOutput.setText("Error: Failed to fetch weather data."); | |
e.printStackTrace(); | |
} | |
//------------------------------------------------------------------------------------------------------------- TO GET CALENDAR EVENTS | |
private List<Event> getCalendarEvents() throws IOException { | |
// Use the provided CalendarEventsRetrieval class to fetch calendar events | |
try { | |
return CalendarEventsRetrieval.getCalendarEvents(); | |
} catch (IOException e) { | |
throw e; | |
} | |
} | |
//-------------------------------------------------------------------------------------------------------------------- TO DISPLAY CALENDAR EVENTS | |
private void displayCalendarEvents(List<Event> events) { | |
StringBuilder eventText = new StringBuilder(); | |
if (events != null && !events.isEmpty()) { | |
for (Event event : events) { | |
String summary = event.getSummary(); | |
String startDateTime = event.getStart().getDateTime().toString(); | |
String endDateTime = event.getEnd().getDateTime().toString(); | |
eventText.append("Summary: ").append(summary).append("\n"); | |
eventText.append("Start Time: ").append(startDateTime).append("\n"); | |
eventText.append("End Time: ").append(endDateTime).append("\n"); | |
eventText.append("\n"); | |
} | |
} else { | |
eventText.append("No upcoming events found."); | |
} | |
calendarEventsOutput.setText(eventText.toString()); | |
} | |
//------------------------------------------------------------------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment