View Javadoc

1   /*
2    * Copyright (c) 2007 Regents of the University of California (Regents). Created
3    * by TELS, Graduate School of Education, University of California at Berkeley.
4    *
5    * This software is distributed under the GNU Lesser General Public License, v2.
6    *
7    * Permission is hereby granted, without written agreement and without license
8    * or royalty fees, to use, copy, modify, and distribute this software and its
9    * documentation for any purpose, provided that the above copyright notice and
10   * the following two paragraphs appear in all copies of this software.
11   *
12   * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
13   * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
14   * PURPOSE. THE SOFTWAREAND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
15   * HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
16   * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17   *
18   * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
19   * SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
20   * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
21   * REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22   */
23  package org.telscenter.pas.steps.quickEditors.html;
24  
25  import java.awt.BorderLayout;
26  import java.awt.Dimension;
27  import java.awt.FlowLayout;
28  import java.awt.event.ActionEvent;
29  import java.awt.event.ActionListener;
30  import java.awt.event.FocusEvent;
31  import java.awt.event.FocusListener;
32  import java.io.BufferedReader;
33  import java.io.File;
34  import java.io.FileInputStream;
35  import java.io.IOException;
36  import java.io.InputStream;
37  import java.io.InputStreamReader;
38  import java.net.URL;
39  import java.net.URLConnection;
40  import java.util.jar.JarOutputStream;
41  
42  import javax.swing.Action;
43  import javax.swing.JButton;
44  import javax.swing.JComponent;
45  import javax.swing.JFileChooser;
46  import javax.swing.JFrame;
47  import javax.swing.JLabel;
48  import javax.swing.JPanel;
49  import javax.swing.JTextArea;
50  import javax.swing.JTextField;
51  import javax.swing.undo.UndoManager;
52  
53  import net.sf.sail.core.beans.Pod;
54  import net.sf.sail.core.util.BinaryUtils;
55  import net.sf.sail.core.util.PodUtils;
56  
57  import org.telscenter.pas.common.ui.panel.TextEditorPanel;
58  import org.telscenter.pas.steps.BrowseWebUI;
59  import org.telscenter.pas.steps.DisplayPage;
60  import org.telscenter.pas.steps.BrowseWeb.PopupPreviewAction;
61  
62  /***
63   * @author aperritano
64   *
65   */
66  public class EditPageQuickEditorUI extends HtmlQuickEditorUI {
67  
68  	public static final String VALUE_LOCAL_FILE_URL = "local";
69  	private static final int TEXT_BOX_LEN = 25;
70  	
71  	private JTextArea htmlArea;
72  
73  	private JButton browseButton;
74  	private JTextField localUrlText;
75  	private JButton previewButton;
76  	private UndoManager undoManager;
77  	
78  	
79  	public EditPageQuickEditorUI(UndoManager undoManager) {
80  		this.undoManager = undoManager;
81  	}
82  	
83  //	/* (non-Javadoc)
84  //	 * @see org.telscenter.pas.steps.quickEditors.html.HtmlQuickEditorUI#createUI()
85  //	 */
86  //	@Override
87  	protected void createUI() {
88  		this.browseWebBean.setIsAuthoringHTMLPage(true);
89  		
90  		this.setOpaque(false);
91  		this.setLayout(new BorderLayout(0,0));
92  		JPanel titlePane = new JPanel(new FlowLayout(FlowLayout.LEFT));
93  		titlePane.setOpaque(false);
94  		JLabel label = new JLabel("HTML Source code:");
95  		label.setOpaque(false);
96  		
97  		titlePane.add(label);
98  		
99  		
100 		this.add(titlePane,BorderLayout.NORTH);
101 		
102 		
103 		htmlArea = new JTextArea();
104 		
105 		if( this.undoManager != null)
106 			htmlArea.getDocument().addUndoableEditListener(this.undoManager);
107 		
108 		//browseWebBean.beforeSessionStart();
109 		browseWebBean.getWebBrowserComponent();
110 		
111 		if( browseWebBean.getBrowser() != null && browseWebBean.getBrowser().getContent() != null ) {
112 			
113 			URL url = browseWebBean.getBrowser().getUrl();
114 
115 			try {
116 				if( url != null) {
117 				//retreives the text from the url and places it into the text box in the UI
118 				htmlArea.setText(readTextFromURL(url.toString()));
119 				} else {
120 					htmlArea.setText(browseWebBean.getContent());
121 				}
122 			} catch (IOException e) {
123 				// TODO Auto-generated catch block
124 				e.printStackTrace();
125 			}
126 			//htmlArea.setText();
127 		}
128 		
129 		
130 		TextEditorPanel ppanel = new TextEditorPanel(htmlArea,new Dimension(400, 125));
131 		
132 		htmlArea.setBackground(this.getBackground());
133 		JButton jb = ppanel.getEditButton();
134 //		getComponent
135 		 if( jb != null ) {
136 			 
137 			 jb.addActionListener(new ActionListener() {
138 
139 				public void actionPerformed(ActionEvent e) {
140 					
141 					
142 					JButton source = (JButton) e.getSource();
143 					String clientProperty = (String) source.getClientProperty(TextEditorPanel.MODE);
144 
145 					if (clientProperty.equals(TextEditorPanel.SAVE_MODE)) {
146 						
147 						
148 						
149 						final String text = htmlArea.getText();
150 						if( text == null) { 
151 							return;
152 						}
153 									if( text != null ) {
154 										htmlArea.setText(text);
155 										browseWebBean.setContent(text);
156 										//browseWebBean.setUrl(null);
157 									}// if
158 					}
159 				}
160 			});
161 				 
162 		 }// if
163 		
164 		this.add(createPreviewButton(), BorderLayout.EAST);
165 		this.add(ppanel,BorderLayout.CENTER);
166 		
167 		//this.setBackground(Color.RED);
168 
169 	}
170 	
171 	private JPanel createPreviewButton() {
172 		JPanel previewButtonPanel = new JPanel(new BorderLayout(0,0));
173 		
174 		//previewButtonPanel.setBackground(Color.BLUE);
175 		previewButtonPanel.setOpaque(false);
176 		BrowseWebUI ui = (BrowseWebUI) browseWebBean.getComponent();
177 		PopupPreviewAction previewAction = (PopupPreviewAction) browseWebBean.getPreviewAction(false);
178 		
179 		previewAction.putValue(Action.NAME, "Preview Step");
180 //		previewAction.putValue(Action.SMALL_ICON, new ImageIcon(
181 //				Curnit.class
182 //						.getResource("icons/preview16.png")));
183 		 previewButton = new JButton(previewAction);
184 		 previewButton.setOpaque(false);
185 		 //previewButton.setBounds(100, 100, 200, 100);
186 		//previewButton.setEnabled(false);
187 		previewButtonPanel.add(previewButton,BorderLayout.NORTH);
188 		return previewButtonPanel;
189 	}
190 	
191 	private JComponent createLocalLabelPanel(JPanel formPanel) {
192 		JLabel local = new JLabel("File:");
193 		return local;
194 	}
195 
196 	private JComponent createLocalTextPanel(JPanel formPanel) {
197 		localUrlText = new JTextField(TEXT_BOX_LEN);
198 		
199 		
200 		if( browseWebBean.getUrl() != null ) {
201 			
202 			
203 			String url = browseWebBean.getUrl().toString();
204 			
205 			localUrlText.setText(url);
206 //			if( url.contains("http://"));
207 //				localUrlText.setText("");
208 		}// if
209 		
210 		localUrlText.setEditable(false);
211 		localUrlText.addFocusListener(new FocusListener() {
212 
213 			public void focusGained(FocusEvent e) {
214 				//System.out.println(".createLocalTextPanel()");
215 			}
216 
217 			public void focusLost(FocusEvent e) {
218 				//System.out.println(".focusLost()");
219 				
220 			}});
221 		
222 		localUrlText.addActionListener(new ActionListener() {
223 
224 			public void actionPerformed(ActionEvent e) {
225 				previewButton.setEnabled(true);
226 			}});
227 		return localUrlText;
228 	}
229 	
230 	/***
231 	 * @param object
232 	 * @return
233 	 */
234 	private JButton createLocalButtonPanel(JPanel formPanel) {
235 		browseButton = new JButton("Select File");
236 		//browseButton.setIcon(new ImageIcon(getClass().getResource("icons/importHTML16.png")));
237 		browseButton.addActionListener(new ActionListener() {
238 
239 			public void actionPerformed(ActionEvent e) {
240 				browseForBean();
241 			}
242 		});
243 		browseButton.setToolTipText("Import a HTML from a local file.");
244 		//CommonUI.makeEnhancedButton(browseButton);
245 		return browseButton;
246 	}
247 
248 	/***
249 	 * 
250 	 */
251 	protected void browseForBean() {
252 		final File selectedFile = showChooserAndReturnFile();
253 
254 		if( selectedFile == null )
255 			return;
256 		
257 		Pod browseWebStep = PodUtils.resolvePod(browseWebBean);
258 		URL resURL = null;
259 		try {
260 			// need to chech if the archive already exists
261 			// and get the existing one.
262 			JarOutputStream podResources = BinaryUtils
263 					.newPodArchiveFor(browseWebStep);
264 
265 			resURL  = BinaryUtils.addToArchive(browseWebStep,
266 					podResources, selectedFile.getName(),
267 					new FileInputStream(selectedFile));
268 			podResources.close();
269 			// ((AbstractUrlStep) bean).setUrl(resURL);
270 
271 			localUrlText.setText(selectedFile.getAbsolutePath());
272 		} catch (Exception exc) {
273 			exc.printStackTrace();
274 		}// try
275 
276 		
277 		browseWebBean.setUrl(resURL); //commented by Geoff
278 		localUrlText.setText(resURL.toString());
279 	}
280 
281 	/***
282 	 * @return
283 	 */
284 	protected File showChooserAndReturnFile() {
285 		JFileChooser chooser = new JFileChooser();
286 		chooser.setFileFilter(new HtmlFilter());
287 		int returnVal = chooser.showOpenDialog(browseButton);
288 		if (returnVal != JFileChooser.APPROVE_OPTION) {
289 			return null;
290 		}
291 
292 		final File selectedFile = chooser.getSelectedFile();
293 		return selectedFile;
294 	}
295 	
296 	class HtmlFilter extends javax.swing.filechooser.FileFilter {
297 		public boolean accept(File file) {
298 			String filename = file.getName();
299 
300 			if (file.isDirectory())
301 				return true;
302 			if (filename.endsWith(".html"))
303 				return true;
304 			if (filename.endsWith(".htm"))
305 				return true;
306 
307 			return false;
308 		}
309 
310 		public String getDescription() {
311 			return "*.html,*.htm";
312 		}
313 	}
314 
315 	   /***
316 	    * This subroutine attempts to copy text from the specified URL onto the screen.  
317 	    * Any error must be handled by the caller of this subroutine.
318 	    * @param urlString contains the URL in text form
319 	    */
320 	   static String readTextFromURL( String urlString ) throws IOException {
321 
322 	      /* Open a connection to the URL, and get an input stream
323 	           for reading data from the URL. */
324 
325 	      URL url = new URL(urlString);
326 	      URLConnection connection = url.openConnection();
327 	      InputStream urlData = connection.getInputStream();
328 	      StringBuffer stringBuf = new StringBuffer();
329 
330 	      /* Check that the content is some type of text.  Note: If 
331 	         getContentType() method were called before getting  the input 
332 	         stream, it is possible for contentType to be null only because 
333 	         no connection can be made.  The getInputStream() method will 
334 	         throw an error if no connection can be made. */
335 
336 	      String contentType = connection.getContentType();
337 	      if (contentType == null || contentType.startsWith("text") == false)
338 	         throw new IOException("URL does not seem to refer to a text file.");
339 
340 	      /* Copy lines of text from the input stream to the screen, until
341 	           end-of-file is encountered  (or an error occurs). */
342 	      
343 	      BufferedReader in;  // For reading from the connection's input stream.
344 	      in = new BufferedReader( new InputStreamReader(urlData) );
345 
346 	      while (true) {
347 	         String line = in.readLine();
348 	         if (line == null) {
349 	            break;
350 	         }
351 	         stringBuf.append(line);
352 	      }
353 	      
354 	      return stringBuf.toString();
355 	   }
356 
357 	   public static void main(String args[]) {
358 		   DisplayPage dp = new DisplayPage();
359 		   dp.setContent("<html><p>hello</p></html>");
360 //		   try {
361 //			   dp.setUrl(new URL("http://www.google.com"));
362 //		   } catch(MalformedURLException mURLE) {
363 //			   System.out.println("Bad URL");
364 //		   }
365 		   
366 		   JFrame frame = new JFrame("FrameDemo");
367 		 //System.out.println("content: " + dp.getContent());
368 		 //2. Optional: What happens when the frame closes?
369 		 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
370 
371 		 //create HTMLEditor here, then do htmleditor.setbean(dp)
372 		 //pass as emptylabel
373 		 //set size of frame
374 		 
375 		 EditPageQuickEditorUI pageEditor = new EditPageQuickEditorUI(null);
376 		 //OutsideLinkQuickEditorUI pageEditor = new OutsideLinkQuickEditorUI();
377 		 pageEditor.setBean(dp);
378 		 frame.setSize(500, 500);
379 		 //3. Create components and put them in the frame.
380 		 //...create emptyLabel...
381 		 frame.getContentPane().add(pageEditor, BorderLayout.CENTER);
382 
383 		 //4. Size the frame.
384 		 frame.pack();
385 
386 		 //5. Show it.
387 		 frame.setVisible(true);
388 	   }
389 
390 }