001: /*
002: * ====================================================================
003: * JAFFA - Java Application Framework For All
004: *
005: * Copyright (C) 2002 JAFFA Development Group
006: *
007: * This library is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU Lesser General Public
009: * License as published by the Free Software Foundation; either
010: * version 2.1 of the License, or (at your option) any later version.
011: *
012: * This library is distributed in the hope that it will be useful,
013: * but WITHOUT ANY WARRANTY; without even the implied warranty of
014: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015: * Lesser General Public License for more details.
016: *
017: * You should have received a copy of the GNU Lesser General Public
018: * License along with this library; if not, write to the Free Software
019: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020: *
021: * Redistribution and use of this software and associated documentation ("Software"),
022: * with or without modification, are permitted provided that the following conditions are met:
023: * 1. Redistributions of source code must retain copyright statements and notices.
024: * Redistributions must also contain a copy of this document.
025: * 2. Redistributions in binary form must reproduce the above copyright notice,
026: * this list of conditions and the following disclaimer in the documentation
027: * and/or other materials provided with the distribution.
028: * 3. The name "JAFFA" must not be used to endorse or promote products derived from
029: * this Software without prior written permission. For written permission,
030: * please contact mail to: jaffagroup@yahoo.com.
031: * 4. Products derived from this Software may not be called "JAFFA" nor may "JAFFA"
032: * appear in their names without prior written permission.
033: * 5. Due credit should be given to the JAFFA Project (http://jaffa.sourceforge.net).
034: *
035: * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
036: * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
037: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
038: * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
039: * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
040: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
041: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
042: * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
043: * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
044: * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
045: * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
046: * SUCH DAMAGE.
047: * ====================================================================
048: */
049:
050: /* Generated by Together */
051:
052: package org.jaffa.presentation.portlet.widgets.controller;
053:
054: import java.util.*;
055: import org.apache.log4j.Logger;
056: import org.jaffa.config.Config;
057: import java.net.URL;
058: import org.jaffa.util.URLHelper;
059: import java.net.MalformedURLException;
060: import java.io.File;
061: import org.jaffa.presentation.portlet.widgets.controller.usergriddomain.UserGridSettings;
062: import java.io.IOException;
063: import org.jaffa.presentation.portlet.widgets.controller.usergriddomain.UserGridColumnSettings;
064: import java.io.FileOutputStream;
065: import java.io.FileNotFoundException;
066: import javax.xml.bind.JAXBContext;
067: import javax.xml.bind.JAXBException;
068: import javax.xml.bind.Unmarshaller;
069: import javax.xml.bind.Marshaller;
070: import javax.xml.bind.Validator;
071: import javax.xml.bind.ValidationException;
072: import org.jaffa.util.XmlHelper;
073:
074: /** manager class file for handling the UserGrid tags
075: */
076: public class UserGridManager {
077: /** Set up Logging for Log4J */
078: private static Logger log = Logger.getLogger(UserGridManager.class);
079:
080: // If no property is specified in the framework.properties file, this is where the system
081: // will look for the roles.xml policy file. It is wise to put an empty policy file at this location!
082: private static final String DEFAULT_SETTINGS_LOCATION = "file:///"
083: + System.getProperty("user.home").replace(
084: File.separatorChar, '/');
085:
086: private static final char URL_CHAR = '/';
087: private static final String URL_STRING = "/";
088:
089: // Hold the unmarshalled object for multiple introspections
090: UserGridSettings m_settings = null;
091:
092: private void loadXML(String userId, String userGridId) {
093: URL settingsUrl = null;
094:
095: //-----------------------------------------------------
096: // Read The Settings XML file, based on User
097: //-----------------------------------------------------
098: try {
099: // Create a URL for the resource file...
100: settingsUrl = URLHelper.newExtendedURL(getFileLocation(
101: "user", userId, userGridId));
102: } catch (MalformedURLException e) {
103: if (log.isDebugEnabled())
104: log.debug("Bad URL for the User Grid Settings- "
105: + getFileLocation("user", userId, userGridId));
106: return;
107: }
108:
109: try {
110: if (log.isDebugEnabled())
111: log
112: .debug("Loading User Settting For UserGrid Widget. File="
113: + settingsUrl.toExternalForm());
114:
115: // create a JAXBContext capable of handling classes generated into the package
116: JAXBContext jc = JAXBContext
117: .newInstance("org.jaffa.presentation.portlet.widgets.controller.usergriddomain");
118:
119: // create an Unmarshaller
120: Unmarshaller u = jc.createUnmarshaller();
121:
122: // enable validation
123: u.setValidating(true);
124:
125: // unmarshal a document into a tree of Java content objects composed of classes from the package.
126: m_settings = (UserGridSettings) u.unmarshal(XmlHelper
127: .stripDoctypeDeclaration(settingsUrl));
128:
129: if (log.isDebugEnabled())
130: log
131: .debug("Loaded User Settting For UserGrid Widget. File="
132: + settingsUrl.toExternalForm());
133: } catch (JAXBException e) {
134: // do not log a warning, since its perfectly acceptable that the file may be missing
135: if (e.getLinkedException() == null
136: || !(e.getLinkedException() instanceof IOException))
137: log.warn("Malformed User Grid Settings Document", e);
138: } catch (IOException e) {
139: // do not log a warning, since its perfectly acceptable that the file may be missing
140: }
141:
142: //-----------------------------------------------------
143: // Read The Settings XML file, based on Default
144: //-----------------------------------------------------
145: if (m_settings == null) {
146: try {
147: // Create a URL for the resource file...
148: settingsUrl = URLHelper.newExtendedURL(getFileLocation(
149: "default", userId, userGridId));
150: } catch (MalformedURLException e) {
151: if (log.isDebugEnabled())
152: log
153: .debug("Bad URL for the default User Grid Settings- "
154: + getFileLocation("default",
155: userId, userGridId));
156: return;
157: }
158:
159: try {
160: if (log.isDebugEnabled())
161: log
162: .debug("Loading Default Settting For UserGrid Widget. File="
163: + settingsUrl.toExternalForm());
164:
165: // create a JAXBContext capable of handling classes generated into the package
166: JAXBContext jc = JAXBContext
167: .newInstance("org.jaffa.presentation.portlet.widgets.controller.usergriddomain");
168:
169: // create an Unmarshaller
170: Unmarshaller u = jc.createUnmarshaller();
171:
172: // enable validation
173: u.setValidating(true);
174:
175: // unmarshal a document into a tree of Java content objects composed of classes from the package.
176: m_settings = (UserGridSettings) u.unmarshal(XmlHelper
177: .stripDoctypeDeclaration(settingsUrl));
178:
179: if (log.isDebugEnabled())
180: log
181: .debug("Loaded Default Settting For UserGrid Widget. File="
182: + settingsUrl.toExternalForm());
183: } catch (JAXBException e) {
184: // do not log a warning, since its perfectly acceptable that the file may be missing
185: if (e.getLinkedException() == null
186: || !(e.getLinkedException() instanceof IOException))
187: log
188: .warn(
189: "Malformed Default User Grid Settings Document",
190: e);
191: } catch (IOException e) {
192: // do not log a warning, since its perfectly acceptable that the file may be missing
193: }
194: }
195: }
196:
197: /** Return the width of the whole table as defined in the XML document.
198: * If the document has aready be unmarshalled this won't try and do it again
199: * @param userId user ID
200: * @param userGridId unique ID of the grid
201: * @return width of the table, null implies 100%
202: */
203: public String getTableWidth(String userId, String userGridId) {
204:
205: // load xml if not loaded
206: if (m_settings == null) {
207: loadXML(userId, userGridId);
208: if (m_settings == null)
209: return null;
210: }
211:
212: // return width
213: return m_settings.getGridWidth();
214: }
215:
216: /** unmarchels any user settings stored in an XML file for the current user
217: * configuration of this grid. Returns a null value if no file found.
218: * Returns an "ORDERED" hash userSettings of the the columns being displayed and the
219: * widths. The key is the the column name and the value is the column width.
220: * In the event that the xml file is not found a default UserGrid file will
221: * be loaded form a property configuration file like...
222: * <@properties>/user/UGW_(uniqueID).xml
223: * or default file
224: * <@properties>/DEFAULT/UGW_(uniqueID).xml
225: * @param userId user ID
226: * @param userGridId unique ID of the grid
227: * @return userGridSettings
228: */
229: public Map getColSettings(String userId, String userGridId) {
230:
231: // load xml if not loaded
232: if (m_settings == null) {
233: loadXML(userId, userGridId);
234: if (m_settings == null)
235: return null;
236: }
237:
238: // We now have the user settings object, build the LinkedHashuserSettings to return...
239: List l = m_settings.getUserGridColumnSettings();
240: if (l == null || l.size() == 0)
241: return null;
242:
243: Map userSettings = new LinkedHashMap();
244:
245: for (Iterator itr = l.iterator(); itr.hasNext();) {
246: UserGridColumnSettings columnSetting = (UserGridColumnSettings) itr
247: .next();
248: userSettings.put(columnSetting.getName(), columnSetting
249: .getWidth());
250: }
251:
252: return userSettings;
253: }
254:
255: /** marshels any user settings defined from the User Grid widget to a user named XML file
256: * @param userId userid
257: * @param userGridId userGridId
258: * @param userGridSettings user Grid Settings
259: */
260: static boolean setColSettings(String userId, String userGridId,
261: UserGridSettings userGridSettings) {
262:
263: URL file = null;
264:
265: // Get the file path and name for the file
266: try {
267: file = new URL(getFileLocation("user", userId, userGridId));
268: } catch (MalformedURLException e) {
269: log.error("Malformed Url !", e);
270: return false;
271: }
272: if (log.isDebugEnabled())
273: log.debug("Write To File : " + file.getPath());
274:
275: // Validate the URL protocol allows write access
276: if (!"file".equalsIgnoreCase(file.getProtocol())) {
277: log.error("Read Only Protocol - Can't Save");
278: return false;
279: }
280:
281: // Create the path structure for the file if not created already
282: File f = new File(file.getFile());
283: File path = new File(f.getParent());
284: if (!path.exists())
285: path.mkdirs();
286:
287: // Create output stream
288: FileOutputStream o = null;
289: try {
290: try {
291: o = new FileOutputStream(file.getPath());
292: } catch (FileNotFoundException e) {
293: log.error("Failed to open output stream !", e);
294: return false;
295: }
296:
297: try {
298: // create a JAXBContext capable of handling classes generated into the package
299: JAXBContext jc = JAXBContext
300: .newInstance("org.jaffa.presentation.portlet.widgets.controller.usergriddomain");
301:
302: // create a Validator
303: Validator v = jc.createValidator();
304:
305: // validate the content tree
306: if (!v.validateRoot(userGridSettings)) {
307: log.error("Failed to validate Structure !");
308: return false;
309: }
310:
311: // Write out XML document to file
312: Marshaller m = jc.createMarshaller();
313: m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
314: Boolean.TRUE);
315: m.marshal(userGridSettings, o);
316: } catch (ValidationException e) {
317: log.error("Failed to validate Structure !", e);
318: return false;
319: } catch (JAXBException e) {
320: log
321: .error(
322: "Failed to marshal xml to output stream !",
323: e);
324: return false;
325: }
326:
327: } finally {
328: if (o != null)
329: try {
330: o.close();
331: } catch (IOException e) {
332: }
333: }
334: return true;
335: }
336:
337: /** determines using path for marshalling and unmarshalling the XML files from teh config files
338: * @param typeOfFile type of file
339: * @param userId user ID
340: * @param userGridId user Grid Id
341: * @return returns location string
342: */
343: private static String getFileLocation(String typeOfFile,
344: String userId, String userGridId) {
345: String root = null;
346: // Get root location of setting files
347: if (typeOfFile.equals("user"))
348: root = (String) Config.getProperty(
349: Config.PROP_USER_GRID_SETTINGS_URI,
350: DEFAULT_SETTINGS_LOCATION);
351: else if (typeOfFile.equals("default"))
352: root = (String) Config.getProperty(
353: Config.PROP_DEFAULT_GRID_SETTINGS_URI,
354: DEFAULT_SETTINGS_LOCATION);
355: else
356: log.fatal("Invalid Mode For File Method :" + typeOfFile);
357:
358: // Make sure the directory seperator is always '/' as this is a url.
359: if (root.startsWith("file:") && File.separatorChar != URL_CHAR)
360: root.replace(File.separatorChar, URL_CHAR);
361:
362: // build url
363: if (typeOfFile == "user") {
364: return root + (root.endsWith(URL_STRING) ? "" : URL_STRING)
365: + userId + URL_STRING + "UGW_" + userGridId
366: + ".xml";
367: }
368: if (typeOfFile == "default") {
369: return root
370: + (root.endsWith("" + URL_STRING) ? "" : URL_STRING)
371: + "UGW_" + userGridId + ".xml";
372: }
373: return null;
374: }
375:
376: /** Restore this user to the default settings by deleting there XML file if they have one
377: * @return returns false if an error occured saving the settings
378: */
379: static boolean restore(String userId, String gridId) {
380: URL file = null;
381: // Get the file path and name for the file
382: try {
383: file = new URL(getFileLocation("user", userId, gridId));
384: } catch (MalformedURLException e) {
385: log.error("Malformed Url !", e);
386: return false;
387: }
388: if (log.isDebugEnabled())
389: log.debug("Delete File : " + file.getPath());
390:
391: // Validate the URL protocol allows write access
392: if (!"file".equalsIgnoreCase(file.getProtocol())) {
393: log.error("Read Only Protocol - Can't Delete");
394: return false;
395: }
396:
397: // Create the path structure for the file if not created already
398: File f = new File(file.getFile());
399:
400: // If file is not there, assume a sucessful delete! Bug#282
401: if (!f.exists())
402: return true;
403:
404: return f.delete();
405: }
406:
407: }
|