View Javadoc
1   package org.kuali.kpme.edo;
2   
3   import org.apache.commons.dbcp.BasicDataSource;
4   import org.apache.ojb.broker.PBKey;
5   import org.apache.poi.hssf.usermodel.*;
6   import org.apache.poi.ss.usermodel.Cell;
7   import org.junit.Test;
8   import org.kuali.kpme.edo.service.EdoServiceLocator;
9   import org.kuali.rice.core.impl.config.property.Config;
10  import org.kuali.rice.core.impl.config.property.Param;
11  import org.kuali.rice.coreservice.api.parameter.Parameter;
12  import org.springframework.context.support.StaticApplicationContext;
13  import org.springframework.jdbc.core.JdbcTemplate;
14  import org.springframework.jdbc.support.rowset.SqlRowSet;
15  import org.xml.sax.*;
16  import org.xml.sax.helpers.XMLFilterImpl;
17  
18  import javax.sql.RowSet;
19  import javax.xml.bind.JAXBContext;
20  import javax.xml.bind.Unmarshaller;
21  import javax.xml.bind.UnmarshallerHandler;
22  import javax.xml.parsers.SAXParser;
23  import javax.xml.parsers.SAXParserFactory;
24  import java.io.*;
25  import java.sql.Connection;
26  import java.sql.DriverManager;
27  import java.util.HashMap;
28  import java.util.Map;
29  import java.util.regex.Matcher;
30  import java.util.regex.Pattern;
31  
32  public class SpreadsheetEditTest {
33  
34  
35      enum Location {LEFT, CENTER, RIGHT};
36  
37  
38      Pattern pattern=Pattern.compile("\\$\\{(.*?)\\}"); // e.g. ${lastName}
39  
40  
41      interface xlsBean { // wraps Cells and Headers so they can be used interchangeably; also simplifies data types
42          public void setData(String datum);
43          public String getData();
44      }
45  
46      Map<String,xlsBean> beans=new HashMap();
47  
48      class CellBean implements xlsBean {
49          int index=1;
50  
51          HSSFCell cell;
52          CellBean(HSSFCell cell) { this.cell=cell;}
53  
54          public void setData(String datum) {
55              int destinationRowNumber=cell.getRow().getRowNum()+index++;
56              int destinationCellNumber=cell.getColumnIndex();
57  
58  
59              HSSFSheet sheet=cell.getRow().getSheet();
60              HSSFRow destinationRow=sheet.getRow(destinationRowNumber);
61              if (destinationRow==null) {
62                  destinationRow=sheet.createRow(destinationRowNumber);
63              }
64              HSSFCell destinationCell=destinationRow.getCell(destinationCellNumber);
65  
66              if (destinationCell==null) {
67                  destinationCell=destinationRow.createCell(destinationCellNumber);
68                  destinationCell.setCellType(cell.getCellType());
69              }
70  
71              if (cell.getCellType()== Cell.CELL_TYPE_NUMERIC) {
72                  destinationCell.setCellValue(new Double(datum));
73              }  else {
74                  destinationCell.setCellValue(datum);
75              }
76          }
77  
78          public String getData() {
79              if (cell.getCellType()== Cell.CELL_TYPE_NUMERIC) {
80                  return ""+cell.getNumericCellValue();
81              }  else {
82                  return cell.getStringCellValue();
83              }
84          }
85  
86      }
87  
88      class HeaderBean implements xlsBean {
89  
90          Location loc;
91          HSSFHeader header;
92          HeaderBean(HSSFHeader header,Location loc) { this.header=header; this.loc=loc;}
93          public void setData(String datum) {
94              switch (loc) {
95                  case LEFT:
96                      header.setLeft(datum);
97                      break;
98                  case CENTER:
99                      header.setCenter(datum);
100                     break;
101                 case RIGHT:
102                     header.setRight(datum);
103                     break;
104             }
105         }
106         public String getData() {
107             switch (loc) {
108                 case LEFT:
109                     return header.getLeft();
110                 case CENTER:
111                     return header.getCenter();
112                 case RIGHT:
113                     return header.getRight();
114             }
115             return null;
116         }
117     }
118 
119 
120     void apply(String var,String val) {
121         System.out.println(String.format("%s=%s",var,val));
122         xlsBean bean=beans.get(var);
123         if (bean instanceof HeaderBean) {  // work around required for weird header font size behavior
124             if (Character.isDigit(val.charAt(0))) {
125                 val=" "+val;
126             }
127         }
128         bean.setData(bean.getData().replace(var,val));
129     }
130 
131 
132     @Test
133     public void testAddRow() throws IOException {
134 
135         final String inFilename=EdoUnitTestBase.UNIT_TEST_SAMPLE_FILES_PATH+"file1.xls";
136         final String outFilename="file1-out.xls";
137 
138         HSSFWorkbook wb=new HSSFWorkbook(new FileInputStream(inFilename));
139         HSSFSheet sheet = wb.getSheetAt(0);
140 
141         HSSFHeader header=sheet.getHeader();
142 
143         Matcher matcher=pattern.matcher(header.getLeft());
144         while (matcher.find()) {
145             String index=matcher.group();
146             beans.put(index, new HeaderBean(header,Location.LEFT));
147         }
148 
149         matcher=pattern.matcher(header.getCenter());
150         while (matcher.find()) {
151             String index=matcher.group();
152             beans.put(index, new HeaderBean(header,Location.CENTER));
153         }
154 
155         matcher=pattern.matcher(header.getRight());
156         while (matcher.find()) {
157             String index=matcher.group();
158             beans.put(index, new HeaderBean(header,Location.RIGHT));
159         }
160 
161         HSSFRow row1=sheet.getRow(1);
162 
163         for (int i=row1.getFirstCellNum(); i<row1.getLastCellNum(); i++ ) {
164             HSSFCell nextCell=row1.getCell(i);
165             beans.put(nextCell.getStringCellValue(),new CellBean(nextCell));
166         }
167 
168         apply("${CampusName}", "Indiana University - Bloomington");
169         apply("${Title1}","2012-13 Summary Sheet");
170         apply("${Title2}","TENURE ONLY");
171 
172         apply("${Last}","Test1");
173         apply("${Last}","Smith2");
174         apply("${Last}","Jones3");
175 
176         apply("${First}","Tester1");
177         apply("${First}","Chris2");
178         apply("${First}","Billy3");
179 
180         sheet.removeRow(row1);   // clears contents
181         sheet.shiftRows(2,5,-1); // gets rid of blank line
182 
183         FileOutputStream stream = new FileOutputStream(outFilename);
184 
185         wb.write(stream);
186         stream.close();
187 
188 
189     }
190 
191     /* A bit extreme but the following helps keep me from checking username & password into CVS */
192 /*
193     Map<String,String> readParameters(String ... inputFiles) throws Exception {
194 
195         Map<String,String> params=new HashMap<String, String>();
196 
197         // Create the XMLFilter
198         XMLFilter filter = new NamespaceFilter();
199 
200         // Set the parent XMLReader on the XMLFilter
201         SAXParserFactory spf = SAXParserFactory.newInstance();
202         SAXParser sp = spf.newSAXParser();
203         XMLReader xr = sp.getXMLReader();
204         filter.setParent(xr);
205 
206         JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
207         Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
208         UnmarshallerHandler unmarshallerHandler = jaxbUnmarshaller.getUnmarshallerHandler();
209         filter.setContentHandler(unmarshallerHandler);
210 
211         for (String filename : inputFiles)   {
212             InputSource xml = new InputSource(filename);
213             filter.parse(xml);
214 
215             Config config = (Config) unmarshallerHandler.getResult();
216             for (Param p : config.getParamList()) {
217                 params.put(p.getName(),p.getValue());
218             }
219         }
220 
221         return params;
222     }
223 */
224     public class NamespaceFilter extends XMLFilterImpl {
225 
226         private static final String NAMESPACE = "http://rice.kuali.org/core/impl/config";
227 
228         @Override
229         public void endElement(String uri, String localName, String qName)
230                 throws SAXException {
231             super.endElement(NAMESPACE, localName, qName);
232         }
233 
234         @Override
235         public void startElement(String uri, String localName, String qName,Attributes atts) throws SAXException {
236             super.startElement(NAMESPACE, localName, qName, atts);
237         }
238 
239     }
240 
241 
242     /*@Test
243     public void testReadData() throws Exception {
244 
245         Map<String,String> params=readParameters("/opt/java/settings/edo/stg/edo-stg-config.xml","/opt/java/security/edo/stg/edo-stg-security.xml");
246 
247 
248         BasicDataSource dataSource=new BasicDataSource();
249         dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
250         dataSource.setUsername(params.get("edo.datasource.username"));
251         dataSource.setPassword(params.get("edo.datasource.password"));
252         dataSource.setUrl(params.get("edo.datasource.url"));
253 
254         StaticApplicationContext ctx=new StaticApplicationContext();
255         EdoServiceLocator esl=new EdoServiceLocator();
256         esl.setApplicationContext(ctx);
257 
258 
259         JdbcTemplate tpl=new JdbcTemplate();
260         tpl.setDataSource(dataSource);
261 
262 
263         SqlRowSet rs=tpl.queryForRowSet("select * from EDO_PT_REPORT_V");
264 
265         while (rs.next()) {
266             System.out.println(rs.getObject("CANDIDATE_USERNAME").toString());
267         }
268 
269 
270  }*/
271         /*
272 
273         WorkAreaDaoSpringOjbImpl workAreaDao=new WorkAreaDaoSpringOjbImpl();
274         workAreaDao.getPersistenceBrokerTemplate().setPbKey(pbKey);
275           */
276 
277 
278    
279 
280 
281 
282 
283 }