Skip to main content
summaryrefslogtreecommitdiffstats
blob: 177e4bbb77de3b15a9d9b8ab654a7d2c5445b338 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.framework.skynet.core.importing.parsers;

import java.io.File;
import java.io.FileFilter;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.osee.framework.core.enums.CoreAttributeTypes;
import org.eclipse.osee.framework.core.exception.OseeArgumentException;
import org.eclipse.osee.framework.core.exception.OseeCoreException;
import org.eclipse.osee.framework.core.model.type.ArtifactType;
import org.eclipse.osee.framework.core.operation.OperationLogger;
import org.eclipse.osee.framework.jdk.core.type.DoubleKeyHashMap;
import org.eclipse.osee.framework.jdk.core.util.GUID;
import org.eclipse.osee.framework.jdk.core.util.Strings;
import org.eclipse.osee.framework.jdk.core.util.io.xml.ExcelSaxHandler;
import org.eclipse.osee.framework.jdk.core.util.io.xml.RowProcessor;
import org.eclipse.osee.framework.logging.OseeLog;
import org.eclipse.osee.framework.skynet.core.artifact.ArtifactTypeManager;
import org.eclipse.osee.framework.skynet.core.importing.RoughArtifact;
import org.eclipse.osee.framework.skynet.core.importing.RoughArtifactKind;
import org.eclipse.osee.framework.skynet.core.importing.RoughRelation;
import org.eclipse.osee.framework.skynet.core.importing.operations.RoughArtifactCollector;
import org.eclipse.osee.framework.skynet.core.internal.Activator;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 * @author Ryan D. Brooks
 */
public class ExcelArtifactExtractor extends AbstractArtifactExtractor {

   private static final Pattern guidPattern = Pattern.compile("(\\d*);(.*)");
   private static final Pattern paragraphNumberPattern = Pattern.compile("\\d{1}+");

   @Override
   public String getDescription() {
      return "Extract each row as an artifact, with header format <Attribute Type 1, Attribute Type 2, ...>";
   }

   @Override
   public FileFilter getFileFilter() {
      return new FileFilter() {
         @Override
         public boolean accept(File file) {
            return file.isDirectory() || file.isFile() && file.getName().endsWith(".xml");
         }
      };
   }

   @Override
   public String getName() {
      return "Excel XML Artifacts";
   }

   @Override
   public boolean usesTypeList() {
      return false;
   }

   @Override
   protected void extractFromSource(OperationLogger logger, URI source, RoughArtifactCollector collector) throws Exception {
      XMLReader xmlReader = XMLReaderFactory.createXMLReader();
      xmlReader.setContentHandler(new ExcelSaxHandler(new ExcelRowProcessor(collector), true));
      xmlReader.parse(new InputSource(new InputStreamReader(source.toURL().openStream(), "UTF-8")));
   }

   private static final class ExcelRowProcessor implements RowProcessor {

      private final DoubleKeyHashMap<String, Integer, RoughArtifact> relationHelper =
         new DoubleKeyHashMap<String, Integer, RoughArtifact>();

      private static enum RowTypeEnum {
         PARAGRAPH_NO(CoreAttributeTypes.ParagraphNumber.getName()),
         ARTIFACT_NAME(CoreAttributeTypes.Name.getName()),
         GUID("GUID"),
         HRID("Human Readable Id"),
         OTHER("");

         private final static Map<String, RowTypeEnum> rawStringToRowType = new HashMap<String, RowTypeEnum>();

         public String _rowType;

         RowTypeEnum(String rowType) {
            _rowType = rowType;
         }

         public static synchronized RowTypeEnum fromString(String value) {
            if (rawStringToRowType.isEmpty()) {
               for (RowTypeEnum enumStatus : RowTypeEnum.values()) {
                  RowTypeEnum.rawStringToRowType.put(enumStatus._rowType, enumStatus);
               }
            }
            RowTypeEnum returnVal = rawStringToRowType.get(value);
            return returnVal != null ? returnVal : OTHER;
         }
      }
      private final Map<Integer, RowTypeEnum> rowIndexToRowTypeMap = new HashMap<Integer, RowTypeEnum>();

      private final Matcher guidMatcher;
      private final RoughArtifactCollector collector;

      private int rowCount;
      private String[] headerRow;
      private ArtifactType primaryDescriptor;
      private boolean importingRelations;

      public ExcelRowProcessor(RoughArtifactCollector collector) {
         this.guidMatcher = guidPattern.matcher("");
         this.collector = collector;
         rowCount = 0;
         importingRelations = false;
      }

      @Override
      public void detectedRowAndColumnCounts(int rowCount, int columnCount) {
         // do nothing
      }

      @Override
      public void foundStartOfWorksheet(String sheetName) {
         rowCount = 0;
         try {
         if (sheetName.equals("relations")) {
            importingRelations = true;
            return;
         }
         primaryDescriptor = ArtifactTypeManager.getType(sheetName);
         if (primaryDescriptor == null) {
            throw new OseeArgumentException("The sheet [%s] is not a valid artifact type name.", sheetName);
         }
         } catch (OseeCoreException ex) {
            throw new IllegalArgumentException("The sheet [%s] is not a valid artifact type name: ", ex);
         }
      }

      @Override
      public void processCommentRow(String[] row) {
         rowCount++;
      }

      @Override
      public void processEmptyRow() {
         rowCount++;
      }

      @Override
      public void processHeaderRow(String[] headerRow) {
         rowCount++;
         this.headerRow = headerRow.clone();
         for (int i = 0; i < this.headerRow.length; i++) {
            String value = headerRow[i];
            if (value != null) {
               value = value.trim();
            }
            if (!Strings.isValid(value)) {
               this.headerRow[i] = null;
            } else {
               RowTypeEnum rowTypeEnum = RowTypeEnum.fromString(value);
               rowIndexToRowTypeMap.put(i, rowTypeEnum);
            }
         }
      }

      @Override
      public void processRow(String[] row) throws OseeArgumentException {
         rowCount++;
         if (importingRelations) {
            String guida = null;
            String guidb = null;
            guida = getGuid(row[1]);
            guidb = getGuid(row[2]);

            if (guida == null || guidb == null) {
               OseeLog.log(Activator.class, Level.WARNING,
                  "we failed to add a relation because at least on of its guids are null");
            }
            collector.addRoughRelation(new RoughRelation(row[0], guida, guidb, row[5]));
         } else {
            RoughArtifact roughArtifact = new RoughArtifact(RoughArtifactKind.PRIMARY);
            if (!rowIndexToRowTypeMap.isEmpty()) {
               for (int rowIndex = 0; rowIndex < row.length; rowIndex++) {
                  RowTypeEnum rowType = rowIndexToRowTypeMap.get(rowIndex);

                  String rowValue = row[rowIndex];

                  if (Strings.isValid(rowValue)) {
                     switch (rowType) {
                        case PARAGRAPH_NO:
                           if (paragraphNumberPattern.matcher(rowValue).matches()) {
                              rowValue = String.format("%s.0", rowValue); //forcing \\d.0 format
                           }
                           roughArtifact.setSectionNumber(rowValue);
                           roughArtifact.addAttribute(CoreAttributeTypes.ParagraphNumber, rowValue);
                           break;
                        case ARTIFACT_NAME:
                           roughArtifact.addAttribute(CoreAttributeTypes.Name, rowValue);
                           break;
                        case GUID:
                           roughArtifact.setGuid(rowValue);
                           break;
                        case HRID:
                           roughArtifact.setHumandReadableId(rowValue);
                           break;
                        case OTHER:
                           roughArtifact.addAttribute(headerRow[rowIndex], rowValue);
                           break;
                     }
                  } else {
                     //complain only if row value invalid and parsing paragraph numbers
                     if (rowType == RowTypeEnum.PARAGRAPH_NO) {
                        throw new OseeArgumentException("%s must not be blank", CoreAttributeTypes.ParagraphNumber);
                     }
                  }

               }
            }

            collector.addRoughArtifact(roughArtifact);
            relationHelper.put(primaryDescriptor.getName(), rowCount, roughArtifact);
         }
      }

      private String getGuid(String string) {
         if (GUID.isValid(string)) {
            return string;
         }
         guidMatcher.reset(string);
         if (guidMatcher.matches()) {
            Integer row = Integer.parseInt(guidMatcher.group(1));
            String sheet = guidMatcher.group(2);
            RoughArtifact artifact = relationHelper.get(sheet, row);
            return artifact.getGuid();
         }
         return null;
      }

      @Override
      public void reachedEndOfWorksheet() {
         // do nothing
      }
   }
}

Back to the top