Version 1.1 by smmccraw on 2007/07/08 09:45

Show last authors
1 For a "clean" copy of this file, head over to http:~/~/www.overhyped.com./downloads/OTCPOIArchive.java
2
3 {{panel}}
4
5 /*
6 Copyright (c) 2003 Overhyped Technologies, LLC.
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10
11 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 */
13
14 package com.overhyped.webobjects;
15
16 import com.webobjects.foundation.*;
17 import com.webobjects.appserver.*;
18 import com.webobjects.eocontrol.*;
19 import com.webobjects.eoaccess.*;
20 import com.webobjects.directtoweb.*;
21
22 import java.io.*;
23 import java.util.Date;
24
25 import org.apache.poi.hssf.usermodel.*;
26
27 public class OTCPOIArchive extends Object {
28 protected D2WContext d2wContext;
29 protected EOEnterpriseObject object;
30 static String _fileUploadPath = null;
31
32 /** Returns the current D2WContext. */
33 public D2WContext d2wContext() {
34 return d2wContext;
35 }
36 /** Sets the current D2WContext. */
37 public void setLocalContext(D2WContext d2w) {
38 d2wContext = d2w;
39 }
40
41 /** Returns the current EOEnterpriseObject. */
42 public EOEnterpriseObject object() {
43 return object;
44 }
45 /** Sets the current EOEnterpriseObject. */
46 public void setObject(EOEnterpriseObject newEO) {
47 object = newEO;
48 }
49
50 /** Creates an Excel Spreadsheet using Apache's POI project. If the objectArray is null or empty, this method will fetch all objects from the database for the given entityNameForArchive. If the entityNameForArchive is null or empty, this method will fetch all entities and iterate over them, while fetching all objects for each entityName. This method will use aKey to set an Integer into the target, allowing for feedback while the calculation is occurring. The resulting file can be found in the /excel/ directory of the WebServer. */
51 public String calculate(NSArray objectArray, String entityNameForArchive, String aKey, WOComponent target) {
52
53 try {
54 EOEditingContext ec;
55 HSSFWorkbook wb;
56 NSArray entities;
57 java.util.Enumeration entityEnum, attributeEnum, eoEnum;
58 int sCount;
59 String eName;
60 HSSFSheet sheet;
61 NSArray attributes;
62 short col;
63 HSSFRow row;
64 String attribute, attribute2, value;
65 short r;
66 EOEnterpriseObject item;
67
68 // set up the d2wcontext
69 if (d2wContext() == null) setLocalContext( new D2WContext(target.session()) );
70 // set the task for archive
71 d2wContext().setTask("archive");
72 // get an EditingContext
73 ec = target.session().defaultEditingContext();
74 // create a workbook
75 wb = new HSSFWorkbook();
76 // get the entities
77 if ((entityNameForArchive h1. null) || (entityNameForArchive.length() 0)) {
78 entities = D2WUtils.allEntities();
79 objectArray = null; // if there's no entity name, we'd better clear out any objects.
80 }
81 else {
82 entities = new NSArray(EOUtilities.entityNamed(ec,entityNameForArchive));
83 }
84 // create an enumerator
85 entityEnum = entities.objectEnumerator();
86 // count the sheets
87 sCount = 0;
88 // enumerate
89 while (entityEnum.hasMoreElements()) {
90 // get the next entity
91 eName = ((EOEntity)entityEnum.nextElement()).name();
92 // set the entity into the D2WContext
93 d2wContext().setEntity(EOUtilities.entityNamed(ec, eName));
94 // get all objects for this entity
95 if ((objectArray h1. null) || (objectArray.count() 0)) objectArray = EOUtilities.objectsForEntityNamed(ec, eName);
96 // check if there are any objects
97 if ((objectArray h1. null) || (objectArray.count() 0)) continue;
98 // create a worksheet
99 sheet = wb.createSheet(displayName());
100 // get the propertyKeys for this entity
101 attributes = (NSArray) d2wContext().valueForKey("displayPropertyKeys");
102 // Label the columns
103 attributeEnum = attributes.objectEnumerator();
104 // zero out the column count
105 col = 0;
106 // Create a row and put some cells in it. Rows are 0 based.
107 row = sheet.createRow((short)0);
108 // iterate the attributes
109 while ( attributeEnum.hasMoreElements() ) {
110 // get the next attribute
111 attribute = (String) attributeEnum.nextElement();
112 // set the property into the D2WContext
113 d2wContext().setPropertyKey(attribute);
114 // insert it at the appropriate column
115 // add the cell to the worksheet
116 row.createCell(col).setCellValue(d2wContext().displayNameForProperty());
117 // move to the next column
118 col++;
119 }
120 // Insert the Rows
121 // make sure we start at row 1, otherwise we'll lose the column headings
122 r = 1;
123 // set up to iterate the EOs
124 eoEnum = objectArray.objectEnumerator();
125 // iterate the EOs
126 while ( eoEnum.hasMoreElements() ) {
127 try {
128 // zero out the column count
129 col = 0;
130 // create a new row
131 row = sheet.createRow(r);
132 // an EO
133 item = (EOEnterpriseObject) eoEnum.nextElement();
134 // set it into the D2W page
135 setObject(item);
136 // set up to iterate the attributes again...
137 attributeEnum = attributes.objectEnumerator();
138 // iterate the attributes again...
139 while ( attributeEnum.hasMoreElements() ) {
140 // the attribute
141 attribute2 = (String) attributeEnum.nextElement();
142 // set the property into the D2WContext
143 d2wContext().setPropertyKey(attribute2);
144 try {
145 // the final value to insert from the current object based on the d2wcontext
146 value = currentValue();
147 // create the cell for the spreadsheet
148 row.createCell(col).setCellValue(value);
149 }
150 catch (Exception e1) {
151 System.err.println(e1);
152 }
153 // move over a column
154 col++;
155 }
156 }
157 catch (Exception e2) {
158 System.err.println(e2);
159 }
160 // move down a row, since there's a new object
161 r++;
162 target.takeValueForKey(new Integer(r),aKey);
163 }
164 // add another worksheet to the spreadsheet, since there's another entity
165 sCount++;
166 // clear out the objectArray, since there's another entity
167 objectArray = null;
168
169 // System.out.println("POIArchive: calculate: Completed Archive: " + eName);
170 }
171 // All sheets and cells added. Now write out the workbook
172 String fn = fileUploadPath() + File.separator + "POI" + new NSTimestamp().getTime() + ".xls";
173 File file = new File(fn);
174 FileOutputStream fileOut = new FileOutputStream(file);
175 wb.write(fileOut);
176 fileOut.close();
177
178 objectArray = null;
179 entityNameForArchive = null;
180
181 System.out.println("POI @ " + fn);
182 return fn;
183 }
184 catch (Exception e) {
185 ByteArrayOutputStream baos = new ByteArrayOutputStream();
186 e.printStackTrace(new PrintStream(baos));
187 System.out.println("POIArchive: archive(): error:" + baos.toString());
188 return null;
189 }
190 }
191
192 /** Returns the current value provided by the d2wContext. Found objects use the d2wContext for timestamp formatting, relationships, etc. If a relationship fo an EOEnterpriseObject is resolved, and no keyForRelationship is found, this method will use the EO's userPresentableDescription. */
193 public String currentValue() {
194 Object o = null;
195 try {
196 if (d2wContext().propertyKeyIsKeyPath()) {
197 o = NSKeyValueCodingAdditions.Utility.valueForKeyPath(object(), d2wContext().propertyKey());
198 } else {
199 o = NSKeyValueCoding.DefaultImplementation.valueForKey(object(), d2wContext().propertyKey());
200 }
201 if ( (o !=_null)_&&_(o_instanceof_EOEnterpriseObject)_)_{
202 ________o_=_((EOEnterpriseObject)_o).valueForKey(d2wContext().keyWhenRelationship());
203 ________if_(_(o_!= null) && (o instanceof EOEnterpriseObject) ) {
204 try {
205 return ((EOEnterpriseObject)o).userPresentableDescription();
206 }
207 catch (Exception ex) {
208 ByteArrayOutputStream baos = new ByteArrayOutputStream();
209 ex.printStackTrace(new PrintStream(baos));
210 System.out.println("POIArchive: currentValue(): error" + baos.toString());
211 return o.toString();
212 }
213 }
214 }
215 if ( (o !=_null)_&&_(o_instanceof_NSArray)_)_{
216 ________/*****_ENHANCE_ME:_could_use_componentsSeparatedByString_along_with_userPresentableDescription._jpaul._*****/
217 ________int_count;
218 ________count_=_((NSArray)_o).count();
219 ________if_(count_==_0)_return_"0";
220 ________return_"_"_+_count;
221 ________}
222 ________if_(_(o_!= null) && (o instanceof NSTimestamp) ) {
223 NSTimestampFormatter formatter = new NSTimestampFormatter((String) d2wContext().valueForKey(D2WModel.FormatterKey));
224 return formatter.format((NSTimestamp) o);
225 }
226 if ( (o !=_null)_&&_(o_instanceof_java.lang.Number)_)_{
227 ________NSNumberFormatter_formatter;
228 ________String_pattern_=_(String)_d2wContext().valueForKey(D2WModel.FormatterKey);
229 ________if_((pattern_!= null) && (pattern.length() > 0)) {
230 formatter = new NSNumberFormatter(pattern);
231 }
232 else {
233 formatter = new NSNumberFormatter();
234 }
235 return formatter.stringForObjectValue(o);
236 }
237 if (o !=_null)_return_o.toString();
238 ________return_"";
239 ____}
240 ____catch_(Exception_e)_{
241 ________return_"(Binary_Data)";
242 ____}
243 ____}
244 ____
245 ____/**_Returns_an_EOEnterpriseObject's_'displayNameForEntity',_using_the_d2wContext._If_it_is_not_found,_the_method_will_check_the_userInfoDictionary_for__displayName._If_all_else_fails,_it_will_return_the_entity's_name._*/
246 ____public_String_displayName()_{
247 ____String_s;
248 ____
249 ____s_=_(String)_d2wContext().valueForKey("displayNameForEntity");
250 ____if_(s_==_null)_{
251 ________s_=_(String)_d2wContext().entity().userInfo().objectForKey("displayName");
252 ________if_(s_!= null) return s;
253 return (String) d2wContext().entity().name();
254 }
255 return s;
256 }
257
258 /**
259 * Returns the directory where uploaded files will be written to disk.
260 */
261 public static String fileUploadPath() {
262 if (_fileUploadPath == null) {
263 String tmpdir = System.getProperty("OTCUploadDirectory");
264 if (tmpdir != null) {
265 File tmpPath = new File(tmpdir);
266 if (tmpPath.exists()) {
267 _fileUploadPath = tmpPath.getAbsolutePath();
268 }
269 }
270 if (_fileUploadPath == null) {
271 NSLog.err.appendln("FileUpload: 'OTCUploadDirectory' does not exist. Please launch this application again with the 'OTCUploadDirectory' System Property set to a directory to which you have write permission.");
272 }
273 }
274 return _fileUploadPath;
275 }
276 }
277
278 {{/panel}}
279
280 Category:WebObjects