Search in sources :

Example 6 with Task

use of org.apache.pivot.util.concurrent.Task in project pivot by apache.

the class WebQueries method startup.

@Override
public void startup(Display display, Map<String, String> properties) throws Exception {
    BXMLSerializer bxmlSerializer = new BXMLSerializer();
    window = (Window) bxmlSerializer.readObject(WebQueries.class, "web_queries.bxml");
    listView = (ListView) bxmlSerializer.getNamespace().get("listView");
    loadingLabel = (Label) bxmlSerializer.getNamespace().get("loadingLabel");
    // Execute the query:
    // http://pipes.yahoo.com/pipes/pipe.run?_id=43115761f2da5af5341ae2e56a93d646&_render=json
    GetQuery getQuery = new GetQuery("pipes.yahoo.com", "/pipes/pipe.run");
    getQuery.getParameters().put("_id", "43115761f2da5af5341ae2e56a93d646");
    getQuery.getParameters().put("_render", "json");
    getQuery.execute(new TaskAdapter<>(new TaskListener<Object>() {

        @Override
        public void taskExecuted(Task<Object> task) {
            List<?> items = (List<?>) JSON.get(task.getResult(), "value.items");
            if (items.getLength() > 0) {
                listView.setListData(items);
                loadingLabel.setVisible(false);
            } else {
                loadingLabel.setText("No results.");
            }
        }

        @Override
        public void executeFailed(Task<Object> task) {
            loadingLabel.setText(task.getFault().getMessage());
        }
    }));
    window.open(display);
}
Also used : Task(org.apache.pivot.util.concurrent.Task) GetQuery(org.apache.pivot.web.GetQuery) TaskListener(org.apache.pivot.util.concurrent.TaskListener) List(org.apache.pivot.collections.List) BXMLSerializer(org.apache.pivot.beans.BXMLSerializer)

Example 7 with Task

use of org.apache.pivot.util.concurrent.Task in project pivot by apache.

the class StockTrackerWindow method refreshTable.

private void refreshTable() {
    // Abort any outstanding query
    if (getQuery != null) {
        synchronized (getQuery) {
            if (getQuery.isPending()) {
                getQuery.abort();
            }
        }
    }
    // Execute the query
    if (symbols.getLength() > 0) {
        getQuery = new GetQuery(SERVICE_HOSTNAME, SERVICE_PATH);
        StringBuilder symbolsParameterBuilder = new StringBuilder();
        for (int i = 0, n = symbols.getLength(); i < n; i++) {
            if (i > 0) {
                symbolsParameterBuilder.append(",");
            }
            symbolsParameterBuilder.append(symbols.get(i));
        }
        // Format:
        // s - symbol
        // n - company name
        // l1 - most recent value
        // o - opening value
        // h - high value
        // g - low value
        // c1 - change percentage
        // v - volume
        String symbolsParameter = symbolsParameterBuilder.toString();
        getQuery.getParameters().put("s", symbolsParameter);
        getQuery.getParameters().put("f", "snl1ohgc1v");
        CSVSerializer quoteSerializer = new CSVSerializer(StockQuote.class);
        quoteSerializer.setKeys("symbol", "companyName", "value", "openingValue", "highValue", "lowValue", "change", "volume");
        getQuery.setSerializer(quoteSerializer);
        getQuery.execute(new TaskAdapter<>(new TaskListener<Object>() {

            @Override
            public void taskExecuted(Task<Object> task) {
                if (task == getQuery) {
                    @SuppressWarnings("unchecked") List<Object> quotes = (List<Object>) task.getResult();
                    // Preserve any existing sort and selection
                    Sequence<?> selectedStocks = stocksTableView.getSelectedRows();
                    @SuppressWarnings("unchecked") List<Object> tableData = (List<Object>) stocksTableView.getTableData();
                    Comparator<Object> comparator = tableData.getComparator();
                    quotes.setComparator(comparator);
                    stocksTableView.setTableData(quotes);
                    if (selectedStocks.getLength() > 0) {
                        // Select current indexes of selected stocks
                        for (int i = 0, n = selectedStocks.getLength(); i < n; i++) {
                            Object selectedStock = selectedStocks.get(i);
                            int index = 0;
                            for (Object stock : stocksTableView.getTableData()) {
                                String symbol = JSON.get(stock, "symbol");
                                String selectedSymbol = JSON.get(selectedStock, "symbol");
                                if (symbol.equals(selectedSymbol)) {
                                    stocksTableView.addSelectedIndex(index);
                                    break;
                                }
                                index++;
                            }
                        }
                    } else {
                        if (quotes.getLength() > 0) {
                            stocksTableView.setSelectedIndex(0);
                        }
                    }
                    refreshDetail();
                    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, Locale.getDefault());
                    lastUpdateLabel.setText(dateFormat.format(new Date()));
                    getQuery = null;
                }
            }

            @Override
            public void executeFailed(Task<Object> task) {
                if (task == getQuery) {
                    System.err.println(task.getFault());
                    getQuery = null;
                }
            }
        }));
    }
}
Also used : Task(org.apache.pivot.util.concurrent.Task) Date(java.util.Date) GetQuery(org.apache.pivot.web.GetQuery) DateFormat(java.text.DateFormat) TaskListener(org.apache.pivot.util.concurrent.TaskListener) ArrayList(org.apache.pivot.collections.ArrayList) List(org.apache.pivot.collections.List) CSVSerializer(org.apache.pivot.serialization.CSVSerializer)

Example 8 with Task

use of org.apache.pivot.util.concurrent.Task in project pivot by apache.

the class SplashScreenTest method startup.

@Override
public void startup(final Display display, final Map<String, String> properties) throws Exception {
    File splashFile = new File("org/apache/pivot/tests/splash.png");
    System.out.println("Startup the application at " + new Date());
    System.out.println("To show the Splash Screen, remember to run as a Standard Java Application this way:\n" + "java -splash:" + splashFile.getPath() + " <mainclassname> --preserveSplashScreen=true\n" + "or no splash screen will be shown.");
    // Create a Task that will load a BXML file and simulate some other
    // processing while updating a progress meter on the SplashScreen
    final Task<Void> prepareApplicationTask = new Task<Void>() {

        final SplashScreenProgressOverlay progressOverlay = new SplashScreenProgressOverlay();

        @Override
        public Void execute() throws TaskExecutionException {
            // Load the main BXML
            progressOverlay.increment(0);
            loadBXML(display, 0.1);
            // Simulate other tasks until the progress meter has been filled
            final Random random = new Random();
            while (progressOverlay.getPercentage() < 1.0) {
                // Short random sleep to simulate some processing
                try {
                    Thread.sleep(random.nextInt(50) + 100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // Update the progress meter by a random amount
                progressOverlay.increment((1 + random.nextInt(10)) / 100.0);
            }
            return null;
        }

        // Load the Pivot UI
        private void loadBXML(final Display displayArgument, final double weight) {
            try {
                ApplicationContext.queueCallback(() -> {
                    Window window = null;
                    try {
                        window = (Window) new BXMLSerializer().readObject(this.getClass().getResource("splash.bxml"));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    if (window != null) {
                        window.open(displayArgument);
                        progressOverlay.increment(weight);
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
    // Hide the SplashScreen when the Task finishes by making the Pivot host
    // window visible.
    final TaskListener<Void> taskListener = new TaskListener<Void>() {

        @Override
        public void taskExecuted(final Task<Void> task) {
            finished();
        }

        @Override
        public void executeFailed(final Task<Void> task) {
            System.err.println(String.format("Failed\n%s", task.getFault()));
            task.getFault().printStackTrace();
            finished();
        }

        private void finished() {
            DesktopApplicationContext.replaceSplashScreen(display);
        }
    };
    // Run the Task asynchronously
    prepareApplicationTask.execute(new TaskAdapter<>(taskListener));
}
Also used : Window(org.apache.pivot.wtk.Window) Task(org.apache.pivot.util.concurrent.Task) Date(java.util.Date) TaskExecutionException(org.apache.pivot.util.concurrent.TaskExecutionException) Random(java.util.Random) TaskListener(org.apache.pivot.util.concurrent.TaskListener) File(java.io.File) BXMLSerializer(org.apache.pivot.beans.BXMLSerializer) Display(org.apache.pivot.wtk.Display)

Example 9 with Task

use of org.apache.pivot.util.concurrent.Task in project pivot by apache.

the class SuggestionDemo method getSuggestions.

private void getSuggestions() {
    if (suggestionQuery != null && suggestionQuery.isPending()) {
        suggestionQuery.abort();
    }
    // Get the query text
    String text;
    try {
        text = URLEncoder.encode(textInput.getText(), "UTF-8");
    } catch (UnsupportedEncodingException exception) {
        throw new RuntimeException(exception);
    }
    // Create query
    suggestionQuery = new GetQuery("search.yahooapis.com", "/WebSearchService/V1/relatedSuggestion");
    suggestionQuery.getParameters().put("appid", getClass().getName());
    suggestionQuery.getParameters().put("query", text);
    suggestionQuery.getParameters().put("output", "json");
    suggestionQuery.execute(new TaskAdapter<>(new TaskListener<Object>() {

        @Override
        public void taskExecuted(Task<Object> task) {
            if (task == suggestionQuery) {
                List<?> suggestions = null;
                Object result = JSON.get(task.getResult(), "ResultSet.Result");
                if (result instanceof List<?>) {
                    suggestions = (List<?>) result;
                }
                if (suggestions == null || suggestions.getLength() == 0) {
                    suggestionPopup.close();
                } else {
                    suggestionPopup.setSuggestionData(suggestions);
                    suggestionPopup.open(textInput, new SuggestionPopupCloseListener() {

                        @Override
                        public void suggestionPopupClosed(SuggestionPopup suggestionPopupArgument) {
                            if (suggestionPopupArgument.getResult()) {
                                String textLocal;
                                try {
                                    textLocal = URLEncoder.encode(textInput.getText(), "UTF-8");
                                } catch (UnsupportedEncodingException exception) {
                                    throw new RuntimeException(exception);
                                }
                                String location = "http://search.yahoo.com/search?p=" + textLocal;
                                try {
                                    Desktop.getDesktop().browse(new URI(location));
                                } catch (IOException exception) {
                                    System.err.println(exception);
                                } catch (URISyntaxException exception) {
                                    System.err.println(exception);
                                }
                            }
                        }
                    });
                }
                activityIndicator.setActive(false);
                suggestionQuery = null;
            }
        }

        @Override
        public void executeFailed(Task<Object> task) {
            if (task == suggestionQuery) {
                System.err.println(task.getFault());
                activityIndicator.setActive(false);
                suggestionQuery = null;
            }
        }
    }));
    activityIndicator.setActive(true);
}
Also used : Task(org.apache.pivot.util.concurrent.Task) SuggestionPopupCloseListener(org.apache.pivot.wtk.SuggestionPopupCloseListener) SuggestionPopup(org.apache.pivot.wtk.SuggestionPopup) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) GetQuery(org.apache.pivot.web.GetQuery) TaskListener(org.apache.pivot.util.concurrent.TaskListener) List(org.apache.pivot.collections.List)

Example 10 with Task

use of org.apache.pivot.util.concurrent.Task in project pivot by apache.

the class SearchDemo method updateArtwork.

/**
 * Updates the artwork to reflect the current selection.
 */
public void updateArtwork() {
    @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) resultsTableView.getSelectedRow();
    URL artworkURL = null;
    if (result != null) {
        try {
            artworkURL = new URL((String) result.get("artworkUrl100"));
        } catch (MalformedURLException exception) {
        // ignore exception
        }
    }
    if (artworkURL == null) {
        artworkImageView.setImage((Image) null);
    } else {
        Image.load(artworkURL, new TaskAdapter<>(new TaskListener<Image>() {

            @Override
            public void taskExecuted(Task<Image> task) {
                artworkImageView.setImage(task.getResult());
            }

            @Override
            public void executeFailed(Task<Image> task) {
                artworkImageView.setImage((Image) null);
            }
        }));
    }
    previewButton.setEnabled(result != null);
}
Also used : MalformedURLException(java.net.MalformedURLException) Task(org.apache.pivot.util.concurrent.Task) TaskListener(org.apache.pivot.util.concurrent.TaskListener) Map(org.apache.pivot.collections.Map) URL(java.net.URL)

Aggregations

Task (org.apache.pivot.util.concurrent.Task)14 TaskListener (org.apache.pivot.util.concurrent.TaskListener)13 GetQuery (org.apache.pivot.web.GetQuery)6 List (org.apache.pivot.collections.List)5 MalformedURLException (java.net.MalformedURLException)3 URISyntaxException (java.net.URISyntaxException)3 URL (java.net.URL)3 BXMLSerializer (org.apache.pivot.beans.BXMLSerializer)3 IOException (java.io.IOException)2 Date (java.util.Date)2 ArrayList (org.apache.pivot.collections.ArrayList)2 Map (org.apache.pivot.collections.Map)2 Test (org.junit.Test)2 Desktop (java.awt.Desktop)1 File (java.io.File)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 DateFormat (java.text.DateFormat)1 Random (java.util.Random)1 FileObject (org.apache.commons.vfs2.FileObject)1