Merge pull request #5205 from solgenomics/topic/generic_trial_upload
[sgn.git] / lib / CXGN / BrAPI / FileResponse.pm
blobb50797100f9dfd7f9db65c8c9161861e24d225bc
1 package CXGN::BrAPI::FileResponse;
3 use Moose;
4 use Data::Dumper;
5 use Spreadsheet::WriteExcel;
7 has 'absolute_file_path' => (
8 isa => 'File::Temp',
9 is => 'rw',
10 required => 1,
13 has 'absolute_file_uri' => (
14 isa => 'Str',
15 is => 'rw',
16 required => 1,
19 has 'format' => (
20 isa => 'Str',
21 is => 'rw',
22 required => 1,
25 has 'data' => (
26 isa => 'ArrayRef[ArrayRef]',
27 is => 'rw',
28 required => 1,
31 sub BUILD {
32 my $self = shift;
33 my $format = $self->format;
34 if ($format ne 'tsv' && $format ne 'csv' && $format ne 'xls'){
35 die "format must be tsv, csv, or xls\n";
39 sub get_datafiles {
40 my $self = shift;
41 my $format = $self->format;
42 if ($format eq 'csv'){
43 return $self->csv;
45 if ($format eq 'tsv'){
46 return $self->tsv;
48 if ($format eq 'xls'){
49 return $self->xls;
53 sub csv {
54 my $self = shift;
55 my $data_array = $self->data;
56 my $file_path = $self->absolute_file_path;
58 my $num_col = scalar(@{$data_array->[0]});
59 open(my $fh, ">", $file_path);
60 print STDERR $file_path."\n";
61 foreach my $cols (@$data_array){
62 my $step = 1;
63 for(my $i=0; $i<$num_col; $i++) {
64 if ($cols->[$i]) {
65 print $fh "\"$cols->[$i]\"";
66 } else {
67 print $fh "\"\"";
69 if ($step < $num_col) {
70 print $fh ",";
72 $step++;
74 print $fh "\n";
76 close $fh;
77 my @datafiles = ($self->absolute_file_uri);
78 return @datafiles;
81 sub tsv {
82 my $self = shift;
83 my $data_array = $self->data;
84 my $file_path = $self->absolute_file_path;
86 my $num_col = scalar(@{$data_array->[0]});
87 open(my $fh, ">", $file_path);
88 print STDERR $file_path."\n";
89 foreach my $cols (@$data_array){
90 my $step = 1;
91 for(my $i=0; $i<$num_col; $i++) {
92 if ($cols->[$i]) {
93 print $fh $cols->[$i];
94 } else {
95 print $fh "";
97 if ($step < $num_col) {
98 print $fh "\t";
100 $step++;
102 print $fh "\n";
104 close $fh;
105 my @datafiles = ($self->absolute_file_uri);
106 return @datafiles;
109 sub xls {
110 my $self = shift;
111 my $data_array = $self->data;
112 my $file_path = $self->absolute_file_path;
114 my $ss = Spreadsheet::WriteExcel->new($file_path);
115 my $ws = $ss->add_worksheet();
117 for (my $line=0; $line< scalar(@$data_array); $line++) {
118 $ws->write_row($line, 0, $data_array->[$line]);
120 $ss ->close();
121 my @datafiles = ($self->absolute_file_uri);
122 return @datafiles;