Open hyyan opened 2 months ago
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.webforj.App; import com.webforj.annotation.InlineStyleSheet; import com.webforj.component.field.TextArea; import com.webforj.component.window.Frame; import com.webforj.exceptions.WebforjException; import com.webforj.exceptions.WebforjRuntimeException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.List; @InlineStyleSheet( /* css */ """ dwc-textarea { display: block; margin: var(--dwc-space-m) auto; max-width: 600px; height: 200px; }""") public class PredictedValue extends App { private static final String API_URL = "https://api.datamuse.com/sug?s="; TextArea textArea = new TextArea("Predicted Text", "", "Type something to see suggestions"); @Override public void run() throws WebforjException { textArea.setHelperText("Type something to see suggestions, for instance, type 'Sky is'. " + "Then wait for a few seconds to see the suggestions. You can insert the suggestion" + "by pressing Tab or ArrowRight key or simply ignore it by typing further."); textArea.onValueChange(event -> { try { String input = event.getValue(); if (input.length() == 0) { textArea.setPredictedText(""); return; } String bestSuggestion = fetchBestSuggestion(input); String predictedValue = ""; if (!bestSuggestion.isEmpty() && bestSuggestion.length() >= input.length()) { predictedValue = input + bestSuggestion.substring(input.length()); } textArea.setPredictedText(predictedValue); } catch (Exception e) { throw new WebforjRuntimeException("Failed to fetch suggestions", e); } }); Frame frame = new Frame(); frame.setTitle("Predicted Text"); frame.add(textArea); } /** * Fetches the best suggestion from the API. * * @param input The input text * @return The best suggestion * @throws Exception If the API call fails */ public String fetchBestSuggestion(String input) throws Exception { String urlString = API_URL + URLEncoder.encode(input, StandardCharsets.UTF_8.toString()) + "*"; URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder content = new StringBuilder(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); conn.disconnect(); // Parse JSON response Gson gson = new Gson(); List<WordSuggestion> suggestions = gson.fromJson(content.toString(), new TypeToken<List<WordSuggestion>>() {}.getType()); // Find the word with the highest score WordSuggestion bestSuggestion = suggestions.stream() .max((a, b) -> Integer.compare(a.getScore(), b.getScore())).orElse(new WordSuggestion()); return bestSuggestion.getWord(); } /** * Represents a suggestion with a score. */ public final class WordSuggestion { private String word = ""; private int score = 0; public String getWord() { return word; } public int getScore() { return score; } } }
see #166