1 /*
2  * Copyright 2008 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  */
16 package com.google.gwt.sample.showcase.client.content.other;
17 
18 import com.google.gwt.core.client.GWT;
19 import com.google.gwt.core.client.RunAsyncCallback;
20 import com.google.gwt.core.client.Scheduler;
21 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
22 import com.google.gwt.event.dom.client.ChangeEvent;
23 import com.google.gwt.event.dom.client.ChangeHandler;
24 import com.google.gwt.event.dom.client.ClickEvent;
25 import com.google.gwt.event.dom.client.ClickHandler;
26 import com.google.gwt.i18n.client.Constants;
27 import com.google.gwt.sample.showcase.client.ContentWidget;
28 import com.google.gwt.sample.showcase.client.ShowcaseAnnotations.ShowcaseData;
29 import com.google.gwt.sample.showcase.client.ShowcaseAnnotations.ShowcaseSource;
30 import com.google.gwt.user.client.Cookies;
31 import com.google.gwt.user.client.Window;
32 import com.google.gwt.user.client.rpc.AsyncCallback;
33 import com.google.gwt.user.client.ui.Button;
34 import com.google.gwt.user.client.ui.Grid;
35 import com.google.gwt.user.client.ui.ListBox;
36 import com.google.gwt.user.client.ui.TextBox;
37 import com.google.gwt.user.client.ui.Widget;
38 
39 import java.util.Collection;
40 import java.util.Date;
41 
42 /**
43  * Example file.
44  */
45 public class CwCookies extends ContentWidget {
46   /**
47    * The constants used in this Content Widget.
48    */
49   @ShowcaseSource
50   public static interface CwConstants extends Constants {
cwCookiesDeleteCookie()51     String cwCookiesDeleteCookie();
52 
cwCookiesDescription()53     String cwCookiesDescription();
54 
cwCookiesExistingLabel()55     String cwCookiesExistingLabel();
56 
cwCookiesInvalidCookie()57     String cwCookiesInvalidCookie();
58 
cwCookiesName()59     String cwCookiesName();
60 
cwCookiesNameLabel()61     String cwCookiesNameLabel();
62 
cwCookiesSetCookie()63     String cwCookiesSetCookie();
64 
cwCookiesValueLabel()65     String cwCookiesValueLabel();
66   }
67 
68   /**
69    * The timeout before a cookie expires, in milliseconds. Current one day.
70    */
71   @ShowcaseData
72   private static final int COOKIE_TIMEOUT = 1000 * 60 * 60 * 24;
73 
74   /**
75    * An instance of the constants.
76    */
77   @ShowcaseData
78   private final CwConstants constants;
79 
80   /**
81    * A {@link TextBox} that holds the name of the cookie.
82    */
83   @ShowcaseData
84   private TextBox cookieNameBox = null;
85 
86   /**
87    * A {@link TextBox} that holds the value of the cookie.
88    */
89   @ShowcaseData
90   private TextBox cookieValueBox = null;
91 
92   /**
93    * The {@link ListBox} containing existing cookies.
94    */
95   @ShowcaseData
96   private ListBox existingCookiesBox = null;
97 
98   /**
99    * Constructor.
100    *
101    * @param constants the constants
102    */
CwCookies(CwConstants constants)103   public CwCookies(CwConstants constants) {
104     super(constants.cwCookiesName(), constants.cwCookiesDescription(), false);
105     this.constants = constants;
106   }
107 
108   /**
109    * Initialize this example.
110    */
111   @ShowcaseSource
112   @Override
onInitialize()113   public Widget onInitialize() {
114     // Create the panel used to layout the content
115     Grid mainLayout = new Grid(3, 3);
116 
117     // Display the existing cookies
118     existingCookiesBox = new ListBox();
119     Button deleteCookieButton = new Button(constants.cwCookiesDeleteCookie());
120     deleteCookieButton.addStyleName("sc-FixedWidthButton");
121     mainLayout.setHTML(
122         0, 0, "<b>" + constants.cwCookiesExistingLabel() + "</b>");
123     mainLayout.setWidget(0, 1, existingCookiesBox);
124     mainLayout.setWidget(0, 2, deleteCookieButton);
125 
126     // Display the name of the cookie
127     cookieNameBox = new TextBox();
128     mainLayout.setHTML(1, 0, "<b>" + constants.cwCookiesNameLabel() + "</b>");
129     mainLayout.setWidget(1, 1, cookieNameBox);
130 
131     // Display the name of the cookie
132     cookieValueBox = new TextBox();
133     Button setCookieButton = new Button(constants.cwCookiesSetCookie());
134     setCookieButton.addStyleName("sc-FixedWidthButton");
135     mainLayout.setHTML(2, 0, "<b>" + constants.cwCookiesValueLabel() + "</b>");
136     mainLayout.setWidget(2, 1, cookieValueBox);
137     mainLayout.setWidget(2, 2, setCookieButton);
138 
139     // Add a handler to set the cookie value
140     setCookieButton.addClickHandler(new ClickHandler() {
141       public void onClick(ClickEvent event) {
142         String name = cookieNameBox.getText();
143         String value = cookieValueBox.getText();
144         Date expires = new Date((new Date()).getTime() + COOKIE_TIMEOUT);
145 
146         // Verify the name is valid
147         if (name.length() < 1) {
148           Window.alert(constants.cwCookiesInvalidCookie());
149           return;
150         }
151 
152         // Set the cookie value
153         Cookies.setCookie(name, value, expires);
154         refreshExistingCookies(name);
155       }
156     });
157 
158     // Add a handler to select an existing cookie
159     existingCookiesBox.addChangeHandler(new ChangeHandler() {
160       public void onChange(ChangeEvent event) {
161         updateExstingCookie();
162       }
163     });
164 
165     // Add a handler to delete an existing cookie
166     deleteCookieButton.addClickHandler(new ClickHandler() {
167       public void onClick(ClickEvent event) {
168         int selectedIndex = existingCookiesBox.getSelectedIndex();
169         if (selectedIndex > -1
170             && selectedIndex < existingCookiesBox.getItemCount()) {
171           String cookieName = existingCookiesBox.getValue(selectedIndex);
172           Cookies.removeCookie(cookieName);
173           existingCookiesBox.removeItem(selectedIndex);
174           updateExstingCookie();
175         }
176       }
177     });
178 
179     // Return the main layout
180     refreshExistingCookies(null);
181     return mainLayout;
182   }
183 
184   @Override
asyncOnInitialize(final AsyncCallback<Widget> callback)185   protected void asyncOnInitialize(final AsyncCallback<Widget> callback) {
186     GWT.runAsync(CwCookies.class, new RunAsyncCallback() {
187 
188       public void onFailure(Throwable caught) {
189         callback.onFailure(caught);
190       }
191 
192       public void onSuccess() {
193         callback.onSuccess(onInitialize());
194       }
195     });
196   }
197 
198   /**
199    * Refresh the list of existing cookies.
200    *
201    * @param selectedCookie the cookie to select by default
202    */
203   @ShowcaseSource
refreshExistingCookies(String selectedCookie)204   private void refreshExistingCookies(String selectedCookie) {
205     // Clear the existing cookies
206     existingCookiesBox.clear();
207 
208     // Add the cookies
209     int selectedIndex = 0;
210     Collection<String> cookies = Cookies.getCookieNames();
211     for (String cookie : cookies) {
212       existingCookiesBox.addItem(cookie);
213       if (cookie.equals(selectedCookie)) {
214         selectedIndex = existingCookiesBox.getItemCount() - 1;
215       }
216     }
217 
218     // Select the index of the selectedCookie. Use a ScheduledCommand to give
219     // the options time to register in Opera.
220     final int selectedIndexFinal = selectedIndex;
221     Scheduler.get().scheduleDeferred(new ScheduledCommand() {
222       public void execute() {
223         // Select the default cookie
224         if (selectedIndexFinal < existingCookiesBox.getItemCount()) {
225           existingCookiesBox.setSelectedIndex(selectedIndexFinal);
226         }
227 
228         // Display the selected cookie value
229         updateExstingCookie();
230       }
231     });
232   }
233 
234   /**
235    * Retrieve the value of the existing cookie and put it into to value label.
236    */
237   @ShowcaseSource
updateExstingCookie()238   private void updateExstingCookie() {
239     // Cannot update if there are no items
240     if (existingCookiesBox.getItemCount() < 1) {
241       cookieNameBox.setText("");
242       cookieValueBox.setText("");
243       return;
244     }
245 
246     int selectedIndex = existingCookiesBox.getSelectedIndex();
247     String cookieName = existingCookiesBox.getValue(selectedIndex);
248     String cookieValue = Cookies.getCookie(cookieName);
249     cookieNameBox.setText(cookieName);
250     cookieValueBox.setText(cookieValue);
251   }
252 }
253