Example usage for com.google.gwt.user.client Random nextInt

List of usage examples for com.google.gwt.user.client Random nextInt

Introduction

In this page you can find the example usage for com.google.gwt.user.client Random nextInt.

Prototype

public static native int nextInt(int upperBound) ;

Source Link

Document

Returns a random int between 0 (inclusive) and upperBound (exclusive) with roughly equal probability of returning any particular int in this range.

Usage

From source file:org.gwtbootstrap3.demo.client.application.extras.FullCalendarView.java

License:Apache License

@SuppressWarnings("deprecation")
protected void addEvents(FullCalendar fc) {
    for (int i = 0; i < 15; i++) {
        Event calEvent = new Event("" + i, "This is Event: " + i);
        int day = Random.nextInt(10);
        Date start = new Date();
        CalendarUtil.addDaysToDate(start, -1 * day);
        calEvent.setStart(start);//from  w w w  .  j a va  2s  . co m
        if (day % 3 == 0) {
            calEvent.setAllDay(true);
        } else {
            Date d = new Date(start.getTime());
            d.setHours(d.getHours() + 1);
            calEvent.setEnd(d);
        }
        fc.addEvent(calEvent);
    }
}

From source file:org.gwtbootstrap3.demo.client.application.extras.FullCalendarView.java

License:Apache License

@SuppressWarnings("deprecation")
protected void addBackgroundEvents(FullCalendar fc) {
    Date start = new Date();
    start.setMinutes(0);/*from ww  w  .  j av  a2  s .  c o m*/
    start.setHours(9);
    CalendarUtil.addDaysToDate(start, -start.getDay() - 1);
    for (int i = 1; i < 28; i++) {
        CalendarUtil.addDaysToDate(start, 1);
        if (i == 3) {
            Event lunch = new Event("" + i, "Business lunch");
            lunch.setStart(new Date(start.getTime() + 1000 * 60 * 60 * 4));
            lunch.setConstraint("businessHours");
            fc.addEvent(lunch);
        }
        if (i == 11 || i == 13) {
            Event available = new Event("availableForMeeting", "");
            available.setStart(start);
            available.setEnd(new Date(start.getTime() + 1000 * 60 * 60 * 8));
            available.setRendering("background");
            available.setBackgroundColor("#8FDF82");
            fc.addEvent(available);
            if (i == 13) {
                Event meeting = new Event("" + i, "Meeting");
                meeting.setStart(new Date(start.getTime() + Random.nextInt(7) * 1000 * 60 * 60));
                meeting.setEnd(new Date(start.getTime() + 1000 * 60 * 60));
                meeting.setBackgroundColor("#257e4a");
                meeting.setConstraint("availableForMeeting");
                fc.addEvent(meeting);
            }
        } else if (i == 6 || i == 7 || i > 23) {
            Event blocked = new Event("" + i, "");
            blocked.setStart(start);
            blocked.setAllDay(true);
            blocked.setOverlap(false);
            blocked.setRendering("background");
            blocked.setBackgroundColor("#ff9f89");
            fc.addEvent(blocked);
        } else if (i == 10) {
            Event conference = new Event("" + i, "Conference");
            conference.setStart(start);
            conference.setEnd(new Date(start.getTime() + 1000 * 60 * 60 * 48));
            conference.setAllDay(true);
            fc.addEvent(conference);
        }
    }
}

From source file:org.gwtlib.samples.table.client.ui.PagingTableEntryPoint.java

License:Apache License

private PagingTable createTable() {
    // Set up the columns we want to be displayed
    final CheckBox checkAll = new CheckBox();
    final Column[] columns = { new Column(0, false, checkAll, "20", new CheckBoxRenderer()),
            new Column(1, true, "Text (StringRenderer)", "10%"),
            new Column(2, false, "Date (StringRenderer)", "10%"),
            new Column(3, false, "Number (StringRenderer)", "10%"),
            new Column(4, true, "Date (DateTimeRenderer)", "10%",
                    new DateTimeRenderer(DateTimeFormat.getFormat("yyyy-MM-dd"))),
            new Column(5, true, "Number (NumberRenderer)", "10%",
                    new NumberRenderer(NumberFormat.getDecimalFormat())),
            new Column(6, false, "(ListBoxRenderer)", "10%",
                    new ListBoxRenderer(new String[] { "One", "Two", "Three" }, "Select an item")),
            new Column(7, false, "(ButtonRenderer)", "10%", new ButtonRenderer("Click here")),
            new Column(8, false, "(TextBoxRenderer)", "10%", new TextBoxRenderer(50, 5, "Enter your message")),
            new Column(9, false, "(HyperlinkRenderer)", "10%", new HyperlinkRenderer("A Hyperlink")),
            new Column(10, false, "(ImageRenderer)", "10%", new ImageRenderer("An Image")), };
    // Generate some semi-random data for our example
    final Row[] rows = new Row[TOTAL_SIZE];
    for (int i = 0; i < rows.length; ++i) {
        Boolean check = new Boolean(false);
        StringBuffer label = new StringBuffer();
        for (int j = 0; j < 25; ++j)
            label.append((char) ('a' + i));
        Date date = new Date(NOW.getTime() + Random.nextInt(365 * 24 * 3600 * 1000));
        Integer number = new Integer(Random.nextInt(10000));
        rows[i] = new Row(i, new Object[] { check, label.toString(), date, number, date, number, "One",
                number.toString(), number.toString(), "Hyperlink", "img/down.gif" });
    }//from   w  w  w  .  ja  v  a  2s  .c  o  m
    // Now configure the table
    ColumnLayout layout = new ColumnLayout(columns);
    final PagingTable table = new PagingTable(layout,
            new PagingBar(0, TOTAL_SIZE, 10, new int[] { 5, 10, 20, 50, 100 }));
    ContentProvider provider = new ContentProvider() {
        // Simulate retrieval of sample data, in requested sort order
        public void load(int begin, int end, final int sortId, boolean ascending) {
            final int sign = ascending ? 1 : -1;
            Row[] tmp = new Row[rows.length];
            for (int i = 0; i < rows.length; ++i)
                tmp[i] = rows[i];
            switch (sortId) {
            case 1:
                Arrays.sort(tmp, new Comparator<Row>() {
                    public int compare(Row o1, Row o2) {
                        String v1 = (String) o1.getValue(sortId);
                        String v2 = (String) o2.getValue(sortId);
                        return sign * (v1.compareTo(v2));
                    }
                });
                break;
            case 4:
                Arrays.sort(tmp, new Comparator<Row>() {
                    public int compare(Row o1, Row o2) {
                        Date v1 = (Date) o1.getValue(sortId);
                        Date v2 = (Date) o2.getValue(sortId);
                        return sign * (v1.compareTo(v2));
                    }
                });
                break;
            case 5:
                Arrays.sort(tmp, new Comparator<Row>() {
                    public int compare(Row o1, Row o2) {
                        int v1 = ((Integer) o1.getValue(sortId)).intValue();
                        int v2 = ((Integer) o2.getValue(sortId)).intValue();
                        return sign * (v1 < v2 ? -1 : (v1 == v2 ? 0 : 1));
                    }
                });
                break;
            default:
                break;
            }
            Row[] srows = new Row[Math.min(end - begin, tmp.length - begin)];
            for (int i = 0; i < srows.length; ++i)
                srows[i] = tmp[begin + i];
            table.onSuccess(new Rows(srows, begin, sortId, ascending));
        }
    };
    table.setContentProvider(provider);
    table.addTableListener(new TableListenerAdapter() {
        public void onCellClicked(SourcesTableEvents sender, Row row, Column column) {
            for (int i = 0; i < columns.length; ++i)
                columns[i].setState(Column.State.NONE);
            column.setState(Column.State.SELECT);
        }

        public void onRowClicked(SourcesTableEvents sender, Row row) {
            GWT.log("Row clicked (id " + row.getId() + ")", null);
            for (int i = 0; i < rows.length; ++i)
                rows[i].setState(Row.State.NONE);
            row.setState(Row.State.SELECT);
            table.refreshRowState();
        }

        public void onClick(SourcesTableEvents sender, Row row, Column column, Widget widget) {
            GWT.log("Renderer widget clicked", null);
            if (widget instanceof CheckBox) {
                row.setValue(0, new Boolean(((CheckBox) widget).getValue()));
            } else if (widget instanceof Button) {
                Window.alert(((Button) widget).getHTML());
            } else if (widget instanceof Hyperlink) {
                Window.alert(((Hyperlink) widget).getHTML());
            } else if (widget instanceof Image) {
                Window.alert(((Image) widget).getUrl());
            }
        }

        public void onChange(SourcesTableEvents sender, Row row, Column column, Widget widget) {
            GWT.log("Renderer widget changed", null);
            if (widget instanceof ListBox) {
                ListBox listBox = (ListBox) widget;
                row.setValue(6, listBox.getValue(listBox.getSelectedIndex()));
            } else if (widget instanceof TextBox) {
                row.setValue(8, ((TextBox) widget).getText());
            }
        }
    });
    checkAll.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
            for (int i = 0; i < rows.length; ++i)
                rows[i].setValue(0, new Boolean(checkAll.getValue()));
            table.update();
        }
    });
    table.update();
    return table;
}

From source file:org.gwtopenmaps.demo.openlayers.client.examples.cluster.AnimatedClusterWithPopup.java

License:Apache License

@Override
public void buildPanel() {
    OpenLayers.setProxyHost("olproxy?targetURL=");

    // create some MapOptions
    MapOptions defaultMapOptions = new MapOptions();
    defaultMapOptions.setDisplayProjection(new Projection("EPSG:4326")); // causes
                                                                         // the
                                                                         // mouse
                                                                         // popup
                                                                         // to
                                                                         // display
                                                                         // coordinates
                                                                         // in
                                                                         // this
                                                                         // format
    defaultMapOptions.setNumZoomLevels(16);

    // Create a MapWidget
    MapWidget mapWidget = new MapWidget("500px", "500px", defaultMapOptions);
    // Create a WMS layer as base layer
    WMSParams wmsParams = new WMSParams();
    wmsParams.setFormat("image/png");
    wmsParams.setLayers("basic");
    wmsParams.setStyles("");

    WMSOptions wmsLayerParams = new WMSOptions();
    wmsLayerParams.setUntiled();//from   w  ww . j  av a  2s  .  c o  m
    wmsLayerParams.setTransitionEffect(TransitionEffect.RESIZE);

    String wmsUrl = "http://vmap0.tiles.osgeo.org/wms/vmap0";

    WMS wmsLayer = new WMS("Basic WMS", wmsUrl, wmsParams, wmsLayerParams);

    // Add the WMS to the map
    final Map map = mapWidget.getMap();
    map.addLayer(wmsLayer);

    // create a semi-random grid of features to be clustered
    int dx = 3;
    int dy = 3;
    final List<Point> points = new ArrayList<Point>();

    for (int x = -45; x <= 45; x += dx) {
        for (double y = -22.5; y <= 22.5; y += dy) {
            double px = (x + (2 * dx * (Math.random() - 0.5)));
            double py = (y + (2 * dy * (Math.random() - 0.5)));

            Point point = new Point(px, py);
            points.add(point);
        }
    }

    Rule[] rules = new Rule[3];

    rules[0] = new Rule();
    ComparisonFilter filter0 = new ComparisonFilter();
    filter0.setType(Types.LESS_THAN);
    filter0.setProperty("count");
    filter0.setNumberValue(5);

    SymbolizerPoint symbolizer0 = new SymbolizerPoint();
    symbolizer0.setFillColor("green");
    symbolizer0.setFillOpacity(0.9);
    symbolizer0.setStrokeColor("green");
    symbolizer0.setStrokeOpacity(0.5);
    symbolizer0.setStrokeWidth(12);
    symbolizer0.setPointRadius(10);
    rules[0].setFilter(filter0);
    rules[0].setSymbolizer(symbolizer0);

    rules[1] = new Rule();
    ComparisonFilter filter1 = new ComparisonFilter();
    filter1.setType(Types.BETWEEN);
    filter1.setProperty("count");
    filter1.setNumberLowerBoundary(5);
    filter1.setNumberUpperBoundary(20);
    SymbolizerPoint symbolizer1 = new SymbolizerPoint();
    symbolizer1.setFillColor("orange");
    symbolizer1.setFillOpacity(0.9);
    symbolizer1.setStrokeColor("orange");
    symbolizer1.setStrokeOpacity(0.5);
    symbolizer1.setStrokeWidth(12);
    symbolizer1.setPointRadius(10);
    rules[1].setFilter(filter1);
    rules[1].setSymbolizer(symbolizer1);

    rules[2] = new Rule();
    ComparisonFilter filter2 = new ComparisonFilter();
    filter2.setType(Types.GREATER_THAN);
    filter2.setProperty("count");
    filter2.setNumberValue(20);
    SymbolizerPoint symbolizer2 = new SymbolizerPoint();
    symbolizer2.setFillColor("red");
    symbolizer2.setFillOpacity(0.9);
    symbolizer2.setStrokeColor("red");
    symbolizer2.setStrokeOpacity(0.5);
    symbolizer2.setStrokeWidth(12);
    symbolizer2.setPointRadius(10);
    rules[2].setFilter(filter2);
    rules[2].setSymbolizer(symbolizer2);

    Style style = new Style();
    style.setLabel("${count}");
    style.setFontColor("#FFFFFF");
    style.setFontSize("20px");

    final StyleMap styleMap = new StyleMap(style);
    styleMap.addRules(rules, "default");

    AnimatedClusterStrategy animatedClusterStrategy = new AnimatedClusterStrategy(
            new AnimatedClusterStrategyOptions());
    VectorOptions vectorOptions = new VectorOptions();
    vectorOptions.setStrategies(new Strategy[] { animatedClusterStrategy });
    vectorOptions.setRenderers(new String[] { "Canvas", "SVG" });
    Vector vectorLayer = new Vector("Clusters", vectorOptions);
    animatedClusterStrategy.setDistance(20);
    animatedClusterStrategy.setThreshold(10);

    VectorFeature[] features = new VectorFeature[points.size()];
    for (int i = 0; i < points.size(); i++) {
        features[i] = new VectorFeature(points.get(i));
        Attributes attributes = new Attributes();
        attributes.setAttribute("examplenumber", Random.nextInt(10));
        features[i].setAttributes(attributes);
    }

    animatedClusterStrategy.setFeatures(features);
    for (Point point : points)
        vectorLayer.addFeature(new VectorFeature(point));

    vectorLayer.setStyleMap(styleMap);
    map.addLayer(vectorLayer);

    // Lets add some default controls to the map
    map.addControl(new LayerSwitcher()); // + sign in the upperright corner
                                         // to display the layer switcher
    map.addControl(new OverviewMap()); // + sign in the lowerright to
                                       // display the overviewmap
    map.addControl(new ScaleLine()); // Display the scaleline

    // Center and zoom to a location
    map.setCenter(new LonLat(0, 0), 1);

    // now we want a popup to appear when user clicks
    // First create a select control and make sure it is actived
    SelectFeature selectFeature = new SelectFeature(vectorLayer);
    selectFeature.setAutoActivate(true);
    map.addControl(selectFeature);

    // Secondly add a VectorFeatureSelectedListener to the feature
    vectorLayer.addVectorFeatureSelectedListener(new VectorFeatureSelectedListener() {
        public void onFeatureSelected(FeatureSelectedEvent eventObject) {
            GWT.log("onFeatureSelected");

            // Attach a popup to the point, we use null as size cause we set
            // autoSize to true
            // Note that we use FramedCloud... This extends a normal popup
            // and creates is styled as a baloon
            int count = eventObject.getVectorFeature().getAttributes().getAttributeAsInt("count");

            int totalNumber = 0;
            VectorFeature[] clusters = eventObject.getVectorFeature().getCluster();
            for (int i = 0; i < clusters.length; i++) {
                GWT.log("examplenumber = " + clusters[i].getAttributes().getAttributeAsInt("examplenumber"));
                totalNumber += clusters[i].getAttributes().getAttributeAsInt("examplenumber");
            }

            Popup popup = new FramedCloud("id1", eventObject.getVectorFeature().getCenterLonLat(), null,
                    "<h1>Hello</H1>Here are " + count
                            + " features.<br/>The sum of all examplenumber attributes is " + totalNumber,
                    null, true);
            popup.setPanMapIfOutOfView(true); // this set the popup in a
                                              // strategic way, and pans the
                                              // map if needed.
            popup.setAutoSize(true);
            eventObject.getVectorFeature().setPopup(popup);

            // And attach the popup to the map
            map.addPopup(eventObject.getVectorFeature().getPopup());
        }
    });

    contentPanel.add(new HTML(
            "<p>This example demonstrates the use of the Animated Cluster Strategy, and the use of styles and filters to dynamicly style the features.</p>"));

    contentPanel.add(new InfoPanel(
            "<P>This example makes use of the AnimatedCluster strategy. This strategy is no part of the default OpenLayers library.</P>"
                    + "<P>To make this work you must" + "<UL>"
                    + "<LI>download this AnimatedCluster strategy from <A HREF=\"https://github.com/acanimal/AnimatedCluster/blob/master/AnimatedCluster.js\">github</A></LI>"
                    + "<LI>Add it to your projects war folder and add the needed tag to your html file (for example &lt;script src=\"AnimatedCluster.js\"&gt;&lt;/script&gt;)</LI>"
                    + "</UL></P>"));
    contentPanel.add(mapWidget);

    initWidget(contentPanel);

    mapWidget.getElement().getFirstChildElement().getStyle().setZIndex(0); // force
                                                                           // the
                                                                           // map
                                                                           // to
                                                                           // fall
                                                                           // behind
                                                                           // popups
}

From source file:org.jboss.as.console.client.domain.topology.TopologyPresenter.java

License:Open Source License

private List<HostInfo> generateFakeDomain() {
    String[] hostNames = new String[] { "lightning", "eeak-a-mouse", "dirty-harry" };
    String[] groupNames = new String[] { "staging", "production", "messaging-back-server-test", "uat",
            "messaging", "backoffice", "starlight" };
    String[] profiles = new String[] { "default", "default", "default", "messaging", "web", "full-ha",
            "full-ha" };

    int numHosts = 13;
    final List<HostInfo> hostInfos = new ArrayList<HostInfo>();

    for (int i = 0; i < numHosts; i++) {
        // host info
        String name = hostNames[Random.nextInt(2)] + "-" + i;
        boolean isController = (i < 1);

        HostInfo host = new HostInfo(name, isController);
        host.setServerInstances(new ArrayList<ServerInstance>());

        // server instances
        for (int x = 0; x < (Random.nextInt(5) + 1); x++) {
            int groupIndex = Random.nextInt(groupNames.length - 1);
            ServerInstance serverInstance = beanFactory.serverInstance().as();
            serverInstance.setGroup(groupNames[groupIndex]);
            serverInstance.setRunning((groupIndex % 2 == 0));
            if (serverInstance.isRunning()) {
                if (Random.nextBoolean()) {
                    serverInstance.setFlag(Random.nextBoolean() ? RESTART_REQUIRED : RELOAD_REQUIRED);
                } else {
                    serverInstance.setFlag(null);
                }/*from w  w w.  j  a  va2 s  .  co  m*/
            }
            serverInstance.setName(groupNames[groupIndex] + "-" + x);
            serverInstance.setSocketBindings(Collections.<String, String>emptyMap());
            serverInstance.setInterfaces(Collections.<String, String>emptyMap());

            host.getServerInstances().add(serverInstance);
        }
        hostInfos.add(host);
    }
    return hostInfos;
}

From source file:org.lirazs.gbackbone.client.core.collection.Collection.java

License:Apache License

private JsArray<Integer> getRandomIndexes(int quantity, JsArray<Integer> excludes) {
    int number;/*from   w w w  .j a  v a  2  s.  com*/

    if (excludes.length() == quantity)
        return excludes;

    do {
        number = Random.nextInt(size());
    } while (excludes.contains(number));

    return getRandomIndexes(quantity, excludes.add(number));
}

From source file:org.n52.client.ui.btn.ImageButton.java

License:Open Source License

private void init() {
    setStyleName("n52_sensorweb_client_imagebutton");
    //        int length = this.size + 2 * this.margin;
    //        this.setWidth(length);
    //        this.setHeight(length);

    String loaderId = "loader_" + (LoaderManager.getInstance().getCount() + Random.nextInt(10000));
    this.loader = new LoaderImage(loaderId, "../img/mini_loader_bright.gif", this);

    this.setID(this.id);
    this.setSrc(this.icon);
    this.setShowHover(true);
    this.setShowRollOver(this.showRollOver);
    this.setShowDownIcon(this.showDown);
    this.setShowFocusedAsOver(false);
    this.setCursor(Cursor.POINTER);

    if (View.getView().isShowExtendedTooltip()) {
        this.setTooltip(this.extendedTooltip);
    } else {/*ww  w.  j a va  2 s  .  c  om*/
        this.setTooltip(this.shortToolTip);
    }
}

From source file:org.n52.client.util.ClientUtils.java

License:Open Source License

private static String getNextFormattedRandomNumber() {
    String randomHex = Integer.toHexString(Random.nextInt(256));
    if (randomHex.length() == 1) {
        // ensure two digits
        randomHex = "0" + randomHex;
    }//from w  ww.  j ava 2  s  .co m
    return randomHex;
}

From source file:org.ned.server.nedadminconsole.client.NedStringGenerator.java

License:Open Source License

public String nextString(int length) {
    char[] buf = new char[length];
    for (int idx = 0; idx < buf.length; ++idx)
        buf[idx] = symbols[Random.nextInt(symbols.length)];
    return new String(buf);
}

From source file:org.obiba.opal.web.gwt.app.client.ui.CriterionDropdown.java

License:Open Source License

CriterionDropdown(VariableDto variableDto, @Nonnull String fieldName, @Nullable QueryResultDto termDto) {
    variable = variableDto;/* w  ww  . j  a v  a 2 s.c  om*/
    this.fieldName = fieldName;
    queryResult = termDto;

    groupId = String.valueOf(Random.nextInt(1000000)); //to be used in radio button names, to make they don't clash

    setSize(ButtonSize.SMALL);
    updateCriterionFilter(translations.criterionFiltersMap().get("all"));

    radioControls.addStyleName("controls");

    addRadioButtons(getNoEmptyCount());

    Widget specificControls = getSpecificControls();
    if (specificControls != null) {
        add(specificControls);
    }
}