/
IngestServiceBean.java
1943 lines (1627 loc) · 97.2 KB
/
IngestServiceBean.java
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
package edu.harvard.iq.dataverse.ingest;
import edu.harvard.iq.dataverse.ControlledVocabularyValue;
import edu.harvard.iq.dataverse.datavariable.VariableCategory;
import edu.harvard.iq.dataverse.datavariable.VariableServiceBean;
import edu.harvard.iq.dataverse.DatasetServiceBean;
import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.DataFileCategory;
import edu.harvard.iq.dataverse.DataFileServiceBean;
import edu.harvard.iq.dataverse.DataTable;
import edu.harvard.iq.dataverse.DatasetField;
import edu.harvard.iq.dataverse.DatasetFieldServiceBean;
import edu.harvard.iq.dataverse.DatasetFieldType;
import edu.harvard.iq.dataverse.DatasetFieldValue;
import edu.harvard.iq.dataverse.DatasetFieldCompoundValue;
import edu.harvard.iq.dataverse.DatasetLock;
import edu.harvard.iq.dataverse.DatasetVersion;
import edu.harvard.iq.dataverse.FileMetadata;
import edu.harvard.iq.dataverse.MetadataBlock;
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
import edu.harvard.iq.dataverse.dataaccess.DataAccess;
import edu.harvard.iq.dataverse.dataaccess.StorageIO;
import edu.harvard.iq.dataverse.dataaccess.ImageThumbConverter;
import edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator;
import edu.harvard.iq.dataverse.datavariable.SummaryStatistic;
import edu.harvard.iq.dataverse.datavariable.DataVariable;
import edu.harvard.iq.dataverse.ingest.metadataextraction.FileMetadataExtractor;
import edu.harvard.iq.dataverse.ingest.metadataextraction.FileMetadataIngest;
import edu.harvard.iq.dataverse.ingest.metadataextraction.impl.plugins.fits.FITSFileMetadataExtractor;
import edu.harvard.iq.dataverse.ingest.tabulardata.TabularDataFileReader;
import edu.harvard.iq.dataverse.ingest.tabulardata.TabularDataIngest;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReader;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.NewDTAFileReader;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReaderSpi;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.rdata.RDATAFileReader;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.rdata.RDATAFileReaderSpi;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.csv.CSVFileReader;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.csv.CSVFileReaderSpi;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.xlsx.XLSXFileReader;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.xlsx.XLSXFileReaderSpi;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.sav.SAVFileReader;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.sav.SAVFileReaderSpi;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader;
import edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReaderSpi;
import edu.harvard.iq.dataverse.util.*;
//import edu.harvard.iq.dvn.unf.*;
import org.dataverse.unf.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;
import java.util.Comparator;
import java.util.ListIterator;
import java.util.logging.Logger;
import java.util.Hashtable;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.annotation.Resource;
import javax.ejb.Asynchronous;
import javax.jms.JMSException;
import javax.jms.QueueConnection;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Message;
import javax.faces.bean.ManagedBean;
import javax.faces.application.FacesMessage;
/**
*
* @author Leonid Andreev
* dataverse 4.0
* New service for handling ingest tasks
*
*/
@Stateless
@Named
@ManagedBean
public class IngestServiceBean {
private static final Logger logger = Logger.getLogger(IngestServiceBean.class.getCanonicalName());
@EJB
VariableServiceBean variableService;
@EJB
DatasetServiceBean datasetService;
@EJB
DatasetFieldServiceBean fieldService;
@EJB
DataFileServiceBean fileService;
@EJB
SystemConfig systemConfig;
@Resource(mappedName = "jms/DataverseIngest")
Queue queue;
@Resource(mappedName = "jms/IngestQueueConnectionFactory")
QueueConnectionFactory factory;
private static String timeFormat_hmsS = "HH:mm:ss.SSS";
private static String dateTimeFormat_ymdhmsS = "yyyy-MM-dd HH:mm:ss.SSS";
private static String dateFormat_ymd = "yyyy-MM-dd";
// This method tries to permanently store new files on the filesystem.
// Then it adds the files that *have been successfully saved* to the
// dataset (by attaching the DataFiles to the Dataset, and the corresponding
// FileMetadatas to the DatasetVersion). It also tries to ensure that none
// of the parts of the DataFiles that failed to be saved (if any) are still
// attached to the Dataset via some cascade path (for example, via
// DataFileCategory objects, if any were already assigned to the files).
// It must be called before we attempt to permanently save the files in
// the database by calling the Save command on the dataset and/or version.
public List<DataFile> saveAndAddFilesToDataset(DatasetVersion version, List<DataFile> newFiles) {
List<DataFile> ret = new ArrayList<>();
if (newFiles != null && newFiles.size() > 0) {
//ret = new ArrayList<>();
// final check for duplicate file names;
// we tried to make the file names unique on upload, but then
// the user may have edited them on the "add files" page, and
// renamed FOOBAR-1.txt back to FOOBAR.txt...
IngestUtil.checkForDuplicateFileNamesFinal(version, newFiles);
Dataset dataset = version.getDataset();
for (DataFile dataFile : newFiles) {
String tempFileLocation = FileUtil.getFilesTempDirectory() + "/" + dataFile.getStorageIdentifier();
// Try to save the file in its permanent location:
String storageId = dataFile.getStorageIdentifier().replaceFirst("^tmp://", "");
Path tempLocationPath = Paths.get(FileUtil.getFilesTempDirectory() + "/" + storageId);
WritableByteChannel writeChannel = null;
FileChannel readChannel = null;
boolean unattached = false;
boolean savedSuccess = false;
StorageIO<DataFile> dataAccess = null;
try {
logger.fine("Attempting to create a new storageIO object for " + storageId);
if (dataFile.getOwner() == null) {
unattached = true;
dataFile.setOwner(dataset);
}
dataAccess = DataAccess.createNewStorageIO(dataFile, storageId);
logger.fine("Successfully created a new storageIO object.");
/*
This commented-out code demonstrates how to copy bytes
from a local InputStream (or a readChannel) into the
writable byte channel of a Dataverse DataAccessIO object:
*/
/*
storageIO.open(DataAccessOption.WRITE_ACCESS);
writeChannel = storageIO.getWriteChannel();
readChannel = new FileInputStream(tempLocationPath.toFile()).getChannel();
long bytesPerIteration = 16 * 1024; // 16K bytes
long start = 0;
while ( start < readChannel.size() ) {
readChannel.transferTo(start, bytesPerIteration, writeChannel);
start += bytesPerIteration;
}
*/
/*
But it's easier to use this convenience method from the
DataAccessIO:
(if the underlying storage method for this file is
local filesystem, the DataAccessIO will simply copy
the file using Files.copy, like this:
Files.copy(tempLocationPath, storageIO.getFileSystemLocation(), StandardCopyOption.REPLACE_EXISTING);
*/
dataAccess.savePath(tempLocationPath);
// Set filesize in bytes
//
dataFile.setFilesize(dataAccess.getSize());
savedSuccess = true;
logger.fine("Success: permanently saved file " + dataFile.getFileMetadata().getLabel());
} catch (IOException ioex) {
logger.warning("Failed to save the file, storage id " + dataFile.getStorageIdentifier() + " (" + ioex.getMessage() + ")");
} finally {
if (readChannel != null) {
try {
readChannel.close();
} catch (IOException e) {
}
}
if (writeChannel != null) {
try {
writeChannel.close();
} catch (IOException e) {
}
}
}
// Since we may have already spent some CPU cycles scaling down image thumbnails,
// we may as well save them, by moving these generated images to the permanent
// dataset directory. We should also remember to delete any such files in the
// temp directory:
List<Path> generatedTempFiles = listGeneratedTempFiles(Paths.get(FileUtil.getFilesTempDirectory()), storageId);
if (generatedTempFiles != null) {
for (Path generated : generatedTempFiles) {
if (savedSuccess) { // no need to try to save this aux file permanently, if we've failed to save the main file!
logger.fine("(Will also try to permanently save generated thumbnail file " + generated.toString() + ")");
try {
//Files.copy(generated, Paths.get(dataset.getFileSystemDirectory().toString(), generated.getFileName().toString()));
int i = generated.toString().lastIndexOf("thumb");
if (i > 1) {
String extensionTag = generated.toString().substring(i);
dataAccess.savePathAsAux(generated, extensionTag);
logger.fine("Saved generated thumbnail as aux object. \"preview available\" status: " + dataFile.isPreviewImageAvailable());
} else {
logger.warning("Generated thumbnail file name does not match the expected pattern: " + generated.toString());
}
} catch (IOException ioex) {
logger.warning("Failed to save generated file " + generated.toString());
}
}
// ... but we definitely want to delete it:
try {
Files.delete(generated);
} catch (IOException ioex) {
logger.warning("Failed to delete generated file " + generated.toString());
}
}
}
// ... and let's delete the main temp file:
try {
logger.fine("Will attempt to delete the temp file " + tempLocationPath.toString());
Files.delete(tempLocationPath);
} catch (IOException ex) {
// (non-fatal - it's just a temp file.)
logger.warning("Failed to delete temp file " + tempLocationPath.toString());
}
if (unattached) {
dataFile.setOwner(null);
}
// Any necessary post-processing:
//performPostProcessingTasks(dataFile);
if (savedSuccess) {
// These are all brand new files, so they should all have
// one filemetadata total. -- L.A.
FileMetadata fileMetadata = dataFile.getFileMetadatas().get(0);
String fileName = fileMetadata.getLabel();
boolean metadataExtracted = false;
if (FileUtil.canIngestAsTabular(dataFile)) {
/*
* Note that we don't try to ingest the file right away -
* instead we mark it as "scheduled for ingest", then at
* the end of the save process it will be queued for async.
* ingest in the background. In the meantime, the file
* will be ingested as a regular, non-tabular file, and
* appear as such to the user, until the ingest job is
* finished with the Ingest Service.
*/
dataFile.SetIngestScheduled();
} else if (fileMetadataExtractable(dataFile)) {
try {
// FITS is the only type supported for metadata
// extraction, as of now. -- L.A. 4.0
dataFile.setContentType("application/fits");
metadataExtracted = extractMetadata(tempFileLocation, dataFile, version);
} catch (IOException mex) {
logger.severe("Caught exception trying to extract indexable metadata from file " + fileName + ", " + mex.getMessage());
}
if (metadataExtracted) {
logger.fine("Successfully extracted indexable metadata from file " + fileName);
} else {
logger.fine("Failed to extract indexable metadata from file " + fileName);
}
}
// temp dbug line
//System.out.println("ADDING FILE: " + fileName + "; for dataset: " + dataset.getGlobalId());
// Make sure the file is attached to the dataset and to the version, if this
// hasn't been done yet:
if (dataFile.getOwner() == null) {
dataFile.setOwner(dataset);
version.getFileMetadatas().add(dataFile.getFileMetadata());
dataFile.getFileMetadata().setDatasetVersion(version);
dataset.getFiles().add(dataFile);
if (dataFile.getFileMetadata().getCategories() != null) {
ListIterator<DataFileCategory> dfcIt = dataFile.getFileMetadata().getCategories().listIterator();
while (dfcIt.hasNext()) {
DataFileCategory dataFileCategory = dfcIt.next();
if (dataFileCategory.getDataset() == null) {
DataFileCategory newCategory = dataset.getCategoryByName(dataFileCategory.getName());
if (newCategory != null) {
newCategory.addFileMetadata(dataFile.getFileMetadata());
//dataFileCategory = newCategory;
dfcIt.set(newCategory);
} else {
dfcIt.remove();
}
}
}
}
}
ret.add(dataFile);
}
}
logger.fine("Done! Finished saving new files in permanent storage and adding them to the dataset.");
}
return ret;
}
public List<Path> listGeneratedTempFiles(Path tempDirectory, String baseName) {
List<Path> generatedFiles = new ArrayList<>();
// for example, <filename>.thumb64 or <filename>.thumb400.
if (baseName == null || baseName.equals("")) {
return null;
}
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path file) throws IOException {
return (file.getFileName() != null
&& file.getFileName().toString().startsWith(baseName + ".thumb"));
}
};
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(tempDirectory, filter)) {
for (Path filePath : dirStream) {
generatedFiles.add(filePath);
}
} catch (IOException ex) {
}
return generatedFiles;
}
// TODO: consider creating a version of this method that would take
// datasetversion as the argument.
// -- L.A. 4.6
public void startIngestJobsForDataset(Dataset dataset, AuthenticatedUser user) {
List<DataFile> scheduledFiles = new ArrayList<>();
for (DataFile dataFile : dataset.getFiles()) {
if (dataFile.isIngestScheduled()) {
// todo: investigate why when calling save with the file object
// gotten from the loop, the roles assignment added at create is removed
// (switching to refinding via id resolves that)
dataFile = fileService.find(dataFile.getId());
scheduledFiles.add(dataFile);
}
}
startIngestJobs(scheduledFiles, user);
}
public String startIngestJobs(List<DataFile> dataFiles, AuthenticatedUser user) {
IngestMessage ingestMessage = null;
StringBuilder sb = new StringBuilder();
List<DataFile> scheduledFiles = new ArrayList<>();
for (DataFile dataFile : dataFiles) {
if (dataFile.isIngestScheduled()) {
// refresh the copy of the DataFile:
dataFile = fileService.find(dataFile.getId());
long ingestSizeLimit = -1;
try {
ingestSizeLimit = systemConfig.getTabularIngestSizeLimit(getTabDataReaderByMimeType(dataFile.getContentType()).getFormatName());
} catch (IOException ioex) {
logger.warning("IO Exception trying to retrieve the ingestable format identifier from the plugin for type " + dataFile.getContentType() + " (non-fatal);");
}
if (ingestSizeLimit == -1 || dataFile.getFilesize() < ingestSizeLimit) {
dataFile.SetIngestInProgress();
scheduledFiles.add(dataFile);
} else {
dataFile.setIngestDone();
String message = "Skipping tabular ingest of the file " + dataFile.getFileMetadata().getLabel() + ", because of the size limit (set to " + ingestSizeLimit + " bytes); ";
logger.info(message);
sb.append(message);
}
dataFile = fileService.save(dataFile);
} else {
String message = "(Re)ingest queueing request submitted on a file not scheduled for ingest! (" + dataFile.getFileMetadata().getLabel() + "); ";
logger.warning(message);
sb.append(message);
}
}
int count = scheduledFiles.size();
if (count > 0) {
String info = "Ingest of " + count + " tabular data file(s) is in progress.";
logger.info(info);
datasetService.addDatasetLock(scheduledFiles.get(0).getOwner().getId(),
DatasetLock.Reason.Ingest,
(user != null) ? user.getId() : null,
info);
// Sort ingest jobs by file size:
DataFile[] scheduledFilesArray = (DataFile[])scheduledFiles.toArray(new DataFile[count]);
scheduledFiles = null;
Arrays.sort(scheduledFilesArray, new Comparator<DataFile>() {
@Override
public int compare(DataFile d1, DataFile d2) {
long a = d1.getFilesize();
long b = d2.getFilesize();
return Long.valueOf(a).compareTo(b);
}
});
ingestMessage = new IngestMessage(IngestMessage.INGEST_MESAGE_LEVEL_INFO, user.getId());
for (int i = 0; i < count; i++) {
ingestMessage.addFileId(scheduledFilesArray[i].getId());
}
QueueConnection conn = null;
QueueSession session = null;
QueueSender sender = null;
try {
conn = factory.createQueueConnection();
session = conn.createQueueSession(false, 0);
sender = session.createSender(queue);
Message queueMessage = session.createObjectMessage(ingestMessage);
sender.send(queueMessage);
} catch (JMSException ex) {
ex.printStackTrace();
logger.warning("Caught exception trying to close connections after starting a (re)ingest job in the JMS queue! Stack trace below.");
sb.append("Failed to queue the (re)ingest job for DataFile (JMS Exception)" + (ex.getMessage() != null ? ex.getMessage() : ""));
} finally {
try {
if (sender != null) {
sender.close();
}
if (session != null) {
session.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception ex) {
logger.warning("Caught exception trying to close connections after starting a (re)ingest job in the JMS queue! Stack trace below.");
ex.printStackTrace();
}
}
}
return sb.toString();
}
public void produceSummaryStatistics(DataFile dataFile, File generatedTabularFile) throws IOException {
/*
logger.info("Skipping summary statistics and UNF.");
*/
produceDiscreteNumericSummaryStatistics(dataFile, generatedTabularFile);
produceContinuousSummaryStatistics(dataFile, generatedTabularFile);
produceCharacterSummaryStatistics(dataFile, generatedTabularFile);
recalculateDataFileUNF(dataFile);
recalculateDatasetVersionUNF(dataFile.getFileMetadata().getDatasetVersion());
}
public void produceContinuousSummaryStatistics(DataFile dataFile, File generatedTabularFile) throws IOException {
/*
// quick, but memory-inefficient way:
// - this method just loads the entire file-worth of continuous vectors
// into a Double[][] matrix.
//Double[][] variableVectors = subsetContinuousVectors(dataFile);
//calculateContinuousSummaryStatistics(dataFile, variableVectors);
// A more sophisticated way: this subsets one column at a time, using
// the new optimized subsetting that does not have to read any extra
// bytes from the file to extract the column:
TabularSubsetGenerator subsetGenerator = new TabularSubsetGenerator();
*/
for (int i = 0; i < dataFile.getDataTable().getVarQuantity(); i++) {
if (dataFile.getDataTable().getDataVariables().get(i).isIntervalContinuous()) {
logger.fine("subsetting continuous vector");
if ("float".equals(dataFile.getDataTable().getDataVariables().get(i).getFormat())) {
Float[] variableVector = TabularSubsetGenerator.subsetFloatVector(new FileInputStream(generatedTabularFile), i, dataFile.getDataTable().getCaseQuantity().intValue());
logger.fine("Calculating summary statistics on a Float vector;");
calculateContinuousSummaryStatistics(dataFile, i, variableVector);
// calculate the UNF while we are at it:
logger.fine("Calculating UNF on a Float vector;");
calculateUNF(dataFile, i, variableVector);
variableVector = null;
} else {
Double[] variableVector = TabularSubsetGenerator.subsetDoubleVector(new FileInputStream(generatedTabularFile), i, dataFile.getDataTable().getCaseQuantity().intValue());
logger.fine("Calculating summary statistics on a Double vector;");
calculateContinuousSummaryStatistics(dataFile, i, variableVector);
// calculate the UNF while we are at it:
logger.fine("Calculating UNF on a Double vector;");
calculateUNF(dataFile, i, variableVector);
variableVector = null;
}
logger.fine("Done! (continuous);");
}
}
}
public void produceDiscreteNumericSummaryStatistics(DataFile dataFile, File generatedTabularFile) throws IOException {
//TabularSubsetGenerator subsetGenerator = new TabularSubsetGenerator();
for (int i = 0; i < dataFile.getDataTable().getVarQuantity(); i++) {
if (dataFile.getDataTable().getDataVariables().get(i).isIntervalDiscrete()
&& dataFile.getDataTable().getDataVariables().get(i).isTypeNumeric()) {
logger.fine("subsetting discrete-numeric vector");
Long[] variableVector = TabularSubsetGenerator.subsetLongVector(new FileInputStream(generatedTabularFile), i, dataFile.getDataTable().getCaseQuantity().intValue());
// We are discussing calculating the same summary stats for
// all numerics (the same kind of sumstats that we've been calculating
// for numeric continuous type) -- L.A. Jul. 2014
calculateContinuousSummaryStatistics(dataFile, i, variableVector);
// calculate the UNF while we are at it:
logger.fine("Calculating UNF on a Long vector");
calculateUNF(dataFile, i, variableVector);
logger.fine("Done! (discrete numeric)");
variableVector = null;
}
}
}
public void produceCharacterSummaryStatistics(DataFile dataFile, File generatedTabularFile) throws IOException {
/*
At this point it's still not clear what kinds of summary stats we
want for character types. Though we are pretty confident we don't
want to keep doing what we used to do in the past, i.e. simply
store the total counts for all the unique values; even if it's a
very long vector, and *every* value in it is unique. (As a result
of this, our Categorical Variable Value table is the single
largest in the production database. With no evidence whatsoever,
that this information is at all useful.
-- L.A. Jul. 2014
TabularSubsetGenerator subsetGenerator = new TabularSubsetGenerator();
*/
for (int i = 0; i < dataFile.getDataTable().getVarQuantity(); i++) {
if (dataFile.getDataTable().getDataVariables().get(i).isTypeCharacter()) {
logger.fine("subsetting character vector");
String[] variableVector = TabularSubsetGenerator.subsetStringVector(new FileInputStream(generatedTabularFile), i, dataFile.getDataTable().getCaseQuantity().intValue());
//calculateCharacterSummaryStatistics(dataFile, i, variableVector);
// calculate the UNF while we are at it:
logger.fine("Calculating UNF on a String vector");
calculateUNF(dataFile, i, variableVector);
logger.fine("Done! (character)");
variableVector = null;
}
}
}
public static void produceFrequencyStatistics(DataFile dataFile, File generatedTabularFile) throws IOException {
List<DataVariable> vars = dataFile.getDataTable().getDataVariables();
produceFrequencies(generatedTabularFile, vars);
}
public static void produceFrequencies( File generatedTabularFile, List<DataVariable> vars) throws IOException {
for (int i = 0; i < vars.size(); i++) {
Collection<VariableCategory> cats = vars.get(i).getCategories();
int caseQuantity = vars.get(i).getDataTable().getCaseQuantity().intValue();
boolean isNumeric = vars.get(i).isTypeNumeric();
Object[] variableVector = null;
if (cats.size() > 0) {
if (isNumeric) {
variableVector = TabularSubsetGenerator.subsetFloatVector(new FileInputStream(generatedTabularFile), i, caseQuantity);
}
else {
variableVector = TabularSubsetGenerator.subsetStringVector(new FileInputStream(generatedTabularFile), i, caseQuantity);
}
if (variableVector != null) {
Hashtable<Object, Double> freq = calculateFrequency(variableVector);
for (VariableCategory cat : cats) {
Object catValue;
if (isNumeric) {
catValue = new Float(cat.getValue());
} else {
catValue = cat.getValue();
}
Double numberFreq = freq.get(catValue);
if (numberFreq != null) {
cat.setFrequency(numberFreq);
} else {
cat.setFrequency(0D);
}
}
} else {
logger.fine("variableVector is null for variable " + vars.get(i).getName());
}
}
}
}
public static Hashtable<Object, Double> calculateFrequency( Object[] variableVector) {
Hashtable<Object, Double> freq = new Hashtable<Object, Double>();
for (int j = 0; j < variableVector.length; j++) {
if (variableVector[j] != null) {
Double freqNum = freq.get(variableVector[j]);
if (freqNum != null) {
freq.put(variableVector[j], freqNum + 1);
} else {
freq.put(variableVector[j], 1D);
}
}
}
return freq;
}
public void recalculateDataFileUNF(DataFile dataFile) {
String[] unfValues = new String[dataFile.getDataTable().getVarQuantity().intValue()];
String fileUnfValue = null;
for (int i = 0; i < dataFile.getDataTable().getVarQuantity(); i++) {
String varunf = dataFile.getDataTable().getDataVariables().get(i).getUnf();
unfValues[i] = varunf;
}
try {
fileUnfValue = UNFUtil.calculateUNF(unfValues);
} catch (IOException ex) {
logger.warning("Failed to recalculate the UNF for the datafile id="+dataFile.getId());
} catch (UnfException uex) {
logger.warning("UNF Exception: Failed to recalculate the UNF for the dataset version id="+dataFile.getId());
}
if (fileUnfValue != null) {
dataFile.getDataTable().setUnf(fileUnfValue);
}
}
public void recalculateDatasetVersionUNF(DatasetVersion version) {
IngestUtil.recalculateDatasetVersionUNF(version);
}
public void sendFailNotification(Long dataset_id) {
FacesMessage facesMessage = new FacesMessage(BundleUtil.getStringFromBundle("ingest.failed"));
/* commented out push channel message:
PushContext pushContext = PushContextFactory.getDefault().getPushContext();
pushContext.push("/ingest" + dataset_id, facesMessage);
*/
}
public boolean ingestAsTabular(Long datafile_id) {
DataFile dataFile = fileService.find(datafile_id);
boolean ingestSuccessful = false;
boolean forceTypeCheck = false;
IngestRequest ingestRequest = dataFile.getIngestRequest();
if (ingestRequest != null) {
forceTypeCheck = ingestRequest.isForceTypeCheck();
}
// Locate ingest plugin for the file format by looking
// it up with the Ingest Service Provider Registry:
String fileName = dataFile.getFileMetadata().getLabel();
TabularDataFileReader ingestPlugin = getTabDataReaderByMimeType(dataFile.getContentType());
logger.fine("Found ingest plugin " + ingestPlugin.getClass());
if (!forceTypeCheck && ingestPlugin == null) {
// If this is a reingest request, we'll still have a chance
// to find an ingest plugin for this file, once we try
// to identify the file type again.
// Otherwise, we can give up - there is no point in proceeding to
// the next step if no ingest plugin is available.
dataFile.SetIngestProblem();
FileUtil.createIngestFailureReport(dataFile, "No ingest plugin found for file type "+dataFile.getContentType());
dataFile = fileService.save(dataFile);
logger.warning("Ingest failure.");
return false;
}
BufferedInputStream inputStream = null;
File additionalData = null;
File localFile = null;
StorageIO<DataFile> storageIO = null;
try {
storageIO = dataFile.getStorageIO();
storageIO.open();
if (storageIO.isLocalFile()) {
localFile = storageIO.getFileSystemPath().toFile();
inputStream = new BufferedInputStream(storageIO.getInputStream());
} else {
ReadableByteChannel dataFileChannel = storageIO.getReadChannel();
localFile = File.createTempFile("tempIngestSourceFile", ".tmp");
FileChannel tempIngestSourceChannel = new FileOutputStream(localFile).getChannel();
tempIngestSourceChannel.transferFrom(dataFileChannel, 0, storageIO.getSize());
inputStream = new BufferedInputStream(new FileInputStream(localFile));
logger.fine("Saved "+storageIO.getSize()+" bytes in a local temp file.");
}
} catch (IOException ioEx) {
dataFile.SetIngestProblem();
FileUtil.createIngestFailureReport(dataFile, "IO Exception occured while trying to open the file for reading.");
dataFile = fileService.save(dataFile);
logger.warning("Ingest failure (No file produced).");
return false;
}
if (ingestRequest != null) {
if (ingestRequest.getTextEncoding() != null
&& !ingestRequest.getTextEncoding().equals("") ) {
logger.fine("Setting language encoding to "+ingestRequest.getTextEncoding());
ingestPlugin.setDataLanguageEncoding(ingestRequest.getTextEncoding());
}
if (ingestRequest.getLabelsFile() != null) {
additionalData = new File(ingestRequest.getLabelsFile());
}
}
if (forceTypeCheck) {
String newType = FileUtil.retestIngestableFileType(localFile, dataFile.getContentType());
ingestPlugin = getTabDataReaderByMimeType(newType);
logger.fine("Re-tested file type: " + newType + "; Using ingest plugin " + ingestPlugin.getClass());
// check again:
if (ingestPlugin == null) {
// If it's still null - give up!
dataFile.SetIngestProblem();
FileUtil.createIngestFailureReport(dataFile, "No ingest plugin found for file type "+dataFile.getContentType());
dataFile = fileService.save(dataFile);
logger.warning("Ingest failure: failed to detect ingest plugin (file type check forced)");
return false;
}
dataFile.setContentType(newType);
}
TabularDataIngest tabDataIngest = null;
try {
if (additionalData != null) {
tabDataIngest = ingestPlugin.read(inputStream, additionalData);
} else {
tabDataIngest = ingestPlugin.read(inputStream, null);
}
} catch (IOException ingestEx) {
dataFile.SetIngestProblem();
FileUtil.createIngestFailureReport(dataFile, ingestEx.getMessage());
dataFile = fileService.save(dataFile);
logger.warning("Ingest failure (IO Exception): " + ingestEx.getMessage() + ".");
return false;
} catch (Exception unknownEx) {
dataFile.SetIngestProblem();
FileUtil.createIngestFailureReport(dataFile, unknownEx.getMessage());
dataFile = fileService.save(dataFile);
logger.warning("Ingest failure (Exception " + unknownEx.getClass() + "): "+unknownEx.getMessage()+".");
return false;
}
String originalContentType = dataFile.getContentType();
String originalFileName = dataFile.getFileMetadata().getLabel();
long originalFileSize = dataFile.getFilesize();
boolean postIngestTasksSuccessful = false;
boolean databaseSaveSuccessful = false;
if (tabDataIngest != null) {
File tabFile = tabDataIngest.getTabDelimitedFile();
if (tabDataIngest.getDataTable() != null
&& tabFile != null
&& tabFile.exists()) {
logger.info("Tabular data successfully ingested; DataTable with "
+ tabDataIngest.getDataTable().getVarQuantity() + " variables produced.");
logger.info("Tab-delimited file produced: " + tabFile.getAbsolutePath());
dataFile.setFilesize(tabFile.length());
// and change the mime type to "Tabular Data" on the final datafile,
// and replace (or add) the extension ".tab" to the filename:
dataFile.setContentType(FileUtil.MIME_TYPE_INGESTED_FILE);
IngestUtil.modifyExistingFilename(dataFile.getOwner().getLatestVersion(), dataFile.getFileMetadata(), FileUtil.replaceExtension(fileName, "tab"));
if (FileUtil.MIME_TYPE_CSV_ALT.equals(dataFile.getContentType())) {
tabDataIngest.getDataTable().setOriginalFileFormat(FileUtil.MIME_TYPE_CSV);
} else {
tabDataIngest.getDataTable().setOriginalFileFormat(originalContentType);
}
tabDataIngest.getDataTable().setOriginalFileSize(originalFileSize);
dataFile.setDataTable(tabDataIngest.getDataTable());
tabDataIngest.getDataTable().setDataFile(dataFile);
try {
produceSummaryStatistics(dataFile, tabFile);
produceFrequencyStatistics(dataFile, tabFile);
postIngestTasksSuccessful = true;
} catch (IOException postIngestEx) {
dataFile.SetIngestProblem();
FileUtil.createIngestFailureReport(dataFile, "Ingest failed to produce Summary Statistics and/or UNF signatures; " + postIngestEx.getMessage());
restoreIngestedDataFile(dataFile, tabDataIngest, originalFileSize, originalFileName, originalContentType);
dataFile = fileService.save(dataFile);
logger.warning("Ingest failure: post-ingest tasks.");
}
if (!postIngestTasksSuccessful) {
logger.warning("Ingest failure (!postIngestTasksSuccessful).");
return false;
}
dataFile.setIngestDone();
// delete the ingest request, if exists:
if (dataFile.getIngestRequest() != null) {
dataFile.getIngestRequest().setDataFile(null);
dataFile.setIngestRequest(null);
}
try {
/*
In order to test a database save failure, uncomment this:
if (true) {
throw new EJBException("Deliberate database save failure");
}
*/
dataFile = fileService.save(dataFile);
databaseSaveSuccessful = true;
logger.fine("Ingest (" + dataFile.getFileMetadata().getLabel() + ".");
if (additionalData != null) {
// remove the extra tempfile, if there was one:
additionalData.delete();
}
} catch (Exception unknownEx) {
// this means that an error occurred while saving the datafile
// in the database.
logger.warning("Ingest failure: Failed to save tabular metadata (datatable, datavariables, etc.) in the database. Clearing the datafile object.");
dataFile = fileService.find(datafile_id);
if (dataFile != null) {
dataFile.SetIngestProblem();
FileUtil.createIngestFailureReport(dataFile, "Ingest produced tabular data, but failed to save it in the database; " + unknownEx.getMessage() + " No further information is available.");
restoreIngestedDataFile(dataFile, tabDataIngest, originalFileSize, originalFileName, originalContentType);
dataFile = fileService.save(dataFile);
}
}
if (!databaseSaveSuccessful) {
logger.warning("Ingest failure (!databaseSaveSuccessful).");
return false;
}
// Finally, let's swap the original and the tabular files:
try {
/* Start of save as backup */
StorageIO<DataFile> dataAccess = dataFile.getStorageIO();
dataAccess.open();
// and we want to save the original of the ingested file:
try {
dataAccess.backupAsAux(FileUtil.SAVED_ORIGINAL_FILENAME_EXTENSION);
logger.fine("Saved the ingested original as a backup aux file "+FileUtil.SAVED_ORIGINAL_FILENAME_EXTENSION);
} catch (IOException iox) {
logger.warning("Failed to save the ingested original! " + iox.getMessage());
}
// Replace contents of the file with the tab-delimited data produced:
dataAccess.savePath(Paths.get(tabFile.getAbsolutePath()));
// Reset the file size:
dataFile.setFilesize(dataAccess.getSize());
// delete the temp tab-file:
tabFile.delete();
/*end of save as backup */
} catch (Exception e) {
// this probably means that an error occurred while saving the file to the file system
logger.warning("Failed to save the tabular file produced by the ingest (resetting the ingested DataFile back to its original state)");
dataFile = fileService.find(datafile_id);
if (dataFile != null) {
dataFile.SetIngestProblem();
FileUtil.createIngestFailureReport(dataFile, "Failed to save the tabular file produced by the ingest.");
restoreIngestedDataFile(dataFile, tabDataIngest, originalFileSize, originalFileName, originalContentType);
dataFile = fileService.save(dataFile);
}
}
ingestSuccessful = true;
}
} else {
logger.warning("Ingest failed to produce data obect.");
}
return ingestSuccessful;
}
private BufferedInputStream openFile(DataFile dataFile) throws IOException {
BufferedInputStream inputStream;
StorageIO<DataFile> storageIO = dataFile.getStorageIO();
storageIO.open();
if (storageIO.isLocalFile()) {
inputStream = new BufferedInputStream(storageIO.getInputStream());
} else {